language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 2,025 | 2.296875 | 2 |
[] |
no_license
|
package ec.edu.ups.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ec.edu.ups.dao.DAOFactory;
import ec.edu.ups.entidades.Empresa;
import ec.edu.ups.entidades.Producto;
/**
* Servlet implementation class BuscarProductoAdm
*/
@WebServlet("/BuscarProductoAdm")
public class BuscarProductoAdm extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public BuscarProductoAdm() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String nomPro = request.getParameter("nomPro");
int idEmpresa = Integer.parseInt(request.getParameter("idEmp"));
Empresa empesa = DAOFactory.getFactory().getEmpresaDAO().read(idEmpresa);
String pagina = request.getParameter("pagina");
ArrayList<Producto> pro = DAOFactory.getFactory().getEmpresaDAO().productosEmpresaTodos(nomPro, idEmpresa);
String url = "/private/admin/jsp/mostrarProductosAdmin.jsp";
request.setAttribute("productosAdmin", pro);
request.setAttribute("empresaBusca", empesa);
request.getRequestDispatcher(url).forward(request, response);
System.out.println("Busqueda de producto pasado");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
Shell
|
UTF-8
| 854 | 3.28125 | 3 |
[] |
no_license
|
#!/bin/bash
# CENTOS 서버 세팅 정보 down 후 작업 디렉토리에 복사 / 작업 디렉토리로 이동
curl ${GIT_REPO_PATH}/${SETTING_INFO_DIRECTORY_PATH}/${SETTING_INFO_NAME}.sh \
> ./${SETTING_INFO_NAME}.sh
cp ./${SETTING_INFO_NAME}.sh ${WORK_DIR}/${SETTING_INFO_NAME}.sh
source ${WORK_DIR}/${SETTING_INFO_NAME}.sh
cd ${WORK_DIR}
######################################
SCRIPT_LIST_POSTFIX=_scriptList
for workName in ${workList[@]}; do
mkdir -p ${WORK_DIR}/${workName}
eval scriptList=\( \${${workName}${SCRIPT_LIST_POSTFIX}[@]} \)
for scriptName in ${scriptList[@]}; do
curl ${GIT_REPO_PATH}/${workName}/${scriptName}.sh \
> ${WORK_DIR}/${workName}/${scriptName}.sh
chmod 700 ${WORK_DIR}/${workName}/${scriptName}.sh
${WORK_DIR}/${workName}/${scriptName}.sh
done
done
|
C#
|
UTF-8
| 583 | 2.703125 | 3 |
[] |
no_license
|
private void UpdateDatabase()
{
//Create an adapter to get the schema and point to the correct table
//Can do something like SELECT * from table_name where 0 = 1
SqlDataAdapter adapt = new SqlDataAdapter(yourSelectString, yourConnectionString);
SqlCommandBuilder builder = new SqlCommandBuilder(adapt);
try
{
adapt.Update(ds.Tables[0]);
}
catch (Exception ex)
{
//Handle any exception here
}
}
|
Java
|
UTF-8
| 2,027 | 2.09375 | 2 |
[] |
no_license
|
package com.devilpanda.task.fw;
import com.devilpanda.task.domain.TaskList;
import org.apache.commons.math3.random.RandomDataGenerator;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.ResultActions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.UUID;
public class UpdateTaskListIntegrationTests extends AbstractApiIntegrationTest{
private static final String UPDATED_NAME = "Renamed Task List";
private UUID epicUuid;
private Long taskListId;
@Test
public void updateTaskList_rename() throws Exception {
epicUuid = UUID.fromString(epic.getEpicId());
taskListId = taskList.getTaskListId();
ResultActions resultActions = performRenameTaskList(epicUuid, taskListId, UPDATED_NAME);
resultActions.andExpect(status().isOk());
assertTaskListNameIs(UPDATED_NAME);
}
@Test
public void updateTaskList_rename_taskListNotFound() throws Exception {
epicUuid = UUID.fromString(epic.getEpicId());
taskListId = new RandomDataGenerator().nextLong(-2423523L, -1L);
ResultActions response = performRenameTaskList(epicUuid, taskListId, UPDATED_NAME);
response.andExpect(status().isNotFound());
}
@Test
void updateTaskList_rename_EpicNotFound() throws Exception {
epicUuid = UUID.randomUUID();
taskListId = taskList.getTaskListId();
ResultActions response = performRenameTaskList(epicUuid, taskListId, UPDATED_NAME);
response.andExpect(status().isNotFound());
}
// =-----------------------------------------------------
// Implementation
// =-----------------------------------------------------
private void assertTaskListNameIs(String updatedName) {
TaskList taskList = taskListRepository.findByEpic_UuidAndId(epicUuid, taskListId).get();
assertEquals(UPDATED_NAME, taskList.getName());
}
}
|
Java
|
UTF-8
| 239 | 1.554688 | 2 |
[] |
no_license
|
package com.codegen.relaxng.edit;
public interface NameClassVisitor {
Object visitChoice(ChoiceNameClass nc);
Object visitAnyName(AnyNameNameClass nc);
Object visitNsName(NsNameNameClass nc);
Object visitName(NameNameClass nc);
}
|
Markdown
|
UTF-8
| 933 | 3.078125 | 3 |
[] |
no_license
|
# Laboratory Work No.1
### Goal: Familiarization with Bootstrap
#### Website theme:
The chosen theme for this website is an online *battle* or *war* between artists.
Basically, it's (going to be) a canvas, where 2 users can compete against each other using their art skills.
Details like who wins/loses will be based on ratings from other users, who can watch the available battles and rate them.
----
#### Implemented features:
1. By default, the usage of Bootstrap makes the pages responsive
1. The overall look (pallette) of the website (using the Darkly theme for Bootstrap)
1. The navbar and footer (with clickable buttons, that redirect to other pages, most of them WIPs)
1. Usage of a layout
----
#### How to run the website
- The recommended approach is to open the project in Visual Studio, and run it. (duh)
- A harder approach involves manually setting a server, doing some magic and somehow running it. ( :| )
|
JavaScript
|
UTF-8
| 452 | 2.5625 | 3 |
[] |
no_license
|
const Reference = require('../model/Reference');
exports.getReferences = (req, res) => {
Reference.find()
.then(references => res.json(references))
.catch(err => res.status(400).json("Error: " + err));
}
exports.addReference = (req, res) => {
const newReference = new Reference(req.body);
newReference.save()
.then(() => res.json("Reference Added!"))
.catch(err => res.status(400).json("Error: " + err));
}
|
TypeScript
|
UTF-8
| 222 | 2.53125 | 3 |
[] |
no_license
|
import { ICommonObject } from 'types/common.type';
export interface IUserStore {
email?: string;
id?: number;
paticipatedParty?: ICommonObject;
}
export type TUserStore = IUserStore | Record<string, never> | null;
|
SQL
|
UTF-8
| 20,171 | 2.703125 | 3 |
[] |
no_license
|
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS "django_migrations" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "app" varchar(255) NOT NULL, "name" varchar(255) NOT NULL, "applied" datetime NOT NULL);
INSERT INTO django_migrations VALUES(1,'contenttypes','0001_initial','2019-09-16 09:48:53.998678');
INSERT INTO django_migrations VALUES(2,'auth','0001_initial','2019-09-16 09:48:54.032084');
INSERT INTO django_migrations VALUES(3,'admin','0001_initial','2019-09-16 09:48:54.043308');
INSERT INTO django_migrations VALUES(4,'admin','0002_logentry_remove_auto_add','2019-09-16 09:48:54.063483');
INSERT INTO django_migrations VALUES(5,'admin','0003_logentry_add_action_flag_choices','2019-09-16 09:48:54.081688');
INSERT INTO django_migrations VALUES(6,'contenttypes','0002_remove_content_type_name','2019-09-16 09:48:54.110319');
INSERT INTO django_migrations VALUES(7,'auth','0002_alter_permission_name_max_length','2019-09-16 09:48:54.126630');
INSERT INTO django_migrations VALUES(8,'auth','0003_alter_user_email_max_length','2019-09-16 09:48:54.143580');
INSERT INTO django_migrations VALUES(9,'auth','0004_alter_user_username_opts','2019-09-16 09:48:54.157611');
INSERT INTO django_migrations VALUES(10,'auth','0005_alter_user_last_login_null','2019-09-16 09:48:54.172005');
INSERT INTO django_migrations VALUES(11,'auth','0006_require_contenttypes_0002','2019-09-16 09:48:54.175854');
INSERT INTO django_migrations VALUES(12,'auth','0007_alter_validators_add_error_messages','2019-09-16 09:48:54.192974');
INSERT INTO django_migrations VALUES(13,'auth','0008_alter_user_username_max_length','2019-09-16 09:48:54.210204');
INSERT INTO django_migrations VALUES(14,'auth','0009_alter_user_last_name_max_length','2019-09-16 09:48:54.225175');
INSERT INTO django_migrations VALUES(15,'auth','0010_alter_group_name_max_length','2019-09-16 09:48:54.240943');
INSERT INTO django_migrations VALUES(16,'auth','0011_update_proxy_permissions','2019-09-16 09:48:54.257965');
INSERT INTO django_migrations VALUES(17,'friendship','0001_initial','2019-09-16 09:48:54.278235');
INSERT INTO django_migrations VALUES(18,'group','0001_initial','2019-09-16 09:48:54.308504');
INSERT INTO django_migrations VALUES(19,'news','0001_initial','2019-09-16 09:48:54.333779');
INSERT INTO django_migrations VALUES(20,'sessions','0001_initial','2019-09-16 09:48:54.343391');
INSERT INTO django_migrations VALUES(21,'subscription','0001_initial','2019-09-16 09:48:54.373160');
CREATE TABLE IF NOT EXISTS "auth_group_permissions" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "group_id" integer NOT NULL REFERENCES "auth_group" ("id") DEFERRABLE INITIALLY DEFERRED, "permission_id" integer NOT NULL REFERENCES "auth_permission" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE TABLE IF NOT EXISTS "auth_user_groups" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "user_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED, "group_id" integer NOT NULL REFERENCES "auth_group" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE TABLE IF NOT EXISTS "auth_user_user_permissions" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "user_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED, "permission_id" integer NOT NULL REFERENCES "auth_permission" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE TABLE IF NOT EXISTS "django_admin_log" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "action_time" datetime NOT NULL, "object_id" text NULL, "object_repr" varchar(200) NOT NULL, "change_message" text NOT NULL, "content_type_id" integer NULL REFERENCES "django_content_type" ("id") DEFERRABLE INITIALLY DEFERRED, "user_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED, "action_flag" smallint unsigned NOT NULL CHECK ("action_flag" >= 0));
INSERT INTO django_admin_log VALUES(1,'2019-09-16 09:51:20.994101','2','testuser1','[{"added": {}}]',4,1,1);
INSERT INTO django_admin_log VALUES(2,'2019-09-16 09:51:55.242885','3','testuser2','[{"added": {}}]',4,1,1);
INSERT INTO django_admin_log VALUES(3,'2019-09-16 09:52:18.495688','1','first group','[{"added": {}}]',8,1,1);
INSERT INTO django_admin_log VALUES(4,'2019-09-16 09:52:27.532215','2','second proup','[{"added": {}}]',8,1,1);
INSERT INTO django_admin_log VALUES(5,'2019-09-16 09:52:38.892764','2','second group','[{"changed": {"fields": ["name"]}}]',8,1,2);
INSERT INTO django_admin_log VALUES(6,'2019-09-16 09:53:18.380850','1','Bla 1','[{"added": {}}]',9,1,1);
INSERT INTO django_admin_log VALUES(7,'2019-09-16 09:53:51.154110','2','bal2','[{"added": {}}]',9,1,1);
INSERT INTO django_admin_log VALUES(8,'2019-09-16 09:54:08.221537','1','User testuser1 subscribed to first group','[{"added": {}}]',10,1,1);
INSERT INTO django_admin_log VALUES(9,'2019-09-16 09:54:14.158247','2','User testuser2 subscribed to second group','[{"added": {}}]',10,1,1);
INSERT INTO django_admin_log VALUES(10,'2019-09-16 09:54:30.976794','1','testuser1 follows testuser2','[{"added": {}}]',7,1,1);
INSERT INTO django_admin_log VALUES(11,'2019-09-18 20:14:43.809436','10','User testuser2 subscribed to second group','',10,1,3);
INSERT INTO django_admin_log VALUES(12,'2019-09-18 20:15:01.347091','11','User testuser1 subscribed to super group','[{"added": {}}]',10,1,1);
INSERT INTO django_admin_log VALUES(13,'2019-09-18 20:55:02.670299','6','checking group','[{"added": {}}]',8,1,1);
INSERT INTO django_admin_log VALUES(14,'2019-09-18 20:55:56.212091','31','checking title','[{"added": {}}]',9,1,1);
INSERT INTO django_admin_log VALUES(15,'2019-09-18 20:56:19.534288','12','User testuser1 subscribed to checking group','[{"added": {}}]',10,1,1);
INSERT INTO django_admin_log VALUES(16,'2019-09-18 20:57:56.780105','2','testuser1','[]',4,1,2);
INSERT INTO django_admin_log VALUES(17,'2019-09-19 12:25:00.578052','4','test','[{"added": {}}]',4,1,1);
INSERT INTO django_admin_log VALUES(18,'2019-09-19 12:58:14.964426','14','User test subscribed to checking group','[{"added": {}}]',10,1,1);
INSERT INTO django_admin_log VALUES(19,'2019-09-19 12:58:30.150720','31','checking title','[{"changed": {"fields": ["text"]}}]',9,1,2);
INSERT INTO django_admin_log VALUES(20,'2019-09-19 12:59:54.121201','14','User test subscribed to checking group','[]',10,1,2);
INSERT INTO django_admin_log VALUES(21,'2019-09-19 13:00:06.963235','6','checking group','[]',8,1,2);
INSERT INTO django_admin_log VALUES(22,'2019-09-19 13:00:08.461142','31','checking title','[]',9,1,2);
CREATE TABLE IF NOT EXISTS "django_content_type" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "app_label" varchar(100) NOT NULL, "model" varchar(100) NOT NULL);
INSERT INTO django_content_type VALUES(1,'admin','logentry');
INSERT INTO django_content_type VALUES(2,'auth','permission');
INSERT INTO django_content_type VALUES(3,'auth','group');
INSERT INTO django_content_type VALUES(4,'auth','user');
INSERT INTO django_content_type VALUES(5,'contenttypes','contenttype');
INSERT INTO django_content_type VALUES(6,'sessions','session');
INSERT INTO django_content_type VALUES(7,'friendship','friendship');
INSERT INTO django_content_type VALUES(8,'group','group');
INSERT INTO django_content_type VALUES(9,'news','news');
INSERT INTO django_content_type VALUES(10,'subscription','subscription');
CREATE TABLE IF NOT EXISTS "auth_permission" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "content_type_id" integer NOT NULL REFERENCES "django_content_type" ("id") DEFERRABLE INITIALLY DEFERRED, "codename" varchar(100) NOT NULL, "name" varchar(255) NOT NULL);
INSERT INTO auth_permission VALUES(1,1,'add_logentry','Can add log entry');
INSERT INTO auth_permission VALUES(2,1,'change_logentry','Can change log entry');
INSERT INTO auth_permission VALUES(3,1,'delete_logentry','Can delete log entry');
INSERT INTO auth_permission VALUES(4,1,'view_logentry','Can view log entry');
INSERT INTO auth_permission VALUES(5,2,'add_permission','Can add permission');
INSERT INTO auth_permission VALUES(6,2,'change_permission','Can change permission');
INSERT INTO auth_permission VALUES(7,2,'delete_permission','Can delete permission');
INSERT INTO auth_permission VALUES(8,2,'view_permission','Can view permission');
INSERT INTO auth_permission VALUES(9,3,'add_group','Can add group');
INSERT INTO auth_permission VALUES(10,3,'change_group','Can change group');
INSERT INTO auth_permission VALUES(11,3,'delete_group','Can delete group');
INSERT INTO auth_permission VALUES(12,3,'view_group','Can view group');
INSERT INTO auth_permission VALUES(13,4,'add_user','Can add user');
INSERT INTO auth_permission VALUES(14,4,'change_user','Can change user');
INSERT INTO auth_permission VALUES(15,4,'delete_user','Can delete user');
INSERT INTO auth_permission VALUES(16,4,'view_user','Can view user');
INSERT INTO auth_permission VALUES(17,5,'add_contenttype','Can add content type');
INSERT INTO auth_permission VALUES(18,5,'change_contenttype','Can change content type');
INSERT INTO auth_permission VALUES(19,5,'delete_contenttype','Can delete content type');
INSERT INTO auth_permission VALUES(20,5,'view_contenttype','Can view content type');
INSERT INTO auth_permission VALUES(21,6,'add_session','Can add session');
INSERT INTO auth_permission VALUES(22,6,'change_session','Can change session');
INSERT INTO auth_permission VALUES(23,6,'delete_session','Can delete session');
INSERT INTO auth_permission VALUES(24,6,'view_session','Can view session');
INSERT INTO auth_permission VALUES(25,7,'add_friendship','Can add friendship');
INSERT INTO auth_permission VALUES(26,7,'change_friendship','Can change friendship');
INSERT INTO auth_permission VALUES(27,7,'delete_friendship','Can delete friendship');
INSERT INTO auth_permission VALUES(28,7,'view_friendship','Can view friendship');
INSERT INTO auth_permission VALUES(29,8,'add_group','Can add group');
INSERT INTO auth_permission VALUES(30,8,'change_group','Can change group');
INSERT INTO auth_permission VALUES(31,8,'delete_group','Can delete group');
INSERT INTO auth_permission VALUES(32,8,'view_group','Can view group');
INSERT INTO auth_permission VALUES(33,9,'add_news','Can add news');
INSERT INTO auth_permission VALUES(34,9,'change_news','Can change news');
INSERT INTO auth_permission VALUES(35,9,'delete_news','Can delete news');
INSERT INTO auth_permission VALUES(36,9,'view_news','Can view news');
INSERT INTO auth_permission VALUES(37,10,'add_subscription','Can add subscription');
INSERT INTO auth_permission VALUES(38,10,'change_subscription','Can change subscription');
INSERT INTO auth_permission VALUES(39,10,'delete_subscription','Can delete subscription');
INSERT INTO auth_permission VALUES(40,10,'view_subscription','Can view subscription');
CREATE TABLE IF NOT EXISTS "auth_user" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "password" varchar(128) NOT NULL, "last_login" datetime NULL, "is_superuser" bool NOT NULL, "username" varchar(150) NOT NULL UNIQUE, "first_name" varchar(30) NOT NULL, "email" varchar(254) NOT NULL, "is_staff" bool NOT NULL, "is_active" bool NOT NULL, "date_joined" datetime NOT NULL, "last_name" varchar(150) NOT NULL);
INSERT INTO auth_user VALUES(1,'pbkdf2_sha256$150000$F5gwLMW62U2L$ayHcD4s/Npsx3lS4QSs1SsgzarBQm2GUP2YqChLw1Ps=','2019-09-19 12:57:30.784088',1,'admin','','admin@example.com',1,1,'2019-09-16 09:50:37.111427','');
INSERT INTO auth_user VALUES(2,'pbkdf2_sha256$150000$8SNf7dTsOXed$v1aAWIuy0oJ1oZZ0pNvsAtyW/WN78VL2uhVenH8nIbQ=','2019-09-19 08:03:37.257881',0,'testuser1','','',0,1,'2019-09-16 09:51:20','');
INSERT INTO auth_user VALUES(3,'pbkdf2_sha256$150000$kr0LBty0bS3h$iTWbns+D9rhVbtcpguipQQ1ChkOGj9oxhZZf4fWK6FU=','2019-09-18 20:04:25.497297',0,'testuser2','','',0,1,'2019-09-16 09:51:55.078029','');
INSERT INTO auth_user VALUES(4,'pbkdf2_sha256$150000$ySimH6qlaLuL$EOUN5/uRIHZnx/m5lwVtEY6nycOBXUw+M2iMkrvdhVw=','2019-09-19 13:01:32.710633',0,'test','','',0,1,'2019-09-19 12:25:00.398481','');
CREATE TABLE IF NOT EXISTS "auth_group" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(150) NOT NULL UNIQUE);
CREATE TABLE IF NOT EXISTS "friendship_friendship" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "first_accepted" bool NOT NULL, "second_accepted" bool NOT NULL, "first_user_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED, "second_user_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED);
INSERT INTO friendship_friendship VALUES(1,0,0,2,3);
INSERT INTO friendship_friendship VALUES(2,1,1,2,1);
INSERT INTO friendship_friendship VALUES(3,1,1,2,3);
INSERT INTO friendship_friendship VALUES(4,1,0,2,3);
INSERT INTO friendship_friendship VALUES(6,1,0,2,2);
INSERT INTO friendship_friendship VALUES(7,1,0,2,2);
INSERT INTO friendship_friendship VALUES(10,1,0,2,2);
INSERT INTO friendship_friendship VALUES(11,1,0,2,1);
INSERT INTO friendship_friendship VALUES(12,1,0,3,2);
CREATE TABLE IF NOT EXISTS "group_group" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(100) NOT NULL UNIQUE, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED);
INSERT INTO group_group VALUES(2,'second group',3);
INSERT INTO group_group VALUES(3,'bla',2);
INSERT INTO group_group VALUES(4,'super group',2);
INSERT INTO group_group VALUES(5,'another group',3);
INSERT INTO group_group VALUES(6,'checking group',3);
CREATE TABLE IF NOT EXISTS "news_news" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(100) NOT NULL, "text" text NOT NULL, "published_at" datetime NOT NULL, "group_id" integer NOT NULL REFERENCES "group_group" ("id") DEFERRABLE INITIALLY DEFERRED);
INSERT INTO news_news VALUES(2,'bal2',replace(replace('BlaBlaBlaBlaBlaBlaBla\r\nBlaBlaBlaBlaBlaBlaBla\r\nBlaBlaBlaBlaBlaBlaBla\r\nBlaBlaBlaBlaBlaBlaBla\r\nBlaBlaBlaBlaBlaBlaBla','\r',char(13)),'\n',char(10)),'2019-09-16 09:53:51.153408',2);
INSERT INTO news_news VALUES(3,'nh','k','2019-09-18 13:55:21.440331',5);
INSERT INTO news_news VALUES(4,'nh','k','2019-09-18 13:56:13.508712',5);
INSERT INTO news_news VALUES(5,'sd','sd','2019-09-18 14:00:35.951100',5);
INSERT INTO news_news VALUES(6,'and','a','2019-09-18 14:00:57.393717',5);
INSERT INTO news_news VALUES(7,'SDF','SDF','2019-09-18 14:03:16.596499',5);
INSERT INTO news_news VALUES(8,'SDF','SDF','2019-09-18 14:06:52.368102',5);
INSERT INTO news_news VALUES(9,'and','a','2019-09-18 14:07:10.929869',5);
INSERT INTO news_news VALUES(10,'and','a','2019-09-18 14:08:48.995930',5);
INSERT INTO news_news VALUES(11,'and','a','2019-09-18 14:09:49.707513',5);
INSERT INTO news_news VALUES(12,'and','a','2019-09-18 14:10:17.987252',5);
INSERT INTO news_news VALUES(13,'and','a','2019-09-18 14:31:58.594744',5);
INSERT INTO news_news VALUES(14,'and','a','2019-09-18 14:32:40.834732',5);
INSERT INTO news_news VALUES(15,'and','a','2019-09-18 14:33:11.643721',5);
INSERT INTO news_news VALUES(16,'and','a','2019-09-18 14:39:31.231646',5);
INSERT INTO news_news VALUES(17,'and','a','2019-09-18 14:41:02.012202',5);
INSERT INTO news_news VALUES(18,'and','a','2019-09-18 14:43:29.124985',5);
INSERT INTO news_news VALUES(19,'and','a','2019-09-18 14:43:46.058181',5);
INSERT INTO news_news VALUES(20,'and','a','2019-09-18 14:48:25.978501',5);
INSERT INTO news_news VALUES(21,'and','a','2019-09-18 14:48:43.088877',5);
INSERT INTO news_news VALUES(22,'and','a','2019-09-18 14:49:54.906913',5);
INSERT INTO news_news VALUES(23,'and','a','2019-09-18 14:50:55.039327',5);
INSERT INTO news_news VALUES(24,'and','a','2019-09-18 14:52:47.120610',5);
INSERT INTO news_news VALUES(25,'and','a','2019-09-18 14:53:50.867349',5);
INSERT INTO news_news VALUES(26,'and','a','2019-09-18 15:02:46.226095',3);
INSERT INTO news_news VALUES(27,'and','a','2019-09-18 15:03:11.809136',4);
INSERT INTO news_news VALUES(28,'ad','and','2019-09-18 15:04:59.826778',3);
INSERT INTO news_news VALUES(29,'and','sad','2019-09-18 15:08:14.116368',4);
INSERT INTO news_news VALUES(30,'and','and','2019-09-18 19:27:00.857717',5);
INSERT INTO news_news VALUES(31,'checking title','checking title','2019-09-18 20:55:56.211146',6);
INSERT INTO news_news VALUES(32,'asd','as','2019-09-19 13:07:51.279014',6);
INSERT INTO news_news VALUES(33,'asd','as','2019-09-19 13:07:53.976719',6);
INSERT INTO news_news VALUES(34,'asd','as','2019-09-19 13:07:59.541831',6);
CREATE TABLE IF NOT EXISTS "django_session" ("session_key" varchar(40) NOT NULL PRIMARY KEY, "session_data" text NOT NULL, "expire_date" datetime NOT NULL);
INSERT INTO django_session VALUES('nn4g20zayeu0dvyf2sau28ca1opkqvwi','ZTk0MjEzOWJhNDk2M2Q5YzQwZWZiNjk4YzI2N2I1NDAwMmVlZjFhOTp7Il9hdXRoX3VzZXJfaWQiOiIzIiwiX2F1dGhfdXNlcl9iYWNrZW5kIjoiZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmQiLCJfYXV0aF91c2VyX2hhc2giOiI4ZTUxNTlkNmJhYmQ5MWZlY2E1MTAyMDI3ZTg0N2M2MGM3MmZlYmFiIn0=','2019-10-02 13:02:01.440520');
INSERT INTO django_session VALUES('aao301dt0i9u592tzul7jjb7b6estzj7','Yjc2Y2MzYmVlOWQ5MTMxZjgzZDE3NDdhNzNmZWEyOTA1Nzg1ZmY3OTp7Il9hdXRoX3VzZXJfaWQiOiI0IiwiX2F1dGhfdXNlcl9iYWNrZW5kIjoiZGphbmdvLmNvbnRyaWIuYXV0aC5iYWNrZW5kcy5Nb2RlbEJhY2tlbmQiLCJfYXV0aF91c2VyX2hhc2giOiJlMzY5NWJkZDM0YzIzNjBmNDI0YjYwMDRjYzUzYThjYWY5YWMzNzhlIn0=','2019-10-03 13:01:32.719338');
CREATE TABLE IF NOT EXISTS "subscription_subscription" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "group_id" integer NOT NULL REFERENCES "group_group" ("id") DEFERRABLE INITIALLY DEFERRED, "user_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED);
INSERT INTO subscription_subscription VALUES(4,4,2);
INSERT INTO subscription_subscription VALUES(5,4,2);
INSERT INTO subscription_subscription VALUES(7,3,2);
INSERT INTO subscription_subscription VALUES(8,5,2);
INSERT INTO subscription_subscription VALUES(11,4,2);
INSERT INTO subscription_subscription VALUES(12,6,2);
INSERT INTO subscription_subscription VALUES(13,6,2);
INSERT INTO subscription_subscription VALUES(14,6,4);
DELETE FROM sqlite_sequence;
INSERT INTO sqlite_sequence VALUES('django_migrations',21);
INSERT INTO sqlite_sequence VALUES('django_admin_log',22);
INSERT INTO sqlite_sequence VALUES('django_content_type',10);
INSERT INTO sqlite_sequence VALUES('auth_permission',40);
INSERT INTO sqlite_sequence VALUES('auth_user',4);
INSERT INTO sqlite_sequence VALUES('auth_group',0);
INSERT INTO sqlite_sequence VALUES('group_group',6);
INSERT INTO sqlite_sequence VALUES('news_news',34);
INSERT INTO sqlite_sequence VALUES('subscription_subscription',15);
INSERT INTO sqlite_sequence VALUES('friendship_friendship',12);
CREATE UNIQUE INDEX "auth_group_permissions_group_id_permission_id_0cd325b0_uniq" ON "auth_group_permissions" ("group_id", "permission_id");
CREATE INDEX "auth_group_permissions_group_id_b120cbf9" ON "auth_group_permissions" ("group_id");
CREATE INDEX "auth_group_permissions_permission_id_84c5c92e" ON "auth_group_permissions" ("permission_id");
CREATE UNIQUE INDEX "auth_user_groups_user_id_group_id_94350c0c_uniq" ON "auth_user_groups" ("user_id", "group_id");
CREATE INDEX "auth_user_groups_user_id_6a12ed8b" ON "auth_user_groups" ("user_id");
CREATE INDEX "auth_user_groups_group_id_97559544" ON "auth_user_groups" ("group_id");
CREATE UNIQUE INDEX "auth_user_user_permissions_user_id_permission_id_14a6b632_uniq" ON "auth_user_user_permissions" ("user_id", "permission_id");
CREATE INDEX "auth_user_user_permissions_user_id_a95ead1b" ON "auth_user_user_permissions" ("user_id");
CREATE INDEX "auth_user_user_permissions_permission_id_1fbb5f2c" ON "auth_user_user_permissions" ("permission_id");
CREATE INDEX "django_admin_log_content_type_id_c4bce8eb" ON "django_admin_log" ("content_type_id");
CREATE INDEX "django_admin_log_user_id_c564eba6" ON "django_admin_log" ("user_id");
CREATE UNIQUE INDEX "django_content_type_app_label_model_76bd3d3b_uniq" ON "django_content_type" ("app_label", "model");
CREATE UNIQUE INDEX "auth_permission_content_type_id_codename_01ab375a_uniq" ON "auth_permission" ("content_type_id", "codename");
CREATE INDEX "auth_permission_content_type_id_2f476e4b" ON "auth_permission" ("content_type_id");
CREATE INDEX "friendship_friendship_first_user_id_f7d9f7b3" ON "friendship_friendship" ("first_user_id");
CREATE INDEX "friendship_friendship_second_user_id_aff6a17e" ON "friendship_friendship" ("second_user_id");
CREATE INDEX "group_group_author_id_49bc001a" ON "group_group" ("author_id");
CREATE INDEX "news_news_group_id_8aaa8f48" ON "news_news" ("group_id");
CREATE INDEX "django_session_expire_date_a5c62663" ON "django_session" ("expire_date");
CREATE INDEX "subscription_subscription_group_id_ee602ed0" ON "subscription_subscription" ("group_id");
CREATE INDEX "subscription_subscription_user_id_ff2293c7" ON "subscription_subscription" ("user_id");
COMMIT;
|
Java
|
UTF-8
| 2,822 | 3.015625 | 3 |
[] |
no_license
|
package interfaces;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class JOptionPaneDemo {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JOptionPaneDemo window = new JOptionPaneDemo();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public JOptionPaneDemo() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel miPanel = new JPanel();
frame.getContentPane().add(miPanel,BorderLayout.CENTER);
JButton boton1 = new JButton("Dialogo 1");
boton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Ha ocurrido un error", "Error", JOptionPane.ERROR_MESSAGE);
}
});
miPanel.add(boton1);
JButton boton2 = new JButton("Dialogo 2");
boton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] opciones = {"Opcion 1","Opcion 2","Opcion 3","Opcion 4"};
JOptionPane.showOptionDialog(frame, "Selecciona una opcion", "Selecciona una opcion", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, opciones, opciones[0]);
}
});
miPanel.add(boton2);
JButton boton3 = new JButton("Dialogo 3");
boton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] opciones = {"Jaen","Cordova","Sevilla","Granada"};
String s = (String)JOptionPane.showInputDialog(frame, "Ciudad preferida", "Seleccione una ciudad", JOptionPane.PLAIN_MESSAGE, null,opciones,opciones[0]);
if(s!=null)JOptionPane.showMessageDialog(frame, s);
}
});
miPanel.add(boton3);
JButton boton4 = new JButton("Dialogo 4");
boton4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = JOptionPane.showInputDialog(null, "Ciudad preferida");
if(s!=null)JOptionPane.showMessageDialog(frame, s);
}
});
miPanel.add(boton4);
JButton boton5 = new JButton("Dialogo Personalizado");
boton5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JDialogDemo miDialog = new JDialogDemo(frame);
}
});
miPanel.add(boton5);
}
}
|
SQL
|
UTF-8
| 638 | 2.953125 | 3 |
[] |
no_license
|
CREATE TABLE [mybuys].[tblBuyAuctionType] (
[BuyAuctionTypeID] TINYINT NOT NULL,
[RowLoadedDateTime] DATETIME2 (7) NOT NULL,
[RowUpdatedDateTime] DATETIME2 (7) NULL,
[LastChangedByEmpID] VARCHAR (128) NULL,
[AuctionTypeKey] VARCHAR (50) NOT NULL,
[AuctionTypeDescription] VARCHAR (200) NULL,
[IsActive] TINYINT NOT NULL,
CONSTRAINT [PK_tblBuyAuctionType] PRIMARY KEY CLUSTERED ([BuyAuctionTypeID] ASC) WITH (FILLFACTOR = 90),
CONSTRAINT [AK_tblBuyAuctionType_AuctionTypeKey] UNIQUE NONCLUSTERED ([AuctionTypeKey] ASC) WITH (FILLFACTOR = 90)
);
|
Java
|
UTF-8
| 1,008 | 2.34375 | 2 |
[] |
no_license
|
package com.tecweb.spring.jpa.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "COUNTRIES")
public class Country {
@Id
@Column(name = "country_id", unique = true)
private String countryId;
@Column(name = "country_name")
private String countryName;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "region_id")
private Region region;
public Country() {
super();
}
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
}
|
Python
|
UTF-8
| 832 | 2.546875 | 3 |
[] |
no_license
|
from .trainers.sick_trainer import SICKTrainer
class TrainerFactory(object):
"""
Get the corresponding Trainer class for a particular dataset.
"""
trainer_map = {
'sick': SICKTrainer,
'eng_fre':SICKTrainer
}
@staticmethod
def get_trainer(dataset_name, model, embedding, train_loader, trainer_config, train_evaluator, test_evaluator, dev_evaluator=None, nce=False):
if nce:
trainer_map = TrainerFactory.trainer_map_nce
else:
trainer_map = TrainerFactory.trainer_map
if dataset_name not in trainer_map:
raise ValueError('{} is not implemented.'.format(dataset_name))
return trainer_map[dataset_name](
model, embedding, train_loader, trainer_config, train_evaluator, test_evaluator, dev_evaluator
)
|
Python
|
UTF-8
| 3,676 | 2.796875 | 3 |
[] |
no_license
|
# Utilities
import re
def read_file(filename):
fh = open(filename, mode="r")
contents = fh.read()
fh.close()
return contents
class TAPData:
def __init__(self):
self.flag = 0
self.status = ""
self.offset = ""
self.text = ""
self.comment = ""
self.test = [("", "", "", -1), ]
self.subtest = [("", "", "", -1), ]
def flag_increment(self):
self.flag += 1
def show(self):
count = 0
for x in range(0, len(self.test)):
print(f"test {self.test.__getitem__(x)[0]} : "
f"{self.test.__getitem__(x)[1]} "
f"{self.test.__getitem__(x)[2]}\n"
f" subtest : {self.test.__getitem__(x)[3]}")
if self.test.__getitem__(x)[-1] > 0:
for y in range(0, self.test.__getitem__(x)[-1]):
print((self.subtest.__getitem__(count)[-1] * "\t") +
f"subtest {self.subtest.__getitem__(count)[0]} : "
f"{self.subtest.__getitem__(count)[1]} "
f"{self.subtest.__getitem__(count)[2]}"),
count += 1
def rec_STATUS(self, t):
test_status = re.fullmatch(r"ok|not ok", t.value)
self.status = test_status.group(0)
def rec_OFFSET(self, t):
test_pos = re.fullmatch(r" ([1-9]\d*)[ \n]", t.value)
self.offset = test_pos.group(0).strip("\n")
def rec_TEXT(self, t, empty, string):
# Capture Text
if empty:
self.text = string
else:
test_text = re.fullmatch(r"(-( [\w\d]*)*\n)", t.value)
self.text = test_text.group(0).strip("\n")
# Save Incidence
# If test
if self.flag == 0:
# If first
if self.test.__getitem__(-1)[-1] == -1: # total_subtest == -1 $default
self.test = [(self.status, self.offset, self.text, 0), ] # Remove default values
# If another
elif self.test.__getitem__(-1)[-1] != -1 and self.offset != "1": # total_subtest == -1
self.test = self.test + [(self.status, self.offset, self.text, 0), ] # Add test
# If subtest
elif self.flag > 0:
# If first
if self.offset == " 1\n" or self.offset == " 1 ":
# Change last test amount of subtest
self.test = self.test[:-1] + [(self.test.__getitem__(-1)[0],
self.test.__getitem__(-1)[1],
self.test.__getitem__(-1)[2],
self.test.__getitem__(-1)[-1] + 1), ]
# If first ever
if self.subtest.__getitem__(0)[0] == "":
# Remove default values
self.subtest = [(self.status, self.offset, self.text, self.flag), ]
# If first in sequence
else:
# Add to list
self.subtest = self.subtest + [(self.status, self.offset, self.text, self.flag), ]
# If another
elif self.offset != "1":
# Increment amount of subtest
self.test = self.test[:-1] + [(self.test.__getitem__(-1)[0],
self.test.__getitem__(-1)[1],
self.test.__getitem__(-1)[2],
self.test.__getitem__(-1)[3] + 1), ]
self.subtest = self.subtest + [(self.status, self.offset, self.text, self.flag), ]
self.flag = 0
|
Shell
|
UTF-8
| 2,304 | 2.765625 | 3 |
[] |
no_license
|
# Shell dili ile kodlanmış basit bir sayı tahmin oyunu. YUInformatics üyeleri için kodlanmıştır.
# Geliştiren: Emrecan ÖKSÜM
# İletişim: ben@emreoksum.com.tr, emreoksum@gmail.com, 05344839345
# Instagram: @eoksum :)
# Giriş, tanıtım vs.
echo Sayı tahmin oyununa hoşgeldiniz. Lütfen alt menuden oyun parametrelerini belirleyiniz.
echo "[Oyuncu 1] Lütfen bir sayi belireyiniz: "; read sayi
echo "[Oyuncu 1] Tahmin eden oyuncunun kac tahmin hakki olacak? :"; read kactahmin
echo "Oyun 6 saniye icinde baslayacak lutfen ekran temizlendigi zaman klavyeyi Oyuncu 2'ye verin..."
sleep 6 # 6 saniye boyunca uyu
clear # Konsol çıktısını temizle
echo "[Oyuncu 2] Sayı tahmin oyununa hoşgeldiniz oyuncu 2. $kactahmin kadar tahmin hakkınız var."
# Oyuncu1'i önden başlat çünkü sayıyı belirleyen o, Oyuncu 2nin tahmin edememesi durumunda kesin kazanacak olan her ihtimalde Oyuncu1.
oyuncu1=1
oyuncu2=0
# Bolum ile oyuncu 1in girdigi sayının tam olarak bolundugu sayıları ipucu olarak bul.
function kaca_tam_bolunur {
sayi=$1
iter=1 # iterator. 1den sayi degiskenine kadar olan tum sayıları alttaki döngüde bölmeyi denettirir.
while [ $iter -lt $sayi ]
do
if (( $sayi % $iter == 0 )); then
echo "Tahmin etmeye calıştığınız sayı $iter ile tam olarak bölünebiliyor."
fi
iter=$(( $iter+1 ))
done
}
# Oyuncu 2nin tahmin yapması için for döngüsü
toplamdeneme=0
while [ $toplamdeneme -le $kactahmin ]
do
echo "[Oyuncu 2] Oyuncu 1'in belirlediği sayıyı tahmin etmeye çalışın. Kalan tahmin hakkınız: $(( $kactahmin-$toplamdeneme )) Tahmininizi giriniz: "; read tahmin
if [ "$tahmin" == "$sayi" ]; then
oyuncu2=1
echo "Oyuncu 2, Oyuncu 1'in belirlediği sayıyı tutturdu ve oyunu kazandı."
break
else
echo "Oyuncu 2 sayıyı doğru bilemedi. Oyuncu 2 için ipucu: "; kaca_tam_bolunur "$sayi"
fi
toplamdeneme=$(( $toplamdeneme+1 ))
done
# Döngü sonunda oyun illaki bitmiş olacak çünkü iki ihtimal var, ya Oyuncu1in belirlediği sayıyı Oyuncu2 tahmin edecek
# ya da Oyuncu2 için önceden belirlenen tahmin hakkı bitmiş olacak.
echo "Oyun bitti!"
# Skorları karşılaştır ve oyunu kimin kazandığını belirleyip kazananı ilan et.
if [ $oyuncu2 == 0 ]; then
echo "Oyunu oyuncu 1 kazandı!"
else
echo "Oyunu oyuncu 2 kazandı!"
fi
|
C++
|
UTF-8
| 2,519 | 2.8125 | 3 |
[] |
no_license
|
#ifndef ST_H_INCLUDED_
#define ST_H_INCLUDED_
#include <iostream>
#include <string>
#include <list>
#include <utility>
using namespace std;
enum error_types{
ET_WRONG_RETURN,
ET_WRONG_PARAMETER_TYPE,
ET_CANNOT_ASSIGN,
ET_INCORRECT_NUMBER_OF_ARGUMENTS,
ET_VOID_VARIABLE,
ET_ARRAY_ARGUMENT_INTEGER,
ET_ARRAY_DECLARATION_INTEGER,
ET_ARRAY_UNDER_USAGE,
ET_ARRAY_OVER_USAGE,
ET_UNDECLARED,
ET_VARIABLE_UNDECLARED,
ET_NOT_A_FUNCTION,
ET_REDECLARTION,
ET_VARIABLE_REDECLARATION,
ET_CANNOT_CAST,
ET_AMBIGUOUS_FUNCALL,
ET_NO_MAIN,
ET_MULTIPLE_MAIN,
ET_NON_INT_MAIN,
ET_INVALID_FORMAT_STRING,
ET_UNMATCHING_FORMAT_STRING,
ET_TOO_FEW_FORMAT_STRING,
ET_TOO_MANY_FORMAT_STRING
};
/*
//TODO
array parameters
polymorphism
*/
enum variable_type{
VT_VARIABLE,
VT_PARAMETER,
VT_FUNCTION,
VT_NULL
};
enum data_type{
DT_INT,
DT_FLOAT,
DT_VOID,
DT_ARRAY,
DT_STRING,
DT_ERROR
};
class ErrorElement{
public:
error_types error;
string identifier;
int line_no;
ErrorElement(error_types e,string id, int ln);
void print_error();
static string error_string(error_types e);
};
class SymbolTable;
class mDataType{
public:
data_type dt;
int size;
mDataType* subArray;
int index_size;
mDataType();
mDataType(data_type data_t);
mDataType(mDataType* subArr, int index_s);
static string data_type_to_string(data_type data);
pair<string,string> get_string();
static data_type are_compatible(data_type d1, data_type d2,int mode_funcall = 0);
void print();
};
class SymbolEntry{
public:
string identifier;
variable_type vt;
mDataType dt;
list<data_type> params;
int offset;
SymbolTable* lst; //Local Symbol Table Pointer
int position_in_table;// for functions only
SymbolEntry();
SymbolEntry(string id, variable_type var_t, mDataType data_t, int ofs, SymbolTable* st);
SymbolEntry(string id, variable_type var_t, mDataType data_t, int ofs, list<data_type> ldt, SymbolTable* st);
SymbolEntry(string id, variable_type var_t, mDataType data_t, int ofs, list<data_type> ldt, SymbolTable* st,int position);
void print(string tabs="");
string print_params();
void print_vt();
};
class SymbolTable{
public:
list<SymbolEntry> table;
int current_offset;
void addEntry(string id,variable_type var_t, mDataType data_t, int ofs, SymbolTable* st);
void addEntry(SymbolEntry se);
void clear_data();
void add_offset(int value);
void print(string tabs="");
bool contains_declaration(string var_name);
SymbolEntry get_declaration(string var_name);
};
#endif // ST_H_INCLUDED_
|
Shell
|
UTF-8
| 531 | 3.109375 | 3 |
[] |
no_license
|
#!/bin/bash
DIR="$( cd "$( dirname "$0" )" && pwd )"
RESULT_DIR=$DIR/result/raw/fio
if [ $# -ne 3 ]
then
echo "Usage:$0 /dev/xvde <DEPTH> xvde"
exit 1
fi
FIO_IOBOW_FILE=$1
DEPTH=$2
DEV=$3
echo "===>Testing model_1024k_100read_0random_${DEV}_$DEPTH"
fio -filename=$FIO_IOBOW_FILE -direct=1 -rw=read -bs=1024k -size=50G -iodepth=$DEPTH -ioengine=libaio -numjobs=1 -group_reporting -name=model_1024k_100read_${DEV}_$DEPTH --output=$RESULT_DIR/model_1024k_100read_${DEV}_$DEPTH.log -ramp_time=20 -time_based -runtime=300
|
Python
|
UTF-8
| 1,034 | 3.453125 | 3 |
[] |
no_license
|
stock = {"tomate": [ 1000, 2.30], #[0] = Cantidad, [1] = Precios
"lechuga": [500, 0.45],
"batata": [2001, 1.20],
"poroto": [100, 1.50]}
venta = input("Ingrese el nombre del producto a comprar: ")
total = 0
if venta in stock:
compra = int(input("Ingrese la cantidad de compras: "))
x = [[venta, compra]]
print("Ventas:\n")
for operacion in x:
producto, cantidad = operacion
if(stock[producto][0] < cantidad or cantidad < 0):
print("No se puede comprar, exceso de mercancias")
else:
precio = stock[producto][1]
costo = precio*cantidad
print("%s: %3d x %6.2f = %6.2f" % (producto, cantidad, precio, costo))
stock[producto][0] -= cantidad
total += costo
else:
print("El producto no existe")
print("Costo total: %21.2f \n" % total)
print("Stock:\n")
for clave, datos in stock.items():
print("Descripcion: ", clave)
print("Cantidad: ", datos[0])
print("Precio: %6.2f\n" % datos[1])
|
C
|
UTF-8
| 312 | 2.875 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<conio.h>
void main()
{
int num,c,j,i=1;
clrscr();
scanf("%d",&num);
while(i<=num)
{
c=0;
j=2;
while(j<=i/2)
{
if(i%j==0)
{
c++;
break;
}
j++;
}
if(c==0 && i!=1)
{
printf("%d ",i," ");
}
i++;
}
getch();
}
|
C#
|
UTF-8
| 2,627 | 2.5625 | 3 |
[] |
no_license
|
using GarageManagement.GarageManagement_DTO;
using GarageManagement_DAL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GarageManagement.GarageManagement_DAL
{
class PhieuSuaChuaDAL
{
private static PhieuSuaChuaDAL instance;
internal static PhieuSuaChuaDAL Instance
{
get
{
if (instance == null) instance = new PhieuSuaChuaDAL();
return instance;
}
private set
{
instance = value;
}
}
public List<PhieuSuaChuaDTO> GetListPhieuSuaChua()
{
List<PhieuSuaChuaDTO> phieusuachuaList = new List<PhieuSuaChuaDTO>();
DataTable data = DataProvider.Instance.ExecuteQuery("select * from dbo.phieusuachua");
foreach (DataRow item in data.Rows)
{
PhieuSuaChuaDTO phieusuachua = new PhieuSuaChuaDTO(item);
phieusuachuaList.Add(phieusuachua);
}
return phieusuachuaList;
}
public bool InsertPhieuSuaChua( int carnumber, int iditem, string detail, DateTime? createddate, float dongia, float tiencong, float totalprice)
{
string query = string.Format("insert dbo.phieusuachua ( carnumber , iditem , detail , createddate , dongia , tiencong , totalprice ) ");
query += string.Format("values ( {0} , {1} , N'{2}' , '{3}' , {4}, {5}, {6}) ", carnumber, iditem, detail, createddate, dongia, tiencong, totalprice);
int result = DataProvider.Instance.ExecuteNonQuery(query);
return result > 0;
}
public bool UpdatePhieuSuaChua(int idpsc, int carnumber, int iditem, string detail, DateTime? createddate, float dongia, float tiencong, float totalprice)
{
string query = string.Format("update dbo.phieusuachua set");
query += string.Format(" carnumber = {0} , iditem = {1} , detail = N'{2}' , createddate = '{3}' , dongia = {4} , tiencong = {5}, totalprice ={6} where idpsc = {7} ", carnumber, iditem, detail, createddate, dongia, tiencong, totalprice, idpsc);
int result = DataProvider.Instance.ExecuteNonQuery(query);
return result > 0;
}
public bool DeletePhieuSuaChua(int idpsc)
{
string query = string.Format("delete dbo.phieusuachua where idpsc ={0}" ,idpsc );
int result = DataProvider.Instance.ExecuteNonQuery(query);
return result > 0;
}
}
}
|
Java
|
UTF-8
| 6,140 | 1.882813 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-rsa-md4",
"HPND-sell-variant",
"metamail",
"LicenseRef-scancode-rsa-1990",
"LicenseRef-scancode-zeusbench",
"Beerware",
"Spencer-94",
"MIT",
"LicenseRef-scancode-pcre",
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"NTP",
"RSA-MD"
] |
permissive
|
/* Copyright (c) 2012 imacat
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* OpenOffice
*
* Created on 2012-08-16, rewritten from CalcMosaic
*
* Copyright (c) 2012 imacat
*/
package tw.idv.imacat.calcmosaic;
import java.util.ResourceBundle;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XDesktop;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
/**
* An OpenOffice instance.
*
* @author <a href="mailto:imacat@mail.imacat.idv.tw">imacat</a>
* @version 2.0.0
*/
public class OpenOffice {
/** The localization resources. */
private ResourceBundle l10n = null;
/** The desktop service. */
private XDesktop desktop = null;
/** The bootstrap context. */
private XComponentContext bootstrapContext = null;
/** The registry service manager. */
private XMultiComponentFactory serviceManager = null;
/**
* Creates a new instance of Office.
*
* @throws com.sun.star.comp.helper.BootstrapException if fails to
* create the initial component context
*/
public OpenOffice()
throws com.sun.star.comp.helper.BootstrapException {
// Obtains the localization resources
this.l10n = ResourceBundle.getBundle(
this.getClass().getPackage().getName() + ".res.L10n");
try {
this.connect();
} catch (com.sun.star.comp.helper.BootstrapException e) {
throw e;
}
}
/**
* Connects to the OpenOffice program.
*
* @throws com.sun.star.comp.helper.BootstrapException if fails to
* create the initial component context
*/
private void connect()
throws com.sun.star.comp.helper.BootstrapException {
XMultiComponentFactory localServiceManager = null;
Object unoUrlResolver = null;
XUnoUrlResolver xUnoUrlResolver = null;
Object service = null;
if (this.isConnected()) {
return;
}
// Obtains the local context
try {
this.bootstrapContext = Bootstrap.bootstrap();
} catch (java.lang.Exception e) {
throw new com.sun.star.comp.helper.BootstrapException(e);
}
if (this.bootstrapContext == null) {
throw new com.sun.star.comp.helper.BootstrapException(
this._("err_ooo_no_lcc"));
}
// Obtains the local service manager
this.serviceManager = this.bootstrapContext.getServiceManager();
// Obtain the desktop service
try {
service = this.serviceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", this.bootstrapContext);
} catch (com.sun.star.uno.Exception e) {
throw new java.lang.UnsupportedOperationException(e);
}
this.desktop = (XDesktop) UnoRuntime.queryInterface(
XDesktop.class, service);
// Obtains the service manager
this.serviceManager = this.bootstrapContext.getServiceManager();
return;
}
/**
* Returns whether the connection is on and alive.
*
* @return true if the connection is alive, false otherwise
*/
private boolean isConnected() {
if (this.serviceManager == null) {
return false;
}
try {
UnoRuntime.queryInterface(
XPropertySet.class, this.serviceManager);
} catch (com.sun.star.lang.DisposedException e) {
this.serviceManager = null;
return false;
}
return true;
}
/**
* Starts a new spreadsheet document.
*
* @return the new spreadsheet document
*/
public SpreadsheetDocument startNewSpreadsheetDocument() {
XComponentLoader xComponentLoader = (XComponentLoader)
UnoRuntime.queryInterface(
XComponentLoader.class, this.desktop);
PropertyValue props[] = new PropertyValue[0];
final String url = "private:factory/scalc";
XComponent xComponent = null;
// Load a new document
try {
xComponent = xComponentLoader.loadComponentFromURL(url,
"_default", 0, props);
} catch (com.sun.star.io.IOException e) {
throw new java.lang.RuntimeException(
String.format(_("err_open"), url), e);
} catch (com.sun.star.lang.IllegalArgumentException e) {
throw new java.lang.RuntimeException(
String.format(_("err_open"), url), e);
}
return new SpreadsheetDocument(xComponent);
}
/**
* Gets a string for the given key from this resource bundle
* or one of its parents. If the key is missing, returns
* the key itself.
*
* @param key the key for the desired string
* @return the string for the given key
*/
private String _(String key) {
try {
return new String(
this.l10n.getString(key).getBytes("ISO-8859-1"),
"UTF-8");
} catch (java.io.UnsupportedEncodingException e) {
return this.l10n.getString(key);
} catch (java.util.MissingResourceException e) {
return key;
}
}
}
|
Java
|
UTF-8
| 278 | 2.4375 | 2 |
[] |
no_license
|
package Controller;
public class AudioException extends Throwable {
private static final long serialVersionUID = 1L;
private String message;
public AudioException(String message) {
this.message = message;
}
public String toString() {
return message;
}
}
|
Java
|
UTF-8
| 614 | 2.515625 | 3 |
[] |
no_license
|
package com.spo.workplace.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
@JsonAutoDetect
public class RoomAssignment {
private int senior;
private int junior;
protected RoomAssignment() {}
public RoomAssignment(int senior, int junior) {
this.senior = senior;
this.junior = junior;
}
public int getSenior() {
return senior;
}
public void setSenior(int senior) {
this.senior = senior;
}
public int getJunior() {
return junior;
}
public void setJunior(int junior) {
this.junior = junior;
}
}
|
Python
|
UTF-8
| 362 | 3.40625 | 3 |
[] |
no_license
|
# Переводить з десяткової в двійкову і навпаки
def to_dec(a):
A = list(a)
A.reverse()
b = 0
for i in range(len(A)):
b += 2 ** i * A[i]
return b
def to_bin_arr(a):
A = int(a)
b = []
while A > 0:
b.append(A % 2)
A = A // 2
b.append(0)
b.reverse()
return b
|
JavaScript
|
UTF-8
| 914 | 2.546875 | 3 |
[] |
no_license
|
const {Schema, model} = require('mongoose'); //require para invocar al módulo
//definicion del esquema para la coleccion de usuario
const UsuarioSchema = Schema({
nombre:{
type: String,
required: true //required: sintaxis propia de mongo
},
email:{
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
},
img:{
type: String
},
role:{
type:String,
required : true,
default: 'USER_ROLE'
},
google:{
type:Boolean,
default: false
},
});
UsuarioSchema.method('toJSON', function(){
const {__v,_id, password,...object} = this.toObject();
object.uid = _id;
return object;
})
//se exporta el modelo
//por defecto mongoose creara un mongodb un documento en plural: usuarios
module.exports= model('Usuario',UsuarioSchema);
|
Swift
|
UTF-8
| 1,268 | 2.921875 | 3 |
[] |
no_license
|
//
// GameScene.swift
// Flappy Bird
//
// Created by Rob Percival on 05/07/2016.
// Copyright © 2016 Appfish. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var bird = SKSpriteNode()
override func didMove(to view: SKView) {
let birdTexture = SKTexture(imageNamed: "flappy1.png")
let birdTexture2 = SKTexture(imageNamed: "flappy2.png")
//animate contains an array of textures that it will use to animate a node
let animation = SKAction.animate(with: [birdTexture, birdTexture2], timePerFrame: 0.1)
let makeBirdFlap = SKAction.repeatForever(animation)
bird = SKSpriteNode(texture: birdTexture)
bird.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
bird.run(makeBirdFlap)//this applies the animation to the bird
self.addChild(bird)//this is how we add and object or node to the view controller
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
|
C#
|
UTF-8
| 936 | 2.53125 | 3 |
[] |
no_license
|
using DPSP_UI_LG.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace DPSP_UI_LG.Services
{
public interface IProjectService
{
/// <summary>
/// GetProject will send username data to API through json and url and deserialize returned data to ProjectViewModel.
/// </summary>
/// <returns>Returns list of ProjectViewModels.</returns>
Task<ListProjectViewModel> GetProject();
/// <summary>
/// Share will share project by sending request to API with json data model.
/// </summary>
/// <param name="model">User's email, whose should be shared with and projects ids of projects, which should be shared.</param>
/// <returns>Returns string for View about succesful or not succesful creation from API.</returns>
Task<string> Share(EmailViewModel model);
}
}
|
Markdown
|
UTF-8
| 5,878 | 2.890625 | 3 |
[] |
no_license
|
# KSP-Wildfire
Warning: Work in progress!
This mod adds pseudo fire hazards to the game. Originally created for another mod, but turned standalone.
Overheating, bumping into things, crashing and other reckless activities may cause fire to break out in the subjected part. A fire will cause the part to gradually overheat, giving only a few seconds until it disintegrates. There is also a risk that a fire may spread to adjacent parts, leading to an (unfortunate) chain reaction.
No more "Oh, I didn't really need that part anyway..." You really need the Primary Buffer panel to stay attached for the whole re-entry sequence! It may cause a leak, or a short-circuit, or general spontaneous combustion.
This add-on attempts to introduce less randomness in how failure (fires) occurs, thus a fire will never occur at total random, but can only be caused by something. This will hopefully encourage players to take proactive steps (WIP) in order to reduce the chance of critical failure, as well as encouraging safe flying (who am I kidding?).
As commander of your sheep, you may want to herd your crew to the pre-installed escape pods when you find the ship on fire and burning from enemy attacks. A LES is also recommended for launch. If you play with a life-support add-on, you may also want to pack potatoes and your stillsuit, in case your craft goes down on Duna...
Incidentally, the add-on also comes included with a fire extinguisher system.
Package contents:
- 1x Automatic fire extinguisher part (Monopropellant tank clone under Utilities). When activated it will automatically try to douse fires at the cost of liquid CO2 and electric charge.
- 1x Automatic fire alarm (Pre-installed in every cockpit).
- 1x Right-click risk info menu. Indicates the highest possible fire risk on the selected part.
- Various fire hazards.
- 1x Water sprinkler with built in sparkler (2 in 1! For performance!). It's a stage-able part in the Utility section (linear RCS clone) when activated, it will start up an give you 5 beeps, and a long beep at the end indicating it's ready. When ready, it will give you a few seconds of halved risk factor for every part! Note: It will only work when landed, and you have to launch before it stops to reap the benefits (NEW in 0.1.3).
More details:
When a part is on fire it will gradually overheat based on its contents. Connected fuel and fuel in the part will drain to feed the fire. Electric charge is also drain by a small amount because of short-circuiting. All parts may catch fire, as well as parts that doesn't "realistically" catch fire are also subjected. However the chance is significantly reduced compared to other parts, and are considered "overheating" as all parts can carry Electric Charge (sparks and smoke only).
[Igniting events] A part may catch fire when:
- ...the temperature of a part reaches 70+%.
- ...a connected part is on fire.
- ...a part collides with another object and rotates its original position.
- ...a connected part explodes.
- ...a part takes exhaust damage from an engine.
- ...a part flexes too much in relation to its connected part. I.e. Wobbliness, bending (NEW in 0.1.3).
Whether or not a part will catch fire at either event mentioned above is dependent on type of part and its contents. At its current state it takes into consider [Risk factors]:
- Vacuum and atmosphere (on Kerbin for now).
- Resources (fuel etc.). Liquid fuel, monopropellant, electric charge and solid fuel.
- Part type: Engines and crew compartment parts.
- Connected fuel containers.
- Explosions, crash velocity etc.
- The mod also tries to calculate where fuel lines between parts are connected. Fuel lines have an increased risk factor when fuel is on board.
- G-forces.
- Dynamic pressure.
Whenever an igniting events occur on a part, a random number is generated between 0 and 100. If the number is bellow the risk factor of the subjected part a fire will occur.
Consequently, the mod also considers situations when a fire is doused:
- When submerging a part in water may douse a fire.
- When in vacuum there is a high chance a fire may douse as long as the part does not contain any oxidising materials.
- When not carrying flammable materials or oxidisers will increase the chance of fire going out.
- When the automatic fire extinguisher is active.
- There is a tiny chance a fire may douse itself.
Parts with decouplers are immune to connected explosions. Parts with heat-shield does not catch fire. Fuel lines and struts are excluded.
Whenever a part is subjected to excess bending from its parent part you may hear a "creaking"-sound. If the part bends above the set bending limit (WIP) a blue highlight will indicate that the part is under stress, and you will hear a louder creaking-sound. At this point the part may catch fire according to the risk factor for the specific part.
Required add-ons:
- ModuleManager (http://forum.kerbalspaceprogram.com/index.php?/topic/50533-105-module-manager-2617-january-10th-with-even-more-sha-and-less-bug/) (Adds mod functionality to all parts in game, can be edited in the config-file if you want to exclude parts.)
- Community Resource Pack (https://kerbalstuff.com/mod/974/Community%20Resource%20Pack) (Uses Liquid CO2.)
Considered features (may or may not come):
- Gameplay balancing (More realism?).
- Integration with other hazardous mods (need to ask for permissions first).
- Pseudo weather hazards (when I can figure out how to make a toolbar interface).
- Atmospheric and deep space hazards.
- Crew skill based fire risk reduction (need to find a gameplay-friendly way to calculate the reduction).
- Ground Control skill based fire risk reduction (encourage hiring random staff).
- Douse fires by opening airlocks (For use with Life Support Mods).
- Bubbles.
- Dynamic extinguishing.
- Dynamic variables
Copyright: All Rights Reserved
|
C++
|
UTF-8
| 622 | 2.71875 | 3 |
[] |
no_license
|
#include "n_tuples_of_m_set.h"
namespace
{
void test()
{
constexpr auto binary_7 = n_tuples_of_m_set<4, 2>::create_tuple(7);
static_assert(binary_7[0] == 0, "");
static_assert(binary_7[1] == 1, "");
static_assert(binary_7[2] == 1, "");
static_assert(binary_7[3] == 1, "");
constexpr auto tuple_types_8 = n_tuples_of_m_set<4, 2>::get_tuple_types<8, std::tuple<int, char>>();
static_assert(std::is_same<decltype(tuple_types_8), const std::tuple<char,int,int,int>>::value, "get_tuple_types 8");
/*constexpr auto n_tuples = n_tuples_of_m_set<4, 2>::create_n_tuples();
constexpr auto binary_10 = n_tuples[10];*/
}
}
|
Markdown
|
UTF-8
| 3,779 | 3.734375 | 4 |
[] |
no_license
|
# Exercise SMS Reminders
You can use this Python script to send exercise reminders and motivation every day. The script uses the Twilio API to send scheduled SMS reminders and motivational quotes. The script can also be used to send links to predefined YouTube searches to help with finding an exercise video for certain activities.
# Example SMS Message
> Here is your exercise plan for the day to keep you motivated!!
>
> Today is Tuesday, 06-30-2020. You will be doing the following activity: HITT
>
> You have trained 4 days so far.
>
> Here is a link to some YouTube videos for HIIT: https://www.youtube.com/results?search_query=hiit+workout+15+minutes. Enjoy your workout!
# Script Logic
## Prerequisites
This program requires a [Twilio license](https://www.twilio.com/pricing). You can obtain a trial version of Twilio. Note that your trial credit will be charged each time that you use the service.
## Converting Days to JSON
First, create the [.csv file](days.csv) with the date, day of the week, activity, and days trained. Then, use the [.csv to JSON](convert_training_days.py) script to convert the file to a [JSON format](days.json). The script calls the .csv file and restructures the data so that it exists as a set of date keys with the value as a dictionary of the different elements from the .csv file.
## Quotes JSON
You can download a [free inspirational quotes](https://forum.freecodecamp.org/t/free-api-inspirational-quotes-json-with-code-examples/311373) JSON file for the inspirational messages that are sent with each SMS. This information is stored in the quotes.json file.
## Constructing a Message
The [main.py](main.py) file uses both JSON files and the Twilio API to construct the SMS message. First, you need to set your Twilio API key that you obtained when creating your account.
> account_sid = ''
> auth_token = ''
> client = Client(account_sid, auth_token)
Enter your Twilio account ID and authorization token. This creates a client for you to have access to the Twilio API.
Then, the script calls the days.json file and uses the `if curday == keyval['Date']:` command to pull the activity that is associated with today's date. The `exerciseBlock` text is then constructed.
> `("Hello! Here is your exercise plan for the day to keep you motivated! \nToday is " + dayWeek +", "+ curday + ". You will be doing the following activity--" + activity + ". You have trained " + daysTrained + " days so far! \n\n" )`
Each of the elements in the `exerciseBlock` is derived from the days.json file.
The `quoteBlock` is then constructed. All elements are derived from the quotes.json file.
>`("Inspirational quote of the day\n" + quote+ " --said by " + author )`
Finally, the `linkBlock` is constructed, which checks to see if the `activity` element is either **barre**, **yoga**, or **HIIT**. A predefined YouTube search such as "HIIT workout 15 minutes" is returned.
All elements are then combined to construct the message or `body` element. The `client.messages.create` function uses the Twilio API to send the message. Replace the `+` in the `from` element with your Twilio-assigned number. Replace the `+` in the `to` element with the recipient's number.
>
> message = client.messages.create(
> from_='+',
> body = body,
> to ='+'
> )
## Scheduling a Job
You can schedule the job to run every day at a particular time. For example, you can set the job to send an SMS at 8:00 AM:
> `schedule.every().day.at("08:00").do(job)`
An infinite loop is set that can always run the service with the following command:
> while True:
> schedule.run_pending()
> time.sleep(1)
|
Java
|
ISO-8859-1
| 5,264 | 3.078125 | 3 |
[] |
no_license
|
package br.com.example1.app;
import java.util.ArrayList;
import java.util.Scanner;
import br.com.example1.model.Aluguel;
import br.com.example1.model.Carro;
import br.com.example1.model.Cliente;
import br.com.example1.model.Locadora;
import br.com.example1.model.Marca;
public class App {
public static void main(String[] args) {
Locadora locadora = new Locadora("Doug Veculos");
System.out.println("----------- MENU ------------");
System.out.println("Selecione o n da opo desejada: ");
System.out.println("1 - Cadastrar Cliente");
System.out.println("2 - Cadastrar Carro");
System.out.println("3 - Realizar Locacao");
System.out.println("4 - Listar Clientes");
System.out.println("5 - Listar Carros");
System.out.println("6 - Listar Alugueis");
System.out.println("0 - Sair\n");
System.out.println("Opcao Escolhida: ");
Scanner scanner = new Scanner(System.in);
String texto = scanner.nextLine();
do {
switch (Integer.parseInt(texto)) {
case 1:
Scanner cliente = new Scanner(System.in);
System.out.println("Digite o nome do Cliente: ");
String nome = cliente.nextLine();
System.out.println("Digite o CPF do Cliente: ");
String cpf = cliente.nextLine();
System.out.println("Cliente Adicionado com Sucesso!\n");
System.out.println("##########################\n");
Cliente novoCliente = new Cliente(nome, cpf);
locadora.addCliente(novoCliente);
break;
case 2:
Scanner carro = new Scanner(System.in);
System.out.println("Digite o Modelo do Veculo: ");
String modelo = carro.nextLine();
System.out.println("Digite a Marca do Veculo: ");
String marca = carro.nextLine();
System.out.println("Digite a placa do Veculo: ");
String placa = carro.nextLine();
try {
Carro novoCarro = new Carro();
novoCarro.setModelo(modelo);
novoCarro.setMarca(new Marca(marca));
novoCarro.setPlaca(placa);
novoCarro.setAlugado(false);
locadora.addCarro(novoCarro);
System.out.println("Carro Adicionado com Sucesso!\n");
System.out.println("##########################\n");
} catch (Exception e) {
System.out.println(e.getMessage()+"\n");
}
break;
case 3:
Scanner aluguel = new Scanner(System.in);
System.out.println("Digite o CPF do Cliente: ");
String cpfAluguel = aluguel.nextLine();
Cliente clienteAluguel = locadora.getCliente(cpfAluguel);
while (clienteAluguel == null) {
System.out.println("Cliente no encontrado! \nConfira os dados ");
System.out.println("Digite o CPF do Cliente: ");
cpfAluguel = aluguel.nextLine();
System.out.println(cpfAluguel);
clienteAluguel = locadora.getCliente(cpfAluguel);
}
System.out.println("Digite a placa do Veculo: ");
String placaAluguel = aluguel.nextLine();
Carro carroAluguel = locadora.getCarro(placaAluguel);
while (carroAluguel == null) {
System.out.println("Carro no encontrado! \nConfira os dados novamente");
System.out.println("Digite a placa do Veculo: ");
placaAluguel = aluguel.nextLine();
carroAluguel = locadora.getCarro(placaAluguel);
}
Aluguel novoAluguel = new Aluguel(clienteAluguel, carroAluguel, 10, 150.00, false);
locadora.addAluguel(novoAluguel);
System.out.println("Aluguel realizado com Sucesso!\n");
System.out.println("##########################\n");
break;
case 4:
ArrayList<Cliente> clientes = locadora.getClientes();
for (int i = 0; i < clientes.size(); i++) {
Cliente aux = clientes.get(i);
System.out.println("[Nome: " + aux.getNome() + " CPF: " + aux.getCpf() + "]");
}
break;
case 5:
ArrayList<Carro> carros = locadora.getCarros();
for (int i = 0; i < carros.size(); i++) {
Carro aux = carros.get(i);
System.out.println("[Modelo: " + aux.getModelo() + " Marca: " + aux.getMarca().getNome()
+ " Placa: " + aux.getPlaca() + "]");
}
break;
case 6:
ArrayList<Aluguel> alugueis = locadora.getAlugueis();
for (int i = 0; i < alugueis.size(); i++) {
Aluguel aux = alugueis.get(i);
System.out.println("[Cliente: " + aux.getCliente().getNome() + " CPF: " + aux.getCliente().getCpf()
+ " Carro: " + aux.getCarro().getModelo() + " Placa: " + aux.getCarro().getPlaca() + "]");
}
break;
case 0:
System.out.println("##########################");
System.out.println("MUITO OBRIGADO, VOLTE SEMPRE!");
System.out.println("##########################\n");
System.exit(0);
break;
}
System.out.println("----------- MENU ------------");
System.out.println("Selecione o n da opo desejada: ");
System.out.println("1 - Cadastrar Cliente");
System.out.println("2 - Cadastrar Carro");
System.out.println("3 - Realizar Locacao");
System.out.println("4 - Listar Clientes");
System.out.println("5 - Listar Carros");
System.out.println("6 - Listar Alugueis");
System.out.println("0 - Sair\n");
System.out.println("Opcao Escolhida: ");
texto = scanner.nextLine();
} while (texto != null);
scanner.close();
}
}
|
TypeScript
|
UTF-8
| 917 | 2.765625 | 3 |
[
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] |
permissive
|
/**
* check to see if we can consolidate cases
*
* @param {object} providers the providers object
* @param {object} providers.applicationContext the application context
* @param {object} providers.path the next object in the path
* @param {object} providers.props the cerebral props object
* @returns {object} the path to take next
*/
export const canConsolidateAction = ({
applicationContext,
path,
props,
}: ActionProps) => {
const { caseDetail, caseToConsolidate, confirmSelection } = props;
if (!confirmSelection) {
return path.error({
error: 'Select a case',
});
}
const results = applicationContext
.getUseCases()
.canConsolidateInteractor(applicationContext, {
caseToConsolidate,
currentCase: caseDetail,
});
if (results.canConsolidate) {
return path.success();
} else {
return path.error({
error: results.reason,
});
}
};
|
C#
|
UTF-8
| 6,292 | 3.421875 | 3 |
[] |
no_license
|
using System;
namespace Pictor
{
public struct Vector2D
{
public double x, y;
public Vector2D (double newX, double newY)
{
x = newX;
y = newY;
}
public Vector2D (float newX, float newY) : this((double)newX, (double)newY)
{
}
public void Set (double inX, double inY)
{
x = inX;
y = inY;
}
public static Vector2D operator + (Vector2D A, Vector2D B)
{
Vector2D temp = new Vector2D ();
temp.x = A.x + B.x;
temp.y = A.y + B.y;
return temp;
}
public static Vector2D operator - (Vector2D A, Vector2D B)
{
Vector2D temp = new Vector2D ();
temp.x = A.x - B.x;
temp.y = A.y - B.y;
return temp;
}
public static Vector2D operator * (Vector2D A, Vector2D B)
{
Vector2D temp = new Vector2D ();
temp.x = A.x * B.x;
temp.y = A.y * B.y;
return temp;
}
public static Vector2D operator * (Vector2D A, double B)
{
Vector2D temp = new Vector2D ();
temp.x = A.x * B;
temp.y = A.y * B;
return temp;
}
public static Vector2D operator * (double B, Vector2D A)
{
Vector2D temp = new Vector2D ();
temp.x = A.x * B;
temp.y = A.y * B;
return temp;
}
public static Vector2D operator * (Vector2D A, float B)
{
Vector2D temp = new Vector2D ();
temp.x = A.x * (double)B;
temp.y = A.y * (double)B;
return temp;
}
public static Vector2D operator * (float B, Vector2D A)
{
Vector2D temp = new Vector2D ();
temp.x = A.x * (double)B;
temp.y = A.y * (double)B;
return temp;
}
public static Vector2D operator / (Vector2D A, Vector2D B)
{
Vector2D temp = new Vector2D ();
temp.x = A.x / B.x;
temp.y = A.y / B.y;
return temp;
}
public static Vector2D operator / (Vector2D A, double B)
{
Vector2D temp = new Vector2D ();
temp.x = A.x / B;
temp.y = A.y / B;
return temp;
}
public static Vector2D operator / (double B, Vector2D A)
{
Vector2D temp = new Vector2D ();
temp.x = A.x / B;
temp.y = A.y / B;
return temp;
}
// are they the same within the error value?
public bool Equals (Vector2D OtherVector, double ErrorValue)
{
if ((x < OtherVector.x + ErrorValue && x > OtherVector.x - ErrorValue) && (y < OtherVector.y + ErrorValue && y > OtherVector.y - ErrorValue)) {
return true;
}
return false;
}
public override bool Equals (System.Object obj)
{
// If parameter is null return false.
if (obj == null) {
return false;
}
// If parameter cannot be cast to Point return false.
Vector2D p = (Vector2D)obj;
if ((System.Object)p == null) {
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public override int GetHashCode ()
{
return x.GetHashCode () ^ y.GetHashCode ();
}
public static bool operator == (Vector2D a, Vector2D b)
{
return a.Equals (b);
}
public static bool operator != (Vector2D a, Vector2D b)
{
return !a.Equals (b);
}
public Vector2D GetPerpendicular ()
{
Vector2D temp = new Vector2D (y, -x);
return temp;
}
public Vector2D GetPerpendicularNormal ()
{
Vector2D Perpendicular = GetPerpendicular ();
Perpendicular.Normalize ();
return Perpendicular;
}
public double GetLength ()
{
return (double)System.Math.Sqrt ((x * x) + (y * y));
}
public double GetLengthSquared ()
{
return Dot (this);
}
public static double GetDistanceBetween (Vector2D A, Vector2D B)
{
return (double)System.Math.Sqrt (GetDistanceBetweenSquared (A, B));
}
public static double GetDistanceBetweenSquared (Vector2D A, Vector2D B)
{
return ((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y));
}
public double GetSquaredDistanceTo (Vector2D Other)
{
return ((x - Other.x) * (x - Other.x) + (y - Other.y) * (y - Other.y));
}
public static double Range0To2PI (double Value)
{
if (Value < 0) {
Value += 2 * (double)System.Math.PI;
}
if (Value >= 2 * (double)System.Math.PI) {
Value -= 2 * (double)System.Math.PI;
}
if (Value < 0 || Value > 2 * System.Math.PI)
throw new Exception ("Value >= 0 && Value <= 2 * PI");
return Value;
}
public static double GetDeltaAngle (double StartAngle, double EndAngle)
{
if (StartAngle != Range0To2PI (StartAngle))
throw new Exception ("StartAngle == Range0To2PI(StartAngle)");
if (EndAngle != Range0To2PI (EndAngle))
throw new Exception ("EndAngle == Range0To2PI(EndAngle)");
double DeltaAngle = EndAngle - StartAngle;
if (DeltaAngle > System.Math.PI) {
DeltaAngle -= 2 * (double)System.Math.PI;
}
if (DeltaAngle < -System.Math.PI) {
DeltaAngle += 2 * (double)System.Math.PI;
}
return DeltaAngle;
}
public double GetAngle0To2PI ()
{
return (double)Range0To2PI ((double)System.Math.Atan2 ((double)y, (double)x));
}
public double GetDeltaAngle (Vector2D A)
{
return (double)GetDeltaAngle (GetAngle0To2PI (), A.GetAngle0To2PI ());
}
public void Normalize ()
{
double Length;
Length = GetLength ();
if (Length == 0)
throw new Exception ("Length != 0.f");
if (Length != 0.0f) {
double InversLength = 1.0f / Length;
x *= InversLength;
y *= InversLength;
}
}
public void Normalize (double Length)
{
if (Length == 0)
throw new Exception ("Length == 0.f");
if (Length != 0.0f) {
double InversLength = 1.0f / Length;
x *= InversLength;
y *= InversLength;
}
}
public double NormalizeAndReturnLength ()
{
double Length;
Length = GetLength ();
if (Length != 0.0f) {
double InversLength = 1.0f / Length;
x *= InversLength;
y *= InversLength;
}
return Length;
}
public void Rotate (double Radians)
{
Vector2D Temp;
double Cos, Sin;
Cos = (double)System.Math.Cos (Radians);
Sin = (double)System.Math.Sin (Radians);
Temp.x = x * Cos + y * Sin;
Temp.y = y * Cos + x * Sin;
x = Temp.x;
y = Temp.y;
}
public void Zero ()
{
x = (double)0;
y = (double)0;
}
public void Negate ()
{
x = -x;
y = -y;
}
public double Dot (Vector2D B)
{
return (x * B.x + y * B.y);
}
public double Cross (Vector2D B)
{
return x * B.y - y * B.x;
}
}
}
|
Java
|
UTF-8
| 426 | 1.921875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.github.piggyguojy.util.model;
import com.github.piggyguojy.util.Msg;
import java.util.function.Function;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
@AllArgsConstructor
@Getter
@EqualsAndHashCode(exclude = {"processor"})
@ToString(of = {"name"})
public class Processor {
private String name;
private Function<Params, Msg<?>> processor;
}
|
Ruby
|
UTF-8
| 177 | 2.96875 | 3 |
[] |
no_license
|
module Players
class Human < Player
def move(board)
puts "Where would you like to move next? Please use a number 1-9"
input = gets.strip
end
end
end
|
C++
|
UTF-8
| 622 | 3.15625 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int main() {
int window_size, no_of_frames;
cout<<"\n Enter the size of window: ";
cin>>window_size;
cout<<"\n Enter the no. of frames: ";
cin>>no_of_frames;
int frames[no_of_frames];
cout<<"\n Enter the frames: ";
for(int i=1; i<=no_of_frames; i++) {
cin>>frames[i];
}
for(int i=1; i<=no_of_frames; i++) {
if(i%window_size == 0) {
cout<<"\n"<<frames[i];
cout<<"\n Acknowledgement of above frames is recieved";
} else {
cout<<"\n"<<frames[i];
}
}
if(no_of_frames%window_size != 0) {
cout<<"\n Acknowledgement of above frames is recieved";
}
}
|
Java
|
UTF-8
| 966 | 2.109375 | 2 |
[] |
no_license
|
package com.example.rabbitmq5001.service;
/**
* @author leejalen
* @Description
* Created on 2020/11/11
*/
public interface IRabbitProducerService {
/**
* 发送消息
* @param message 消息
* */
public void sendMessage(String message);
/**
* 直连交换机生产者
* @param message 生产者发送的消息
* */
void producerDirect1(String message);
/**
* 直连交换机生产者
* @param message 生产者发送的消息
* */
void producerDirect2(String message);
/**
* 扇形交换机生产者
* @param message 生产者发送的消息
* */
void producerFanout(String message);
/**
* 主题交换机生产者
* @param message 生产者发送的消息
* */
void producerTopic(String message);
/**
* 头部交换机生产者
* @param message 生产者发送的消息
* */
void producerHeaders(String message);
}
|
PHP
|
UTF-8
| 1,252 | 2.59375 | 3 |
[] |
no_license
|
<?php
namespace App\Http\Controllers\PublicAdmin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Event;
use Spatie\GoogleCalendar\Event as GoogleCalendarObject;
use Carbon\Carbon;
class GoogleCalendarController extends Controller
{
public function create($id)
{
$eventId = Event::findOrFail($id);
if ($eventId) {
$event = new GoogleCalendarObject;
$event->name = $eventId->name;
$event->startDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $eventId->date.' '.$eventId->hour);
$event->endDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $eventId->date.' '.$eventId->hour)->addHour();
$event->colorId = 4;
$event->description = '<a href="'.route('public.events.show', ['id'=>$eventId->id,'slug'=>$eventId->slug]).'" title="'.$eventId->name.'" target="_blank">Event Link | '.$eventId->name.'</a>';
$event->save();
return redirect()->back()->with('success', 'This Event was been added correctly to your Google Calendar!');
} else {
return redirect()->back()->with('warning', 'An error occured while trying to add the event to your calendar! Try Again.');
}
}
}
|
Python
|
UTF-8
| 3,469 | 2.859375 | 3 |
[] |
no_license
|
import pickle
import nltk
from nltk import classify, word_tokenize
import re, string
from nltk.tag import pos_tag
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import stopwords
from nltk.classify import ClassifierI
from statistics import mode
import sys
stop_words = stopwords.words('english')
class VoteClassifier(ClassifierI):
def __init__(self, *classifiers):
self._classifiers = classifiers
def classify(self, featureset):
votes = []
for c in self._classifiers:
v = c.classify(featureset)
votes.append(v)
return mode(votes)
def confidence(self, featureset):
votes = []
for c in self._classifiers:
v = c.classify(featureset)
votes.append(v)
choice_votes = votes.count(mode(votes))
conf = choice_votes / len(votes) * 100
return conf
class predict_text:
def __init__(self):
file_classifier = open("D:\\VSprojects\\VisualStudioProj\\Thesis\\VirusTracker\\PythonScripts\\final_classifier.pickle", "rb")
self.classifier = pickle.load(file_classifier)
file_classifier.close()
def clean_text(self, input, stopwords=()):
tokens = word_tokenize(input)
offset = 0
for i, t in enumerate(tokens): # concatenate the hyperlinks because they where split by word_tokenize in order
i -= offset # to remove them later via regex
if t == ':' and i > 0:
if "http" in tokens[i - 1]:
left = tokens[:i - 1]
right = tokens[i + 2:]
joined = [tokens[i - 1] + tokens[i] + tokens[i + 1]]
tokens = left + joined + right
offset += 2
cleaned = []
for token, tag in pos_tag(tokens):
token = re.sub('(\b(http|https):\/\/.*[^ alt]\b)', '', token) # links removal
token = re.sub("(@[A-Za-z0-9_]+)", "", token) # mention removal
token = re.sub("(#[A-Za-z0-9_]+)", "", token) # hashtag removal
if tag.startswith('NN'):
pos = 'n'
elif tag.startswith('VB'):
pos = 'v'
else:
pos = 'a'
lemmatizer = WordNetLemmatizer()
token = lemmatizer.lemmatize(token, pos)
if len(token) > 0 and token not in string.punctuation and token.lower() not in stopwords and re.search(
"[@_!#$0123456789.`%^&*()<>?/|}{~:]", token.lower()) == None:
cleaned.append(token.lower())
return cleaned
def get_prediction(self, input):
return self.classifier.classify(input)
def get_confidence(self, input):
return self.classifier.confidence(input)
def main():
#file_classifier = open("final_classifier.pickle", "rb")
#file_data = open("test_data.pickle", "rb")
#test_data = pickle.load(file_data)
#classifier = pickle.load(file_classifier)
#file_classifier.close()
#file_data.close()
predicter = predict_text()
custom = sys.argv[1]
cleaned = predicter.clean_text(custom, stopwords=stop_words)
input = dict([token, True] for token in cleaned)
print(predicter.get_prediction(input))
print(predicter.get_confidence(input))
# print(custom)
#print("My classifier accuracy: ", (nltk.classify.accuracy(classifier, test_data)) * 100)
if __name__ == '__main__':
main()
|
C++
|
UTF-8
| 2,393 | 3.140625 | 3 |
[
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// Part of Metta OS. Check https://atta-metta.net for latest version.
//
// Copyright 2007 - 2017, Stanislav Karchebnyy <berkus@atta-metta.net>
//
// Distributed under the Boost Software License, Version 1.0.
// (See file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once
template<typename T>
class Element
{
public:
T data;
bool operator < (Element& e) const { return data < e.data;}
bool operator <= (Element& e) const { return data <= e.data;}
bool operator > (Element& e) const { return data > e.data;}
bool operator >= (Element& e) const { return data >= e.data;}
bool operator == (Element& e) const { return data == e.data;}
Element& operator = (const Element& e)
{
data=e.data;
return *this;
}
Element(T& d) : data(d){}
};
//An integer element.
typedef Element<int> Elem;
class BTreeNode
{
public:
vector<Elem> m_data;
//m_child[i] is the child whose keys are smaller than that of m_data[i];
//and the size of m_child is always one more than m_data
vector<BTreeNode*> m_child;
//Here is my B-tree strcture representation
//
// m_data[0] m_data[1] ... m_data[i] ...
// m_child[0]--> / | | \ <--m_child[i+1]
// / | | \
//
BTreeNode* m_parent; // pointer to the parent BTreeNode
BTreeNode(BTreeNode* mp=NULL) : m_parent(mp){}
};
class BTree
{
typedef void (*v_func)(Elem &data);//visit function
protected:
int m_order; //maximum number of the elements stored a node
BTreeNode* m_root;//the root of the tree
v_func m_visit;
//return true if the insertion does not need split the current node
bool Normal_insert(Elem &);
//When the number of current node's element is overflow, perform split insertion
bool Split_insert(Elem &);
//store the result of every search
BTreeNode* search_result;
public:
BTree(v_func f, int n, BTreeNode* r=NULL):m_visit(f),m_order(n),m_root(r)
{
search_result = NULL;
};
~BTree();
bool Insertion(Elem&);//Insert a element to the B-tree.
bool Deletion(Elem&);
BTreeNode* Search(Elem&);//Search an Element in B-tree.
void travel(BTreeNode*) const; // travel the Btree
void print() const { travel(m_root); } // print the elements in a sorted order
};
|
C#
|
ISO-8859-2
| 4,232 | 2.671875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Transactions;
using AutoMapper;
using BLL.ModelManagers;
using CommonModels.Models;
using CommonModels.Models.EntityFramework;
using CommonPortable.Enums;
using CommonPortable.Exceptions;
using DAL.EntityFramework;
using UtilsLocal;
using UtilsShared;
using UtilsSharedPortable;
namespace BLL.EntityManagers
{
public static class RatingManager
{
#region CREATE
#region Add
public static void Add(Rating rating, ProductGroup ratingsProductGroup = null)
{
using(var ctx = new DBEntities())
using(var transactionScope = new TransactionScope())
{
Add(ctx, rating, ratingsProductGroup);
transactionScope.Complete();
}
}
public static void Add(DBEntities ctx, Rating rating, ProductGroup ratingsProductGroup = null)
{
try
{
ctx.Rating.Add(rating);
var productGroup = ratingsProductGroup ?? rating.ProductGroup;
productGroup.SumOfRatings++;
productGroup.SumOfRatingsValue += rating.Value;
ctx.SaveChanges();
}
catch (Exception e)
{
ctx.Entry(rating).State = EntityState.Detached;
const string msg = "Nem sikerlt beszrni a Rating rekordot. ";
throw new BookteraException(msg, e, BookteraExceptionCode.AddRating_InsertFailed);
}
}
#endregion
#endregion
#region READ
#region GetByID
public static Rating Get(int id)
{
using (var ctx = new DBEntities())
{
return Get(ctx, id);
}
}
public static Rating Get(DBEntities ctx, int id)
{
try
{
return ctx.Rating.Single(p => p.ID == id);
}
catch (Exception e)
{
var msg = String.Format("Nem tallhat a Rating rekord az adatbzisban. ID: {0}. ", id);
throw new BookteraException(msg, e, BookteraExceptionCode.GetRatingById);
}
}
#endregion
#region GetUsersRatings
public static List<RatingWithProductGroupVM> GetUsersRatings(int userId)
{
using(var ctx = new DBEntities())
{
return GetUsersRatings(ctx, userId);
}
}
public static List<RatingWithProductGroupVM> GetUsersRatings(DBEntities ctx, int userId)
{
var ratings = ctx.Rating.Where(r => r.UserID == userId).OrderByDescending(r => r.Date);
var result = new List<RatingWithProductGroupVM>();
foreach(Rating rating in ratings)
{
result.Add(new RatingWithProductGroupVM().DoConsturctorWork(rating));
}
return result;
}
#endregion
#endregion
#region UPDATE
#region Update
public static void Update(Rating rating)
{
using (var ctx = new DBEntities())
{
Update(ctx, rating);
}
}
public static void Update(DBEntities ctx, Rating rating)
{
try
{
ctx.SaveChanges();
}
catch (Exception e)
{
ctx.Entry(rating).State = EntityState.Unchanged;
string msg = string.Format("Nem sikerlt a frissteni a Rating rekordot! ID: {0}. ", rating.ID);
throw new BookteraException(msg, e, BookteraExceptionCode.UpdateRating);
}
}
#endregion
#endregion
#region DELETE
#region Delete
public static void Delete(Rating rating)
{
using (var ctx = new DBEntities())
{
Delete(ctx, rating);
}
}
public static void Delete(int id)
{
using (var ctx = new DBEntities())
{
var rating = Get(ctx, id);
Delete(ctx, rating);
}
}
public static void Delete(DBEntities ctx, Rating rating)
{
try
{
ctx.Rating.Remove(rating);
ctx.SaveChanges();
}
catch (Exception e)
{
ctx.Entry(rating).State = EntityState.Unchanged;
string msg = string.Format("Nem sikerlt a Rating rekord trlse. ID: {0}. ", rating.ID);
throw new BookteraException(msg, e, BookteraExceptionCode.DeleteRating);
}
}
#endregion
#endregion
#region OTHERS
#region CopyFromProxy
public static Rating CopyFromProxy(Rating rating)
{
bool wasNew;
AutoMapperInitializer<Rating, Rating>
.InitializeIfNeeded(out wasNew, sourceProxy: rating)
.ForMemberIfNeeded(wasNew, rating.Property(r => r.ProductGroup), imce => imce.Ignore())
.ForMemberIfNeeded(wasNew, rating.Property(r => r.UserProfile), imce => imce.Ignore());
return Mapper.Map<Rating>(rating);
}
#endregion
#endregion
}
}
|
C
|
UTF-8
| 4,971 | 2.84375 | 3 |
[] |
no_license
|
/*
* fileServer.c
*
* Created on: Jul 25, 2021
* Author: jinkies
*/
#include "esp_http_server.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include "cJSON.h"
#include "server.h"
#include "config.h"
const char *type = "text/html";
static esp_err_t hello_get_handler(httpd_req_t *req)
{
const char* resp_str = (const char*) req->user_ctx;
httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
if (httpd_req_get_hdr_value_len(req, "Host") == 0) {
ESP_LOGI(TAG, "Request headers lost");
}
return ESP_OK;
}
static uint16_t volume = 35;
static uint16_t val1 = 15;
static uint16_t val2 = 52;
/* An HTTP GET handler */
static esp_err_t main_get_handler(httpd_req_t *req)
{
char* buf;
size_t buf_len;
/* Get header value string length and allocate memory for length + 1,
* extra byte for null termination */
buf_len = httpd_req_get_hdr_value_len(req, "Host") + 1;
if (buf_len > 1) {
buf = malloc(buf_len);
/* Copy null terminated value string into buffer */
if (httpd_req_get_hdr_value_str(req, "Host", buf, buf_len) == ESP_OK) {
ESP_LOGI(TAG, "Found header => Host: %s", buf);
}
free(buf);
}
/* Set some custom headers */
httpd_resp_set_hdr(req, "Type", "Info");
/* Send response with custom headers and body set as the
* string passed in user context*/
const char* resp_str = (const char*) req->user_ctx;
httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN);
/* After sending the HTTP response the old HTTP request
* headers are lost. Check if HTTP request headers can be read now. */
if (httpd_req_get_hdr_value_len(req, "Host") == 0) {
ESP_LOGI(TAG, "Request headers lost");
}
return ESP_OK;
}
static esp_err_t update_get_handler(httpd_req_t *req){
httpd_resp_set_hdr(req, "Type", "Update");
/* Send response with custom headers and body set as the
* string passed in user context*/
/*char * val = strcat("{\"Volume\" : ",(char *)volume);
val = strcat(val,",\"val1\" :");
val = strcat(val,(char *)val1);
val = strcat(val,", \"val2\" : ");
val = strcat(val,(char *)val2);
val = strcat(val,"}");*/
cJSON *obj = cJSON_CreateObject();
cJSON_AddNumberToObject(obj, "Volume", volume);
cJSON_AddNumberToObject(obj, "val1", val1);
cJSON_AddNumberToObject(obj, "val2", val2);
char *objData = cJSON_PrintUnformatted(obj);
ESP_LOGI(TAG, "%s",objData);
httpd_resp_send(req, objData, HTTPD_RESP_USE_STRLEN);
/* After sending the HTTP response the old HTTP request
* headers are lost. Check if HTTP request headers can be read now. */
if (httpd_req_get_hdr_value_len(req, "Host") == 0) {
ESP_LOGI(TAG, "Request headers lost");
}
return ESP_OK;
}
static const httpd_uri_t hello = {
.uri = "/hello",
.method = HTTP_GET,
.handler = hello_get_handler,
/* Let's pass response string in user
* context to demonstrate it's usage */
.user_ctx = HTML_HELLO
};
static const httpd_uri_t info = {
.uri = "/",
.method = HTTP_GET,
.handler = main_get_handler,
/* Let's pass response string in user
* context to demonstrate it's usage */
.user_ctx = HTML_MAIN
};
static const httpd_uri_t update = {
.uri = "/update",
.method = HTTP_GET,
.handler = update_get_handler,
.user_ctx = HTML_MAIN
};
static httpd_handle_t start_webserver(void)
{
httpd_handle_t server = NULL;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.lru_purge_enable = true;
// Start the httpd server
ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port);
if (httpd_start(&server, &config) == ESP_OK) {
// Set URI handlers
ESP_LOGI(TAG, "Registering URI handlers");
httpd_register_uri_handler(server, &hello);
httpd_register_uri_handler(server, &info);
httpd_register_uri_handler(server, &update);
return server;
}
ESP_LOGI(TAG, "Error starting server!");
return NULL;
}
static void disconnect_handler(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data)
{
httpd_handle_t* server = (httpd_handle_t*) arg;
if (*server) {
ESP_LOGI(TAG, "Stopping webserver");
httpd_stop(*server);
*server = NULL;
}
}
static void connect_handler(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data)
{
httpd_handle_t* server = (httpd_handle_t*) arg;
if (*server == NULL) {
ESP_LOGI(TAG, "Starting webserver");
*server = start_webserver();
}
}
void init_server(void)
{
static httpd_handle_t server = NULL;
esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &connect_handler, &server);
esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &disconnect_handler, &server);
server = start_webserver();
ESP_LOGI(TAG, "Server started.");
}
|
Java
|
UTF-8
| 663 | 1.921875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package it.av.es.web.rest;
import it.av.es.model.Order;
import it.av.es.service.OrderService;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(value = "/orders")
public class OrdersController {
@Autowired
private OrderService orderService;
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public Collection<Order> get() {
return orderService.getAll();
}
}
|
Python
|
UTF-8
| 1,780 | 2.875 | 3 |
[] |
no_license
|
from collections import defaultdict, deque
from operator import and_, invert, lshift, or_, rshift
from sys import stdin
gates = dict(AND=and_, LSHIFT=lshift, NOT=invert, OR=or_, RSHIFT=rshift)
def parse_part(word):
if word.isdigit():
return int(word)
elif word.islower():
return word
elif word.isupper():
return gates[word]
else:
raise ValueError('Invalid part: {word}')
def parse_instruction(line):
source_str, wire = line.split(' -> ')
source = [parse_part(s) for s in source_str.split()]
return source, wire
def provide_signal(source, signals):
gate = None
input_signals = []
for part in source:
if type(part) == int:
input_signals.append(part)
elif type(part) == str:
if part not in signals:
return None
input_signals.append(signals[part])
else:
gate = part
return input_signals[0] if len(source) == 1 else gate(*input_signals)
def main():
circuit = [parse_instruction(line.strip()) for line in stdin]
sources = {}
output_wire_sets = defaultdict(set)
for source, wire in circuit:
sources[wire] = source
input_wires = [part for part in source if type(part) == str]
for input_wire in input_wires:
output_wire_sets[input_wire].add(wire)
signals = dict(b=956)
queue = deque(wire for _, wire in circuit)
while queue:
wire = queue.popleft()
if wire in signals:
continue
signal = provide_signal(sources[wire], signals)
if signal is not None:
signals[wire] = signal
queue.extend(output_wire_sets[wire])
print(signals['a'])
if __name__ == '__main__':
main()
|
C
|
UTF-8
| 2,704 | 3.15625 | 3 |
[] |
no_license
|
#include "Includes.h"
int main(){
//pega a entrada
char entrada[100];
int func;
fgets(entrada,100,stdin);
while(fgets(entrada,100,stdin)!=NULL){
//funcao para gerar uma string da funcionalidade
char *token = strtok(entrada, " ");
if (strcmp(token, "Insert") == 0){
func = 1;
}
if (strcmp(token, "Search") == 0){
func = 2;
}
if (strcmp(token, "Update") == 0){
func = 3;
}
if (strcmp(token, "Exit") == 0){
func = 4;
}
else continue;
switch(func){
//se for a funcionalidade 1 Insert
case 1:
char *entrada_aux = entrada+strlen(token)+1;
Student *student = entrada_student(entrada_aux);
if (student == NULL) {
printf("Input inválido!\n");
}
else {
int testebusca; //só pra compilar enquanto n arrumo
if (testebusca == 0) {
// Caso falhe com código 0, significa que já existe
printf("O Registro ja existe!\n");
}
else {
/* BTree *bTree;
bTree = createBTree();
addNewNodeToFile(bTree->rootNode);
Entry entry;
entry.key = 5;
entry.child = 0;
entry.rrn = 20;
insertNewElement(bTree, bTree->rootNode, &entry); */
setStudentByRRN(student->nUSP, student);
}
}
break;
//se for a funcionalidade 2 Search
case 2:
break;
//se for a funcionalidade 3 Update
case 3:
char * entrada_aux = entrada+strlen(token)+1;
Student *student = entrada_student(entrada_aux);
if (student == NULL) {
printf("Input inválido!\n");
}
else {
char arquivo[10] = "arquivo";
FILE * fp = fopen(arquivo , "w");
update(student);
/*Result * result = getRRNByPrimaryKey(0, student->nUSP);
if (result->node ) {
// Caso falhe com código 0, significa que não existe
printf("O Registro não foi encontrado!\n");
}
else {
updateToFile(fp, student, result->node);
fclose(fp);
}*/
}
break;
//se for a funcionalidade 4 Exit
case 4:
break;
//caso nao exista a funcionalidade ainda
default:
printf("Funcionalidade %d não implementada.\n", func);
return 0;
}
}
}
|
Python
|
UTF-8
| 990 | 2.890625 | 3 |
[] |
no_license
|
import pygame
class Lightbolt(pygame.sprite.Sprite):
def __init__(self, player):
super().__init__()
self.velocity = 15
self.player = player
self.image = pygame.image.load('assets/skill/lightbolt.png')
self.image = pygame.transform.scale(self.image, (100, 100))
self.rect = self.image.get_rect()
self.rect.x = player.rect.x + 100
self.rect.y = player.rect.y - 250
def remove(self):
self.player.all_spells.remove(self)
def move(self):
self.rect.y += self.velocity
# Check collision with monster
for monster in self.player.game.check_collision(self, self.player.game.monsters_group):
self.remove()
monster.damage(self.player.attack, 'wind')
for monster in self.player.game.check_collision(self, self.player.game.boss_group):
self.remove()
monster.damage(self.player.attack, 'wind')
# Remove projectile outside
if self.rect.x > 800:
self.remove()
if self.rect.y > 320:
self.remove()
|
Python
|
UTF-8
| 5,870 | 3.625 | 4 |
[] |
no_license
|
'''
数据结构--07--映射Map(基于二分搜索树BST实现)
'''
import time
from Map.map_base import MapBase
__author__ = 'Yan'
__date__ = '2018/3/17 15:48'
class BSTMap(MapBase):
'''
数据结构--07--映射Map(基于二分搜索树BST实现)
'''
class _Node:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.left = None
self.right = None
def __init__(self):
self.root = None
self._size = 0
def get_size(self):
return self._size
def is_empty(self):
return self._size == 0
def add(self, key, value):
self.root = self._add(self.root, key, value)
def _add(self, node, key, value):
'''
向以node为根节点的二分搜索树中插入节点,节点的键为key,键对应的值为value,采用递归算法实现
'''
if node is None:
self._size += 1
return self._Node(key, value)
if key < node.key:
node.left = self._add(node.left, key, value)
elif key > node.key:
node.right = self._add(node.right, key, value)
return node
def remove(self, key):
self.root = self._remove(self.root, key)
def _remove(self, node, key):
'''
从以node为根节点的二分搜索树中删除键为key的节点,采用递归算法实现
'''
if node is None:
return None
if key < node.key:
node.left = self._remove(node.left, key)
elif key > node.key:
node.right = self._remove(node.right, key)
else:
if node.left is None:
# node的左子树为空
right_node = node.right
node.right = None
self._size -= 1
return right_node
elif node.right is None:
# node的右子树为空
left_node = node.left
node.left = None
self._size -= 1
return left_node
else:
# node的左右子树均不为空
successor = self._minimum(node.right)
successor.left = node.left
successor.right = self._remove_min(node.right)
node.left = None
node.right = None
return successor
def minimum(self):
'''
返回二分搜索树的最小元素值,用户调用的minimum方法,真正处理逻辑在_minimum方法中
'''
if self._size == 0:
raise IndexError("BSTMap is empty")
return self._minimum(self.root).key
def _minimum(self, node):
'''
返回以node为根节点中最小元素值的节点,最小元素值所在的节点在整棵树的最左下方,采用递归实现
'''
if node.left is None:
return node
node = self._minimum(node.left)
return node
def remove_min(self):
'''
删除最小元素所在的节点,并返回最小值,用户调用的remove_min方法,真正处理逻辑在_remove_min方法中
'''
ret = self._minimum(self.root)
self.root = self._remove_min(self.root)
return ret.key
def _remove_min(self, node):
'''
删除以node为根节点的最小元素值所在节点,并返回新二分搜索树的根节点,采用递归算法实现
存在两种情况:
1. 最小元素值所在节点没有右子节点,直接remove即可
2. 最小元素值所在节点存在右子节点,需要先保存右子节点,并连接上最小元素值所在节点的父节点
'''
if node.left is None:
right_node = node.right
node.right = None
self._size -= 1
return right_node
node.left = self._remove_min(node.left)
return node
def find_node(self, node, key):
'''
在以node为根节点的二分搜索树种查找键为key的节点,并返回,采用递归实现
'''
if node is None:
raise IndexError("key {} is not exist".format(key))
if key == node.key:
return node
elif key < node.key:
result = self.find_node(node.left, key)
else:
result = self.find_node(node.right, key)
return result
def getter(self, key):
node = self.find_node(self.root, key)
return node.value
def setter(self, key, value):
try:
node = self.find_node(self.root, key)
node.value = value
except IndexError:
self.add(key, value)
def contains(self, key):
try:
self.find_node(self.root, key)
return True
except IndexError:
return False
def bst_map_test(bst_map):
'''
测试BSTMap代码书写是否正确
'''
with open('shakespeare.txt', 'r') as f:
words = f.read()
words = words.split()
start_time = time.time()
for word in words:
if bst_map.contains(word):
bst_map.setter(word, bst_map.getter(word)+1)
else:
bst_map.add(word, 1)
print('total words: ', len(words))
print("unique words: ", bst_map.get_size())
print("contains word 'This': ", bst_map.contains('This'))
print('total time: {} seconds'.format(time.time() - start_time))
bst_map.remove("This")
print("contains word 'This' after remove : ", bst_map.contains("This"))
bst_map.setter("This", 200)
print("the value of key is 'This' : ", bst_map.getter("This"))
if __name__ == "__main__":
bst_map = BSTMap()
bst_map_test(bst_map)
|
C#
|
UTF-8
| 5,100 | 2.734375 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using System;
// NOTE ALL REACTIONS THAT FADE IN / OUT NEED TO HAVE NUM OBJECTS >= 1.
// DO NOT ADD A REACTION SCRIPT TO THE SCENE IF YOU HAVE THE NUM OBJECTS = 0
namespace Assets.Scripts{
public static class Utilities {
public static Boolean fadeOutObjects(GameObject[] realObjs, Vector3[] originalScaleArray, ref float fadeOutClock, float deltaTime) {
// keep track of if we need to keep calling this fun
Boolean anyFadeOut = false;
Vector3 originalScale;
fadeOutClock += deltaTime;
// every twentieth of a second
if (fadeOutClock > 0.05f) {
fadeOutClock = 0.0f;
// go through all objects
for (int i = 0; i < realObjs.Length; i++) {
// use either the default original scale or the one corresponding to our array object
if (originalScaleArray.Length == 1) originalScale = originalScaleArray[0];
else originalScale = originalScaleArray[i];
// check if its already been destroyed
if (realObjs[i] == null) continue;
// and decrease their scale by 10% of the original scale
if (realObjs[i].transform.localScale.x > originalScale.x) {
realObjs[i].transform.localScale = originalScale;
anyFadeOut = true;
}
else if (realObjs[i].transform.localScale.x > originalScale.x * 0.1f) {
realObjs[i].transform.localScale -= originalScale * 0.1f;
anyFadeOut = true;
}
else if (realObjs[i].transform.localScale.x > 0) {
realObjs[i].transform.localScale = originalScale * 0;
anyFadeOut = true;
}
else {
// if the object is done shrinking, DESTROY IT
GameObject.Destroy(realObjs[i]);
}
}
}
else {
// since we haven't reached the time req yet, we assume we're still fading out.
// once we read 0.05 seconds and nothing needs resizing, we're done
anyFadeOut = true;
}
return anyFadeOut;
}
public static Boolean fadeInObjects(GameObject[] realObjs, Vector3[] originalScaleArray, ref float fadeOutClock, float deltaTime) {
// keep track if any needed fading in
// return false if we're done
Boolean anyFadeIn = false;
Vector3 originalScale;
fadeOutClock += deltaTime;
// every twentieth of a second
if (fadeOutClock > 0.05f) {
fadeOutClock = 0.0f;
// go through all objects
for (int i = 0; i < realObjs.Length; i++) {
// use either the default original scale or the one corresponding to our array object
if (originalScaleArray.Length == 1) originalScale = originalScaleArray[0];
else originalScale = originalScaleArray[i];
// and increase their scale by 10% of the original scale
if (realObjs[i].transform.localScale.x < originalScale.x) {
realObjs[i].transform.localScale += originalScale * 0.1f;
anyFadeIn = true;
}
// this should never happen, but if they grow beyond the original scale, set them to it
if (realObjs[i].transform.localScale.x > originalScale.x) {
realObjs[i].transform.localScale = new Vector3(originalScale.x, originalScale.y, originalScale.z);
}
}
}
else {
// since we haven't reached the time req yet, we assume we're still fading in.
// once we read 0.05 seconds and nothing needs resizing, we're done
anyFadeIn = true;
}
return anyFadeIn;
}
// within 15 of player on all axis is too close
public static Boolean isNearPlayer (Vector3 position) {
if (position.x > -15.0f && position.x < 15.0f) {
if (position.y > -15.0f && position.y < 15.0f) {
if (position.z > -15.0f && position.z < 15.0f) {
return true;
}
}
}
return false;
}
// within 100 of player on 2d axis is too close
public static Boolean isNearPlayerFar (Vector3 position) {
if (position.x > -100.0f && position.x < 100.0f) {
if (position.z > -100.0f && position.z < 100.0f) {
return true;
}
}
return false;
}
}
}
|
Java
|
UTF-8
| 3,144 | 2.59375 | 3 |
[] |
no_license
|
package com.example.weixin;
import android.app.Activity;
import android.os.*;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
/**
* Created by fan on 2016/5/5.
*/
public class ProgressBarActivity extends Activity{
ProgressBar pb_load;
Button btn_pbload;
//Handler handler;
//int progress=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progressbar);
/*handler=new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==0x110){
pb_load.setProgress(progress);
}
if(msg.what==0x120){
Toast.makeText(ProgressBarActivity.this,"加载完成",Toast.LENGTH_LONG).show();
}
}
};*/
pb_load=(ProgressBar)findViewById(R.id.pb_load);
btn_pbload=(Button)findViewById(R.id.btn_pbload);
btn_pbload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new ProgressAsyncTask().execute();
Toast.makeText(ProgressBarActivity.this,"加载完成",Toast.LENGTH_LONG).show();
/*pb_load.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
@Override
public void run() {
while(true){
int random=(int)(Math.random()*10);
progress=progress*random;
handler.sendEmptyMessage(0x110);
if(progress>100){
break;
}
SystemClock.sleep(1000);
}
handler.sendEmptyMessage(0x120);
}
}).start();*/
}
});
}
class ProgressAsyncTask extends AsyncTask<String,Integer,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
pb_load.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... strings) {
int progress=0;
while(true){
int random=(int)(Math.random()*10);
progress=progress*random;
publishProgress(progress);
if(progress>=100)break;
SystemClock.sleep(1000);
}
return "success";
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pb_load.setProgress(values[0]);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result=="success"){
Toast.makeText(ProgressBarActivity.this,"加载完成",Toast.LENGTH_LONG).show();
}
}
}
}
|
Go
|
UTF-8
| 1,533 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
package encoding
import (
"encoding/binary"
"io"
"math"
)
type Encoder interface {
Encode(w io.Writer) error
}
func WriteUint64(w io.Writer, val uint64) error {
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, val)
_, err := w.Write(buf)
return err
}
func WriteUint32(w io.Writer, val uint32) error {
buf := make([]byte, 4)
binary.LittleEndian.PutUint32(buf, val)
_, err := w.Write(buf)
return err
}
func WriteUint16(w io.Writer, val uint16) error {
buf := make([]byte, 2)
binary.LittleEndian.PutUint16(buf, val)
_, err := w.Write(buf)
return err
}
func WriteUInt16BE(w io.Writer, val uint16) error {
buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf, val)
_, err := w.Write(buf)
return err
}
func WriteUint8(w io.Writer, val uint8) error {
_, err := w.Write([]byte{val})
return err
}
func WriteVarint(w io.Writer, val uint64) error {
var buf []byte
if val <= 0xfc {
buf = []byte{uint8(val)}
} else if val <= math.MaxUint16 {
buf = make([]byte, 3)
buf[0] = 0xfd
binary.LittleEndian.PutUint16(buf[1:], uint16(val))
} else if val <= math.MaxUint32 {
buf = make([]byte, 5)
buf[0] = 0xfe
binary.LittleEndian.PutUint32(buf[1:], uint32(val))
} else {
buf := make([]byte, 9)
buf[0] = 0xff
binary.LittleEndian.PutUint64(buf[1:], val)
}
_, err := w.Write(buf)
return err
}
func WriteVarBytes(w io.Writer, buf []byte) error {
if err := WriteVarint(w, uint64(len(buf))); err != nil {
return err
}
if _, err := w.Write(buf); err != nil {
return err
}
return nil
}
|
JavaScript
|
UTF-8
| 986 | 4.0625 | 4 |
[] |
no_license
|
// Construct a square matrix with a size N × N containing integers from 1 to N * N in a spiral order, starting from top-left and in clockwise direction.
// Example
// For n = 3, the output should be
// spiralNumbers(n) = [[1, 2, 3],
// [8, 9, 4],
// [7, 6, 5]]
// Input/Output
// [execution time limit] 4 seconds (js)
// [input] integer n
// Matrix size, a positive integer.
// Guaranteed constraints:
// 3 ≤ n ≤ 100.
// [output] array.array.integer
function spiralNumbers(n) {
var matrix = [...Array(n)].map(_ => []),
x = 0,
y = 0,
dir = 2,
size = n,
c = 0;
for (var i = 1; i <= n * n; i++) {
matrix[y][x] = i;
if (++c == size) {
dir = (dir + 1) % 4;
console.log("dir " + dir)
size -= dir % 2;
c = 0;
}
if (dir % 2 == 0) x += dir > 1 ? 1 : -1;
else y += dir > 1 ? 1 : -1;
}
return matrix;
}
|
C#
|
UTF-8
| 3,656 | 2.625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Merwer.Chronicle.Dungeoneering.Tracker.Models
{
/*
* Stats to be calculated:
- General
- Total Drafts
- Total Games
- Win Rate
- Going First Win Rate
- Average Dungeon Depth
- Number of Times at each Depth
- Average Rewards
- Win Rate vs. Legend Y
- Stats as Legend X
- Total Drafts
- Total Games
- Win Rate
- Going First Win Rate
- Average Dungeon Depth
- Number of Times at each Depth (0-2, 3-6, 7-11, 12)
- Win Rate vs. Legend Y
- Total Rewards
- Play Schedule (X times per day of the week)
*/
public class BasicStatsData
{
public int Drafts { get; set; }
public int Games { get; set; }
public int TotalWins { get; set; }
public int TotalLosses { get; set; }
[DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
public double AverageWins { get; set; }
[DisplayFormat(DataFormatString = "{0:P2}", ApplyFormatInEditMode = true)]
public double WinRate { get; set; }
[DisplayFormat(DataFormatString = "{0:P2}", ApplyFormatInEditMode = true)]
public double FirstWinRate { get; set; }
[DisplayFormat(DataFormatString = "{0:P2}", ApplyFormatInEditMode = true)]
public double SecondWinRate { get; set; }
public int ZeroToTwoWins { get; set; }
public int ThreeToSixWins { get; set; }
public int SevenToElevenWins { get; set; }
public int TwelveWins { get; set; }
}
public class LegendSpecificStatsData : BasicStatsData
{
public Archetype Legend { get; set; }
}
public class MyStatsData : BasicStatsData
{
public MatchRewardList AverageRewards { get; set; }
public MatchRewardList TotalRewards { get; set; }
public List<LegendSpecificStatsData> LegendStats { get; set; }
public LegendSpecificStatsData RaptorStats { get; set; }
public LegendSpecificStatsData ArianeStats { get; set; }
public LegendSpecificStatsData OzanStats { get; set; }
public LegendSpecificStatsData VanesculaStats { get; set; }
public LegendSpecificStatsData LinzaStats { get; set; }
public LegendSpecificStatsData MorvranStats { get; internal set; }
public ArchetypeMatchData LegendMatches { get; set; }
}
public class ArchetypeMatchData
{
public ArchetypeMatchList Raptor { get; set; }
public ArchetypeMatchList Ariane { get; set; }
public ArchetypeMatchList Ozan { get; set; }
public ArchetypeMatchList Vanescula { get; set; }
public ArchetypeMatchList Linza { get; set; }
public ArchetypeMatchList Morvran { get; set; }
}
public class ArchetypeMatchList
{
public Archetype Legend { get; set; }
public ArchetypeMatch VersusRaptor { get; set; }
public ArchetypeMatch VersusAriane { get; set; }
public ArchetypeMatch VersusOzan { get; set; }
public ArchetypeMatch VersusVanescula { get; set; }
public ArchetypeMatch VersusLinza { get; set; }
public ArchetypeMatch VersusMorvran { get; set; }
}
public class ArchetypeMatch
{
public Archetype Opponent { get; set; }
public int Matches { get; set; }
public int Wins { get; set; }
[DisplayFormat(DataFormatString = "{0:P2}", ApplyFormatInEditMode = true)]
public double WinRate
{
get
{
return Matches == 0 ? 0 : ((double)Wins) / Matches;
}
}
}
}
|
Python
|
UTF-8
| 27,950 | 3.25 | 3 |
[] |
no_license
|
import log_setup
import regex
log = log_setup.get_log()
def sub(pattern: str, repl: str, string: str, debug: bool = False) -> str:
'''
Wrapper for the regex.sub function which includes an optional debug argument.
Parameters
----------
pattern : str
The regex pattern to match against.
repl : str
The replacement string.
string : str
The string in which to perform the replacement.
debug : bool
If True, will log the output of the substitution.
Returns
-------
str
A new string with the substitution applied (if applicable).
'''
word = regex.sub(pattern, repl, string)
if debug:
log(word, stacklevel=2)
return word
consonants: list[str] = []
vowels: list[str] = []
def reset() -> None:
'''
Resets the consonants and vowels to their initial (i.e., Latin) state.
'''
global consonants, vowels
consonants = ['b', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'v', 'w', 'z']
vowels = ['a', 'e', 'i', 'o', 'u']
def join(include: list[str], *exclude: str) -> str:
'''
Joins the elements of the list and returns a non-capturing regex group of the form '(?:e1|e2|e3...)'.
Parameters
----------
include : list[str]
The list of elements to include in the group.
*exclude : str
Elements which should be excluded from the list.
Returns
-------
str
The non-capturing group.
'''
return '(?:' + '|'.join(i for i in include if i not in exclude) + ')'
def to_proto_western_romance(word: str, debug: bool = False) -> str:
'''
Simulates the sounds changes that occurred between Latin and Proto-Western Romance and returns the result.
Parameters
----------
word : str
The word to apply the sound changes to.
debug : bool
If True, debug information will be output.
Returns
-------
str
The evolved word.
'''
global consonants, vowels
# Substitute "kʷ" for /kw/ and "gʷ" for /gw/. The velarized forms of /k/ and /g/ evolve differently from regular /k/ and /g/, but they're difficult to type, so this substitution should help.
word = sub('kw', 'kʷ', word, debug)
word = sub('gw', 'gʷ', word, debug)
consonants.extend(['kʷ', 'gʷ'])
# Dissimilation of multiple /kw/s.
word = sub('kʷ(?=.+kʷ)', 'k', word, debug)
# Introduction of short /i/ before initial /s/ + consonant.
word = sub(f'^(?=s{join(consonants)})', 'i', word, debug)
# Reduction of 10 vowels to 7. Unstressed /ɛ/, /ɔ/ raised to /e/, /o/, respectively.
# TODO: I'm not sure at the moment if this only affected /aj/ from <ae> or if it affected /ai/ + vowel clusters as well. Similarly for /oj/. For now I'm going to assume that it only affected <ae>/<oe>.
word = sub('a:', 'a', word, debug)
word = sub(f'aj(?={join(consonants)}|$)|e(?!:)', 'ɛ', word, debug)
word = sub(f'oj(?={join(consonants)}|$)|e:|(?:i|y)(?!:)', 'e', word, debug)
word = sub('(?:i|y):', 'i', word, debug)
word = sub('o(?!:)', 'ɔ', word, debug)
word = sub('u(?!:)|o:', 'o', word, debug)
word = sub('u:', 'u', word, debug)
word = sub('(?<!/)ɛ', 'e', word, debug)
word = sub('(?<!/)ɔ', 'o', word, debug)
vowels.extend(['ɛ', 'ɔ'])
# Loss of final /m/ except in monosyllables, which becomes /n/.
# TODO: Based on examples, this appears to have also happened to final /n/ in words borrowed from Gaulish.
word = sub(f'(?<={join(vowels)}{join(consonants)}*/?{join(vowels)})(?:m|n)$', '', word, debug)
word = sub('m$', 'n', word, debug)
# Loss of /h/.
word = sub('h', '', word, debug)
# I'm going to leave /h/ in the list for the time being as it can reappear in Germanic borrowings in later periods.
# consonants.remove('h')
# /ns/ > /s/.
word = sub('ns', 's', word, debug)
# /rs/ > /ss/.
# TODO: There are some expections to this, but they aren't clearly defined, so I'm going to ignore them now.
word = sub('rs', 'ss', word, debug)
# Final /er/ > /re/, /or/ > /ro/.
# TODO: It's unspecified if this happens to /ɛr/ and /ɔr/ as well. I don't believe Latin ever allowed stress on the final syllable, and since /ɛ/ and /ɔ/ are only ever stressed, these combinations might not be possible. As such, I'm going to ignore them for now. However, it doesn't indicate whether it happens with stressed /e/ and /o/ either, but again, since I don't believe Latin ever allowed stress to fall on the final syllable, this probably doesn't occur, so I'm going to assume it's only unstressed until I see an example indicating otherwise. I also suspect that this doesn't happen in single syllable words, since Latin <per> > French <par>.
word = sub(f'(?<={join(vowels)}{join(consonants)}+)(e|o)r$', 'r\\1', word, debug)
# Loss of unstressed interior syllables between /k/, /g/ and /r/, /l/.
# TODO: It's unspecified if this applies to /a/ or not, which typically resists being lost in other situations. For now, I'm going to assume that it's lost with the others.
word = sub(f'(?<=k|g){join(vowels)}(?=r|l)', '', word, debug)
# Reduction of /e/, /i/ in hiatus to /j/, followed by palatalization. Stress shifts forward. /k/ geminates before palatalization.
word = sub(f'(/?)(?:e|i)(?=/?{join(vowels)})', 'j\\1', word, debug)
word = sub(f'(?<={join(consonants)})j', 'ʲ', word, debug)
word = sub('(?<!k)kʲ', 'kkʲ', word, debug)
# Reduction of /o/, /u/ in hiatus to /w/. Stress shifts backward if possible. Initial /w/ > /v/.
# TODO: Not gonna lie, I'm purely guessing on the "initial /w/ > /v/" part based on some examples that I've seen, but I have no idea how to explain certain later changes otherwise.
word = sub(f'({join(vowels)})(/?)(?:o|u)(?=/?{join(vowels)})', '\\1\\2w', word, debug)
word = sub(f'(/?)(?:o|u)(?=/?{join(vowels)})', 'w\\1', word, debug)
word = sub('^w', 'v', word, debug)
# /k/, /g/ palatalized before front vowels.
word = sub('(?<=k|g)(/?(?:e|i|ɛ))', 'ʲ\\1', word, debug)
# Initial /j/ and /dʲ/, /gʲ/, /z/ > /ɟ/.
word = sub('^j|dʲ|gʲ|z', 'ɟ', word, debug)
consonants.append('ɟ')
return word
def to_proto_gallo_ibero_romance(word: str, debug: bool = False) -> str:
'''
Simulates the sounds changes that occurred between Latin and Proto-Gallo-Ibero-Romance and returns the result.
Parameters
----------
word : str
The word to apply the sound changes to.
debug : bool
If True, debug information will be output.
Returns
-------
str
The evolved word.
'''
global consonants, vowels
# /kʲ/, /tʲ/ merge to /ʦʲ/.
word = sub('kkʲ', 'ttʲ', word, debug)
word = sub('(?:k|t)ʲ', 'ʦʲ', word, debug)
consonants.append('ʦ')
# /nkt/ > /nt/, /nks/ > /ns/, /kt/ > /jt/, /ks/ > /jss/, /gm/ > /wm/.
# TODO: I think the /ks/ case becomes /jss/ as opposed to /js/ as suggested because it maintains an /s/ in French, rather than leniting to /z/, so it must've been long.
# word = sub('(?<=n)k(?=s|t)', '', word, debug)
word = sub('k(?=s)', 'js', word, debug)
word = sub('k(?=t)', 'j', word, debug)
word = sub('gm', 'wm', word, debug)
# First diphthongization: stressed open /ɛ/ > /jɛ/, /ɔ/ > /wɔ/. This also happens in closed syllables before /j/.
# TODO: Based on examples, it appears that /ɔ/ remains before nasals.
word = sub(f'/ɛ(?={join(consonants)}ʲ?{join(vowels)}|j)', 'j/ɛ', word, debug)
word = sub(f'(?<!w)/ɔ(?=(?:{join(consonants, "n", "m")}|(?:p|b|t|d|g|k)(?:r|l))ʲ?{join(vowels)}|j)', 'w/ɔ', word, debug)
# /a/ > /ɔ/ before back rounded vowels or /g/ + back rounded vowels. This also happens to /aw/ before /g/ + back rounded vowels.
# TODO: Based on examples, I think the /a/ might need to be stressed. If you allow both stressed and unstressed /a/, you get contradicting examples. I'm not entirely sure on this though, so I might change it later.
word = sub(f'/a(?=(?:o|u|ɔ)|w{join(vowels)}|(?:g|k)(?:o|u|ɔ))', '/ɔ', word, debug)
word = sub(f'aw(?=(?:g|k)/?(?:o|u|ɔ))', 'ɔ', word, debug)
word = sub(f'(?<={join(vowels, "ɔ")})w(?=/?{join(vowels)})', 'v', word, debug)
# First lenition.
# TODO: Based on examples, I'm guessing that preceding diphthongs still count.
word = sub(f'(?<={join(vowels)}w?j?)(?:b|f)(?=r?ʲ?/?{join(vowels)})', 'v', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)p(?=(?:r|l)?ʲ?/?{join(vowels)})', 'b', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)d(?=r?ʲ?/?{join(vowels)}|$)', 'ð', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)t(?=r?ʲ?/?{join(vowels)}|$)', 'd', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)s(?=ʲ?/?{join(vowels)})', 'z', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)ʦ(?=ʲ?/?{join(vowels)})', 'ʣ', word, debug)
word = sub(f'(?<=ɔ)(?:g|k)(?=/?(?:o|u|ɔ|w))', 'w', word, debug)
word = sub(f'(?<={join(vowels)})g(?=/?(?:o|u|ɔ))', '', word, debug)
word = sub('(?<=u|w)g(?=/?a)', '', word, debug)
word = sub('(?<=o|ɔ)g(?=/?a)', 'v', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)g(?=(?:n|r|l)?ʲ?/?{join(vowels)})', 'j', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)k(?=(?:r|l)?ʲ?/?{join(vowels)})', 'g', word, debug)
word = sub(f'(?<=i|e|ɛ)kʷ(?=/?{join(vowels)})', 'w', word, debug)
consonants.extend(['ð', 'ʣ'])
# Formation of palatal new palatal consonants: /ɲ/, /ʎ/.
word = sub('jn|nj|nɟ|nʲ', 'ɲ', word, debug)
word = sub('jl|gl|lʲ', 'ʎ', word, debug)
consonants.extend(['ɲ', 'ʎ'])
# First vowel loss: loss of pretonic vowels except /a/ when not initial. This sporadically occurs before the first lenition.
# TODO: Based on examples, it looks like initial vowels are then reduced to /ə/.
word = sub(f'(?<={join(vowels)}{join(consonants)}*){join(vowels, "a")}(?={join(consonants)}*(?:ʲ|j|w)?/{join(vowels)})', '', word, debug)
# TODO: Consonant clusters are reduced here, but the mechanisms are complicated. Ignoring it for now.
return word
def to_early_old_french(word: str, debug: bool = False) -> str:
'''
Simulates the sounds changes that occurred between Latin and Early Old French and returns the result.
Parameters
----------
word : str
The word to apply the sound changes to.
debug : bool
If True, debug information will be output.
Returns
-------
str
The evolved word.
'''
global consonants, vowels
# /ɟ/ when initial and following a consonant become /ʤ/. All others become /j/.
word = sub(f'^ɟ|(?<={join(consonants, "w", "j")}ʲ?)ɟ', 'ʤ', word, debug)
word = sub('ɟ', 'j', word, debug)
consonants.remove('ɟ')
# /j/ palatalizes following consonants.
# TODO: It's unspecified if the palatalization passes through clusters. For now I'll assume that that situation doesn't occur.
word = sub(f'j({join(consonants, "ɲ", "ʎ")}(?!ʲ))', 'j\\1ʲ', word, debug)
# Consonants depalatalize and eject a /j/ (sometimes two).
word = sub(f'(?<={join(vowels)})(?:b|v)ʲ(?=/?{join(vowels)})', 'ʤ', word, debug)
word = sub(f'(?<={join(vowels)})(?:p|f)ʲ(?=/?{join(vowels)})', 'ʧ', word, debug)
word = sub(f'(?<={join(vowels)})mʲ(?=/?{join(vowels)})', 'nʤ', word, debug)
word = sub(f'arʲ(?=/?{join(vowels)})', 'jarʲ', word, debug)
word = sub(f'(?<={join(vowels)})((?:{join(consonants, "r")}|ss)ʲ)(?=/?{join(vowels)})', 'j\\1', word, debug)
word = sub(f'({join(consonants)}ʲ|ʤ|ʧ)(?=/(?:a|æ|e)j?w?(?:{join(consonants)}ʲ?{join(vowels)}|$))', '\\1j', word, debug)
word = sub('ʲ', '', word, debug)
consonants.append('ʧ')
# Second diphthongization: stressed open /e/ > /ej/, /o/ > /ow/, /a/ > /æ/ when not followed by /j/.
# TODO: Based on examples, it appears that /o/ remains before nasals, and /a/ remains before /ɲ/.
word = sub(f'/e(?=(?:{join(consonants, "j")}|(?:p|b|t|d|g|k)(?:r|l)){join(vowels)}|$)', '/ej', word, debug)
word = sub(f'/o(?=(?:{join(consonants, "j", "n", "m", "ɲ")}|(?:p|b|t|d|g|k)(?:r|l)){join(vowels)}|$)', '/ow', word, debug)
word = sub(f'/a(?=(?:{join(consonants, "j", "ɲ")}|(?:p|b|t|d|g|k)(?:r|l)){join(vowels)}|$)', '/æ', word, debug)
vowels.append('æ')
# /ɔ/ combines with back rounded vowels to produce /ɔw/.
word = sub('(?<=ɔ)g?(?:o|u|ɔ)', 'w', word, debug)
# TODO: I originally included these steps as part of the second lenition below, but based on examples, these need to happen before the posttonic vowel loss.
word = sub(f'(?<={join(vowels)})g(?=/?(?:o|u|ɔ))', '', word, debug)
word = sub('(?=o|u|ɔ|w)g(?=/?a)', '', word, debug)
# Loss of posttonic vowels except /a/, which reduces to /ə/. Remaining final vowels except /a/ reduced to /ə/.
# TODO: Because the vocalization of /l/ needed to occur after the vowel loss, this step continues with the reduction to /ə/ after the vocalization step below.
word = sub(f'(?<=/{join(vowels)}{join(consonants)}*){join(vowels, "a")}', '', word, debug)
# Vocalization of /l/ before consonants began in the ninth century with /l/ > /ɫ/. It's not specified exactly when, but it for certain had to have begun before the loss of gemination as vocalization occurred in /ll/ as well except before /a/. Vocalization won't complete until much later, however, when /ɫ/ > /w/.
# TODO: Based on examples, it looks like this affects /ʎ/ before consonants as well.
word = sub('lla', 'la', word, debug)
word = sub('ll', 'ɫɫ', word, debug)
word = sub(f'(?:l|ʎ)(?={join(consonants, "j", "w")})', 'ɫ', word, debug)
consonants.append('ɫ')
# This is the continuation of the vowel loss mentioned above.
word = sub(f'(?<=/{join(vowels)}{join(consonants)}*){join(vowels)}', 'ə', word, debug)
vowels.append('ə')
# TODO: Consonant clusters may be reduced here again.
# /tl/ > /kl/.
word = sub('tl', 'kl', word, debug)
# Second lenition.
# TODO: Based on examples, I'm guessing preceding diphthongs still count.
word = sub(f'(?<={join(vowels)}w?j?)(?:b|f)(?=r?/?{join(vowels)})', 'v', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)p(?=(?:r|l)?/?{join(vowels)})', 'b', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)d(?=r?/?{join(vowels)}|$)', 'ð', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)t(?=r?/?{join(vowels)}|$)', 'd', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)s(?=/?{join(vowels)})', 'z', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)ʦ(?=/?{join(vowels)})', 'ʣ', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)g(?=(?:n|r|l)?/?{join(vowels)})', 'j', word, debug)
word = sub(f'(?<={join(vowels)}w?j?)k(?=(?:r|l)?/?{join(vowels)})', 'g', word, debug)
word = sub(f'(?<=i|e|ɛ|æ)kʷ(?=/?{join(vowels)})', 'w', word, debug)
# Palatalization of /k/ > /ʧ/, /g/ > /ʤ/ before /a/.
# TODO: Although unspecified. I suspect this happened before /æ/ as well. It looks like this also affected /kk/ and /gg/.
word = sub('k?k(?=/?(?:a|æ))', 'ʧ', word, debug)
word = sub('g?g(?=/?(?:a|æ))', 'ʤ', word, debug)
consonants.append('ʧ')
# /æ/ > /jɛ/ after /ʧ/ or /ʤ/ and followed by a nasal or /j/, or /aj/ before nasals if not preceeded by /j/, otherwise /ɛ/.
# TODO: The addition of /j/ after /ʧ/ or /ʤ/ seems to have been universal, but by Modern French, based on examples, the /j/ only remains if followed by a nasal. Compare the evolution of <cher> vs <chien>.
word = sub('(?<=ʧ|ʤ)/æ(?=(?:j|n|m|ɲ))', 'j/ɛ', word, debug)
word = sub('(?<!j)/æ(?=(?:n|m|ɲ))', '/aj', word, debug)
word = sub('æ', 'ɛ', word, debug)
vowels.remove('æ')
# /aw/ > /ɔ/.
word = sub('aw', 'ɔ', word, debug)
# Loss of gemination accept for /rr/.
word = sub(f'({join(consonants, "r")})\\1', '\\1', word, debug)
# Final stops and fricatives devoiced.
# TODO: I'm assuming this also happens to affricates based on /ʣ/ not being listed in the deaffrication step which happens later in combination with the following step in which it deaffricates to /z/. Otherwise, this sound would still exist in modern French.
word = sub('b$', 'p', word, debug)
word = sub('v$', 'f', word, debug)
word = sub('d$', 't', word, debug)
word = sub('ð$', 'θ', word, debug)
word = sub('z$', 's', word, debug)
word = sub('ʣ$', 'ʦ', word, debug)
word = sub('g$', 'k', word, debug)
consonants.append('θ')
# /ʣ/ > /z/ when not final.
word = sub('ʣ(?!$)', 'z', word, debug)
consonants.remove('ʣ')
# /t/ inserted between /ɲ/, /ʎ/ and following /s/.
word = sub('(ɲ|ʎ)s', '\\1ʦ', word, debug)
# Depalatalization of /ɲ/, /ʎ/ when following a consonant or final.
# TODO: Based on examples, it looks like it happens to /ɲ/ when followed by consonants also.
word = sub(f'ɲ(?={join(consonants)})', 'jn', word, debug)
word = sub(f'(?<={join(consonants, "j")})ɲ|(?<!j)ɲ$', 'jn', word, debug)
word = sub(f'(?<={join(consonants)})ʎ|ʎ$', 'l', word, debug)
# /jaj/, /jɛj/, /jej/ > /i/ and /wɔj/ > /uj/.
word = sub('j(/?)(?:a|ɛ|e)j', '\\1i', word, debug)
word = sub('w(/?)ɔj', '\\1uj', word, debug)
# Final /a/ > /ə/.
# TODO: I think this occurs for unstressed /a/s in other places too, but need examples.
word = sub('a$', 'ə', word, debug)
return word
def to_old_french(word: str, debug: bool = False) -> str:
'''
Simulates the sounds changes that occurred between Latin and Old French and returns the result.
Parameters
----------
word : str
The word to apply the sound changes to.
debug : bool
If True, debug information will be output.
Returns
-------
str
The evolved word.
'''
global consonants, vowels
# Loss of /f/, /p/, /k/ before final /s/, /t/.
word = sub('(?:f|p|k)(?=s$|t$)', '', word, debug)
# Nasalization of low vowels before all nasals.
word = sub('((?:a|e|o|ɛ|ɔ|ɑ)(?:w|j)?)(?=m|n|ɲ)', '\\1~', word, debug)
# /ej/ > /oj/ (blocked by nasalization).
word = sub('ej(?!~)', 'oj', word, debug)
# /ow/ > /ew/ (blocked by labials and nasalization).
word = sub('ow(?!p|b|v|f|m|~)', 'ew', word, debug)
# /wɔ/ > /wɛ/ (blocked by nasalization).
word = sub('w(/?)ɔ(?!~)', 'w\\1ɛ', word, debug)
# /a/ > /ɑ/ before /s/ or /z/.
word = sub('a(?=s|z)', 'ɑ', word, debug)
vowels.append('ɑ')
# Loss of /θ/ and /ð/. When it results in a hiatus of /a/ with a following vowel, the /a/ becomes /ə/.
word = sub('θ|ð', '', word, debug)
word = sub(f'a(?={join(vowels)})', 'ə', word, debug)
consonants = [i for i in consonants if i not in ('θ', 'ð')]
# /kʷ/ > /k/ and /gʷ/ > /g/.
word = sub('kʷ', 'k', word, debug)
word = sub('gʷ', 'g', word, debug)
consonants = [i for i in consonants if i not in ('kʷ', 'gʷ')]
# /u/ > /y/.
word = sub('u', 'y', word, debug)
vowels.append('y')
# Merge of /e~/ and /ɛ~/ to /a~/, but not in /jɛ~/ or /ej~/.
word = sub('(?<!j)/(?:e|ɛ)(?=~)', '/a', word, debug)
word = sub('(?<!j|/)(?:e|ɛ)(?=~)', 'a', word, debug)
# Nasalization of high vowels before all nasals.
word = sub('((?:i|u|y)(?:w|j)?)(?=m|n|ɲ)', '\\1~', word, debug)
# Reduction of /e/ and /ɛ/ in hiatus to /ə/.
word = sub(f'(?:e|ɛ)(?=/{join(vowels)}|(?:w|j)/{join(vowels)})', 'ə', word, debug)
# Final /rn/, /rm/ > /r/.
# TODO: What about /rɲ/?
word = sub('r(?:n|m)$', 'r', word, debug)
return word
def to_late_old_french(word: str, debug: bool = False) -> str:
'''
Simulates the sounds changes that occurred between Latin and Late Old French and returns the result.
Parameters
----------
word : str
The word to apply the sound changes to.
debug : bool
If True, debug information will be output.
Returns
-------
str
The evolved word.
'''
global consonants, vowels
# /o/ > /u/.
word = sub('o(?!j)', 'u', word, debug)
# /ɔ/ > /o/ before /s/ or /z/.
word = sub('ɔ(?=s|z)', 'o', word, debug)
# /wɛ/, /ew/ > /œ/, but /ø/ before /s/, /z/, or /t/ and /jœ/ before /ɫ/ when not after a labial or velar.
word = sub('w(/?)ɛ|ew', '\\1œ', word, debug)
word = sub('(?<!m|p|b|v|f|k|g)/œ(?=ɫ)', 'j/œ', word, debug)
word = sub('(?<!m|p|b|v|f|k|g|/)œ(?=ɫ)', 'jœ', word, debug)
word = sub('œ(?=s|z|t)', 'ø', word, debug)
vowels.extend(['ø', 'œ'])
# Stress shift to second element of diphthongs.
# TODO: I'll probably add more as I encounter them.
word = sub('(/?)yj', 'ɥ\\1i', word, debug)
word = sub(f'y(?=/?{join(vowels)})', 'ɥ', word, debug)
consonants.append('ɥ')
# /oj/, /ɔj/ > /wɛ/.
word = sub('(/?)(?:o|ɔ)j', 'w\\1ɛ', word, debug)
# /aj/ > /ɛ/.
# TODO: I'm marking /ɛ/ which evolve from /aj/ with "E", as it apparently evolves differently from other /ɛ/s.
word = sub('aj', 'E', word, debug)
vowels.append('E')
# Closed /e/ > /ɛ/.
word = sub(f'e(?={join(consonants, "j", "ɫ")}{{2,}}|{join(consonants, "j", "ɫ")}$)', 'ɛ', word, debug)
# Deaffrication.
word = sub('ʦ', 's', word, debug)
word = sub('ʧ', 'ʃ', word, debug)
word = sub('ʤ', 'ʒ', word, debug)
consonants = [i for i in consonants if i not in ('ʦ', 'ʧ', 'ʤ')]
consonants.extend(['ʃ', 'ʒ'])
# /ɫ/ > /w/.
word = sub(f'ɫ', 'w', word, debug)
# Loss of /s/ before consonants with lengthening of preceeding vowel.
word = sub(f's(?={join(consonants, "j", "w", "ɥ")})', ':', word, debug)
return word
def to_middle_french(word: str, debug: bool = False) -> str:
'''
Simulates the sounds changes that occurred between Latin and Middle French and returns the result.
Parameters
----------
word : str
The word to apply the sound changes to.
debug : bool
If True, debug information will be output.
Returns
-------
str
The evolved word.
'''
global consonants, vowels
# /aw/ > /o/ (from previous /aɫ/).
# TODO: I'm going to assume the other vowel + /w/ (from vowel + /ɫ/) combinations take affect here as well.
word = sub('aw', 'o', word, debug)
word = sub('(?<!j)/ɛw', '/o', word, debug)
word = sub('(?<!j|/)ɛw', 'o', word, debug)
word = sub('(?:ɛ|e|œ)w', 'œ', word, debug)
word = sub('œ(?=s|z|t)', 'ø', word, debug)
word = sub('uw', 'u', word, debug)
# /ej/ > /ɛ/.
word = sub('ej', 'ɛ', word, debug)
# Nasal /u~/ > /ɔ~/.
word = sub('u~', 'ɔ~', word, debug)
# Denasalization of open vowels.
word = sub(f'~(?=(?:n|m|ɲ)(?:/?{join(vowels)}|j|w))', '', word, debug)
# Loss of nasals after nasal vowels.
word = sub('(?<=~)(?:n|m|ɲ)', '', word, debug)
return word
def to_early_modern_french(word: str, debug: bool = False) -> str:
'''
Simulates the sounds changes that occurred between Latin and Early Modern French and returns the result.
Parameters
----------
word : str
The word to apply the sound changes to.
debug : bool
If True, debug information will be output.
Returns
-------
str
The evolved word.
'''
global consonants, vowels
# Loss of long vowels.
word = sub(':', '', word, debug)
# Loss of final consonants. This actually started in Middle French, but it was based on external sandhi.
# TODO: Wikipedia isn't very specific regarding which consonants are lost. Based on examples, it looks like /r/, /l/, /f/ and /k/ remain. Beyond that, I need to refer to other sources. For now, I'm going to just assume all other consonants except those that form diphthongs. Addtionally, based on examples, /l/ does appear to be lost after high vowels, however, I've seen one example, /nu:llum/ > /nyl/, which suggests it's not always true. One source suggested that examples like this are the exception, based on influence from Latin.
word = sub(f'{join(consonants, "f", "k", "r", "l", "j", "w", "ɥ")}+$', '', word, debug)
word = sub('(?<=i|u|y)l$', '', word, debug)
# /wɛ/ > /wa/ or sometimes /ɛ/.
# TODO: Wikipedia doesn't indicate when it becomes /ɛ/. I need to check other sources. Based on examples, it also appears to be blocked by nasalization.
word = sub('w(/?)ɛ(?!~)', 'w\\1a', word, debug)
# /ɔw/ > /u/.
word = sub('ɔw', 'u', word, debug)
# Loss of /h/. It reemerged in borrowings from Germanic languages.
word = sub('h', '', word, debug)
consonants.remove('h')
return word
def to_modern_french(word: str, debug: bool = False) -> str:
'''
Simulates the sounds changes that occurred between Latin and Modern French and returns the result.
Parameters
----------
word : str
The word to apply the sound changes to.
debug : bool
If True, debug information will be output.
Returns
-------
str
The evolved word.
'''
global consonants, vowels
# /r/ > /ʁ/.
word = sub('r', 'ʁ', word, debug)
consonants.remove('r')
consonants.append('ʁ')
# /ʎ/ merges with /j/.
word = sub('ʎ', 'j', word, debug)
# Loss of /ə/ unless it results in an invalid consonant cluster.
# TODO: Handling all possible resulting consonant clusters sounds like a huge pain, so for now I'm going to just remove all of them and then chalk it up to "use your best judgement".
word = sub('ə', '', word, debug)
# Lowering of nasal /i~/, /e~/ to /ɛ~/. In the 20th century, this has started to happen with /y~/, which originally shifted to /œ~/. As such, I've implemented this change as well.
word = sub('(?:i|e|y)(?=~)', 'ɛ', word, debug)
# Merge of /ɑ/ with /a/.
word = sub('ɑ', 'a', word, debug)
# Nasal /a~/ shifts to /ɑ~/.
word = sub('a~', 'ɑ~', word, debug)
# Final /ɔ/ > /o/, /ɛ/ > /e/, /œ/ > /ø/.
word = sub('ɔ$', 'o', word, debug)
word = sub('ɛ$', 'e', word, debug)
word = sub('œ$', 'ø', word, debug)
word = sub('E', 'ɛ', word, debug)
vowels.remove('E')
return word
def evolve(word: str, debug: bool = False) -> str:
'''
Simulates the sounds changes that occurred between Latin and French and returns the result.
To ensure the word is converted as expected, use the following conventions. In general, the word should be written phonetically, rather than as it's spelled in Latin.
- Stress falls on the penultimate syllable unless short, in which case it falls on the antepenultimate if possible.
- Note that plosive + liquid clusters are considered short when determining the position of stress.
- Mark stress with a '/' before the stressed vowel, like so: 'mediet/a:tem'.
- Mark long vowels with a ':' after the vowel, like so: 'mediet/a:tem'.
- Replace 'y' with 'i', 'ae' with 'aj', 'oe' with 'oj'.
- Replace 'i' in hiatus with 'j' and 'u' in hiatus with 'w'.
- Replace 'c' with 'k', 'qu' with 'kw', and 'x' with 'ks'.
Parameters
----------
word : str
The word to apply the sound changes to.
debug : bool
If True, debug information will be output.
Returns
-------
str
The evolved word.
'''
reset()
word = to_proto_western_romance(word, debug)
word = to_proto_gallo_ibero_romance(word, debug)
word = to_early_old_french(word, debug)
word = to_old_french(word, debug)
word = to_late_old_french(word, debug)
word = to_middle_french(word, debug)
word = to_early_modern_french(word, debug)
word = to_modern_french(word, debug)
return word
|
Java
|
UTF-8
| 5,654 | 3.28125 | 3 |
[] |
no_license
|
package org.aschyiel.KnightTour;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class KnightsTour
{
protected ChessBoard board;
/**
* Usually, chess-boards are gonna be 8x8 = 64 squares.
*/
public final static int DEFAULT_DIMENSIONS = 8;
/**
* Flag to enable annoying debugging messages.
*/
public static final boolean DEBUG = false;
public KnightsTour()
{
this( DEFAULT_DIMENSIONS, DEFAULT_DIMENSIONS );
}
public KnightsTour( int m, int n )
{
attempted = new HashMap<Integer, Map<String, Map<String, Boolean>>>();
board = new ChessBoard( m, n );
}
/**
* Depth, by parent square, to attempted child square.
*/
protected Map<Integer, Map<String, Map<String, Boolean>>> attempted;
/**
* Attempt to tour from the origin to the destination within a section.
*
* If the origin and destination squares are different,
* it is considered an "open" tour, otherwise it's "closed".
*/
public Solution solveSection( Square origin,
Square destination,
ChessBoardSection section )
{
int m = section.getRowCount();
int n = section.getColumnCount();
Solution soln = new Solution( m, n );
int maxSteps = soln.getMaxMoves();
Square current = origin;
current.markAsOrigin();
while ( true )
{
int step = soln.getStep();
Move prev = null;
Square[] unvisited = current.getUnvisitedNeighbors();
boolean exhausted = hasExhausted( step, current, unvisited );
if ( exhausted && current == origin )
{
System.out.println( "WARNING:Failed to find a solution from "+ origin + " to " + destination );
return null;
}
Square next = ( exhausted )? null : getRandomUnvisitedNeighbor( step, current, unvisited );
boolean isLastMove = step + 2 == maxSteps;
if ( null != next )
{
if ( !isLastMove && next == destination )
{
tag( step, current, next );
continue;
}
if ( next.isDeadEnd() )
{
tag( step, current, next );
continue;
}
}
if ( exhausted )
{
// We ran out of stuff to try at this level.
debug( "Exausted:"+ current.toString() );
unexhaustSubSteps( step, maxSteps );
prev = soln.undo();
}
else if ( null != next && !hasTried( step, current, next ) )
{
soln.move( current, next );
if ( isLastMove && next.neighborsWith( destination ) )
{
soln.move( next, destination );
break; // We found a solution.
}
if ( next.hasOrphanedNeighbors() )
{
prev = soln.undo();
}
else
{
current = next;
}
}
if ( !isLastMove && destination.isDeadEnd() )
{
debug( "Accidentally blocked off destination." );
prev = soln.undo();
}
if ( null != prev )
{
tag( prev.getStep(), prev.getFrom(), prev.getTo() );
current = prev.getFrom();
}
}
return soln;
}
/**
* Returns true if we've tried everything from the given square already.
*/
private boolean hasExhausted( int depth, Square sq, Square[] unvisited )
{
for ( int i = 0; i < unvisited.length; i++ )
{
if ( !hasTried( depth, sq, unvisited[i] ) )
{
return false;
}
}
return true;
}
/**
* Un-tag/free-up attempts; preferably while you're moving "up" in the DFS;
* this applies to sections that we're not gonna retry again
* because we've exhausted them at a higher-level.
*/
private void unexhaustSubSteps( int depth, int max )
{
for ( ; depth < max + 1; depth++ )
{
attempted.put( depth, null );
}
}
/**
* Returns a random unvisited neighbor.
*/
private Square getRandomUnvisitedNeighbor( int depth, Square src, Square[] unvisited )
{
if ( unvisited.length < 1 )
{
return null;
}
Square them = unvisited[ random( unvisited.length ) ];
while ( hasTried( depth, src, them ) )
{
them = unvisited[ random( unvisited.length ) ];
}
return them;
}
/**
* Keep track of bad inter-square attempts during DFS.
*/
private void tag( int depth, Square a, Square b )
{
String k1 = a.toString();
String k2 = b.toString();
if ( null == attempted.get( depth ) )
{
attempted.put( depth, new HashMap<String, Map<String, Boolean>>() );
}
if ( null == attempted.get( depth ).get( k1 ) )
{
attempted.get( depth ).put( k1, new HashMap<String, Boolean>() );
}
attempted.get( depth ).get( k1 ).put( k2, true );
}
/**
* Returns true if we're already attempted something previously.
*/
private boolean hasTried( int depth, Square a, Square b )
{
Map<String, Map<String, Boolean>> xi = attempted.get( depth );
String k1 = a.toString();
String k2 = b.toString();
if ( null == xi )
{
return false;
}
Map<String, Boolean> zi = xi.get( k1 );
Boolean yesh = ( null == zi || !zi.containsKey( k2 ) )?
false : zi.get( k2 );
return ( null == yesh )?
false : yesh;
}
private Random r = new Random();
/**
* Return a random (zero-based) index from the available choices.
*/
protected int random( int n )
{
return r.nextInt( n );
}
public static void debug( String msg )
{
if ( DEBUG )
{
System.out.println( msg );
}
}
}
|
Python
|
UTF-8
| 13,831 | 2.65625 | 3 |
[] |
no_license
|
import os
import csv
import decimal # for putting in right formats.
from flask import Flask, flash, jsonify, redirect, render_template, request, session
from sqlalchemy import distinct, func, and_
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
from helpers import apology, login_required, lookup, usd
from tech_terms_detection import extract_terms_with_RoBERTa, extract_terms_with_Ensemble_models
from datetime import datetime # for getting current time.
from models import * # tables defined for DB
# Make sure Databse URL key is set
if not os.environ.get("DATABASE_URL"):
raise RuntimeError("DATABASE_URL not found on config file")
# Configure application
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
db.init_app(app) # sqlalchemy db init.
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
# Custom filter
app.jinja_env.filters["usd"] = usd
# Configure session to use filesystem (instead of signed cookies)
# app.config["SESSION_FILE_DIR"] = mkdtemp()
# app.config['SECRET_KEY'] = 'e5ac358c-f0bf-11e5-9e39-d3b532c10a28'
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# Make sure API key is set
if not os.environ.get("API_KEY"):
raise RuntimeError("API_KEY not found on config file")
@app.route("/")
@login_required
def index():
"""Show portfolio of stocks
Notes:
IN Group By below, technically, grouping by symbol is equivalent
to grouping by symbol, name, price_per_share collectively. PSQL (not mySQL)
forces you to put all three in group by clause or in an aggregate function (SUM etc).
PSQL doesn't know that exactly one name is associated with one symbol, for example.
"""
# Select by default will return list of dicts. Each dict is a transaction to be displayed.
this_user_id = session['user_id']
transactions = Transaction.query.with_entities(
Transaction.stock_symbol,
Transaction.stock_name,
func.sum(Transaction.n_shares).label('total_shares_for_this_symbol'),
Transaction.price_per_share
).filter_by(id=this_user_id).group_by(Transaction.stock_symbol,
Transaction.stock_name, Transaction.price_per_share).all()
_all_stocks_worth = sum(map(lambda transaction: transaction.total_shares_for_this_symbol \
* transaction.price_per_share, transactions))
return render_template("index.html", transactions=transactions, all_stocks_worth=_all_stocks_worth)
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock"""
if request.method == "POST":
# get current time
now = datetime.now()
# verify a symbol is passed
this_stock_symbol = request.form.get("symbol")
if not this_stock_symbol:
return apology("Must provide symbol", 403)
# verify the number of shares is passed and valid.
_n_shares = int(request.form.get("shares"))
if not _n_shares:
return apology("Must provide shares", 403)
if _n_shares < 1:
return apology("Number of shares must be a positive integer", 403)
this_stock_quote = lookup(this_stock_symbol) # a dict with keys [name, price, symbol]
if this_stock_quote:
this_stock_name = this_stock_quote['name']
this_stock_price_per_share = this_stock_quote['price']
else:
return apology("Symbol Error", 403)
total_price_for_n_shares_for_this_stock = _n_shares \
* this_stock_price_per_share # no need to store this in database.
this_user_id = session["user_id"] # this is a primary key in this table and 'foreign key'
this_user = User.query.filter_by(id=this_user_id).one_or_none()
cash_this_user_currently_has = this_user.cash
if not cash_this_user_currently_has:
raise Exception("Finding cash_this_user_currently_has is problematic")
# Not enough cash left for this user to make this transaction.
if total_price_for_n_shares_for_this_stock > cash_this_user_currently_has:
return apology("You do not have sufficient balance to complete this transaction!", 403)
# deduct transaction money from the users account.
total_price_for_n_shares_for_this_stock = decimal.Decimal(
total_price_for_n_shares_for_this_stock) # decimal format
cash_left_after_transaction = cash_this_user_currently_has \
- total_price_for_n_shares_for_this_stock
# Update cash in DB
this_user.cash = cash_left_after_transaction
db.session.add(this_user)
# Get current time in string- right format.
time_now = now.strftime("%d/%m/%Y %H:%M:%S") # dd/mm/YY H:M:S
_transaction_time = time_now
# Save this transaction information into databse. Each transaction is unique based on timestamps.
new_transaction = Transaction(
id=this_user_id,
stock_symbol=this_stock_symbol,
stock_name=this_stock_name,
n_shares=_n_shares,
price_per_share=this_stock_price_per_share,
transaction_time=_transaction_time
)
db.session.add(new_transaction)
db.session.commit() # commit all changes (adds) at once.
# redirect the user to home page.
return redirect("/")
else:
return render_template("buy.html")
@app.route("/history")
@login_required
def history():
"""Show history of transactions"""
this_user_id = session['user_id']
_history = Transaction.query.with_entities(
Transaction.stock_symbol,
Transaction.n_shares,
Transaction.price_per_share,
Transaction.transaction_time,
).filter_by(id=this_user_id).all()
return render_template("history.html", history=_history)
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username", 403)
# Ensure password was submitted
if not request.form.get("password"):
return apology("must provide password", 403)
# Query database for username
this_user_data = User.query.filter_by(username=request.form.get("username")).one_or_none()
# Ensure username exists and password is correct
if not this_user_data or not check_password_hash(this_user_data.hash, request.form.get("password")):
return apology("invalid username and/or password", 403)
# Remember which user has logged in
session["user_id"] = this_user_data.id
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("login.html")
@app.route("/logout")
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to login form
return redirect("/")
@app.route("/quote", methods=["GET", "POST"])
@login_required
def quote():
"""Get stock quote."""
if request.method == "POST":
_passage = request.form.get('passage')
if not _passage:
return apology("Must provide passage", 403)
else:
extracted_terms = extract_terms_with_RoBERTa(_passage)
return render_template("quoted.html", extracted_terms=extracted_terms)
else:
return render_template("quote.html")
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
_username = request.form.get("username")
if not _username:
return apology("Must provide username", 403)
# Ensure password was submitted
_password = request.form.get("password")
if not _password:
return apology("Must provide password", 403)
_password_confirmation = request.form.get("confirmation")
if not _password_confirmation:
return apology("Must provide confirmation password", 403)
if _password != _password_confirmation:
return apology("Passwords do not match", 403)
# Check if username already exists. Query database for username
username_exits = User.query.filter_by(username=request.form.get("username")).one_or_none()
if username_exits:
return apology("Username already exists", 403)
# OK. Store this new user into database.
else:
# generate hash of the password
password_hash = generate_password_hash(_password)
# insert username and hash of this user into database.
new_user = User(username=_username, hash=password_hash)
db.session.add(new_user)
db.session.commit()
# keep the user logged in when registered.
session["user_id"] = new_user.id
# Redirect user to home page
return redirect("/")
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("register.html")
@app.route("/sell", methods=["GET", "POST"])
@login_required
def sell():
"""Sell shares of stock"""
this_user_id = session['user_id']
_tentative_symbols_unclean = Transaction.query.with_entities(distinct(Transaction.stock_symbol))\
.filter_by(id=this_user_id).all()
_tentative_symbols = list(map(lambda elm: elm[0], _tentative_symbols_unclean)) # remove commas etc
# "For display", keep only those stock symbols for which the user has positive number (>0) of shares.
_available_symbols = []
for idx, symb in enumerate(_tentative_symbols):
net_shares_for_this_stock = Transaction.query.with_entities(
func.sum(Transaction.n_shares)
).filter_by(stock_symbol=symb).scalar()
if net_shares_for_this_stock > 0:
this_symbol = _tentative_symbols[idx]
_available_symbols.append(this_symbol)
if request.method == "POST":
# Get current time.
now = datetime.now()
this_stock_symbol = request.form.get('symbol')
if not this_stock_symbol:
return apology("Must provide Symbol", 403)
n_shares_to_be_sold = int(request.form.get("shares"))
if not n_shares_to_be_sold:
return apology("Must provide Shares", 403)
if n_shares_to_be_sold < 1:
return apology("Shares must be a postive integer.", 403)
# Get number of shares of this stock symbol, this user has bought so far.
n_shares_bought = Transaction.query.with_entities(func.sum(Transaction.n_shares)).filter(
and_(
Transaction.id == this_user_id), (Transaction.stock_symbol == this_stock_symbol)
).scalar()
n_shares_will_be_left_on_selling = n_shares_bought - n_shares_to_be_sold
if n_shares_will_be_left_on_selling < 0:
return apology("You don't have enough shares to sell.", 403)
this_stock_quote = lookup(this_stock_symbol) # a dict with keys [name, price, symbol]
this_stock_name = this_stock_quote['name']
this_stock_price_per_share = this_stock_quote['price']
# money earned by selling those shares at current price.
money_earned = n_shares_to_be_sold * this_stock_price_per_share
# This user object- as per DB.
this_user = User.query.filter_by(id=this_user_id).one_or_none()
cash_already_in_account = this_user.cash
money_earned = decimal.Decimal(money_earned) # put in right format for addition next.
new_cash_after_selling_shares = cash_already_in_account + money_earned
this_user.cash = new_cash_after_selling_shares # update cash of the user
db.session.add(this_user) # Add now. Commit all changes once later.
# Get current time in string- right format.
time_now = now.strftime("%d/%m/%Y %H:%M:%S") # dd/mm/YY H:M:S
_transaction_time = time_now
# Save this new transaction in DB.
with_neg_sign_n_shares_to_be_sold = -n_shares_to_be_sold
new_transaction = Transaction(
id=this_user_id,
stock_symbol=this_stock_symbol,
stock_name=this_stock_name,
n_shares=with_neg_sign_n_shares_to_be_sold,
price_per_share=this_stock_price_per_share,
transaction_time=_transaction_time
)
db.session.add(new_transaction)
db.session.commit()
return redirect("/")
else:
return render_template("sell.html", symbols=_available_symbols)
def errorhandler(e):
"""Handle error"""
if not isinstance(e, HTTPException):
e = InternalServerError()
return apology(e.name, e.code)
# Listen for errors
for code in default_exceptions:
app.errorhandler(code)(errorhandler)
|
Markdown
|
UTF-8
| 2,313 | 3.421875 | 3 |
[
"MIT"
] |
permissive
|
---
content_title: eosio-blocklog
link_text: eosio-blocklog
---
`eosio-blocklog` is a command-line interface (CLI) utility that allows node operators to perform low-level tasks on the block logs created by a `nodeos` instance. `eosio-blocklog` can perform one of the following operations:
* Convert a range of blocks to JSON format, as single objects or array.
* Generate `blocks.index` from `blocks.log` in blocks directory.
* Trim `blocks.log` and `blocks.index` between a range of blocks.
* Perform consistency test between `blocks.log` and `blocks.index`.
* Output the results of the operation to a file or `stdout` (default).
## Usage
```sh
eosio-blocklog <options> ...
```
## Options
Option (=default) | Description
-|-
`--blocks-dir arg (="blocks")` | The location of the blocks directory (absolute path or relative to the current directory)
`-o [ --output-file ] arg` | The file to write the generated output to (absolute or relative path). If not specified then output is to `stdout`
`-f [ --first ] arg (=0)` | The first block number to log or the first block to keep if `trim-blocklog` specified
`-l [ --last ] arg (=4294967295)` | the last block number to log or the last block to keep if `trim-blocklog` specified
`--no-pretty-print` | Do not pretty print the output. Useful if piping to `jq` to improve performance
`--as-json-array` | Print out JSON blocks wrapped in JSON array (otherwise the output is free-standing JSON objects)
`--make-index` | Create `blocks.index` from `blocks.log`. Must give `blocks-dir` location. Give `output-file` relative to current directory or absolute path (default is `<blocks-dir>/blocks.index`)
`--trim-blocklog` | Trim `blocks.log` and `blocks.index`. Must give `blocks-dir` and `first` and/or `last` options.
`--smoke-test` | Quick test that `blocks.log` and `blocks.index` are well formed and agree with each other
`-h [ --help ]` | Print this help message and exit
## Remarks
When `eosio-blocklog` is launched, the utility attempts to perform the specified operation, then yields the following possible outcomes:
* If successful, the selected operation is performed and the utility terminates with a zero error code (no error).
* If unsuccessful, the utility outputs an error to `stderr` and terminates with a non-zero error code (indicating an error).
|
C++
|
UTF-8
| 1,989 | 2.875 | 3 |
[] |
no_license
|
#include "Node.h"
SmallTree::SmallTree(){
treeSizeX = 3;
treeSizeY = 4;
tree = new MapTile**[treeSizeX];
for (int i = 0; i < treeSizeX; i++){
tree[i] = new MapTile*[treeSizeY];
for (int j = 0; j < treeSizeY; j++){
if (j < 2){
tree[i][j] = new MapTile(new Symbol('*', 10, 0));
}
else if (i == 1){
tree[i][j] = new MapTile(new Symbol('|', 4, 0));
}
else{
tree[i][j] = new MapTile(new Symbol('`', 2, 0));
}
}
}
}
MedTree::MedTree(){
treeSizeX = 4;
treeSizeY = 6;
tree = new MapTile**[treeSizeX];
for (int i = 0; i < treeSizeX; i++){
tree[i] = new MapTile*[treeSizeY];
for (int j = 0; j < treeSizeY; j++){
if (j < 3){
tree[i][j] = new MapTile(new Symbol('*', 10, 0));
}
else if (i == 1 || i == 2){
tree[i][j] = new MapTile(new Symbol('|', 4, 0));
}
else{
tree[i][j] = new MapTile(new Symbol('`', 2, 0));
}
}
}
}
LargeTree::LargeTree(){
treeSizeX = 6;
treeSizeY = 8;
tree = new MapTile**[treeSizeX];
for (int i = 0; i < treeSizeX; i++){
tree[i] = new MapTile*[treeSizeY];
for (int j = 0; j < treeSizeY; j++){
if (j < 3){
tree[i][j] = new MapTile(new Symbol('*', 10, 0));
}
else if (i >= 1 && i <= 4){
tree[i][j] = new MapTile(new Symbol('|', 4, 0));
}
else{
tree[i][j] = new MapTile(new Symbol('`', 2, 0));
}
}
}
}
SmallRock::SmallRock(){
rockSize = 1;
rock = new MapTile**[rockSize];
rock[0] = new MapTile*[rockSize];
rock[0][0] = new MapTile(new Symbol('x', 8, 0));
}
MedRock::MedRock(){
rockSize = 2;
rock = new MapTile**[rockSize];
for (int i = 0; i < rockSize; i++){
rock[i] = new MapTile*[rockSize];
for (int j = 0; j < rockSize; j++){
rock[i][j] = new MapTile(new Symbol('x', 8, 0));
}
}
}
LargeRock::LargeRock(){
rockSize = 3;
rock = new MapTile**[rockSize];
for (int i = 0; i < rockSize; i++){
rock[i] = new MapTile*[rockSize];
for (int j = 0; j < rockSize; j++){
rock[i][j] = new MapTile(new Symbol('x', 8, 0));
}
}
}
|
Python
|
UTF-8
| 38 | 3.1875 | 3 |
[] |
no_license
|
a = [1, 2, 3]
print(a[0])
print(a[-2])
|
Python
|
UTF-8
| 1,193 | 3.15625 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
#Dataset upload
data_karolina = pd.read_csv("corona.csv", encoding="utf-8",error_bad_lines=False, names=["count", "Date", "location", "Tweet"])
data_karolina = data_karolina.drop(columns=['count'], axis=1)
data_karolina
#data_karolina.to_csv("final.csv", sep=";", na_rep="", index=False, encoding="utf-8-sig")
# In[2]:
# Load the regular expression library
import re
# Remove punctuation
data_karolina['Tweet'] = data_karolina['Tweet'].map(lambda x: re.sub('[,\.!?@]', '', x))
# Convert the titles to lowercase
data_karolina['Tweet'] = data_karolina['Tweet'].map(lambda x: x.lower())
# Print out the first rows
data_karolina['Tweet'].head()
# In[4]:
# Import the wordcloud library
import matplotlib
import wordcloud
from wordcloud import WordCloud
# Join the different processed titles together.
long_string = ','.join(list(data_karolina['Tweet'].values))
# Create a WordCloud object
wordcloud = WordCloud(background_color="white", max_words=5000, contour_width=3, contour_color='steelblue')
# Generate a word cloud
wordcloud.generate(long_string)
# Visualize the word cloud
vis = wordcloud.to_image()
vis.show()
|
JavaScript
|
UTF-8
| 1,565 | 3.234375 | 3 |
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Defining text characters for the empty and full hearts for you to use later.
const EMPTY_HEART = '♡'
const FULL_HEART = '♥'
// Your JavaScript code goes here!
const hearts = document.querySelectorAll("span.like-glyph");
let modal = document.getElementById("modal");
document.addEventListener("DOMContentLoaded", event => {
hearts.forEach(like => like.addEventListener("click", likePost))
})
function likePost(event) {
let heart = event.target
mimicServerCall()
.then(function() {
heart.innerHTML = changeHeart(heart)
heart.classList.toggle("activated-heart")
})
.catch(function() {
modal.classList.remove("hidden")
setTimeout(() => modal.classList.toggle("hidden"), 5000)
})
}
function changeHeart(heart) {
if (heart.innerHTML == EMPTY_HEART){
return FULL_HEART
heart.setAttribute("class", "activated-heart")
} else {
return EMPTY_HEART
heart.removeAttribute("class")
}
}
//------------------------------------------------------------------------------
// Ignore after this point. Used only for demo purposes
//------------------------------------------------------------------------------
function mimicServerCall(url="http://mimicServer.example.com", config={}) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
let isRandomFailure = Math.random() < .2
if (isRandomFailure) {
reject("Random server error. Try again.");
} else {
resolve("Pretend remote server notified of action!");
}
}, 300);
});
}
|
Java
|
UTF-8
| 742 | 2.203125 | 2 |
[] |
no_license
|
package bonaguasato.gui;
/**
* Created by kouichisato on 1/30/17.
*/
public class UBAS {
private int id;
private String name;
private String password;
public UBAS(int i, String philip, String aDefault)
{
}
public UBAS()
{
this.id=id;
this.name=name;
this.password=password;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPassword(String address) {
this.password = password;
}
public int getId() {
return id;
}
public String getPassword() {
return password;
}
public String getName() {
return name;
}
}
|
JavaScript
|
UTF-8
| 5,184 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
//----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Run the following npm command from a console prompt in this directory
// to install the required Azure Blob Storage client libraries:
//
// npm install
//
// Update package.json to keep the required versions current.
//
// Use the following command to run this test app
//
// node SAS.js
//----------------------------------------------------------------------------------
const {
BlobServiceClient,
StorageSharedKeyCredential,
ContainerSASPermissions,
BlobSASPermissions,
generateBlobSASQueryParameters } = require('@azure/storage-blob');
const Constants = require('./constants.js');
constants = new Constants();
const accountUrl = 'https://' + constants.accountName + '.blob.core.windows.net';
// Use StorageSharedKeyCredential with storage account and account key
// StorageSharedKeyCredential is only available in Node.js runtime, not in browsers
const sharedKeyCredential = new StorageSharedKeyCredential(constants.accountName, constants.accountKey);
const blobSvcClient = new BlobServiceClient(accountUrl, sharedKeyCredential);
const containerClient = blobSvcClient.getContainerClient(constants.containerName);
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
//<Snippet_ContainerSAS>
// Create a service SAS for a blob container
function getContainerSasUri(containerClient, sharedKeyCredential, storedPolicyName) {
const sasOptions = {
containerName: containerClient.containerName,
permissions: ContainerSASPermissions.parse("c")
};
if (storedPolicyName == null) {
sasOptions.startsOn = new Date();
sasOptions.expiresOn = new Date(new Date().valueOf() + 3600 * 1000);
} else {
sasOptions.identifier = storedPolicyName;
}
const sasToken = generateBlobSASQueryParameters(sasOptions, sharedKeyCredential).toString();
console.log(`SAS token for blob container is: ${sasToken}`);
return `${containerClient.url}?${sasToken}`;
}
//</Snippet_ContainerSAS>
//<Snippet_BlobSAS>
// Create a service SAS for a blob
function getBlobSasUri(containerClient, blobName, sharedKeyCredential, storedPolicyName) {
const sasOptions = {
containerName: containerClient.containerName,
blobName: blobName
};
if (storedPolicyName == null) {
sasOptions.startsOn = new Date();
sasOptions.expiresOn = new Date(new Date().valueOf() + 3600 * 1000);
sasOptions.permissions = BlobSASPermissions.parse("r");
} else {
sasOptions.identifier = storedPolicyName;
}
const sasToken = generateBlobSASQueryParameters(sasOptions, sharedKeyCredential).toString();
console.log(`SAS token for blob is: ${sasToken}`);
return `${containerClient.getBlockBlobClient(blobName).url}?${sasToken}`;
}
//</Snippet_BlobSAS>
//-----------------------------------------------
// SAS menu
//-----------------------------------------------
function Menu() {
console.clear();
console.log('SAS scenario menu:');
console.log('1) SAS for a container');
console.log('2) SAS for a blob');
console.log('X) Exit');
readline.question('Select an option: ', (option) => {
readline.close();
switch (option) {
case "1":
containerSasUri = getContainerSasUri(containerClient, sharedKeyCredential, null);
console.log('Container SAS URI: ', containerSasUri);
return true;
case "2":
blobSasUri = getBlobSasUri(containerClient, constants.blobName, sharedKeyCredential, null);
console.log('Blob SAS URI:', blobSasUri);
return true;
case "x":
case "X":
console.log('Exit...');
return false;
default:
console.log('default...');
return true;
}
});
}
//-----------------------------------------------
// main - program entry point
//-----------------------------------------------
function main() {
try {
while (Menu()){ }
}
catch (ex) {
console.log(ex.message);
}
}
main();
|
Markdown
|
UTF-8
| 1,889 | 3.84375 | 4 |
[] |
no_license
|
[toc]
Given the root of a binary **search** tree with distinct values, modify it so that every `node` has a new value equal to the sum of the values of the original tree that are greater than or equal to `node.val`.
As a reminder, a binary search tree is a tree that satisfies these constraints:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
Constraints:
* The number of nodes in the tree is between `1` and `100`.
* Each node will have value between `0` and `100`.
* The given tree is a binary search tree.
## 题目解读
 将二叉查找树转化为最大和树。同[#538 Convert BST to Greater Tree](./#538 Convert BST to Greater Tree.md)。
```java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode bstToGst(TreeNode root) {
}
}
```
## 程序设计
* 中序遍历,先遍历右节点,再遍历左节点。
```java
class Solution {
// 记录后面的数字和
int next = 0;
public TreeNode bstToGst(TreeNode root) {
if (root == null) return null;
bstToGst(root.right);
// 将后面的数字和加入当前节点
root.val += next;
// 更新数字和
next = root.val;
bstToGst(root.left);
return root;
}
}
```
## 性能分析
 时间复杂度为$O(N)$,空间复杂度为$O(\log_2N)$,最坏为$O(N)$。
执行用时:0ms,在所有java提交中击败了100.00%的用户。
内存消耗:37.5MB,在所有java提交中击败了100.00%的用户。
## 官方解题
 暂无,密切关注。
|
C#
|
UTF-8
| 2,030 | 3.28125 | 3 |
[] |
no_license
|
using System;
using CourierApi.Models;
namespace CourierApi
{
/// <summary>
/// Class used to run pricing calculations.
/// </summary>
public class CourierPricingEngine
{
private TransportResult _transportResult;
public CourierPricingEngine()
{
_transportResult = new TransportResult();
}
/// <summary>
/// Add Parcel to be transported
/// </summary>
/// <param name="parcelToTransport"></param>
public void AddNewParcel(Parcel parcelToTransport)
{
parcelToTransport.ShippingCost = CalculateCost(parcelToTransport);
_transportResult.AddParcel(parcelToTransport);
}
/// <summary>
/// Clear the TransportResults.
/// </summary>
public void ClearResults()
{
_transportResult = new TransportResult();
}
/// <summary>
/// Retrieve the TransportResult Object.
/// </summary>
/// <returns></returns>
public TransportResult GetTransportResult()
{
return _transportResult;
}
/// <summary>
/// Print the Invoice for the TransportResult.
/// </summary>
/// <returns></returns>
public string PrintInvoice()
{
return _transportResult.ToString();
}
private decimal CalculateCost(Parcel parcelToTransport)
{
switch (parcelToTransport.GetSize())
{
case ParcelSize.Small:
return 3M;
case ParcelSize.Medium:
return 8M;
case ParcelSize.Large:
return 15M;
case ParcelSize.ExtraLarge:
return 25M;
}
throw new ArgumentOutOfRangeException(nameof(parcelToTransport), parcelToTransport.GetSize(),
"The parcel's size value was not valid.");
}
}
}
|
C#
|
UTF-8
| 1,711 | 2.890625 | 3 |
[] |
no_license
|
using System;
using System.Collections;
namespace JezicniProcesor
{
/// <summary>
/// Ova klasa obavlja leksicku analizu
/// </summary>
class LeksickiAnalizator
{
public LeksickiAnalizator()
{
}
/// <summary>
/// Obavlja leksicku analizu
/// </summary>
public void Analiziraj(string sourceProgram)
{
DKASimulator dkaSimulator = new DKASimulator();
dkaSimulator.Simuliraj(sourceProgram, _listaGresaka);
_listaUniformnihZnakova = dkaSimulator.TablicaUniformnihZnakova;
_tablicaZnakova = dkaSimulator.TablicaZnakova;
UniformniZnak uniformniZnak=new UniformniZnak(OznakeZnakovaGramatike.KrajUlaznogNiza, OznakeZnakovaGramatike.KrajUlaznogNiza,
UniformniZnakEnum.TerminatorUlaznogNiza, 0, -2);
_listaUniformnihZnakova.Add(uniformniZnak);
}
/// <summary>
/// Ova metoda se koristi za dohvat liste uniformnif znakova iz analizianog programa
/// </summary>
/// <returns>Vraca listu UniformnifZnakova</returns>
public ICollection VratiListuUniformnihZnakova()
{
return _listaUniformnihZnakova ;
}
/// <summary>
/// Ova metoda vraca listu gresaka koje su se javile tijekom leksicke analize
/// </summary>
/// <returns></returns>
public IList VratiListuGresaka()
{
return _listaGresaka;
}
/// <summary>
/// Ova metoda se koristi za dohvat tablice leksickih jedinki iz analiziranog programa
/// </summary>
/// <returns>Vraca TabicuLeksickihJedinki</returns>
public TablicaZnakova VratiTablicuZnakova()
{
return _tablicaZnakova;
}
private TablicaZnakova _tablicaZnakova = new TablicaZnakova();
private ArrayList _listaUniformnihZnakova = new ArrayList();
private ArrayList _listaGresaka = new ArrayList();
}
}
|
Go
|
UTF-8
| 7,142 | 2.828125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT",
"BSD-2-Clause"
] |
permissive
|
package controllers
import (
"cron-server/server/src/controllers"
"cron-server/server/src/transformers"
"cron-server/server/src/utils"
"cron-server/server/tests"
"cron-server/server/tests/fixtures"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestJobController_CreateOne(t *testing.T) {
pool := tests.GetTestPool()
t.Log("Respond with status 400 if request body does not contain required values")
{
jobController := controllers.JobController{ Pool: pool }
inboundJob := transformers.Job{}
inboundJob.CronSpec = "* * * * *"
jobByte, err := inboundJob.ToJson()
utils.CheckErr(err)
jobStr := string(jobByte)
req, err := http.NewRequest("POST", "/jobs", strings.NewReader(jobStr))
if err != nil {
t.Fatalf("\t\t Cannot create http request")
}
w := httptest.NewRecorder()
jobController.CreateJob(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
}
t.Log("Respond with status 201 if request body is valid")
{
project := transformers.Project{}
project.Name = "TestJobController_Project"
project.Description = "TestJobController_Project_Description"
projectManager := project.ToManager()
projectID, err := projectManager.CreateOne(pool)
if err != nil {
t.Fatalf("\t\t Cannot create project %v", err)
}
j1 := transformers.Job{}
j1.CronSpec = "1 * * * *"
j1.ProjectID = projectID
j1.CallbackUrl = "http://random.url"
j1.StartDate = time.Now().Add(60 * time.Second).UTC().Format(time.RFC3339)
jobByte, err := j1.ToJson()
utils.CheckErr(err)
jobStr := string(jobByte)
req, err := http.NewRequest("POST", "/jobs", strings.NewReader(jobStr))
if err != nil {
t.Fatalf("\t\t Cannot create job %v", err)
}
w := httptest.NewRecorder()
controller := controllers.JobController{ Pool: pool }
controller.CreateJob(w, req)
body, err := ioutil.ReadAll(w.Body)
if err != nil {
t.Fatalf("\t\t Could not read response body %v", err)
}
var response map[string]interface{}
if err = json.Unmarshal(body, &response); err != nil {
t.Fatalf("\t\t Could unmarsha json response %v", err)
}
if len(response) < 1 {
t.Fatalf("\t\t Response payload is empty")
}
fmt.Println(response)
assert.Equal(t, http.StatusCreated, w.Code)
}
}
func TestJobController_GetAll(t *testing.T) {
pool := tests.GetTestPool()
t.Log("Respond with status 200 and return all created jobs")
{
project := transformers.Project{}
project.Name = "TestJobController_GetAll"
project.Description = "TestJobController_GetAll"
projectManager:= project.ToManager()
projectID, err := projectManager.CreateOne(pool)
if err != nil {
t.Fatalf("\t\t Cannot create project using manager %v", err)
}
jobModel := transformers.Job{}
startDate := time.Now().Add(60 * time.Second).UTC().Format(time.RFC3339)
jobModel.ProjectID = projectID
jobModel.CronSpec = "1 * * * *"
jobModel.StartDate = startDate
jobModel.CallbackUrl = "some-url"
jobManager, err := jobModel.ToManager()
if err != nil {
t.Fatalf("\t\t Failed to create job manager %v", err)
}
_, err = jobManager.CreateOne(pool)
req, err := http.NewRequest("GET", "/jobs?offset=0&limit=10&projectID="+projectID, nil)
if err != nil {
t.Fatalf("\t\t Cannot create http request %v", err)
}
w := httptest.NewRecorder()
controller := controllers.JobController{ Pool: pool }
controller.ListJobs(w, req)
assert.Equal(t, http.StatusOK, w.Code)
body, err := ioutil.ReadAll(w.Body)
if err != nil {
t.Fatalf("\t\t Error reading transformers %v", err)
}
fmt.Println(string(body))
}
}
func TestJobController_UpdateOne(t *testing.T) {
pool := tests.GetTestPool()
t.Log("Respond with status 400 if update attempts to change cron spec")
{
inboundJob := transformers.Job{}
inboundJob.CronSpec = "3 * * * *"
jobByte, err := inboundJob.ToJson()
utils.CheckErr(err)
jobStr := string(jobByte)
req, err := http.NewRequest("PUT", "/jobs/"+inboundJob.ID, strings.NewReader(jobStr))
if err != nil {
t.Fatalf("\t\t Cannot create http request %v", err)
}
w := httptest.NewRecorder()
controller := controllers.JobController{ Pool: pool }
controller.UpdateJob(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
}
t.Log("Respond with status 200 if update body is valid")
{
project := fixtures.CreateProjectFixture(pool, t)
startDate := time.Now().Add(60 * time.Second).UTC().Format(time.RFC3339)
inboundJob := transformers.Job{}
inboundJob.StartDate = startDate
inboundJob.CronSpec = "1 * * * *"
inboundJob.Description = "some job description"
inboundJob.Timezone = "UTC"
inboundJob.ProjectID = project.ID
inboundJob.CallbackUrl = "some-url"
jobManager, err := inboundJob.ToManager()
jobID, err := jobManager.CreateOne(pool)
utils.CheckErr(err)
updateJob := transformers.Job{}
updateJob.ID = jobID
updateJob.Description = "some new job description"
updateJob.ProjectID = project.ID
updateJob.CronSpec = "1 * * * *"
updateJob.StartDate = time.Now().UTC().Format(time.RFC3339)
jobByte, err := updateJob.ToJson()
utils.CheckErr(err)
jobStr := string(jobByte)
req, err := http.NewRequest("PUT", "/jobs/"+jobID, strings.NewReader(jobStr))
if err != nil {
t.Fatalf("\t\t Cannot create http request %v", err)
}
w := httptest.NewRecorder()
controller := controllers.JobController{ Pool: pool }
router := mux.NewRouter()
router.HandleFunc("/jobs/{id}", controller.UpdateJob)
router.ServeHTTP(w, req)
body, err := ioutil.ReadAll(w.Body)
if err != nil {
t.Fatalf("\t\t Cannot create http request %v", err)
log.Println("Response body :", string(body))
}
assert.Equal(t, http.StatusOK, w.Code)
log.Println("Response body :", string(body))
}
}
func TestJobController_DeleteOne(t *testing.T) {
pool := tests.GetTestPool()
t.Log("Respond with status 204 after successful deletion")
{
project := fixtures.CreateProjectFixture(pool, t)
startDate := time.Now().Add(60 * time.Second).UTC().Format(time.RFC3339)
inboundJob := transformers.Job{}
inboundJob.StartDate = startDate
inboundJob.CronSpec = "1 * * * *"
inboundJob.Description = "some job description"
inboundJob.Timezone = "UTC"
inboundJob.ProjectID = project.ID
inboundJob.CallbackUrl = "some-url"
jobManager, err := inboundJob.ToManager()
if err != nil {
t.Fatalf("\t\t cannot create job manager from in-bound job %v", err)
}
jobID, err := jobManager.CreateOne(pool)
if err != nil {
t.Fatalf("\t\t cannot create job from job-manager %v", err)
}
req, err := http.NewRequest("DELETE", "/jobs/"+jobID, nil)
if err != nil {
t.Fatalf("\t\t cannot create request to delete job %v", err)
}
w := httptest.NewRecorder()
controller := controllers.JobController{ Pool: pool }
router := mux.NewRouter()
router.HandleFunc("/jobs/{id}", controller.DeleteJob)
router.ServeHTTP(w, req)
if err != nil {
t.Fatalf("\t\t Cannot create http request %v", err)
}
assert.Equal(t, http.StatusNoContent, w.Code)
}
}
|
PHP
|
UTF-8
| 255 | 3.671875 | 4 |
[] |
no_license
|
<?php
$ans = array();
$num = 100;
for ($i = 0; $i < $num; $i++) {
if ($i <= 1) {
$ans[$i] = $i;
} else {
$ans[$i] = $ans[$i - 2] + $ans[$i - 1];
}
}
echo implode(" ", $ans) . PHP_EOL;
|
Java
|
UTF-8
| 1,318 | 1.882813 | 2 |
[
"Apache-2.0"
] |
permissive
|
package bc.juhaohd.com.bean;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
/**
* Created by bocang on 18-3-20.
*/
@Entity
public class GdAttrBeanList {
@Id
private Long alid;
private String attr_value;
private int id;
private int attr_bean_index;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getAttr_value() {
return this.attr_value;
}
public void setAttr_value(String attr_value) {
this.attr_value = attr_value;
}
public Long getAlid() {
return this.alid;
}
public void setAlid(Long alid) {
this.alid = alid;
}
public int getAttr_bean_index() {
return this.attr_bean_index;
}
public void setAttr_bean_index(int attr_bean_index) {
this.attr_bean_index = attr_bean_index;
}
@Generated(hash = 1210397736)
public GdAttrBeanList(Long alid, String attr_value, int id, int attr_bean_index) {
this.alid = alid;
this.attr_value = attr_value;
this.id = id;
this.attr_bean_index = attr_bean_index;
}
@Generated(hash = 627765814)
public GdAttrBeanList() {
}
}
|
JavaScript
|
UTF-8
| 282 | 2.71875 | 3 |
[] |
no_license
|
// JavaScript Document
function showMenu()
{
"use strict";
var mainList = document.getElementById('mainList');
var elementToHide = document.getElementById('elementToHide');
mainList.classList.toggle("showListonClick");
elementToHide.classList.toggle("hideElement");
}
|
C++
|
UTF-8
| 1,002 | 2.78125 | 3 |
[] |
no_license
|
#pragma once
#include "stdafx.h"
#include "Image.h"
#include "lodepng.h"
Image::Image()
{
}
Image::Image(string filename)
{
this->filename = filename;
lodepng_decode32_file(&img, &width, &height, filename.c_str());
selected = false;
}
Image& Image::operator=(const char* name)
{
this->filename = name;
lodepng_decode32_file(&(this->img), &(this->width), &(this->height), (this->filename.c_str()));
this->selected = false;
return *this;
}
Image& Image::operator=(string& name)
{
this->filename = name;
lodepng_decode32_file(&(this->img), &(this->width), &(this->height), (this->filename.c_str()));
return *this;
}
Image& Image::operator=(Image& img)
{
this->filename = img.filename;
this->selected = img.selected;
this->height = img.height;
this->width = img.width;
this->img = img.img;
return *this;
}
bool Image::isSelected()
{
return this->selected;
}
void Image::toggleSelect()
{
this->selected = !this->selected;
}
string Image::getFilename()
{
return this->filename;
}
|
C#
|
UTF-8
| 15,335 | 2.953125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using web_team3_assignment.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Security.Cryptography;
using System.Text;
namespace web_team3_assignment.DAL
{
public class LecturerDAL
{
private IConfiguration Configuration { get; set; }
private SqlConnection conn;
//Constructor
public LecturerDAL()
{
//Locate the appsettings.json file
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
//Read ConnectionString from appsettings.json file
Configuration = builder.Build();
string strConn = Configuration.GetConnectionString(
"Student_EportfolioConnectionString");
//Instantiate a SqlConnection object with the
//Connection String read.
conn = new SqlConnection(strConn);
}
public int Add(Lecturer lecturer)
{
//sql command to add (i hope it works :pray:)
SqlCommand cmd = new SqlCommand
("INSERT INTO Lecturer (Name, EmailAddr, Password, Description)" +
" OUTPUT INSERTED.LecturerID" +
" VALUES(@name, @email, @password, @description)", conn);
cmd.Parameters.AddWithValue("@name", lecturer.Name);
cmd.Parameters.AddWithValue("@email", lecturer.Email);
cmd.Parameters.AddWithValue("@password", lecturer.Password);
if (lecturer.Description!= null)
cmd.Parameters.AddWithValue("@description", lecturer.Description);
else
cmd.Parameters.AddWithValue("@description", DBNull.Value);
//open connection to run command
conn.Open();
lecturer.LecturerId = (int)cmd.ExecuteScalar();
//close connection
conn.Close();
return lecturer.LecturerId;
}
public bool IsEmailExist(string email)
{
SqlCommand cmd = new SqlCommand
("SELECT LecturerID FROM Lecturer WHERE EmailAddr=@selectedEmail", conn);
cmd.Parameters.AddWithValue("@selectedEmail", email);
SqlDataAdapter daEmail = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
//Use DataAdapter to fetch data to a table "EmailDetails" in DataSet.
daEmail.Fill(result, "EmailDetails");
conn.Close();
if (result.Tables["EmailDetails"].Rows.Count > 0)
return true; //The email exists for another staff
else
return false; // The email address given does not exist
}
public List<Lecturer> GetAllLecturer()
{
//Instantiate a SqlCommand object, supply it with a
//SELECT SQL statement that operates against the database,
//and the connection object for connecting to the database.
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Lecturer ORDER BY LecturerID", conn);
//Instantiate a DataAdapter object and pass the
//SqlCommand object created as parameter.
SqlDataAdapter da = new SqlDataAdapter(cmd);
//Create a DataSet object to contain records get from database
DataSet result = new DataSet();
//Open a database connection
conn.Open();
//Use DataAdapter, which execute the SELECT SQL through its
//SqlCommand object to fetch data to a table "StaffDetails"
//in DataSet "result".
da.Fill(result, "LecturerDetails");
//Close the database connection
conn.Close();
//Transferring rows of data in DataSet’s table to “Staff” objects
List<Lecturer> lecturerList = new List<Lecturer>();
foreach (DataRow row in result.Tables["LecturerDetails"].Rows)
{
lecturerList.Add(
new Lecturer
{
LecturerId = Convert.ToInt32(row["LecturerID"]),
Name = row["Name"].ToString(),
Email = row["EmailAddr"].ToString(),
Password = row["Password"].ToString(),
Description = row["Description"].ToString()
}
);
}
return lecturerList;
}
public LecturerPassword getPasswordDetails(int lecturerId)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Lecturer WHERE LecturerID = @selectedLecturerID", conn);
cmd.Parameters.AddWithValue("@selectedLecturerID", lecturerId);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
da.Fill(result, "LecturerPasswordDetails");
conn.Close();
LecturerPassword lecturer = new LecturerPassword();
if (result.Tables["LecturerPasswordDetails"].Rows.Count > 0)
{
lecturer.LecturerId = lecturerId;
DataTable table = result.Tables["LecturerPasswordDetails"];
if (!DBNull.Value.Equals(table.Rows[0]["Password"]))
lecturer.Password = table.Rows[0]["Password"].ToString();
return lecturer;
}
else
{
return null;
}
}
//get the details of the lecturer and return a lecturer object
public Lecturer getLecturerDetails(int lecturerId)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Lecturer WHERE LecturerID = @selectedLecturerID", conn);
cmd.Parameters.AddWithValue("@selectedLecturerID", lecturerId);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
da.Fill(result, "LecturerDetails");
conn.Close();
Lecturer lecturer = new Lecturer();
if (result.Tables["LecturerDetails"].Rows.Count > 0)
{
lecturer.LecturerId = lecturerId;
DataTable table = result.Tables["LecturerDetails"];
if (!DBNull.Value.Equals(table.Rows[0]["Name"]))
lecturer.Name = table.Rows[0]["Name"].ToString();
if (!DBNull.Value.Equals(table.Rows[0]["EmailAddr"]))
lecturer.Email = table.Rows[0]["EmailAddr"].ToString();
if (!DBNull.Value.Equals(table.Rows[0]["Password"]))
lecturer.Password = table.Rows[0]["Password"].ToString();
if (!DBNull.Value.Equals(table.Rows[0]["Description"]))
lecturer.Description = table.Rows[0]["Description"].ToString();
return lecturer;
}
else
{
return null;
}
}
public LecturerEdit EditLecturerDetails(int lecturerId)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Lecturer WHERE LecturerID = @selectedLecturerID", conn);
cmd.Parameters.AddWithValue("@selectedLecturerID", lecturerId);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
da.Fill(result, "LecturerDetails");
conn.Close();
LecturerEdit lecturer = new LecturerEdit();
if (result.Tables["LecturerDetails"].Rows.Count > 0)
{
lecturer.LecturerId = lecturerId;
DataTable table = result.Tables["LecturerDetails"];
if (!DBNull.Value.Equals(table.Rows[0]["Name"]))
lecturer.Name = table.Rows[0]["Name"].ToString();
if (!DBNull.Value.Equals(table.Rows[0]["EmailAddr"]))
lecturer.Email = table.Rows[0]["EmailAddr"].ToString();
if (!DBNull.Value.Equals(table.Rows[0]["Password"]))
lecturer.Password = table.Rows[0]["Password"].ToString();
if (!DBNull.Value.Equals(table.Rows[0]["Description"]))
lecturer.Description = table.Rows[0]["Description"].ToString();
return lecturer;
}
else
{
return null;
}
}
//returns true if password is changed successfully without errors
public bool ChangePassword(LecturerPassword lecturer)
{
//numeric validation
//count the number of character in the password
int counter = lecturer.NewPassword.Length;
//use for loop to loop thru each character in the string, checks through the whole string for numbers
for (int i = 0; i < counter; i++)
{
//if the current iteration contains a number, execute the query which updates the password
if (Char.IsDigit(lecturer.NewPassword, i))
{
//hashed the new password
var sha1 = new SHA1CryptoServiceProvider();
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(lecturer.NewPassword));
string hashedPassword = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
SqlCommand cmd = new SqlCommand("UPDATE Lecturer SET Password=@newPassword" +
" WHERE LecturerID = @selectedLecturerID", conn);
cmd.Parameters.AddWithValue("@newPassword", hashedPassword);
cmd.Parameters.AddWithValue("@selectedLecturerID", lecturer.LecturerId);
conn.Open();
int count = cmd.ExecuteNonQuery();
conn.Close();
return true;
}
}
return false;
}
//this method checks whether there are students are under the currently logged in lecturer
public bool CheckIsUsed(int lecturerId)
{
SqlCommand cmd = new SqlCommand("Select Name FROM Student" +
" WHERE MentorID = @selectedlecturerID", conn);
cmd.Parameters.AddWithValue("@selectedlecturerID", lecturerId);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
da.Fill(result, "CheckMentorID");
conn.Close();
List<Student> studentCount = new List<Student>();
foreach (DataRow row in result.Tables["CheckMentorID"].Rows)
{
studentCount.Add(
new Student
{
Name = row["Name"].ToString(),
});
}
//if there are students under the lecturer, return true
if (studentCount.Count > 0)
{
//ViewData["StudentNames"] =
return true;
}
//if not return false
else
{
return false;
}
}
//deletes record from database
public int Delete(int lecturerId)
{
SqlCommand cmd = new SqlCommand("DELETE FROM Lecturer " +
"WHERE LecturerID = @selectLecturerID", conn);
cmd.Parameters.AddWithValue("@selectLecturerID", lecturerId);
conn.Open();
int rowCount;
rowCount = cmd.ExecuteNonQuery();
conn.Close();
return rowCount;
}
//get mentees profile in a student list
public List<Student> GetMenteeDetails(int lecturerId)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Student" +
" WHERE MentorID = @selectedMentorID" +
" ORDER BY StudentID ASC", conn);
cmd.Parameters.AddWithValue("@selectedMentorID", lecturerId);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
da.Fill(result, "AllMentees");
conn.Close();
List<Student> studentList = new List<Student>();
foreach (DataRow row in result.Tables["AllMentees"].Rows)
{
studentList.Add(
new Student
{
StudentID = Convert.ToInt32(row["StudentID"]),
Name = row["Name"].ToString(),
Course = row["Course"].ToString(),
Photo = row["Photo"].ToString(),
Description = row["Description"].ToString(),
Achievement = row["Achievement"].ToString(),
ExternalLink = row["ExternalLink"].ToString(),
EmailAddr = row["EmailAddr"].ToString(),
Password = row["Password"].ToString(),
MentorID = Convert.ToInt32(row["MentorID"])
});
}
return studentList;
}
//get a list of mentees under the lecturer in a selectListItem List
public List<SelectListItem> GetMentees(int lecturerId)
{
SqlCommand cmd = new SqlCommand("SELECT StudentID, Name FROM Student " +
"WHERE MentorID = @selectedMentorID " +
"ORDER BY Name ASC", conn);
cmd.Parameters.AddWithValue("@selectedMentorID", lecturerId);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet result = new DataSet();
conn.Open();
da.Fill(result, "MenteeDetails");
conn.Close();
List<SelectListItem> menteesList = new List<SelectListItem>();
System.Diagnostics.Debug.WriteLine(menteesList.Count);
foreach (DataRow row in result.Tables["MenteeDetails"].Rows)
{
menteesList.Add(
new SelectListItem
{
Value = row["StudentID"].ToString(),
Text = row["Name"].ToString()
});
}
return menteesList;
}
public int Update(LecturerEdit lecturer)
{
SqlCommand cmd = new SqlCommand("UPDATE Lecturer SET Name=@name, EmailAddr=@email, Description=@desc" +
" WHERE LecturerID = @selectedLecturerID", conn);
cmd.Parameters.AddWithValue("@name", lecturer.Name);
cmd.Parameters.AddWithValue("@email", lecturer.Email);
if (lecturer.Description != null)
cmd.Parameters.AddWithValue("@desc", lecturer.Description);
else
cmd.Parameters.AddWithValue("@desc", DBNull.Value);
cmd.Parameters.AddWithValue("@selectedLecturerID", lecturer.LecturerId);
conn.Open();
int count = cmd.ExecuteNonQuery();
conn.Close();
return count;
}
}
}
|
Markdown
|
UTF-8
| 2,718 | 2.671875 | 3 |
[] |
no_license
|
Formats: [HTML](/news/2010/07/23/serbia-states-its-intention-to-never-recognize-kosovo-s-independence-after-international-court-of-justice-s-yesterday-ruling.html) [JSON](/news/2010/07/23/serbia-states-its-intention-to-never-recognize-kosovo-s-independence-after-international-court-of-justice-s-yesterday-ruling.json) [XML](/news/2010/07/23/serbia-states-its-intention-to-never-recognize-kosovo-s-independence-after-international-court-of-justice-s-yesterday-ruling.xml)
### [2010-07-23](/news/2010/07/23/index.md)
##### Serbia
# Serbia states its intention to never recognize Kosovo's independence after International Court of Justice's yesterday ruling.
### Sources:
1. [BBC](http://www.bbc.co.uk/news/world-europe-10734502)
1. [Cover Image](http://www.bbc.co.uk/news/special/2015/newsspec_10857/bbc_news_logo.png?cb=1)
### Related:
1. [The International Court of Justice rules that Kosovo's unilateral declaration of independence was legal, in a move that could set a precedent for unrecognised countries.](/news/2010/07/22/the-international-court-of-justice-rules-that-kosovo-s-unilateral-declaration-of-independence-was-legal-in-a-move-that-could-set-a-preceden.md) _Context: International Court of Justice, Kosovo, yesterday ruling_
2. [ The International Court of Justice begins hearings into the legality of the Kosovan declaration of independence from Serbia. ](/news/2009/12/1/the-international-court-of-justice-begins-hearings-into-the-legality-of-the-kosovan-declaration-of-independence-from-serbia.md) _Context: International Court of Justice, Kosovo, Serbia_
3. [Serbian President Tomislav Nikolic accuses Kosovo of "seeking a war" after a train, en route to the Serb-majority city of Mitrovica in North Kosovo, and decorated in Serbian national colors and the words ""Kosovo je Srbija"" (Kosovo is Serbia), was prevented from crossing the Kosovan border. The Prime Minister of Kosovo Isa Mustafa says the train had been stopped "to protect the country's sovereignty". ](/news/2017/01/15/serbian-president-tomislav-nikolia-accuses-kosovo-of-seeking-a-war-after-a-train-en-route-to-the-serb-majority-city-of-mitrovica-in-nort.md) _Context: Kosovo, Serbia_
4. [Anti-Serbian protesters set fire to the government's headquarters in Kosovo's capital, Pristina, over an EU-brokered deal that will give Kosovo's ethnic Serb minority greater local powers. ](/news/2016/01/9/anti-serbian-protesters-set-fire-to-the-government-s-headquarters-in-kosovo-s-capital-pristina-over-an-eu-brokered-deal-that-will-give-kos.md) _Context: Kosovo, Serbia_
5. [Papua New Guinea recognizes the independence of Kosovo. ](/news/2012/10/3/papua-new-guinea-recognizes-the-independence-of-kosovo.md) _Context: Kosovo, Kosovo_
|
Python
|
UTF-8
| 908 | 3.34375 | 3 |
[] |
no_license
|
class Solution:
# O(n + logm) O(1) space where n is the input n and m is n!
def trailingZeroes(self, n: int) -> int:
# Get that actual factorial value
if n == 0 or n == 1 or n == 2:
return 0
index = 3
factorial = 2
while index <= n:
factorial = factorial * index
index += 1
# Start dividing by 10
zero_count = 0
while factorial >= 10:
if factorial % 10 != 0:
break
factorial = factorial // 10
zero_count += 1
return zero_count
# O(logn) time O(1) space where n is the input n
def trailingZeroesDivideByFive(self, n: int) -> int:
zeros = 0
while n > 0:
n //= 5
zeros += n
return zeros
|
Java
|
UTF-8
| 1,166 | 1.8125 | 2 |
[] |
no_license
|
package com.c4.intepark.faq.model.service;
import java.util.ArrayList;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.c4.intepark.faq.model.vo.Faq;
import com.c4.intepark.faq.model.service.FaqService;
import com.c4.intepark.faq.model.dao.FaqDao;
@Service("faqService")
public class FaqServiceImpl implements FaqService{
public FaqServiceImpl() {}
@Autowired
private FaqDao faqDao;
@Override
public ArrayList<Faq> selectall() {
// TODO Auto-generated method stub
return faqDao.selectAll();
}
@Override
public Faq selectOne(int faqno) {
// TODO Auto-generated method stub
return faqDao.selectOne(faqno);
}
@Override
public int faqinsert(Faq faq) {
// TODO Auto-generated method stub
return faqDao.faqinsert(faq);
}
@Override
public Faq faqUpdate(Faq faq) {
// TODO Auto-generated method stub
return faqDao.faqUpdate(faq);
}
@Override
public int faqDelete(int faqno) {
// TODO Auto-generated method stub
return faqDao.faqDelete(faqno);
}
}
|
Shell
|
UTF-8
| 1,489 | 3.09375 | 3 |
[
"GPL-2.0-or-later",
"GPL-1.0-or-later",
"GPL-2.0-only",
"GPL-3.0-only",
"FSFAP",
"GPL-3.0-or-later",
"Autoconf-exception-3.0",
"LicenseRef-scancode-other-copyleft",
"MIT",
"BSD-2-Clause"
] |
permissive
|
#! /bin/sh
# Copyright (C) 2013 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Check that we can force generated '.info' info files not to be
# distributed.
required=makeinfo
. test-init.sh
echo AC_OUTPUT >> configure.ac
cat > Makefile.am << 'END'
AUTOMAKE_OPTIONS = info-in-builddir
info_TEXINFOS = foo.texi
CLEANFILES = foo.info
# To make distcheck work without requiring TeX and texi2dvi.
dvi:
# Do not distribute generated '.info' files.
dist-info:
@:
END
mkdir subdir
cat > foo.texi << 'END'
\input texinfo
@setfilename foo.info
@settitle foo
@node Top
Hello walls.
@include version.texi
@bye
END
$ACLOCAL
$AUTOCONF
$AUTOMAKE -a -Wno-override
./configure
$MAKE distdir
ls -l . $distdir # For debugging.
test ! -e foo.info
test ! -e $distdir/foo.info
$MAKE
test -f foo.info
$MAKE distdir
ls -l $distdir # For debugging.
test ! -f $distdir/foo.info
$MAKE distcheck
:
|
Markdown
|
UTF-8
| 2,703 | 2.71875 | 3 |
[] |
no_license
|
# Resources for the Heather project.
A master thesis project by Mai Hartmann.
This repository holds the code resources for the project, and a guide of how to setup the Raspberry Pi whish runs the project, together with two Arduino's. It is not a total rundown of the project, and how it was made. :-/
## Parts used in the project:
- Raspberry Pi 4B (8GB RAM version)
- 5" HDMI display for raspberry pi
- USB-c power supply for Raspberry Pi
- micro HDMI to HDMI cable
- USB keyboard and mouse
- 2 x Arduino Uno boards
- 2 x USB cables for arduino Uno
- MPR121 touch controller (for arduino)
- Vibration motor (for Arduino)
- Over-ear headphone
- A painting by Mai Hartmann
- Conductive ink, tape, jumper cables etc.
## The setup
### Raspberry Pi
- Interfaces the two Arduinos, and outputs a soundscape based on the input from the user interactions on the touch sensors.
### Arduino MPR121 - touch sensors
- This arduino takes care of sending touch data to the Raspberry Pi.
### Arduino Vibration motor
- The Raspberry Pi sends vibration commands to this Arduino, that then makes the motor vibrate.
## Setting up the Raspberry Pi
Start with a new and updated version of the Raspberry Pi OS. Connect the screen, mouse, kayboard, headphones, and the two Arduinos to the Raspberry Pi, then boot it up.
Download the Processing files from this repository in the folder **Heather_Processing_final**, and move them to the desktop of the Raspberry Pi.
Install Processing using this command in a terminal vwindow: **curl https://processing.org/download/install-arm.sh | sudo sh**
### Make the sketch start with the OS
- Opening the autostart file with: **sudo nano /etc/xdg/lxsession/LXDE-pi/autostart**
- Add the following line to the bottom of the autostart document: **@processing-java --sketch=/home/Desktop/Heather_Processing_final --run**
- Then close and save the document: **ctrl+x** then **shift+y**
### Increase the volume
The code exploits the volume capabilities of the standard setup to its max, os in order to be able to increase the volume a bit more, do the following.
- Install the PulseAudio controls GUI with: **sudo apt-get install pavucontrol paprefs**
- Then go to: **Menu->Sound & Video -> PulseAudio Volume Control**
- Here you adjust the **Analog Output** under **Output Devices**
**NB:** We also adjusted the volume settings in the Alsamixer, but that was before trying with the PulseAudop GUI controls. In case that is necessary, type **alsamixer** in a terminal window, to open a terminal GUI for Alsa, and make sure the analog output is turned all the way up.
-----------------------------------------------------------
Now restart the Pi, and hopefully everything just works :-)
|
Markdown
|
UTF-8
| 2,163 | 3.09375 | 3 |
[] |
no_license
|
---
title: 原则已被打破
date: 2019-05-26 20:45:34
tags:
categories: 生而爲人,我很抱歉
---
我平躺着,手腳冰涼,心理極度恐懼,那十來分鐘,思緒陳雜。腦海裏浮現盤香燃燒又復原的畫面,黑與白相互蠶食。城市的燈光開始旋轉,時間一切開始在腦海中畫圈。我知道,我的世界崩塌了。如果你問我當時是什麼感受,我會如實的回答。
以前看過一張圖,應該是周星馳某部電影。

很喜歡的一段話呀,我其實並沒有想做個多特別的人,沒有想過成功、富有和地位。但還是想做一個俗人,起碼要正直。但我還是打破了我以爲的正直,我以爲我一生都不會去消費女性。一個陌生人,幫你打飛機,還讓你摸胸。或許這就是所謂成年人的世界,其實帶我去的朋友說的很對,如果我堅持的話,也不會有這些事情發生。只是我後悔罷了,覺得自己不應該這樣,打破自己的原則。
很抱歉啊,沒有成爲自己想要變成的人。人生的條款,好像也一條接着一條的被我打破。以前只是覺得人生沒有信仰罷了,而現在唯一還認爲有的原則也沒有了。我不知道以後如果去回想這段經歷,也不知道是這世界太複雜,還是自己不夠堅定。
人生好像就這般停止了,我感覺找不到追逐下去的意義。
不知道還能說點什麼,其實現在大腦裏也是一片空白,我只想趕緊忘掉這些事情。可是真的能忘掉嗎?總會有天又想惡魔一般,在心裏一刀一刀的刻着。
對不起。如果可以哭泣,那麼我想哭一次。因爲我怕極了。
我想如何能被自己寬恕,但這只是僥倖,我永遠也不會原諒這樣的自己啊。以後的人生是怎樣呢?原則全被打破,開始進入風花雪月的場所覺得正常嗎?開始覺得總有女性該被消費?我無法去阻止別人這樣,而想制止自己別這樣。我並沒有做到。
如果抱歉有用的話,也不會這樣恐懼吧。
|
JavaScript
|
UTF-8
| 709 | 3.640625 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
// add solution here
function theBeatlesPlay(musicians,instruments){
var myArray = []
var musiciansPlaysStrings
for( let i = 0 ; i < musicians.length; i++){
musiciansPlaysStrings = musicians[i] + " plays " + instruments[i]
myArray.push(musiciansPlaysStrings)
}return myArray
}
function johnLennonFacts(facts){
var myString
var emptyFacts =[]
var i =0
while (i < facts.length){
myString = facts[i] + "!!!"
emptyFacts.push(myString)
i++
}
return emptyFacts
}
function iLoveTheBeatles(number){
var myEmptyArray = [];
do {
myEmptyArray.push("I love the Beatles!")
number++
}while( number < 15);
return myEmptyArray
}
|
C#
|
UTF-8
| 1,150 | 2.953125 | 3 |
[
"Apache-2.0"
] |
permissive
|
// <copyright file="RoomOrientationExtension.cs" company="Marcel Just">
// Copyright (c) Marcel Just. FPK NT WS 2020/21, UDE.
// </copyright>
namespace FPKHotelreservierung.RoomUtil
{
/// <summary>
/// Klasse mit Methoden zur Umwandlung in und von das/dem enum RoomOrientation.
/// </summary>
public class RoomOrientationExtension
{
// Umwandlung eines RoomOrientation-Mitglieds in string.
public static string ToString(RoomOrientation roomOrientation)
{
return roomOrientation switch
{
RoomOrientation.Street => "Straße",
RoomOrientation.Valley => "Tal",
RoomOrientation.Sea => "Meer",
_ => null,
};
}
// Umwandlung eines string in RoomOrientation-Mitglied.
public static RoomOrientation ToRoomOrientation(string roomOrientationString)
{
return roomOrientationString switch
{
"Straße" => RoomOrientation.Street,
"Tal" => RoomOrientation.Valley,
_ => RoomOrientation.Sea,
};
}
}
}
|
PHP
|
UTF-8
| 3,550 | 2.75 | 3 |
[] |
no_license
|
<?php
/**
* This is the model class for table "cvgen_activerecordlog".
*
* The followings are the available columns in table 'cvgen_activerecordlog':
* @property string $log_id
* @property string $log_description
* @property string $log_action
* @property string $log_model
* @property string $log_idModel
* @property string $log_field
* @property string $log_creationdate
* @property string $log_userid
*/
class ActiveRecordLog extends CActiveRecord
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'cvgen_activerecordlog';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('log_creationdate', 'required'),
array('log_description', 'length', 'max'=>255),
array('log_action', 'length', 'max'=>20),
array('log_model, log_field, log_userid', 'length', 'max'=>45),
array('log_idModel', 'length', 'max'=>10),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('log_id, log_description, log_action, log_model, log_idModel, log_field, log_creationdate, log_userid', 'safe', 'on'=>'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'log_id' => 'Log',
'log_description' => 'Log Description',
'log_action' => 'Log Action',
'log_model' => 'Log Model',
'log_idModel' => 'Log Id Model',
'log_field' => 'Log Field',
'log_creationdate' => 'Log Creationdate',
'log_userid' => 'Log Userid',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('log_id',$this->log_id,true);
$criteria->compare('log_description',$this->log_description,true);
$criteria->compare('log_action',$this->log_action,true);
$criteria->compare('log_model',$this->log_model,true);
$criteria->compare('log_idModel',$this->log_idModel,true);
$criteria->compare('log_field',$this->log_field,true);
$criteria->compare('log_creationdate',$this->log_creationdate,true);
$criteria->compare('log_userid',$this->log_userid,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return ActiveRecordLog the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
|
Java
|
UTF-8
| 1,121 | 2.453125 | 2 |
[] |
no_license
|
package model.record;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class DimensionRecord {
@XmlElement
private String dimensionName;
private long id;
@XmlElement
private String value;
public DimensionRecord() {
}
public DimensionRecord(String dimensionName, String value) {
this.dimensionName = dimensionName;
this.value = value;
}
public DimensionRecord(long id, String value) {
super();
this.id = id;
this.value = value;
}
public String getDimensionName() {
return dimensionName;
}
public void setDimensionName(String dimensionName) {
this.dimensionName = dimensionName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
|
Swift
|
UTF-8
| 1,637 | 3.28125 | 3 |
[] |
no_license
|
//
// ColorPalette.swift
// ToDoDiary
//
// Created by Tatsuya Ishii on 2020/12/23.
//
import SwiftUI
fileprivate struct ColorTile: View {
var eventColor: EventColor
@Binding var selectedColor: EventColor
var body: some View {
Button(action: {
if selectedColor == eventColor {
selectedColor = .none
} else {
selectedColor = eventColor
}
}) {
ZStack {
// 選択されていたら枠線がつく
if eventColor == selectedColor {
Circle()
.fill(ColorManager.denseBorder)
.frame(width: 30, height: 30)
}
Circle()
.fill(eventColor.color)
.frame(width: 24, height: 24)
.shadow(color: ColorManager.shadow, radius: 5, x: 0, y: 5)
.padding(3) // 枠線の大きさと同じにすることで位置がずれないように
}
}
}
}
struct ColorPalette: View {
@Binding var selectedColor: EventColor
var body: some View {
HStack {
ForEach(EventColor.list, id: \.self) { color in
Spacer()
ColorTile(eventColor: color, selectedColor: $selectedColor)
Spacer()
}
}
.padding(.vertical, 10)
.padding(.horizontal, 40)
}
}
struct ColorPalette_Previews: PreviewProvider {
static var previews: some View {
ColorPalette(selectedColor: .constant(.none))
}
}
|
Swift
|
UTF-8
| 7,278 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
// Copyright © 2016 Alejandro Isaza.
//
// This file is part of HDF5Kit. The full HDF5Kit copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import XCTest
import HDF5Kit
class AttributeTests: XCTestCase {
func testName() {
let filePath = tempFilePath()
guard let file = File.create(filePath, mode: .truncate) else {
fatalError("Failed to create file")
}
let group = file.createGroup("group")
XCTAssertEqual(group.name, "/group")
let dataspace = Dataspace(dims: [4])
guard let attribute = group.createIntAttribute("attribute", dataspace: dataspace) else {
XCTFail()
return
}
XCTAssertEqual(attribute.name, "attribute")
}
func testWriteReadInt() {
let filePath = tempFilePath()
guard let file = File.create(filePath, mode: .truncate) else {
fatalError("Failed to create file")
}
let group = file.createGroup("group")
XCTAssertEqual(group.name, "/group")
let dataspace = Dataspace(dims: [4])
guard let attribute = group.createIntAttribute("attribute", dataspace: dataspace) else {
XCTFail()
return
}
do {
let writeData = [1, 2, 3, 4]
try attribute.write(writeData)
XCTAssertEqual(try attribute.read(), writeData)
} catch {
XCTFail()
}
}
func testWriteReadBool() {
let filePath = tempFilePath()
guard let file = File.create(filePath, mode: .truncate) else {
fatalError("Failed to create file")
}
let group = file.createGroup("group")
XCTAssertEqual(group.name, "/group")
let dataspace = Dataspace(dims: [4])
guard let attribute = group.createBoolAttribute("attribute", dataspace: dataspace) else {
XCTFail()
return
}
do {
let writeData = [true, false, true, false]
try attribute.write(writeData)
XCTAssertEqual(try attribute.read(), writeData)
} catch {
XCTFail()
}
}
func testWriteReadString() {
let filePath = tempFilePath()
guard let file = File.create(filePath, mode: .truncate) else {
fatalError("Failed to create file")
}
let group = file.createGroup("group")
XCTAssertEqual(group.name, "/group")
guard let attribute = group.createStringAttribute("attribute") else {
XCTFail()
return
}
do {
let writeData = "ABCD"
try attribute.write(writeData)
let readData = try attribute.read()
XCTAssertEqual(readData, [writeData])
} catch {
XCTFail()
}
}
func testWriteReadStringScalar() {
let filePath = tempFilePath()
guard let file = File.create(filePath, mode: .truncate) else {
fatalError("Failed to create file")
}
let group = file.createGroup("group")
XCTAssertEqual(group.name, "/group")
do {
let writeData = "Scalar text"
guard let attribute = try group.writeScalarAttribute("attribute", writeData) else {
XCTFail()
return
}
XCTAssertEqual(try attribute.read(), [writeData])
XCTAssertEqual(group.stringAttributeValue("attribute"), writeData)
} catch {
XCTFail()
}
}
func testWriteReadNumberScalar() {
let filePath = tempFilePath()
guard let file = File.create(filePath, mode: .truncate) else {
fatalError("Failed to create file")
}
let group = file.createGroup("group")
XCTAssertEqual(group.name, "/group")
do {
let writeData: Int = 345
guard let attribute = try group.writeScalarAttribute("Int", writeData) else {
XCTFail()
return
}
XCTAssertEqual(try attribute.read(), [writeData])
XCTAssertEqual(group.intAttributeValue("Int"), writeData)
} catch {
XCTFail()
}
do {
let writeData: Int32 = 678
guard let attribute = try group.writeScalarAttribute("Int32", writeData) else {
XCTFail()
return
}
let readData = try attribute.read()
XCTAssertEqual(readData.map { Int32($0) }, [writeData])
XCTAssertEqual(Int32(group.intAttributeValue("Int32")!), writeData)
} catch {
XCTFail()
}
do {
let writeData: Float = 30.5
guard let attribute = try group.writeScalarAttribute("Float", writeData) else {
XCTFail()
return
}
XCTAssertEqual(try attribute.read(), [writeData])
XCTAssertEqual(group.floatAttributeValue("Float"), writeData)
} catch {
XCTFail()
}
do {
let writeData: Double = 345467.3736
guard let attribute = try group.writeScalarAttribute("Double", writeData) else {
XCTFail()
return
}
XCTAssertEqual(try attribute.read(), [writeData])
XCTAssertEqual(group.doubleAttributeValue("Double"), writeData)
} catch {
XCTFail()
}
}
func testWriteReadBoolScalar() {
let filePath = tempFilePath()
guard let file = File.create(filePath, mode: .truncate) else {
fatalError("Failed to create file")
}
let group = file.createGroup("group")
XCTAssertEqual(group.name, "/group")
do {
let writeData: Bool = true
guard let attribute = try group.writeScalarAttribute("Bool", writeData) else {
XCTFail()
return
}
XCTAssertEqual(try attribute.read(), [writeData])
XCTAssertEqual(group.boolAttributeValue("Bool"), writeData)
} catch {
XCTFail()
}
}
func testWriteReadDelete() {
let filePath = tempFilePath()
guard let file = File.create(filePath, mode: .truncate) else {
fatalError("Failed to create file")
}
let group = file.createGroup("group")
XCTAssertEqual(group.name, "/group")
do {
let writeData: Int32 = 678
guard try group.writeScalarAttribute("Int32", writeData) != nil else {
XCTFail()
return
}
XCTAssertEqual(Int32(group.intAttributeValue("Int32")!), writeData)
let eraseData: Int32? = nil
XCTAssertNil(try group.writeScalarAttribute("Int32", eraseData))
let deletedAttribute = group.intAttributeValue("Int32")
XCTAssertNil(deletedAttribute)
} catch {
XCTFail()
}
}
}
|
Java
|
UTF-8
| 5,935 | 3.21875 | 3 |
[] |
no_license
|
package com.xls;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class GamePanel extends JPanel {
//飞机位置
int planeX ;
int planeY;
//判断飞机生死
boolean isDie = false;
//存放十个炮弹
int[] shellXs = new int[10];
int[] shellYs = new int[10];
//每一个炮弹弧度
double[] degrees = new double[10];
long startTime;
long endTime;
//游戏默认暂停状态
boolean isStart = false;
//飞机方向
boolean up,down,left,right;
//定时器
Timer timer;
//初始化炮弹
public void init(){
planeX = 250;
planeY = 450;
//炮弹坐标
for (int i = 0; i <10 ; i++) {
shellXs[i] = 100;
shellYs[i] = 100;
//每一炮弹随机弧度
degrees[i] = (int)(Math.random()*2*Math.PI);
}
}
//构造方法初始化飞机、炮弹
public GamePanel(){
init();
//游戏开始时间
startTime = System.currentTimeMillis();
//将焦点放在面板上
this.setFocusable(true);
//添加监听器
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
int keyCode = e.getKeyCode();
if(keyCode==KeyEvent.VK_SPACE){
if(isDie){
init();
isDie = false;
}else {
isStart = !isStart;
//重新绘制画板
repaint();
}
}
if(keyCode==KeyEvent.VK_UP){
up = true;
}
if(keyCode==KeyEvent.VK_DOWN){
down = true;
}
if(keyCode==KeyEvent.VK_LEFT){
left = true;
}
if(keyCode==KeyEvent.VK_RIGHT){
right= true;
}
repaint();
//System.out.println(keyCode);
}
//按键抬起
@Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
int keyCode = e.getKeyCode();
if(keyCode==KeyEvent.VK_UP){
up = false;
}
if(keyCode==KeyEvent.VK_DOWN){
down = false;
}
if(keyCode==KeyEvent.VK_LEFT){
left = false;
}
if(keyCode==KeyEvent.VK_RIGHT){
right= false;
}
repaint();
}
});
//初始化定时器
timer = new Timer(50, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//游戏开始才动
if (isStart == true&&isDie==false) {
if (left) {
planeX -= 7;
}
if (right) {
planeX += 7;
}
if (up) {
planeY -= 7;
}
if (down) {
planeY += 7;
}
//炮弹按弧度运动
for (int i = 0; i <10 ; i++) {
shellXs[i] += Math.cos(degrees[i])*7;
shellYs[i] += Math.sin(degrees[i])*7;
//炮弹到边界后从另一边回来
if(shellXs[i]<=0){
shellXs[i] = 600;
}
if(shellXs[i]>600){
shellXs[i] = 0;
}
if(shellYs[i]<=0){
shellYs[i] = 550;
}
if(shellYs[i]>550){
shellYs[i] = 0;
}
//炮弹和飞机碰撞intersects检测碰撞
boolean flag = new Rectangle(planeX,planeY,70,51).
intersects(new Rectangle(shellXs[i],shellYs[i],45,27));
//结束时间
endTime = System.currentTimeMillis();
//碰撞飞机就死
if(flag){
isDie = true;
}
}
repaint();
}
}
});
//启动定时器
timer.start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
//this.setBackground(new Color(111, 160,255));
Images.bgImg.paintIcon(this,g,0,0);
Images.planeImg.paintIcon(this,g,planeX,planeY);
//画炮弹
for (int i = 0; i <10 ; i++) {
Images.shellImg.paintIcon(this,g,shellXs[i],shellYs[i]);
}
//游戏默认关闭
if(isStart==false){
g.setColor(new Color(0x6262FC));
//样式,加粗效果,大小
g.setFont(new Font("微软雅黑",Font.BOLD,20));
//写字
g.drawString("游戏开始",250,200);
}
//游戏默认关闭
if(isDie==true){
g.setColor(new Color(0x6262FC));
//样式,加粗效果,大小
g.setFont(new Font("微软雅黑",Font.BOLD,20));
//写字
g.drawString("游戏结束",250,200);
g.drawString("历时"+(endTime-startTime)/1000+"秒",250,250);
}
}
}
|
JavaScript
|
UTF-8
| 2,273 | 3 | 3 |
[] |
no_license
|
$(document).ready(function() {
var actorList = ["Johnny Depp",
"Al Pacino",
"Robert De Niro",
"Kevin Spacey",
"Denzel Washington",
"Russell Crowe",
"Brad Pitt",
"Angelina Jolie",
"Leonardo DiCaprio",
"Tom Cruise",
"John Travolta",
"Arnold Schwarzenegger",
"Sylvester Stallone",
"Kate Winslet",
"Christian Bale",
"Morgan Freeman",
"Keanu Reeves",
"Nicolas Cage",
"Hugh Jackman",
"Edward Norton"];
function renderButtons() {
$("#buttons").empty();
for (var i=0; i < actorList.length; i++){
var a = $("<button>");
a.addClass("btn btn-info actor");
a.attr("data-name", actorList[i]);
a.text(actorList[i]);
$("#buttons").append(a);
};
};
$("#addActor").on("click", function(event) {
event.preventDefault();
var actor = $("#actorInput").val().trim();
actorList.push(actor);
renderButtons();
});
function giphyQuery(){
var actorName = $(this).attr("data-name");
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" +
actorName + "&api_key=da1c58a5cc3c4c269de67eb540ebbd7e&limit=10";
$.ajax({
url: queryURL,
method: "GET"
})
.done(function(response){
var results = response.data;
console.log(results)
for (var i = 0; i < results.length; i++){
var actorDiv = $("<div>");
var rating = $("<p>").text("Rating: " + results[i].rating);
var actorImage = $("<img>");
actorImage.attr("src", results[i].images.fixed_height_still.url);
actorImage.attr("data-still", results[i].images.fixed_height_still.url);
actorImage.attr("data-animate", results[i].images.fixed_height.url);
actorImage.attr("data-state", "still");
actorImage.attr("class", "gif");
actorDiv.append(rating);
actorDiv.append(actorImage);
$("#gifDump").prepend(actorDiv);
};
});
};
function playPause(){
var state = $(this).attr("data-state");
if (state === "still") {
$(this).attr("src", $(this).attr("data-animate"));
$(this).attr("data-state", "animate");
} else {
$(this).attr("src", $(this).attr("data-still"));
$(this).attr("data-state", "still");
}
};
$(document).on("click", ".gif", playPause);
$(document).on("click", ".actor", giphyQuery);
renderButtons();
});
|
PHP
|
UTF-8
| 3,225 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Imbehe\Services\Payments\Mfs;
use Imbehe\Services\MiddleWare;
/**
* Payment
*/
class Payment extends MiddleWare
{
protected $url = 'http://10.138.84.138:8002/osb/services/Purchase_2_0';
protected $company;
protected $sender;
protected $pin;
protected $amount;
function __construct() {
parent::__construct();
}
/**
* PAY
* @param string $sender the person who is supposed to pay with tigo cash (EXAMPLE 250722123127)
* @param string $amount amount to pay (EXAMPLE 5000)
* @param string $pin the pin for the customer (EXAMPLE 0060)
* @param string $company the company ID (EXAMPLE ELEC)
* @return bool
*/
public function pay($sender,$amount,$pin,$company)
{
$this->sender = $sender;
$this->pin = $pin;
$this->amount = $amount;
$this->company = $company;
$this->makeRequest();
$response = $this->sendRequest();
return $this->cleanResponse($response);
}
/**
* Send SMS notification
* @param string $to the MSISDN with 250 that is going to receive sms
* @param from $sender the sender of the sms
* @param string $message
* @return true
*/
public function makeRequest(){
//Store your XML Request in a variable
$this->request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v2="http://xmlns.tigo.com/MFS/PurchaseRequest/V2" xmlns:v3="http://xmlns.tigo.com/RequestHeader/V3" xmlns:v21="http://xmlns.tigo.com/ParameterType/V2" xmlns:cor="http://soa.mic.co.af/coredata_1">
<soapenv:Header xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<cor:debugFlag>true</cor:debugFlag>
<wsse:Security>
<wsse:UsernameToken>
<wsse:Username>'.$this->username.'</wsse:Username>
<wsse:Password>'.$this->password.'</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<v2:PurchaseRequest>
<v3:RequestHeader>
<v3:GeneralConsumerInformation>
<v3:consumerID>TIGO</v3:consumerID>
<!--Optional:-->
<v3:transactionID>333</v3:transactionID>
<v3:country>RWA</v3:country>
<v3:correlationID>111</v3:correlationID>
</v3:GeneralConsumerInformation>
</v3:RequestHeader>
<v2:requestBody>
<v2:sourceWallet>
<v2:msisdn>'.$this->sender.'</v2:msisdn>
</v2:sourceWallet>
<!--Optional:-->
<v2:targetWallet>
<v2:msisdn>'.$this->company.'</v2:msisdn>
</v2:targetWallet>
<v2:password>'.$this->pin.'</v2:password>
<v2:amount>'.$this->amount.'</v2:amount>
<v2:internalSystem>Yes</v2:internalSystem>
<!--Optional:-->
<!--Optional:-->
<v2:comment>ImbeheApp payment</v2:comment>
<!--Optional:-->
<v2:paymentReference></v2:paymentReference>
<!--Optional:-->
<v2:notificationNumber></v2:notificationNumber>
<!--Optional:-->
</v2:requestBody>
</v2:PurchaseRequest>
</soapenv:Body>
</soapenv:Envelope>';
}
}
|
Java
|
UTF-8
| 1,723 | 2.5 | 2 |
[] |
no_license
|
package com.sumit.assignmentfive.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.HttpClientErrorException.BadRequest;
import org.springframework.web.context.request.WebRequest;
import java.util.Date;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ArithmeticException.class)
public final ResponseEntity<Object> arithmeticException(ArithmeticException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), "Arithmetic Exception", "Exception",400);
return new ResponseEntity(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(NullPointerException.class)
public final ResponseEntity<Object> nullPointerException(NullPointerException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), "Null Pointer Exception", "Exception",404);
return new ResponseEntity(errorDetails, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> exception(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), ex.getCause().getMessage(),500);
return new ResponseEntity(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler( BadRequest.class)
public final ResponseEntity<Object> badRequestException(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), "Bad Request",400);
return new ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST);
}
}
|
C++
|
UTF-8
| 852 | 3.953125 | 4 |
[] |
no_license
|
//SourceWriter.cpp
#include <iostream>
#include <fstream>
#include <vector>
void outputVector(std::vector<char>);
int main()
{
//create the input file stream
char character;
std::ifstream input_stream;
std::vector<char> input_vector;
//open the file stream
input_stream.open("SourceWriter.cpp");
//get the first character from the stream
input_stream.get(character);
//loop through the file outputting each character
while (!input_stream.eof())
{
input_vector.push_back(character);
input_stream.get(character);
}
//close the file stream
input_stream.close();
outputVector(input_vector);
std::cout << std::endl;
return 0;
}
void outputVector(std::vector<char> vec)
{
std::vector<char>::iterator it;
for (it = vec.begin(); it != vec.end(); it++)
{
std::cout << *it;
}
}
|
Python
|
UTF-8
| 899 | 3.65625 | 4 |
[] |
no_license
|
"""
Problema:
Receber um numero como entrada
caso:
X % 3 -> Queijo
X % 5 -> Goiabada
X % 3 and X % 5 -> Romeu e Julieta
"""
from unittest import TestCase
from app import romeu_julieta
class TesteRomeuEJulieta(TestCase):
def teste_retorna_queijo_quando_input_for_mult_3(self):
valores_de_entrada = [3, 12, 18]
for valor in valores_de_entrada:
self.assertEqual(romeu_julieta(valor), "Queijo")
def teste_retorna_goiabada_quando_input_for_mult_5(self):
valores_de_entrada = [5, 20, 25, 40]
for valor in valores_de_entrada:
self.assertEqual(romeu_julieta(valor), "Goiabada")
def teste_retorna_romeu_e_julieta_quando_input_for_mult_15(self):
valores_de_entrada = [15, 30, 45, 90]
for valor in valores_de_entrada:
self.assertEqual(romeu_julieta(valor), "Romeu e Julieta")
|
Go
|
UTF-8
| 1,014 | 2.65625 | 3 |
[] |
no_license
|
package node
import (
"context"
"encoding/json"
"github/mlyahmed.io/nominee/pkg/stonither"
)
type Specifier interface {
GetDaemonName() string
GetElectionKey() string
GetName() string
GetAddress() string
GetPort() int64
GetSpec() *Spec
}
// Node ...
type Node interface {
Specifier
Lead(context.Context, Spec) error
Follow(context.Context, Spec) error
stonither.Stonither
}
// Spec ...
type Spec struct {
ElectionKey string
Name string
Address string
Port int64
}
// Marshal ...
func (n *Spec) Marshal() string {
data, _ := json.Marshal(n)
return string(data)
}
// Unmarshal ...
func Unmarshal(data []byte) (Spec, error) {
value := Spec{}
err := json.Unmarshal(data, &value)
return value, err
}
func (n *Spec) GetElectionKey() string {
return n.ElectionKey
}
func (n *Spec) GetName() string {
return n.Name
}
func (n *Spec) GetAddress() string {
return n.Address
}
func (n *Spec) GetPort() int64 {
return n.Port
}
func (n *Spec) GetSpec() *Spec {
return n
}
|
C#
|
UTF-8
| 546 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DesignPatterns.Strategy
{
public class InserirJogoPlaystation : _InserirJogo
{
public void Inserir()
{
Console.WriteLine("Pleysteixo:::: O (CD)");
}
}
public class InserirJogoSuperNintendo : _InserirJogo
{
public void Inserir()
{
Console.WriteLine("Super Ultra Mother of Games Nintendo:::: | T T | (Cartucho)");
}
}
}
|
TypeScript
|
UTF-8
| 1,781 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
import { NodeType } from '../../enums/NodeType'
import { FormNodeFieldset, FormNodeFieldsetJson } from './FormNodeFieldset'
describe('FormNodeFieldset', () => {
it('should convert to json', () => {
const formNodeFieldset = new FormNodeFieldset('id', {
legend: 'legend',
children: [new FormNodeFieldset('id2', { legend: 'legend2' })],
})
expect(formNodeFieldset.toJson()).toEqual({
id: 'id',
type: NodeType.FormNodeFieldset,
element: 'fieldset',
isVisible: true,
legend: 'legend',
children: [
{
id: 'id2',
type: NodeType.FormNodeFieldset,
element: 'fieldset',
isVisible: true,
legend: 'legend2',
children: [],
},
],
})
})
it('should convert from json', () => {
const formNode = FormNodeFieldset.fromJson({
id: 'id',
type: NodeType.FormNodeFieldset,
legend: 'legend',
children: [
{
id: 'id2',
type: NodeType.FormNodeFieldset,
legend: 'legend2',
children: [],
} as FormNodeFieldsetJson,
],
})
expect(formNode).toBeInstanceOf(FormNodeFieldset)
expect(formNode.id).toEqual('id')
expect(formNode.type).toEqual(NodeType.FormNodeFieldset)
expect(formNode.element).toEqual('fieldset')
expect(formNode.legend).toEqual('legend')
expect(formNode.children).toHaveLength(1)
const child = formNode.children[0] as FormNodeFieldset
expect(child).toBeInstanceOf(FormNodeFieldset)
expect(child.id).toEqual('id2')
expect(child.type).toEqual(NodeType.FormNodeFieldset)
expect(child.element).toEqual('fieldset')
expect(child.legend).toEqual('legend2')
expect(child.children).toHaveLength(0)
})
})
|
Python
|
UTF-8
| 622 | 3.578125 | 4 |
[] |
no_license
|
import pandas as pd
'''
d = {'x':100, 'y':200, 'z':300}
print(d.keys())
print(d.values())
print(d['x'])
s1 = pd.Series(d) #组,类似于字典
print(s1)
print(s1.index)
'''
'''
L1 = [100, 200, 300]
L2 = ['x', 'y', 'y']
s2 = pd.Series(L1, index=L2)
print(s2)
'''
s1 = pd.Series([1, 2, 3], index=[1, 2, 3], name='A')
print(s1)
s2 = pd.Series([10, 20, 30], index=[1, 2, 3], name='B')
s3 = pd.Series([100, 200, 300], index=[1, 2, 3], name='C')
df1 = pd.DataFrame({s1.name: s1, s2.name: s2, s3.name: s3})
print(df1)
df1.to_excel("c:/1.xls")
df2 = pd.DataFrame([s1, s2, s3])
print(df2)
|
C++
|
UTF-8
| 4,938 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include "namespace.h"
#include <map>
#include <memory>
#include <stdint.h>
#include <algorithm>
#include <string>
SKIWI_BEGIN
template <class TEntry>
class environment
{
public:
environment(const std::shared_ptr<environment<TEntry>>& outer) : p_outer(outer) {}
bool has(const std::string& name)
{
auto it = env.find(name);
if (it != env.end())
return true;
auto p_outer_copy = p_outer;
while (p_outer_copy)
{
it = p_outer_copy->env.find(name);
if (it != p_outer_copy->env.end())
return true;
p_outer_copy = p_outer_copy->p_outer;
}
return false;
}
bool find(TEntry& e, const std::string& name)
{
auto it = env.find(name);
if (it != env.end())
{
e = it->second;
return true;
}
auto p_outer_copy = p_outer;
while (p_outer_copy)
{
it = p_outer_copy->env.find(name);
if (it != p_outer_copy->env.end())
{
e = it->second;
return true;
}
p_outer_copy = p_outer_copy->p_outer;
}
return false;
}
template <class Pred>
bool find_if(std::pair<std::string, TEntry>& out, Pred p)
{
auto it = std::find_if(env.begin(), env.end(), p);
if (it != env.end())
{
out = *it;
return true;
}
//if (p_outer)
// {
// return p_outer->find_if(out, p);
// }
auto p_outer_copy = p_outer;
while (p_outer_copy)
{
it = std::find_if(p_outer_copy->env.begin(), p_outer_copy->env.end(), p);
if (it != p_outer_copy->env.end())
{
out = *it;
return true;
}
p_outer_copy = p_outer_copy->p_outer;
}
return false;
}
bool replace(const std::string& name, TEntry e)
{
auto it = env.find(name);
if (it != env.end())
{
it->second = e;
return true;
}
auto p_outer_copy = p_outer;
while (p_outer_copy)
{
it = p_outer_copy->env.find(name);
if (it != p_outer_copy->env.end())
{
it->second = e;
return true;
}
p_outer_copy = p_outer_copy->p_outer;
}
//if (p_outer)
// return p_outer->replace(name, e);
return false;
}
void remove(const std::string& name)
{
auto it = env.find(name);
if (it != env.end())
{
env.erase(it);
}
//if (p_outer)
// p_outer->remove(name);
auto p_outer_copy = p_outer;
while (p_outer_copy)
{
it = p_outer_copy->env.find(name);
if (it != p_outer_copy->env.end())
{
p_outer_copy->env.erase(it);
}
p_outer_copy = p_outer_copy->p_outer;
}
}
void push(const std::string& name, TEntry e)
{
env[name] = e;
}
void push_outer(const std::string& name, TEntry e)
{
/*
if (p_outer)
p_outer->push_outer(name, e);
else
env[name] = e;
*/
if (p_outer)
{
auto p_outer_copy = p_outer;
while (p_outer_copy->p_outer)
p_outer_copy = p_outer_copy->p_outer;
p_outer_copy->env[name] = e;
}
else
env[name] = e;
}
typename std::map<std::string, TEntry>::iterator begin()
{
return env.begin();
}
typename std::map<std::string, TEntry>::iterator end()
{
return env.end();
}
void rollup()
{
/*
if (p_outer)
{
p_outer->rollup();
auto it = p_outer->begin();
auto it_end = p_outer->end();
for (; it != it_end; ++it)
env.insert(*it);
p_outer.reset();
}
*/
while (p_outer)
{
auto it = p_outer->begin();
auto it_end = p_outer->end();
for (; it != it_end; ++it)
env.insert(*it);
p_outer = p_outer->p_outer;
}
}
private:
template <class T>
friend std::shared_ptr<environment<T>> make_deep_copy(const std::shared_ptr<environment<T>>& env);
std::map<std::string, TEntry> env;
std::shared_ptr<environment<TEntry>> p_outer;
};
template <class TEntry>
std::shared_ptr<environment<TEntry>> make_deep_copy(const std::shared_ptr<environment<TEntry>>& env)
{
if (!env.get())
return env;
std::shared_ptr<environment<TEntry>> out = std::make_shared<environment<TEntry>>(*env);
//if (out->p_outer)
// out->p_outer = make_deep_copy(out->p_outer);
auto* p_outer_copy = &(out->p_outer);
while (*p_outer_copy)
{ // this loop is not tested anywhere yet
*p_outer_copy = std::make_shared<environment<TEntry>>(*p_outer_copy);
p_outer_copy = &((*p_outer_copy)->p_outer);
}
return out;
}
SKIWI_END
|
C#
|
UTF-8
| 832 | 3.6875 | 4 |
[] |
no_license
|
using System;
class FindingIfBitOnPositonPIsOne
{
static void Main()
{
Console.WriteLine("Checking if bit on position P(counting from 0) in an integer number V is '1'.\n");
Console.Write("Please type an integer number V: ");
int vNumberToCheck = int.Parse(Console.ReadLine());
Console.Write("Please type the bit positon P: ");
byte pPositionToCheck = byte.Parse(Console.ReadLine());
int numberToThePowerOfP = (int)Math.Pow(2, pPositionToCheck);
int resultOfBitwiseOperation = vNumberToCheck & numberToThePowerOfP;
if (resultOfBitwiseOperation != 0)
{
Console.WriteLine("\nThe bit P(counting from 0) is '1'.");
}
else
{
Console.WriteLine("\nThe bit P(counting from 0) is NOT '1'.");
}
}
}
|
JavaScript
|
UTF-8
| 2,146 | 3.171875 | 3 |
[
"MIT"
] |
permissive
|
/**
* Object sort pour trier des éléments typique de HTML
*/
class sort {
/**
* Fonction de trié des tableau dans l'order croissant et décroissant
* @param {int} column Numéro de la colonne à trié
* @param {string} table Id du tableau à trié
*/
static table(column, table) {
let rows; let switching; let i; let shouldSwitch; let dir; let switchCount = 0;
let current; let next;
table = document.getElementById(table);
switching = true;
dir = 'asc';
while (switching) {
switching = false;
rows = table.querySelector('tbody').rows;
if (rows.length) {
for (i = 0; i < (rows.length - 1); i++) {
shouldSwitch = false;
current = rows[i].querySelectorAll('td')[column].innerHTML;
next = rows[i + 1].querySelectorAll('td')[column].innerHTML;
current = (isNaN(current) ? (current.includes('%') || current.includes('€') ? parseFloat(current.split(/( )|( )/)[0]) : current) : parseFloat(current));
next = (isNaN(next) ? (next.includes('%') || next.includes('€') ? parseFloat(next.split(/( )|( )/)[0]) : next) : parseFloat(next));
if (dir === 'asc') {
if (current > next) {
shouldSwitch = true;
break;
}
} else {
if (current < next) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchCount++;
} else {
if (switchCount === 0 && dir === 'asc') {
dir = 'desc';
switching = true;
}
}
}
}
}
}
export default sort;
|
JavaScript
|
UTF-8
| 2,172 | 2.765625 | 3 |
[] |
no_license
|
import "./App.css";
import logo from "./logo.svg";
import { connect } from "react-redux";
import Numbers from "./components/Numbers";
import * as actionCreator from "./redux/actions/ageActions";
function App(props) {
// Props passed by redux
const {
age,
handleAgeIncrement,
handleAgeDecrement,
history,
handleHistoryItemDelete,
loading,
} = props;
return (
<div className="App">
<br />
<br />
<br />
<br />
<br />
<div>
Age: <span>{age}</span>
</div>
<br />
<br />
<button onClick={handleAgeIncrement}>Make me older</button>
<br />
<br />
<button onClick={handleAgeDecrement}>Make me younger</button>
<br />
<div>
History:{" "}
<ul>
{history.map((entity) => (
<li
key={entity.id}
onClick={() => handleHistoryItemDelete(entity.id)}
>
{entity.age}
</li>
))}
</ul>
</div>
{loading && <img src={logo} alt="logo" />}
<Numbers />
</div>
);
}
// States in the redux store
const mapStateToProps = (state) => {
return {
age: state.rAge.age,
history: state.rAge.history,
loading: state.rAge.loading,
};
};
// Dispatchers in the redux store
const mapDispatchToProps = (dispatch) => {
return {
// Use action creators imported to pass the state
handleAgeIncrement: () => dispatch(actionCreator.ageIncrement(1)),
handleAgeDecrement: () => dispatch(actionCreator.ageDecrement(1)),
// Pass the state directly
handleHistoryItemDelete: (id) =>
dispatch({ type: "DEL_ITEM", key: id }),
};
};
// Connect App component to the store and get the states
// and dispatchers
export default connect(mapStateToProps, mapDispatchToProps)(App);
|
C++
|
UHC
| 4,844 | 2.859375 | 3 |
[] |
no_license
|
//----------------------------------------------------------------------
// CStorageSurface.cpp
//----------------------------------------------------------------------
#include "client_PCH.h"
#include "CDirectDrawSurface.h"
#include "CStorageSurface.h"
//#include "DebugInfo.h"
//----------------------------------------------------------------------
//
// constructor/destructor
//
//----------------------------------------------------------------------
CStorageSurface::CStorageSurface()
{
m_Size = 0;
m_pPoint = NULL;
m_pStorageSurface = NULL;
}
CStorageSurface::~CStorageSurface()
{
Release();
}
//----------------------------------------------------------------------
//
// member functions
//
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Init
//----------------------------------------------------------------------
// (Surface, surfaceũ, ũ)
//----------------------------------------------------------------------
void
CStorageSurface::Init(int size, int width, int height)
{
// parameter ߸ ..
if (size==0 || width==0 || height==0)
return;
// ϴ ִ Ŀ..
Release();
// ..
m_Size = size;
m_pPoint = new POINT [m_Size];
m_pStorageSurface = new CDirectDrawSurface [m_Size];
for (int i=0; i<m_Size; i++)
{
// surface ġ ʱȭѴ.
m_pPoint[i].x = 0;
m_pPoint[i].y = 0;
// surface ũ⸦ صд.
m_pStorageSurface[i].InitOffsurface(width, height);
m_pStorageSurface[i].SetTransparency(0);
}
}
//----------------------------------------------------------------------
// Release
//----------------------------------------------------------------------
//
//----------------------------------------------------------------------
void
CStorageSurface::Release()
{
if (m_pStorageSurface!=NULL)
{
delete [] m_pStorageSurface;
m_pStorageSurface = NULL;
}
if (m_pPoint!=NULL)
{
delete [] m_pPoint;
m_pPoint = NULL;
}
m_Size = 0;
}
//----------------------------------------------------------------------
// Store
//----------------------------------------------------------------------
// pSurface pPointκ о i° surface ѵд.
//----------------------------------------------------------------------
void
CStorageSurface::Store(int i, CDirectDrawSurface* pSurface, POINT* pPoint)
{
// i surfaceȣ ..
if (i<0 || i>=m_Size)
return;
POINT origin = {0, 0};
int width = pPoint->x + m_pStorageSurface[i].GetWidth();
int height = pPoint->y + m_pStorageSurface[i].GetHeight();
// clipping
if (pPoint->x < 0)
{
width += -pPoint->x;
pPoint->x = 0;
}
else if (width > pSurface->GetWidth())
{
pPoint->x -= width - pSurface->GetWidth();
width = pSurface->GetWidth();
}
// clipping
if (pPoint->y < 0)
{
height += -pPoint->y;
pPoint->y = 0;
}
else if (height > pSurface->GetHeight())
{
pPoint->y -= height - pSurface->GetHeight();
height = pSurface->GetHeight();
}
// pSurface ѵ
RECT rect =
{
pPoint->x,
pPoint->y,
width,
height
};
// Ų ġ صд.
m_pPoint[i] = *pPoint;
// m_pStorageSurface[i] (0,0)
// pSurface ѵд.
m_pStorageSurface[i].BltNoColorkey(&origin, pSurface, &rect);
//DEBUG_ADD_FORMAT("Store : [%d] (%d, %d)", i, m_pPoint[i].x, m_pPoint[i].y);
}
//----------------------------------------------------------------------
// Restore
//----------------------------------------------------------------------
// i° surface pSurface ġ(m_pPoint) ش.
//----------------------------------------------------------------------
void
CStorageSurface::Restore(int i, CDirectDrawSurface* pSurface, POINT* pPoint) const
{
// i surfaceȣ ..
if (i<0 || i>=m_Size)
return;
// pSurface ѵ
RECT rect =
{
0,
0,
m_pStorageSurface[i].GetWidth(),
m_pStorageSurface[i].GetHeight()
};
// pSurface ġ(m_pPoint)
// m_pStorageSurface[i] ½Ų.
if (pPoint==NULL)
{
POINT point = m_pPoint[i];
pSurface->BltNoColorkey(&point, &m_pStorageSurface[i], &rect);
}
else
{
pSurface->BltNoColorkey(pPoint, &m_pStorageSurface[i], &rect);
}
//DEBUG_ADD_FORMAT("Restore : [%d] (%d, %d)", i, m_pPoint[i].x, m_pPoint[i].y);
}
|
C
|
UTF-8
| 992 | 3.75 | 4 |
[
"MIT"
] |
permissive
|
// Implementation of Single Circular Linked List in C
/// FONT: https://www.tutorialspoint.com/data_structures_algorithms/circular_linked_list_program_in_c.htm
#include <stdio.h>
#include <stdlib.h>
#include "ds_simpleCircularLinkedList.h"
int main(int argc, char const *argv[])
{
// Create empty Linked List pointing to NULL
printf("\n\tCreated Linked List!\n");
struct sCircularLinkedList head = {NULL};
showLL(&head);
printf("\n\tInserts\n");
insertFirst(&head, 'a');
insertLast(&head, '0');
insertAt(&head, 'e', 2);
showLL(&head);
printf("\n\tSearches\n");
searchData(&head, 'b');
searchData(&head, '0');
searchPosition(&head, 42);
searchPosition(&head, 2);
printf("\n\tReverse\n");
showLL(&head);
reverseLL(&head);
showLL(&head);
printf("\n\tDeletes\n");
deleteFirst(&head);
deleteLast(&head);
showLL(&head);
printf("\n\tFree\n");
freeLL(&head);
showLL(&head);
return 0;
}
|
Ruby
|
UTF-8
| 1,484 | 2.984375 | 3 |
[] |
no_license
|
require 'curses'
require_relative 'table'
include Curses
class Display
def initialize
init_screen
start_color
init_color(COLOR_BLACK, 0, 0, 0)
fill_window(stdscr, COLOR_BLACK)
curs_set(0)
refresh
@windows = []
end
def attach(object, x, y)
@windows.push(x: x, y: y, object: object)
object.register(self)
object.draw(x, y)
end
def redraw
fill_window(stdscr, COLOR_BLACK)
refresh
@windows.each do |win|
win[:object].draw(win[:x], win[:y])
end
end
def close(object)
window = @windows.detect { |w| w[:object] == object }
@windows.delete(window)
redraw
end
def focus(object)
window = @windows.detect { |w| w[:object] == object }
@windows.delete(window)
@windows.push(window)
redraw
end
def move(object, x, y)
window = @windows.detect { |w| w[:object] == object }
window[:x] = x
window[:y] = y
redraw
end
def temp
while true do
# if getch == Curses::KEY_RESIZE
# # File.open('log.txt', 'a+') { |file| file.write('res'+"\n") }
# resizeterm(Curses.lines, Curses.cols)
# draw_headers(@table)
# draw_table(@table)
# end
getch
@windows[1][:object].add_row({ a: 'dra', b: 'dar', c: 'dar'})
end
end
private def fill_window(win, color)
win.attron(color_pair(color)) do
lines.times do |line|
win.setpos(line, 0)
win << ' ' * cols
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.