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
|
|---|---|---|---|---|---|---|---|
C++
|
UTF-8
| 1,445
| 3.640625
| 4
|
[] |
no_license
|
/*
* test_Blob.cpp
* Test the Blob class template.
* Compilation: g++ -o test_Blob test_Blob.cpp -std=c++11
* Created: 2015-09-26
*/
#include "Blob.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <iterator>
using std::cout;
using std::endl;
using std::vector;
using std::list;
using std::string;
using std::begin;
using std::end;
int main(void)
{
Blob<string> articles{"a", "an", "the"};
// instantiates Blob<int> and the initializer_list<int> constructor
Blob<int> squares{0,1,2,3,4,5,6,7,8,9};
// instantiates Blob<int>::size() const
for (size_t i = 0; i != squares.size(); ++i)
squares[i] = i * i; // instantiates Blob<int>::operator[](size_type i)
for (size_t i = 0; i != squares.size(); ++i)
cout << squares[i] << ' ';
cout << endl;
int ia[] = {0,1,2,3,4,5,6,7,8,9};
vector<long> vi = {0,1,2,3,4,5,6,7,8,9};
list<const char*> w = {"now", "is", "the", "time"};
// instantiates the Blob<int> class
// and the Blob<int> constructor that has two int* parameter
Blob<int> b1(begin(ia), end(ia));
// instantiates the Blob<int> constructor that has
// two vector<long>::iterator parameters
Blob<int> b2(vi.begin(), vi.end());
// instantiates the Blob<string> class and the Blob<string>
// constructor that has two list<const char*>::iterator parameters
Blob<string> a3(w.begin(), w.end());
return 0;
}
|
Python
|
UTF-8
| 611
| 2.84375
| 3
|
[] |
no_license
|
# -*- coding:utf8 -*-
# @TIME :2019/5/20 20:39
# @Author : 洪松
# @File : 插入数据.py
import pymysql
# 创建连接
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='123456', db='ssl')
# 创建游标
cursor = conn.cursor()
# 执行SQL
cursor.execute('insert into test1(name, age) values("洪松", "24")')
# r = cursor.execute('insert into test1(name, age) values("洪松", "24")')
# # 1 ---》执行SQL受影响的行数
# print(r)
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
|
C#
|
UTF-8
| 252
| 2.53125
| 3
|
[] |
no_license
|
// See https://aka.ms/new-console-template for more information
using Engine;
Console.WriteLine("Hello, World!");
ulong mask = 1;
for (int i = 0; i < Board.Size; i++)
{
Console.WriteLine(mask);// BitConverter.ToUInt64(mask));
mask <<= 1;
}
|
JavaScript
|
UTF-8
| 632
| 3.796875
| 4
|
[] |
no_license
|
function validParens(str) {
// hash table to check if valid
let hash = {
')': '(',
'}': '{',
']': '['
};
// use a stack
let stack = [];
for (let paren of str) {
// open paren will push to stack
// console.log(paren);
if (paren === '(' || paren === '{' || paren === '[') {
stack.push(paren);
} else {
// check close paren if it matches the last open paren
let lastOpenParen = stack.pop();
if (lastOpenParen !== hash[paren]) {
return false;
}
}
}
return true;
}
console.log(validParens('{[]}')); // true
console.log(validParens('([)]')); // false
|
JavaScript
|
UTF-8
| 170
| 3.21875
| 3
|
[] |
no_license
|
function reverseString(str) {
var arr = [];
arr= str.split("");
var newArr = arr.reverse();
var ans = newArr.join("");
return ans;
}
reverseString("hello");
|
Python
|
UTF-8
| 2,217
| 3.078125
| 3
|
[] |
no_license
|
from itertools import starmap
from adventofcode2020.utils import (
DataName,
fetch_input_data_if_not_exists,
print_call,
read,
submit,
)
@print_call
def solve_part1(file_name):
cards = read(file_name).split("\n\n")
player1_cards = list(map(int, cards[0].splitlines()[1:]))
player2_cards = list(map(int, cards[1].splitlines()[1:]))
while len(player1_cards) and len(player2_cards):
if (c1 := player1_cards.pop(0)) > (c2 := player2_cards.pop(0)):
player1_cards.extend([c1, c2])
else:
player2_cards.extend([c2, c1])
if len(player1_cards):
return _score(player1_cards)
return _score(player2_cards)
def _score(cards):
return sum(starmap(lambda a, b: a * b, zip(cards[::-1], range(1, len(cards) + 1))))
@print_call
def solve_part2(file_name):
cards = read(file_name).split("\n\n")
player1_cards = list(map(int, cards[0].splitlines()[1:]))
player2_cards = list(map(int, cards[1].splitlines()[1:]))
winner, cards = _recursive_game(player1_cards, player2_cards)
return _score(cards)
def _recursive_game(player1_cards, player2_cards):
memo = set()
while (l1 := len(player1_cards)) and (l2 := len(player2_cards)):
if (key := (tuple(player1_cards), tuple(player2_cards))) in memo:
return 0, player1_cards
memo.add(key)
c1 = player1_cards.pop(0)
c2 = player2_cards.pop(0)
if ((l1 - 1) >= c1) and ((l2 - 1) >= c2):
winner, _ = _recursive_game(player1_cards[:c1], player2_cards[:c2])
else:
winner = 0 if c1 > c2 else 1
if winner == 0:
player1_cards.extend([c1, c2])
else:
player2_cards.extend([c2, c1])
if len(player1_cards):
return 0, player1_cards
return 1, player2_cards
if __name__ == "__main__":
fetch_input_data_if_not_exists()
part = "a"
assert solve_part1(DataName.SAMPLE_1) == 306
answer = solve_part1(DataName.PUZZLE)
submit(answer, part)
part = "b"
assert solve_part2(DataName.SAMPLE_1) == 291
assert solve_part2(DataName.SAMPLE_2) == 105
answer = solve_part2(DataName.PUZZLE)
submit(answer, part)
|
Java
|
UTF-8
| 429
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.codebits.softwareninja.interpretation.operations;
import com.codebits.softwareninja.interpretation.Value;
public class EqualOperation extends ConditionOperation {
public EqualOperation(String originalText, Value leftValue, Value rightValue) {
super(originalText, leftValue, rightValue);
}
@Override
public Boolean computeResult() {
return getLeftValue().getInt().equals(getRightValue().getInt());
}
}
|
JavaScript
|
UTF-8
| 3,160
| 2.5625
| 3
|
[] |
no_license
|
import React from 'react';
import axios from 'axios';
export default class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
stockNumber: '',
personalPassportId: '',
name: ''
};
this.inputChange = this.inputChange.bind(this);
this.submitData = this.submitData.bind(this);
}
inputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
};
submitData(event) {
const {stockNumber, personalPassportId, name} = this.state;
axios.post('/checking', {
stockNumber: stockNumber,
personalPassportId: personalPassportId,
name: name
}).then((response) => {
this.setState({
tableData: response.data
}, () => {
this.props.dataReturnOnForm(this.state);
});
}).catch((err) => {
console.log(err);
});
event.preventDefault();
};
render() {
return (
<form onSubmit={this.submitData}>
<h2 className="card-inside-title">Floating Label Examples</h2>
<div className="row clearfix">
<div className="col-sm-12">
<div className="form-group form-float form-group-lg">
<div className="form-line">
<input type="text" className="form-control" name="stockNumber" autoFocus
onChange={this.inputChange}/>
<label className="form-label">Stock number</label>
</div>
</div>
<div className="form-group form-float form-group-lg">
<div className="form-line">
<input type="text" className="form-control" name="personalPassportId"
onChange={this.inputChange}/>
<label className="form-label">Personal ID/Passport number</label>
</div>
</div>
<div className="form-group form-float form-group-lg">
<div className="form-line">
<input type="text" className="form-control" name="name"
onChange={this.inputChange}/>
<label className="form-label">Stockholder name</label>
</div>
</div>
</div>
</div>
<div className="row clearfix">
<div className="col-sm-12">
<button type="submit" className="btn btn-lg btn-primary waves-effect">
Submit
</button>
</div>
</div>
</form>
)
}
}
|
Java
|
UTF-8
| 1,389
| 2.46875
| 2
|
[] |
no_license
|
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.doubao.finance.util.ajax;
public class JsonResponseBuilder {
public JsonResponseBuilder() {
}
public static <T> JsonResponse buildJsonResponse(ResponseCode code, T data) {
if (code == null) {
throw new NullPointerException();
} else {
return data == null ? new JsonResponse(code.getCode(), code.getMessage(), "") : new JsonResponse(code.getCode(), code.getMessage(), data);
}
}
public static <T> JsonResponse buildSuccessJsonResponse(T data) {
return buildJsonResponse(ResponseCode.OK, data);
}
public static JsonResponse buildSuccessJsonResponseWithoutData() {
return buildSuccessJsonResponse((Object) null);
}
public static <T> JsonResponse buildErrorJsonResponse(ResponseCode code, T data) {
if (code == null) {
throw new NullPointerException();
} else if (code == ResponseCode.OK) {
throw new IllegalArgumentException("build error json code ,but you passed a success json code !");
} else {
return buildJsonResponse(code, data);
}
}
public static JsonResponse buildErrorJsonResponseWithoutData(ResponseCode code) {
return buildErrorJsonResponse(code, (Object) null);
}
}
|
PHP
|
UTF-8
| 4,054
| 2.84375
| 3
|
[] |
no_license
|
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
// author:huynhvanduoc
// date:30/05.2012
// Viết xóa xml với php
/*
<?xml version="1.0" encoding="utf-8"
?>
<cautruc>
<thuonghieu id="26" name="Tên thương hiệu">
<sanpham id="79" name="Tên sản phẩm">
<tieude>
Tiêu đề 1
<tieude/>
</sanpham>
</thuonghieu>
</cautruc>
*/
class CI_lib_xml {
function writeXML($idthuonghieu, $id, $name, $tieude) {
$dom = new DOMDocument;
$dom -> preserveWhiteSpace = false;
$dom -> formatOutput = true;
// Xuất định dạng cho đẹp
$dom -> load("dom.xml");
$thedocument = $dom -> documentElement;
$list = $thedocument -> getElementsByTagName('thuonghieu');
$nodeToRemove = null;
foreach ($list as $domElement) {
$attrValue = $domElement -> getAttribute('id');
if ($attrValue == $idthuonghieu) {
$new_tag = $domElement -> appendChild($dom -> createElement('sanpham'));
$new_tag -> setAttributeNode(new DOMAttr('id', $id));
$new_tag -> setAttributeNode(new DOMAttr('name', $name));
$new_tag -> appendChild($dom -> createElement('tieude', $tieude));
}
}
//Now remove it.
if ($nodeToRemove != null)
$thedocument -> removeChild($nodeToRemove);
$dom -> save('dom.xml');
/* Ý tưởng: Thêm một sản phẩm vào trong nút thương hiệu với với tham số truyền vào là id thương hiệu
* Thêm 1 nút con vào nút cha với điều kiện là id của nút cha
*/
}
function delXML($idthuonghieu, $idsp) {
$doc = new DOMDocument;
$doc -> load("dom.xml");
$thedocument = $doc -> documentElement;
//this gives you a list of the messages
$list = $thedocumen -> getElementsByTagName('thuonghieu');
$nodeToRemove = null;
foreach ($list as $domElement) {
$attrValue = $domElement -> getAttribute('id');
if ($attrValue == $idthuonghieu) {
$listSub = $domElement -> getElementsByTagName('sanpham');
foreach ($listSub as $domElementSub) {
$attrValueSub = $domElementSub -> getAttribute('id');
if ($attrValueSub == $idsp) {
$domElement -> removeChild($domElementSub);
}
}
}
}
$doc -> preserveWhiteSpace = false;
$doc -> formatOutput = true;
$doc -> save('dom.xml');
//Ý tưởng: Xóa nút con với điều kiện idCon=A,nằm trong nút cha có idCha=B
}
function writeXML_Level1($idthuonghieu, $ten_thuonghieu, $type) {
$dom = new DOMDocument();
$dom -> preserveWhiteSpace = false;
$dom -> formatOutput = true;
//URL file xml
$dom -> load("dom.xml");
// create root nodes
$resumedata = $dom -> createElement("cautruc");
//$dom->appendChild($resumedata);
$new_tag = $dom -> createElement('thuonghieu');
$new_tag -> setAttributeNode(new DOMAttr('id', $idthuonghieu));
$new_tag -> setAttributeNode(new DOMAttr('name', $ten_thuonghieu));
$new_tag -> appendChild($dom -> createElement('type', $type));
//Het chinh sua
$dom -> documentElement -> appendChild($new_tag);
$dom -> save('dom.xml');
// Ý tưởng: Thêm 1 nút nằm trong nút gốc <cautruc>, nút được thêm có các thuộc tính như: id,name
}
function delXML_Level_1($id)
{
$doc = new DOMDocument;
$doc->load("dom.xml");
$thedocument = $doc->documentElement;
//this gives you a list of the messages
$list = $thedocument->getElementsByTagName('thuonghieu');
//figure out which ones you want -- assign it to a variable (ie: $nodeToRemove )
$nodeToRemove = null;
foreach ($list as $domElement) {
$attrValue = $domElement->getAttribute('id');
if ($attrValue == $id) {
$nodeToRemove = $domElement; //will only remember last one- but this is just an example :)
}
}
//Now remove it.
if ($nodeToRemove != null)
$thedocument->removeChild($nodeToRemove);
$doc->save('dom.xml');
// Ý tưởng: Xóa nút với điều kiện id(thuộc tính) được truyền vào
}
}
// Class lib-xml
// Location:application/libraries/lib-xml.php
?>
|
C++
|
UTF-8
| 3,376
| 2.640625
| 3
|
[] |
no_license
|
// gencoinlistKEK.cpp
// g++ -Wall gencoinlistKEK.cpp -o gencoinlistKEK
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
class CheckOpt
{
public:
CheckOpt ();
void usage (std::ostream& os, const char* pname);
bool setup (int argc, char* argv []);
public:
bool m_infile_given;
std::string m_infilename;
bool m_outfile_given;
std::string m_outfilename;
};
CheckOpt::CheckOpt ()
{
m_infile_given = false;
m_infilename = "";
m_outfile_given = false;
m_outfilename = "";
}
void
CheckOpt::usage (std::ostream& os, const char* pname)
{
os
<< "Usage: "
<< pname
<< " [option(s)] runno_filename\n"
<< "Option(s):\n"
<< " -o[ut] filename \t specifies output filename\n"
<< std::endl;
}
bool
CheckOpt::setup (int argc, char* argv[])
{
int npos = 1;
while (npos < argc)
{
std::string optword (argv[npos]);
if ((optword == "-o") || (optword == "-out"))
{
++npos;
if (npos < argc)
{
m_outfilename = std::string (argv[npos]);
m_outfile_given = true;
}
else
{
std::cerr << "ERROR: missing output filename." << std::endl;
return false;
}
}
else
{
if (m_infile_given)
{
std::cerr << "WARNING: input filename already given, replaced." << std::endl;
}
m_infilename = optword;
m_infile_given = true;
}
++npos;
}
// if (!m_infile_given)
// return false;
return true;
}
int main (int argc, char* argv[])
{
CheckOpt opt;
if ( !opt.setup (argc, argv) )
{
opt.usage (std::cerr, argv[0] );
return (-1);
}
std::string infilename;
if (opt.m_infile_given)
infilename = opt.m_infilename;
else
infilename = "gencoinlistKEK.xml";
std::ifstream ifs ( infilename.c_str() );
if (!ifs)
{
std::cerr
<< "ERROR: input file ("
<< infilename
<< ") cannot be opened."
<< std::endl;
return (-2);
}
std::string outfilename;
if (opt.m_outfile_given)
outfilename = opt.m_outfilename;
else
outfilename = "coinlist.txt";
std::ofstream ofs ( outfilename.c_str() );
if (!ofs)
{
std::cerr
<< "ERROR: output file ("
<< outfilename
<< ") cannot be opened."
<< std::endl;
return (-2);
}
ofs
<< "%";
for (int i = 0; i < argc; i++)
ofs << " " << argv[i];
ofs << std::endl;
std::string datafolder ("/data1/Detector5/data/");
std::string foldersep ("/");
std::string coinprefix ("d5-r");
std::string coinpostfix ("_m24c32.dat.gz");
std::string sline;
while (std::getline (ifs, sline))
{
if ((sline.size () >= 10) &&
(sline.substr(0,9) == "<RunRange"))
{
std::string::size_type n = 9;
while (n < sline.size ())
{
if (sline[n] == '>')
break;
n++;
}
break;
}
sline.clear ();
}
while (std::getline (ifs, sline))
{
if ((sline.size () >= 4) && (sline.substr (0, 4) == "<!--"))
continue;
else if (sline.size () >= 3)
{
std::stringstream ss (sline);
int srun;
int erun;
while ((ss >> srun >> erun))
{
for (int runno = srun; runno <= erun; runno++)
{
ofs
<< datafolder
<< runno
<< foldersep
<< coinprefix
<< runno
<< coinpostfix
<< std::endl;
}
}
}
sline.clear ();
}
return 0;
}
|
C
|
UTF-8
| 466
| 3.171875
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
int sum_up_to(int num)
{
int i;
int sum = 0;
for (i = 1; i <= num; i++)
sum += i;
return sum;
}
// test for rel 32bit probe
int func1(int a, int b)
{
return (a + b) * a;
}
int func1a(int a, int b)
{
return (a + b) * a;
}
int func1b(int a, int b)
{
return (a + b) * a;
}
// This can be used abs 64bit probe (bacause function size is larger than 12B)
int func2(int a, int b)
{
return (a + b) * (a + a) * a / b;
}
|
C++
|
UTF-8
| 982
| 2.609375
| 3
|
[] |
no_license
|
#include "HttpClient.h"
HttpClient::HttpClient()
{
}
void HttpClient::HttpSendPerformanceData()
{
string url = "http://192.168.1.200:8000/postNodeStatus.php";
Poco::URI uri(url);
string path = uri.getPath();
HTTPClientSession session(uri.getHost(), uri.getPort());
session.setKeepAlive(true);
HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1);
req.setContentType("application/x-www-form-urlencoded");
req.setKeepAlive(true);
GenerateJsonData *json = new GenerateJsonData();
Json::Value performance = json->GetPerformanceData();
string databody = performance.toStyledString();
string data = "data=" + databody;
req.setContentLength(data.length());
//ostream &myOstream = session.sendRequest(req);
//myOstream <<data;
/*HTTPResponse rep(HTTPResponse::HTTPStatus::HTTP_OK);
istream &myIstream = session.receiveResponse(rep);
cout<<myIstream.rdbuf() << endl;
*/
cout << "send ok" << endl;
}
HttpClient::~HttpClient()
{
}
|
C
|
UTF-8
| 6,253
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
/*
Author: ChrisB
Description: Utilities functions for interfacing with controller.
Date: Summer 2020
*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
//source code headers
#include "pro_con_utils.h"
#include "pro_con_errors.h"
int getButtonInfo(struct js_event* event_info,button_input_t* button_data){
button_data->button_code = event_info->number;
button_data->isPressed = event_info->value;
switch(button_data->button_code){
case B_BUTTON:
button_data->button_name = "B-Button";
break;
case A_BUTTON:
button_data->button_name = "A-Button";
break;
case Y_BUTTON:
button_data->button_name = "Y-Button";
break;
case X_BUTTON:
button_data->button_name = "X-Button";
break;
case L_BUTTON:
button_data->button_name = "L-Button";
break;
case R_BUTTON:
button_data->button_name = "R-Button";
break;
case ZL_BUTTON:
button_data->button_name = "ZL Button";
break;
case ZR_BUTTON:
button_data->button_name = "ZR Button";
break;
case MINUS_BUTTON:
button_data->button_name = "Minus Button";
break;
case PLUS_BUTTON:
button_data->button_name = "Plus Button";
break;
case LEFT_JS_PRESS:
button_data->button_name = "Left Joystick";
break;
case RIGHT_JS_PRESS:
button_data->button_name = "Right Joystick";
break;
case HOME_BUTTON:
button_data->button_name = "Home Button";
break;
case SCREENSHOT_BUTTON:
button_data->button_name = "Screenshot Button";
break;
default:
break;
}
return SUCCESSFUL_EXECUTION;
}
int getJoystickInfo(struct js_event* event_info,direction_input_t* joystick_data){
joystick_data->joysticks_pos[event_info->number] = event_info->value;
joystick_data->changed_axis = event_info->number;
joystick_data->direction_type = (joystick_data->changed_axis >= DIR_PAD_HORIZ) ? "Arrow" : "Stick";
switch(joystick_data->changed_axis){
case LEFT_JOY_HORIZ_AXIS:
joystick_data->direction = "Left";
joystick_data->other_axis = LEFT_JOY_VERT_AXIS;
break;
case LEFT_JOY_VERT_AXIS:
joystick_data->direction = "Left";
joystick_data->other_axis = LEFT_JOY_HORIZ_AXIS;
break;
case RIGHT_JOY_HORIZ_AXIS:
joystick_data->direction = "Right";
joystick_data->other_axis = RIGHT_JOY_VERT_AXIS;
break;
case RIGHT_JOY_VERT_AXIS:
joystick_data->direction = "Right";
joystick_data->other_axis = RIGHT_JOY_HORIZ_AXIS;
break;
case DIR_PAD_HORIZ:
if(event_info->value == 0){
joystick_data->direction = "Idle";
joystick_data->direction_type = "Pad";
} else{
joystick_data->direction = event_info->value < 0 ? "Left" : "Right";
}
joystick_data->other_axis = DIR_PAD_VERT;
break;
case DIR_PAD_VERT:
if(event_info->value == 0){
joystick_data->direction = "Idle";
joystick_data->direction_type = "Pad";
} else{
joystick_data->direction = event_info->value < 0 ? "Up" : "Down";
}
joystick_data->other_axis = DIR_PAD_HORIZ;
break;
default:
break; //no other axes
}
return SUCCESSFUL_EXECUTION;
}
int readControllerEvent(int joystick_fd, struct js_event* event_info){
int status = 0;
ssize_t num_bytes;
num_bytes = read(joystick_fd,event_info,sizeof(*event_info)); //blocks until bytes to read, EOL, or error
status = (num_bytes == sizeof(*event_info)) ? SUCCESSFUL_EXECUTION : DEVICE_READ_ERROR;
return status;
}
//Purpose: Loop over controller input & print to stdout
int testControllerInputs(int joystick_fd,char* joystick_file_name){
int status = SUCCESSFUL_EXECUTION;
int x_pos = 0,
y_pos = 0;
char* direction = NULL,
* direction_type = NULL;
struct js_event cur_event = {0};
direction_input_t controler_js = {0};
button_input_t controller_button = {0};
fprintf(stdout,"\n------Starting Nintendo Pro Controller Testing------\n");
fprintf(stdout,"Controller Device @ %s\n",joystick_file_name);
//process & print events
while( status == SUCCESSFUL_EXECUTION ){
status = readControllerEvent(joystick_fd,&cur_event);
if(status == DEVICE_READ_ERROR){ continue; }
switch(cur_event.type){
case KEY_BUTTON_TYPE:
getButtonInfo(&cur_event,&controller_button);
fprintf(stdout,"\nJoystick Event: %s %s\n",
controller_button.button_name,
controller_button.isPressed ? "pressed": "released"
);
break;
case JOYSTICK_TYPE:
getJoystickInfo(&cur_event,&controler_js);
if(controler_js.changed_axis % 2 == 0){
x_pos = controler_js.changed_axis;
y_pos = controler_js.other_axis;
} else{
x_pos = controler_js.other_axis;
y_pos = controler_js.changed_axis;
}
fprintf(stdout,"\nJoystick Event: %s %s @ position (%d, %d)\n",
controler_js.direction,
controler_js.direction_type,
controler_js.joysticks_pos[controler_js.changed_axis],
controler_js.joysticks_pos[controler_js.other_axis]
); //add CLI for file logging enable
break;
default:
//ignore JS_EVENT_INIT
break;
}
fflush(stdout); //clear buffers for next read
}
return SUCCESSFUL_EXECUTION;
}
|
C#
|
UTF-8
| 1,407
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
using System.Text.RegularExpressions;
using NhaNhaNha.Extensions;
using NUnit.Framework;
namespace NhaNhaNha.Test
{
[TestFixture]
public class DadoUmGeradorDeDocumento
{
[Test]
public void AoGerarCpfResultadoDeveConter11Digitos()
{
var cpf = NhaNhaNha.CPF.Cpf;
Assert.AreEqual(11, cpf.Length);
}
[Test]
public void AoGerarCpfResultadoDeveSerUmCpfValido()
{
string cpf = NhaNhaNha.CPF;
Assert.IsTrue(cpf.CpfValido());
}
[Test]
public void AoGerarCpfResultadoDeveDeveConterUmFormatoEspecifico()
{
var cpf = NhaNhaNha.CPFFormatado;
Assert.IsTrue(Regex.IsMatch(cpf, @"\d{3}\.\d{3}\.\d{3}-\d{2}"));
}
[Test]
public void AoGerarCnpjResultadoDeveConter11Digitos()
{
var cnpj = NhaNhaNha.Cnpj.Cnpj;
Assert.AreEqual(14, cnpj.Length);
}
[Test]
public void AoGerarCnpjResultadoDeveSerUmCpfValido()
{
string cnpj = NhaNhaNha.Cnpj;
Assert.IsTrue(cnpj.CNPJValido());
}
[Test]
public void AoGerarCnpjResultadoDeveDeveConterUmFormatoEspecifico()
{
var cnpj = NhaNhaNha.CnpjFormatado;
Assert.IsTrue(Regex.IsMatch(cnpj, @"\d{1}\.\d{3}\.\d{3}/0001-\d{2}"));
}
}
}
|
Java
|
UTF-8
| 2,045
| 2.4375
| 2
|
[] |
no_license
|
package com.zhaoyan.webserver.userinfomanage;
import java.util.ArrayList;
import com.zhaoyan.webserver.common.JDBCUtils;
import com.zhaoyan.webserver.db.DBData.UserInfoTable;
public class ModifyUserInfoDao implements ModifyUserInfoService {
private JDBCUtils mJdbcUtils;
public ModifyUserInfoDao() {
mJdbcUtils = new JDBCUtils();
}
@Override
public boolean modifyPassword(String username, String newPassword) {
boolean result = false;
String sql = "update " + UserInfoTable.TABLE_NAME + " set "
+ UserInfoTable.PASSWORD + "=? where "
+ UserInfoTable.USER_NAME + "=?";
ArrayList<Object> params = new ArrayList<>();
params.add(newPassword);
params.add(username);
try {
mJdbcUtils.getConnection();
result = mJdbcUtils.updateByPreparedStatement(sql, params);
} catch (Exception e) {
e.printStackTrace();
} finally {
mJdbcUtils.releaseConnection();
}
return result;
}
@Override
public boolean modifyEmail(String username, String email) {
boolean result = false;
String sql = "update " + UserInfoTable.TABLE_NAME + " set "
+ UserInfoTable.EMAIL + "=? where " + UserInfoTable.USER_NAME
+ "=?";
ArrayList<Object> params = new ArrayList<>();
params.add(email);
params.add(username);
try {
mJdbcUtils.getConnection();
result = mJdbcUtils.updateByPreparedStatement(sql, params);
} catch (Exception e) {
e.printStackTrace();
} finally {
mJdbcUtils.releaseConnection();
}
return result;
}
@Override
public boolean modifyPhone(String username, String phone) {
boolean result = false;
String sql = "update " + UserInfoTable.TABLE_NAME + " set "
+ UserInfoTable.PHONE + "=? where " + UserInfoTable.USER_NAME
+ "=?";
ArrayList<Object> params = new ArrayList<>();
params.add(phone);
params.add(username);
try {
mJdbcUtils.getConnection();
result = mJdbcUtils.updateByPreparedStatement(sql, params);
} catch (Exception e) {
e.printStackTrace();
} finally {
mJdbcUtils.releaseConnection();
}
return result;
}
}
|
Java
|
UTF-8
| 9,727
| 1.8125
| 2
|
[] |
no_license
|
package ru.gosuslugi.dom.schema.integration.house_management;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for GKNRelationshipStatusType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="GKNRelationshipStatusType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Status">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <length value="1"/>
* <enumeration value="C"/>
* <enumeration value="D"/>
* <enumeration value="N"/>
* </restriction>
* </simpleType>
* </element>
* <choice>
* <element name="AppartmentHouseAcceptedParameter" type="{http://dom.gosuslugi.ru/schema/integration/house-management/}ApartmentHouseAcceptedParameterType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="LivingHouseAcceptedParameter" type="{http://dom.gosuslugi.ru/schema/integration/house-management/}LivingHouseAcceptedParameterType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="NonResidentialPremiseAcceptedParameter" type="{http://dom.gosuslugi.ru/schema/integration/house-management/}NonResidentialPremiseAcceptedParameterType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="ResidentialPremiseAcceptedParameter" type="{http://dom.gosuslugi.ru/schema/integration/house-management/}ResidentialPremiseAcceptedParameterType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="RoomAcceptedParameter" type="{http://dom.gosuslugi.ru/schema/integration/house-management/}RoomAcceptedParameterType" maxOccurs="unbounded" minOccurs="0"/>
* </choice>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GKNRelationshipStatusType", propOrder = {
"status",
"appartmentHouseAcceptedParameter",
"livingHouseAcceptedParameter",
"nonResidentialPremiseAcceptedParameter",
"residentialPremiseAcceptedParameter",
"roomAcceptedParameter"
})
@XmlSeeAlso({
ru.gosuslugi.dom.schema.integration.house_management.OGFImportStatusType.GKNRelationshipStatus.class
})
public class GKNRelationshipStatusType {
@XmlElement(name = "Status", required = true)
protected String status;
@XmlElement(name = "AppartmentHouseAcceptedParameter")
@XmlSchemaType(name = "string")
protected List<ApartmentHouseAcceptedParameterType> appartmentHouseAcceptedParameter;
@XmlElement(name = "LivingHouseAcceptedParameter")
@XmlSchemaType(name = "string")
protected List<LivingHouseAcceptedParameterType> livingHouseAcceptedParameter;
@XmlElement(name = "NonResidentialPremiseAcceptedParameter")
@XmlSchemaType(name = "string")
protected List<NonResidentialPremiseAcceptedParameterType> nonResidentialPremiseAcceptedParameter;
@XmlElement(name = "ResidentialPremiseAcceptedParameter")
@XmlSchemaType(name = "string")
protected List<ResidentialPremiseAcceptedParameterType> residentialPremiseAcceptedParameter;
@XmlElement(name = "RoomAcceptedParameter")
@XmlSchemaType(name = "string")
protected List<RoomAcceptedParameterType> roomAcceptedParameter;
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStatus(String value) {
this.status = value;
}
/**
* Gets the value of the appartmentHouseAcceptedParameter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the appartmentHouseAcceptedParameter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAppartmentHouseAcceptedParameter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ApartmentHouseAcceptedParameterType }
*
*
*/
public List<ApartmentHouseAcceptedParameterType> getAppartmentHouseAcceptedParameter() {
if (appartmentHouseAcceptedParameter == null) {
appartmentHouseAcceptedParameter = new ArrayList<ApartmentHouseAcceptedParameterType>();
}
return this.appartmentHouseAcceptedParameter;
}
/**
* Gets the value of the livingHouseAcceptedParameter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the livingHouseAcceptedParameter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLivingHouseAcceptedParameter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link LivingHouseAcceptedParameterType }
*
*
*/
public List<LivingHouseAcceptedParameterType> getLivingHouseAcceptedParameter() {
if (livingHouseAcceptedParameter == null) {
livingHouseAcceptedParameter = new ArrayList<LivingHouseAcceptedParameterType>();
}
return this.livingHouseAcceptedParameter;
}
/**
* Gets the value of the nonResidentialPremiseAcceptedParameter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the nonResidentialPremiseAcceptedParameter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNonResidentialPremiseAcceptedParameter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link NonResidentialPremiseAcceptedParameterType }
*
*
*/
public List<NonResidentialPremiseAcceptedParameterType> getNonResidentialPremiseAcceptedParameter() {
if (nonResidentialPremiseAcceptedParameter == null) {
nonResidentialPremiseAcceptedParameter = new ArrayList<NonResidentialPremiseAcceptedParameterType>();
}
return this.nonResidentialPremiseAcceptedParameter;
}
/**
* Gets the value of the residentialPremiseAcceptedParameter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the residentialPremiseAcceptedParameter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getResidentialPremiseAcceptedParameter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ResidentialPremiseAcceptedParameterType }
*
*
*/
public List<ResidentialPremiseAcceptedParameterType> getResidentialPremiseAcceptedParameter() {
if (residentialPremiseAcceptedParameter == null) {
residentialPremiseAcceptedParameter = new ArrayList<ResidentialPremiseAcceptedParameterType>();
}
return this.residentialPremiseAcceptedParameter;
}
/**
* Gets the value of the roomAcceptedParameter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the roomAcceptedParameter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRoomAcceptedParameter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link RoomAcceptedParameterType }
*
*
*/
public List<RoomAcceptedParameterType> getRoomAcceptedParameter() {
if (roomAcceptedParameter == null) {
roomAcceptedParameter = new ArrayList<RoomAcceptedParameterType>();
}
return this.roomAcceptedParameter;
}
}
|
Java
|
UTF-8
| 7,314
| 2.59375
| 3
|
[] |
no_license
|
package edu.ncsu.csc.itrust.model.old.dao.mysql;
import edu.ncsu.csc.itrust.DBUtil;
import edu.ncsu.csc.itrust.exception.DBException;
import edu.ncsu.csc.itrust.model.old.beans.ObstetricsInitBean;
import edu.ncsu.csc.itrust.model.old.beans.ObstetricsOfficeVisitBean;
import edu.ncsu.csc.itrust.model.old.beans.loaders.ObstetricsOfficeVisitLoader;
import edu.ncsu.csc.itrust.model.old.dao.DAOFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
/**
* Used for managing obstetrics office visit records related to a patient. For other
* information related to all aspects of patient care, see the other DAOs.
*
* DAO stands for Database Access Object. All DAOs are intended to be
* reflections of the database, that is, one DAO per table in the database (most
* of the time). For more complex sets of queries, extra DAOs are added. DAOs
* can assume that all data has been validated and is correct.
*
* DAOs should never have setters or any other parameter to the constructor than
* a factory. All DAOs should be accessed by DAOFactory (@see
* {@link DAOFactory}) and every DAO should have a factory - for obtaining JDBC
* connections and/or accessing other DAOs.
*/
public class ObstetricsOfficeVisitDAO {
private DAOFactory factory;
private ObstetricsOfficeVisitLoader obstetricsOfficeVisitLoader;
/**
* The typical constructor.
*
* @param factory
* The {@link DAOFactory} associated with this DAO, which is used
* for obtaining SQL connections, etc.
*/
public ObstetricsOfficeVisitDAO(DAOFactory factory)
{
this.factory = factory;
this.obstetricsOfficeVisitLoader = new ObstetricsOfficeVisitLoader();
}
/**
* Adds an obstetrics office visit record to the database
*
* @param oov ObstetricsOfficeVisitBean containing information about the visit
* @return long representing visit ID
* @throws DBException
*/
public long addObstetricsOfficeVisit(ObstetricsOfficeVisitBean oov) throws DBException {
try (Connection conn = factory.getConnection())
{
PreparedStatement ps = conn.prepareStatement("INSERT INTO obstetricsOfficeVisit " +
"(obstetricsInitRecordID, locationID, patientMID, hcpMID, apptID, visitDate, " +
"weight, bloodPressure, fetalHeartRate, lowLyingPlacentaObserved, numberOfBabies) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
ps = obstetricsOfficeVisitLoader.loadParameters(ps, oov);
ps.executeUpdate();
return DBUtil.getLastInsert(conn);
}
catch (SQLException e) {
throw new DBException(e);
}
}
/**
* Edits an existing obstetrics office visit record
*
* @param oov ObstetricsOfficeVisitBean containing edits to be made
* @throws DBException
*/
public void editObstetricsOfficeVisit(ObstetricsOfficeVisitBean oov) throws DBException {
try (Connection conn = factory.getConnection()) {
PreparedStatement ps = conn.prepareStatement("UPDATE obstetricsOfficeVisit SET " +
"obstetricsInitRecordID=?, locationID=?, patientMID=?, hcpMID=?, apptID=?, visitDate=?, " +
"weight=?, bloodPressure=?, fetalHeartRate=?, lowLyingPlacentaObserved=?, numberOfBabies=? " +
"WHERE visitID=?");
ps = obstetricsOfficeVisitLoader.loadParameters(ps, oov);
ps.setLong(12, oov.getVisitID());
ps.executeUpdate();
}
catch (SQLException e) {
throw new DBException(e);
}
}
/**
* Returns all obstetrics office visit records associated with a given obstetrics
* initialization record ID
*
* @param obstetricsInitID ID of obstetrics initialization record
* @return List of ObstetricOfficeVisitBeans associated with given obstetricsInitID
* @throws DBException
*/
public List<ObstetricsOfficeVisitBean> getObstetricsOfficeVisitByInitRecord(long obstetricsInitID) throws DBException {
List<ObstetricsOfficeVisitBean> list;
try (Connection conn = factory.getConnection()) {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM obstetricsOfficeVisit WHERE obstetricsInitRecordID=?");
ps.setLong(1, obstetricsInitID);
ResultSet rs = ps.executeQuery();
list = obstetricsOfficeVisitLoader.loadList(rs);
return list;
}
catch (SQLException e) {
throw new DBException(e);
}
}
public List<ObstetricsOfficeVisitBean> sortByVisitDate(List<ObstetricsOfficeVisitBean> list) {
Collections.sort(list, new Comparator<ObstetricsOfficeVisitBean>() {
@Override
public int compare(ObstetricsOfficeVisitBean o1, ObstetricsOfficeVisitBean o2) {
Date first = o1.getVisitDate();
Date second = o2.getVisitDate();
if (first == null && second == null) {
return 0;
} else if (first == null) {
return 1;
} else if (second == null){
return -1;
}
return second.compareTo(first);
}
});
return list;
}
/**
* Returns obstetrics office visit record by its visit ID
*
* @param visitID ID of obstetrics office visit
* @return ObstetricOfficeVisitBean containing information about the requested office visit
* @throws DBException
*/
public ObstetricsOfficeVisitBean getObstetricsOfficeVisitByID(long visitID) throws DBException {
ObstetricsOfficeVisitBean oov;
try (Connection conn = factory.getConnection()) {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM obstetricsOfficeVisit WHERE visitID=?");
ps.setLong(1, visitID);
ResultSet rs = ps.executeQuery();
oov = rs.next() ? obstetricsOfficeVisitLoader.loadSingle(rs) : null;
return oov;
}
catch (SQLException e) {
throw new DBException(e);
}
}
/**
* Returns all obstetrics office visit records associated with a given patient MID
*
* @param patient MID
* @return List of ObstetricOfficeVisitBeans associated with given patient MID
* @throws DBException
*/
public List<ObstetricsOfficeVisitBean> getObstetricsOfficeVisitByMID(long patientMID) throws DBException
{
List<ObstetricsOfficeVisitBean> list;
try (Connection conn = factory.getConnection())
{
PreparedStatement ps = conn.prepareStatement("SELECT * FROM obstetricsOfficeVisit WHERE patientMID = ?");
ps.setLong(1, patientMID);
ResultSet rs = ps.executeQuery();
list = obstetricsOfficeVisitLoader.loadList(rs);
return list;
}
catch (SQLException e)
{
throw new DBException(e);
}
}
/**
* Deletes an obstetrics office visit that matches the visitID
* This will remove from each of the obstetric init records
*
* @param visitID the ID of the visit to be deleted
* @return true if deletion was successful
* @throws DBException
*/
public boolean deleteObstetricsOfficeVisit(long visitID) throws DBException {
try (
Connection conn = factory.getConnection();
PreparedStatement ps = conn.prepareStatement("DELETE FROM obstetricsOfficeVisit WHERE visitID = ?")
) {
ps.setLong(1, visitID);
boolean success = ps.executeUpdate() == 1;
return success;
}
catch (SQLException e) {
throw new DBException(e);
}
}
}
|
Java
|
UTF-8
| 4,250
| 2.28125
| 2
|
[] |
no_license
|
package com.example.admin.iposapp.database;
/**
* Created by admin on 21/06/2016.
*/
public interface InterfaceClientSchema {
String tableName = "PERSONA";
String columnId = "clave";
String columnName = "nombre";
String columnNames = "nombres";
String columnLastName = "apellidos";
String columnAddress = "domicilio";
String columnPhone1 = "telefono1";
String columnPhone2 = "telefono2";
String columnRfc = "rfc";
String columnBalance = "saldo";
String columnCity = "ciudad";
String columnSellerId = "vendedor_id";
String columnPostalCode = "codigo_postal";
String columnPriceListId = "lista_precioid";
String columnCreditLimit = "limite_credito";
String columnDays = "dias";
String columnStreets = "calles";
String columnContact1 = "contacto1";
String columnContact2 = "contacto2";
String columnEmail1 = "correo1";
String columnEmail2 = "correo2";
String columnSerie = "serie";
String columnCountry = "pais";
String columnState = "estado";
String columnNeighborhood = "colonia";
String columnIntNumber = "numero_interior";
String columnExtNumber = "numero_exterior";
String columnIeps = "cuenta_ieps";
String columnAddresService = "servicio_domicilio";
String columnDeadline = "plazo";
String columnPrice = "precio";
String columnPayday = "dia_pago";
String columnReview = "revision";
String columnCard = "tarjeta";
String columnCredit = "credito";
String columnCheck = "cheque";
String columnTransfer = "transferencia";
String columnBlocked = "bloqueado";
String createQuery = "CREATE TABLE IF NOT EXISTS "
+ tableName
+ " ("
+ columnId + " TEXT NOT NULL,"
+ columnName + " TEXT,"
+ columnNames + " TEXT,"
+ columnLastName + " TEXT,"
+ columnAddress + " TEXT,"
+ columnPhone1 + " TEXT,"
+ columnPhone2 + " TEXT,"
+ columnRfc + " TEXT,"
+ columnBalance + " DECIMAL,"
+ columnCity + " TEXT,"
+ columnSellerId + " INTEGER,"
+ columnPostalCode + " INTEGER,"
+ columnPriceListId + " INTEGER,"
+ columnCreditLimit + " DECIMAL,"
+ columnDays + " INTEGER, "
+ columnStreets + " TEXT, "
+ columnContact1 + " TEXT, "
+ columnContact2 + " TEXT, "
+ columnEmail1 + " TEXT, "
+ columnEmail2 + " TEXT, "
+ columnSerie + " TEXT, "
+ columnCountry + " TEXT, "
+ columnState + " TEXT, "
+ columnNeighborhood + " TEXT, "
+ columnIntNumber + " TEXT, "
+ columnExtNumber + " TEXT, "
+ columnIeps + " TEXT, "
+ columnAddresService + " TEXT, "
+ columnDeadline + " TEXT, "
+ columnPrice + " TEXT, "
+ columnPayday + " TEXT, "
+ columnReview + " TEXT, "
+ columnCard + " TEXT, "
+ columnCredit + " TEXT, "
+ columnCheck + " TEXT, "
+ columnTransfer + " TEXT, "
+ columnBlocked + " TEXT"
+ ")";
String [] clientColumns = new String[] {columnId, columnName, columnNames, columnLastName,
columnAddress, columnPhone1, columnPhone2, columnRfc,
columnBalance, columnCity, columnSellerId,
columnPostalCode, columnPriceListId, columnCreditLimit,
columnDays, columnStreets, columnContact1,
columnContact2, columnEmail1, columnEmail2, columnSerie,
columnCountry, columnState, columnNeighborhood,
columnIntNumber, columnExtNumber, columnIeps,
columnAddresService, columnDeadline, columnPrice,
columnPayday, columnReview, columnCard, columnCredit,
columnCheck, columnTransfer, columnBlocked};
}
|
C
|
UTF-8
| 1,075
| 2.8125
| 3
|
[] |
no_license
|
/*
** check.c for my_survey in /home/decomb_s/Backup/ACC2
**
** Made by Sylvain Decombe
** Login <decomb_s@epitech.net>
**
** Started on Wed Mar 26 14:53:27 2014 Sylvain Decombe
** Last update Sun Mar 30 00:20:30 2014 Sylvain Decombe
*/
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "survey.h"
void check2(char **stock)
{
int y;
int err;
y = 0;
err = check_validity(stock);
if (err == 0)
gere_displ(stock);
else if (err == -1)
my_putstr("Error, put a valid survey. \n");
}
int compar(int count, int max)
{
if (count == max)
return(0);
else
return(-1);
}
int check_validity(char **stock)
{
int y;
int k;
int j;
j = my_getnbr(stock[0]);
k = 0;
y = 1;
while (stock[y] != NULL)
{
if (stock[y][0] == 'O' && stock[y][1] == 'Q')
k++;
if (stock[y][0] == 'C' && stock[y][1] == 'Q')
k++;
if (stock[y][0] == 'A' && stock[y][1] == ':')
k++;
y++;
}
if (compar(k, j) == 0)
return (0);
return (-1);
}
|
Markdown
|
UTF-8
| 11,274
| 3.234375
| 3
|
[] |
no_license
|
在第三模块中,我们主要讲解了基于常见组件的微服务场景的相关内容,因为市面上已经存在比较流行的开源组件,因此你只需要搞清楚组件的原理即可。从这一讲开始,我们将正式进入第四模块——微服务场景进阶内容的讲解。
在介绍业务场景之前,我们先来谈谈对微服务的一些理解。
单体式架构 VS 微服务架构
为了让你快速理解单体式架构与微服务架构之间的区别,我们先来看一个新零售系统的例子。
比如门店(门店分为自营店和加盟店)想研发一款新零售系统进行商品售卖,它需要包含订单、营销、门店、商品、加盟商、会员等功能模块。
在搭建新零售系统架构时,如果我们使用单体式架构进行设计,它的架构图如下所示:
新零售系统:单体式架构图
从图中我们发现,单体式架构将所有模块的代码存放在一个应用中,所有模块的数据存放在一个数据库中。在这种架构模式下,当业务功能增加到一定程度,我们只要稍微有点小改动,就有可能影响整个应用的其他功能,这种事情在我们公司实在了发生太多次了。
虽然每次不小心把公司系统弄崩后,我们都会进行复盘总结,后期需要 Code Review、合理设计、仔细评估风险、一起评审方案,但是就算这么做了这种事情还是会发生。因此,随着风险控制流程的复杂化,代码发布的频率也就越来越慢,最终导致系统迭代不了了,而别家公司交付新功能的效率却是我们的 10 倍+。
面对这种情况,我们必须把各个模块的代码进行拆分,以免相互影响。于是我们把单体式架构拆分为如下图所示的微服务架构。
新零售系统:微服务架构图
在上面的架构图中,我们发现 1 个应用被拆分为了 6 个应用,它们分别负责订单、营销、商品、门店、加盟商、会员等相关业务逻辑,且每个模块的数据分别存放在不同数据库中。如果各个应用之间彼此存在依赖关系,我们可以通过接口、消息、共享缓存、数据库同步等方式解决。
微服务的好处
将单体式架构迁移到微服务架构后,确实为我们带来了诸多便利,下面我们具体谈谈微服务的好处有哪些。
易于扩展: 某个模块的服务器处理能力不足时,我们在那个模块所处应用的服务器中增加节点就行。
发布简单: 在单体式架构中,因为所有代码存放在一个应用中,所以每次发布代码时,我们需要连带整个应用一起发布,使得整个团队人员都得配合集成测试、统一协调排期。但是迁移到微服务架构后,我们只需要保证对外契约不变就行,发布过程变得特别简单了。
技术异构: 因为各个服务之间相互独立、互不影响,所以我们只需要保证外部契约(一般指接口)不变即可,而内部想使用什么语言或框架都行。
便于重构: 在单体式架构中,因为系统重构的影响面较大,所以在做任何改动时我们都要小心翼翼,以至于我们不敢尝试大的重构或优化,最终出现代码加速腐烂的情况。但是在微服务架构中,因为我们把模块间的影响进行了隔离,所以大大增加了重构的灵活性。
微服务的痛
在产品研发过程中,我认为引入一个技术解决一个业务问题并不难,难的是我们能否合理评估技术风险,这个观点对微服务同样适用。因此,我将通过三讲的内容聊聊微服务会带来哪些问题,这部分内容不管是在面试中还是日常技术设计中,对我们的帮助都会非常大。
因篇幅有限,这一讲我们主要聊聊微服务的两个痛点,其他的痛点会分别在 14讲、15讲中详细介绍。
(1)微服务职责划分
微服务的难点在于无法对一些特定职责进行清晰划分,比如这个特定职责它应该归属于服务 A 还是服务 B?为了方便你理解这部分内容,下面我们举几个例子说明下。
比如一个能根据商品 ID 找出商品信息的接口,我们把它放在商品服务中就行。再比如单个用户的所有订单,我们把它放在订单服务中就行。
业务逻辑服务归属与业务人员的划分可能存在关系,比如每个商品在每个门店的库存应该放在商品服务还是门店服务呢?因为各自门店的商品库存由各自门店的运营人员管理,最终我们决定把它放在门店系统中。
业务逻辑服务归属与产品人员的划分可能存在关系,比如业务部门提了一个新需求,需要我们设计一个能对商品进行相关设置的功能,使得某些门店只能卖某些商品。此时这个功能应该放门店服务还是放商品服务呢?这就需要看这个功能由哪条业务线的产品负责人负责了,比如由商品系统的产品经理负责,我们就把它放商品服务中就行;比如由门店的产品经理负责,把它放门店服务中就行。
业务逻辑服务归属与工期可能存在关系,紧接着上面的例子——实现某些门店只能卖某些商品的需求,最终我们依据 DDD 中的相关原则定了一个划分逻辑,特定门店的特定商品的上架功能放在门店服务中,因为特定商品由门店的运营人员负责上架。但是这种划分逻辑会出现这么一个情况:比如门店服务的开发人员很忙,没空接这个需求,而商品服务的开发人员刚好有空,但他们对门店服务的逻辑不了解。于是,商品的开发人员提议,如果我们想在 2 周内实现上线这个需求,则必须把这个功能放在商品服务中。这种方案看起来比较诡异,不过最终他们确实把这个功能放在了商品服务中,因为再优雅的设计也抵不过业务部门要求的上线压力。
业务逻辑服务归属还与组织架构可能存在关系,通过康威定律我们就能很快明白。
Conway's law is an adage named after computer programmer Melvin Conway, who introduced the idea in 1967. It states that. organizations which design systems ... are constrained to produce designs which are copies of the communication structures of these organizations.
康威是个程序员,他在 1967 年提出:设计系统的组织在设计系统时,会设计出基于这些组织的沟通结构的系统。
关于微服务职责划分的痛,通过前面几个例子的介绍,你应该隐隐约约有所感觉了,接下来我们再说一个进销存供应链系统的例子,让你有更深刻的体会。
这里的进指的是供应商的采购,销指的是门店的销售单,存指的是一些中央仓库的库存,且进销存供应链系统与新零售系统之间紧密结合,对应的架构图如下所示。
供应链系统+新零售系统结合后的架构图
在这个架构中,原本门店的商品库存是由门店运营人员(即新零售业务)负责,中央仓库库存由供应链人员管理。后来,不知什么原因领导要求更改供应链总监职责,此时供应链总监需要同时负责门店商品库存+中央仓库库存。
我们先来看看原职责划分情况,对应关系如下图所示。
原职责划分对应关系图
在图中我们可以看到,在原有的组织架构中,新零售业务的产研只对接新零售业务,供应链业务的产研只对接供应链业务。现如今,门店库存管理职责需要划分到供应链业务中,也就是说新零售业务的产研不再负责这个需求,而是交由供应链业务的产研负责了。此时供应链业务的产研会把门店库存积极地搬运到供应链的库存管理中,因为门店库存管理好了,供应链业务方的绩效也就好了,产研的绩效也就高了,年终奖也就更多了。
因此,在现实场景中,微服务职责的划分会受太多人为因素的影响,我们也就能理解为什么市面上关于服务职责划分原则的相关资料太少了。
(2)微服务粒度拆分
在我所经历的企业中,发现大家都会遇到微服务太多的情况。因此,我们有必要通过一个加盟商的例子把服务粒度的内容详细介绍下。
还是以上面的新零售系统为例,刚开始系统只有登录和信息管理功能,我们把这些功能存放在一个服务中就行,实现起来比较简单。随着加盟商的加入,因为加盟商准入、开店、退出都涉及费用问题,因此我们又需要增加财务功能(如应收、应付、实收、实付、退款、对账等)。
随着业务的逐步开展,我们又需要增加加盟商员工管理(员工管理、部门管理、权限管理)返点、加盟商子门店管理等功能,而此时的加盟商管理系统只有一个服务,你觉得合适吗?答案肯定是不合适。那微服务的粒度到底拆分多少比较合适呢?比如什么时候拆分加盟商服务比较合适?做加盟商的财务功能时还是加盟商的员工管理功能时?做加盟商的返点功能时还是加盟商的子门店管理功能时?
一般来说,在设计新功能之前,我们会遵循一个大致原则:根据新的微服务的大小,安排 3-4 人设计即可。
但是当一个微服务设计出来后,它的改动成本一般不高,除非实现大规模重构,为了防止开发人员出现闲置的情况,公司会安排他们设计新的功能。而设计新功能时,开发人员倾向于将独立的功能存放在新的服务中,导致加盟商的财务、员工管理及返点功能都被独立出来了。为了避免这种情况的发生,因此,在对微服务粒度进行拆分时,我们还需要考虑另外一个因素——绩效。
大家都知道,开发人员的绩效很难实现量化,而微服务数可谓是一个难得的可量化指标。在规章制度上,虽然我们不会把微服务数列为一个 KPI(这样微服务数绝对会爆发),但是开发人员在阐述个人工作量时偶尔还是会提微服务数,如果其他同事听后开始留心,潜意识里也喜欢上做微服务,随着时间的推移,微服务就会越来越多,甚至出现人均 5 个服务数的奇葩情况。
说到这你可能想说,会不会是你们的微服务分得太细了?说得太对了,我们也是这样认为的,于是开始控制服务数,这种方式确实起到了一定的效果。
那服务的粒度大小控制在什么范围比较合适呢?我只能说没有确切的答案,需要根据实际业务情况来定。
总结与预告
以上介绍的微服务的痛点是根据我的实际工作经历总结出来的,因此为了便于你理解,每个痛点我都会举一个实际的例子进行说明。这一讲我们先讲 2 个痛点,14 讲我们将继续讲微服务的其他痛点。
这里留一个思考题:在实际工作中,你是如何控制微服务数量的?欢迎你在留言区与我互动、交流。另外,如果你喜欢此专栏,欢迎分享给更多的好友看到哦。
|
Java
|
UTF-8
| 2,863
| 2.640625
| 3
|
[] |
no_license
|
package com.it_uatech.jdbcOperations;
import com.it_uatech.dao.AuthorDao;
import com.it_uatech.domain.Author;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("ConstantConditions")
@Repository("authorDao")
public class AuthorJDBCOperations implements AuthorDao {
private final NamedParameterJdbcTemplate namedJdbcTemplate;
private final static AuthorRowMapper authorRowMapper = new AuthorRowMapper();
public AuthorJDBCOperations(NamedParameterJdbcTemplate namedJdbcTemplate) {
this.namedJdbcTemplate = namedJdbcTemplate;
}
@Override
public int count() {
final Map<String, Object> params = new HashMap<>(1);
String query = "select count(*) from author";
return namedJdbcTemplate.queryForObject(query, params, Integer.class);
}
@Override
public Author getById(int id) {
final Map<String, Object> params = new HashMap<>(1);
params.put("id", id);
String query = "select * from author where id = :id";
try {
return namedJdbcTemplate.queryForObject(query, params, authorRowMapper);
}catch (EmptyResultDataAccessException ex){
return null;
}
}
@Override
public List<Author> getAllAuthor() {
String query = "select * from author";
return namedJdbcTemplate.query(query, authorRowMapper);
}
@Override
public void deleteById(int id) {
final Map<String, Object> params = new HashMap<>(1);
params.put("id", id);
String query = "delete from author where id = :id";
namedJdbcTemplate.update(query, params);
}
@Override
public void insert(Author author) {
final Map<String, Object> params = new HashMap<>(3);
params.put("id", author.getId());
params.put("firstName", author.getFirstName());
params.put("secondName", author.getSecondName());
String query = "insert into author (id, firstName, secondName) values (:id, :firstName, :secondName) on duplicate key update id= :id";
namedJdbcTemplate.update(query,params);
}
private static class AuthorRowMapper implements RowMapper<Author> {
@Override
public Author mapRow(ResultSet resultSet, int i) throws SQLException {
return new Author(resultSet.getInt("id"),
resultSet.getString("firstName"),
resultSet.getString("secondName"));
}
}
public AuthorRowMapper getAuthorRowMapper() {
return authorRowMapper;
}
}
|
C#
|
UTF-8
| 985
| 3.59375
| 4
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace _26._4_线程操作之线程休眠
{
class Program
{
public static void method()
{
string state;
for (int i = 1; i <= 5000; i++)
{
state = Thread.CurrentThread.ThreadState.ToString();
if (i % 5 == 0)
{
Console.WriteLine("当前线程状态:{0}", state);
}
}
}
static void Main(string[] args)
{
//委托实例
ThreadStart ts = new ThreadStart(method);
Thread t = new Thread(ts);
t.Start();
while (t.IsAlive)
{
Console.WriteLine("线程开始执行!");
Thread.Sleep(1);
}
Console.ReadLine();
}
}
}
|
Java
|
UTF-8
| 248
| 2.375
| 2
|
[] |
no_license
|
/**
* 类的描述
*
* @Author lirf
* @Date 2018/4/15 17:57
*/
public class StringTest {
public static void main(String[] args) {
String s1 = "1" + "2";
String s2 = "abcd";
System.out.println(s1 == s2);
}
}
|
PHP
|
UTF-8
| 465
| 2.875
| 3
|
[] |
no_license
|
<?php
/**
* 跳转结果
* @author julian.song
*/
class ResultRedirect implements Result{
public function createResult(array $resultMap){
$response=ResponseContext::getResponse();
$arguments=array();
foreach($resultMap['arguments'] as $key=>$val){
array_push($arguments,$key."=".$response->get($val));
}
$resultMap['value'].=count($arguments)?"?".implode("&",$arguments):"";
header("Location: ".$resultMap['value']);
;
}
}
?>
|
Java
|
UTF-8
| 1,492
| 2.421875
| 2
|
[] |
no_license
|
package com.ufrpe.ava.negocio;
import java.util.ArrayList;
import com.ufrpe.ava.excecoes.ObjetoJaExistenteExcepitions;
import com.ufrpe.ava.excecoes.ObjetoNaoExistenteExcepitions;
import com.ufrpe.ava.negocio.entidades.Usuario;
import com.ufrpe.ava.negocio.controladores.ControladorUsuario;
public class AvaFachada implements IAvaFachada {
private ControladorUsuario controladorUsuario;
public AvaFachada() {
controladorUsuario = new ControladorUsuario();
}
@Override
public Usuario buscarLogin(String cpf, String senha) throws ObjetoNaoExistenteExcepitions {
Usuario usuario = controladorUsuario.buscarLogin(cpf, senha);
return usuario;
}
@Override
public ArrayList<Usuario> selecionarTudo() {
// TODO Auto-generated method stub
return null;
}
@Override
public void cadastrarAluno(String nome, String cpf, String email, String senha, int codCurso, String tipo,
int grad) throws Exception, ObjetoNaoExistenteExcepitions, ObjetoJaExistenteExcepitions {
// TODO Auto-generated method stub
controladorUsuario.cadastrarAluno(nome, cpf, email, senha, codCurso, tipo, grad);
}
@Override
public void cadastarProfessor(String nome, String cpf, String email, String senha, int idDepartamento,
int grad) throws Exception, ObjetoNaoExistenteExcepitions, ObjetoJaExistenteExcepitions {
controladorUsuario.cadastrarProfessor(nome, cpf, email, senha, idDepartamento, grad);
}
}
|
Java
|
UTF-8
| 11,286
| 1.882813
| 2
|
[] |
no_license
|
package com.example.foxtrotfrontend;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NavUtils;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class NewReportActivity extends AppCompatActivity {
String[] pests = {"Pea and been weevil", "Downy mildew", "Aphid", "Chocolate spot", "Bean seed beetle", "Bean rust"};
Double lat = null;
Double lon = null;
Bitmap imageBitmap = null;
Integer severity = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_report);
Intent intent = getIntent();
getSupportActionBar().setTitle("New Report");
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.select_dialog_item, pests);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.pestName);
actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
String flag = intent.getStringExtra("I_CAME_FROM");
if((flag != null) && flag.equals("initial")){
//you came from a1 activity
actv.setText("Bean Rust");
}
actv.setThreshold(1);//will start working from first character
// Setting Button to Go To Map Activity
Button buttonLoc = (Button) findViewById(R.id.location);
buttonLoc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pickPointOnMap();
}
});
// Setting Button to Go To Camera Activity
Button buttonCam = (Button) findViewById(R.id.cameraButton);
buttonCam.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
// Setting Button to Go Back To Main Once Sent
Button buttonSend = (Button) findViewById(R.id.Send);
buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendIntent();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
static final int PICK_MAP_POINT_REQUEST = 999; // The request code
private void pickPointOnMap() {
Intent pickPointIntent = new Intent(this, MapsActivity.class);
startActivityForResult(pickPointIntent, PICK_MAP_POINT_REQUEST);
}
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
private void sendIntent() {
EditText pestName = (EditText) findViewById(R.id.pestName);
EditText cropName = (EditText) findViewById(R.id.cropName);
EditText description = (EditText) findViewById(R.id.description);
if (pestName.getText().toString().equals("")){
Toast.makeText(this, "Please insert a pest", Toast.LENGTH_LONG).show();
return;
}
if (cropName.getText().toString().equals("")){
Toast.makeText(this, "Please insert a crop", Toast.LENGTH_LONG).show();
return;
}
if (severity == null){
Toast.makeText(this, "Please give a severity", Toast.LENGTH_LONG).show();
return;
}
if (lat == null){
Toast.makeText(this, "Please give a location", Toast.LENGTH_LONG).show();
return;
}
if (imageBitmap == null){
Toast.makeText(this, "Please give an image", Toast.LENGTH_LONG).show();
return;
}
Random random = new Random();
Date date = new Date();
Integer idval = random.nextInt();
try {
ReportHTTP reportHTTP = new ReportHTTP("http://10.248.103.59:4567");
Boolean success = reportHTTP.newReport(idval, date, lat, lon, pestName.getText().toString(), description.getText().toString(), "", imageBitmap, severity.toString());
if (success){
Set<String> idvals;
SharedPreferences sharedPreferences = getSharedPreferences("REPORTS", MODE_PRIVATE);
idvals = sharedPreferences.getStringSet("MYREPORTS", null);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
String currentTime = (sdf.format(cal.getTime()));
String newid = currentTime + " - " + pestName.getText().toString();
if (idvals == null){
idvals = new HashSet<>();
idvals.add(newid);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("MYREPORTS", idvals);
editor.commit();
}
else{
Set<String> newvals = new HashSet<>();
newvals.addAll(idvals);
newvals.add(newid);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("MRREPORS", newvals);
editor.commit();
}
NavUtils.navigateUpFromSameTask(this);
Toast.makeText(this, "Report Sent", Toast.LENGTH_LONG).show();
}
else{
Set<String> idvals;
SharedPreferences sharedPreferences = getSharedPreferences("REPORTS", MODE_PRIVATE);
idvals = sharedPreferences.getStringSet("MYREPORTS", null);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
String currentTime = (sdf.format(cal.getTime()));
String newid = currentTime + " - " + pestName.getText().toString();
if (idvals == null){
idvals = new HashSet<>();
idvals.add(newid);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("MYREPORTS", idvals);
editor.commit();
}
else{
Set<String> newvals = new HashSet<>();
newvals.addAll(idvals);
newvals.add(newid);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("MRREPORS", newvals);
editor.commit();
}
NavUtils.navigateUpFromSameTask(this);
Toast.makeText(this, "Report Sent", Toast.LENGTH_LONG).show();
}
} catch (Exception e){
e.printStackTrace();
Set<String> idvals;
SharedPreferences sharedPreferences = getSharedPreferences("REPORTS", MODE_PRIVATE);
idvals = sharedPreferences.getStringSet("MYREPORTS", null);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
String currentTime = (sdf.format(cal.getTime()));
String newid = currentTime + " - " + pestName.getText().toString();
if (idvals == null){
idvals = new HashSet<>();
idvals.add(newid);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("MYREPORTS", idvals);
editor.commit();
}
else{
Set<String> newvals = new HashSet<>();
newvals.addAll(idvals);
newvals.add(newid);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("MYREPORTS", newvals);
editor.commit();
}
NavUtils.navigateUpFromSameTask(this);
Toast.makeText(this, "Report Sent", Toast.LENGTH_LONG).show();
}
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.severity1:
if (checked)
severity = 1;
break;
case R.id.severity2:
if (checked)
severity = 2;
break;
case R.id.severity3:
if (checked)
severity = 3;
break;
case R.id.severity4:
if (checked)
severity = 4;
break;
case R.id.severity5:
if (checked)
severity = 5;
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_MAP_POINT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
LatLng latLng = (LatLng) data.getParcelableExtra("picked_point");
Toast.makeText(this, "Point Chosen" + latLng.latitude + " " + latLng.longitude, Toast.LENGTH_LONG).show();
lat = latLng.latitude;
lon = latLng.longitude;
}
}
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
}
}
}
|
Markdown
|
UTF-8
| 21,675
| 2.59375
| 3
|
[] |
no_license
|
# TS流解析【PCR】自己的总结 - zp704393004的专栏 - CSDN博客
2018年08月30日 18:19:49[原来未知](https://me.csdn.net/zp704393004)阅读数:2227
http://www.cnblogs.com/ztteng/articles/3166025.html
http://blog.csdn.net/liuhongxiangm/article/details/8981032
http://blog.sina.com.cn/s/blog_6b94d5680101ton7.html
http://blog.csdn.net/jl2011/article/details/47044647
## 二.TS流包含的内容
一段TS流,必须包含PAT包、PMT包、多个音频包、多个视频包、多个PCR包、以及其他信息包PSI。
解析TS流数据的流程:查找PID为0x0的包,解析PAT,PAT包中的program_map_PID表示PMT的PID;查找PMT,PMT包中的elementary_PID表示音视频包的PID,PMT包中的PCR_PID表示PCR的PID,**有的时候PCR的PID跟音频或者视频的PID相同,说明PCR会融进音视频的包,注意解析,有的时候PCR是自己单独的包;CAT、NIT、SDT、EIT的PID分别为: 0x01、0x10、0x11、0x12**。
PSI被分为4个表结构,他们应被进一步划分为各个段(SECTION)并插入到传输流TS分组中,一些带有预先规定的PID,另一些带有用户可选的PID。
**TS包中净荷所承载的信息包括以下3种:**
• **1、视频/音频的PES包以及辅助数据**
• **2、描述单路节目复用信息的节目映射表(PMT)**
• **3、描述单路节目复用信息的节目关联表(PAT)**
• (1)系统复用时,对视频和音频的ES流进行打包,形成视频和音频的PES流,**辅助数据不需要打成PES包**.
• (2)视频和音频的PES包以**一帧编码图像为单位**,音频PES包恒定长度,视频PES包长度可变。
• (3)PES包的长度通常都是远大于TS包的长度,一个PES包必须由整数个TS包来传送,没装满的TS包由填充字节填充。
• (4)TS包长度固定,188字节,有效净荷184字节。
一个PMT表包含了与**单路节目**复用有关的节目信息,典型的构成包括1路视频ES流,2-5路音频ES流,1路或多路辅助数据。
• 进行TS流复用时,**各路ES流被分配了唯一的PID,**ES流与被分配的PID值间的关系构成了一张表,称为节目映射表PMT。
• PMT完整描述了**一路**节目由哪些ES流组成,他们的PID分别是什么。
• MPEG-2传送层中,**传送PMT表的码流称为控制码流**,和其他ES流一样,在TS包的净荷中传送,分配唯一的PID.
• PAT包含了与多路节目复用有关的控制信息。
• PAT描述了系统级复用中传送每路节目PMT的码流的PID。
• PAT作为一个独立的码流,装载在TS包的净荷中传送,分配唯一的PID。传送PAT的码流的PID值定义为固定的数值“0”。
**• 若复用时(mux时)遇到有不同码流的PID值相同,则必须把它记录下来,记录在PAT和PMT中**。
• 允许单路数字电视节目可由其中某些节目流(例如视频,不同音频,不同字幕)任意组合构成,节目可根据需要ES码流进行增加或删除。
• 允许对多路节目进行灵活复用,若其中某些节目流发生变化,只需要将PAT和PMT做相应修改即可。
• 能够在TS级上提供本地节目插入和条件接收等对广播界非常重要的功能。


**PES包格式:**

**PES再打包成TS流或PS流,往往一个PES会分存到多个ts包中**
每个ES都由若干个**存取单元(AU)**组成,每个视频AU或音频AU都是由头部和编码数据两部分组成,1个AU相当于编码的1幅视频图像或1个音频帧,也可以说,每个AU实际上是编码数据流的显示单元,即相当于解码的1幅视频图像或1个音频帧的取样。
简而言之:**一个AU对应一个帧,一个ES由多个帧组成**
- **PAT**
– **每个TS流一个,每隔0.5秒重复。**
– **描述TS流中有多少个节目。**
– **包含该表的TS包的PID为0,便于识别。**
– **PAT的payload中传送特殊PID的列表,每个PID对应一个节目。**
– **这些PID是描述每个独立节目详细信息的指针。**
– **PID指向PMT表。**

• **PMT**
– **对应TS包有特殊的PID和特殊的payload。**
– **PMT的PID由PAT传送。**
– **例如要接收节目3时,先从PAT的payload中的所有PID列表中选出节目3的PID为1FF3hex,然后查找包头中PID=1FF3hex的TS包,就是节目3的PMT。**
– **PMT包含该节目中所有ES流(视频、音频或数据)的PID。**
****
一个节目可能有多个视频和音频流,解码器必须选择2个PID,一个视频流的PID(100hex),一个音频流的PID(200hex)。
此后解码器只收集这些TS包,**解复用,重新组成PES包,这些PES包再送到视频或音频解码器。**
**传输过程中TS流的结构也可能发生改变。解码端机顶盒,如DVB-S,必须连续检测TS流瞬时结构,读出PAT和PMT,做自适应调整。**
• PAT和PMT读出以后,用户确定出一个节目的两个PID:
待解码视频信号的PID(如100hex)
待解码音频信号的PID(如200hex)
解码器只处理这两个PID的TS包:
**解复用过程中,PID为100hex的所有TS包集合成视频PES包,送到视频解码器。**
** 同样,PID为200hex的所有TS包重新集合成音频PES包,送到音频解码器。**
如果ES流没有加扰,这时可以直接解码。
对付费电视或许可证和地域限制等情况,ES流利用电子码进行传输保护。
– ES流利用各种方法进行混扰,接收端必须配有附加硬件并授权。
– 附加硬件必须有TS流中合适的解扰和授权数据。
**– 因此TS流中传送一个特殊的表CAT(conditionalaccess table)**
**• CAT提供了TS流其他数据包的PID,该数据包传送了解扰所需信息**:
– ECM(entitlement control message) 用于传送加扰码
– EMM(entitlement management message) 用于用户管理
• 只有ES流本身可以加扰,TS包头、表格和**adaptation field**不能加扰。
• 解扰本身在MPEG解码器以外的附加硬件设备进行,附加硬件与解扰方法相关,可以做成智能板卡通过CI(common interface)插入机顶盒。
• 在MPEG解码器做进一步处理之前,TS流在该硬件设备中循环。
• ECM和EMM的信息,以及用户的个人码可以将码流解扰。

– 亮度信号采样频率13.5MHz,色度信号6.75MHz。27MHz是采样频率的倍数,作为发送端MPEG编码器所有处理过程的参考或基本频率。
– 编码器中27MHz振荡器作为系统时钟(STC)的输入。
– STC是42bit计数器,由27MHz时钟计数,溢出后重新从0开始。
– 接收端也必须提供STC,其27MHz振荡器和42bit计数器必须与编码器STC完全同步。
MPEG码流中需传送参考信息——**PCR(program clock reference),即在固定时刻将最新的STC计数器值复制到TS流中**
**• 码流中传送的PCR值必须足够多,有最大间隔的限制;而且要相对准确,没有抖动。**
**MPEG标准规定:**
**– 每个节目PCR的最大间隔为40ms。**
**– PCR的抖动小于±500ns。**
• PCR如果出错:
– 本来应该显示彩色图像,却显示出黑白图像。
– TS流重复用时会出现抖动,因为TS包顺序改变,但其中PCR信息却没变。经常会有最大±30μs的PCR抖动,该问题许多机顶盒可以解决。
• **PCR信息在相应节目TS包的adaptation field中传送**,而TS包类型的准确信息可以从PMT中获得。
• 节目时钟同步以后,视音频编码就可以锁定系统时钟进行了。
• 欧洲DVB项目组和美国ATSC项目组都定义了数字视音频节目传输的附加信息,以便简化机顶盒操作,使其更加人性化:
– 在TS流中传送节目名称来分辨不同节目;
• MPEG-2为扩展留有空间,在PSI、PMT和CAT之外,**TS流中还可以有private tables,定义了用户表的结构以及如何将用户表插入到TS流中**。
**TS包**头定义:
typedef struct TS_packet_header
{
unsigned sync_byte : 8; //同步字节, 固定为0x47,表示后面的是一个TS分组
unsigned transport_error_indicator : 1; //传输误码指示符
unsigned payload_unit_start_indicator : 1; //有效荷载单元起始指示符
unsigned transport_priority : 1; //传输优先, 1表示高优先级,传输机制可能用到,解码用不着
unsigned PID : 13; //PID
unsigned transport_scrambling_control : 2; //传输加扰控制
unsigned adaption_field_control : 2; //自适应控制 01仅含有效负载,10仅含调整字段,11含有调整字段和有效负载。为00解码器不进行处理
unsigned continuity_counter : 4; //连续计数器 一个4bit的计数器,范围0-15
} **TS_packet_header; //总共32位,4个字节**
****TS包, 很多地方packet译为分组,即传输分组,XX分组****
- **sync_byte**
是包中的第一个字节,TS包以固定的8bit的同步字节开始,所有的TS传送包,同步字都是唯一的OX47,用于建立发送端和接收端包的同步。
MPEG-2解码器接收到MPEG-2 TS流时,首先检测包结构,在TS流中查找同步字节:
总是OX47,总位于TS包开始位置,固定间隔为188字节。同时满足这两个条件,可以确定同步。
如果出现一个字节为47hex(OX47),解码器将检测这个字节前后n倍188字节的位置是否也是同步字节。
如果是,则当前字节为同步字节;否则,当前字节只是码流中偶尔出现的47hex,不是同步字节。
接收端收到5个TS包之后开始同步。丢包3个之后解码器即失步,需重新同步。
- **transport_error_indicator**
用于从解码器向分接器指示传输误码。若这个比特被设置,表示此TS包中所携带的净荷信息有错误,无法使用。
传输错误标志位,一般传输错误的话就不会处理这个包了
- **payload_unit_start_indicator**
有效负载的开始标志
标志PES包头以及包含节目特定信息的表(PMT,PAT)的头是否出现在该包中,在失步后的重新同步中起着重要的作用
一个PES包会被封装在很多小的TS包中,该标识指示是否是一个PES包的第一个TS包,用于重新同步
- **PID**
PID是识别TS包的重要参数,用来识别TS包所承载的数据类型。在TS码流生成时,每一类业务(视频,音频,数据)的基本码流均被赋予一个不同的识别号PID,解码器借助于PID判断某一个TS包属于哪一类业务的基本码流。
** //0X00 -> PAT, 0x01->CAT, PMT与NIT的TS包的PID在PAT中指定**
** //0X1FFF->空分组、空包, 0X0002-0X000F也被保留**
** //ISO/IEC13818-1中定义,通过传输流传送PSI表时,****PSI应被划分为一个或多个段(SECTION)后, 将SECTION映射到传输流中进行传送,****ISO/IEC13818-1 中定义了这种传输段(SECTION)的语法结构,通过这种结构,将PSI的数据填充到传输流中进行传送. 为什么要把PSI划为多个SECTION来传输了,一次传输不就行了? 因为每个TS包的数据负载能力是有限的,即每个TS包的长度是有限的,所以当有些PSI表很长很大时,就需要将表拆分成一个一个SECTION语法数据段,再把这钟结构的SECTION填充到TS包中进行传输 **
** 【每一个段的长度不一,一个段的开始由TS包的有效负载中的p**ayload_unit_start_indicator**来标识】**

if (adaption_field_control == '10' || adaption_field_control == '11')
{
adaption_fields() //调整字段的处理
}
if (adaption_field_control == '01' || adaption_field_control == '11')
{
for(i = 0; i < N ; i++) //**N值 = 184 - 调整字段的字节数**
{
}
}
- t**ransport_scrambling_control**
传送信息通过加入扰码来加密,各个基本码流可以独立进行加扰。加扰控制字段说明TS包中的净荷数据是否加扰。如果加扰,标志出解扰的密匙。
- **adaption_field_control**
调整字段控制
0x0: // reserved for future use by ISO/IEC
0x1: // 无调整字段,仅含有效负载
0x2: // 仅含调整字段,无有效负载
0x3: // 调整字段后含有效负载
**适配域是一个可变长度的域,它在TS包中是否存在,由适配域控制标识决定。**- **continuity_counter**
用于对传输误码进行检测。在发送端对所有的包都做0-15的循环计数,在接收终端,如发现循环计数器的值有中断,表明数据在传输中有丢失。
============
TS包头解析:
oid adjust_TS_packet_header(TS_packet_header* pheader)
{
unsigned char buf[4];
memcpy(buf, pheader, 4);
pheader->transport_error_indicator = buf[1] >> 7;
pheader->payload_unit_start_indicator = buf[1] >> 6 & 0x01;
pheader->transport_priority = buf[1] >> 5 & 0x01;
pheader->PID = (buf[1] & 0x1F) << 8 | buf[2];
pheader->transport_scrambling_control = buf[3] >> 6;
pheader->adaption_field_control = buf[3] >> 4 & 0x03;
pheader->continuity_counter = buf[3] & 0x03;
}
例如要提取结构体中的adaption_field_control,因为它是第26~27位,也就是第3(基于0)字节的第2~3位(共两位),所以要取第3字节,然后右移2位(把右边多余的2位抛弃),再“与”3(屏蔽左边多余的位)。
==========================**PCR**================
http://dekst.awardspace.com/project/download/PCR.pdf
时间上的同步包括音频和视频上的同步,然而 在传输流(Transport Stream, TS)的传输过程中, 由于网络延迟、复接,以及在适配器(网卡)中适时的加 入了空包和兆帧初始化包( Mega-frame Initialization Packet,MIP)等种种因素,使得附 带音频和视频时间信息的两个相邻 PCR 的相对位 置发生了改变,这将可能造成接收端解出的图像 出现马赛克和唇音不同步等现象,即 PCR 发生了 抖动,因此,在单频网适配器中,需要对接收到 的 PCR 信息进行校正。
**编码器中使用一个 27MHz 的系统时钟来产 生一系列时间标签,包括指示音频、视频正确显 示(PTS)和解码的时间(DTS),以及采样过程中系统时钟本身 的瞬时值。**
在 TS 流中描述该系统时钟瞬时值的时 间标签称为节目参考时钟标签(PCR),是编码器 27MHz 系统时钟的 42 比特采样值。
解码器中也 有一个 27MHz 的系统时钟,它根据打包的基本码 流 (Packetized Elementary Stream, PES)中的显 示时间标签 (Presentation Time Stamp, PTS)和 解码时间标签 (Decoding Time Stamp, DTS)字段 所指示的时间进行解码和显示。
**如果前端编码器 的时钟与后端解码器中时钟“绝对”同步,那么 TS 传输流中的 PCR 就没有任何意义了**。
但是如 果“绝对”变为“相对”以后,它们之间的“微 小”误差经过长时间的累积(1~2 小时足以),机 顶盒中解码器就会因为自己的时钟“快”了而造 成 buffer 中没有数据(即停帧),或是因为时钟“慢” 了而造成 buffer 中数据溢出(即丢帧)。
所以**解码 器就需要用 TS 流中的 PCR 字段来不断修正自己 与编码器时钟之间的“微小”误差**。
同时 **TS 流经 过适配器时,在原有的 TS 流中插入了用于调整 速率的空包和控制TS流传输的MIP包,因此PCR 必须进行非均匀延迟修正**。
- **PCR的查找和提取**
**在 TS 流的传输过程中,并不是每一个 TS 包 (188 个字节)都带有 PCR 信息**,这样,在处理 流入单频网适配器中的 TS 流的 PCR 信息时,就 需要先查找到 PCR 信息,将其提取出来,然后再 对 PCR 信息进行修正。

**如上图所示,PCR是存在自适应区的。有没有自适应区由TS包头中的adaption_field_control字段控制。**
**如果有自适应区,那么其内容存放在TS流中数据域中,在有效负载(音视频数据)之前。**
图 1 给出了 TS 流的帧结构,由此可以看出, 要查找 PCR,首先应检查包头中自适应控制位**adaption_field_control**的 值,当其为“10”或“11”时,表示连续计数器后紧跟 着自适应区,当其为“00”或“01”时,就不存在自适 应区,那么,连续计数器后紧跟着的就是有效负 载。
当判定 TS 包中存在自适应区后,就查询自适应区中的 PCR 标志位是否为 1,如果是 1,则该 TS 包中有 PCR 信息,且 PCR 信息就存放在可选 字段的前 48 位中。
**4. PCR 改进校正算法**
对 PCR 字段进行校正的基本思路是在原始的 PCR 上加上一个校正值。一般校正值的计算公式 如下:
∆PCR = delact − delconst (4)
其中,delact是某 TS 流的 PCR 从进入本地系统到 离开系统所经历的实际延迟,delconst 是节目的所 有 PCR 使用的一个常数。
假定 PCR 进入适配器时,本地有一个以 27MHZ 时钟计数的计数器,此时该计数器的值记 为 PCRin;当 PCR 离开适配器时,计数器的值记 为 PCRout,
那么: ∆PCR = PCRout − PCRin (5)

**对 PCR 先做减法后做加法,中间的差值实质 上就是系统引入非恒定延时所需要校正补偿的 值,这样就间接地实现了 PCR 校正**。
按照上述原理,传统的 PCR 间接校正算法就 是在 TS 流进入单频网适配器时,经过 PCR 包查 找和 PCR 域定位,将 PCR 域中的值提取出来和 本地计数器的当前计数值相减,差值存入 FIFO 当中。
TS 流输出时,又一次对 PCR 包进行查找 和域定位,然后从 FIFO 中取出数据,和本地计数 器的当前值相加,将结果按照 TS 包的格式转换为6 个字节数据插入到 TS 流相应的 PCR 域里,从 而完成对 PCR 的校正。
这种设计方式和 PCR 直接校正算法(用 27MHZ 的计数器,直接记录 PCR 信息从流入适 配器到流出适配器的时间,然后将这段时间直接 在输出时加在原有的 PCR 值上)相比具有占用逻 辑资源少,不用记录与当前 PCR 相匹配的计数器 号,及时序控制相对简单等优点。
但是,由于本 文设计的是单频网适配器中的 PCR 校正,在适配 器中,对TS流进行去空包处理时用到了一个FIFO 作为缓冲器,若用上诉 PCR 间接算法的设计方式, 还将用到一个 FIFO,两个内部 FIFO 的使用将大 大提高对 FPGA 逻辑资源的占用。
另外,在 TS 输入和输出适配器时,都要进行 PCR 的查找和定 位,两个过程完全相同,这也同样增加了 FPGA 的逻辑资源占用。
为了减少 FPGA 的逻辑资源占用率,优化设 计,我们在对 TS 流进行第一次 PCR 查找和定位 以后,就在原有的每个字节前均加上一个标志位。 当定位到的 PCR 域时,将 PCR 域的每个字节前 的标志位置 1;其他情况下,每个字节前的标志位 均为 0。这样,在输出 TS 流进行第二次查找和定 位 PCR 时,只需看字节前的标志位为 1 还是为 0, 只对标志位为 1 的字节进行处理即可。在第一次 查找定位 PCR 信息后,将 PCR 值提取出来与本 地计数器做了减法,差值不再放入 FIFO 而是重 新插入 TS 流中;输出时再从 TS 流中取出这个 差值与本地计数器做加法,将结果再插回 TS 流, 完成 PCR 校正的间接算法。通过 TS 流本身来 传递减法差值,这样就既节省了一个 FIFO 所要 占用的逻辑资源,又避免了在减法差值存储过程 中对 FIFO 的读写控制,彻底杜绝了数据竞争冒 险的潜在危险,同时还简化了程序。
|
C++
|
UTF-8
| 1,306
| 2.96875
| 3
|
[] |
no_license
|
#include"B_node.h"
#pragma once
enum Error_code{success,not_present};
template<class Record, int order>
class B_tree{
public:
Error_code search_tree(Record &target);
Error_code insert(const Record&new_entry);
Error_code remove(const Record&target);
private:
Error_code recursive_search_tree(B_node<Record,order>*current,Record &target);
Error_code search_node(B_node<Record,order>*current,const Record&target,int &position);
Error_code push_down(B_node<Record,order>*current,const Record&new_entry,Record&median,B_node<Record,order>*&right_branch);
void push_in(B_node<Record,order>*current, const Record&entry,B_node<Record,order>*right_branch,int position);
void split_node(B_tree<Record,order>*current,const Record&extra_entry,B_node<Record,order>*extra_branch,int position,B_node<Record,order>*&right_half,Record &median);
Error_code recursive_remove(B_node<Record,order> *current,const Record &target);
void remove_data(B_node<Record,order>*current,int position);
void copy_in_predecessor(B_node<Record,order>*current,int position);
void restore(B_node<Record,order>*current,int position);
void move_left(B_node<Record,order>*current,int position);
void move_right(B_node<Record,order>*current,int position);
void combine(B_node<Record,order>*current,int position);
};
|
C++
|
UTF-8
| 830
| 2.90625
| 3
|
[] |
no_license
|
#ifndef _fast_daq_error_hh_
#define _fast_daq_error_hh_
#include <exception>
#include <string>
#include <sstream>
namespace fast_daq
{
class error : public std::exception
{
public:
error();
error( const error& p_copy );
error& operator=( const error& p_copy );
virtual ~error() throw ();
template< class x_type >
error& operator<<( const x_type& p_fragment );
const char* what() const throw ();
protected:
std::string f_message;
};
template< class x_type >
error& error::operator<<( const x_type& p_fragment )
{
std::stringstream f_converter;
f_converter << f_message << p_fragment;
f_message.assign( f_converter.str() );
return (*this);
}
}
#endif
|
Python
|
UTF-8
| 1,170
| 3.046875
| 3
|
[] |
no_license
|
class Solution:
# def canJump(self, nums):
# """
# :type nums: List[int]
# :rtype: bool
# """
# def dfs(idx, nums, vis):
# vis[idx] = True
# flag = False
# if idx == len(nums) - 1:
# return True
# if idx + nums[idx] < len(nums) and not vis[idx + nums[idx] ]:
# if dfs(idx+nums[idx], nums, vis):
# flag = True
# if idx - nums[idx] >= 0 and not vis[idx - nums[idx]]:
# if dfs(idx-nums[idx], nums, vis):
# flag = True
# return flag
# vis = [False for i in nums]
# return dfs(0, nums, vis)
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
idx = 0
maxsLen = [0 for i in nums]
maxsLen[0] = nums[0]
for i in range(1, len(nums)):
if maxsLen[i-1] < i:
return False
maxsLen[i] = max(maxsLen[i-1], i + nums[i])
return True
print(Solution().canJump([2,3,1,1,4]))
print(Solution().canJump([3,2,1,0,4]))
print(Solution().canJump([3,2,2,0,4]))
print(Solution().canJump([1,1,1,0,4]))
|
Markdown
|
UTF-8
| 6,592
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post
title: 명령행 프로그램 이야기
date: 2013-05-28 00:23:54
categories: [CommandLine Interface, CLI]
tags: [CommandLine Interface, CLI]
comments: true
---
내가 처음 접한 프로그래밍 언어는 Basic이 아닌, C였다.
그리고 Turbo-C 2.0이 첫 컴파일러였다.
내가 처음 샀던 C언어 서적이 터보 C 2.0을 알려주는 주황색 서적이었는데, 뭔가 시리즈 였던 기억이 난다.
그 책이 너무 설명이 어려워, 다음에 샀던 책이 바로, [Turbo-C 2.0 길라잡이](http://books.google.co.kr/books/about/%ED%84%B0%EB%B3%B4_C_2_0_%EA%B8%B8%EB%9D%BC%EC%9E%A1%EC%9D%B4_S_W%ED%8F%AC%ED%95%A8.html?id=9MZ3MgAACAAJ&redir_esc=y)다.
내 기억에 이 책의 표지는 초록색이었는데, 사진도 목차도 안나와있어서이책이 맞는지는 모르겠다
여튼 당시 내가 봤던 서적에서의 "Hello, World!"는 다음과 같다.
~~~ cpp
#include < stdio.h >
void main()
{
printf("Hello, World!\n");
}
~~~
뭐....당시엔 대다수 국내 C언어 서적이 저랬을려나...?
ANSI C Programming의 번역서만이.
~~~ cpp
#include < stdio.h >
int main(int argc, char* argv[])
{
printf("Hello, World!\n");
return 0;
}
~~~
였던걸로 기억한다.
고작 이게 뭐 그리 중요하냐고?
이 별거 아닌 차이가, 유닉스 문화와 윈도우 문화를 가르는 발단이 되었기 때문이다.
GCC에서는 애초에 void main()이 허용되지 않는다.
유닉스에서는 명령행 프로그램 사이의 연동에 인자(int argc, char* argv[])를, 넘기고 그 결과로 exit 코드 (main의 int 리턴 타입)를 이용한다.
그래서 프로그램간의 연동이 쉽게 가능하며, 명령행 프로그램 위에 UI를 붙이는 과정이 이런 전제하에 있다. (물론, 파이프 통신이나 소켓 통신등으로 IPC를 하기도 하지만)
여러 포스팅을 보면, void mai()과 int main(int argc, char* argv[])의 차이에 대해 표준에 대한 이유를 언급하곤 하는데, 이 표준의 전제에는 프로그램 간의 상호 작용을 매끄럽게 하기 위해서라 할 수 있다.
터보-C와 MSC라 불리우는 Visual C++이 void main() 을 허용하다보니, 그렇게 만들어진 프로그램의 exit코드는 신용할 수 없다.
물론 리눅스 환경에서 개발됐고, ANSI C 표준을 따른 프로그램이라해도, 목표로한 동작을 완료하지 못했음에도 exit코드를 0이 아닌 값을 반환하는 상황도 있을 수 있으나, 대부분의 규칙을 잘 따른 프로그램들은 정상 수행에 0을 반환한다는 것을 목표로 삼고 있다.
이 반환값을 기반으로 도는 프로그램은 수없이 많다.
나는 철저히 윈도우 프로그래머였다. 그것도 클라이언트 온리 게임만 만들던 동인 게임 개발자였고.
애초에 프로그램간의 연동이 목표가 아니라, 그저 내 프로그램 하나가 수많은 기능을 담고 싶어했던, 바퀴를 다시 발명하는 것을 즐겼던(?) 그저 흔한 프로그래머였음은 물론이고. 심지어 게임 개발할 때마다 전용 툴까지도 만들었던...흑역사를 품고 있다.
내가 윈도우 쉘 연동으로 생산성을 높이게됐던 계기는, 서버 개발자가 된 후 라이브팀 업무때가 주로 그랬다. 나에게 주어진 시간은 그다지 많지 않았고, 컨텐츠를 개발하는 일 이외의 시간은 사실 잘 주어지지 않았다. 그렇다보니 자연스레 바퀴를 재발명하는건 시간이 부족하다보니 여의치않아졌다.
가능하면 기존에 있는 기능들을 잘 묶고, 명령행 프로그램 여러개의 기능을 엮는 자동화에 대한 의지가 늘게된 시기였다.
물론 이전에도 난 게으르기 때문에, 게을러 지기 위한 기반 작업. 자동화에 대한 의지가 있었으나 그 자동화를 C++ 코드위에서 하곤 했다. FTP고, HTTP고 WIN32 API를 통해 다시 만들어, 내 프로그램 위에 얹었다.
잘 만들어져 있는 명령행 프로그램들을 엮는 일이, 얼마나 내 생산성을 높아지게 했는지 뼈저리게 느꼈다.
그와 함께 기존에 안좋았던 습관들이 조금씩 사라지게 된 계기가 됐고.
그런 깨닳음을 얻어가던 중 내가 만든 여러 프로그램들을 돌이켜봤다.
어째서 내 프로그램은 어찌 하나같이, GUI 기반으로만 동작하는가?!?
GUI기반으로 동작하는건 좋다 이거야. 헌데, 다른 프로그램과 엮기 왜 이렇게 힘든거지?
내가 짠 프로그램들은 하나같이 main함수에서 return 0으로 프로그램을 종료시키고 있었다.
원하는 목표를 달성했는지 여부와는 전혀 상관없이 말이다.
기능을 재사용하는건 , 라이브러리화 해둔 코드를 재사용하는 것에 의존했을 뿐이었고.
별거 아닌거 같으면서, 큰 깨닳음을 얻고, 자동화와 각종 보조 업무등을 위해 다른 사람들이 만든 프로그램들을 엮는 작업이 늘어가면서 내가 만든 프로그램들도 그 사이에 엮을 수 있게끔 맞춰가고 있다.
아직 많이 미숙하지만 리눅스 환경에서 ROR을 운영하며 리눅스에서의 기능 재사용, 프로그램 사이의 연동의 문화, 흔히 리눅스 문화라 불리는 것들을 잘 느낄 수 있었다.
윈도우 환경 위에서 만들어진 수 많은 메이저 프로그램이 명령행 기능을 지원하지 않는다.
특정 프로그램에서 95%가 만족스러운데, 살짝 아쉬운 한두가지 요소 때문에, 다른 프로그램을 찾아 다녀야했던 일이 리눅스 문화라고 없는건 아니지만, 명령행 위에 UI를 얹은 많은 프로그램들은 이런 고민을 해결해준다.
이런 깨닳음이 늦게 온 원인이 윈도우 환경 위에서 프로그래밍을 해왔기 때문이라고 핑계대고 싶진 않다.
다만 GUI 환경의 문화가 프로그램 사이의 연동을 어렵게 만드는 요인이라는 생각을 갖게 됐다.
아직 능숙해지려면 멀었지만 리눅스 환경에 조금씩 적응될수록 여러가지 생각이 드는데, 그 중 명령행 프로그램에 대한 이야기는 꼭 한번 하고 싶었다.
앞으로도 윈도우 환경에 대한 감사함을 얼마나 느끼게 될지, 리눅스 환경에 대한 감탄을 얼마나 하게 될지는 잘 모르겠지만 윈도우'만' 써왔다고 할 수 있는 프로그래머가, 리눅스 환경에 적응해가며 드는 감상을 적어보겠다.
|
Markdown
|
UTF-8
| 1,488
| 3.34375
| 3
|
[] |
no_license
|
res.end()方法返回的相应内容只能是二进制数据(Buffer)或者字符串
数字、对象、数组、布尔值统统不行
JSON有两个方法:
- parse('[]')返回[]
- stringify([])返回'[]',会中文乱码
```
res.end(JSON.stringify(products))
```
## 代码无分号问题
```javascript
// 当你采用无分号的代码风格的时候,只要注意以下情况就不会有问题了:
// 当一行代码是以:
// (
// [
// `
// 开头的时候,则在前面补上一个分号以避免一些语法错误。不要不在上一行行末。
// 所以你会发现在一些第三方的代码中能看到一上来就以一个;开头。
// 有些人也喜欢玩一些花哨的东西比方说加!、&、~等
function say() {
console.log('hello world!')
}
// TypeError: say(...) is not a function
say()
// 1.JavaScript中的匿名函数定义 function (a,b) { }
// 个人常用的直接执行匿名函数的方式
// (匿名函数)();【推荐使用】 (匿名函数() );
;(function () {
console.log('hello')
})()
;(function () {
console.log('world')
}())
// 2.数组遍历
;['苹果', '香蕉'].forEach(function (item) {
console.log(item)
})
// 3.` 是 EcmaScript 6 中新增的一种字符串包裹方式, 叫做: 模板字符串
// 它支持换行和非常方便的凭借变量
var foo =
`
大家好 床前明月光
hello
world
哈哈啊
`
console.log(foo)
;`hello`.toString()
```
|
Java
|
UTF-8
| 3,074
| 3.296875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.myrobotlab.control.widget;
// ButtonsPanel.java
// Andrew Davison, October 2006, ad@fivedots.coe.psu.ac.th
/* A collection of Joystick.NUM_BUTTONS textfields
representing the buttons on the game pad,
divided into two rows
When a button is pressed, the textfield's
background colour changes from OFF_COLOUR to ON_COLOUR
*/
import java.awt.Color;
import javax.swing.JPanel;
public class JoystickButtonsPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
// background colours for the textfields (game pad buttons)
// below is not used?
// private static final Color OFF_COLOUR = Color.LIGHT_GRAY;
// private static final Color ON_COLOUR = Color.YELLOW;
// not used
// private JTextField buttonTFs[]; // represents the game pad buttons
/**
* Add the textfields to the panel and store references to them in a
* buttonTFs[] array.
*
* Each textfield contains a number, is uneditable, and starts with an
* OFF_COLOUR background (meaning it's not pressed).
*/
public JoystickButtonsPanel() {
setBackground(Color.white);
/*
* // initialize buttonTFs[] buttonTFs = new
* JTextField[Joystick.NUM_BUTTONS]; for (int i = 0; i <
* Joystick.NUM_BUTTONS; i++) { buttonTFs[i] = new JTextField("" + (i), 2);
* buttonTFs[i].setEditable(false); buttonTFs[i].setBackground(OFF_COLOUR);
* }
*
* setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // vertical box layout
*
* makeRow(0, Joystick.NUM_BUTTONS / 2); // 1st row
* makeRow(Joystick.NUM_BUTTONS / 2, Joystick.NUM_BUTTONS); // 2nd row
*/
} // end of ButtonsPanel()
// not used method below
// private void makeRow(int start, int end)
// // a row of textfields from buttonTFs[start] to buttonTFs[end-1]
// {
// JPanel rowPanel = new JPanel();
// rowPanel.setLayout(new BoxLayout(rowPanel, BoxLayout.X_AXIS)); // horiz
// // box
// // layout
//
// JPanel p;
// for (int i = start; i < end; i++) {
// p = new JPanel();
// p.setBackground(Color.white);
// p.add(buttonTFs[i]); // add button to its own panel p to stop
// // resizing
// rowPanel.add(p); // add panel p to row
// }
// add(rowPanel);
// } // end of makeRow()
public void setButton(int buttonNum, Float value) {
/*
* Color c = (value == Joystick.BUTTON_ON) ? ON_COLOUR : OFF_COLOUR;
* buttonTFs[buttonNum].setBackground(c);
*
*/
repaint();
}
public void setButtons(boolean bVals[])
/*
* Use the bVals[] array to switch the buttonTFs on/off by changing the
* background colour of their textfields.
*/
{/*
* if (bVals.length != Joystick.NUM_BUTTONS) System.out.println(
* "Wring number of button values"); else { Color c; for (int i = 0; i <
* Joystick.NUM_BUTTONS; i++) { c = (bVals[i] == true) ? ON_COLOUR :
* OFF_COLOUR; buttonTFs[i].setBackground(c); } repaint(); }
*/
} // end of setButtons()
} // end of ButtonsPanel class
|
Markdown
|
UTF-8
| 2,707
| 4.1875
| 4
|
[] |
no_license
|
### 搜索
#### 二分查找
前提:1.有序序列 2.顺序表O(1)
二分查找(折半查找),优点是比较次数少,查找速度快,平均性能好,缺点是待查表必须是有序表,且插入删除困难,适用于不经常变动而查找频繁的有序表。
1. 假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较;
2. 如果两者相等,则查找成功;
3. 否则利用中间位置记录将表分成前、后两个子表;
4. 如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。
5. 重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
##### 递归实现
```Python
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 18-11-9 @Author:libo @FileName: 01_binary_search.py
def binary_search(alist,item):
"""
二分查找 递归版本
:param alist: 数组
:param item: 查找元素
:return: True False
"""
# version 1
# n = len(alist)
# if n == 0:
# return False
# mid = n // 2
# if alist[mid] == item:
# return True
# elif item < alist[mid]:
# return binary_search(alist[:mid],item)
# else:
# return binary_search(alist[alist[mid+1]:],item)
# version 2
n = len(alist)
if n == 0:
return False
mid = n // 2
if alist[mid] == item:
return True
else:
if item < alist[mid]:
return binary_search(alist[:mid],item)
else:
return binary_search(alist[mid+1:],item)
if __name__ == '__main__':
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binary_search(testlist, 17))
print(binary_search(testlist, 13))
```
##### 非递归实现
```PYTHON
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 18-11-9 @Author:libo @FileName: 02_binary_search_no_recursive.py
def binary_search(alist,item):
"""
二分查找 非递归版本
:param alist: 数组
:param item: 待查找元素
:return: True False
"""
start = 0
end = len(alist) -1
while start <= end:
mid = (start + end) // 2
if item == alist[mid]:
return True
elif item < alist[mid]:
end = mid - 1
else :
start = mid + 1
# 退出循环,表示没有找到
return False
if __name__ == '__main__':
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(binary_search(testlist, 19))
print(binary_search(testlist, 42))
```
##### 时间复杂度
- 最优时间复杂度:O(1)
- 最坏时间复杂度:O(logn)
|
Java
|
UTF-8
| 3,644
| 2.34375
| 2
|
[] |
no_license
|
package parts;
import parts.annotations.Printable;
import parts.annotations.Sortable;
import parts.entity.annotations.*;
import parts.entity.annotations.Object;
import java.io.Serializable;
import java.util.Date;
//@Entity(name = PartHtml.PARTS, nameInDB = PartDb.PARTS)
//@Entity(name = "PARTS")
@Object("Part") @TableDb("parts")
public class Part implements Serializable {
//@Id(name = "PART_ID", viewName = "Part Id") @Sortable
@ObjectId("Part Id") @TableDbId("PART_ID") @Sortable @Printable
private Integer partId;
//@Field(name = "PART_NAME", viewName = "Part Name") @Sortable
@ObjectField("Part Name") @TableDbField("PART_NAME") @Sortable //@Printable
private String partName;
//@Field(name = "PART_NUMBER", viewName = "Part Number") @Sortable
@ObjectField("Part Number") @TableDbField("PART_NUMBER") @Sortable @Printable
private String partNumber;
//@Field(name = "VENDOR", viewName = "Vendor") @Sortable
@ObjectField("Vendor") @TableDbField("VENDOR") @Sortable @Printable
private String vendor;
//@Field(name = "QTY", viewName = "Qty") @Sortable
@ObjectField("Qty") @TableDbField("QTY") @Sortable @Printable
private Integer qty;
//@Field(name = "SHIPPED", viewName = "Shipped") @Sortable
@ObjectField("Shipped") @TableDbField("SHIPPED") @Sortable @Printable
private Date shipped;
//@Field(name = "RECEIVED", viewName = "Received") @Sortable
@ObjectField("Received") @TableDbField("RECEIVED") @Sortable @Printable
private Date received;
public Part() {}
public Part(Integer partId, String partName, String partNumber, String vendor, Integer qty, Date shipped, Date received) {
this.partId = partId;
this.partName = partName;
this.partNumber = partNumber;
this.vendor = vendor;
this.qty = qty;
this.shipped = shipped;
this.received = received;
}
public Integer getPartId() {
return partId;
}
public void setPartId(Integer partId) {
this.partId = partId;
}
//@Sortable
public String getPartName() {
return partName;
}
public void setPartName(String partName) {
this.partName = partName;
}
//@Sortable
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
//@Sortable
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
//@Sortable
public Integer getQty() {
return qty;
}
public void setQty(Integer qty) {
this.qty = qty;
}
//@Sortable
public Date getShipped() {
return shipped;
}
public void setShipped(Date shipped) {
this.shipped = shipped;
}
//@Sortable
public Date getReceived() {
return received;
}
public void setReceived(Date received) {
this.received = received;
}
@Override
public String toString() {
return (partId==null && partName==null && partNumber==null && vendor==null && qty==null && shipped==null && received==null) ? "" : "part{" +
"partId=" + partId +
", partName='" + partName + '\'' +
", partNumber='" + partNumber + '\'' +
", vendor='" + vendor + '\'' +
", qty=" + qty +
", shipped=" + shipped +
", received=" + received +
"}";
}
public boolean isEmpty(){
return this.equals(new Part());
}
}
|
Java
|
UTF-8
| 892
| 1.742188
| 2
|
[] |
no_license
|
package com.cenpro.siscu.service;
import java.util.List;
import com.cenpro.siscu.model.admision.Afiliacion;
import com.cenpro.siscu.model.criterio.CriterioBusquedaEstamento;
public interface IAfiliacionService extends IMantenibleService<Afiliacion>
{
public List<Afiliacion> buscarTodos();
public List<Afiliacion> buscarPorNroDocumento(CriterioBusquedaEstamento criterioBusquedaEstamento);
public List<Afiliacion> buscarPorNroDocumentoNoAfiliado(CriterioBusquedaEstamento criterioBusquedaEstamento);
public List<Afiliacion> buscarPorId(String nroDocumento, String tipoDocumento);
public List<Afiliacion> registrarAfiliacion(Afiliacion afiliacion);
public void actualizarAfiliacion(Afiliacion afiliacion);
//public List<Afiliacion> buscarPorNroDocumento( CriterioBusquedaEstamento criterioBusquedaEstamento);
}
|
JavaScript
|
UTF-8
| 5,249
| 2.59375
| 3
|
[] |
no_license
|
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
window.addEventListener("resize", () => {
displayHiddenNavBarMobile();
});
window.addEventListener("scroll", () => {
handlingNavBarBackgroundAnimation();
$$(".heading-container").forEach((element) => {
headingViewportAnimation(element, element.children[0], element.children[1]);
});
$$(".container-image-list .container-image-item").forEach((element) => {
elementViewportAnimationFadeIn(element, 430);
})
elementViewportAnimationFadeIn($(".container-card-bicycle"), 200);
elementViewportAnimationFadeIn($(".section-4 .heading-3"), 50);
elementViewportAnimationFadeIn($(".section-4 .heading-3"), 200);
elementViewportAnimationFadeIn($(".section-4 .button-bold"), 100);
elementViewportAnimationFadeIn($(".section-4 img"), 100);
$$(".container-small-card-bicycle").forEach((element) => {
elementViewportAnimationFadeIn(element, 200);
});
$$(".card-bike-news-item").forEach((element) => {
elementViewportAnimationFadeIn(element, 240);
});
headingViewportAnimationSlide($(".section-4 .heading-1"), 200);
headingViewportAnimationSlide($(".section-4 .heading-2"), 200);
});
let pageActiveCarousel = 1;
window.addEventListener("load", () => {
displayHiddenNavBarMobile();
updateNewPageCarousel();
let pageItems = $$(".page-item");
let pageArrows = $$(".page-arrow");
pageArrows.forEach((pageArrow) => {
pageArrow.addEventListener("click", (e) => {
if (e.target.className.includes("left")) {
if (pageActiveCarousel >= 1) pageActiveCarousel -= 1;
if (pageActiveCarousel < 1) pageActiveCarousel = pageItems.length;
updateNewPageCarousel();
return;
}
if (pageActiveCarousel <= pageItems.length) pageActiveCarousel += 1;
if (pageActiveCarousel > pageItems.length) pageActiveCarousel = 1;
updateNewPageCarousel();
});
});
pageItems.forEach((pageItem, index) => {
pageItem.addEventListener("click", (e) => {
if (!e.target.className.includes(" active")) {
pageActiveCarousel = index + 1;
updateNewPageCarousel();
}
});
});
$(".nav-bar-container .menu").addEventListener("click", () => {
if (!$(".nav-bar-container .menu").className.includes("active")) {
$(".nav-bar-container .menu").className = "menu active";
document.body.style.overflow = "hidden"
$(".side-bar-nav-container").className = "side-bar-nav-container active";
return;
}
$(".nav-bar-container .menu").className = "menu";
document.body.style.overflow = "auto"
$(".side-bar-nav-container").className = "side-bar-nav-container";
});
$(".side-bar-nav-wrapper .close-button").addEventListener("click",() => {
$(".nav-bar-container .menu").className = "menu";
document.body.style.overflow = "auto"
$(".side-bar-nav-container").className = "side-bar-nav-container";
})
});
function headingViewportAnimationSlide(element, threshold) {
if (isElementInViewport(element, threshold)) {
element.style.transition = "2s";
element.style.opacity = "1";
element.style.transform = "translateX(0)";
}
}
function elementViewportAnimationFadeIn(element, threshold) {
if (isElementInViewport(element, threshold)) {
element.style.transform = "translateY(0)";
element.style.opacity = "1";
element.style.transition = "1.5s";
element.style.top = "66%";
}
}
function headingViewportAnimation(section, heading1, heading2) {
if (isElementInViewport(section, 70)) {
heading1.style.transform = "translateX(-50%)";
heading1.style.transition = "1s";
setTimeout(() => {
heading2.style.transition = "1s";
heading2.style.transform = "translateX(0)";
}, 500);
}
}
function handlingNavBarBackgroundAnimation() {
const navBarContainer = $(".nav-bar-container");
if (window.scrollY === 0) {
navBarContainer.style.backgroundColor = "transparent";
navBarContainer.style.paddingTop = "40px";
} else {
navBarContainer.style.backgroundColor = "#3a3a3a";
navBarContainer.style.paddingTop = "0";
}
}
function updateNewPageCarousel() {
let carouselSlideItems = $$(".carousel-slide-item");
let pageItems = $$(".page-item");
pageItems.forEach((pageItem, index) => {
if (index === pageActiveCarousel - 1) {
if (!pageItem.className.includes(" active"))
pageItem.className += " active";
return;
}
pageItem.className = pageItem.className.replace(" active", "");
});
carouselSlideItems.forEach((carouselSlideItem, index) => {
if (
!carouselSlideItem.className.includes(" active") &&
index === pageActiveCarousel - 1
) {
carouselSlideItem.className += " active";
return;
}
carouselSlideItem.className = carouselSlideItem.className.replace(
" active",
""
);
});
}
function isElementInViewport(element, threshold) {
return element.getBoundingClientRect().y - window.innerHeight + threshold < 0;
}
function displayHiddenNavBarMobile() {
if (window.innerWidth < 1000) {
$(".nav-bar-container").className = "nav-bar-container mobile";
return;
}
$(".nav-bar-container").className = "nav-bar-container";
}
|
PHP
|
UTF-8
| 1,337
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
<?php namespace App\Controllers;
/**
* Controller가 View를 호출하는 구조
*/
class Home extends BaseController
{
/**
* http://localhost
* 사이트의 대문 페이지로 인식된다.
*/
public function index()
{
// views 폴더의 welcome_message.php 파일을 호출하여 화면 표시를 요청한다.
return view('welcome_message');
}
//--------------------------------------------------------------------
/**
* 컨트롤러와 View의 관계를 이해하기 위한 메서드 추가 작성
*/
/** hello 페이지 --> http://localhost/home/hello */
public function hello()
{
// View에게 전달할 데이터를 연관배열로 구성하여 전달한다.
$data = ['name' => '코드이그나이터', 'version' => '4.0.4'];
return view('home/hello', $data); // /views 디렉토리 내의 경로를 의미 (확장자 생략)
}
/** world 페이지 --> http://localhost/home/world */
public function world()
{
// View에게 전달할 데이터를 객체로 구성하여 전달한다.
$data = new \stdClass();
$data->name = 'Codeigniter';
$data->version = '4.0.4';
$data = get_object_vars($data); // view는 연관배열만 받는다.
return view('home/world', $data);
}
}
|
JavaScript
|
UTF-8
| 3,384
| 4.09375
| 4
|
[] |
no_license
|
'use strict';
// function iceCream(){
// console.log('Jerry');
// }
// iceCream();
//Counting Sheep
// function sheepCount(number){
// if(number === 0){
// return;
// }
// console.log(` ${number} - Another sheep jump over the fence`);
// sheepCount(number-1);
// }
// sheepCount(3);
//Array Double
// function arrayDoubler(arr){
// if(arr.length === 0)
// return [];
// else{
// let newArr = [];
// newArr = [2 * arr[0], ...arrayDoubler(arr.slice(1))];
// return newArr;
// }
// }
//console.log(arrayDoubler([2, 18, 52, 31]));
//REVERSE STRING
// function stringReverser(str){
// if(str=== ''){
// return '';
// }
// else{
// let newStr = '';
// newStr = newStr + str.charAt(str.length - 1);
// return newStr + stringReverser(str.slice(0, str.length-1));
// //return str.charAt(str.length-1) + stringReverser(arr.pop());
// }
// }
// console.log(stringReverser('Caterpiller'));
//Triangles
function findTriangle(num, increment = 1, results= []){
if(increment === num){
return 0;
}
if(results.length === 0){
increment++;
return results.push(1);
}
else {
increment++;
results.push(results.length);
}
}
//SPLIT
// if (str === char) {
// return "";
// }
// if (str.length === 0) {
// results.push(newString);
// return results;
// }
// if (str[0] === char) {
// results.push(newString);
// newString = "";
// return splitString(str.slice(1), char, newString, results);
// } else {
// newString += str[0];
// return splitString(str.slice(1), char, newString, results);
// }
// }
//console.log(splitString("Welcome to Jumanji World", "o"));```
// if(i === num)
// return 0;
// else{
// let input = 1;
// let increment = 1;
// increment = increment + 1;
// return increment + findTriangle( input + increment, i + 1);
// }
// }
//console.log(findTriangle(17));
// const str = 'Caterpiller';
// console.log(str.slice(0, str.length-1));
// function reverseString(str) {
// if (str === "") // This is the terminal case that will end the recursion
// return "";
// else
// return reverseString(str.substr(1)) + str.charAt(0);
// }
// console.log(reverseString('Caterpiller'));
// const str = 'Hello';
// const new1 = str.split('');
// console.log(new1[new1.length-1]);
//Split and Separate
// function splitAndSeparate(str, char){
// if(str){
// } else{
// return newArr;
// }
// }
// //let newArr = [str.charAt(0), ...splitAndSeparate(str.slice(1), char)];
// console.log(splitAndSeparate('Jumanji', '&'));
//FACTORIAL
// function factorial(num){
// if(num === 1){
// return 1;
// }
// else{
// return num * factorial(num - 1);
// }
// }
// console.log(factorial(4));
//FIBONACCI
function fibonacciGo(num, results){
if(num === 0){
return;
}
if(num === 1){
return [0,1];
}
//let start = [ 1, 1, 2];
else {
results = fibonacciGo(num - 1);
let newNum = ((results[results.length -1] + results[results.length -2]));
results.push(newNum);
return results;
}
}
// console.log(fibonacciGo(8));
//ANAGRAM
// function anagram(word){
// if(word.length === 0)
// return ""
// let permutations = [];
// else
// permutations.push(word[-1])
// }
|
Java
|
UTF-8
| 3,965
| 2.375
| 2
|
[] |
no_license
|
package com.adobe.aem.commons.assetshare.util;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.AbstractResourceVisitor;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.jcr.resource.api.JcrResourceConstants;
import org.apache.sling.models.factory.ModelFactory;
import java.util.ArrayList;
import java.util.Collection;
/**
* Utility visitor that walks a Page and collects the models for resources matching at least one of the provided resource Types.
*
* This visitor only visits resources with a sling:resourceType.
*
* @param <T> The Model type to collect.
*/
public final class ComponentModelVisitor<T> extends AbstractResourceVisitor {
final Collection<T> models = new ArrayList<>();
final Collection<Resource> resources = new ArrayList<>();
private final SlingHttpServletRequest request;
private final ModelFactory modelFactory;
private final String[] resourceTypes;
private final Class<T> clazz;
/**
* @param request the SlingHttpServletRequest object
* @param modelFactory the ModelFactory object used to construct the Model
* @param resourceTypes the resource types that will be attempted to be resolved to the T type.
* @param clazz the Model class the resources should be made into.
*/
public ComponentModelVisitor(SlingHttpServletRequest request,
ModelFactory modelFactory,
String[] resourceTypes,
Class<T> clazz) {
this.request = request;
this.modelFactory = modelFactory;
this.resourceTypes = resourceTypes;
this.clazz = clazz;
}
/**
* Note that getModels() may return a SUBSET of getResources(). If a resource matches the resource type check but cannot be turned into a model, the resources will be in getResources() but not in getModels().
* @return a list of Models representing the visited resources (assuming they match the resourceTypes and can be made into the clazz model type.
*/
public final Collection<T> getModels() {
return models;
}
/**
* Note that getModels() may return a SUBSET of getResources(). If a resource matches the resource type check but cannot be turned into a model, the resources will be in getResources() but not in getModels().
* @return a list of resource that match at least one resourceTypes.
*/
public final Collection<Resource> getResources() {
return resources;
}
@Override
/**
* {@inheritDoc}
**/
public final void accept(Resource resource) {
final ValueMap properties = resource.getValueMap();
// Only traverse resources that have a sling:resourceType; those without sling:resourceTypes are not components and simply sub-component configurations resources (such as Option lists)
if (properties.get(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, String.class) != null) {
super.accept(resource);
}
}
@Override
protected final void visit(Resource resource) {
for (final String resourceType : resourceTypes) {
if (handleResourceVisit(resource, resourceType)) {
handleModelVisit(resource);
break;
}
}
}
private boolean handleResourceVisit(Resource resource, String resourceType) {
if (resource != null && resource.getResourceResolver().isResourceType(resource, resourceType)) {
resources.add(resource);
return true;
}
return false;
}
private void handleModelVisit(Resource resource) {
if (clazz != null) {
final T model = modelFactory.getModelFromWrappedRequest(request, resource, clazz);
if (model != null) {
models.add(model);
}
}
}
}
|
C
|
UTF-8
| 268
| 3.421875
| 3
|
[] |
no_license
|
#include<stdio.h>
int main()
{
int num,x,temp,i=0,decimal=0;
printf("enter binary number");
scanf("%d",&num);
while(num!=0)
{
temp=num%10;
x=temp*pow(2,i);
decimal+=x;
num=num/10;
i++;
}
printf("\n the decimal number is =%d\n",decimal);
return 0;
}
|
Java
|
UTF-8
| 3,796
| 2.625
| 3
|
[] |
no_license
|
package com.rest.server;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import com.model.shared.Device;
public class OracleManagerImpl implements Connector, DBManager {
private String driverName = "oracle.jdbc.driver.OracleDriver";
private Connection conn = null;
private String url = "jdbc:oracle:thin:@sql.edu-netcracker.com:1251:XE";
private String login = "unc17i_aisaev";
private String password = "Dc9v9yLH";
public OracleManagerImpl() throws ClassNotFoundException {
Locale.setDefault(Locale.US);
Class.forName(driverName);
connect(login, password);
}
public void connect() {
try {
conn = DriverManager.getConnection(url, login, password);
} catch (SQLException e) {
System.err.println("can not establish connection");
e.printStackTrace();
}
}
public Connection getConnection() {
return conn;
}
public void closeConnection() {
try {
conn.close();
} catch (SQLException e) {
}
}
public void addDevice(Device device) {
String insertDeviceQuery = "insert into device(name, description)" + "values (?, ?);";
try {
PreparedStatement statement = conn.prepareStatement(insertDeviceQuery);
statement.setString(1, device.getName());
statement.setString(2, device.getDescription());
statement.executeUpdate();
} catch (SQLException e) {
}
}
public List<Device> getAllDevices() {
List<Device> result = new ArrayList<Device>();
String selectAllDevicesQuery = "select * from device;";
try {
PreparedStatement statement = conn.prepareStatement(selectAllDevicesQuery);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
result.add(new Device(BigInteger.valueOf(Long.parseLong(rs.getString(1).toString())),
rs.getString(2), rs.getString(3)));
}
} catch (SQLException e) {
}
return result;
}
public Device getDevice(BigInteger id) {
Device device = null;
String selectDeviceQuery = "select * from device where id = ?;";
try {
PreparedStatement statement = conn.prepareStatement(selectDeviceQuery);
statement.setInt(1, id.intValue());
ResultSet rs = statement.executeQuery();
while (rs.next()) {
device = new Device(id,
rs.getString(2), rs.getString(3));
}
} catch (SQLException e) {
}
return device;
}
public void updateDevice(Device device) {
String updateDeviceQuery = "update device set name = ?, description = ? where id = ?;";
try {
PreparedStatement statement = conn.prepareStatement(updateDeviceQuery);
statement.setString(1, device.getName());
statement.setString(2, device.getDescription());
statement.setBigDecimal(3, new BigDecimal(device.getId()));
statement.executeUpdate();
} catch (SQLException e) {
}
}
public void deleteDevice(BigInteger id) {
String deleteDeviceQuery = "delete device " + "where id = ?;";
try {
PreparedStatement statement = conn.prepareStatement(deleteDeviceQuery);
statement.setInt(1, id.intValue());
statement.executeUpdate();
} catch (SQLException e) {
}
}
public void connect(String login, String password) {
// TODO Auto-generated method stub
try {
Class.forName("org.postgresql.Driver");
Locale.setDefault(Locale.US);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try {
conn = DriverManager.getConnection(url, login, password);
} catch (SQLException e) {
System.err.println("can not establish connection");
e.printStackTrace();
}
}
@Override
public void disconnect() {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
Swift
|
UTF-8
| 1,777
| 3.171875
| 3
|
[] |
no_license
|
//
// HomeViewModel.swift
// expired-date-ios
//
// Created by fit-sys on 2020/10/13.
//
import SwiftUI
import CoreData
class HomeViewModel : ObservableObject{
@Published var content = ""
@Published var date = Date()
@Published var isNewData = false
@Published var updateItem : Food!
let calender = Calendar.current
func checkDate()->String{
if calender.isDateInToday(date){
return "今日"
}
else if calender.isDateInTomorrow(date){
return "明日"
}
else{
return "その他"
}
}
func updateDate(value: String){
if value == "今日"{date = Date()}
else if value == "明日"{
date = calender.date(byAdding: .day, value: 1, to: Date())!
}
else{
}
}
func writeData(context : NSManagedObjectContext){
if updateItem != nil{
updateItem.date = date
updateItem.content = content
try! context.save()
updateItem = nil
isNewData.toggle()
content = ""
date = Date()
return
}
let newFood = Food(context: context)
newFood.date = date
newFood.content = content
do{
try context.save()
isNewData.toggle()
content = ""
date = Date()
}
catch{
print(error.localizedDescription)
}
}
func EditItem(item: Food){
updateItem = item
date = item.date!
content = item.content!
isNewData.toggle()
}
}
|
Python
|
UTF-8
| 2,682
| 3.546875
| 4
|
[
"Apache-2.0"
] |
permissive
|
import ast
from typing import Dict, List, Optional
def read_object_name(node: ast.AST, name: Optional[List[str]] = None) -> str:
"""Parse the object's (class or function) name from the right-hand size of an
assignement nameession.
The parsing is done recursively to recover the full import path of the
imported names. This step is only an operation on strings: we do not check
whether the names are indeed present in the namespace.
Args:
node: The right-hand-side of the assignment node.
name: The parts of the name that have been parsed.
Returns:
The full path to the object on the right-hand-side of the assignment.
Raises:
ValueError: If the next node in the recursion is neither a variable
(ast.Name) nor and attribute.
Examples:
When the name is imported directly:
>>> read_object_name(ast.Name(id='Exponential'))
Exponential
When it is imported from a submodule. Here for `mcmx.distributions.Normal`
>>> read_object_name(
... ast.Attribute(value=ast.Attribute(value=ast.Name(id='mcmx'), attr='distributions'), attr='Normal')
... )
mcmx.distributions.Normal
"""
if not name:
name = []
if isinstance(node, ast.Name):
name.insert(0, node.id)
return ".".join(name)
elif isinstance(node, ast.Attribute):
name.insert(0, node.attr)
new_node = node.value
return read_object_name(new_node, name)
else:
raise ValueError(
"Error while getting the right-hand-side object's name: expected `ast.Name` or `ast.Attribute`, got {}".format(
node
)
)
def relabel_arguments(value_node: ast.AST, mapping: Dict):
""" Walk down the Abstract Syntax Tree of the right-hand-side of the
assignment to relabel the arguments.
Returns
-------
A list of variable names, default to an empty list.
"""
for node in ast.walk(value_node):
if isinstance(node, ast.BinOp):
if isinstance(node.left, ast.Name):
var_name = node.left.id
if var_name in mapping:
node.left.id = mapping[var_name]
if isinstance(node.right, ast.Name):
var_name = node.right.id
if var_name in mapping:
node.right.id = mapping[var_name]
elif isinstance(node, ast.Call):
for arg in node.args:
if isinstance(arg, ast.Name):
var_name = arg.id
if var_name in mapping:
arg.id = mapping[var_name]
|
C
|
UTF-8
| 2,268
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
/**
* @file
* @author David Barina <ibarina@fit.vutbr.cz>
* @brief Simple application showing various system informations.
*/
#include "libdwt.h"
#include <stdio.h> // fopen, fscanf, fgets, fclose
#include <string.h> // strcmp, strchr, strstr
#include <ctype.h> // isspace
int main()
{
dwt_util_print_info();
dwt_util_log(LOG_INFO, "CPU flags:\n");
#define CPUINFO_MAX 8192
char buff[CPUINFO_MAX] = {0};
FILE *fcpuinfo = fopen("/proc/cpuinfo", "r");
if(!fcpuinfo)
{
dwt_util_log(LOG_DBG, "cpuinfo opening failure!\n");
goto close_cpuinfo;
}
// opened
while( strcmp("flags", buff) )
{
int res = fscanf(fcpuinfo, "%s", buff);
if( EOF == res )
{
dwt_util_log(LOG_DBG, "cpuinfo parsing failure!\n");
goto close_cpuinfo;
}
}
// got 'flags' line
char *ptr = fgets(buff, CPUINFO_MAX, fcpuinfo);
if(!ptr)
{
dwt_util_log(LOG_DBG, "fgets failure!\n");
goto close_cpuinfo;
}
ptr = strchr(ptr, ':');
if(!ptr)
{
dwt_util_log(LOG_DBG, "strchr failure!\n");
goto close_cpuinfo;
}
ptr++;
// got content of 'flags'
struct {char *key, *desc;} flags[] = {
{ .key="lm", .desc="long mode (64-bit mode)" },
{ .key="mmx", .desc="MMX" },
{ .key="3dnow", .desc="3DNow!" },
{ .key="sse", .desc="SSE (Streaming SIMD Extensions)" },
{ .key="sse2", .desc="SSE2 (Streaming SIMD Extensions 2)" },
{ .key="pni", .desc="SSE3 (Streaming SIMD Extensions 3)" },
{ .key="ssse3", .desc="SSSE3 (Supplemental Streaming SIMD Extensions 3)" },
{ .key="sse4_1", .desc="SSE4.1 (Streaming SIMD Extensions 4.1)" },
{ .key="sse4_2", .desc="SSE4.2 (Streaming SIMD Extensions 4.2)" },
{ .key="sse4a", .desc="SSE4A (Streaming SIMD Extensions 4a)" },
{ .key="avx", .desc="AVX (Advanced Vector Extensions)" },
{ .key="avx2", .desc="AVX2 (Advanced Vector Extensions 2)" },
{ .key="fma4", .desc="FMA4 (4-operand Fused Multiply/Add)" },
{ .key="fma", .desc="FMA (Fused Multiply/Add)" },
};
const int nflags = sizeof(flags)/sizeof(*flags);
for(int f = 0; f < nflags; f++)
{
char *flag = strstr(ptr, flags[f].key);
if( flag )
{
int cl = *(flag-1);
int cr = *(flag+strlen(flags[f].key));
if( isspace(cl) && isspace(cr) )
{
dwt_util_log(LOG_INFO, "%s\n", flags[f].desc);
}
}
}
close_cpuinfo:
fclose(fcpuinfo);
return 0;
}
|
PHP
|
UTF-8
| 3,738
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
<?php
require dirname(__FILE__)."/../utils/config.inc.php";
class ConfigurationCommandsController extends \BaseController {
/**
* Display a listing of the resource.
* GET /configurationcommands
*
* @return Response
*/
public function index()
{
$commands = $this->getList();
return Response::json($commands);
}
/**
* Show the form for creating a new resource.
* GET /configurationcommands/create
*
* @return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
* POST /configurationcommands
*
* @return Response
*/
public function store()
{
$command_name = Input::get("command_name");
$command_line = Input::get("command_line");
$uuid = UUID::v4();
Object::create(array(
"uuid" => $uuid,
"object_type" => "12",
"first_name" => $command_name,
"second_name" => "",
"is_active" => "1"
));
Command::create(array(
"object_uuid" => $uuid,
"command_line" => $command_line
));
$this->writeConfig();
return Response::json(array("success" => true));
}
/**
* Display the specified resource.
* GET /configurationcommands/{id}
*
* @param int $id
* @return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
* GET /configurationcommands/{id}/edit
*
* @param int $id
* @return Response
*/
public function edit($id)
{
$command = DB::table("commands")
->join("objects", "commands.object_uuid", "=", "objects.uuid")
->select("commands.id", "objects.first_name as command_name", "commands.command_line")
->where("commands.id", "=", $id)
->get();
return Response::json($command);
}
/**
* Update the specified resource in storage.
* PUT /configurationcommands/{id}
*
* @param int $id
* @return Response
*/
public function update($id)
{
$command_name = Input::get("command_name");
$command_line = Input::get("command_line");
$result = DB::table("commands")->select("object_uuid")->where("id", "=", $id)->get();
$uuid = $result[0]->object_uuid;
DB::table("objects")
->where("uuid", "=", $uuid)
->update(array("first_name" => $command_name));
DB::table("commands")
->where("id", "=", $id)
->update(array("command_line" => $command_line));
$this->writeConfig();
return Response::json(array("success" => true));
}
/**
* Remove the specified resource from storage.
* DELETE /configurationcommands/{id}
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
$result = DB::table("commands")
->select("object_uuid")
->where("id", "=", $id)
->get();
$object_uuid = $result[0]->object_uuid;
DB::table("commands")->where("id", "=", $id)->delete();
DB::table("objects")->where("uuid", "=", $object_uuid)->delete();
$this->writeConfig();
return Response::json(array("success" => true));
}
private function getList()
{
return DB::table("commands")
->join("objects", "commands.object_uuid", "=", "objects.uuid")
->select("commands.id", "objects.first_name as command_name", "commands.command_line")
->orderBy("commands.created_at", "desc")
->get();
}
private function writeConfig()
{
global $config;
$file = $config["NAGIOS_OBJECTS_DIR"].$config["NAGIOS_COMMANDS_CFG"];
$commands = $this->getList();
$contents = "";
if (file_exists($file)) {
unlink($file);
}
foreach ($commands as $command) {
$contents .= $config["NAGIOS_DEFINE_COMMAND"]."{\n";
$contents .= "\tcommand_name\t".$command->command_name."\n";
$contents .= "\tcommand_line\t".$command->command_line."\n";
$contents .= "}\n\n";
}
file_put_contents($file, $contents, FILE_APPEND | LOCK_EX);
}
}
|
JavaScript
|
UTF-8
| 5,165
| 2.703125
| 3
|
[] |
no_license
|
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import axios from "axios";
import Selector from "./components/Selector";
import Passage from "./components/Passage";
import Favorites from "./components/Favorites";
import FavoriteButton from "./components/FavoriteButton";
class App extends Component {
constructor() {
super();
this.state = {
version: {},
versions: [],
book: {},
books: [],
chapter: "",
chapters: [],
verse: {},
verses: [],
randomVerse: {},
updateState: false
};
this.getChaps = this.getChaps.bind(this);
this.getVerses = this.getVerses.bind(this);
this.updateVersion = this.updateVersion.bind(this);
this.updateBook = this.updateBook.bind(this);
this.updateChapter = this.updateChapter.bind(this);
this.updateVerse = this.updateVerse.bind(this);
this.updateState = this.updateState.bind(this);
}
componentDidMount() {
axios
.get("/api/versions")
.then(response => {
this.setState({
version: response.data[0],
versions: response.data
});
})
.then(response => {
axios
.get(`/api/books`)
.then(response => {
this.setState({
book: response.data[0],
books: response.data
});
})
.then(response => {
this.getChaps(this.state.version.slug, this.state.book.slug);
});
});
}
componentDidUpdate() {}
getChaps(version, book) {
let urlParam = version + "/" + book;
console.log("This URL PARAMETER: " + urlParam);
axios
.get(`/api/chapters/${urlParam}`)
.then(response => {
console.log("!@!@!@!xyz", urlParam);
this.setState({
chapter: response.data[0],
chapters: response.data
});
})
.then(response => {
this.getVerses(
this.state.version.slug,
this.state.book.slug,
this.state.chapter
);
});
}
getVerses(version, book, chapter) {
let urlParam = version + "/" + book + "/" + chapter;
console.log(urlParam);
axios.get(`/api/verses/${urlParam}`).then(response => {
this.setState({
verse: response.data[0],
verses: response.data
});
});
}
updateVersion(event) {
let answer = this.state.versions.filter(val => {
return val.name === event.target.value;
});
this.setState(
{ version: answer[0] },
this.getChaps(answer[0].slug, this.state.book.slug)
);
}
updateBook(event) {
let answer = this.state.books.filter(val => {
return val.name === event.target.value;
});
console.log(answer);
this.setState(
{ book: answer[0] },
this.getChaps(this.state.version.slug, answer[0].slug)
);
console.log(this.state.book.slug);
}
updateChapter(event) {
this.setState(
{ chapter: event.target.value },
this.getVerses(
this.state.version.slug,
this.state.book.slug,
event.target.value
)
);
}
updateVerse(event) {
let newanswer = this.state.verses.filter(val => {
return val.slug == event.target.value;
});
this.setState({ verse: newanswer[0] });
}
updateState() {
this.setState({ updateState: !this.state.updateState });
}
render() {
let chapterList = Array.from(new Set(this.state.chapters));
let verseList = this.state.verses.map((val, index) => Number(val.slug));
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Bible Navigator</h1>
<p className="App-intro">
To get started select a book, chapter, verse combination.
</p>
</header>
<h1>{this.state.version.name}</h1>
<div className="Selectors">
<Selector
criteria={this.state.versions}
onChange={e => this.updateVersion(e)}
/>
<Selector
criteria={this.state.books}
onChange={e => this.updateBook(e)}
/>
<Selector
criteria={Array.from(new Set(this.state.chapters))}
onChange={e => this.updateChapter(e)}
/>
<Selector criteria={verseList} onChange={e => this.updateVerse(e)} />
</div>
<div className="flex center">
<Passage
title={`${this.state.book.name} ${this.state.chapter} :
${this.state.verse.ordinal}`}
text={this.state.verse.text}
className="VerseHolder"
>
<FavoriteButton
title={`${this.state.book.name} ${this.state.chapter} : ${
this.state.verse.ordinal
}`}
text={this.state.verse.text}
updateState={this.updateState}
/>
</Passage>
</div>
<Favorites
updateVerse={this.updateVerse}
updateState={this.state.updateState}
updateStateFnc={this.updateState}
/>
</div>
);
}
}
export default App;
|
C++
|
UTF-8
| 6,363
| 2.734375
| 3
|
[] |
no_license
|
/**
* ------------------------------------------------------------------------------------------------
* Stream: Monitor.h
* Author: Monteiro
*
* Created on November 26, 2015, 12:37 PM
* ------------------------------------------------------------------------------------------------
*/
#ifndef MONITOR_H
#define MONITOR_H
/**
* std
*/
#include <system_error>
#include <chrono>
#include <memory>
#include <vector>
#include <list>
/**
* space
*/
#include "SResource.h"
/**
* ------------------------------------------------------------------------------------------------
* monitor exceptions
* ------------------------------------------------------------------------------------------------
*/
typedef class SMonitorException : public std::system_error {
public:
using std::system_error::system_error;
/**
* constructor
*/
SMonitorException(std::error_code ec) : system_error(ec) {
}
} MonitorException;
typedef class SMonitorExceptionTIMEOUT : public SMonitorException {
public:
using SMonitorException::SMonitorException;
/**
* constructor
*/
SMonitorExceptionTIMEOUT(const std::string& msg)
: SMonitorException(std::make_error_code(std::errc::stream_timeout), msg) {
}
SMonitorExceptionTIMEOUT()
: SMonitorException(std::make_error_code(std::errc::stream_timeout)) {
}
} MonitorExceptionTIMEOUT;
typedef class SMonitorExceptionCANCEL : public SMonitorException {
public:
using SMonitorException::SMonitorException;
/**
* constructor
*/
SMonitorExceptionCANCEL(const std::string& msg)
: SMonitorException(make_error_code(std::errc::no_such_process), msg) {
}
SMonitorExceptionCANCEL()
: SMonitorException(make_error_code(std::errc::no_such_process)) {
}
} MonitorExceptionCANCEL;
/**
* ------------------------------------------------------------------------------------------------
* Monitor
* ------------------------------------------------------------------------------------------------
*/
class SMonitor {
public:
using Handler = SResource::pHandler<>;
using Handlers = std::vector<Handler>;
using Time = std::chrono::milliseconds;
/**
* ------------------------------------------------------------------------
* handler for native system
* ------------------------------------------------------------------------
* handler
*/
class SHandler {
protected:
SHandler() = default;
virtual ~SHandler() = default;
};
/**
* handler type
*/
template<class H = SHandler>
using pHandler = std::shared_ptr<H>;
/**
* handler pointer
*/
template<class H = SHandler>
inline pHandler<H> handler() const {
return std::static_pointer_cast<H>(__h);
}
/**
* ------------------------------------------------------------------------
* Interfaces
* ------------------------------------------------------------------------
* size
*/
virtual size_t size() = 0;
/**
* insert
*/
virtual size_t insert(Handler h) = 0;
/**
* wait
*/
virtual std::list<size_t> wait(const Time& timeout) = 0;
protected:
/**
* ------------------------------------------------------------------------
* Constructor
* ------------------------------------------------------------------------
*/
SMonitor() = default;
/***
* ------------------------------------------------------------------------
* methods
* ------------------------------------------------------------------------
* set phandler
*/
template<class H = SHandler>
void handler(pHandler<H> h) {
__h = std::static_pointer_cast<SHandler>(h);
}
private:
/**
* ------------------------------------------------------------------------
* variables
* ------------------------------------------------------------------------
**
* pointer to handler
*/
pHandler<SHandler> __h;
};
namespace Monitor {
/**
* ------------------------------------------------------------------------------------------------
* base - static monitor
* ------------------------------------------------------------------------------------------------
*/
class SStatic: public SMonitor {
protected:
/**
* ------------------------------------------------------------------------
* Defaults
* ------------------------------------------------------------------------
*/
SStatic(SStatic &&) = default;
SStatic& operator=(SStatic &&) = default;
/**
* ------------------------------------------------------------------------
* Constructor
* ------------------------------------------------------------------------
*/
SStatic();
/**
* ------------------------------------------------------------------------
* Interfaces
* ------------------------------------------------------------------------
* size
*/
size_t size() override;
/**
* insert
*/
size_t insert(Handler h) override;
/**
* wait
*/
std::list<size_t> wait(const Time& timeout) override;
};
/**
* ------------------------------------------------------------------------------------------------
* Base - Dynamic monitor
* ------------------------------------------------------------------------------------------------
*/
class SDynamic: public SMonitor, public SResource {
protected:
/**
* ------------------------------------------------------------------------
* Defaults
* ------------------------------------------------------------------------
*/
SDynamic(SDynamic &&) = default;
SDynamic& operator=(SDynamic &&) = default;
/**
* ------------------------------------------------------------------------
* constructor
* ------------------------------------------------------------------------
*/
SDynamic();
/**
* ------------------------------------------------------------------------
* Interfaces
* ------------------------------------------------------------------------
* size
*/
size_t size() override;
/**
* insert
*/
size_t insert(Handler h) override;
/**
* wait
*/
std::list<size_t> wait(const Time& timeout) override;
};
/**
* ------------------------------------------------------------------------------------------------
* End
* ------------------------------------------------------------------------------------------------
*/
}
#endif /* MONITOR_H */
|
Java
|
UTF-8
| 377
| 1.984375
| 2
|
[] |
no_license
|
package org.germanbeyger.lab5.server_commands;
import org.germanbeyger.lab5.datatypes.SendableCommand;
import org.germanbeyger.lab5.datatypes.TargetCollection;
public final class History {
private History() {}
public static String execute(SendableCommand command, TargetCollection targetCollection) {
return targetCollection.getStringifiedHistory();
}
}
|
Java
|
UTF-8
| 26,636
| 2.359375
| 2
|
[
"WTFPL"
] |
permissive
|
package de.uni_stuttgart.riot.thing;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnore;
import de.uni_stuttgart.riot.commons.rest.data.Storable;
import de.uni_stuttgart.riot.notification.NotificationSeverity;
import de.uni_stuttgart.riot.references.ParentReference;
import de.uni_stuttgart.riot.references.Referenceable;
import de.uni_stuttgart.riot.references.ResolveReferenceException;
import de.uni_stuttgart.riot.thing.rest.ThingPermission;
import de.uni_stuttgart.riot.thing.ui.UIHint;
/**
* A {@link Thing} (e.g. Car, House, ...) contains Properties, supported {@link Action}s and {@link Event}s. Apart from this, each thing
* contains a reference to its {@link ThingBehavior} and some meta-information like its name, owner and parent.
*/
public class Thing extends Storable implements Referenceable<Thing> {
final Map<String, Property<?>> properties = new HashMap<String, Property<?>>();
final Map<String, Event<?>> events = new HashMap<String, Event<?>>();
final Map<String, Action<?>> actions = new HashMap<String, Action<?>>();
private final transient ThingBehavior behavior;
private final ParentReference parent = new ParentReference(this);
private long ownerId;
private String name;
/**
* Creates a new thing.
*
* @param behavior
* The behavior for this thing.
*/
public Thing(ThingBehavior behavior) {
this.behavior = behavior;
this.behavior.register(this);
}
/**
* Creates a new action for the thing.
*
* @param <A>
* The type of instances of the action.
* @param actionName
* The name of the action. Must be unique, i.e., this method can only be called once for each name.
* @param instanceType
* The type of instances of the action.
* @return The newly created action.
*/
protected <A extends ActionInstance> Action<A> newAction(String actionName, Class<A> instanceType) {
return getBehavior().newAction(actionName, instanceType);
}
/**
* Creates a new action without parameters for the thing.
*
* @param actionName
* The name of the action. Must be unique, i.e., this method can only be called once for each name.
* @return The newly created action.
*/
protected Action<ActionInstance> newAction(String actionName) {
return getBehavior().newAction(actionName, ActionInstance.class);
}
/**
* Creates a new event for the thing.
*
* @param <E>
* The type of instances of the event.
* @param eventName
* The name of the event. Must be unique, i.e., this method can only be called once for each name.
* @param instanceType
* The type of instances of the event.
* @return The newly created event.
*/
protected <E extends EventInstance> Event<E> newEvent(String eventName, Class<E> instanceType) {
return getBehavior().newEvent(eventName, instanceType);
}
/**
* Creates a new event without parameters for the thing.
*
* @param eventName
* The name of the event. Must be unique, i.e., this method can only be called once for each name.
* @return The newly created event.
*/
protected Event<EventInstance> newEvent(String eventName) {
return getBehavior().newEvent(eventName, EventInstance.class);
}
/**
* Creates a new {@link NotificationEvent} for the thing.
*
* @param <E>
* The type of instances of the event.
* @param eventName
* The name of the event. Must be unique, i.e., this method can only be called once for each name.
* @param instanceType
* The type of instances of the event.
* @param severity
* The severity of the notifications fired by the created notification event.
* @param titleKey
* The key of the message title in notification.properties.
* @param messageKey
* The key of the message in notification.properties.
* @param permissions
* The permissions that a user needs to have on the thing to receive the notifications fired by the NotificationEvent. If no
* permissions are specified, the {@link ThingPermission#READ} permission will be required.
* @return The newly created notification.
*/
protected <E extends EventInstance> NotificationEvent<E> newNotification(String eventName, Class<E> instanceType, NotificationSeverity severity, String titleKey, String messageKey, ThingPermission... permissions) {
EnumSet<ThingPermission> permissionsSet;
if (permissions.length == 0) {
permissionsSet = EnumSet.of(ThingPermission.READ);
} else {
permissionsSet = EnumSet.of(permissions[0], permissions);
}
return getBehavior().newNotification(eventName, instanceType, severity, titleKey, messageKey, permissionsSet);
}
/**
* Creates a new {@link NotificationEvent} for the thing. The <tt>titleKey</tt> and <tt>messageKey</tt> are derived canonically from the
* Thing's type and the event name. See <tt>notification_xx.properties</tt> for details.
*
* @param <E>
* The type of instances of the event.
* @param eventName
* The name of the event. Must be unique, i.e., this method can only be called once for each name.
* @param instanceType
* The type of instances of the event.
* @param severity
* The severity of the notifications fired by the created notification event.
* @param permissions
* The permissions that a user needs to have on the thing to receive the notifications fired by the NotificationEvent. If no
* permissions are specified, the {@link ThingPermission#READ} permission will be required.
* @return The newly created notification.
*/
protected <E extends EventInstance> NotificationEvent<E> newNotification(String eventName, Class<E> instanceType, NotificationSeverity severity, ThingPermission... permissions) {
String notificationName = getClass().getSimpleName() + "_" + eventName;
return newNotification(eventName, instanceType, severity, notificationName + "_title", notificationName + "_message", permissions);
}
/**
* Creates a new {@link NotificationEvent} without parameters for the thing. The <tt>titleKey</tt> and <tt>messageKey</tt> are derived
* canonically from the Thing's type and the event name. See <tt>notification_xx.properties</tt> for details.
*
* @param eventName
* The name of the event. Must be unique, i.e., this method can only be called once for each name.
* @param severity
* The severity of the notifications fired by the created notification event.
* @param permissions
* The permissions that a user needs to have on the thing to receive the notifications fired by the NotificationEvent. If no
* permissions are specified, the {@link ThingPermission#READ} permission will be required.
* @return The newly created notification.
*/
protected NotificationEvent<EventInstance> newNotification(String eventName, NotificationSeverity severity, ThingPermission... permissions) {
return newNotification(eventName, EventInstance.class, severity, permissions);
}
/**
* Creates a new property for the thing.
*
* @param <V>
* The type of the property's values.
* @param propertyName
* The name of the property. Must be unique, i.e., this method can only be called once for each name.
* @param valueType
* The type of the property's values.
* @param initialValue
* The initial value of the property.
* @return The newly created property.
*/
protected <V> Property<V> newProperty(String propertyName, Class<V> valueType, V initialValue) {
return newProperty(propertyName, valueType, initialValue, null);
}
/**
* Creates a new property for the thing.
*
* @param <V>
* The type of the property's values.
* @param propertyName
* The name of the property. Must be unique, i.e., this method can only be called once for each name.
* @param valueType
* The type of the property's values.
* @param initialValue
* The initial value of the property.
* @param uiHint
* The UI hint for the property. See {@link UIHint} for static factory methods.
* @return The newly created property.
*/
protected <V> Property<V> newProperty(String propertyName, Class<V> valueType, V initialValue, UIHint uiHint) {
return getBehavior().newProperty(propertyName, valueType, initialValue, uiHint);
}
/**
* Creates a new writable property for the thing.
*
* @param <V>
* The type of the property's values.
* @param propertyName
* The name of the property. Must be unique, i.e., this method can only be called once for each name.
* @param valueType
* The type of the property's values.
* @param initialValue
* The initial value of the property.
* @return The newly created property.
*/
protected <V> WritableProperty<V> newWritableProperty(String propertyName, Class<V> valueType, V initialValue) {
return newWritableProperty(propertyName, valueType, initialValue, null);
}
/**
* Creates a new writable property for the thing.
*
* @param <V>
* The type of the property's values.
* @param propertyName
* The name of the property. Must be unique, i.e., this method can only be called once for each name.
* @param valueType
* The type of the property's values.
* @param initialValue
* The initial value of the property.
* @param uiHint
* The UI hint for the property. See {@link UIHint} for static factory methods.
* @return The newly created property.
*/
protected <V> WritableProperty<V> newWritableProperty(String propertyName, Class<V> valueType, V initialValue, UIHint uiHint) {
return getBehavior().newWritableProperty(propertyName, valueType, initialValue, uiHint);
}
/**
* Creates a new reference property for the thing.
*
* @param <R>
* The type of the referenced entities.
* @param propertyName
* The name of the property.
* @param targetType
* The type of the referenced entities.
* @return The newly created property.
*/
protected <R extends Referenceable<? super R>> ReferenceProperty<R> newReferenceProperty(String propertyName, Class<R> targetType) {
return newReferenceProperty(propertyName, targetType, null);
}
/**
* Creates a new reference property for the thing.
*
* @param <R>
* The type of the referenced entities.
* @param propertyName
* The name of the property.
* @param targetType
* The type of the referenced entities.
* @param uiHint
* The UI hint for the property. See {@link UIHint} for static factory methods.
* @return The newly created property.
*/
protected <R extends Referenceable<? super R>> ReferenceProperty<R> newReferenceProperty(String propertyName, Class<R> targetType, UIHint uiHint) {
return getBehavior().newReferenceProperty(propertyName, targetType, uiHint);
}
/**
* Creates a new writable reference property for the thing.
*
* @param <R>
* The type of the referenced entities.
* @param propertyName
* The name of the property.
* @param targetType
* The type of the referenced entities.
* @return The newly created property.
*/
protected <R extends Referenceable<? super R>> WritableReferenceProperty<R> newWritableReferenceProperty(String propertyName, Class<R> targetType) {
return newWritableReferenceProperty(propertyName, targetType, null);
}
/**
* Creates a new writable reference property for the thing.
*
* @param <R>
* The type of the referenced entities.
* @param propertyName
* The name of the property.
* @param targetType
* The type of the referenced entities.
* @param uiHint
* The UI hint for the property. See {@link UIHint} for static factory methods.
* @return The newly created property.
*/
protected <R extends Referenceable<? super R>> WritableReferenceProperty<R> newWritableReferenceProperty(String propertyName, Class<R> targetType, UIHint uiHint) {
return getBehavior().newWritableReferenceProperty(propertyName, targetType, uiHint);
}
/**
* Gets the {@link ParentReference} of this Thing.
*
* @return The parent reference. Note: Use this with care. Especially, it can be harmful to set this property without checking for
* cycles first!
*/
public ParentReference getParentReference() {
return parent;
}
/**
* Gets the ID of the parent thing.
*
* @return The parent's ID or <tt>null</tt> if there is no parent.
*/
public Long getParentId() {
return parent.getId();
}
/**
* Sets the parent ID. Note: Use with care. This method might lead to an inconsistent thing hierarchy! Always prefer
* {@link #setParent(Thing)}.
*
* @param parentId
* The new parent ID or <tt>null</tt> for no parent.
*/
public void setParentId(Long parentId) {
parent.setId(parentId);
}
/**
* Gets the parent of this Thing.
*
* @return The thing's parent or <tt>null</tt> if it does not have a parent.
* @throws ResolveReferenceException
* When the parent should be present but could not be resolved.
*/
public Thing getParent() throws ResolveReferenceException {
return parent.getTarget();
}
/**
* Checks if this thing has a parent. This does not mean that the parent still exists or is resolvable!
*
* @return True if this thing has a parent (and possibly more ancestors).
*/
public boolean hasParent() {
return parent.getId() != null;
}
/**
* Checks if the given <tt>otherThing</tt> is somewhere up the parent hierarchy of this thing. In particular, this method returns
* <tt>true</tt> if making the given <tt>otherThing</tt> the parent of <tt>this</tt> thing would lead to a circle in the parent
* hierarchy. This method is recursive, but it will always terminate if there is not already a cycle in the parent hierarchy.
*
* @param otherThing
* The potential ancestor.
* @return True if <tt>otherThing</tt> is an ancestor of this thing.
* @throws ResolveReferenceException
* If the parent hierarchy contains an error because a parent reference cannot be resolved.
*/
public boolean hasAncestor(Thing otherThing) throws ResolveReferenceException {
Thing ownParent = parent.getTarget();
if (ownParent == null) {
return false;
} else if (ownParent == otherThing) {
return true;
} else {
return ownParent.hasAncestor(otherThing);
}
}
/**
* Sets a new parent for the thing. Note that this method will throw an {@link IllegalArgumentException} if the new thing-parent
* relation would cause a cycle in the parent hierarchy.
*
* @param parent
* The new parent, may be <tt>null</tt> for no parent.
*/
public void setParent(Thing parent) {
try {
if (parent == null) {
this.parent.setTarget(null);
} else {
assertValidParent(parent);
this.parent.setTarget(parent);
}
} catch (ResolveReferenceException e) {
throw new IllegalStateException("Incomplete ancestor hierarchy", e);
}
}
/**
* Ensures that <tt>parent</tt> could become the parent of <tt>this</tt> thing without corrupting the parent hierarchy. Throws an
* {@link IllegalArgumentException} if the parent hierarchy would be invalid.
*
* @param newParent
* The possible new parent. Must not be <tt>null</tt>.
* @throws ResolveReferenceException
* When the ancestor hierarchy is corrupted.
*/
public void assertValidParent(Thing newParent) throws ResolveReferenceException {
if (newParent == this) {
throw new IllegalArgumentException("A thing cannot be its own parent.");
} else if (newParent.hasAncestor(this)) {
throw new IllegalArgumentException(this + " is already an ancestor of " + newParent + ", so that the call would result in a cycle.");
}
}
/**
* Gets the thing's name.
*
* @return The name of this thing.
*/
public String getName() {
return name;
}
/**
* Changes the name of this thing.
*
* @param name
* The new name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the owner ID.
*
* @return The ID of the user that owns this thing.
*/
public long getOwnerId() {
return ownerId;
}
/**
* Sets the owner ID.
*
* @param ownerId
* The ID of the user that owns this thing.
*/
public void setOwnerId(long ownerId) {
this.ownerId = ownerId;
}
/**
* Gets the behavior.
*
* @return The behavior of this thing.
*/
@JsonIgnore
public ThingBehavior getBehavior() {
return behavior;
}
/**
* Retrieves an event by its name.
*
* @param eventName
* The name of the event.
* @return The event or <tt>null</tt> if the event does not exist.
*/
public Event<?> getEvent(String eventName) {
return events.get(eventName);
}
/**
* Retrieves a typed event by its name.
*
* @param <E>
* The type of the event's instances.
* @param eventName
* The name of the event.
* @param instanceType
* The expected type of the event.
* @return The event, <tt>null</tt> if an event with this name does not exist or an {@link IllegalArgumentException} if the event exists
* but has a different instance type.
*/
public <E extends EventInstance> Event<E> getEvent(String eventName, Class<E> instanceType) {
Event<?> event = getEvent(eventName);
if (event == null) {
return null;
} else if (event.getInstanceType() != instanceType) {
throw new IllegalArgumentException("The instanceType " + instanceType + " did not match the actual type " + event.getInstanceType());
}
@SuppressWarnings("unchecked")
Event<E> result = (Event<E>) event;
return result;
}
/**
* Returns a non-editable collection of all events that this thing has.
*
* @return The events of this thing.
*/
public Collection<Event<?>> getEvents() {
return Collections.unmodifiableCollection(events.values());
}
/**
* Retrieves an action by its name.
*
* @param actionName
* The name of the action.
* @return The action or <tt>null</tt> if the action does not exist.
*/
public Action<?> getAction(String actionName) {
return actions.get(actionName);
}
/**
* Retrieves a typed action by its name.
*
* @param <A>
* The type of the action instances.
* @param actionName
* The name of the action.
* @param instanceType
* The expected type of the action.
* @return The action, <tt>null</tt> if an action with this name does not exist or an {@link IllegalArgumentException} if the action
* exists but has a different instance type.
*/
public <A extends ActionInstance> Action<A> getAction(String actionName, Class<A> instanceType) {
Action<?> action = getAction(actionName);
if (action == null) {
return null;
} else if (action.getInstanceType() != instanceType) {
throw new IllegalArgumentException("The instanceType " + instanceType + " did not match the actual type " + action.getInstanceType());
}
@SuppressWarnings("unchecked")
Action<A> result = (Action<A>) action;
return result;
}
/**
* Returns a non-editable collection of all actions that this thing has.
*
* @return The actions of this thing.
*/
public Collection<Action<?>> getActions() {
return Collections.unmodifiableCollection(actions.values());
}
/**
* Retrieves a property by its name.
*
* @param propertyName
* The name of the property.
* @return The property or <tt>null</tt> if the action does not exist.
*/
public Property<?> getProperty(String propertyName) {
return properties.get(propertyName);
}
/**
* Retrieves a typed property by its name.
*
* @param <V>
* The type of the property's values.
* @param propertyName
* The name of the property.
* @param valueType
* The expected value type of the property.
* @return The property, <tt>null</tt> if a property with this name does not exist or an {@link IllegalArgumentException} if the
* property exists but has a different value type.
*/
public <V> Property<V> getProperty(String propertyName, Class<V> valueType) {
Property<?> property = getProperty(propertyName);
if (property == null) {
return null;
} else if (property.getValueType() != valueType) {
throw new IllegalArgumentException("The valueType " + valueType + " did not match the actual type " + property.getValueType());
}
@SuppressWarnings("unchecked")
Property<V> result = (Property<V>) property;
return result;
}
/**
* Retrieves a writable property by its name.
*
* @param propertyName
* The name of the property.
* @return The property, <tt>null</tt> if a property with this name does not exist or a {@link IllegalArgumentException} if the property
* is not writable.
*/
public WritableProperty<?> getWritableProperty(String propertyName) {
Property<?> property = getProperty(propertyName);
if (property instanceof WritableProperty) {
return (WritableProperty<?>) property;
} else {
throw new IllegalArgumentException("The property " + propertyName + " is not writable!");
}
}
/**
* Retrieves a typed writable property by its name.
*
* @param <V>
* The type of the property's values.
* @param propertyName
* The name of the property.
* @param valueType
* The expected value type of the property.
* @return The property, <tt>null</tt> if a property with this name does not exist or an {@link IllegalArgumentException} if the
* property exists but has a different value type or if it is not writable.
*/
public <V> WritableProperty<V> getWritableProperty(String propertyName, Class<V> valueType) {
Property<V> property = getProperty(propertyName, valueType);
if (property instanceof WritableProperty) {
return (WritableProperty<V>) property;
} else {
throw new IllegalArgumentException("The property " + propertyName + " is not writable!");
}
}
/**
* Returns a non-editable collection of all properties that this thing has.
*
* @return The properties of this thing.
*/
public Collection<Property<?>> getProperties() {
return Collections.unmodifiableCollection(properties.values());
}
@Override
public String toString() {
StringBuilder output = new StringBuilder();
output.append(getClass().getSimpleName());
output.append("[id=");
output.append(getId());
output.append(", name=");
output.append(getName());
output.append(", behavior=");
output.append(behavior.getClass().getSimpleName());
for (Property<?> property : properties.values()) {
output.append(", ");
output.append(property.getName());
output.append("=");
output.append(property.get());
}
output.append("]");
return output.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((actions == null) ? 0 : actions.hashCode());
result = prime * result + ((events == null) ? 0 : events.hashCode());
result = prime * result + ((properties == null) ? 0 : properties.hashCode());
return result;
}
/**
* Two things are equal if they are of the same type, have the same ID, the same name and their properties set to the same values.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Thing other = (Thing) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return actions.equals(other.actions) && events.equals(other.events) && properties.equals(other.properties);
}
}
|
C++
|
UTF-8
| 1,740
| 2.625
| 3
|
[] |
no_license
|
#ifndef _J1_GROUP_MOVEMENT_
#define _J1_GROUP_MOVEMENT_
#include "j1Module.h"
#include "p2Point.h"
#include "j1EntitiesManager.h"
#define FORMATION_WIDTH_LIMIT 5
#define FORMATION_HEIGHT_LIMIT 5
enum FormationType {
NO_FORMATION,
SQUARE_CLOSE_FORMATION,
SQUARE_SEPARATE_FORMATION
};
struct Formation
{
void SetFormation(int size);
int formationSize = 0;
int height = 0;
int width = 0;
FormationType formation_type = NO_FORMATION;
};
class j1GroupMovement :public j1Module
{
public:
j1GroupMovement();
~j1GroupMovement();
void Init();
//Functions
//CreatePath
//Set middle_point
//leader path on middle_point other units path around the middle_point
//leader do path to destination other units copy the path with minor modifications
//return the path to units
iPoint destination = { 0,0 };;
iPoint map_destination = { 0,0 };;
void AttackOnGroup(std::list<Entity*>* units, Entity* target, bool active);
void HealOnGroup(std::list<Entity*>* units, Entity* target);
void RecolectOnGroup(std::list<Entity*>* units, Resource* resource);
void GetGroupOfUnits(std::list<Entity*>* units, int x, int y, bool active);
private:
iPoint GetMiddlePoint();
void OtherUnitsPath(bool active);
bool GroupCanWalk(const iPoint& position);
bool PlaceTaken(const std::vector<iPoint> positions, const iPoint& check);
std::vector<iPoint>* CreatePath();
std::vector<iPoint>* CreateFirstDestination();
std::vector<iPoint>* LeaderPath();
private:
// list of units selected
// Pointer first unit "leader"
std::list<Entity*>* units = nullptr;
Entity* lead = nullptr;
iPoint middle_point = { 0,0 };
Formation formation;
int group_size = 0;
DIRECTION_TYPE lead_direcction = NO_DIRECTION;
};
#endif // !_J1_GROUP_MOVEMENT_
|
Python
|
UTF-8
| 1,012
| 3.328125
| 3
|
[] |
no_license
|
class Document:
def __init__(self, string=[]):
if string:
self.string = list(string)
else:
self.string = []
def append(self, string):
self.string.append(string)
def print(self):
printing = self.string[0]
self.string = self.string[1:]
return printing
def __len__(self):
return len(self.string)
class Printer:
def __init__(self):
self.queue = []
def enqueue(self, document):
self.queue.append(document)
def cancel(self):
self.queue = self.queue[1:]
def __len__(self):
return len(self.queue)
def pages(self):
return sum(len(document) for document in self.queue)
def print(self):
if not self.queue[0]:
printing = ""
else:
printing = self.queue[0].string[0]
self.queue[0] = self.queue[0].string[1:]
if len(self.queue[0]) == 0:
self.queue = self.queue[1:]
return printing
|
Java
|
UTF-8
| 150
| 1.976563
| 2
|
[] |
no_license
|
package iti.jets.tripplanner.interfaces;
import iti.jets.tripplanner.pojos.Trip;
public interface ObjectCarrier {
void sendTripId(Trip trip);
}
|
Java
|
UTF-8
| 1,288
| 2.90625
| 3
|
[] |
no_license
|
package main.java.model;
import java.sql.Date;
import java.text.SimpleDateFormat;
public class CityRateData {
private Date date;
private String name = null;
private int PV = 0;
private int UV = 0;
private double rate = 0;
public void setCityRateData(Date date, String name, int PV, int UV, double rate) {
this.date = date;
this.name = name;
this.PV = PV;
this.UV = UV;
this.rate = rate;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPV() {
return PV;
}
public void setPV(int PV) {
this.PV = PV;
}
public int getUV() {
return UV;
}
public void setUV(int UV) {
this.UV = UV;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
@Override
public String toString() {
return new SimpleDateFormat("yyyy-MM-dd").format(date) + '\t' + name + '\t' + String.valueOf(PV) + '\t' + String.valueOf(UV) + '\t' + Double.toString(rate);
}
}
|
Java
|
UTF-8
| 2,338
| 2.375
| 2
|
[] |
no_license
|
package text;
import com.itcast.domain.Account3;
import com.itcast.service.ServiceAccount;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* 测试
*/
public class TextAccount {
/**
* 查询所有
*/
@Test
public void testFindAll(){
//读取核心容器对象
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
// 获取业务层实体类对象
ServiceAccount bean = ac.getBean(ServiceAccount.class);
List<Account3> allAccount3 = bean.findAllAccount3();
for (Account3 account3 : allAccount3) {
System.out.println(account3);
}
}
/**
* 查询一个
*
*/
@Test
public void testFindById(){
// 读取核心容器对象
ApplicationContext ca=new ClassPathXmlApplicationContext("bean.xml");
// 获取业务层对象
ServiceAccount bean = ca.getBean(ServiceAccount.class);
Account3 byId = bean.findById(1);
System.out.println(byId);
}
/**
* 保存
*/
@Test
public void testSave(){
Account3 account3=new Account3();
account3.setId(4);
account3.setName("古乐天");
account3.setMoney(10000000.0);
// 读取核心容器对象
ApplicationContext ca=new ClassPathXmlApplicationContext("bean.xml");
// 获取业务层对象
ServiceAccount bean = ca.getBean(ServiceAccount.class);
bean.saveAccount3(account3);
}
/**
* 删除
*/
@Test
public void testDelete(){
// 读取核心容器对象
ApplicationContext ca=new ClassPathXmlApplicationContext("bean.xml");
// 获取业务层对象
ServiceAccount bean = ca.getBean(ServiceAccount.class);
bean.deleteAccount3(4);
}
/**
* 更新
*/
@Test
public void testUpdate(){
// 读取核心容器对象
ApplicationContext ca=new ClassPathXmlApplicationContext("bean.xml");
// 获取业务层对象
ServiceAccount bean = ca.getBean(ServiceAccount.class);
Account3 byId = bean.findById(1);
byId.setMoney(80000.0);
bean.updateAccount3(byId);
}
}
|
C#
|
UTF-8
| 8,490
| 2.515625
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Attached to the prefabFileMenu. Used as both a Load Game and Save Game menu.
/// Buttons are adjusted based on the scenario.
/// Creates "slots" representing current save game files, which are external files.
/// File operations are handled by FileUtil. Player-specific info is stored in PlayerPrefs.
/// REFACTOR: Make a generic "panel" interface that can be used by this and any inventory menu.
/// </summary>
public class FileMenuMonitor : MonoBehaviour
{
#region Fields
// Fields set for the prefab
[SerializeField]
Text welcomeLabel = null, newSlotText = null, deleteSaveText = null,
saveText = null, loadText = null;
[SerializeField]
GameObject gridContents = null;
// Index of the selected slot
int? selection = null;
// prefab dialog box
GameObject confirmationDialog;
#endregion
#region Methods
// Sets up the menu as either a Load or Save menu, used intead of Start()
public void SetupFileMenu(bool asSave)
{
// Set up as a listener for selection events and confirmation
EventManager.AddListener_PanelSelect(MakeSelection);
EventManager.AddListener_Confirmation(ConfirmDeleteSlot);
// Shows Load, Save, Create Save, Delete, etc. buttons
ShowHideButtons(asSave);
// Produces clickable slots for each save file curently existing
PopulateGrid();
// Sets the welcome label
if (asSave)
{
welcomeLabel.text = "Select a file to save.";
}
else
{
welcomeLabel.text = "Select a file to load.";
}
}
// Chooses which buttons to display or hide, based on whether a Save or Load Game
void ShowHideButtons(bool asSave)
{
newSlotText.gameObject.transform.parent.gameObject.SetActive(asSave);
//deleteSaveText.gameObject.transform.parent.gameObject.SetActive(asSave);
saveText.gameObject.transform.parent.gameObject.SetActive(asSave);
loadText.gameObject.transform.parent.gameObject.SetActive(!asSave);
}
// Creates slots as buttons, representing available save files
void PopulateGrid()
{
// Create template panel (button)
GameObject newPanel;
GameObject prefabPanel = Resources.Load<GameObject>(@"MenuPrefabs\prefabFileSlotPanel");
// PlayerPrefs keeps track of the *maximum* number of slots that has ever
// been created by the player. This is different from the number of files available.
int maxPotentialSlots = PlayerPrefs.HasKey(PlayerPrefsKeys.HighestSlotNum.ToString()) ?
PlayerPrefs.GetInt(PlayerPrefsKeys.HighestSlotNum.ToString()) : 0;
// PlayerPrefs has an entry for each save file created. The Key is "Slot#SaveName", and
// the value is string saying either "No Save Data" or listing of the hero's names,
// the party gold, and the date of the save.
// Create a button for each key
for (int i = 0; i < maxPotentialSlots; i++)
{
if (PlayerPrefs.HasKey(KeyName(i)))
{
// Create from template
newPanel = GameObject.Instantiate(prefabPanel, gridContents.transform);
// Access FilePanel component
PanelSelection filePanel = newPanel.GetComponent<PanelSelection>();
// Set up the panel with the string to display
filePanel.SetupPanel(i, PlayerPrefs.GetString(KeyName(i)));
}
}
// Disable buttons until a slot is clicked
EnableButtons(false);
}
// Destroys the displayed slots, in order to repopulate an updated display
void ClearGrid()
{
for (int i = 0; i < gridContents.transform.childCount; i++)
{
Destroy(gridContents.transform.GetChild(i).gameObject);
}
}
// Converts an int to a string, used as a key in PlayerPrefs
string KeyName (int slot)
{
return "Slot" + slot + "SaveName";
}
// Selects or deselects a slot button. Invoked when a slot is clicked.
void MakeSelection(int? index)
{
if (index != null)
{
if (selection == index)
{
selection = null;
EnableButtons(false);
}
else
{
selection = index;
EnableButtons(true);
}
}
else
{
Debug.Log("null index sent through events");
}
}
// Sets buttons (Load, Save, etc.) as either interactable or not
void EnableButtons(bool on)
{
Color color = on ? Color.white : Color.gray;
deleteSaveText.GetComponent<Button>().interactable = on;
deleteSaveText.color = color;
saveText.GetComponent<Button>().interactable = on;
saveText.color = color;
loadText.GetComponent<Button>().interactable = on;
loadText.color = color;
}
// Create a slot button representing an empty save slot
public void Click_NewSlot()
{
AudioManager.Chirp();
Debug.Log("Create new slot");
// Count how many consecutive save slots are mentioned in PlayerPrefs
// If a slot has been deleted, this will find the gap.
int i = 0;
while (PlayerPrefs.HasKey(KeyName(i)))
{
i++;
}
// Create an empty entry in PlayerPrefs
PlayerPrefs.SetString(KeyName(i), "No Save Data");
// If a new highest is created, store the new highest
if (PlayerPrefs.HasKey(PlayerPrefsKeys.HighestSlotNum.ToString()))
{
int highest = PlayerPrefs.GetInt(PlayerPrefsKeys.HighestSlotNum.ToString());
if (i > highest)
{
PlayerPrefs.SetInt(PlayerPrefsKeys.HighestSlotNum.ToString(), i);
}
}
else
{
PlayerPrefs.SetInt(PlayerPrefsKeys.HighestSlotNum.ToString(), i);
}
// Recreate the grid including the new slot
ClearGrid();
PopulateGrid();
PlayerPrefs.Save();
}
// Called by the Delete button's On_Click().
public void Click_DeleteSlot()
{
AudioManager.Chirp();
// Load confirmation dialogue, Delete when OK is clicked.
confirmationDialog = Resources.Load<GameObject>(@"MenuPrefabs\prefabConfirmation");
GameObject.Instantiate(confirmationDialog);
}
// Called by confirmation event
void ConfirmDeleteSlot(bool ok)
{
// If cancel, then do nothing
if (ok)
{
// Delete the key from playerprefs
PlayerPrefs.DeleteKey(KeyName((int)selection));
// Redo the grid without the deleted slot.
ClearGrid();
PopulateGrid();
PlayerPrefs.Save();
}
}
// Called by Save button On_Click()
public void Click_SaveGame()
{
// Only save when a selection is active
AudioManager.PlaySound(AudioClipName.Save);
if (selection != null)
{
// Create a new SaveFile (class instance), based on slot selected
SaveFile saveFile = new SaveFile((int)selection);
// Put game data into the saveFile, then write it into a file
saveFile.SaveData();
FileUtil.WriteData(saveFile);
// Set PlayerPrefs value from saveFile
PlayerPrefs.SetString(KeyName((int)selection), saveFile.ToString());
// Redo display
ClearGrid();
PopulateGrid();
PlayerPrefs.Save();
}
}
// Called by Load button On_Click()
public void Click_LoadGame()
{
AudioManager.PlaySound(AudioClipName.Save);
if (selection != null)
{
// Replace current game data with data from the file
FileUtil.LoadData((int)selection);
// Go back to town and exit menu
MenuManager.GoToMenu(MenuName.MainToTown);
Destroy(gameObject);
}
}
// Destroy this menu and return to previous
public void Click_CloseButton()
{
AudioManager.Close();
Destroy(gameObject);
}
#endregion
}
|
Java
|
UTF-8
| 1,833
| 2.6875
| 3
|
[] |
no_license
|
/**
* Project Name:Infrared
* File Name:SocketAddress.java
* Package Name:com.syzx.infrared.service
* Date:2017年12月31日下午1:29:32
* Copyright (c) 2017, syzx.com All Rights Reserved.
*
*/
package com.syzx.infrared.service.web;
import java.net.InetSocketAddress;
import com.syzx.infrared.service.interfaces.ISocketAddress;
/**
* ClassName: SocketAddress <br/>
* Function: TODO 描述类的功能. <br/>
* date: 2017年12月31日 下午1:29:32 <br/>
*
* @author Zxy
* @version
* @since JDK 1.8
*/
public class SocketAddress extends AbstractNetAddress implements ISocketAddress {
private String ip;
private int port;
/**
*创建一个NetSocketAddress的实例.
*
* @param ip
*/
public SocketAddress(String ip, int port) {
this.ip = ip;
this.port = port;
}
/**
* TODO 简单描述该方法的实现功能(可选).
* @see com.syzx.infrared.service.web.AbstractNetAddress#getPort()
*/
public int getPort() {
return port;
}
/**
* TODO 简单描述该方法的实现功能(可选).
* @see com.syzx.infrared.service.web.AbstractNetAddress#toInetSocketAddress()
*/
public InetSocketAddress toInetSocketAddress() {
return new InetSocketAddress(getIp(), getPort());
}
/**
* TODO 简单描述该方法的实现功能(可选).
* @see com.syzx.infrared.service.interfaces.ISocketAddress#generateUrl()
*/
public String generateUrl() {
return generateUrl(ip, port);
}
/**
* TODO 简单描述该方法的实现功能(可选).
* @see com.syzx.infrared.service.interfaces.ISocketAddress#getIp()
*/
public String getIp() {
return ip;
}
}
|
C
|
UTF-8
| 15,326
| 2.859375
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <unistd.h>
#include "gfx.h"
#define BLUE 10
#define RED -10
#define XSIZE 1000
#define YSIZE 800
#define UP 'A';
#define DOWN 'B';
#define LEFT 'D';
#define RIGHT 'C';
int locations[YSIZE][XSIZE];
double bullets1[100][5]; //BLUE TANK BULLETS - Whether it's on the board, x position, y position, delta x, delta y
double bullets2[100][5]; //RED TANK BULLETS - Whether it's on the board, x position, y position, delta x, delta y
int redDirection = 1; //1 equal to moving up / down, 2 equal to moving side to side
int blueDirection = 1;
char livesStr[30]; //prints current lives onto graphics screen
int randTime; //initializes randomized time for CPU shooter
int randBullets; //CPU randomly fires 10 bullets every now and then
clock_t start_t, end_t, total_t;
struct tank {
int xPos;
int yPos;
double deltaX;
double deltaY;
double theta;
int color;
int lives;
} blueTank, redTank;
void fireBullet(int, int);
void setLocations(void);
void setTanks(void);
void drawTanks(void);
void drawTanks2(void);
void applyChange(char, int);
void checkBoard(void);
void drawBodies(void);
void drawTreads(void);
void drawBullets(void);
void drawBullets2(void);
char calcCpuDirection(int, int);
int set_lives(int);
int main(void){
srand(time(NULL)); // initializes random int generator
//This part of the code sets up the program
int bullet1Num = 0;
int bullet2Num = 0;
int returnFireCount = 0;
printf("Now we are going to establish the variables\n");
char c;
char q = ' ';
gfx_open(XSIZE, YSIZE, "TANKS");
printf("The Board is now open\n");
setTanks();
printf("The Tanks are now set to their original positions\n");
drawTanks();
printf("The Board is now drawn\n");
gfx_color(255,255,255);
strcpy(livesStr,"Lives: Red 10 || Blue 10");
start_t = clock();
randTime = (1 + (rand() % 3));
// Now everything is set up
while(c != 'q'){
gfx_text((XSIZE/2) - 20,YSIZE/8, "TANKS");
gfx_text((XSIZE/2) - 20,(YSIZE/8)+30, "Game by Jose Badilla and Owen Phelan");
gfx_text((XSIZE/2) - 20,(YSIZE/8)+60, "Difficulty: Left click for EASY || Right click for HARD");
redTank.lives = 10;
blueTank.lives = 10;
strcpy(livesStr,"Lives: Red 10 || Blue 10");
q = gfx_wait();
if(q == 1){
while(1){
gfx_text(3*XSIZE/4,YSIZE/8, livesStr);
if ( (redTank.lives == 0) || (blueTank.lives == 0) ){
break;
}
gfx_color(255,255,255);
gfx_text(3*XSIZE/4,YSIZE/8, livesStr);
if( gfx_event_waiting() ){
c = gfx_wait();
if(c == 'q'){ //Quits the program if they click q
break;
}
else if( c == 1){ // Fires a bullet
bullet1Num++;
bullet2Num++;
if(bullet1Num == 100){
bullet1Num = 0;
}
if(bullet2Num == 100){
bullet2Num = 0;
}
while(bullets1[bullet1Num][0] != 0){ //This while loop means that it won't overwrite any bullets that are on the board already;
bullet1Num++;
}
while(bullets2[bullet2Num][0] != 0){
bullet2Num++;
}
fireBullet(BLUE, bullet1Num);
fireBullet(RED, bullet2Num);
}
else{ // Takes the user input and moves the tank positions if its valid
applyChange(c , BLUE);
}
}
else{ // If there is no button click, it animates any bullets on the board
usleep(2000);
drawTanks();
applyChange(q , RED);
returnFireCount++;
end_t = clock();
total_t = (double)(end_t-start_t)/CLOCKS_PER_SEC;
if((randTime >= (total_t - 1)) && (randTime <= (total_t + 1))){
for (randBullets = 0; randBullets < 10; randBullets++){ //Allows CPU to shoot when user is not shooting
bullet2Num++;
if(bullet2Num == 100){
bullet2Num = 0;
}
fireBullet(RED, bullet2Num);
}
randTime = randTime + (1 + (rand() % 3));
}
if(returnFireCount == 20){
returnFireCount = 0;
q = calcCpuDirection(redTank.xPos, redTank.yPos);
}
}
gfx_color(255,255,255);
gfx_text(3*XSIZE/4,YSIZE/8, livesStr);
}
}
else if(q == 3){
while(1){
gfx_text(3*XSIZE/4,YSIZE/8, livesStr);
if ( (redTank.lives == 0) || (blueTank.lives == 0) ){
break;
}
gfx_color(255,255,255);
gfx_text(3*XSIZE/4,YSIZE/8, livesStr);
if( gfx_event_waiting() ){
c = gfx_wait();
if(c == 'q'){ //Quits the program if they click q
break;
}
else if( c == 1){ // Fires a bullet
bullet1Num++;
bullet2Num++;
if(bullet1Num == 100){
bullet1Num = 0;
}
if(bullet2Num == 100){
bullet2Num = 0;
}
while(bullets1[bullet1Num][0] != 0){ //This while loop means that it won't overwrite any bullets that are on the board already;
bullet1Num++;
}
while(bullets2[bullet2Num][0] != 0){
bullet2Num++;
}
fireBullet(BLUE, bullet1Num);
fireBullet(RED, bullet2Num);
}
else{ // Takes the user input and moves the tank positions if its valid
applyChange(c , BLUE);
}
}
else{ // If there is no button click, it animates any bullets on the board
usleep(2000);
drawTanks2();
applyChange(q , RED);
returnFireCount++;
end_t = clock();
total_t = (double)(end_t-start_t)/CLOCKS_PER_SEC;
if((randTime >= (total_t - 1)) && (randTime <= (total_t + 1))){
for (randBullets = 0; randBullets < 10; randBullets++){ //Allows CPU to shoot when user is not shooting
bullet2Num++;
if(bullet2Num == 100){
bullet2Num = 0;
}
fireBullet(RED, bullet2Num);
}
randTime = randTime + (1 + (rand() % 3));
}
if(returnFireCount == 20){
returnFireCount = 0;
q = calcCpuDirection(redTank.xPos, redTank.yPos);
}
}
gfx_color(255,255,255);
gfx_text(3*XSIZE/4,YSIZE/8, livesStr);
}
}
}
} // End Main
/*################### FUNCTIONS ######################*/
void setTanks(void){
blueTank.xPos = 750;
blueTank.yPos = 550;
blueTank.deltaX = 0;
blueTank.deltaY = 0;
blueTank.theta = 2.356;
blueTank.color = BLUE;
redTank.xPos = 50;
redTank.yPos = 50;
redTank.deltaX = 0;
redTank.deltaY = 0;
redTank.theta = 2.356;
redTank.color = RED;
int i, j;
for(i = 0 ; i < 100 ; i++){
for(j = 0 ; j < 5 ; j++){
bullets1[i][j]= 0;
bullets2[i][j]= 0;
}
}
setLocations();
}
void drawTanks(void){
gfx_clear();
setLocations();
drawBodies();
drawTreads();
drawBullets();
checkBoard();
}
void drawTanks2(void){
gfx_clear();
setLocations();
drawBodies();
drawTreads();
drawBullets2();
checkBoard();
}
void setLocations(void){
int xi, xj;
for( xi = 0 ; xi < XSIZE ; xi++){
for( xj = 0 ; xj < YSIZE ; xj++){
locations[xj][xi] = 0;
}
}
}
void applyChange(char direction, int color){
if(color == BLUE){
switch(direction){
case 'w':
blueDirection = 1;
if( blueTank.yPos > 20 ){
blueTank.yPos = blueTank.yPos-10;
}
break;
case 's':
blueDirection = 1;
if( blueTank.yPos < (YSIZE - 20) ){
blueTank.yPos = blueTank.yPos+10;
}
break;
case 'a':
blueDirection = 2;
if( blueTank.xPos > 20 ){
blueTank.xPos = blueTank.xPos-10;
}
break;
case 'd':
blueDirection = 2;
if( blueTank.xPos < (XSIZE - 20) ){
blueTank.xPos = blueTank.xPos+10;
}
break;
default:
printf("The Input is not Valid or is a Mouse Click\n");
break;
}
}
else if(color == RED){
switch(direction){
case 'w':
redDirection = 1;
if( (redTank.yPos - 27) > 0){
redTank.yPos = redTank.yPos-6;
drawTanks();
}
break;
case 's':
redDirection = 1;
if( (redTank.yPos + 27) < YSIZE){
redTank.yPos = redTank.yPos+6;
drawTanks();
}
break;
case 'a':
redDirection = 2;
if( (redTank.xPos - 27) > 0){
redTank.xPos = redTank.xPos-6;
drawTanks();
}
break;
case 'd':
redDirection = 2;
if( (redTank.xPos + 27) < XSIZE){
redTank.xPos = redTank.xPos+6;
drawTanks();
}
break;
default:
printf("The Input is not Valid or is a Mouse Click\n");
break;
}
}
}
void fireBullet(int color, int bulletNumber){
double theta1, theta2;
int x, y, deltaX, deltaY;
if(color == BLUE){
bullets1[bulletNumber][0] = 1;
bullets1[bulletNumber][1] = (double) blueTank.xPos;
bullets1[bulletNumber][2] = (double) blueTank.yPos;
x = gfx_xpos();
y = gfx_ypos();
deltaX = x - blueTank.xPos; //difference between initial position of tank and bullet destination
deltaY = y - blueTank.yPos;
theta1 = atan2(deltaY, deltaX);
bullets1[bulletNumber][3] = cos(theta1);
bullets1[bulletNumber][4] = sin(theta1);
}
else if(color == RED){
bullets2[bulletNumber][0] = 1;
bullets2[bulletNumber][1] = (double) redTank.xPos;
bullets2[bulletNumber][2] = (double) redTank.yPos;
deltaX = blueTank.xPos - redTank.xPos;
deltaY = blueTank.yPos - redTank.yPos;
theta2 = atan2(deltaY, deltaX);
bullets2[bulletNumber][3] = cos(theta2);
bullets2[bulletNumber][4] = sin(theta2);
}
}
void checkBoard(void){
int count = 0;
for(count = 0 ; count < 100 ; count++){
int xCheck1 = bullets1[count][1];
int yCheck1 = bullets1[count][2];
int xCheck2 = bullets2[count][1];
int yCheck2 = bullets2[count][2];
if( bullets1[count][0] == 1){
if( (xCheck1 < 0) || (xCheck1 > XSIZE ) || (yCheck1 < 0) || (yCheck1 > YSIZE ) ){
bullets1[count][0] = 0;
printf("The blue bullet is out of bounds\n");
}
else if( locations[xCheck1][yCheck1] == 1 ){
bullets1[count][0] = 0;
redTank.lives = set_lives(redTank.lives);
sprintf(livesStr, "Lives: Red %d || Blue %d", redTank.lives, blueTank.lives);
setTanks();
printf("The blue Bullet Hit the other Tank\n");
}
}
if( bullets2[count][0] == 1){
if( (xCheck2 < 0) || (xCheck2 > XSIZE ) || (yCheck2 < 0) || (yCheck2 > YSIZE ) ){
bullets2[count][0] = 0;
printf("The red bullet is out of bounds\n");
}
else if( locations[xCheck2][yCheck2] == 2 ){
bullets2[count][0] = 0;
blueTank.lives = set_lives(blueTank.lives);
sprintf(livesStr, "Lives: Red %d || Blue %d", redTank.lives, blueTank.lives);
setTanks();
printf("The red Bullet Hit the other Tank\n");
}
}
}
}
void drawBodies(void){
int i, j;
//This draws the inner grey square
for( i = 0 ; i < 36 ; i++){
for( j = 0 ; j < 36 ; j++){
gfx_color(192,192,192);
gfx_point(blueTank.xPos-18+i, blueTank.yPos-18+j);
gfx_point(redTank.xPos-18+i, redTank.yPos-18+j);
locations[redTank.xPos-18+i][redTank.yPos-18+j] = 1;
if(locations[blueTank.xPos-18+i][blueTank.yPos-18+j] != 0){
setTanks();
}
else{
locations[blueTank.xPos-18+i][blueTank.yPos-18+j] = 2;
}
}
}
//This draws the color inside the square
for( i = 0 ; i < 10 ; i++){
for( j = 0 ; j < 10 ; j++){
gfx_color(0,0,255);
gfx_point(blueTank.xPos-5+i, blueTank.yPos-5+j);
gfx_color(255,0,0);
gfx_point(redTank.xPos-5+i, redTank.yPos-5+j);
}
}
}
void drawTreads(void){
int i, j;
gfx_color(160,160,160);
//This Draws the Treads
if(blueDirection == 1){
for( i = 0 ; i < 8 ; i++){
for( j = 0 ; j < 44 ; j++){
gfx_point(blueTank.xPos - 26 + i , blueTank.yPos - 22 + j);
gfx_point(blueTank.xPos + 18 + i , blueTank.yPos - 22 + j);
gfx_point(redTank.xPos - 26 + i , redTank.yPos - 22 + j);
gfx_point(redTank.xPos + 18 + i , redTank.yPos - 22 + j);
locations[redTank.xPos-26+i][redTank.yPos-22+j] = 1;
locations[redTank.xPos+18+i][redTank.yPos-22+j] = 1;
if(locations[blueTank.xPos-26+i][blueTank.yPos-22+j] != 0){
setTanks();
}
else if(locations[blueTank.xPos-26+i][blueTank.yPos-22+j] != 0){
setTanks();
}
else{
locations[blueTank.xPos-26+i][blueTank.yPos-22+j] = 2;
locations[blueTank.xPos+18+i][blueTank.yPos-22+j] = 2;
}
}
}
}
else if(blueDirection == 2){
for( i = 0 ; i < 8 ; i++){
for( j = 0 ; j < 44 ; j++){
gfx_point(blueTank.xPos - 22 + j , blueTank.yPos - 26 + i );
gfx_point(blueTank.xPos - 22 + j , blueTank.yPos + 18 + i );
gfx_point(redTank.xPos - 26 + i , redTank.yPos - 22 + j);
gfx_point(redTank.xPos + 18 + i , redTank.yPos - 22 + j);
locations[redTank.xPos-26+i][redTank.yPos-22+j] = 1;
locations[redTank.xPos+18+i][redTank.yPos-22+j] = 1;
if(locations[blueTank.xPos-22+j][blueTank.yPos-26+i] != 0){
setTanks();
}
else if(locations[blueTank.xPos-22+j][blueTank.yPos+18+i] != 0){
setTanks();
}
else{
locations[blueTank.xPos-22+j][blueTank.yPos-26+i] = 2;
locations[blueTank.xPos-22+j][blueTank.yPos+18+i] = 2;
}
}
}
}
}
void drawBullets(void){
int bulletCount, i, j;
for( bulletCount = 0 ; bulletCount < 100 ; bulletCount++){
if(bullets1[bulletCount][0] == 1){
for( i = 0 ; i < 4 ; i++){
for( j = 0 ; j < 4 ; j++){
gfx_color(255,255,0);
gfx_point(bullets1[bulletCount][1]-2+i, bullets1[bulletCount][2]-2+j);
}
}
bullets1[bulletCount][1] = bullets1[bulletCount][1] + 2*bullets1[bulletCount][3];
bullets1[bulletCount][2] = bullets1[bulletCount][2] + 2*bullets1[bulletCount][4];
}
}
for( bulletCount = 0 ; bulletCount < 100 ; bulletCount++){
if(bullets2[bulletCount][0] == 1){
for( i = 0 ; i < 4 ; i++){
for( j = 0 ; j < 4 ; j++){
gfx_color(0,255,255);
gfx_point(bullets2[bulletCount][1]-2+i, bullets2[bulletCount][2]-2+j);
}
}
bullets2[bulletCount][1] = bullets2[bulletCount][1] + 2*bullets2[bulletCount][3];
bullets2[bulletCount][2] = bullets2[bulletCount][2] + 2*bullets2[bulletCount][4];
}
}
}
void drawBullets2(void){
int bulletCount, i, j;
for( bulletCount = 0 ; bulletCount < 400 ; bulletCount++){
if(bullets1[bulletCount][0] == 1){
for( i = 0 ; i < 4 ; i++){
for( j = 0 ; j < 4 ; j++){
gfx_color(255,255,0);
gfx_point(bullets1[bulletCount][1]-2+i, bullets1[bulletCount][2]-2+j);
}
}
bullets1[bulletCount][1] = bullets1[bulletCount][1] + 2*bullets1[bulletCount][3];
bullets1[bulletCount][2] = bullets1[bulletCount][2] + 2*bullets1[bulletCount][4];
}
}
for( bulletCount = 0 ; bulletCount < 400 ; bulletCount++){
if(bullets2[bulletCount][0] == 1){
for( i = 0 ; i < 4 ; i++){
for( j = 0 ; j < 4 ; j++){
gfx_color(0,255,255);
gfx_point(bullets2[bulletCount][1]-2+i, bullets2[bulletCount][2]-2+j);
}
}
bullets2[bulletCount][1] = bullets2[bulletCount][1] + 2*bullets2[bulletCount][3];
bullets2[bulletCount][2] = bullets2[bulletCount][2] + 2*bullets2[bulletCount][4];
}
}
}
char calcCpuDirection(int xPos, int yPos){
char direction;
int t = rand() % 6;
int boolean = 0; //determines final direction
while (boolean != 1){
if(t == 1){
if(yPos < 2){
continue;
}
direction = 'w';
boolean = 1;
}
else if(t == 2){
if(yPos > (YSIZE - 2)){
continue;
}
direction = 's';
boolean = 1;
}
else if(t == 3){
if(xPos < 2){
continue;
}
direction = 'a';
boolean = 1;
}
else if(t == 4){
if(xPos > (XSIZE - 2)){
continue;
}
direction = 'd';
boolean = 1;
}
else{
direction = 'l';
boolean = 1;
}
}
return(direction);
}
int set_lives(int lives) {
--lives;
return lives;
}
|
TypeScript
|
UTF-8
| 226
| 2.53125
| 3
|
[] |
no_license
|
export interface Product {
id : number;
name : string;
description : string;
image : string;
rating : number;
}
export interface Order {
id : number;
date : string;
products : Array<string>;
}
|
C++
|
UTF-8
| 652
| 3.203125
| 3
|
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
stack < int > s1,s2;
void enqueue(int item)
{
s1.push(item);
}
int dequeue()
{
if(s1.empty() && s2.empty())
{
cout<<"Q is empty\n";
return 0;
}
else
{
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
int x=s2.top();
s2.pop();
return x;
}
}
int main()
{
enqueue(10);
enqueue(20);
cout<<dequeue()<<"\n";
enqueue(30);
enqueue(10);
cout<<dequeue()<<"\n";
cout<<dequeue()<<"\n";
enqueue(40);
}
|
Markdown
|
UTF-8
| 3,002
| 2.75
| 3
|
[] |
no_license
|
# 调漆工具修改报告
* 数据库字段限制问题
**问题描述**:在之前的版本中,由于数据库字段限制问题,若主剂料号长度超过20字符,则无法存入数据库,数据无法保存且无错误提示。
**解决方案**:经反馈,数据库SQL文件建表字段同意由20长度更新为256。
**结果**:问题已解决。
* 关于启动界面加载的问题改进
**问题描述**:在前期版本中,程序以FrmMain(主窗口)作为程序入口,并以模态形式弹出登录窗体。该方式存在的问题在于,由于先加载主窗口隐藏后,再加载登录窗口,会导致页面一闪而过,降低体验。
**解决方案**:程序以登录窗口为入口,登录成功后再进行主窗口加载。
**结果**:问题已解决。
* 关于界面右上角提示文字的改进
**问题描述**:根据需要,需在界面右上角显示欢迎信息。
**解决方案**:通过使用Label实现信息展示。
**结果**:问题已解决。
* 关于记住密码的改进
**问题描述**:每次加载登录窗口时,会进行其他状态的清除,为增强体验,需加入记住密码。
**解决方案**:在登录成功后,若用户选择记住密码,则将用户信息编码后存入注册表:LOCAL_MACHINE\Software\OilPainterSpan\Security\AccountOption\。
**结果**:功能已实现
* 料号维护界面,现有Release版本无法删除选中记录
**问题描述**:选中记录后,选择删除,仅按钮状态发生改变,未删除数据。根据代码分析,代码中确实必要的数据移除代码。
**解决方案**:根据现有数据绑定方案,通过向DataGrid中数据源中删除选中行,以实现数据删除。
**结果**:问题已解决
* 料号排序问题
**问题描述**:由于料号数据较多,数据未进行初始排序显示,数据杂乱。
**解决方案**:通过借助SQL优化,加入ORDER BY进行默认排序,默认以‘客户名称’进行升序排列。
**结果**:问题已解决,符合预期排序效果。
* 料号维护,部分客户名不显示问题
**问题描述**:点击ABC、DCB等客户用料时,在信息显示中,未显示客户名。具体情况如图:

**解决方案**:经过检查,原因在于Combobox中不存在该客户名记录,无法通过Text属性设置并显示,数据库不完善,增加相应数据记录,已改进现有SQL。
**结果**:问题已解决。
* 增加BOM用料时,刷新数据
**问题描述**:在进行BOM添加时,若添加成功,并保存时,系统显示界面会进行刷新操作,导致体验不佳。
**解决方案**:使用局部添加的方式,在SQL执行成功后,仅更新一条记录到数据源,不做整个数据源的重新绑定,避免刷新。
**结果**:问题已解决,实现局部增加。
|
Python
|
UTF-8
| 732
| 2.84375
| 3
|
[] |
no_license
|
import argparse
from logcreator.logcreator import Logcreator
"""
Handles arguments provided in comand line
"""
__author__ = 'Andreas Kaufmann, Jona Braun, Sarah Morillo'
__email__ = "ankaufmann@student.ethz.ch, jonbraun@student.ethz.ch, sleonardo@student.ethz.ch"
def get_args():
"""
Returns list of args
"""
return args
def boolean_string(s):
s = s.lower()
if s not in {'false', 'true'}:
raise ValueError('Not a valid boolean string')
return s == 'true'
def parse_args(parser):
"""
Read and parse args from comandline and store in args
"""
if parser:
global args
args = parser.parse_args()
else:
raise EnvironmentError(
Logcreator.info("Parsing of comand line parameters failed")
)
return args
|
Markdown
|
UTF-8
| 565
| 2.71875
| 3
|
[] |
no_license
|
# OrdenaPilha
Crie uma rotina usando o conceito de pilhas e/ou filas que permita analisar uma
expressão matemática fornecida pelo usuário via Scanner, e identificar as
operações a serem realizadas, e realizar os cálculos na ordem correta. A rotina
deve identificar se o número de parênteses está correto, e identificar se existem
dois operadores seguidos. Por exemplo, se o usuário informar a expressão
(4+(1*3-(2/5))), a rotina deve realizar as operações dentro dos parênteses,
depois divisões e multiplicações e depois somas e subtrações.
|
Python
|
UTF-8
| 985
| 2.609375
| 3
|
[] |
no_license
|
import re
import json
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
f = pd.read_csv('desk1.csv', header=0, index_col=0)
print(f)
f = f.fillna(0)
print(f)
f = f.T
print(f)
f = f.values
print(f)
np.random.seed(5)
X = f
model = KMeans(n_clusters=5)
model.fit(X)
labels = model.labels_
print(type(labels))
print("labels", labels, labels.shape)
fig = plt.figure('f0', figsize=(50, 40))
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=labels.astype(np.float), edgecolors='k')
C = model.cluster_centers_
ax.scatter(C[:, 0], C[:, 1], C[:, 2], c='red', s=100, alpha=0.5)
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
ax.set_xlabel('A', fontproperties="SimSum")
ax.set_ylabel('B', fontproperties="SimSum")
ax.set_zlabel('C', fontproperties="SimSum")
ax.set_title("KM3D")
ax.dist = 12
plt.show()
|
C#
|
UTF-8
| 1,009
| 3.25
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DetectorDeFalhas
{
class Program
{
static void Main(string[] args)
{
string X;
bool achou = false;
int maior = Int32.MinValue;
int Y = 0;
while (!string.IsNullOrEmpty(X = Console.ReadLine()))
{
int numero = Convert.ToInt32(X);
if (numero > maior && !achou)
{
maior = numero;
}
else if (numero <= maior && !achou)
{
Y = maior + 1;
achou = true;
}
}
if (achou)
{
Console.WriteLine(Y);
}
else
{
maior++;
Console.WriteLine(maior);
}
Console.ReadKey();
}
}
}
|
Java
|
UTF-8
| 1,247
| 2.234375
| 2
|
[] |
no_license
|
package com.dzqc.enterprise.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class AppDBHelper extends SQLiteOpenHelper {
public AppDBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
/**
* 创建表语句
*/
private static final String create_schools= "create table schools ("
+ "id integer primary key autoincrement," + "schoolcode text,"+"schoolname text,"
+ "address text,"+ "city text,"+ "citycode text,"+"url text)";
/**
* 创建表语句
*/
private static final String create_selectSchool= "create table checkSchoolTable ("
+ "id integer primary key autoincrement," + "schoolcode text)";
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//db.execSQL(create_schools);
db.execSQL(create_selectSchool);
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
// TODO Auto-generated method stub
db.execSQL("drop table if exists checkSchoolTable");
onCreate(db);
}
}
|
Java
|
UTF-8
| 934
| 2.234375
| 2
|
[] |
no_license
|
package com.learningwithrakesh.EventManagement.entity;
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
/**
*
*/
@SuppressWarnings("javadoc")
@MappedSuperclass
public class BaseDomain implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long whenCreated;
private Long whenLastUpdated;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getWhenCreated() {
return whenCreated;
}
public void setWhenCreated(Long whenCreated) {
this.whenCreated = whenCreated;
}
public Long getWhenLastUpdated() {
return whenLastUpdated;
}
public void setWhenLastUpdated(Long whenLastUpdated) {
this.whenLastUpdated = whenLastUpdated;
}
}
|
JavaScript
|
UTF-8
| 2,770
| 4.53125
| 5
|
[] |
no_license
|
//Hey this is the code for Linkedlist:
//Hit the terminal and run node FileName without .js eg: FileName: index.js run in the terminal node index.
class Node{
//A node has a data and a reference to that of the next node.
constructor(data, next = null){
this.data = data;
this.next = next;
}
}
class LinkedList{
//A LinkedlIst has a list of nodes.
// A head and a size of the LinkedList:
//By default the header is gonna be null and the size of the linkedList is zero.
constructor(head = null , size = 0){
this.head = head;
this.size = size;
}
//Inserting a node into the linkedList:
insertData(data){
//since in head it is a form of a node.
this.head = new Node(data, this.head);
this.size++;
}
//inserting a node at the last:
insertLast(data){
let current = this.head;
let nNode = new Node(data);
let previous;
while(current){
previous = current;
current = current.next;
}
previous.next = nNode;
}
//inserting a data at a particular index:
insertAt(data , index){
let count = 0;
let current = this.head;
let previous;
let node = new Node(data);
while(count < index){
previous = current;
current = current.next
count++;
}
console.log(previous);
previous.next = node;
node.next = current;
console.log(current);
}
//Get a particular element from a List:
getAtindex(index){
let count = 0;
let current = this.head;
let previous;
while(count < index){
previous = current;
count++;
current = current.next;
}
console.log(previous.next);
}
//remove a particluar element from the list:
deleteItemList(index){
let current = this.head;
let count = 0;
let previous;
while(count < index){
previous = current;
count++;
current = current.next;
}
console.log(previous);
console.log(current);
previous.next = current.next;
}
//printing all the data withing a List:
printList(){
let currentNode = this.head;
while(currentNode){
console.log(currentNode.data);
currentNode = currentNode.next;
}
}
}
const ll = new LinkedList();
ll.insertData(100);
ll.insertData(200);
ll.insertData(300);
ll.insertLast(400);
ll.insertLast(900);
ll.insertAt(270,2);
ll.insertAt(456,4);
ll.printList();
console.log('---');
ll.getAtindex(2);
ll.getAtindex(3);
console.log('--Code for deletion--')
ll.deleteItemList(3);
console.log('--- printing every Item in the List ---');
ll.printList();
//console.log(ll);
|
Java
|
UTF-8
| 295
| 1.796875
| 2
|
[] |
no_license
|
package nc.vo.so.salequotation.entity;
import nc.vo.pubapp.pattern.model.meta.entity.bill.AbstractBillMeta;
public class SalequotationMeta extends AbstractBillMeta {
public SalequotationMeta() {
this.setParent(SalequotationHVO.class);
this.addChildren(SalequotationBVO.class);
}
}
|
TypeScript
|
UTF-8
| 3,465
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
import { BackgroundColor, Parent, Scenes, Size, WebGL } from '@phaserjs/phaser/config';
import { Game } from '@phaserjs/phaser/Game';
import { Scene } from '@phaserjs/phaser/scenes/Scene';
import { StaticWorld } from '@phaserjs/phaser/world';
import { AddChild } from '@phaserjs/phaser/display/';
import { Sprite, SetTint, SetAlpha } from '@phaserjs/phaser/gameobjects/sprite';
import { Text } from '@phaserjs/phaser/gameobjects/text'
import { Between as RandomInt } from '@phaserjs/phaser/math'
import { Board, HexagonGrid, CreateTileTexture, Match } from '../../src/board';
const Colors: number[] = [0xff0000, 0x00ff00, 0x0000ff, 0x800080, 0x808000, 0x008080];
class MyChess extends Sprite {
__symbol: number;
constructor() {
super(0, 0, 'chess');
}
setSymbol(symbol: number): this {
this.__symbol = symbol;
SetTint(Colors[symbol], this);
return this;
}
getSymbol(): number {
return this.__symbol;
}
}
class MyBoard extends Board {
world: StaticWorld;
match: Match;
lastMatchedCount: number;
constructor(config) {
super(config);
this.match = new Match({
board: this
});
this.lastMatchedCount = 0;
CreateTileTexture(this, 'tile', undefined, 'white', 2);
CreateTileTexture(this, 'chess', 'white');
}
setWorld(world: StaticWorld): this {
this.world = world;
return this;
}
strokeGrid(): this {
this.forEachTileXY((tileXY) => {
let worldXY = this.tileXYToWorldXY(tileXY.x, tileXY.y, true);
let tile = new Sprite(worldXY.x, worldXY.y, 'tile');
AddChild(this.world, tile);
})
return this;
}
fillChess(): this {
this.forEachTileXY((tileXY) => {
let chess = new MyChess();
chess.setSymbol(RandomInt(0, Colors.length - 1));
AddChild(this.world, chess);
this.addChess(chess, tileXY.x, tileXY.y, 0);
})
return this;
}
refreshSymbols(): this {
this.match.refreshSymbols((tileXY) => {
var chess = this.tileXYZToChess(tileXY.x, tileXY.y, 0) as MyChess;
return (chess === null) ? null : chess.getSymbol();
});
return this;
}
match3(): this {
let matchedCount = 0;
this.refreshSymbols();
this.match.match(3, (result) => {
let chessArray = this.tileXYArrayToChessArray(result.tileXY, 0);
for (let i = 0, cnt = chessArray.length; i < cnt; i++) {
SetAlpha(0.5, chessArray[i] as Sprite);
}
matchedCount++;
});
this.lastMatchedCount = matchedCount;
return this;
}
}
class Demo extends Scene {
constructor() {
super();
const world = new StaticWorld(this);
const board = new MyBoard({
grid: (new HexagonGrid({
x: 80, y: 80,
cellWidth: 60, cellHeight: 68
})),
width: 8, height: 8
})
board
.setWorld(world)
.strokeGrid()
.fillChess()
.match3();
const text = new Text(0, 580, `Match count= ${board.lastMatchedCount}`);
text.setOrigin(0);
AddChild(world, text);
}
}
new Game(
WebGL(),
Size(800, 600),
Parent('game'),
BackgroundColor(0x2d2d2d),
Scenes(Demo)
);
|
Python
|
UTF-8
| 2,996
| 3.578125
| 4
|
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# Libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
########## Read the Dataset with pandas library
data=pd.read_csv("Datasets/Electricity_Norm/electricity-normalized.csv")
# Shuffle data
#
######### In order to get some random train and test data ###################
data=data.sample(len(data))
print(data)
# Get from the dataset just the labels that we need to implement the model
#Train data
X=["nswprice","nswdemand","vicprice","vicdemand"];Y="transfer"
xtrain=data[X][0:2000]
ytrain=data[Y][0:2000]
#Test data
xtest=data[X][2000:2100]
ytest=data[Y][2000:2100]
# Hypothesis function
def hyp(params, x):
h = 0
for i in range(len(params)):
h+=(params[i]*x[i])
return h
############## Error calc ##############3
# It gives the actual improvement of the error mean and keep it for further plotting
evol_error = []
def error(params, x, y):
e_acum=0
for i in range(len(x)):
n=hyp(params, x[i])
e_acum+=(n - y[i])**2 #mean square error
error_mean= e_acum / len(x)
evol_error.append(error_mean)
print("E_meam = %f" %(error_mean))
############# Gradient Descent ##############
# This function updates the params to improve performance
def gd(params, x, y, a):
tmp=list(params)
for j in range(len(params)):
acum=0;
for i in range(len(x)):
error = hyp(params, x[i]) - y[i]
acum+= error * x[i][j]
tmp[j] = params[j] - a * (1/len(x)) * acum
return tmp # Return new parameters
################## Main ###################
#### Training the Model
evol_error = [] #Save the error evolution to plot it
epoch = 0 #inicialized epochs
a = 0.0006 # Learning rate
limit = 3000 #3000 epochs to finish
params=[0, 0, 0, 0, 0]
xlist=xtrain.values.tolist()
ylist=ytrain.values.tolist()
for i in range(len(xlist)):
xlist[i]=[1] + xlist[i]
while True:
old = list(params)
params=gd(params, xlist, ylist, a)
error(params, xlist, ylist)
epoch+=1
if(old==params or epoch==limit):
print ("Weights:")
print (params)
break
plt.plot(evol_error)
# Test
#
# Evaluate with the test data, show graph relationa and error mean
x = np.linspace(0,len(ytest),len(ytest))
p=(hyp(params,[1, xtest["nswprice"], xtest["nswdemand"], xtest["vicprice"], xtest["vicdemand"]]))
testem_error=0
p=p.values.tolist()
y=ytest.values.tolist()
for i in range(len(x)):
testem_error+= (p[i]-y[i])**2
print("Test Errormean = %f"%(testem_error/len(x)))
################# User queries ####################33
### User iputs in order to make a prediction
x1=float(input("Enter nswprice:"))
x2=float(input("Enter nswdemand:"))
x3=float(input("Enter vicprice:"))
x4=float(input("Enter vicdemand:"))
prediction = (hyp(params,[1,x1,x2,x3,x4]))
print(prediction)
|
PHP
|
UTF-8
| 1,402
| 2.640625
| 3
|
[] |
no_license
|
<?php
include('private/database.php');
if(isset($_POST['email']) && !empty($_POST['email'])){
$message = $_POST;
// verifier les champs
$errors = [];
if(filter_var($message['email'], FILTER_VALIDATE_EMAIL)){
//L'email est bonne
}else{
$errors['email'] = "Veuillez-verifier l'adresse e-mail saisi";
}
if(count($errors)> 0){
include("index.php");
// si erreur => include("gallerie_edit_view.php");
}else{
/* syntaxe avec preparedStatements */
/* INSERT table galerie */
$sqlmessages = "insert into users (id, email) values(:id, :email)";
$sqlmessages .= " on duplicate key update email=:email";
$sthmessages = $dbh->prepare($sqlmessages, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
if(
$sthmessages->execute(array(
':id' => $message['id'],
':email' => $message['email']
))){
// si OK => rien ou message succes
$contact_id = (!empty($contact['id'])? $contact['id'] : $dbh->lastInsertId() );
$ok_email = "Votre e-mail a bien été envoyer";
header('Location: index.php?send=ok');
}else{
echo ("ERREUR LORS DE LA SAUVEGARDE");
include("index.php");
}
}
}else{
$error_email = "Veuillez saisir une adresse e-mail";
include("index.php");
}
|
Markdown
|
UTF-8
| 36,408
| 2.59375
| 3
|
[
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
---
---
title: 卷三百七十七·再生三
---
赵泰 袁廓 曹宗之 孙回璞 李强友 韦广济 郄惠连
赵泰
晋赵泰字文和,清河贝丘人也。祖父京兆太守。泰郡察孝廉,公府辟不就。精思圣典,有誉乡里。当晚乃仕,终中散大夫。泰年三十五时,尝卒心痛,须臾而死。下尸于地,心暖不冷,屈申随意。既死十日,忽然喉中有声如雨,俄而苏活。说初死之时,梦有一人,来近心下。复有二人,乘黄马,从者二人,夹持泰腋,(“腋”原作“胀”,据明抄本改。)径将东行。不知可几里,至一大城,崔峷高峻,城邑青黑色,遂将泰向城门八。经两重门,有瓦室,可数千间。男女大小,亦数千人。行列而吏着皂衣,有五六人,条疏姓字。云:“当以科呈府君。”泰名在三十,须臾,将泰与数千人男女,一时俱进。府君西向坐,阅视名簿讫,复遣泰南入里门。有人着绛衣,坐大屋下,以次呼名。问生时何作罪,行何福善,谛汝等以实言也。此恒遣六部使者在人间,疏记善恶,具有条状,不可得虚。泰答:“父兄仕官皆二千石。我少在家,修学而已,无所事也,亦不犯恶。”乃遣泰为水官监作吏,将二千余人,运沙裨岸,昼夜勤苦。后转泰水官都督,知诸狱事。给泰兵马,令案行地狱,所至诸狱。楚毒各殊。或针贯其舌,流血竟体。或被头露发,裸形徒跣,相牵而行。有持大仗,从后催促。铁床铜柱,烧之洞然。驱迫此人,抱卧其上,赴即焦烂,寻复还生。或炎炉巨镬,焚煮罪人,身首碎坠,随沸翻转。有鬼持叉,倚于其侧。有三四百人,立于一面,次当入镬,相抱悲泣。或剑树高广,不知限极,根茎枝叶,皆剑为之。人众相訾,自登自攀,若有欣竞,而身体割截,尺寸离断。泰见祖父母及二弟,在此狱中涕泣。泰出狱门,见有二人,赍文书来。说狱吏。言有三人,其家为于塔寺中悬幡烧香,救解其罪,可出福舍。俄见三人,自狱而出,已有自然衣服,完整在身。南诣一门,名开光大舍。有三重门,朱彩照发。见此三人,即入舍中,泰亦随入。前有大殿,珍宝周饰,精光耀目,金玉为床。见一神人,姿容伟异,殊好非常,坐此座上。边有沙门,立倚甚众。见府君来,恭敬作礼。泰问此是何人,府君致敬。吏曰:“号名世尊,度人之师。”有顷,令恶道中人,皆出听经。时有万九千人,皆出地狱,入百里城。在此到者,奉法众生也。行虽亏殆,尚当得度,故开经法。七日之中,随本所作善恶多少,差次免脱。泰未出之顷,已见十人,升虚而去。出此舍,复见一城,方二百余里,名为受变形城。地狱考治已毕者,当于此城,更受变报。泰入其城,见有土瓦屋数千区,各有房舍。正中有瓦屋高壮,栏槛采饰。有数百局吏,对校文书。云:杀生者当作蜉蝣,朝生暮死,劫盗者当作猪羊,受人屠割;淫逸者作鹤鹜鹰麋;两舌作鸱枭鸺鹠;捍债者为骡驴牛马。泰案行毕,还水官处。主者语泰,卿是谁者子,以何罪过,而来在此。泰答:“祖父兄弟,皆二千石。我举孝廉,公府辟不行。修志念善,不染众恶。”主者曰:“卿无罪,故相使为水官都督。不尔,与地狱中人无以异也。”泰问主者曰:“人有何行,死得乐报?”主者言:“唯奉法弟子,精进持戒,得乐报,无有谪罚也。”泰复问曰:“人未事法时,所行罪过。事法之后,得以除否?”答曰:“皆除也。”语毕,主者开藤箧,检年纪,尚有余算三十年在。乃遣泰还。临别,主者曰:“已见地狱罪报如是,当告世人,皆令作善。善恶随人,其犹影响,可不慎乎?”时亲表内外候视泰者,五六十人,同闻泰说。泰自书记,以示时人。时晋太始五年,七月十三日也。乃为祖父母二弟,延请僧众,大设福会。皆命子孙,改意奉法,课观精进。士人闻泰死而复生,多见罪福,互来访问。时有太中大夫武城孙丰、关内侯常山郝伯平等十人,同集泰会。款曲寻问,莫不惧然。皆即奉法。(出《冥祥记》)
袁廓
宋袁廓字思度,陈郡人也。元徽中,为吴郡丞。病经少日,奄然如死,但余息未尽。棺衾之具并备,待毕而殓。三日而能转动视瞬。自说云:有使者称教唤,廓随去。既至,有大城池,楼堞高整,阶闱崇丽。既命廓进。主人南面,与廓温凉毕,命坐。设酒炙,果粽菹者等味,不异世中。酒数行,主人谓廓曰:“主簿不幸有缺,以君才颖,故欲相屈,当能顾怀不?”廓意知是幽途,乃固辞凡薄,非所克堪。加少穷孤,兄弟零落,乞蒙恩放。主人曰:“君当以幽显异方,故辞耳。此间荣禄服御,乃胜君世中,甚贪共事。想必降意,副所期也。”廓复固请曰:“男女藐然,并在龆龀,仆一旦供任,养视无托。父子之恋,理有可矜。”廓因流涕稽颡。主人曰:“君辞让乃尔,何容相逼?愿言不获,深为叹恨。”就案上取一卷文书,勾点之。既而廓谢恩辞归。主人曰:“君不欲定省先亡乎?”乃遣人将廓行,经历寺署甚众,末得一垣门,盖囹圄也。将廓入中,叙趣一隅有诸屋宇,骈阗相接。次有一屋弊陋,见其所生母羊氏在焉,容服不佳,甚异平生。见廓惊喜。户边有一人,身面伤疾,呼廓。廓惊问谁,羊氏曰:“此王夫人,汝不识耶?”王夫人曰:“吾在世时,不信报应。虽无馀罪,正坐鞭挞婢仆过苦,受此罚。亡来痛楚,殆无暂休。今特小时宽隙耳。前唤汝姊来,望以自代,竟无所益,徒为忧聚。”言毕涕泗。王夫人即廓嫡母也,廓娣时亦在侧。有顷。使人复将廓去,经涉巷陌,闾里整顿,似是民居。末有一宅,竹篱茅屋,见父凭案而坐。廓入门,父扬手遣廓曰:“汝既蒙罢,可速归去,不须迟也。”廓跪辞而归,至家即活。(出《法苑珠林》)
曹宗之
高平曹宗之,元嘉二十五年,在彭城,夜寝不寤,旦亡。晡时气息还通。自说所见:一人单衣帻,执手板,称北海王使者,殿下相唤。宗之随去。殿前中庭,有轻云,去地数十丈,流荫徘徊。帷幌之间,有紫烟飘摇。风吹近人,其香非常。使者曰:“君停阶下,今入白之。”须臾,传令谢曹君。“君事能可称,久怀钦迟,今欲相屈为府佐。君今年几,曾经卤簿官未?”宗之答:“才干素弱,仰惭圣恩。今年三十一,未曾经卤簿官。”又报曰:“君年算虽少,然先有福业,应受显要,当经卤簿官。乃辞身,可且归家,后当更议也。”寻见向使者送出门,恍惚而醒。宗之后任广州,年四十七。明年职解,遂还州病亡。(出《述巽记》)
孙回璞
唐殿中侍医孙回璞,济阴人也。贞观十三年,从车驾幸九成宫三善谷,与魏征邻家。尝夜二更,闻外有一人,呼孙侍医者。璞谓是魏征之命,既出,见两人谓璞曰:“官唤。”璞曰:“我不能步行。”即取马乘之。随二人行,乃觉天地如昼日光明,璞怪而不敢言。出谷,历朝堂东,又东北行六七里,至苜蓿谷。遥见有两人,持韩凤方行。语所引璞二人曰:“汝等错追,所得者是,汝宜放彼。”人即放璞。璞循路而还,了了不异平生行处。既至家,系马,见婢当户眠,唤之不应。越度入户,见其身与妇并眠,欲就之而不得。但着南壁立,大声唤妇,终不应。屋内极明光,壁角中有蜘蛛网,中二蝇,一大一小。并见梁上所着药物,无不分明,唯不得就床。自知是死,甚忧闷,恨不得共妻别。倚立南壁,久之微睡,忽惊觉,身已卧床上,而屋中暗黑,无所见。唤妇,令起然火,而璞方大汗流。起视蜘蛛网,历然不殊。见马亦大汗。凤方是夜暴死。后至十七年,璞奉敕,驿驰往齐州,疗齐王佑疾。还至洛州东孝义驿,忽见一人来问曰:“君子是孙回璞。”曰:“是。君何问为?”答:“我是鬼耳,魏太监(“监”原作“师”据明抄本改)追君为记室。”因出书示璞。璞视之,则魏征署也。璞惊曰:“郑公不死,何为遣君送书?”鬼曰。已死矣,今为太阳都录太监,令我召君。”回璞引坐共食,鬼甚喜谢。璞请曰:“我奉敕使未还,郑公不宜追。我还京奏事毕,然后听命,可乎?”鬼许之。于是昼则同行,夜便同宿,遂至阌乡。鬼辞曰:“吾今先行,度关待君。”次日度关,出西门,见鬼已在门外。复同行,到滋水。鬼又与璞别曰:“待君奏事讫,相见也。君可勿食荤辛。”璞许诺。既奏事毕,访征已薨。校其薨日,则孝义驿之前日也。璞自以必死,与家人诀别。而请僧行道,造像写经。可六七夜。梦前鬼来召,引璞上高山,山巅有大宫殿。既入,见众君子迎谓曰:“此人修福,不得留之,可放去。”即推(“推”原作“随”,据明抄本改)璞堕山,于是惊悟。遂至今无恙矣。(出《冥祥记》)
李强友
李强友者,御史如璧之子。强友天宝末,为剡县丞。上官数日,有素所识屠者,诣门再拜。问其故,答曰:“因得病暴死,至地下,被所由领过太山。见大郎做主簿,因往陈诉。未合死至,蒙放得还。故来拜谢。”大郎者,强友也。强友闻,惆怅久之。曰:“死得太山主簿,办复何忧?”因问职事何如?屠者云:“太山有两主簿,于人间如判官也,傧从甚盛。鬼神之事,多经其所。”后数日,强友亲人死,得活。复去被收至太山。太山有两主簿,一姓李,即强友也。一姓王。其人死在王下,苦自论别。年尚未尽,忽闻府君召王主簿,去顷便回。云,官家设斋,须漆器万口。谓人曰,君家有此物,可借一用。速宜取之,事了即当放。此人来诣强友云。被借(“被借”原作“彼着”,据明抄本改)漆器,实无手力。强友为嘱王候,久之未决。又闻府君唤李主簿,走去却回。谓亲吏曰:“官家嗔王主簿不了事,转令与觅漆器。此事已急,无可至辞,宜速取也。”其人不得已,将手力来取。拣阅之声,家人悉闻。事毕,强友领过府君,因而得放。既愈,又为强友说之。强友于官严毅,典吏甚惧。衙后多在门外。忽传赞府出,莫不罄折。有窃视,见强友着帽,从百余人,不可复识。皆怪讶之。如是十余日,而强友卒。(出《广异记》)
韦广济
韦广济,上元中,暴死。自言初见(“见”字原缺,据明抄本补)使持帖,云,阎罗王追己为判官,己至门下,而未见王。须臾,衢州刺史韦黄裳复至。广济拜候。黄裳与广济为从兄弟,问汝何由而来。答云:“奉王帖,追为判官。”裳笑曰:“我已为之,汝当得去。”命坐久之,命所司办食。顷之食至,盘中悉是人鼻手指等。谓济曰:“此鬼道中食,弟既欲还,不宜复吃。”因令向前人送广济还。及苏,说其事。而黄裳犹无恙,后数日而暴卒。其年,吕延为浙东节度,有术士谓曰:“地下所由云,王追公为判官。速作功德,或当得免。”延之惶惧,大造经像。数十日,术者曰:“公已得免矣,今王取韦衢州,其牒已行。”延之使人至信安,遽报消息。后十日,黄裳竞亡也。(出《广异记》)
郄惠连
大历中,山阳人郄惠连,始居泗上,以其父尝为河朔官,遂从居清河。父殁,惠连以哀瘠闻。廉使命吏临吊,赠粟帛。既免丧,表授漳南尉。岁余,一夕独处于堂,忽见一人,衣紫(“衣紫”二字原空缺,据明抄本补。)佩刀,趋至前,谓惠连曰:“上帝有命,拜公为司命主者,以册(“册”字原空缺,据许本、黄本补。)立阎波罗王。”即以锦纹箱贮书,进于惠连曰:“此上帝命也。”轴用琼钿,标以纹锦。又象笏紫绶,金龟玉带,以赐。惠连且喜且惧,心甚惶惑,不暇顾问。遂受之。立于前轩,有相者趋入,赞曰:“驱殿吏卒且至。”已而有数百人,绣衣红额,左右佩兵器,趋入,罗为数行,再拜。一人前曰:“某幸得为使之吏,敢以谢。”词竟又拜。拜讫,分立于前。相者又曰:“五岳卫兵主将。”复有百余人趋入,罗为五行,衣如五方色,皆再拜。相者又曰:“礼器乐悬吏,鼓吹吏,车舆乘马吏,符印簿书吏,帑藏厨膳吏。”近数百人,皆趋而至。有顷,相者曰:“诸岳卫兵及礼器东悬车舆乘马等,请使躬自阅之。”惠连曰:“诸岳卫兵安在?”对曰:“自有所自有所耳。”惠连即命驾,于是控一白马至,具以金玉。其导引控御从辈,皆向者绣衣也。数骑夹道前驱,引惠连东北而去,传呼甚严。可行数里,兵士万余,或骑或步,尽介金执戈,列于路。枪槊旗饰,文繍交焕。俄见朱门外,有数十人,皆衣绿执笏,曲躬而拜者。曰:“此属吏也。”其门内,悉张帷帟几榻,若王者居。惠连既升阶,据几而坐。俄绿衣者十辈,各赍簿书,请惠连判署。己而相者引惠连于东庑下一院,其前庭有车舆乘马甚多,又有乐器鼓箫,及符印管钥。尽致于榻上,以黄纹帊蔽之。其榻绕四墉。又有玉册,用紫金填字,以篆籀书,盘屈若龙凤之势。主吏白曰:“此阎波罗王之册也。”有一人具簪冕来谒,惠连与抗礼。既坐,谓惠连曰:“上帝以邺郡内黄县南兰若海悟禅师有德,立心画一册。有阎波罗王礼甚,言以执事有至行,故拜执事为司命主者,统册立使。某幸列宾掾。故得侍左右。”惠连问曰:“阎波罗王居何?”府掾曰:“地府之尊者也。摽冠岳渎,总幽冥之务。非有奇特之行者,不在是选。”惠连思曰:“吾行册礼于幽冥,岂非身已死乎?”又念及妻子,怏怏有不平之色。府掾已察其旨,谓惠连曰:“执事有忧色,得非以妻子为念乎?”惠连曰:“然。”府掾曰:“册命之礼用明日,执事可暂归治其家。然执事官至崇,幸不以幽显为恨。”言讫遂起。惠连即命驾出行,而昏然若醉者。即据案假寐,及寤,已在县。时天才晓,惊叹且久。自度上帝命,固不可免。即具白妻子,为理命。又白于县令。令曹某不信。惠连遂汤沐,具绅冕,卧于榻。是夕,县吏数辈,皆闻空中有声若风雨,自北来,直入惠连之室。食顷,惠连卒。又闻其声北向而去,叹骇。因遣使往邺郡内黄县南问,果是兰若院禅师海悟者,近卒矣。(出《宣室志》)
----------
---------
解释翻译
赵泰 袁廓 曹宗之 孙回璞 李强友 韦广济 郄惠连
赵泰
西晋,清河贝丘人赵泰,字文和。他祖父任京兆太守。郡府打算举荐他为孝廉,欲征召任职,但赵泰躲在家里不愿做官。他精心钻研圣人经典,在乡里百姓中很有名望。直到晚年时才做官,临终时任中散大夫。赵泰三十五岁时,曾突然心痛,片刻而死,尸体停放在地上,但心仍热而不冷,四肢可随意屈伸。在他死后第十天的时候,忽然听到他喉咙中有如下雨的声音,倾刻便苏醒活过来。他说他刚死的时候,梦见有一个人来到他心下,又有两人骑黄马,两个随从夹扶着赵泰的两臂径直向东走。不知走了多少里,走到一座大城,城镇高大险峻,青黑色,他们便夹扶赵泰进入城门。经过两重门后,看到数千间瓦房,还有数千男女老少排列成行,有五六个小吏身穿皂衣,按顺序排列每个人的姓名,并说要分门别类地呈报给府君。赵泰排在第三十名。一会儿,将赵泰和数千名男女一齐带进地府,府君面西而坐,阅视名册后,又让赵泰向南进入里门。见有人穿着深红色衣服坐在大屋下,按顺序呼叫名字,并问活着时犯过什么罪,行过什么善事,要详细的如实说明。地府一直派遣六部使者在人间,逐条记录了每个人的善恶,不能说假话。赵泰回答说:“我父亲和我哥哥当官时都是两千石的俸禄,我年少时在家读书,没有做事,也没犯过什么罪恶。”于是便任赵泰为水官监作吏,率两千多人,运沙石修堤岸,昼夜忙碌。后来又让赵泰任水官都督,掌管各地狱中的事务,给他兵马,命他巡视地狱。他所到的各狱,各种毒刑各有不同。有的针穿舌头,遍身流血;有的披头散发,赤身裸足,相互牵引而行。有人拿着大木棒,在后边催促。铁床铜柱用火烧得能看见火苗,逼迫着有罪的人抱住铁床趴在上面,身体马上被火烧得焦烂,随即又活过来。还有火炉和大锅烧煮罪人,身首粉碎,随着沸水翻转,有拿着叉的鬼站在旁边。有三四百人站在一边,按顺序该进入锅内时,互相拥抱哭泣。有非常高大的剑树,树的根茎枝叶都是用剑做成,人们互相怨恨,各自攀登,好像很高兴似的互相比赛,而身体却被割截成一段一段的。赵泰看见他的祖父祖母和二弟,在这个狱中哭泣。赵泰走出了狱门,看见了两个人抱着文书走来,告诉狱吏说,有三个人,他们家在塔寺中悬挂招魂幡、烧纸,解救他们的罪过,可以走出福舍。不一会儿,见三人从狱中走出,穿着原来的衣服,很齐整,向南进入一门,名叫开光大舍,有三重门,红色发光。只见这三人进入开光大舍中,赵泰也随着进去。前面有一大殿,用珍宝装饰,精光耀眼,用金玉做的床。看见一个神人,身姿容貌魁伟与众不同,坐在殿中座上,旁边有许多和尚站在那里。府君走来,恭敬地行礼。赵泰问座中人是谁,府君都向他施礼?狱吏说,法号世尊,超度人的法师。一会儿,命令作恶的人出来听经,当时有一万九千多人,全都走出地狱,进入百里城。到这里的人,大都是世间守法的人,虽然他们的作为尚有不足之处,还是可以得到超度的,所以请僧人来讲经说法。七天之中,由本人所做的善恶多少,分别给予超脱。赵泰还没出去时,见十个人升空而去。走出大舍后又见一座城,方圆二百多里,名为受变形城。在地狱中受完惩罚的人才能到这座城,接受变形报应。赵泰进入这座城内,看见土瓦房数千处,各处都有房舍,正中的瓦房非常高大,栏槛都用彩色装饰。有数百名小吏,正在校阅文书,说,前世杀生的人应变作蜉蝣(一种昆虫),早晨生晚间死;前世抢劫偷盗者应变成猪羊,任人宰割;前世淫乱放荡的人应变成飞禽走兽;摇舌拔弄是非的人应变成叫声难听的鸟;抗债不还的人变成任人使役的牛马骡驴。赵泰看完之后又回到了他的水官督府,主事的人问赵泰,你是谁的儿子?因为什么罪过到这里来的?赵泰回答说,我的祖父和兄弟,都是两千石俸禄的官。我被乡里推举为孝廉,公府召我任职我没去。专心做善事,从不做各种恶事。”主事人说:“你无罪,所以才派你做水官都督。不然的话,你和地狱中的人没什么不同。”赵泰又问主事人:“怎样为人才能得到好的报应?”主事人说:“唯有尊奉佛法的弟子,精心进取,不做坏事的人才能得到好报,而不受惩罚。”赵泰又问:“人在不懂佛法时所犯的罪过,懂佛法以后能免除吗?”回答说:“都可以免除。”说完,主事人打开了藤箱,检视赵泰年纪还有三十年阳寿,便叫赵泰回还人世。临别时主事人说:“你已经见过地狱中犯罪报应的情形,你应当告诉世上的人,都要做善事。善恶与人相随,就像影子和回声一样,能不谨慎吗?”当时来探视赵泰的有五六十人,都听到了赵泰这样说,赵泰自己亲笔书写此事,用以告示世人。当时正是西晋武帝泰始五年七月十三日。他又为祖父母、二弟请了很多和尚大摆福会,又叫自己的子孙改奉佛法,并经常观察督促。一些读书人听说赵泰死而复生,在阴间见到了许多因果报应的事,便都来访问。当时有太中大夫武成人孙丰、关内侯常山人郝伯平等十余人,一齐来会见赵泰,诚恳地寻问,听后都很惧怕,都能立即奉法行善。
袁廓
北宋陈郡人袁廓,字思度,南朝宋后废帝元徽年间任吴郡丞。病不多日,像死了似的,只有一息尚存。棺槨被子等物已准备好,只等死后入殓。三天后却能转动眼珠看视,他自己说:有个使者说有人叫他,他便跟了去。到了时看到一座大城,城楼和城墙高大整齐,台阶和小门都很华丽,就叫袁廓进去。见主人面南而坐,与袁廓寒喧后让袁廓坐。摆设酒席,酒、肴、瓜果等物和世间一样。酒过数巡后,主人对袁廓说:“我这里缺少一个掌管文书典籍的人,知道你很有才华,所以想请你屈尊任此职,不知你是否愿意?”袁廓知道这是在阴间,于是坚决推辞此事,并说:“这不是能胜任的,我少年时孤苦贫穷,兄弟也都死亡飘零,请求你开恩放我回去。”主人说:“你可能认为阴间与阳世很不相同,所以才推辞。这里的荣华富贵吃穿使用,要比你在世间强的多,我很想和你共事,我想你必然会同意,不负我的期望。”袁廓又坚持请求说:“家中儿女尚小,正是幼稚的年龄,我要在这任职,靠谁来养育他们。父子之爱,理应得到怜悯同情。”袁廓痛苦流涕跪在地上磕头作揖。主人说:“你既然这样推辞,我也不能逼迫你,我的愿望没有实现,我深感遗憾。”主人从案桌上取出一卷文书,用笔勾点。这时,袁廓要谢恩回去。主人说:“你不想看一看先死去的人吗?”便派人领袁廓走,一路上寺庙衙署很多,最后到了一个衙署的门前,是一座监狱。把袁廓领进去,在一边按顺序建有很多房屋,并排相接。后又有一屋比较简陋,袁廓看见了自己的生母羊氏在这里,面容很脏,衣服很乱,和活着时很不一样。看见袁廓又惊又喜。门边还有一人,脸上和身上都有伤痕,她招呼袁廓,袁廓很吃惊问这人是谁?羊氏说:“这是王夫人,你不认识了吗?”王夫人说:“我在世的时候,不相信报应,虽然没有别的罪,却因为鞭打丫环仆人太厉害,才受到这样的惩罚,死后遭受这样的痛苦,恐怕暂时不能停止,今天特别给了一点时间的宽限。前些天唤你姐姐来,本想我自己代替你们受刑罚,看来也是不可能的,也只能在这里痛苦的见见面。”说完便痛哭流涕。王夫人是袁廓父亲的正妻,袁廓的妹妹也在旁边。一会儿,来人又将袁廓带走,经过了很多街巷,房舍建筑很整齐,好像似民房。最后有一个宅院,竹篱笆草房,袁廓看见了父亲坐在案桌前。袁廓走进门,父亲挥手告诉他说:“你对这里的情况都明白了,应该急速回去,不能迟误。”袁廓跪下辞别了父亲便回去了,到家中便复活了过来。
曹宗之
高平人曹宗之,南朝宋元嘉二十五年时在彭城,晚间睡觉没醒过来,天亮死了,到了下午气息相通,又活了过来。自己述说见闻。他说,见一个人身穿单衣,扎头巾,手拿竹板,自称是北海王的使者,说北海王要招唤曹宗之,曹宗之便随他去了。殿前的中庭,离地数十丈处有轻云飘荡,帷幔之间有紫气飘摇,风吹到人前,阵阵异香。使者说,“你在阶下等着,我进去告诉一声。”一会儿,传令让曹宗之进去,并对他说:“你很有才干和能力,已经钦佩很久了,今天想委屈你在府中任职。你今年多大年龄?曾经做过官没有?”曹宗之回答:“我的才干不强,愧对圣贤的恩德。今年三十一岁,没当过官。”又对曹宗之说:“你的年龄还小,但祖先有福业,应得到显要的职务,先去做个官。你现在可以起身回家,以后再说吧。”一会儿,那个使者便把曹宗之送出门,曹宗之恍惚间醒来。曹宗之后来在广州任官,年龄四十七岁,第二年解职,从广州回来便病故。
孙回璞
唐朝宫中侍医孙回璞,济阴人。唐太宗贞观十三年时,他伴驾皇上到九成宫三善谷,与魏征家相邻。当夜二更天,听到外面有一人呼唤孙侍医,孙回璞以为是魏征的命令,便出来了。见两个人对孙回璞说:“当官的叫你。”回璞说:“我不能步行。”便牵来马骑上随二人走,竟觉得天地间像和白天一样明亮,孙回璞感觉奇怪,但不敢说。出了三善谷,经过朝堂东侧,又往东北走了六七里,到了苜蓿谷。远远地看见两个人夹持韩凤方在走,并对领孙回璞的这两个人说:“你们追错了,我们得到的这个才是,你们应放了他。”这两人便放了孙回璞。孙回璞顺着原路往回走,和原来走过的地方一样。到了家拴好马,看见丫环在门旁睡觉,招呼也不答应。他越过丫环进了屋里,看到他的身体和妻子一齐躺着,想上床却上不去。只好靠着南墙站着,大声叫他妇人,却始终不应声。室内特别亮,墙角有蜘蛛网,网上有两个苍蝇,一大一小,还看见了房梁上挂着的药物,样样分明,可就是上不去床。他自己知道是死了,很忧愁,怨恨不能和妻子告别。他倚在南墙上慢慢睡着了,忽然惊醒,身体已躺在床上,屋里很暗很黑,什么也看不到。叫他妇人起来点燃灯火,孙回璞身上在流汗,起来看蜘蛛网,和原来一样,看到马也在流汗。韩凤方就是在这夜暴病而死。后来,到了贞观十七年,孙回璞奉命骑马去齐州,为齐王治病。回来时直到洛州东孝义驿站时,忽然见到一个人来问:“你是孙回璞吗?”孙回璞回答:“是。你问我有什么事?”那人说:“我是鬼,魏太监让你去当记室。”并拿出文书给孙回璞看。孙回璞一看,确是魏征的署名。孙回璞吃惊地说:“魏太监没有死,为什么派你来送文书?”鬼说:“他已经死了,现在任阴间太阳都录太监,让我来召你。”孙回璞给鬼让坐一齐吃饭,鬼很高兴很感谢。孙回璞请求说:“我是奉皇上的命令出使还没有回去,魏太监不应追我,等我回京向皇上禀奏之后再听命,可以吗?”鬼允许了。于是孙回璞和鬼白天同行,夜间同宿。到了阌乡,鬼告辞说:“我先走了,过了关等你。”第二天过关后出了西门,看见鬼已等在门外。到了滋水,鬼又和孙回璞告别说:“等你回京奏事后再见,你可不要吃荤腥辛辣的东西。”孙回璞答应了。孙回璞回京奏事后,访到魏征确实已死,查对魏征死的日期,正好是孙回璞到孝义驿站的前一天。孙回璞自己认为必然要死了,便和家里人诀别,并请和尚做道场,请人画像写经文。过了六七夜,孙回璞梦见以前遇见的鬼来召他,把他领上高山,山顶上有大宫殿。他们进去,看到很多君子迎上来并说:“这个人是行善有福的人,不能留在这里,可放他回去。”立即一推,孙回璞便跌落山下,于是惊醒,至今天无病无灾。
李强友
李强友是御史李如壁的儿子,在唐玄宗天宝末年时任剡县县丞。他上任不久,便有一个他平日熟悉的屠夫来登门拜谢。他问为什么谢他,屠夫回答说:“我因得病暴死,到了阴间,被人领过太山,看见了大郎你在那作主簿,我向你请求,还没到死的时候,蒙你开恩放我回来,所以才来向你拜谢。”大郎就是李强友,强友一听感到很伤感,说:“死后能在太山当主簿,也没什么可忧虑的。”又问屠夫,在那里主簿都干些什么事?屠夫说:“太山有两个主簿,和人间的判官一样,手下随从很多,鬼神的事大都由他办。”以后又过了几天,强友的一个亲人死了后复活了,又死去,被收到太山。太山有两个主簿,一个姓李,就是强友;一个姓王,强友的亲人就是死在王主簿手下。他向王主簿苦诉,自己的阳寿还没到头。忽然听到府君召王主簿,去了一会儿便回来了,说,官家要设斋,需要一万多只漆器。王主簿对强友亲人说,你家有这种器皿,可借来用一用,你快回去取来,事办完后就放你。此人来找强友说,借用这么多漆器。实在没有人手取。强友听说是王主簿的嘱咐,便犹豫了很久。又听到府君召唤李主簿,强友去了后回来对亲人说:“官家责怪王主簿不会办事,又让我去寻找漆器。这事很急,不能推辞,应该马上去取。”这人不得已带领众人回家去取,家里人都听到了搬动器皿的声音。事办完后,强友领亲人去见府君,此人被放还。病愈后,又对强友说了这件事。强友为官严厉果断,手下官吏都很惧怕他。衙役都站在门外,忽传强友要出府,都弯腰低头。有人偷看,见强友衣帽整齐,后跟百多人,再看却不见了,都感到奇怪和惊讶。就这样过了十几天,强友便死去了。
韦广济
韦广济在唐肃宗上元年间突然死去。自己说他当初看见一个使者拿着帖子对他说,阎王要他去当判官,他到了阎王门前,却没看到阎王。不一会儿,衢州刺史韦黄裳也到了这里,韦广济上前拜见问候,黄裳和广济是堂兄弟。黄裳问广济为什么来到这里,广济答道:“奉阎王的帖子,追我为判官。”黄裳笑说:“我已经当了,你应当回去。”叫广济坐一会儿,命人去办伙食。顷刻之间饭菜已到,盘中都是人的鼻子、手指等物。黄裳对广济说:“这是鬼道中的食物,你既然想回去,不应再吃。”又叫带广济来的那人把广济送回去。到他醒来时,便说了他的见闻,而韦黄裳却平安无事,几天后才突然暴死。那年,吕延任浙东节度使,有个江湖术士对他说:“地狱的差役说,阎王追你为判官,你应该速设道场诵经念佛,或许能免除。”吕延很害怕,大设道场造像诵经,数十天后,那术士对他说:“你已经得到免除,阎王去召韦衢州,文书已经发出。”吕延派人到信安,命其急速报告消息,十天后,韦黄裳死去。
郄惠连
唐代宗大历年间,山阳人郄惠连,初住在泗水上游地区,因为他父亲曾在河朔为官,他便随从父亲住在清河。他父亲死后,他由于过分悲痛形容消瘦而闻名,巡察使者到此地派人前去吊唁,赠以粮食布匹。守孝结束之后,皇帝下旨,授他为漳南尉。一年多后,一天晚上,他一人独坐堂前,忽然看见一个人,身穿紫衣腰佩刀,到他面前对他说:“天神有命,任你为司命主者是为了册封阎波罗王。”从锦纹箱中取出文书递给惠连说:“这是天神的命令。”轴是用美玉金银做成,用带花纹的锦绣装裱,又把象牙笏板绶带和金龟玉带,赐给惠连。他又喜又怕,心里很惶恐,没有时间细问,便接受了。他立在廊前,有个主持礼仪的人上前来说:“驱殿的官吏和士卒到。”这时有身穿绣衣左右佩兵器的几百人走向前来,站成数行,再拜。有一人上前说:“我有幸为你的下属,表示谢意。”说完又拜,拜完分别立在前面。司仪又说:“五岳卫兵主将。”又有一百多人走向前来,站成五行,衣服也分五种颜色,都再拜。司仪又说,“掌管礼仪用品的官、管鼓乐的官、管车轿马匹的官、掌符文书簿网的官、管库藏伙食的官。”将近几百人,都走向前来。过了一会儿,司仪说:“各岳卫兵礼仪器皿车轿马匹等请你亲自检阅。”惠连说:“诸岳卫兵在哪?”回答说:“各在各的住所。”惠连马上命令出发,于是有人牵一匹白马来,马具都是镶金嵌玉。前面导引的,后面跟从的都穿着绣衣。好几个骑兵夹道前导,引领惠连往东北方而去,传递命令非常严格。队伍走出几里路,一万多士兵,有的骑马有的步行,都金甲执戈站在路旁。枪矛旗帜,交相辉映。不久,看见朱门外有数十人,都穿着绿衣,手执笏板,弯腰而拜。说:“都是你属下的官吏。”门内,悬挂着帷幔,摆设着桌几床榻,好似王爷的居室。惠连走到阶上,坐在桌几旁,马上有十多个穿绿衣的人,各自带着册簿文书,请惠连判处签署。以后,司仪又领惠连到东厢的一个院内,前庭有很多车轿马匹,又有乐器鼓箫,以及符印钥匙等,都摆放在木案上,用带花的黄绫布盖着,木案四周都有护栏。又有一个玉册,用紫金写的字,好像篆书,每个字都有龙飞凤舞之势。主管的官吏说:“这是阎波罗王受册封的文书。”有一人头戴冠冕前来拜见,惠连与他见过礼后就坐。他对惠连说,天神说要以邺郡内黄县南边的佛寺中的海悟禅师最有功德,天神心中早有谋划,想立他为阎波罗王。因为这个仪式非常重大,我说你有很高的品德,因此拜你为司命主者,统管册立使臣的大权,我有幸列在你的属下,所以能侍奉在你的左右。”惠连问道:“阎波罗王管什么事?”府掾说:“他是地府中最尊贵的人,威震山河,总管阴间一切事物,没有奇特品行的人是不能选上的。”惠连自己想道:“我在阴间掌握册封礼仪,莫非我的身体已死了吗?”又想到了妻子儿女,流露出怏怏不乐的神色。府掾已经觉察出他的心思,对惠连说:“我看你面色忧郁,是不是挂念家中的妻子儿女?”惠连说:“对。”府掾又说:“册封的礼仪在明天举行,你可以暂时回家看看。这里的执事官权力是至高无上的,你不要以为这是在阴间而悔恨。”说完起身走了。惠连便命令车马出行,他觉得昏沉沉像醉酒了似的。便伏在案上睡着了,等到醒来已经是在县内。当时天刚亮,他回想起这段经历惊叹很久。他也想到,这是天神的命令,是不可免除的,便把这事告诉了妻子,让她赶快准备后事。他又告诉了县令,县令曹某却不相信。惠连便用热水沐浴,穿戴好衣冠,躺卧在床上。这天晚上,县里的好几个官吏,都听到了空中有刮风下雨的声音,从北边来,直到惠连住的屋内。吃顿饭的时间惠连便死了,又听到了声音往北去了。大家都感到惊骇,因此又派人到邺郡内黄县南面询问,果然是兰若院禅师海悟最近死亡。
|
JavaScript
|
UTF-8
| 2,669
| 3.453125
| 3
|
[] |
no_license
|
//Tiny Disco Javascript File
setTimeout(play, 20)
function play() {
cash = 100;
$(".coin-button").on("click", function(){
var coin = $(this).attr("data-coin");
coinPick(coin);})
$(".coin-button").on("click", function(){
var coin = $(this).attr("data-coin");
coinPick(coin);})
$(".dice-button").on("click", function(){
var dicepick = $(this).attr("data-dice");
die = 0;
diePick(die);
$(".diceresult").append("<p>You picked " + dicepick + " dice came up <br><br> "+die+"<p>");
})
$(".rsp-button").on("click", function(){
var myRsp = $(this).attr("data-rsp");
comprsp = 'bunnies'
temp2 = "bunnies"
rspPick(comprsp);
$(".rspresult").append("<p>You picked " + myRsp + " and the Computer chose "+temp2+"<p>");
if (myRsp == temp2) {result = "DRAW"}
else if (myRsp == "Rock" && temp2 == "Paper") {result = "LOST"; cash = cash - 30; }
else if (myRsp == "Paper" && temp2 == "Scissors") {result = "LOST"; cash = cash - 30; }
else if (myRsp == "Scissors" && temp2 == "Rock") {result = "LOST";cash = cash - 30;}
else {result = "WON!";
cash = cash + 90;}
rC();
$("header").append("<h2>CURRENT CASH = "+ cash +"<h2>");
$(".rspresult").append("<p>"+result+"<p>");
})
}
function rC(){
$("h2").remove();
}
function coinPick(temp){
$('p').remove();
var compcoin = Math.ceil(Math.random()*2)
if (compcoin == 1){
compcoin = "heads"
$(".coinresult").append("<p>You picked " + temp + " coin was " + compcoin + "<p>");
}
if (compcoin == 2){
compcoin = "tails"
$(".coinresult").append("<p>You picked " + temp + " coin was " + compcoin +"<p>");
}
if (temp == compcoin) {results = "WON!!"; cash = cash + 20}
else {results = "LOST"; cash = cash - 20;}
rC();$("header").append("<h2>CURRENT CASH = "+ cash +"<h2>");
$(".coinresult").append("<p>"+results+"<p>");
}
function diePick(diex){
$('p').remove();
die = Math.ceil(Math.random()*6)
switch(die) {
case 1: die = 1;
break;
case 2: die = 2;
break;
case 3: die = 3;
break;
case 4: die = 4;
break;
case 5: die = 5;
break;
case 6: die = 6;
break;
default: die = 666;
}
diex = die
return diex;
}
function rspPick(comprsp){
$('p').remove();
var numpicks = Math.ceil(Math.random()*3)
switch(numpicks) {
case 1: temp2 = "Rock";
break;
case 2: temp2= "Scissors";
break;
case 3: temp2 = "Paper";
break;
default: temp2 = "Bunnies";
}
comprsp = temp2
return comprsp;
}
|
C++
|
UTF-8
| 408
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
#pragma once
#include "Collider.h"
class BoxCollider : public Collider {
private:
Vector3 mDimensions; // Length - x, Height - Y, Breadth - Z
public:
BoxCollider(const Vector &origin, const Vector3 &size);
~BoxCollider();
bool collide(const Vector& position, float radius) override;
void fillCollisionSpace(Cell (&grid)[PATH_GRID_SIZE][PATH_GRID_SIZE], int width, int height) override;
};
|
C++
|
UTF-8
| 10,808
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// Created by cpasjuste on 17/10/18.
//
#include <algorithm>
#include "cross2d/skeleton/config_group.h"
using namespace c2d::config;
Group::Group(const std::string &name, int id) {
this->name = name;
this->id = id;
}
std::string Group::getName() const {
return name;
}
int Group::getId() const {
return id;
}
void Group::setId(int i) {
id = i;
}
/// childs options
void Group::addOption(const Option &option) {
options.push_back(option);
}
bool Group::removeOption(const std::string &n) {
auto found = std::find_if(options.begin(), options.end(), [&n](Option const &option) {
return n == option.getName();
});
if (found != options.end()) {
options.erase(found);
return true;
}
return false;
}
bool Group::removeOption(int i) {
auto found = std::find_if(options.begin(), options.end(), [&i](Option const &option) {
return i == option.getId();
});
if (found != options.end()) {
options.erase(found);
return true;
}
return false;
}
Option *Group::getOption(const std::string &n) {
for (Option &option : options) {
if (option.getName() == n) {
return &option;
}
}
return nullptr;
}
Option *Group::getOption(int i) {
for (Option &option : options) {
if (option.getId() == i) {
return &option;
}
}
return nullptr;
}
Option *Group::getOption(const std::string &groupName, const std::string &optionName) {
Group *group = getGroup(groupName);
if (group != nullptr) {
return group->getOption(optionName);
}
return nullptr;
}
Option *Group::getOption(int groupId, int optionId) {
Group *group = getGroup(groupId);
if (group != nullptr) {
return group->getOption(optionId);
}
return nullptr;
}
std::vector<Option> *Group::getOptions() {
return &options;
}
/// childs group
void Group::addGroup(const Group &group) {
groups.push_back(group);
}
bool Group::removeGroup(const std::string &n) {
auto found = std::find_if(groups.begin(), groups.end(), [&n](Group const &group) {
return n == group.getName();
});
if (found != groups.end()) {
groups.erase(found);
return true;
}
return false;
}
bool Group::removeGroup(int i) {
auto found = std::find_if(groups.begin(), groups.end(), [&i](Group const &group) {
return i == group.getId();
});
if (found != groups.end()) {
groups.erase(found);
return true;
}
return false;
}
Group *Group::getGroup(const std::string &name) {
if (name == this->name) {
// used for recursive lookup
return this;
}
for (Group &group : groups) {
Group *s = group.getGroup(name);
if (s != nullptr) {
return s;
}
}
return nullptr;
}
Group *Group::getGroup(int id) {
if (id == this->id) {
// used for recursive lookup
return this;
}
for (Group &group : groups) {
Group *s = group.getGroup(id);
if (s != nullptr) {
return s;
}
}
return nullptr;
}
std::vector<Group> *Group::getGroups() {
return &groups;
}
///
/// PROTECTED
///
bool Group::load(config_setting_t *parent) {
if (!savable) {
return true;
}
if (parent == nullptr) {
printf("Config::Group::load: could not find root config: %s\n", name.c_str());
return false;
}
config_setting_t *settings = config_setting_lookup(parent, name.c_str());
if (settings == nullptr) {
printf("Config::Group::load: group not found, skipping: %s\n", name.c_str());
return false;
}
for (auto &option : options) {
if (!option.isSavable()) {
continue;
}
if (option.getType() == Option::Type::String) {
const char *value;
if (config_setting_lookup_string(settings, option.getName().c_str(), &value) == CONFIG_FALSE) {
printf("Config::Group::load: option not found, skipping: %s\n", option.getName().c_str());
continue;
}
option.setString(value);
} else if (option.getType() == Option::Type::Integer) {
int value = 0;
if (config_setting_lookup_int(settings, option.getName().c_str(), &value) == CONFIG_FALSE) {
printf("Config::Group::load: option not found, skipping: %s\n", option.getName().c_str());
continue;
}
option.setInteger(value);
} else if (option.getType() == Option::Type::Float) {
double value = 0;
if (config_setting_lookup_float(settings, option.getName().c_str(), &value) == CONFIG_FALSE) {
printf("Config::Group::load: option not found, skipping: %s\n", option.getName().c_str());
continue;
}
option.setFloat((float) value);
} else if (option.getType() == Option::Type::Vector2f) {
std::vector<float> values = {option.getVector2f().x, option.getVector2f().y};
config_setting_t *sub = config_setting_lookup(settings, option.getName().c_str());
if (sub != nullptr) {
for (int i = 0; i < 2; i++) {
values[i] = (float) config_setting_get_float_elem(sub, i);
}
}
option.setVector2f({values[0], values[1]});
} else if (option.getType() == Option::Type::FloatRect) {
FloatRect r = option.getFloatRect();
std::vector<float> values = {r.left, r.top, r.width, r.height};
config_setting_t *sub = config_setting_lookup(settings, option.getName().c_str());
if (sub != nullptr) {
for (int i = 0; i < 4; i++) {
values[i] = (float) config_setting_get_float_elem(sub, i);
}
}
option.setFloatRect({values[0], values[1], values[2], values[3]});
} else if (option.getType() == Option::Type::Color) {
FloatRect r = option.getFloatRect();
std::vector<uint8_t> values = {(uint8_t) r.left, (uint8_t) r.top, (uint8_t) r.width, (uint8_t) r.height};
config_setting_t *sub = config_setting_lookup(settings, option.getName().c_str());
if (sub != nullptr) {
for (int i = 0; i < 4; i++) {
values[i] = (uint8_t) config_setting_get_int_elem(sub, i);
}
}
option.setColor({values[0], values[1], values[2], values[3]});
} else if (option.getType() == Option::Type::Choice) {
int value = 0;
if (config_setting_lookup_int(settings, option.getName().c_str(), &value) == CONFIG_FALSE) {
printf("Config::Group::load: option not found, skipping: %s\n", option.getName().c_str());
continue;
}
option.setChoicesIndex(value);
}
}
// load childs, if any
for (Group &group : groups) {
group.load(settings);
}
return true;
}
bool Group::save(config_setting_t *parent) {
if (!savable) {
return true;
}
if (parent == nullptr) {
printf("Config::Group::save: could not save group (%s), no parent\n", name.c_str());
return false;
}
config_setting_t *root = config_setting_add(parent, name.c_str(), CONFIG_TYPE_GROUP);
for (Option &option : options) {
if (option.getType() == Option::Type::String) {
config_setting_t *setting = config_setting_add(root, option.getName().c_str(), CONFIG_TYPE_STRING);
config_setting_set_string(setting, option.getString().c_str());
} else if (option.getType() == Option::Type::Integer) {
config_setting_t *setting = config_setting_add(root, option.getName().c_str(), CONFIG_TYPE_INT);
config_setting_set_int(setting, option.getInteger());
} else if (option.getType() == Option::Type::Float) {
config_setting_t *setting = config_setting_add(root, option.getName().c_str(), CONFIG_TYPE_FLOAT);
config_setting_set_float(setting, (double) option.getFloat());
} else if (option.getType() == Option::Type::Vector2f) {
config_setting_t *array = config_setting_add(root, option.getName().c_str(), CONFIG_TYPE_ARRAY);
config_setting_t *subset = config_setting_add(array, nullptr, CONFIG_TYPE_FLOAT);
config_setting_set_float(subset, option.getVector2f().x);
subset = config_setting_add(array, nullptr, CONFIG_TYPE_FLOAT);
config_setting_set_float(subset, option.getVector2f().y);
} else if (option.getType() == Option::Type::FloatRect) {
config_setting_t *array = config_setting_add(root, option.getName().c_str(), CONFIG_TYPE_ARRAY);
config_setting_t *subset = config_setting_add(array, nullptr, CONFIG_TYPE_FLOAT);
config_setting_set_float(subset, option.getFloatRect().left);
subset = config_setting_add(array, nullptr, CONFIG_TYPE_FLOAT);
config_setting_set_float(subset, option.getFloatRect().top);
subset = config_setting_add(array, nullptr, CONFIG_TYPE_FLOAT);
config_setting_set_float(subset, option.getFloatRect().width);
subset = config_setting_add(array, nullptr, CONFIG_TYPE_FLOAT);
config_setting_set_float(subset, option.getFloatRect().height);
} else if (option.getType() == Option::Type::Color) {
config_setting_t *array = config_setting_add(root, option.getName().c_str(), CONFIG_TYPE_ARRAY);
config_setting_t *subset = config_setting_add(array, nullptr, CONFIG_TYPE_INT);
config_setting_set_int(subset, (int) option.getFloatRect().left);
subset = config_setting_add(array, nullptr, CONFIG_TYPE_INT);
config_setting_set_int(subset, (int) option.getFloatRect().top);
subset = config_setting_add(array, nullptr, CONFIG_TYPE_INT);
config_setting_set_int(subset, (int) option.getFloatRect().width);
subset = config_setting_add(array, nullptr, CONFIG_TYPE_INT);
config_setting_set_int(subset, (int) option.getFloatRect().height);
} else if (option.getType() == Option::Type::Choice) {
config_setting_t *setting = config_setting_add(root, option.getName().c_str(), CONFIG_TYPE_INT);
config_setting_set_int(setting, option.getChoiceIndex());
}
}
// save childs, if any
for (Group &group : groups) {
group.save(root);
}
return true;
}
bool Group::isSavable() const {
return savable;
}
void Group::setSavable(bool s) {
savable = s;
}
|
SQL
|
UTF-8
| 469
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
set serveroutput on;
DECLARE
data_mea_de_nastere varchar2(30) := '05-09-1997';
BEGIN
DBMS_OUTPUT.PUT_LINE('Numarul de zile este: '||abs(extract(day from sysdate)-extract(day from to_date(data_mea_de_nastere,'DD-MM-YYYY')))||', iar numarul de luni este: '||round(months_between(sysdate,to_date(data_mea_de_nastere,'DD-MM-YYYY')))||'.');
DBMS_OUTPUT.PUT_LINE('Ziua in care m-am nascut este: '||to_char(to_date(data_mea_de_nastere,'DD-MM-YYYY'),'Day')||'.');
END;
|
Shell
|
UTF-8
| 873
| 3.46875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env bash
# Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
# Uses vespa-security-env to call curl with paths to credentials.
# This script should be installed in libexec only. It is not public api.
set -e
. $(vespa-security-env)
CURL_PARAMETERS=$1
CONFIGSERVER_URI_WITHOUT_SCHEME=$2
if [ -n "${VESPA_TLS_ENABLED}" ]
then
CONFIGSERVER_URI="https://${CONFIGSERVER_URI_WITHOUT_SCHEME}"
else
CONFIGSERVER_URI="http://${CONFIGSERVER_URI_WITHOUT_SCHEME}"
fi
if [ -n "${VESPA_TLS_CA_CERT}" ]
then
CURL_PARAMETERS="--cacert \"${VESPA_TLS_CA_CERT}\" ${CURL_PARAMETERS}"
fi
if [[ -n "${VESPA_TLS_CERT}" && -n "${VESPA_TLS_PRIVATE_KEY}" ]]
then
CURL_PARAMETERS="--cert \"${VESPA_TLS_CERT}\" --key \"${VESPA_TLS_PRIVATE_KEY}\" ${CURL_PARAMETERS}"
fi
curl ${CURL_PARAMETERS} "${CONFIGSERVER_URI}"
|
C
|
UTF-8
| 341
| 3.9375
| 4
|
[] |
no_license
|
#include <stdio.h>
int main(int argc, char const *argv[])
{
// 1-7 打印 EOF
printf("EOF = %d", EOF);
// 1-9 替换多个空格为单个空格
int c, last;
while ((c = getchar()) != EOF)
{
if (!(c == ' ' && last == ' '))
{
putchar(c);
}
last = c;
}
return 0;
}
|
Go
|
UTF-8
| 1,538
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
package danmu
import (
"errors"
"flag"
"fmt"
log "github.com/alecthomas/log4go"
"github.com/larspensjo/config"
"os"
"runtime"
)
var (
Conf *Config
appPath = os.Getenv("GOPATH") + "/src/github.com/kong36088/danmu/"
configFile = flag.String("config", appPath+"config/config.ini", "General configuration file")
)
type Config struct {
values map[string]map[string]string
}
//topic list
func NewConfig() *Config {
return &Config{
values: make(map[string]map[string]string),
}
}
func InitConfig() error {
Conf = NewConfig()
runtime.GOMAXPROCS(runtime.NumCPU())
flag.Parse()
cfgSecs, err := config.ReadDefault(*configFile)
if err != nil {
return errors.New(fmt.Sprintf("Fail to find %s %s", *configFile, err))
}
for _, section := range cfgSecs.Sections() {
options, err := cfgSecs.SectionOptions(section)
if err != nil {
log.Error("Read options of file %s section %s failed, %s\n", *configFile, section, err)
continue
}
Conf.values[section] = make(map[string]string)
for _, v := range options {
option, err := cfgSecs.String(section, v)
if err != nil {
log.Error("Read file %s option %s failed, %s\n", *configFile, v, err)
continue
}
Conf.values[section][v] = option
}
}
return nil
}
func (c *Config) GetConfig(section, option string) string {
return c.values[section][option]
}
func (c *Config) GetSectionConfig(section string) map[string]string {
return c.values[section]
}
func (c *Config) GetAllConfig() map[string]map[string]string {
return c.values
}
|
Python
|
UTF-8
| 692
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
import torch
import pytorch_lightning as pl
from pathlib import Path
from shutil import copyfile
class ModelCheckpoint(pl.callbacks.ModelCheckpoint):
""""""
def _do_check_save(
self,
filepath: str,
current: torch.Tensor,
epoch: int,
trainer,
pl_module,
):
"""Additionally copies the best checkpoint to "best.ckpt" in the checkpoint
directory.
"""
res = super()._do_check_save(filepath, current, epoch, trainer, pl_module)
best_model_path = Path(self.best_model_path).resolve()
dst = best_model_path.parent / "best.ckpt"
copyfile(best_model_path, dst)
return res
|
Java
|
UTF-8
| 260
| 1.601563
| 2
|
[
"MIT"
] |
permissive
|
package com.forest.crm.service;
import java.util.List;
import java.util.Map;
/**
* Created by CodeGenerator on 2018/04/30.
*/
public interface CrmService {
List<Map<String, Object>> callCrmDatas(Map<String, Object> paramsMap); // 调用存储过程
}
|
Java
|
UTF-8
| 4,310
| 1.890625
| 2
|
[] |
no_license
|
package com.lwj.image.loader;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.widget.ImageView;
import com.lwj.image.download.ILoadImageUrlConverter;
import com.lwj.image.download.ILoadImageUrlConverter.ImageType;
import com.lwj.image.helper.IImageDownLoaderHelper;
import com.lwj.image.helper.IImageLoaderManagerHelper;
import com.lwj.image.util.ReSize;
/**
* Created by lwj on 2016/12/30.
* lwjfork@gmail.com
*/
public abstract class AImageLoader {
protected ILoadImageUrlConverter urlConverter;
public AImageLoader(ILoadImageUrlConverter urlConverter) {
this.urlConverter = urlConverter;
}
//----圆形图加载
public abstract void loadImageCircle(Context context, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
//----圆形图加载
public abstract void loadImageCircle(Fragment fragment, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
//----圆形图带边框加载
public abstract void loadImageCircleWithBorder(Context context, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, int borderWidth, int borderColor, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
//----圆形图带边框加载
public abstract void loadImageCircleWithBorder(Fragment fragment, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, int borderWidth, int borderColor, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
//----圆角图加载
public abstract void loadRoundImage(Context context, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, float tlradius, float trradius, float brRadius, float blRadius, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
//----圆角图加载
public abstract void loadRoundImage(Fragment fragment, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, float tlradius, float trradius, float brRadius, float blRadius, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
//----圆角图加载带边框
public abstract void loadRoundImageWithBorder(Context context, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, float tlradius, float trradius, float brRadius, float blRadius, int borderWidth, int borderColor, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
//----圆角图加载带边框
public abstract void loadRoundImageWithBorder(Fragment fragment, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, float tlradius, float trradius, float brRadius, float blRadius, int borderWidth, int borderColor, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
//---普通加载
public abstract void loadImage(Context context, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
//---普通加载
public abstract void loadImage(Fragment fragment, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
//---普通加载加边框
public abstract void loadImageWithBorder(Context context, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, int borderWidth, int borderColor, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
//---普通加载加边框
public abstract void loadImageWithBorder(Fragment fragment, @ImageType int urlType, ImageView imageView, String url, int defaultImg, int errorImg, int borderWidth, int borderColor, ReSize reSize, boolean isAnim, int iterations, int blurRadius);
// 加载 gif 图
public abstract void loadGifImage(Context context, @ImageType int urlType, ImageView imageView, String url);
// 加载 gif 图
public abstract void loadGifImage(Fragment fragment, @ImageType int urlType, ImageView imageView, String url);
}
|
Shell
|
UTF-8
| 749
| 4.125
| 4
|
[
"Apache-2.0"
] |
permissive
|
#! /usr/bin/env bash
# This takes boundary update PDFs converted to text and
# builds a JSON list of boundary objects for each zone.
# It will take more effort to parse the language...
# Usage: listify input_file output_file
FILE=$1
OUTFILE=$2
if [ -z $OUTFILE ]
then
OUTFILE=$1.json
fi
echo [ > $OUTFILE
# Zones are represented as XX## and a paragraph of
# text describing their boundaries. Here the zone
# names are used as keys.
sed '/^[A-Z0-9]\{4\}$/s/^/{/; /^{/s/$/:/; s/^$/}/' $FILE |\
tr '\n' ' ' |\
sed 's/:}/:"/g; s/}/"},/g;' |\
sed 's/ {/{"/g; s/:/":/' |\
sed '/:/s/"}, $//; s/: "}, /":"/g; s/},/},\n/g' |\
sed 's/. "}/."}/' |\
grep ^{ >> $OUTFILE
sed -i '$s/},/}/' $OUTFILE
echo ] >> $OUTFILE
|
PHP
|
UTF-8
| 6,037
| 2.78125
| 3
|
[] |
no_license
|
<?php
class ORDER
{
private $conn;
public function __construct()
{
$database = new OrderTable();
$db = $database->dbConnection();
$this->conn = $db;
}
public function neworder($ID, $uproduct, $uquantity, $uretouch, $ualum, $uinstructions)
{
try {
$stmt = $this->conn->prepare('INSERT INTO order_Details(customer_ID, product, product_quantity, retouching, aluminum_Options, instructions)
VALUES(:ID, :uproduct, :uquantity, :uretouch, :ualum, :uinstructions)');
$stmt->bindparam(':ID', $ID);
$stmt->bindparam(':uproduct', $uproduct);
$stmt->bindparam(':uquantity', $uquantity);
$stmt->bindparam(':uretouch', $uretouch);
$stmt->bindparam(':ualum', $ualum);
$stmt->bindparam(':uinstructions', $uinstructions);
$stmt->execute();
$id = $this->conn->lastInsertId();
return $id;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function orderShipped($shipped_ID)
{
try {
$stmt = $this->conn->prepare(
"UPDATE customers
SET shipped = '$shipped_ID',
WHERE ID = '$shipped_ID'"
);
$stmt->execute();
return $stmt;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function getOrderID($query)
{
$stmt = $this->conn->prepare($query);
$stmt->execute();
$ID;
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$ID = $row['ID'];
}
}
return $ID;
}
public function dataview($query)
{
$stmt = $this->conn->prepare($query);
$stmt->execute(); ?>
<tr>
<th data-th="Name"><span>Name</span></th>
<th>Shipping Address</th>
<th>Email</th>
<th>Order</th>
<th>Shipped</th>
</tr>
<?php
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['shipping']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><label> <a href="view-Order.php">View Order</a></label></td>
<td align="center">
<a href="edit-data.php?edit_id=<?php echo $row['id']; ?>"><i class="glyphicon glyphicon-edit"></i></a>
</td>
<td align="center">
<a href="delete.php?delete_id=<?php echo $row['id']; ?>"><i class="glyphicon glyphicon-remove-circle"></i></a>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
public function base64_to_jpeg($base64_string, $output_file)
{
$ifp = fopen($output_file, 'wb');
fwrite($ifp, base64_decode($base64_string));
fclose($ifp);
return $output_file;
}
public function ViewOrderItems($query)
{
$stmt = $this->conn->prepare($query);
$stmt->execute(); ?>
<tr>
<th></th>
<th>Product</th>
<th>Images</th>
<th>Quantity</th>
<th></th>
<!--<th>Image</th>-->
</tr>
<?php
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<tr>
<td width="31%"></td>
<td width="13%"><?php echo $row['product']; ?></td>
<td width="13%"><label> <a href="view-Images.php?order_ID=<?php echo $row['ID']; ?>" style="color:#2b6ca3;">View Image</a></label></td>
<td width="13%"><?php echo $row['product_quantity']; ?></td>
<td width="31%"></td>
</tr>
<?php
}
} else {
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
public function ViewImages($query)
{
$stmt = $this->conn->prepare($query);
$stmt->execute(); ?>
<tr>
<th></th>
</tr>
<?php
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $row['product']; ?></td>
<td><?php echo $row['product_quantity']; ?></td>
<td><label> <a href="view-Order.php?order_ID=<?php echo $row['ID']; ?>">View Image</a></label></td>
<td><?php echo $row['retouching']; ?></td>
<td><?php echo $row['aluminum_Options']; ?></td>
<td><?php echo $row['instructions']; ?></td>
<!--<td align="center">-->
<!--<a href="delete.php?delete_id=<?php echo $row['id']; ?>"><i class="glyphicon glyphicon-remove-circle"></i></a>-->
<!--</td>-->
</tr>
<?php
}
} else {
?>
<tr>
<td>Nothing here...</td>
</tr>
<?php
}
}
public function paging($query, $records_per_page)
{
$starting_position = 0;
if (isset($_GET['page_no'])) {
$starting_position = ($_GET['page_no'] - 1) * $records_per_page;
}
$query2 = $query." limit $starting_position,$records_per_page";
return $query2;
}
public function jsonview($query)
{
$stmt = $this->db->prepare($query);
$stmt->execute();
$json = array();
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$json[] = $row;
}
}
return json_encode($json);
}
}
?>
|
JavaScript
|
UTF-8
| 1,158
| 2.859375
| 3
|
[
"CC0-1.0"
] |
permissive
|
const API_URL = 'http://localhost:3000'
//Trending posts
const trendingPosts = document.querySelector('.trending-1')
//Date
const postDate = document.querySelector('#post-date')
let postDay = new Date().getDay()
let postMounth = new Date().getMonth()
const postYear = new Date().getFullYear()
if(postDay < 10){
postDay = '0' + postDay
}if(postMounth < 10){
postMounth = '0' + postMounth
}
postDate.textContent = postDay + '/' + postMounth + '/' + postYear
//Buttons
const upvoteBtn = document.querySelector('#upvote-button')
const downvoteBtn = document.querySelector('#downvote-button')
const awardBtn = document.querySelector('#award-button')
const commentBtn = document.querySelector('#comment-button')
const darkModeBtn = document.querySelector('#dark-mode-button')
const upvoteCount = document.querySelector('#upvote-count')
const downvoteCount = document.querySelector('#downvote-count')
upvoteBtn.addEventListener('click', ()=>{
upvoteCount.textContent ++
})
downvoteBtn.addEventListener('click', ()=>{
downvoteCount.textContent ++
})
darkModeBtn.addEventListener('click', ()=>{
document.body.classList.toggle('dark-mode')
})
|
Python
|
UTF-8
| 2,127
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
"""
Routes for main page of image labelling app
"""
import os
import logging
from flask import render_template, redirect, request, current_app, url_for
from flask_login import current_user
from image_labeller import db
from image_labeller.main import bp
from image_labeller.main.forms import LabelForm
from image_labeller.main.labelling_utils import (
# fill_user_table,
fill_image_table_if_empty,
fill_category_table,
get_user, get_image, save_label
)
logger = logging.getLogger(__name__)
@bp.route("/")
@bp.route("/index")
def index():
if not current_user.is_authenticated:
return redirect(url_for("auth.not_confirmed"))
if current_user.is_authenticated:
user_id = current_user.user_id
fill_image_table_if_empty()
categories = current_app.config["CATEGORIES"]
fill_category_table(categories)
title = current_app.config["TITLE"]
homepage_text = current_app.config["HOMEPAGE_TEXT"]
print("HERE I AM!")
return render_template("index.html", title=title,
homepage_text=homepage_text)
return "User not authenticated"
@bp.route("/new",methods=["POST","GET"])
def new_image():
"""
Display an image, and ask the user to label it
"""
user_id = current_user.user_id
image_filename, image_id = get_image(user_id)
image_dir = current_app.config["IMAGE_DIR"]
image_path = os.path.join(image_dir,image_filename)
categories = current_app.config["CATEGORIES"]
label_form = LabelForm()
label_form.cat_radio.choices = [(cat,cat) for cat in categories]
if request.method=="POST":
label = label_form.cat_radio.data
notes = label_form.notes.data
save_label(user_id, image_id, label, notes)
# now reset the form to re-render the page
new_label_form = LabelForm(formdata=None)
new_label_form.cat_radio.choices = [(cat,cat) for cat in categories]
return render_template("new_image.html",
new_image=image_path,
img_id=image_id,
form=new_label_form)
|
PHP
|
UTF-8
| 298
| 2.734375
| 3
|
[] |
no_license
|
<?php
namespace App\Repositories;
use App\Models\Property;
class PropertyRepository
{
/**
* Cria um bem.
*
* @param array $attributes
* @return mixed
*/
public function createProperty(array $attributes)
{
return Property::create($attributes);
}
}
|
TypeScript
|
UTF-8
| 2,830
| 2.546875
| 3
|
[] |
no_license
|
module Pan3d.me {
export class FrameUIRender extends UIRenderComponent {
public constructor() {
super();
}
public setImg(url: string, wNum: number, hNum: number, fun: Function, num: number = 1): void {
TextureManager.getInstance().getTexture(Scene_data.fileRoot + url, ($texture: TextureRes) => {
var ui: UIAtlas = new UIAtlas;
ui.textureRes = $texture;
this.uiAtlas = ui;
if (num == 1) {
fun(this.getFrameTipComponent(wNum, hNum));
} else {
var ary: Array<FrameTipCompenent> = new Array;
for (var i: number = 0; i < num; i++) {
ary.push(this.getFrameTipComponent(wNum, hNum));
}
fun(ary);
}
});
}
public update(): void {
super.update();
for (var i: number = this._uiList.length - 1; i >= 0; i--) {
if (this._uiList[i] instanceof FrameTipCompenent) {
(<FrameTipCompenent>this._uiList[i]).updateEnd();
}
}
}
public getFrameTipComponent(wNum: number, hNum: number): FrameTipCompenent {
var frameTipCom: FrameTipCompenent = new FrameTipCompenent;
var rec: UIRectangle = new UIRectangle;
rec.x = 0;
rec.y = 0;
rec.width = 1;
rec.height = 1;
rec.pixelWitdh = this.uiAtlas.textureRes.width;
rec.pixelHeight = this.uiAtlas.textureRes.height;
rec.pixelX = 0;
rec.pixelY = 0;
rec.type = 2;
rec.cellX = wNum;
rec.cellY = hNum;
frameTipCom.setFrameData(rec);
frameTipCom.uiRender = this;
var rect: any = new Object;
rect.width = this.uiAtlas.textureRes.width / wNum;
rect.height = this.uiAtlas.textureRes.height / hNum;
rect.x = 0;
rect.y = 0;
frameTipCom.width = rect.width;
frameTipCom.height = rect.height;
frameTipCom.x = rect.x;
frameTipCom.y = rect.y;
frameTipCom.baseRec = rect;
return frameTipCom;
}
}
export class FrameTipCompenent extends FrameCompenent {
public constructor() {
super();
}
public playOne($container: UIConatiner): void {
if (!this.parent) {
$container.addChild(this);
}
this.endFlag = false;
this.goToAndPlay(0);
}
public updateEnd(): void {
if (this.endFlag) {
this.parent.removeChild(this);
}
}
}
}
|
JavaScript
|
UTF-8
| 1,583
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//addNote.js
Page({
/**
* 页面的初始数据
*/
data: {
content: ''
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (e) {
var id = e.id;
if (id) {
getData(id, this);
} else {
this.setData({
id: Date.now()
})
}
},
/**
* input change事件
*/
change(e) {
var val = e.detail.value;
this.setData({
content: val
});
},
/**
* cancel 事件
*/
cancel() {
wx.navigateBack();
},
/*
判断内容谁否不为空并赋值回退
*/
sure() {
var reg = /^\s*$/g;
if (!this.data.content || reg.test(this.data.content)) {
console.log('不能为空');
return;
}
this.setData({
time: Date.now()
});
setValue(this);
wx.navigateBack();
}
})
/**
* 根据跳转的url中的id获取编辑信息回填
*/
function getData(id, page) {
var arr = wx.getStorageSync('txt');
if (arr.length) {
arr.forEach((item) => {
if (item.id == id) {
page.setData({
id: item.id,
content: item.content
})
}
})
}
}
/**
* 设置填写的信息,分编辑、新增
*/
function setValue(page) {
var arr = wx.getStorageSync('txt');
var data = [],
flag = true;
if (arr.length) {
arr.forEach(item => {
if (item.id == page.data.id) {
item.time = Date.now();
item.content = page.data.content;
flag = false;
}
data.push(item);
})
}
if (flag) {
data.push(page.data);
}
wx.setStorageSync('txt', data);
}
|
C++
|
UTF-8
| 9,289
| 2.828125
| 3
|
[] |
no_license
|
#include "w_game.hpp"
#include "w_utils.hpp"
#include "w_timer.hpp"
#include <iostream>
#include <vector>
#include <ctime>
// Based on:
// http://weblog.jamisbuck.org/2011/1/10/maze-generation-prim-s-algorithm
// Keep the cell size power-of-two
const int cell_size = 16;
// No instance version
void w_drawLine(SDL_Renderer *wRenderer, SDL_Texture *target, int x1, int y1, int x2, int y2, uint32_t color)
{
auto rgba = uint32ToVec4(color);
if(rgba.w < 0xff) SDL_SetRenderDrawBlendMode(wRenderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderTarget(wRenderer, target);
SDL_SetRenderDrawColor(wRenderer, rgba.x, rgba.y, rgba.z, rgba.w);
SDL_RenderDrawLine(wRenderer, x1, y1, x2, y2);
// Reset back to default renderer
if(target) SDL_SetRenderTarget(wRenderer, nullptr);
}
static bool within(int v, int v_min, int v_max)
{
if (v > v_min && v < v_max) return true;
return false;
}
// Fetch random done cell near candidate
static std::pair<int, int> valid_dones(std::vector<std::vector<int>> &p_grid, int x, int y)
{
std::vector<std::pair<int, int>> mov;
const std::vector<std::pair<int, int>> dirs = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
for (const auto &f: dirs){
if (within(y + f.second, -1, p_grid.size()) &&
within(x + f.first, -1, p_grid[0].size()) &&
p_grid[y + f.second][x + f.first] == 1){
mov.push_back(std::make_pair(x + f.first, y + f.second));
}
}
int rdir = rand() % mov.size();
return mov[rdir];
}
// Advance to next cell
static void advance(std::vector<std::vector<int>> &p_grid, std::vector<std::pair<int, int>> &p_done,
std::vector<std::pair<int, int>> &p_cand, int rx, int ry)
{
p_grid[ry][rx] = 1;
p_done.push_back(std::make_pair(rx, ry));
const std::vector<std::pair<int, int>> dirs = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
for(const auto &f: dirs){
if (within(ry + f.second, -1, p_grid.size()) &&
within(rx + f.first, -1, p_grid[0].size()) &&
p_grid[ry + f.second][rx + f.first] == 0){
p_grid[ry + f.second][rx + f.first] = 2;
p_cand.push_back(std::make_pair(rx + f.first, ry + f.second));
}
}
}
// Do the frontier line segments
static void advanceDraw(std::vector<std::vector<int>> &p_grid, SDL_Texture *maze,
std::pair<int, int> to, std::pair<int, int> from, SDL_Renderer *wRenderer)
{
const int max_x = p_grid[0].size();
const int max_y = p_grid.size();
const int x2 = to.first;
const int y2 = to.second;
const int x2_mult = x2 * cell_size;
const int y2_mult = y2 * cell_size;
// Note: Combine these to 1 for loop like above for better editing in the future
if (within(y2 - 1, -1, max_y) && p_grid[y2 - 1][x2] == 1 && y2 - 1 != from.second){
w_drawLine(wRenderer, maze, x2_mult,
y2_mult,
x2_mult + cell_size,
y2_mult,
0xffffffff);
}
if (within(y2 + 1, -1, max_y) && p_grid[y2 + 1][x2] == 1 && y2 + 1 != from.second){
w_drawLine(wRenderer, maze, x2_mult,
y2_mult + cell_size,
x2_mult + cell_size,
y2_mult + cell_size,
0xffffffff);
}
if (within(x2 - 1, -1, max_x) && p_grid[y2][x2 - 1] == 1 && x2 - 1 != from.first){
w_drawLine(wRenderer, maze, x2_mult,
y2_mult,
x2_mult,
y2_mult + cell_size,
0xffffffff);
}
if (within(x2 + 1, -1, max_x) && p_grid[y2][x2 + 1] == 1 && x2 + 1 != from.first){
w_drawLine(wRenderer, maze, x2_mult + cell_size,
y2_mult,
x2_mult + cell_size,
y2_mult + cell_size,
0xffffffff);
}
}
static bool primS(std::vector<std::vector<int>> &p_grid, SDL_Texture *maze,
bool set_spawn = false, SDL_Renderer *wRenderer = nullptr)
{
static std::vector<std::pair<int, int>> already_done;
static std::vector<std::pair<int, int>> candidates;
if(set_spawn){
int rx = rand() % (p_grid[0].size() - 1);
int ry = rand() % (p_grid.size() - 1);
advance(p_grid, already_done, candidates, rx, ry);
}
else{
// No more room to fill. Return done
if (candidates.size() == 0) return true;
int rcan = rand() % candidates.size();
auto direction = valid_dones(p_grid, candidates[rcan].first, candidates[rcan].second);
advance(p_grid, already_done, candidates, candidates[rcan].first, candidates[rcan].second);
advanceDraw(p_grid, maze, candidates[rcan], direction, wRenderer);
candidates.erase(candidates.begin() + rcan);
}
return false;
}
W_Game::W_Game(const char *title, int width, int height)
{
SDL_Init(SDL_INIT_EVERYTHING);
wWindow = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, 0);
wRenderer = SDL_CreateRenderer(wWindow, -1, 0);
wWidth = width;
wHeight = height;
}
W_Game::~W_Game(void)
{
SDL_DestroyWindow(wWindow);
SDL_DestroyRenderer(wRenderer);
SDL_Quit();
}
void W_Game::w_clear(uint32_t color)
{
auto rgba = uint32ToVec4(color);
SDL_SetRenderDrawColor(wRenderer, rgba.x, rgba.y, rgba.z, rgba.w);
SDL_RenderClear(wRenderer);
}
void W_Game::w_flip(void)
{
SDL_RenderPresent(wRenderer);
}
void W_Game::w_drawRect(SDL_Texture *target, int x1, int y1, int x2, int y2, uint32_t color, bool _fill)
{
auto rgba = uint32ToVec4(color);
if(rgba.w < 0xff) SDL_SetRenderDrawBlendMode(wRenderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderTarget(wRenderer, target);
SDL_SetRenderDrawColor(wRenderer, rgba.x, rgba.y, rgba.z, rgba.w);
const SDL_Rect dst{x1, y1, x2, y2};
if(!_fill) SDL_RenderDrawRect(wRenderer, &dst);
else SDL_RenderFillRect(wRenderer, &dst);
// Reset back to default renderer
if(target) SDL_SetRenderTarget(wRenderer, nullptr);
}
void W_Game::w_drawLine(SDL_Texture *target, int x1, int y1, int x2, int y2, uint32_t color)
{
auto rgba = uint32ToVec4(color);
if(rgba.w < 0xff) SDL_SetRenderDrawBlendMode(wRenderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderTarget(wRenderer, target);
SDL_SetRenderDrawColor(wRenderer, rgba.x, rgba.y, rgba.z, rgba.w);
SDL_RenderDrawLine(wRenderer, x1, y1, x2, y2);
// Reset back to default renderer
if(target) SDL_SetRenderTarget(wRenderer, nullptr);
}
void W_Game::w_gameloop(void)
{
W_FramerateManager w_timer{.num_of_samples=16};
srand(time(NULL));
SDL_Texture *maze = SDL_CreateTexture(wRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, wWidth, wHeight);
int x = 0, y = 0;
for (y; y < wHeight / cell_size; y++){
x = 0;
for (x; x < wWidth / cell_size; x++){
w_drawRect(maze, x * cell_size, y * cell_size, cell_size, cell_size, 0x101010ff);
}
}
w_drawRect(maze, 0, 0, wWidth, wHeight, 0xffffffff);
std::vector<std::vector<int>> grid_2d(y, std::vector<int>(x));
primS(grid_2d, maze, true);
SDL_Event event;
double up = 0.0;
bool draw_done = false;
while(1)
{
w_timer.tick();
SDL_SetWindowTitle(wWindow, std::to_string(w_timer.ft_getFramerate()).c_str());
w_clear(0x303030ff);
while(SDL_PollEvent(&event) != 0){
switch(event.type){
case SDL_QUIT: return;
case SDL_KEYUP:
int key = event.key.keysym.sym;
switch(key){
case SDLK_UP:
primS(grid_2d, maze, false, wRenderer);
}
}
}
if (!draw_done){
if (w_timer.ft_getSeconds() > up)
{
up = w_timer.ft_getSeconds() + .0002;
draw_done = primS(grid_2d, maze, false, wRenderer);
}
}
SDL_RenderCopy(wRenderer, maze, nullptr, nullptr);
// Debug draw (Comment out to save framerate)
// Conquered cell 1: White
// Candidate cell 2: Green
for (y = 0; y < wHeight / cell_size; y++){
for (x = 0; x < wWidth / cell_size; x++){
if (grid_2d[y][x] == 1){
w_drawRect(nullptr, x * cell_size, y * cell_size, cell_size, cell_size, 0xffffff20, true);
}
else if (grid_2d[y][x] == 2){
w_drawRect(nullptr, x * cell_size, y * cell_size, cell_size, cell_size, 0x00400080, true);
}
}
}
w_flip();
}
}
|
TypeScript
|
UTF-8
| 526
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
// just dummy typescript file
import { Component, ElementRef, OnInit } from '@angular/core';
const num = 1;
let me: {};
export interface LintResult {
failureCount: number;
format: string;
output: string;
}
@Component({
selector: 'sg-codelyzer',
template: `
<h1>Hello {{ name }}!</h1>
`
})
class CodelyzerComponent implements OnInit {
name = 'World';
field = true;
private readonly _field: boolean;
constructor(public test: ElementRef) {}
ngOnInit(): void {
console.log('Initialized');
}
}
|
Markdown
|
UTF-8
| 3,562
| 3.28125
| 3
|
[] |
no_license
|
2015.1.19-19
=============
晚上的时候,部门组织聚餐。一堆人聚在一起吃饭喝酒,今天就聊一聊在饭店吃饭的话题。
上大学之前,一般都是跟着父母去饭店吃饭,不用喝酒。自己常常一句话不说。然后就是吃饭。饭桌上大人们聊天,自己也是听的津津有味的,并不觉得无趣。可能是吃饭时比较乖,所以父母经常带着我去饭店吃饭,虽然很多时候是大人们的聚餐。小的时候随父母在外面吃饭,什么都不用管,坐在位置上安静的吃饭就好了。再大一点的时候,自己就被要求服务大家了,给大人们倒茶、敬酒等,总之各种不情愿做的事情都要去做,慢慢的不愿随父母去饭店吃饭了。不过有时也没办法,家里没有人做饭,所以那个时候只能如此。
上大学后,离开父母,生活变得自由起来。当时宿舍里有个传统,就是有人过生日的时候就请宿舍的其他人吃饭。这个传统有点不可思议,不是应该其他人请过生日的那个人吃饭吗?不过现在想想真的给大家一次聚餐的由头,大家一起吃饭的次数多了,关系也就变得紧密了。所以毕业很多年了,一个宿舍的几个人关系也都特别好。上了研究生的时候,宿舍里没有这个传统了,所以毕业了都不知道其他人哪一天的生日。或许他们的生日都赶到假期了。但是实验室还是有一些传统的,例如师兄师姐请新来的学生吃饭,然后毕业的时候要毕业的学生请其他人吃饭,以及没毕业的学生再请要毕业的师兄师姐吃饭。还有就是元旦的时候,导师请大家吃饭,虽然最近几年这个环节被取消了。刚刚察觉到,这些聚餐的传统真的是一个好的传统。不需要费劲心思去思考大家聚餐的由头。而且吃饭这件事情,没有什么好的理由去拒绝,所以能更好的组织大家聚在一起。
关于在饭店吃饭,有些事情印象还是很深刻的。记得本科一个师兄考上了研究生,然后请大家吃饭。这个师兄是在一个协会里认识的,然后他请来吃饭的就是那个协会的人。自己在协会里待了一年,后来就离开了,然后和大家就没怎么联系了。这次吃饭真的是又见到了一些很久没见到而又想要见到的人。已经无法想象当时的心情了,而且吃饭的时候还坐在了一起。再然后就记得一个细节是她竟然还给我夹菜了,大概是自己喝多了,这件事情现在都无法确定了。虽然已经过去很久很久了,常常还是会想起她,想起这件事情。但是记忆已经慢慢变得模糊了,名字和样子都快要记不清了,感觉永远都不会再见了。这可能又是另外一个故事了。
然后上研究生的时候,实验室第一次吃饭,自己就喝多了。当时吐的很厉害,现在想想当时大概是第一次喝多酒。再然后还有一次也是喝多了,然后回到宿舍里,在洗漱室里吐。读研时吃饭就没有再本科时吃饭那么愉快了,在本科时候宿舍集体聚餐,一般都是很少喝酒的,而且整个气氛也比较轻松愉快。而在研究生实验室聚餐,还是学弟的时候要顾及师兄,然后等到自己熬到师兄的时候又要去照顾师弟。而且读到研究生时,大家年龄也都很大了。所以吃顿饭也会觉得累了。
工作后,真的很少在外面很多人一起吃饭了。没有人约啊!
2015.1.19
|
Java
|
UTF-8
| 3,550
| 2.59375
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
/**
* This code is free software; you can redistribute it and/or modify it under
* the terms of the new BSD License.
*
* Copyright (c) 2008-2009, Sebastian Staudt
*/
package steamcondenser.steam.sockets;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
import steamcondenser.SteamCondenserException;
import steamcondenser.steam.packets.SteamPacket;
import steamcondenser.steam.packets.SteamPacketFactory;
/**
* A socket used for connections to Source game servers.
* @author Sebastian Staudt
*/
public class SourceSocket extends QuerySocket
{
public SourceSocket(InetAddress ipAddress, int portNumber)
throws IOException
{
super(ipAddress, portNumber);
}
public SteamPacket getReply()
throws IOException, TimeoutException, SteamCondenserException
{
int bytesRead;
boolean isCompressed = false;
SteamPacket packet;
bytesRead = this.receivePacket(1400);
if(this.packetIsSplit()) {
byte[] splitData;
int packetCount, packetNumber, requestId, splitSize;
int packetChecksum = 0;
ArrayList<byte[]> splitPackets = new ArrayList<byte[]>();
do {
// Parsing of split packet headers
requestId = Integer.reverseBytes(this.buffer.getInt());
isCompressed = ((requestId & 0x80000000) != 0);
packetCount = this.buffer.get();
packetNumber = this.buffer.get() + 1;
if(isCompressed) {
splitSize = Integer.reverseBytes(this.buffer.getInt());
packetChecksum = Integer.reverseBytes(this.buffer.getInt());
}
else {
splitSize = Short.reverseBytes(this.buffer.getShort());
}
// Caching of split packet Data
splitData = new byte[Math.min(splitSize, this.buffer.remaining())];
this.buffer.get(splitData);
splitPackets.ensureCapacity(packetCount);
splitPackets.add(packetNumber - 1, splitData);
// Receiving the next packet
if(splitPackets.size() < packetCount) {
try {
bytesRead = this.receivePacket();
}
catch(TimeoutException e) {
bytesRead = 0;
}
}
else {
bytesRead = 0;
}
Logger.getLogger("global").info("Received packet #" + packetNumber + " of " + packetCount + " for request ID " + requestId + ".");
} while(bytesRead > 0 && this.packetIsSplit());
if(isCompressed) {
packet = SteamPacketFactory.reassemblePacket(splitPackets, true, splitSize, packetChecksum);
}
else {
packet = SteamPacketFactory.reassemblePacket(splitPackets);
}
}
else {
packet = this.getPacketFromData();
}
this.buffer.flip();
if(isCompressed) {
Logger.getLogger("global").info("Received compressed reply of type \"" + packet.getClass().getSimpleName() + "\"");
}
else {
Logger.getLogger("global").info("Received reply of type \"" + packet.getClass().getSimpleName() + "\"");
}
return packet;
}
}
|
C++
|
UTF-8
| 156
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
#include<iostream>
#include<list>
using namespace std;
int main()
{
list<int> l {4,5,9,17,12};
for(auto i:l)
cout<<i<<endl;
return 0;
}
|
JavaScript
|
UTF-8
| 4,078
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
// Given a certain column and target value, get records
// product/api/get/?c={target_column}&q={target_value}&order={orderby}
exports.findByColumn = function (req,res) {
var connection = require('../model/dbconnection');
var column = req.query.c;
var val = req.query.q;
// If order not speficied, then use order date
if (typeof req.query.order == 'undefined')
{
var order = 'Order_Date';
} else {
var order = req.query.order;
}
// get value of limit
if (typeof req.query.limit == 'undefined')
{
var limit = 100;
} else {
var limit = parseInt(req.query.limit);
}
if (limit > 500 || limit < 1) {
limit = 100;
}
// get offset value from requested page
if (typeof req.query.page == 'undefined')
{
var page = 1;
} else {
var page = parseInt(req.query.page);
}
var offset = limit * (page - 1);
connection.query('SELECT * from saleData where ?? = ? ORDER BY ?? DESC LIMIT ? OFFSET ?',
[ column, val, order, limit, offset ], function(err, rows, fields) {
if (!err){
var response = [];
if (rows.length != 0) {
response.push({'result' : 'success', 'data' : rows});
} else {
response.push({'result' : 'error', 'msg' : 'No Results Found'});
}
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
res.status(400).send(err);
}
});
};
// Get all records
// product/api/get/all?order={orderby}
exports.getAllRecords = function (req,res) {
var connection = require('../model/dbconnection');
var val = req.query.q;
// If order not speficied, then use order date
if (typeof req.query.order == 'undefined')
{
var order = 'Order_Date';
} else {
var order = req.query.order;
}
// get value of limit
if (typeof req.query.limit == 'undefined')
{
var limit = 100;
} else {
var limit = parseInt(req.query.limit);
}
if (limit > 500 || limit < 1) {
limit = 100;
}
// get offset value from requested page
if (typeof req.query.page == 'undefined')
{
var page = 1;
} else {
var page = parseInt(req.query.page);
}
var offset = limit * (page - 1);
connection.query('SELECT * from saleData ORDER BY ?? DESC LIMIT ? OFFSET ?',
[ order, limit, page ], function(err, rows, fields) {
if (!err){
var response = [];
if (rows.length != 0) {
response.push({'result' : 'success', 'data' : rows});
} else {
response.push({'result' : 'error', 'msg' : 'No Results Found'});
}
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
res.status(400).send(err);
}
});
};
// Given a certain column and a range of values, get records in range
// product/api/get/search/?c={target_column}&s={start}&e={end}&order={orderby}
exports.rangeSearch = function (req,res) {
var connection = require('../model/dbconnection');
var column = req.query.c;
var startVal = req.query.s;
var endVal = req.query.e;
// If order not speficied, then use order date
if (typeof req.query.order == 'undefined')
{
var order = 'Order_Date';
} else {
var order = req.query.order;
}
// get value of limit
if (typeof req.query.limit == 'undefined')
{
var limit = 100;
} else {
var limit = parseInt(req.query.limit);
}
if (limit > 500 || limit < 1) {
limit = 100;
}
// get offset value from requested page
if (typeof req.query.page == 'undefined')
{
var page = 1;
} else {
var page = parseInt(req.query.page);
}
var offset = limit * (page - 1);
connection.query('SELECT * from saleData WHERE ?? > ? AND ?? < ? ORDER BY ?? DESC LIMIT ? OFFSET ?',
[ column, startVal, column, endVal, order, limit, offset ], function(err, rows, fields) {
if (!err){
var response = [];
if (rows.length != 0) {
response.push({'result' : 'success', 'data' : rows});
} else {
response.push({'result' : 'error', 'msg' : 'No Results Found'});
}
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
res.status(400).send(err);
}
});
};
|
PHP
|
UTF-8
| 3,018
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Emarref\Namer;
use Emarref\Namer\Strategy\StrategyInterface;
use Emarref\Namer\Detector\DetectorInterface;
class Namer
{
const STRATEGY_DEFAULT_LIMIT = 100;
/**
* @var StrategyInterface
*/
private $strategy;
/**
* @var DetectorInterface
*/
private $detector;
/**
* @var int
*/
private $limit;
/**
* @param StrategyInterface $strategy
* @param DetectorInterface|null $detector
* @param int $limit
*/
public function __construct(
StrategyInterface $strategy,
DetectorInterface $detector = null,
$limit = self::STRATEGY_DEFAULT_LIMIT
) {
$this->strategy = $strategy;
$this->detector = $detector;
$this->setLimit($limit);
}
/**
* Set the number of tries to get an available name before throwing an exception.
*
* @param int $limit
*/
public function setLimit($limit)
{
$this->limit = $limit;
}
/**
* Get the number of tries to get an available name before throwing an exception.
*
* @return int
*/
public function getLimit()
{
return $this->limit;
}
/**
* Find an available free name and return it. Returns false if no free name can be found.
*
* @param string $name
* @param Detector\DetectorInterface $detector
* @return false|string
*/
private function findNewName($name, DetectorInterface $detector)
{
$i = 1;
$limit = $this->getLimit();
$originalName = $name;
while (!$detector->isAvailable($name)) {
$name = $this->strategy->getName($originalName, $i);
$i++;
if ($i > $limit) {
return false;
}
}
return $name;
}
/**
* Given a name, use the detector to determine if the name is available to be used. If not, use the strategy to
* generate a new name, then use the detector to determine if that name is available to be used. Continue until
* either an available name has been found, or the limit has been reached.
*
* @param string $originalName
* @param Detector\DetectorInterface|null $detector
* @throws \RuntimeException
* @return string
*/
public function getName($originalName, DetectorInterface $detector = null)
{
$detector = $detector ?: $this->detector;
if (null === $detector) {
throw new \RuntimeException('No detector is configured for this namer.');
}
$newName = $this->findNewName($originalName, $detector);
if (false === $newName) {
throw new \RuntimeException(sprintf(
'Could not find available name for "%s" after %d attempts.',
$originalName,
$this->getLimit()
));
}
return $newName;
}
}
|
Python
|
UTF-8
| 8,810
| 3
| 3
|
[] |
no_license
|
import chess
from chess_helper import board_rotation, get_rank_file, adj_mask, adj_pawns
def material_heuristic(board):
# https://python-chess.readthedocs.io/en/latest/core.html
# chess.PAWN: chess.PieceType= 1
# chess.KNIGHT: chess.PieceType= 2
# chess.BISHOP: chess.PieceType= 3
# chess.ROOK: chess.PieceType= 4
# chess.QUEEN: chess.PieceType= 5
# chess.KING: chess.PieceType= 6
# Hans Berliner's system
# https://en.wikipedia.org/wiki/Chess_piece_relative_value
material_scores = [100, 320, 333, 510, 880, 20000]
score = 0
for piece_type in chess.PIECE_TYPES:
white_player = board.pieces(piece_type, chess.WHITE)
black_player = board.pieces(piece_type, chess.BLACK)
score += material_scores[piece_type - 1] * len(white_player) - material_scores[
piece_type - 1
] * len(black_player)
return score
def pst_heuristic(board):
# The matrices values was found on chessprogramming
# https://www.chessprogramming.org/Simplified_Evaluation_Function
pst_matrix = []
# pawn
pst_matrix.append([0, 0, 0, 0, 0, 0, 0, 0, 50, 50, 50, 50, 50, 50, 50, 50, 10, 10, 20, 30, 30, 20, 10, 10, 5, 5, 10, 25, 25, 10,
5, 5, 0, 0, 0, 20, 20, 0, 0, 0, 5, -5, -10, 0, 0, -10, -5, 5, 5, 10, 10, -20, -20, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0])
# knight
pst_matrix.append([-50, -40, -30, -30, -30, -30, -40, -50, -40, -20, 0, 0, 0, 0, -20, -40, -30, 0, 10, 15, 15, 10, 0, -30, -30, 5, 15, 20, 20, 15,
5, -30, -30, 0, 15, 20, 20, 15, 0, -30, -30, 5, 10, 15, 15, 10, 5, -30, -40, -20, 0, 5, 5, 0, -20, -40, -50, -40, -30, -30, -30, -30, -40, -50, ])
# bishop
pst_matrix.append([-20, -10, -10, -10, -10, -10, -10, -20, -10, 0, 0, 0, 0, 0, 0, -10, -10, 0, 5, 10, 10, 5, 0, -10, -10, 5, 5, 10, 10, 5,
5, -10, -10, 0, 10, 10, 10, 10, 0, -10, -10, 10, 10, 10, 10, 10, 10, -10, -10, 5, 0, 0, 0, 0, 5, -10, -20, -10, -10, -10, -10, -10, -10, -20, ])
# rook
pst_matrix.append([0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 10, 10, 10, 10, 5, -5, 0, 0, 0, 0, 0, 0, -5, -5, 0, 0, 0, 0, 0,
0, -5, -5, 0, 0, 0, 0, 0, 0, -5, -5, 0, 0, 0, 0, 0, 0, -5, -5, 0, 0, 0, 0, 0, 0, -5, 0, 0, 0, 5, 5, 0, 0, 0])
# queen
pst_matrix.append([-20, -10, -10, -5, -5, -10, -10, -20, -10, 0, 0, 0, 0, 0, 0, -10, -10, 0, 5, 5, 5, 5, 0, -10, -5, 0, 5, 5, 5, 5,
0, -5, 0, 0, 5, 5, 5, 5, 0, -5, -10, 5, 5, 5, 5, 5, 0, -10, -10, 0, 5, 0, 0, 0, 0, -10, -20, -10, -10, -5, -5, -10, -10, -20])
# king
pst_matrix.append([-30, -40, -40, -50, -50, -40, -40, -30, -30, -40, -40, -50, -50, -40, -40, -30, -30, -40, -40, -50, -50, -40, -40, -30, -30, -40, -40, -50, -
50, -40, -40, -30, -20, -30, -30, -40, -40, -30, -30, -20, -10, -20, -20, -20, -20, -20, -20, -10, 20, 20, 0, 0, 0, 0, 20, 20, 20, 30, 10, 0, 0, 10, 30, 20])
score = 0
for piece in chess.PIECE_TYPES:
for square in board.pieces(piece, chess.WHITE):
pos = 7 * (7 - int((square - 1) / 8)) + (square - 1) % 8
score += pst_matrix[piece - 1][pos]
for square in board_rotation(board.pieces(piece, chess.BLACK)):
pos = 7 * (7 - int((square - 1) / 8)) + (square - 1) % 8
score -= pst_matrix[piece - 1][pos]
return score
def is_isolated(pawn, pawns):
return int(adj_pawns(pawn, pawns)) > 0
def is_doubled_isolated(pawn, pawns, opponent_pawns):
(p_rank, p_file) = get_rank_file(pawn)
return (
is_isolated(pawn, pawns)
and chess.BB_FILES[p_file] & int(opponent_pawns) > 0
and chess.BB_FILES[p_file] & (~chess.BB_RANKS[p_rank]) & int(pawns) > 0
)
def is_doubled(pawn, pawns):
(p_rank, p_file) = get_rank_file(pawn)
return (
is_isolated(pawn, pawns)
and chess.BB_FILES[p_file] & chess.BB_RANKS[p_rank + 1] & int(pawns) > 0
)
def is_backward(pawn, pawns, opponent_pawns):
(p_rank, p_file) = get_rank_file(pawn)
# Is backward?
adjp = adj_pawns(pawn, pawns)
for y in range(p_rank, 7):
if adjp & chess.BB_RANKS[y] > 0:
return False
# Can safely move?
tmp_mask = 0
if p_rank > 0:
tmp_mask = p_file & chess.BB_RANKS[p_rank - 1]
if p_rank > 1:
tmp_mask = tmp_mask | (adj_mask(pawn) & chess.BB_RANKS[p_rank - 2])
if tmp_mask & int(opponent_pawns) > 0:
return True
return False
def is_supported(pawn, pawns):
(p_rank, _) = get_rank_file(pawn)
return int(adj_pawns(pawn, pawns)) & chess.BB_RANKS[p_rank + 1] > 0
def is_phalanx(pawn, pawns):
(p_rank, _) = get_rank_file(pawn)
return int(adj_pawns(pawn, pawns)) & chess.BB_RANKS[p_rank] > 0
def is_connected(pawn, pawns):
return is_phalanx(pawn, pawns) or is_supported(pawn, pawns)
def is_opposed(pawn, opponent_pawns):
(_, p_file) = get_rank_file(pawn)
return chess.BB_FILES[p_file] & int(opponent_pawns) > 0
def connected_bonus(pawn, pawns, opponent_pawns):
(p_rank, _) = get_rank_file(pawn)
seed = [0, 7, 8, 12, 29, 48, 86, 0]
oppo = is_opposed(pawn, opponent_pawns)
phal = is_phalanx(pawn, pawns)
supp = is_supported(pawn, pawns)
return seed[p_rank] * (2 + phal - oppo) + 21 * supp
def is_weak_unopposed(pawn, pawns, opponent_pawns):
if is_opposed(pawn, opponent_pawns):
return False
return is_isolated(pawn, pawns) or is_backward(pawn, pawns, opponent_pawns)
def pawn_score(a, b):
score = 0
for pawn in a:
if is_doubled_isolated(pawn, a, b):
score -= 11
elif is_isolated(pawn, a):
score -= 5
elif is_backward(pawn, a, b):
score -= 9
if is_doubled(pawn, a):
score -= 11
if is_connected(pawn, a):
score += connected_bonus(pawn, a, b)
if is_weak_unopposed(pawn, a, b):
score -= 13
return score
def pawn_heuristic(board):
WP = board.pieces(chess.PAWN, chess.WHITE)
BP = board.pieces(chess.PAWN, chess.BLACK)
return pawn_score(WP, BP) - pawn_score(board_rotation(BP), board_rotation(WP))
def attacked_by(piece_type, pieces):
attacked_mask = 0
if piece_type == chess.PAWN:
for pawn in pieces:
(p_rank, _) = get_rank_file(pawn)
if(p_rank > 0):
attacked_mask = attacked_mask | (
adj_mask(pawn) & chess.BB_RANKS[p_rank - 1]
)
return attacked_mask
def mobility_area(pawns, king, opponent_pawns):
return chess.SquareSet(~ (int(pawns) | int(king) | attacked_by(chess.PAWN, opponent_pawns)))
def mobility_heuristic(board):
bonus = {
chess.KNIGHT: [-62, -53, -12, -4, 3, 13, 22, 28, 33],
chess.BISHOP: [-48, -20, 16, 26, 38,
51, 55, 63, 63, 68, 81, 81, 91, 98],
chess.ROOK: [-60, -20, 2, 3, 3, 11,
22, 31, 40, 40, 41, 48, 57, 57, 62],
chess.QUEEN: [-30, -12, -8, -9, 20, 23, 23, 35, 38, 53, 64, 65, 65, 66, 67,
67, 72, 72, 77, 79, 93, 108, 108, 108, 110, 114, 114, 116]
}
score = 0
for piece_type in bonus.keys():
for piece in board.pieces(piece_type, chess.WHITE):
score += bonus[piece_type][len(
chess.SquareSet(board.attacks_mask(piece)))]
for piece in board.pieces(piece_type, chess.BLACK):
score -= bonus[piece_type][len(
chess.SquareSet(board.attacks_mask(piece)))]
pawns = board.pieces(chess.PAWN, chess.WHITE)
king = board.pieces(chess.QUEEN, chess.WHITE)
opponent_pawns = board.pieces(chess.PAWN, chess.BLACK)
score += len(mobility_area(pawns, king, opponent_pawns))
pawns = board.pieces(chess.PAWN, chess.BLACK)
king = board.pieces(chess.QUEEN, chess.BLACK)
opponent_pawns = board.pieces(chess.PAWN, chess.WHITE)
score -= len(mobility_area(pawns, king, opponent_pawns))
return score
def evaluation(board):
return (
material_heuristic(board)
+ 0.3 * pst_heuristic(board)
+ 0.3 * pawn_heuristic(board)
+ 0.5 * mobility_heuristic(board)
)
# def get_heuristics(board, color):
# h1 = material_heuristic(board) * (-1 if not color else 1)
# h2 = pst_heuristic(board) * (-1 if not color else 1)
# h3 = pawn_heuristic(board) * (-1 if not color else 1)
# h4 = mobility_heuristic(board) * (-1 if not color else 1)
def get_heuristics(board):
h1 = material_heuristic(board)
h2 = pst_heuristic(board)
h3 = pawn_heuristic(board)
h4 = mobility_heuristic(board)
return (h1, h2, h3, h4)
|
Java
|
GB18030
| 503
| 2.796875
| 3
|
[] |
no_license
|
package hello;
public class task2 {
public static void main(String[] args) {
int[] nums=new int[]{61,23,4,74,13,148,20};
int max=nums[0];
int min=nums[0];
double sum=0;
double avg=0;
for(int i=0;i<nums.length;i++){
if(nums[i]>max){
max=nums[i];
}
if(nums[i]<min){
min=nums[i];
}
sum=sum+nums[i];
}
avg=sum/nums.length;
System.out.println("еֵ"+max);
System.out.println("еСֵ"+min);
System.out.println("ƽֵ"+avg);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.