branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>import random, time
from PIL import Image
class Avatar():
def __init__(self):
print('Avatar generator\n=======================================================')
avatar_size = int(input('Avatar size\nstandard value is 7: '))
avatar_scale = int(input('Avatar Scale\nstandard value is 7: '))
avatars_to_generate = int(input('Quantity: '))
print('=======================================================')
for i in range(avatars_to_generate):
avatar_array = []
print('generating... nr', i + 1)
self.create_array(avatar_array, avatar_size)
# ~ self.display_array(avatar_array)
self.generate_avatar(avatar_array, avatar_size)
# ~ self.display_array(avatar_array)
self.mirror_avatar(avatar_array, avatar_size)
# ~ self.display_array(avatar_array)
avatar_array = self.interpolation(avatar_array, avatar_scale)
# ~ self.display_array(avatar_array)
target = self.image_generate(avatar_array)
def create_array(self, array, size):
for y in range(size):
array.append([])
for x in range(size):
array[y].append('_')
return None
def display_array(self, array):
print('\n')
for y in range(len(array)):
print(array[y])
return None
def generate_avatar(self, array, size):
for y in range(size):
for x in range(size):
r = random.randint(0, 100)
if r > 50:
array[y][x] = 'x'
return None
def mirror_avatar(self, array, size):
mirror = size // 2
for y in range(size):
for x in range(mirror):
array[y][x] = array[y][(size - 1) - x]
return None
def interpolation(self, array, inter):
array2 = []
array3 = []
for y in range(len(array)):
array2.append([])
for x in range(len(array[y])):
for i in range(inter):
array2[y].append(array[y][x])
for y in range(len(array2)):
for i in range(inter):
array3.append(array2[y])
del array
del array2
return array3[:]
def image_generate(self, array):
color = (random.randint(0,255), random.randint(0,255),random.randint(0,255))
image_obj = Image.new('RGBA', (len(array), len(array)), (0,0,0,0))
for y in range(len(array)):
for x in range(len(array)):
if array[y][x] == 'x':
image_obj.putpixel((x,y), (color))
image_obj.save('%s.png' %(str(int(time.time()))))
image_obj.close()
time.sleep(1)
return None
if __name__ == '__main__':
ava = Avatar()
|
536ee6ee28b3a433af034a8e27b3dd0d75c5ca58
|
[
"Python"
] | 1
|
Python
|
InternalCode/Avatar_generator
|
bd26c0fccbe04f670145620ea5ba3a05ac50d61e
|
20d26f8ad1597683c44f2707e6b132759dad406e
|
refs/heads/master
|
<file_sep>Borisbikes
==========
First time experiencing classes and 'CRC' cards in making a program that tracks London's Boris bikes and their usage in day to day use.
Boris Bikes are the blue bikes that you may see dotted in and around london. The bikes interact with the users; the dockingstations the get parked into on the street; the van's that transport the bikes from dock to dock and the garages that will repair the broken bikes.
My task is to model this in code using Ruby. useing OOD and TDD using Rspec.
#Contributers
* <NAME> https://github.com/JackRubio26
* <NAME> https://github.com/jakealvarez
<file_sep>require 'bike'
describe Bike do
let(:bike){Bike.new}
it 'should not be broken when spawned' do
expect(bike.broken?).to eq false
end
it 'should have the ability to break' do
bike.break!
expect(bike.broken?).to eq true
end
it 'should be able to be fixed' do
bike.break!
bike.fix!
expect(bike.broken?).to eq false
end
end
<file_sep>require 'station'
describe DockingStation do
let(:bike){Bike.new}
let(:station){DockingStation.new(capacity:20)}
it 'should accept a bike' do
expect(station.bike_count).to eq (0)
station.dock(bike)
expect(station.bike_count).to eq(1)
end
it 'should release a bike' do
station.dock(bike)
station.release(bike)
expect(station.bike_count).to eq(0)
end
it 'should know when it\'s full' do
expect(station).not_to be_full
20.times {station.dock(Bike.new)}
expect(station).to be_full
end
end
|
e9ca2075b80c868671ef0b7843a8f606432d3ec1
|
[
"Markdown",
"Ruby"
] | 3
|
Markdown
|
JackRubio26/Borisbikes
|
0039d058f22028bf91689c4387ae9069586bbe71
|
072cf8c27c95209fd280a079d62c8ed3414ede4c
|
refs/heads/master
|
<file_sep>// To set up player1, player 2
var game = {
player1: {
name: 'Player 1',
score: 0
},
player2: {
name: 'Player 1',
score: 0
},
ellapsedTime: 0,
currentPlayer: {}
};
// To make the game last only 10 seconds per player, then switch.
// if(game.ellapsedTime > 10){
// switchTurn();
// }
// To end the game and compare scores to determine winner
// if(player1.score > player2.score){
// }
var message = $('#message');
//var score = 0;
var keyCode = 0;
var images = [
{url: './images/0gun1.png', answer: 0},
{url: './images/0gun2.png', answer: 0},
{url: './images/0gun3.png', answer: 0},
{url: './images/0gun4.png', answer: 0},
{url: './images/0gun5.png', answer: 0},
{url: './images/1angry1.png', answer: 1},
{url: './images/1angry2.png', answer: 1},
{url: './images/1angry3.png', answer: 1},
{url: './images/1angry4.png', answer: 1},
{url: './images/1angry5.png', answer: 1},
{url: './images/2calm1.png', answer: 2},
{url: './images/2calm2.png', answer: 2},
{url: './images/2calm3.png', answer: 2},
{url: './images/2calm4.png', answer: 2},
{url: './images/2calm5.png', answer: 2},
];
function chooseRandomPic(){
randomPic = Math.floor((Math.random()*images.length));
$(".bullseye").attr('src', images[randomPic].url );
message.text('');
}
// DRY Fix: created a function for the right and wrong answer display
function rightAnswer(){
game.currentPlayer.score++;
console.log("Right Answer!");
message.text("Right Answer!");
setTimeout(chooseRandomPic, 300);
}
function wrongAnswer(){
console.log("Wrong Answer!");
message.text('Wrong Answer!');
setTimeout(chooseRandomPic, 300);
}
// STEP 1: Create random picture to begin
function startGame(player){
console.log(player);
//alert('Starting game as ', player.name);
game.currentPlayer = player;
//To capture the value of the names that were input
chooseRandomPic();
// To set the timer to count up each second of the game
var seconds = 11;
var timer = setInterval(function(){
seconds--;
console.log('seconds left: ', seconds);
$('.timer').text('Seconds Left: '+seconds.toString());
if (seconds === 0){
clearInterval(timer);
if (game.currentPlayer == game.player1 ){
//player1 finished turn, switch to player2
startGame(game.player2);
} else {
//player2 finished turn, compare score
console.log('Player 1:', game.player1, 'Player 2:', game.player2);
$('#player1-score').text(game.player1.name + ' : ' + game.player1.score);
$('#player2-score').text(game.player2.name + ' : ' + game.player2.score);
//remove event listners
}
}
}, 1000)
}
// STEP 2: Event listener keydown when arrow keys are pressed
// Arrow Key Codes: left = 37 (answer = 0) to shoot
// down = 40 (answer = 1) to tase
// Right = 39 (answer = 2) to pass
function attachKeyDown(){
document.addEventListener('keydown', function(event){
console.log(event.keyCode);
// STEP 3: If there's a match to correct answer, award 1 point, if not 0 points.
// Then move on to next randomly selected image. Iterate.
switch (event.keyCode) {
case 37 :
if(images[randomPic].answer == 0) {
game.currentPlayer.score++;
$('.bullseye').attr('src', './images/bam.png');
rightAnswer();
}else{
wrongAnswer();
};
break;
case 40 :
if(images[randomPic].answer == 1) {
game.currentPlayer.score++;
$('.bullseye').attr('src', './images/zap.png');
rightAnswer();
}else{
wrongAnswer();
};
break;
case 39 :
if(images[randomPic].answer == 2) {
game.currentPlayer.score++;
$('.bullseye').attr('src', './images/thumbup.png');
rightAnswer();
}else{
wrongAnswer();
};
break;
default:
alert("Choose The Arrow Keys: Left, Down or Right");
break;
}
});
}
// Starts game with the press of the "Enter" key
$('.startGameBtn').on('click', function(){
console.log("Clicked start game");
if(!$('#player1-display').val() || !$('#player2-display').val()){
message.text('Missing Player Name!');
} else {
attachKeyDown();
game.player1.name = $('#player1-display').val();
game.player2.name = $('#player2-display').val();
startGame(game.player1);
}
});
<file_sep>GAME NAME: Use of Force AR
DESCRIPTION: Use of Force is designed to both show a use-case of augmented reality (AR) and the need for more training in our nations police academies, security details, and understanding of rules of engagement. Especially given differences in background and social dynamics.
RULES: The display will show three different types of citizens: Gun Weilding, Hostile/Aggressive, Scared/Passive. And the three correct responses award one point per player. Correct responses correspond to: shoot, tase and pass.
CONTROLS: Use arrow keys.
Left = Shoot
Down = Tase
Right = Pass
PLAYERS: Two player game. First player inputs name, Second player inputs name. To start, click HERE with mouse. Then first player has 10 seconds, and switches to second player.
CODE USED: HTML, CSS, Javascript and JQuery
IF MORE TIME: Would make the game much more dynamic by comparing "rounds" of play, more varied citizen types that warrant different responses, and of course application to mobile devices for true AR effect.
=======
# useofforcear
My first ever app coded after exposure to HTML, CSS and Javascript for a week.
|
fdc7390fdb224d987884559f0772c47c849f9483
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
KJWBeige/UseofForceAR
|
50ae5a5fbab9b41bff99b82b7ae1370143fd7067
|
15157eb0b3ac194cc3c43a2ae29323d69541b868
|
refs/heads/master
|
<repo_name>FredyC/grunt-shared-config<file_sep>/test/expected/config-amd.js
define( function() {
return {
"HEIGHT": 120,
"WIDTH": 380,
"AMOUNT": 0.33,
"ANIMATION_SPEED": 100,
"OFFSET": 20
}
} );
<file_sep>/test/expected/config.js
var globalConfig = {
"height": 120,
"width": 380,
"amount": 0.33,
"animation_speed": 100,
"offset": 20
};
|
3d9b1c4756c35e57867e7fd275cac8d60236216a
|
[
"JavaScript"
] | 2
|
JavaScript
|
FredyC/grunt-shared-config
|
641799f596c75c35502402ec361b632a47640df0
|
548378303fb0003e18b2799a9c972cdb1e0017ad
|
refs/heads/master
|
<repo_name>cyberkom-learning/www.cyberkom.pl<file_sep>/inc/index.tpl.pl.php
<html>
<head>
<?php echo $t->head;?>
</head>
<body>
<center>
<div id="is" style="width: 770px;">
<?php echo $t->header;?>
<?php echo $t->main;?>
<?php echo $t->footer;?>
</div>
</center>
</body>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-3218598-1");
pageTracker._trackPageview();
} catch(err) {}</script>
</html>
<file_sep>/class/sms/sendsms.php
<?php
class sms_sendsms{
public function setNumber($nr){
$this->nr = $this->parseNumber($nr);
}
public function setFrom($from){
$this->from = substr($from,0,10);
}
public function setDate($date){
$this->date = $date;
}
public function setTime($time){
$this->time = $time;
}
public function setText($text){
$this->text = $text;
}
private function parseNumber($nr){
$class = new stdClass;
$class->prefix = substr($nr, -9, 3);
$class->number = substr($nr, -6, 6);
return $class;
}
private function getDate(){
if(isset($this->date)){
return date("Y-m-d", strtotime($this->date));
}
else{
return date("Y-m-d");
}
}
private function getTime(){
$class = new stdClass;
if(isset($this->time)){
$class->hour = date("H");
$class->minute = date("i");
}
else{
$class->hour = date("H", strtotime($this->time));
$class->minute = date("i", strtotime($this->time));
}
return $class;
}
public function send(){
$time = $this->getTime();
$curl = new Net_Curl('http://www.text.plusgsm.pl/sms/sendsms.php');
$curl->fields = array('tprefix' => $this->nr->prefix, 'numer' => $this->nr->number, "odkogo" => $this->from, "dzien" => $this->getDate(), "godz" => $time->hour, "min" => $time->minute, "tekst" => $this->text);
$result = $curl->execute();
if (!PEAR::isError($result)) {
return true;
}
else{
return false;
}
}
}
?><file_sep>/class/portal/factory.php
<?php
class portal_factory{
public static $subfolder = "page";
function generatePage($page="main"){
if(empty($page)){
$page = "main";
}
$page = self::$subfolder."_".$page;
if(class_exists($page)){
$html = new $page;
}
else{
throw new Exception("Brak klasy w pliku");
}
$class = new stdClass;
$class->header = $html->executeHeader();
$class->main = $html->execute();
$class->footer = $html->executeFooter();
$class->head = $html->setMetaTags($page);
return portal_buildportal::publish($class, "index");
}
}
?><file_sep>/page/footer.php
<?php
class page_footer extends portal_buildportal{
function execute(){
$this->dupa = "date";
return $this->publish($this, "footer");
}
}
?><file_sep>/inc/lorem.tpl.pl.php
<div style="width: 270px; border: 0px solid #F00; float: left;">
<?php echo $t->leftColumn;?>
</div>
<div style="width: 500px; border: 0px solid #F00; float: right">
<?php echo $t->rightColumn;?>
</div>
<div style="width: 500px; text-align: justify; margin-left: 10px; float: right">
<table class="robert" cellpading=6 rules=groups frame=null border=1>
<thead>
<TR>
<TH>Weekday</TH><TH>Date</TH><TH>Manager</TH><TH>Qty</TH>
</TR>
</thead>
<tbody>
<TR>
<TD>Mon</TD><TD>09/11</TD><TD>Kelsey</TD><TD>639</TD>
</TR>
<TR>
<TD>Tue</TD><TD>09/12</TD><TD>Lindsey</TD><TD>596</TD>
</TR>
<TR>
<TD>Wed</TD><TD>09/13</TD><TD>Randy</TD><TD>1135</TD>
</TR>
<TR>
<TD>Thu</TD><TD>09/14</TD><TD>Susan</TD><TD>1002</TD>
</TR>
<TR>
<TD>Fri</TD><TD>09/15</TD><TD>Randy</TD><TD>908</TD>
</TR>
<TR>
<TD>Sat</TD><TD>09/16</TD><TD>Lindsey</TD><TD>371</TD>
</TR>
<TR>
<TD>Sun</TD><TD>09/17</TD><TD>Susan</TD><TD>272</TD>
</TR>
</tbody>
<tfoot>
<TR>
<TH ALIGN=LEFT COLSPAN=3>Total</TH><TH>4923</TH>
</TR>
</tfoot>
</table>
<ol class='without-margin'><?php if ($this->options['strict'] || (is_array($t->lista) || is_object($t->lista))) foreach($t->lista as $key => $val) {?>
<li>
<?php echo htmlspecialchars($val);?>
</li>
<?php }?>
</ol>
<dl>
<?php if ($this->options['strict'] || (is_array($t->lista) || is_object($t->lista))) foreach($t->lista as $key => $val) {?>
<dt>
<?php echo htmlspecialchars($val);?>
</dt>
<?php }?>
</dl>
<ol class='without-margin'><?php if ($this->options['strict'] || (is_array($t->rightColumn) || is_object($t->rightColumn))) foreach($t->rightColumn as $key => $val) {?>
<li>
<?php echo htmlspecialchars($val->name);?>
</li>
<?php }?>
</ol>
</div>
<div style="clear: both"></div>
<file_sep>/module/projects.php
<?php
class module_projects{
static public function getLastProject($howMany=5){
$class = new stdClass();
$class->array = array();
$news = new dbdata_News;
$news->orderBy("ID DESC");
$news->limit($howMany);
$news->find();
while($news->fetch()){
$class->array[] = clone($news);
}
return portal_buildportal::publish($class, "module_project_last");
}
static public function getSwf($name){
$class = new stdClass();
$class->swf = $name[0];
$class->swf2 = $name[1];
return portal_buildportal::publish($class, "module_project_swf");
}
}
?><file_sep>/inc/kontakt.tpl.pl.php
<div style="width: 270px; border: 0px solid #F00; float: left;">
<?php echo htmlspecialchars($t->robert);?>
<?php echo $t->leftColumn;?>
</div>
<div style="width: 500px; border: 0px solid #F00; float: right">
<?php echo $t->rightColumn;?>
</div>
<div style="clear: both"></div>
<file_sep>/page/uslugi.php
<?php
class page_uslugi extends portal_buildportal {
function execute(){
portal_head::setStyle("style.css");
$this->leftColumn = $this->setLeftColumn();
$this->rightColumn = $this->setRightColumn();
return $this->publish($this, "firma");
}
function setLeftColumn(){
return module_projects::getSwf(array("firma","menu03"));
}
}
?><file_sep>/class/dbdata/Statystyki.php
<?php
/**
* Table Definition for statystyki
*/
require_once 'DB/DataObject.php';
class dbdata_Statystyki extends DB_DataObject
{
###START_AUTOCODE
/* the code below is auto generated do not remove the above tag */
public $__table = 'statystyki'; // table name
public $ID; // int(10) not_null primary_key unsigned auto_increment
public $IP; // string(15)
public $HOST; // string(100)
public $DATA; // datetime(19) binary
public $CZASPOBYTU; // int(11)
public $PRZEGLADARKA; // string(50)
public $SYSTEM; // string(50)
public $KRAJ; // string(50)
public $WOJEWODZTWO; // string(50)
public $MIASTO; // string(50)
public $IMIE; // string(30)
public $STALY; // string(50)
public $DOMENA; // string(100)
public $HTTP_USER; // blob(65535) blob
public $HTTP_X_FORWARDED_FOR; // string(15)
public $HTTP_X_FORWARDED_FOR_DOMAIN; // string(100)
public $HTTP_REFERER; // string(500) not_null
/* Static get */
function staticGet($k,$v=NULL) { return DB_DataObject::staticGet('dbdata_Statystyki',$k,$v); }
/* the code above is auto generated do not remove the tag below */
###END_AUTOCODE
}
<file_sep>/class/portal/head.php
<?php
class portal_head{
static private $style = array();
static private $title = "..:: CYBERKOM ::.. webdesign";
public function get(){
$class = new stdClass;
$class->title = self::getTitle();
$class->style = self::getStyle();
return portal_buildportal::publish($class, "head");
}
public function setStyle($name){
self::$style[] = $name;
}
private function getStyle(){
return self::$style;
}
public function setTitle($title=false){
if($title){
self::$title = $title;
}
}
private function getTitle(){
return self::$title;
}
}
?><file_sep>/_config.php
<?php
set_include_path(getcwd()."/class/".PATH_SEPARATOR.getcwd()."/class/PEAR/".PATH_SEPARATOR.get_include_path());
DB_DataObject::debuglevel(7);
$options = &PEAR::getStaticProperty('DB_DataObject','options');
$databasedsn = "mysql://rsuchomski:pL2UjbNTWLz3SJDF@localhost:3306/rsuchomski";
$options = array(
'database' => $databasedsn,
'schema_location' => 'ini/',
'class_location' => 'class/dbdata/',
'require_prefix' => 'dbdata/',
'class_prefix' => 'dbdata_',
'quote_identifiers' => true
);
function __autoload($class){
$class = str_replace("_", "/", $class);
if(!include_once($class.".php")){
throw new Exception("No class");
}
}
function printPre($var){
echo "<pre>";
print_r($var);
echo "</pre>";
}
?><file_sep>/class/dbdata/Robert.php
<?php
/**
* Table Definition for robert
*/
require_once 'DB/DataObject.php';
class dbdata_Robert extends DB_DataObject {
public $__table = 'robert';
// table name
public $id;
public $name;
function __construct(){
$this->query("SET NAMES latin2");
}
/* Static get */
function staticGet($k, $v = NULL) {
return DB_DataObject::staticGet('dbdata_Robert', $k, $v);
}
}
<file_sep>/page/portfolio.php
<?php
class page_portfolio extends portal_buildportal {
public $srcimg = "/img/portfolio/";
function execute(){
portal_head::setStyle("style.css");
$this->portfolio = $this->getPortFolio();
return $this->publish($this, "module_project_portfolio");
}
private function getPortFolio(){
$portfolio = new dbdata_Portfolio;
$portfolio->orderBy("firma");
$portfolio->find();
$array = array();
while($portfolio->fetch()){
$array[] = clone($portfolio);
}
return $array;
}
}
?><file_sep>/page/webdesign.php
<?php
class page_webdesign extends page_uslugi{
}
?><file_sep>/inc/headerRobert.tpl.pl.php
<div style="width: 770px; height:50px; border: 0px solid #F00; float: middle; font-size: 20">
<?php echo $t->header;?>
</div>
<div style="clear: both"></div><file_sep>/ini/rsuchomski.ini
[news]
ID = 129
tytul = 130
tresc = 194
data = 134
[news__keys]
ID = N
[portfolio]
ID = 129
firma = 130
obrazek = 130
zakres = 194
adres = 130
referencje = 2
technologie = 194
wykonanie = 130
[portfolio__keys]
ID = N
[stat_old]
ID = 129
IP = 2
HOST = 2
DATA = 1
CZASPOBYTU = 1
PRZEGLADARKA = 2
SYSTEM = 2
KRAJ = 2
WOJEWODZTWO = 2
MIASTO = 2
IMIE = 2
STALY = 2
DOMENA = 2
HTTP_USER = 66
[stat_old__keys]
ID = N
[statystyki]
ID = 129
IP = 2
HOST = 2
DATA = 14
CZASPOBYTU = 1
PRZEGLADARKA = 2
SYSTEM = 2
KRAJ = 2
WOJEWODZTWO = 2
MIASTO = 2
IMIE = 2
STALY = 2
DOMENA = 2
HTTP_USER = 66
HTTP_X_FORWARDED_FOR = 2
HTTP_X_FORWARDED_FOR_DOMAIN = 2
HTTP_REFERER = 130
[statystyki__keys]
ID = N
[robert]
id = 129
name = 2
[robert__keys]
ID = N<file_sep>/class/portal/buildportal.php
<?php
abstract class portal_buildportal {
function setMetaTags($page){
return portal_head::get($page);
}
function executeHeader(){
return page_header::execute();
}
function execute(){
}
function executeFooter(){
return page_footer::execute();
}
function setRightColumn(){
$text = new module_staticText;
$name = str_replace("page_", "", get_class($this));
return $text->$name();
}
function publish($object, $tpl=false){
if(!$tpl){
$tpl = str_replace("page_", "",get_class($object));
}
$tpl = str_replace("_", "/",$tpl);
$options = array(
'templateDir' => 'tpl/',
'compileDir' => getcwd().'/inc/',
'forceCompile' => 0,
'debug' => 0,
'locale' => 'pl',
'compiler' => 'Standard',
'charset' => 'utf-8'
);
$template = new HTML_Template_Flexy($options);
$template->compile($tpl.".tpl");
if($_GET["debug"]){
$ret = "<div style='border:0px solid #F00; position:relative'>";
$ret .= "<div style='background-color:#333; color:#FFF; border:1px solid #F00; position:absolute'>";
$ret .= $tpl.".tpl";
$ret .= "</div>";
}
$ret.= $template->bufferedOutputObject($object);
if($_GET["debug"]){
$ret .= "</div>";
}
return $ret;
}
}
?><file_sep>/class/dbdata/Portfolio.php
<?php
/**
* Table Definition for portfolio
*/
require_once 'DB/DataObject.php';
class dbdata_Portfolio extends DB_DataObject
{
###START_AUTOCODE
/* the code below is auto generated do not remove the above tag */
public $__table = 'portfolio'; // table name
public $ID; // int(10) not_null primary_key unsigned auto_increment
public $firma; // string(100) not_null
public $obrazek; // string(100) not_null
public $zakres; // blob(65535) not_null blob
public $adres; // string(100) not_null
public $referencje; // string(100)
public $technologie; // blob(65535) not_null blob
public $wykonanie; // string(100) not_null
function __construct(){
$this->query("SET NAMES latin2");
}
/* Static get */
function staticGet($k,$v=NULL) { return DB_DataObject::staticGet('dbdata_Portfolio',$k,$v); }
/* the code above is auto generated do not remove the tag below */
###END_AUTOCODE
}
<file_sep>/page/kontakt2.php
<?php
class page_kontakt2 extends portal_buildportal {
function execute(){
portal_head::setStyle("style.css");
$this->getData();
$this->leftColumn = $this->setLeftColumn();
$this->rightColumn = $this->setRightColumn();
$this->robert = "Piotr";
return $this->publish($this, "kontakt");
}
function setLeftColumn(){
$text = new module_staticText;
return $text->danefirmy();
}
private function getData(){
if($_POST["B1"]){
mail("<EMAIL>", "Osoba odwiedzajaca strone ".$_SERVER["HTTP_HOST"]." prosi o kontakt", "Firma: ".$_POST["firma"]."\nImi� i nazwisko: ".$_POST["nazwisko"]."\nTelefon: ".$_POST["telefon"]."\nE-mail: ".$_POST["email"]."\nZapytanie: ".$_POST["zapytanie"], "From: ".$_SERVER["HTTP_HOST"]." <<EMAIL>>");
}
}
}
?>
<file_sep>/page/lorem.php
<?php
class page_lorem extends portal_buildportal {
function execute() {
portal_head::setStyle("style.css");
$this -> leftColumn = $this -> setLeftColumn();
$this -> rightColumn = $this -> setRightColumn();
$this -> lista = array("pozycja1", "pozycja2", "pozycja3");
$this -> dziala = true;
return $this -> publish($this, "lorem");
}
function setRightColumn() {
//$text = new module_staticText;
//$name = str_replace("page_", "", get_class($this));
//return $text -> $name();
//$robert = new DataObjects_Robert;
//ZADANIE BAZADANYCH
$class = new stdClass();
$class->array = array();
$robert = new dbdata_Robert;
$robert->name='Robert';
$id = $robert->insert();
$robert->name='Piotr';
$id = $robert->insert();
$robert->name=null;
//$robert->orderBy("name");
$robert->find();
while($robert->fetch()){
if ($robert->name=='Piotr') $robert->name='Hania';
$class->array[] = clone($robert);
}
return $class->array;
//KONIEC ZADANIA
}
function setLeftColumn() {
$text = new module_staticText;
$name = str_replace("page_", "", get_class($this));
$name = $name . "left";
return $text -> $name();
}
function executeHeader() {
$this -> header = "Strona Roberta :-)";
return $this -> publish($this, "headerRobert");
}
}
?>
<file_sep>/index.php
<?php
include_once("_config.php");
//include_once("test.php");
try{
echo portal_factory::generatePage($_GET["id"]);
}
catch (Exception $e){
echo portal_factory::generatePage();
}
?>
<file_sep>/module/staticText.php
<?php
class module_staticText{
public function __call($name, $value){
return portal_buildportal::publish(new stdClass(), "module_staticText_".$name);
}
}
?>
<file_sep>/page/header.php
<?php
class page_header extends portal_buildportal{
function execute(){
$this->dupa = "date";
return $this->publish($this, "header");
}
}
?>
|
869b4da43e5e7075810ebc9613ca9d75512bc4b3
|
[
"PHP",
"INI"
] | 23
|
PHP
|
cyberkom-learning/www.cyberkom.pl
|
5cb56e789650987260c061c9477457e4867ee9c6
|
945c330258f65581a442796abd171022bf00b174
|
refs/heads/main
|
<repo_name>aarti7400/Git-Demo<file_sep>/math.py
# Add Imlementation
def add(x,y):
return x+y
# sub Imlementation
def subtract(x,y): #main
if y>x
return error;
else
return x-y
# mul Imlementation
def multiply(x,y):
pass
# div Imlementation
def divide(x,y):
pass<file_sep>/README.md
# Git-Demo
# This is readme file
|
57e0902acf4f2a7a09410411578b0f6b7f7cc289
|
[
"Markdown",
"Python"
] | 2
|
Python
|
aarti7400/Git-Demo
|
91c365499fa579ed74e8430538b502b559a461e1
|
39bf5ca73d8ba91ff7cc9be1224e901ab7d79615
|
refs/heads/master
|
<repo_name>paoliniluis/shift-to-spectrum<file_sep>/index.js
const { Pool } = require('pg');
const argv = require('minimist')(process.argv.slice(2));
const fs = require('fs');
let dbConfig = {
user: argv.user,
database: argv.db,
password: <PASSWORD>,
host: argv.host,
port: argv.port || 5439, //default for redshift
ssl: true
};
let finalSyntax = '';
const pool = new Pool(dbConfig);
const dataTypeValidator = (dataType) => {
let type = '';
switch(dataType.data_type) {
case 'character varying':
type = 'VARCHAR(' + dataType.character_maximum_length + ')';
break;
case 'timestamp without time zone':
type = 'TIMESTAMP';
break;
case 'bigint':
type = 'BIGINT';
break;
case 'boolean':
type = 'BOOLEAN';
break;
case 'double precision':
type = 'FLOAT(' + dataType.numeric_precision + ')';
break;
default:
type = '';
break;
}
return dataType.column_name + ' ' + type + ','
}
async function tableSyntaxGen(schema, table) {
let unloadToS3 = `
UNLOAD ('select * from ` + schema + '.' + table + `')
TO 's3://` + argv.spdir+ `/` + schema + table + `/'
ACCESS_KEY_ID '` + argv.awskey + `'
SECRET_ACCESS_KEY '` + argv.awssecret + `'
MAXFILESIZE 100 mb
GZIP;`
let describeTable = `
SELECT column_name,
data_type,
character_maximum_length,
numeric_precision
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = '` + schema +`'
AND table_name = '` + table + `';`
let countRows = 'SELECT COUNT(*) FROM ' + schema + '.' + table + ';'
const client = await pool.connect();
const structure = await client.query(describeTable);
const rowCount = await client.query(countRows);
await client.release();
let newTableStructure = '';
structure.rows.forEach(row => {
newTableStructure += dataTypeValidator(row);
})
let createExternal = `
CREATE EXTERNAL TABLE e_` + schema + `.` + table +
`(` + newTableStructure.slice(0,-1) + `)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '|'
LOCATION 's3://` + argv.spdir + `/` + schema + table + `/'
TABLE PROPERTIES ('numRows'='`+ rowCount.rows[0].count +`');`
return unloadToS3 + createExternal;
}
async function schemaSyntaxGen(schema) {
let getAllTablesOfTheSchema = `
SELECT table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
AND table_schema ='` + schema + `';`
const client = await pool.connect();
const tables = await client.query(getAllTablesOfTheSchema);
await client.release();
let tablesResponse = [];
tables.rows.forEach(table => {
tablesResponse.push(table.table_name)
})
return tablesResponse;
}
const externalSchemaSyntaxGen = (schema) => {
return generateExternalSchema = `
CREATE external SCHEMA e_` + schema + `
FROM data catalog
DATABASE '` + schema + `'
iam_role '` + argv.awsiamrole + `'
CREATE external DATABASE if not exists;`
}
async function main() {
if (!argv || argv.help || argv.h || argv['?']) throw new Error (`I need the following mandatory attributes to work:
--host: AWS Redshift host to connect to
--user: username (must have privileges to unload and create new tables in Spectrum schemas) to connect to AWS Redshift
--pass: <PASSWORD> to connect to AWS Redshift
--db: database to connect to inside AWS Redshift
--schema: originl Redshift Schema (the one that will be unloaded)
--spdir: AWS Redshift Spectrum S3 Bucket
--awskey: IAM Key that has privileges over the S3 where files will be unloaded
--awssecret: IAM Secret that has privileges over the S3 Bucket where files will be unloaded
OPTIONAL:
--port: in case you have your cluster in another port
--table: if you want to generate the script for a single table instead of the whole schema
--awsiamrole: the IAM Role who has access to the S3 bucket that Spectrum can query`)
if (!argv.pass || argv.pass == '') throw new Error ('I need a password to connect to Redshift, otherwise I cannot continue');
if (!argv.host || argv.host == '') throw new Error ('I need a host to connect to, otherwise I cannot continue');
if (!argv.user || argv.user == '') throw new Error ('I need a username to connect to Redshift, otherwise I cannot continue');
if (!argv.db || argv.db == '') throw new Error ('I need a database to point to, otherwise I cannot continue');
if (!argv.schema || argv.schema == '') throw new Error ('I need a DB schema at least, otherwise I cannot continue');
if (!argv.spdir || argv.spdir == '') throw new Error ('I need the S3 Bucket where the Spectrum files will be located, otherwise I cannot continue');
if (!argv.awskey || argv.awskey == '') throw new Error ('I need the AWS key that will be used for unloading the table, otherwise I cannot continue');
if (!argv.awssecret || argv.awssecret == '') throw new Error ('I need the AWS Secret that will be used for unloading the table, otherwise I cannot continue');
if (argv.schema && !argv.table) {
console.log('I will generate the script for unloading the whole schema', argv.schema);
finalSyntax += externalSchemaSyntaxGen(argv.schema);
tables = await schemaSyntaxGen(argv.schema);
for (let table of tables) {
console.log('Generating syntax for', table, '...');
finalSyntax += await tableSyntaxGen(argv.schema, table);
}
if (argv.execute == 'true') return console.log('I will be executing the following syntax', finalSyntax) || await client.query(finalSyntax);
if (!argv.execute || argv.execute == 'false' || argv.execute == '') return console.log('syntax.sql file generated') || fs.writeFileSync('syntax.sql', finalSyntax);
}
if (argv.schema && argv.table) {
console.log('I will generate the script for unloading ', argv.schema + '.' + argv.table)
console.log('Generating syntax for', argv.table, '...');
finalSyntax = await table(argv.schema, argv.table);
if (argv.execute == 'true') return console.log('I will be executing the following syntax', finalSyntax) || await client.query(finalSyntax);
if (!argv.execute || argv.execute == 'false' || argv.execute == '') return console.log('syntax.sql file generated') || fs.writeFileSync('syntax.sql', finalSyntax);
}
}
try {
main();
}
catch (e) {
console.log(e)
}<file_sep>/README.md
#### NOTE: I AM NOT RESPONSIBLE OF ANYTHING THAT HAPPENED OR CAN HAPPEN TO YOUR REDSHIFT CLUSTER, THE USER (YOU) IS THE ONE AND ONLY RESPONSIBLE OF THE USE/MISUSE OF THIS SCRIPT. I HAVEN'T GOT ANY RELATIONSHIP WITH AWS SO THE CREATION AND USE OF THIS SCRIPT HAS BEEN DONE ACCORDING TO AWS DOCUMENTATION. PLEASE CHECK THE LICENSE.
# Shift to Spectrum
This script was created to ease the offloading of tables/schemas out of AWS Redshift and having them on Redshift Spectrum. This is of special use when you want to dump historical data into other types of storage (like AWS S3). The Spectrum layer does a wonderful job when queried with AWS Redshift, so I created this script to help myself in the offloading of old and rarely used tables of our Data Warehouse.
At this stage, the script only supports offloading the tables with a AWS Key and Secret (the ones you create through IAM) and it stores the tables in TEXT files separated by PIPE (|). It stores those files GZIP'ed and with a size of maximum 100MB, as this is a recommended practice according to AWS documentation as Spectrum can parallelize its queries across all these files.
You can use this script to generate the Syntax and run it for yourself, with any client you want, or run it though the Node postgre client itself. You can use it in multiple ways:
1. Generate (or execute) the offloading script for an entire schema
2. Generate (or execute) the offloading script for a single table
### REQUIREMENTS
**Node.js 8+** (must support async/await)
### USAGE:
1. `git clone` or download this repo
2. on the downloaded directory do a `npm i` to install all dependencies
3. `node index` with the flags below
4. Once finished (and if you didn't use the execute flag), you will see a syntax.sql file generated with all the commands
### FLAGS
> **--host**: AWS Redshift host to connect to
>
> **--user**: username (must have privileges to unload and create new tables in Spectrum schemas) to connect to AWS Redshift
>
> **--pass**: password to connect to AWS Redshift
>
> **--db**: database to connect to inside AWS Redshift
>
> **--schema**: originl Redshift Schema (the one that will be unloaded)
>
> **--spdir**: AWS Redshift Spectrum S3 Bucket
>
> **--awskey**: IAM Key that has privileges over the S3 Bucket where files will be unloaded
>
> **--awssecret**: IAM Secret that has privileges over the S3 Bucket where files will be unloaded
#### OPTIONAL:
> **--port**: in case you have your cluster in another port
>
> **--table**: if you want to generate the script for a single table instead of the whole schema
>
> **--awsiamrole**: the IAM Role who has access to the S3 bucket that Spectrum can query
The script will generate the UNLOAD syntax followed by a CREATE EXTERNAL TABLE one with the same structure as the table has. For entire schema dump, it will also generate the CREATE EXTERNAL SCHEMA and will generate a new schema with an "e_" + the name of your schema
Please note that this script does not configure your Redshift cluster to use Redshift Spectrum and you MUST do that before running this script, otherwise it will fail.
NOTE: I'm already aware that having PARQUET formatted files in S3 rather than text files is way quicker than text files, but Redshift does a great job caching the queries so while the Redshift team builds the UNLOAD to Parquet feature, this tool provides great functionality to everyone that is running out of space on their clusters.
TODO:
1. Include an option to generate the VIEW in the old schema
2. Add new Data Types in the function dataTypeValidator --> this was planned to only use TIMESTAMP, VARCHAR and BIGINT, BOOLEAN and FLOAT fields, if there are more fields that you need, please send a Pull Request so we can all improve this tool!
|
73c422e76bf89450f8334b64539b3403562833f0
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
paoliniluis/shift-to-spectrum
|
453d1a436335a13b1f75f945275fe58a90adb24a
|
b999d063a09a1580db9e90c3cf45ca6c74d42eb4
|
refs/heads/master
|
<file_sep># Dog Articles Scraper
## What is it?
Dog Articles Scraper is an application that allows its users to scrape for the latest dog's articles from a dog website:https://moderndogmagazine.com/articles
Users can then comment on articles of interest and save them.
***
## User Interaction
When the user enters the page they are led to a page where they can choose to scrape for new articles from modern dog magazine.
<img src="./public/assets/images/forReadMe1.jpg" width="400px" height="350px">
They can open a link to view the original article and read it.
<img src="./public/assets/images/forReadMe2.jpg" width="400px" height="350px">
The user can then click the comment button and leave a comment about what they thought about the article.
<img src="./public/assets/images/forReadMe3.jpg" width="400px" height="350px">
## What technologies are used?
The technologies used in this News Scraper include:
* HTML
* CSS
* JavaScript
* Handlebars
* Node (primarily the cheerio and axios packages)
* MongoDB
* Express
***
## How to Initialize the Dog Scraper on your own machine
1. Git clone the repository
2. Navigate to the repository in terminal or bash
3. Type npm i
4. Type node server (or nodemon server)
***
## Future Development
1. Adding a user database and authentication process so that users can save articles to their account
***
## See the App in Action
[See the App in Action](https://ancient-crag-53575.herokuapp.com/)
<file_sep>const cheerio = require("cheerio");
const request = require("request");
const express = require('express');
const router = express.Router();
const axios = require("axios");
const db = require("../models");
const phantom = require("phantom");
router.get("/scrape", function (req, res) {
console.log("scrape hit");
axios.get("https://moderndogmagazine.com/articles").then(function (response) {
var $ = cheerio.load(response.data);
var dummyArray = [];
$("tr").each(function(i, element){
var result= {};
// var url = "https://moderndogmagazine.com";
result.site = "Dog's Articles";
result.url = $(this)
.find("td").find("span").children("a").attr("href");
result.image = $(this)
.find("td").find("a").children("img").attr("src");
result.headline = $(this)
.find("td").children("h2").text().trim();
result.byline = $(this)
.find("td").find(".category").children("a").attr("href");
result.summary = $(this)
.find("td").text();
dummyArray.push(result);
db.Article.create(result)
.then(function(newArticle){
}).catch(function(err){
console.log("Couldn't create new articles");
})
});
res.redirect("/");
});
axios.get("https://moderndogmagazine.com/articles?page=1").then(function (response) {
var $ = cheerio.load(response.data);
var dummyArray = [];
$("tr").each(function(i, element){
var result= {};
// var url = "https://moderndogmagazine.com";
result.site = "Dog's Articles";
result.url = $(this)
.find("td").find("span").children("a").attr("href");
result.image = $(this)
.find("td").find("a").children("img").attr("src");
result.headline = $(this)
.find("td").children("h2").text().trim();
result.byline = $(this)
.find("td").find(".category").children("a").attr("href");
result.summary = $(this)
.find("td").text();
dummyArray.push(result);
db.Article.create(result)
.then(function(newArticle){
}).catch(function(err){
console.log("Couldn't create new articles");
})
});
res.redirect("/");
});
axios.get("https://moderndogmagazine.com/articles?page=2").then(function (response) {
var $ = cheerio.load(response.data);
var dummyArray = [];
$("tr").each(function(i, element){
var result= {};
// var url = "https://moderndogmagazine.com";
result.site = "Dog's Articles";
result.url = $(this)
.find("td").find("span").children("a").attr("href");
result.image = $(this)
.find("td").find("a").children("img").attr("src");
result.headline = $(this)
.find("td").children("h2").text().trim();
result.byline = $(this)
.find("td").find(".category").children("a").attr("href");
result.summary = $(this)
.find("td").text();
dummyArray.push(result);
db.Article.create(result)
.then(function(newArticle){
}).catch(function(err){
console.log("Couldn't create new articles");
})
});
res.redirect("/");
});
});
router.get("/view", function(req, res){
db.Article.find({ site: "Dog's Articles"}, function(err, docs){
if (err){console.log(err)};
let dndInfo = {
posts: docs
};
res.render("index", dndInfo);
});
})
router.get("/", function(req, res){
console.log("index hit");
db.Article.find({}, function(err, docs){
let handleInfo = {
posts: docs
};
res.render("index", handleInfo);
});
});
// route to go to comments page for article
router.get("/comments/:id", function(req, res){
let id = req.params.id;
console.log("comments hit", id);
db.Article.find({_id: id}).populate("comments").then(function(docs){
return docs;
console.log(docs);
}).then(function(data){
let commentData = {
comment: data
};
console.log(commentData);
res.render("comments", commentData);
})
});
//route to add comments
router.post("/addComment/:id", function(req, res){
console.log("add comment hit");
db.Comments.create(req.body).then(docs =>{
console.log(docs);
return db.Article.findOneAndUpdate({_id: req.params.id}, {$push: {comments: docs._id} }, {new: true, upsert: true});
}).then(newArticle => {
console.log(newArticle);
res.redirect("/comments/" + req.params.id);
})
});
module.exports = router;
|
3ea74828794502758846a7324d3ba3206ac0c2f4
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
AnnyHuynh/News-Scraper
|
23f1357fd298654095220d382ef3cfc38a696cd3
|
deb0f0bda21ca18579426ccc5ae93b4c2ef77081
|
refs/heads/master
|
<repo_name>tesfay-bsrat/OOP-project<file_sep>/Best/Best/Class1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace Best
{
public delegate void dataReceived(object sender, SerialPortEventArgs arg);
public class SerialPortEventArgs : EventArgs
{
public string ReceivedData { get; private set; }
public SerialPortEventArgs(string data)
{
ReceivedData = data;
}
}
class Class1
{
public event dataReceived DataReceived;
/// <summary>
/// event based on delegate
/// </summary>
private string Send_data;
private string Recieve_data;
private string portname;
public string display;
public string[] Ports_incbox;
private TextBox textboxshow;
private ProgressBar Connection;
private string toolStripCombo1;
private string toolStripCombo2;
SerialPort serial = new SerialPort();
public string data_to_send
{
get
{
return Send_data;
}
set
{
Send_data = value;
}
}
public TextBox ChatWindow
{
get { return textboxshow; }
set { textboxshow = value; }
}
public ProgressBar Conx
{
get
{
return Connection;
}
}
public string data_to_reciev
{
get
{
return Recieve_data;
}
set
{
Recieve_data = value;
}
}
public string Port
{
get
{
return portname;
}
set
{
portname = value;
}
}
public string toolStripComboBox1
{
set
{
toolStripCombo1 = value;
}
get
{
return toolStripCombo1;
}
}
public string toolStripComboBox2
{
set
{
toolStripCombo2 = value;
}
get
{
return toolStripCombo2;
}
}
public string displayed
{
get
{
return display;
}
}
public void Show_Ports()
{
Ports_incbox = SerialPort.GetPortNames();
}
public void OpenConnection()
{
if (!serial.IsOpen)
{
serial.PortName = Port;
serial.Open();
// serial.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
serial.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
}
else
{
MessageBox.Show(" Please Select Communication Port First!");
}
}
public void CloseConnection()
{
if (serial.IsOpen)
{
serial.Close();
Connection = null;
}
}
//private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
data_to_reciev = serial.ReadExisting();
if (this.DataReceived != null)
{
SerialPortEventArgs args = new SerialPortEventArgs(data_to_reciev);
this.DataReceived(this, args);
}
//ShowData();
}
//private void ShowData()
//{
// if (toolStripComboBox1 == "Add to old data")
// {
// textboxshow.Invoke(new EventHandler(delegate {
// textboxshow.Text += data_to_reciev;
// //textboxshow.Text = textboxshow.Text.Insert(0, textboxshow);
// }));
// }
// else if (toolStripComboBox1 == "Always Update")
// {
// textboxshow.Invoke(new EventHandler(delegate
// {
// textboxshow.Text = data_to_reciev;
// //textboxshow.Text = textboxshow.Text.Insert(0, textboxshow);
// }));
// }
// else
// {
// textboxshow.Invoke(new EventHandler(delegate {
// textboxshow.Text += data_to_reciev;
// }));
// }
//}
public void Gone()
{
if (serial.IsOpen)
{
if(toolStripComboBox2 == "None")
{
serial.WriteLine(data_to_send);
}
else if(toolStripComboBox2 == "Both")
{
serial.WriteLine(data_to_send + "\r\n");
}
else if(toolStripComboBox2 == "New Line")
{
serial.WriteLine(data_to_send + "\n");
}
else if(toolStripComboBox2 == "Carriage Return")
{
serial.WriteLine(data_to_send + "\r");
}
else
{
serial.WriteLine(data_to_send + "\r");
//MessageBox.Show("Too " + toolStripComboBox2);
}
}
else
{
MessageBox.Show(" Please Open Connection First!");
}
}
public void Clear()
{
display = "";
}
}
}
<file_sep>/Best/Best/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using Best.Properties;
namespace Best
{
public partial class Form1 : Form
{
Class1 c = new Class1();
delegate void textUpdate(string txt);
public Form1()
{
InitializeComponent();
c.DataReceived += new dataReceived(_workingObject_DataReceived);
}
private void Form1_Load(object sender, EventArgs e)
{
Accept_data();
c.Show_Ports();
cBoxPortSelect.Items.AddRange(c.Ports_incbox);
//cBoxbaudrate.Text = Setting.baundrate;
cBoxPortSelect.Text = Settings.Default["Comport"].ToString();
cBoxbaudrate.Text = Settings.Default["Boudrate"].ToString();
cBoxdatabits.Text = Settings.Default["Databit"].ToString();
cBoxstopbits.Text = Settings.Default["Stopbit"].ToString();
cBoxparitybits.Text = Settings.Default["Paritybit"].ToString();
}
public void Accept_data()
{
c.Port=cBoxPortSelect.Text;
c.data_to_send = tBoxgo.Text;
c.data_to_reciev = tBoxreciev.Text;
c.ChatWindow = tBoxreciev;
//Console.WriteLine(c.data_to_send);
//Console.WriteLine(c.data_to_reciev);
}
private void SendMessage_Click(object sender, EventArgs e)
{
Accept_data();
c.Gone();
//tBoxreciev.Text = c.displayed.ToString();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
Accept_data();
c.OpenConnection();
progressBar.Value = 100;
}
void _workingObject_DataReceived(object sender, SerialPortEventArgs arg)
{
//tBoxreciev.Text += arg.ReceivedData;
updateUi(arg.ReceivedData);
}
private void updateUi(string msg)
{
this.Invoke(new EventHandler(delegate
{
tBoxreciev.AppendText(msg);
}));
}
//private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
//{
// //c.Recieved();
// // c.data_to_reciev();
// //Accept_data();
// // c.data_to_reciev = serialPort1.ReadExisting();
// c.data_to_reciev = serialPort1.ReadExisting();
// Invoke(new EventHandler(ShowData));
//}
//private void ShowData(object sender, EventArgs e)
//{
// //class1.ShowD();
// // if (toolStripComboBox1.Text == "Always Update")
// // if (cBoxalwaysupdate.Checked)
// //{
// tBoxreciev.Text = c.data_to_reciev;
// //}
// //else if (toolStripComboBox1.Text == "Add to old data")
// //{
// // else if (cBoxaddtoolddata.Checked)
// // tBoxrecievecontrol.Text += class1.dataIN;
// // tBoxrecievecontrol.Text = tBoxrecievecontrol.Text.Insert(0, tBoxrecievecontrol);
// //}
//}
private void comControlToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
c.CloseConnection();
progressBar.Value = 0;
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
c.Clear();
tBoxgo.Text = c.displayed.ToString();
}
private void clearToolStripMenuItem1_Click(object sender, EventArgs e)
{
c.Clear();
tBoxreciev.Text = c.displayed.ToString();
}
private void cBoxrtsenable_CheckedChanged(object sender, EventArgs e)
{
}
private void settingToolStripMenuItem_Click(object sender, EventArgs e)
{
Setting goto_setting = new Setting();
//this.Hide();
goto_setting.Show();
}
private void toolStripComboBox1_Click(object sender, EventArgs e)
{
c.toolStripComboBox1 = toolStripComboBox1.Text;
}
private void toolStripComboBox2_Click(object sender, EventArgs e)
{
c.toolStripComboBox2 = toolStripComboBox2.Text;
}
private void existToolStripMenuItem_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>/Best/Best/Setting.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Best.Properties;
namespace Best
{
public partial class Setting : Form
{
public static string baundrate;
public Setting()
{
InitializeComponent();
}
private void Setting_Load(object sender, EventArgs e)
{
}
private void Save_Setting_Click(object sender, EventArgs e)
{
//Settings.Default["Comport"] = cBoxPortSelect.Text;
//Settings.Default["Boudrate"] = cBoxbaudrate.Text;
//Settings.Default["Databit"] = cBoxdatabits.Text;
//Settings.Default["Stopbit"] = cBoxstopbits.Text;
//Settings.Default["Paritybit"] = cBoxparitybits.Text;
Properties.Settings.Default.Comport = cBoxPortSelect.Text;
Properties.Settings.Default.Boudrate = cBoxbaudrate.Text;
Properties.Settings.Default.Databit = cBoxdatabits.Text;
Properties.Settings.Default.Stopbit = cBoxstopbits.Text;
Properties.Settings.Default.Paritybit = cBoxparitybits.Text;
Settings.Default.Save();
MessageBox.Show("Saved");
this.Close();
//Form1 datapass = new Form1();
//datapass.ShowDialog();
}
}
}
|
40a4bc6b80f4c8221ca45244668edcb99d9247cb
|
[
"C#"
] | 3
|
C#
|
tesfay-bsrat/OOP-project
|
7974d632c4f65b2e1ad8917d00a427133041fe07
|
f0841df1327847f4e088c983ff304ed81aca4cf2
|
refs/heads/master
|
<repo_name>Ghostman100/predictionsBot<file_sep>/filename.js
<script>
document.addEventListener("DOMContentLoaded", function(){
var clickId = location.href.split("?clickid=")
var link = "http://172.16.31.10/click.php?cnv_id=#s2#&payout=#price#"
var s = link.replace("#s2#", clickId[1]).replace("#price#", 1);
var i = new Image();
i.src = s;
});
</script><file_sep>/db/migrate/20190624094925_create_payments.rb
class CreatePayments < ActiveRecord::Migration[5.2]
def change
create_table :payments do |t|
t.references :users
t.datetime :payed_at
t.timestamp
end
end
end
<file_sep>/config/initializers/bot_initializers.rb
Telegram.bots_config = {
default: '708079498:AAFjsD7bNEJFOgUo9iw9K39bEJhZCe9LYt0'
}
<file_sep>/lib/auto_require/prediction.rb
class Prediction
# @@status = 'off'
@@games = []
def self.get
a = RestClient.get 'http://tds-vk-1.ru/betting_games/predictions?bankroll=2000&betting_site=ws_gg11_bet'
JSON.parse(a.body).each do |pr|
unless @@games.include?(pr['id'])
Telegram.bot.send_message(chat_id: -1001459280119,
text: "В матче #{pr['radiant_team_name']} - #{pr['dire_team_name']}\n#{pr['map']} #{pr['team']}\n#{pr['bet']}")
@@games.push(pr['id'])
end
end
end
def self.result(games, messages)
r = RestClient.get 'http://tds-vk-1.ru/bets/details.json'
bets = JSON.parse(r.body)
games.each do |id|
bets.each do |bet|
if bet['raw_data']['status'] == 'success'
p bet['bet']['is_winning_bet']
if bet['id'] == id
if bet['bet']['is_winning_bet'] == true
ws = Webshot::Screenshot.instance
ws.capture "http://192.168.3.11:3000/image?value=#{bet['bet']['amount'].to_i}&bet=#{bet['bet']['coef']}&1st_team=#{bet['raw_data']['radiant_team_name']}&2nd_team=#{bet['raw_data']['dire_team_name']}&winner=#{bet['bet']['team']}&map=#{bet['raw_data']['map'][-1]}&time=#{bet['bet']['created_at']}", "image.png", width: 1024, height: 350
photo = File.new("image.png", 'r')
Telegram.bot.request(:forwardMessage, chat_id: -1001277836279, from_chat_id: -1001396010827, message_id: messages[id])
Telegram.bot.request :sendPhoto, chat_id: -1001277836279,
caption: "Мы поставили #{bet['bet']['amount'].to_i} и выиграли #{(bet['bet']['amount'].to_i * bet['bet']['coef']).round(2)}",
photo: photo,
reply_markup: {
inline_keyboard: [[{text: "Подпишись", url: "tg://resolve?domain=bet_predictions_bot"}]]
}
photo.close
messages.delete(id)
games.delete(id)
p "true"
elsif bet['bet']['is_winning_bet'] == nil
else
messages.delete(id)
games.delete(id)
p "false"
p bet['bet']['is_winning_bet']
end
break
end
end
end
end
return games, messages
end
end
<file_sep>/app/controllers/pay_controller.rb
class PayController < ApplicationController
def index
sleep(2)
id = Payment.last.user.user_id
redirect_to "https://money.yandex.ru/quickpay/shop-widget?writer=seller&targets=#{id}dota2_odds&targets-hint=&default-sum=3000&button-text=11&hint=&successURL=&quickpay=shop&account=4100136132008"
end
end
<file_sep>/lib/tasks/push.rake
task push: :environment do
games = []
messages = {}
while (true)
begin
# a = RestClient.get 'http://tds-vk-1.ru/betting_games/predictions?bankroll=2000&betting_site=ws_gg11_bet'
# b = JSON.parse(a.body)
r = RestClient.get 'http://tds-vk-1.ru/bets/details.json'
bets = JSON.parse(r.body)
bets.each do |pr|
if pr['bet'] && pr['bet']['is_winning_bet'] == nil
unless games.include?(pr['id'])
m = Telegram.bot.send_message(chat_id: -1001396010827,
text: "В матче #{pr['raw_data']['radiant_team_name']} - #{pr['raw_data']['dire_team_name']}\n#{pr['raw_data']['map']} #{pr['bet']['team']}\n#{pr['bet']['coef']}")
messages[pr['id']] = m['result']['message_id']
games.push(pr['id'])
end
end
end
games, messages = Prediction.result(games, messages)
p games
rescue
p "Ошибка #{$!.inspect}"
end
sleep(10)
end
end<file_sep>/app/controllers/telegram/webhooks_controller.rb
class Telegram::WebhooksController < Telegram::Bot::UpdatesController
# include Telegram::Bot::UpdatesController::MessageContext
def callback_query(data)
unless user = User.find_by(user_id: from['id'])
user = User.create(first_name: from['first_name'], last_name: from['last_name'], username: from['username'], user_id: from['id'])
end
user.payments.create()
end
def start!(*)
respond_with :message, text: "Привет"
message
# Telegram.bot.send_message(chat_id: -274859994, text: "test")
end
def message(*)
respond_with :message, text: "Привет, что бы купить подписку - перейди по ссылке.", reply_markup: {
inline_keyboard: [[{text: "Подпишись", callback_data: "test", url: "https://money.yandex.ru/quickpay/shop-widget?writer=seller&targets=#{from['id']}dota2_odds&targets-hint=&default-sum=3000&button-text=11&hint=&successURL=&quickpay=shop&account=4100136132008"}]]
}
end
def test!(*)
respond_with :message, text: "test",
reply_markup: {
inline_keyboard: [[{text: "test", callback_data: "test", url: "0.0.0.0:3000/pay"}]]
}
end
def start_predictions(*)
games = []
end
end<file_sep>/app/controllers/images_controller.rb
class ImagesController < ApplicationController
def index
o = [('a'..'z'), ('A'..'Z'), (0..9)].map(&:to_a).flatten
@id = (0...11).map { o[rand(o.length)] }.join
@time = params[:time].to_time
end
end
|
7e67a1dc58ac0d934e790b3034d9199050ef625b
|
[
"JavaScript",
"Ruby"
] | 8
|
JavaScript
|
Ghostman100/predictionsBot
|
fd96320313cb0949868962596b6c8d6c73295af5
|
eddc7409e6d60092a088c443ef6eedcb9c297e32
|
refs/heads/master
|
<file_sep>import csv
import os
csvpath = os.path.join('C:/Users/rajka/Desktop/UofT/Assignments/Instructions/PyPoll/Resources/election_data.csv')
with open(csvpath,newline='') as csvfile:
csvreader = csv.reader(csvfile,delimiter=',')
csvheader = next(csvreader)
listcsv = list(csvreader)
unique_candidates = []
khan_votes = 0
correy_votes = 0
li_votes = 0
otooley_votes = 0
votes = []
for row in listcsv:
if row[2] not in unique_candidates:
unique_candidates.append(row[2])
if row[2] == unique_candidates[0]:
khan_votes += 1
votes.append(row[2])
elif row[2] == unique_candidates[1]:
correy_votes += 1
votes.append(row[2])
elif row[2] == unique_candidates[2]:
li_votes += 1
votes.append(row[2])
else:
otooley_votes += 1
votes.append(row[2])
if max(khan_votes,correy_votes,li_votes,otooley_votes) == votes.count('Khan'):
winner = "Khan"
elif max(khan_votes,correy_votes,li_votes,otooley_votes) == votes.count('Correy'):
winner = "Correy"
elif max(khan_votes,correy_votes,li_votes,otooley_votes) == votes.count('li'):
winner = "Li"
else:
winner = "O'Tooley"
print("Election Results")
print("--------------------------------")
print(f"Total Votes: {len(listcsv)}")
print("--------------------------------")
print(f"{unique_candidates[0]}: {round((khan_votes/len(listcsv)*100),3)}00% ({khan_votes})")
print(f"{unique_candidates[1]}: {round((correy_votes/len(listcsv)*100),3)}00% ({correy_votes})")
print(f"{unique_candidates[2]}: {round((li_votes/len(listcsv)*100),3)}00% ({li_votes})")
print(f"{unique_candidates[3]}: {round((otooley_votes/len(listcsv)*100),3)}00% ({otooley_votes})")
print("--------------------------------")
print(f"Winner: {winner}")
print("--------------------------------")
output_file = os.path.join('C:/Users/rajka/Desktop/UofT/Assignments/Instructions/PyPoll/Output/Election Results.txt')
with open(output_file,'w') as report:
report.write("Election Results\n")
report.write("------------------------------\n")
report.write(str(f"Total Votes: {len(listcsv)} \n"))
report.write("------------------------------\n")
report.write(str(f"{unique_candidates[0]}: {round((khan_votes/len(listcsv)*100),3)}00% ({khan_votes})\n"))
report.write(str(f"{unique_candidates[1]}: {round((correy_votes/len(listcsv)*100),3)}00% ({correy_votes})\n"))
report.write(str(f"{unique_candidates[2]}: {round((li_votes/len(listcsv)*100),3)}00% ({li_votes})\n"))
report.write(str(f"{unique_candidates[3]}: {round((otooley_votes/len(listcsv)*100),3)}00% ({otooley_votes})\n"))
report.write("------------------------------\n")
report.write(str(f"Winner: {winner}\n"))
report.write("------------------------------")<file_sep>import csv
import os
csvpath = os.path.join('C:/Users/rajka/Desktop/UofT/Assignments/Instructions/PyBank/Resources/budget_data.csv')
with open (csvpath,'r',newline='') as cvsfile:
csvreader = csv.reader(cvsfile,delimiter=',')
csvheader = next(csvreader)
listcsv = list(csvreader)
totalprofit = []
averagechange = 0.00
net_sum = 0
total_months = len(listcsv)
for row in listcsv:
net_sum = net_sum + int(row[1])
for i in range(len(listcsv)-1):
curline = int(listcsv[i][1])
nextline= int(listcsv[i+1][1])
totalprofit.append(nextline -curline)
averagechange = round(sum(totalprofit)/len(totalprofit),2)
print("Fianancial Analysis")
print("------------------------------")
print(f"Total Months: {total_months}")
print(f"Total: ${net_sum}")
print(f"Average Change: ${averagechange}")
print(f"Greatest Increase in Profits: {max(listcsv, key = lambda x: float(x[1]))[0]} (${max(totalprofit)})")
print(f"Greatest Decrease in Profits: {min(listcsv, key = lambda x: float(x[1]))[0]} (${min(totalprofit)})")
output_file = os.path.join('C:/Users/rajka/Desktop/UofT/Assignments/Instructions/PyBank/Output/Financial Analysis.txt')
with open(output_file,'w') as report:
report.write("Fianancial Report\n")
report.write("-----------------------------\n")
report.write(str(f"Total Months: {total_months}\n"))
report.write(str(f"Total: ${net_sum}\n"))
report.write(str(f"Average Change: ${averagechange}\n"))
report.write(str(f"Greatest Increase in Profits: {max(listcsv, key = lambda x: float(x[1]))[0]} (${max(totalprofit)})\n"))
report.write(str(f"Greatest Decrease in Profits: {min(listcsv, key = lambda x: float(x[1]))[0]} (${min(totalprofit)})\n"))
|
e5799f5ea2ed4dc80aaa746e125cc376b1af94aa
|
[
"Python"
] | 2
|
Python
|
rajkamal85/python-challenge
|
fad97a85bcd98ed9610c5ea65491f49b7f0dab0c
|
83e63e71afa0753758bee86e2354cc78ecabb488
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using Newtonsoft.Json;
namespace ubit.ipt.server
{
/// <summary>
/// Summary description for Marksheet
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Marksheet : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public string calculateMarksheet()
{
string subjectStr = HttpContext.Current.Request.Params["request"];
List<SubjectModel> subjects = JsonConvert.DeserializeObject<List<SubjectModel>>(subjectStr);
double totalMarks = 0;
double min = subjects[0].obtainedMarks;
string minSub = subjects[0].name;
double max = subjects[0].obtainedMarks;
string maxSub = subjects[0].name;
for (int i = 0; i < subjects.Count; i++)
{
totalMarks += subjects[i].obtainedMarks;
if (min > subjects[i].obtainedMarks)
{
min = subjects[i].obtainedMarks;
minSub = subjects[i].name;
}
if (max < subjects[i].obtainedMarks)
{
max = subjects[i].obtainedMarks;
maxSub = subjects[i].name;
}
}
double percent = (totalMarks / (subjects.Count * 100)) * 100;
MarksheetModel marksheetModel = new MarksheetModel();
marksheetModel.percentage = percent;
marksheetModel.minMarks = min;
marksheetModel.maxMarks = max;
marksheetModel.minSubjectMarks = minSub;
marksheetModel.maxSubjectMarks = maxSub;
string str = JsonConvert.SerializeObject(marksheetModel);
return str;
}
public class SubjectModel
{
public string name { get; set; }
public double obtainedMarks { get; set; }
}
public class MarksheetModel
{
public double percentage { get; set; }
public double minMarks { get; set; }
public double maxMarks { get; set; }
public string minSubjectMarks { get; set; }
public string maxSubjectMarks { get; set; }
}
}
}
|
16d32958de7a0436fcaffb5cfe4b34f6c4aa7171
|
[
"C#"
] | 1
|
C#
|
inam-22/INAM-IPT-ASSIGNMENT-2
|
b9cfe74251ee3d91aada08db4d1a749d2b6514d4
|
17407fd89211d1c2ab7850c828cc4cd35b66d3ce
|
refs/heads/master
|
<file_sep>sqlite3 data/ufo.db <<EOF
.mode tabs
.output data/sighting_types.tsv
select * from sighting_types;
.output data/states.tsv
select * from states;
.output data/cities.tsv
select cities.*, count(*) as sighting_count , cities.name||', '||states.name_abbreviation as city_name from cities join sightings on sightings.city_id = cities.id join states on cities.state_id = states.id group by cities.id;
.output data/airports.tsv
select * from airports;
.output data/military_bases.tsv
select * from military_bases;
.output data/weather_stations.tsv
select * from weather_stations;
.output data/city_dist.tsv
select cities.id, city_airport_dist.distance as airportDist, city_military_base_dist.distance as militaryDist, city_weather_station_dist.distance as weatherDist from cities left outer join city_airport_dist on cities.id = city_airport_dist.city_id left outer join city_military_base_dist on cities.id = city_military_base_dist.city_id left outer join city_weather_station_dist on cities.id = city_weather_station_dist.city_id;
.exit
EOF
<file_sep>import sqlite3
from lxml import etree
import re
conn = sqlite3.connect('data/ufo.db')
c = conn.cursor()
parser = etree.HTMLParser()
tree = etree.parse('data/geographical_center_of_state.html', parser)
location_re = re.compile("""(\d+(?:\.\d+)?)'(\d+(?:\.\d+)?)'([WE])\s+(\d+(?:\.\d+)?)'(\d+(?:\.\d+)?)'?([NS])?""")
def degrees_to_decimal(d, m, s, dir):
f = float(d) + float(m)/60. + float(s)/3600.
if dir in ['S', 'W']: f = -f
return f
trs = tree.xpath('//table/tbody/tr')
for tr in trs:
state, location, _ = tr.xpath('.//text()')
if state == 'State': continue
m = location_re.match(location)
lon = degrees_to_decimal(m.group(1), m.group(2), 0, m.group(3))
lat = degrees_to_decimal(m.group(4), m.group(5), 0, m.group(6))
print state, lon, lat
c.execute('update states set lat = ?, lon = ? where name = ?', (lat, lon, state.upper()))
conn.commit()<file_sep>import sqlite3
import csv
import re
import codecs
conn = sqlite3.connect('data/ufo.db')
c = conn.cursor()
with codecs.open("data/Gaz_counties_national.csv","r","latin-1") as f:
for idx, line in enumerate(f):
if idx == 0: continue
row = line.split('\t')
lat = float(row[8])
lon = float(row[9])
name = re.sub('\s+County','',row[3])
c.execute('select id from counties where name like ?', (name,))
id = c.fetchone()
if id:
c.execute('update counties set lat = ?, lon = ? where id = ?', (lat, lon, id[0]))
else:
print "not found:", name
conn.commit()<file_sep>{% extends "layout.html" %}
{% block content %}
<div id="content">
<div class="post">
<h2 class="title"><a href="#">Sources used</a></h2>
<p class="meta"><span class="date"></span> <span class="posted"><a href="#"></a></span></p>
<div style="clear: both;"> </div>
<div class="entry" style="color:white;">
<ul>
<li>
<a href="http://www.census.gov/geo/www/gazetteer/gazetteer2010.html">http://www.census.gov/geo/www/gazetteer/gazetteer2010.html</a>
<br /> Coordinates of places <small>(<a href="#csv_instructions">CSV Instructions</a>)</small>
</li>
<li>
<a href="http://www.nuforc.org/webreports/ndxloc.html">http://www.nuforc.org/webreports/ndxloc.html</a>
<br /> Detailed sigting information / accounts <small>(<a href="#scraping_instructions">Scraping Instructions</a>)</small>
</li>
<li>
<a href="http://factfinder2.census.gov">http://factfinder2.census.gov</a>
<br /> Population density by county <small>(<a href="#csv_instructions">CSV Instructions</a>)</small>
</li>
<li>
<a href="http://code.google.com/apis/maps/index.html">http://code.google.com/apis/maps/index.html</a>
<br /> Place coordinates and county lookup <small>(<a href="#api_instructions">API Instructions</a>)</small>
</li>
<li>
<a href="http://msdn.microsoft.com/en-us/library/dd877180.aspx">http://msdn.microsoft.com/en-us/library/dd877180.aspx</a>
<br /> Place coordinates and county lookup <small>(<a href="#api_instructions">API Instructions</a>)</small>
</li>
<li>
<a href="http://www.wunderground.com/history">http://www.wunderground.com/history</a>
<br /> Temperature and weather conditions <small>(<a href="#scraping_instructions">Scraping Instructions</a>)</small>
</li>
<li>
<a href="http://weather.noaa.gov">http://weather.noaa.gov</a>
<br /> Positions of weather stations <small>(<a href="#scraping_instructions">Scraping Instructions</a>)</small>
</li>
<li>
<a href="www.partow.net/miscellaneous/airportdatabase/">www.partow.net/miscellaneous/airportdatabase/</a>
<br /> Airports locations <small>(<a href="#csv_instructions">CSV Instructions</a>)</small>
</li>
<li>
<a href="http://militarybases.com/">http://militarybases.com/</a>
<br /> Military base locations <small>(<a href="#kml_instructions">KML Instructions</a>)</small>
</li>
</ul>
<!-- <p class="links"><a href="#" class="more">Read More</a><a href="#" title="b0x" class="comments">Comments</a></p> -->
<fieldset>
<legend><a name="csv_instructions">CSV instructions</a></legend>
<ol>
<li>Comma delimited data was downloaded manually</li>
<li>Data was processed via Ruby script using FasterCSV gem</li>
<li>Data was cleaned of spaces and extra dashes</li>
<li>Data was inserted into sqlite3 database with columns in CSV mapped to database columns accordingly</li>
</ol>
</fieldset>
<fieldset>
<legend><a name="api_instructions">API instructions</a></legend>
<ol>
<li>Using ruby net/http library, data was pulled via HTTP in XML form</li>
<li>Lat/Lon was extracted using Nokogiri library</li>
<li>Cleaned up of extra spaces / characters</li>
</ol>
</fieldset>
<fieldset>
<legend><a name="kml_instructions">KML instructions</a></legend>
<ol>
<li>Data was downloaded manually</li>
<li>Processed using ruby nokogiri XML library</li>
<li>Relation name, coordinates were extracted and inserted into the database</li>
</ol>
</fieldset>
<fieldset>
<legend><a name="scraping_instructions">Scraping Instructions</a></legend>
<ol>
<li>Specific target webpage was chosen manually as an entry point</li>
<li>Forms were anylized to get a page with proper links of all necessary information</li>
<li>Data was further processed to get rid of padded spacings and inserted into database</li>
</ol>
</fieldset>
</div>
</div>
</div>
{% endblock %}
<file_sep>import sqlite3
from math import *
def haversin(x):
return sin(x/2)**2
def geo_dist(lon1, lat1, lon2, lat2):
"""
in: coordinates in degrees
out: great circle distance in km
http://en.wikipedia.org/wiki/Haversine_formula
"""
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
h = haversin(lat2 - lat1) + cos(lat1) * cos(lat2) * haversin(lon2 - lon1)
R = 6371. # mean earth radius in km
return R * 2 * asin(sqrt(h))
conn = sqlite3.connect('data/ufo.db')
c = conn.cursor()
c2 = conn.cursor()
def make_table(placetype):
c.execute('CREATE TABLE city_%s_dist (city_id INTEGER, %s_id INTEGER, distance NUMERAL)' % (placetype,placetype))
c.execute('CREATE INDEX city_%s_dist_index_city_id on city_%s_dist(city_id)' % (placetype,placetype))
def load_distances(placetype):
places = []
c.execute('select id, lat, lon from ' + placetype + 's')
for id, lat, lon in c:
places.append((id,lat,lon))
c.execute('select id, lat, lon from cities')
for id, lat, lon in c:
if lat == None or lon == None: continue
min_d = 10000000
min_aid = None
for aid, alat, alon in places:
d = geo_dist(lon, lat, alon, alat)
if d < min_d:
min_d = d
min_aid = aid
c2.execute('insert into city_%s_dist (city_id, %s_id, distance) values (?, ?,?)'
% (placetype,placetype), (id, min_aid, min_d))
<file_sep>CREATE INDEX states_index_id ON states(id);
CREATE INDEX states_index_name_abbreviation ON states(name_abbreviation);
CREATE INDEX counties_index_id ON counties(id);
CREATE INDEX counties_index_state_id ON counties(state_id);
CREATE INDEX cities_index_id ON cities(id);
CREATE INDEX cities_index_state_id ON cities(state_id);
CREATE INDEX cities_index_county_id ON cities(county_id);
CREATE INDEX cities_index_lat_lon ON cities(lat, lon);
CREATE INDEX cities_index_name ON cities(name);
CREATE INDEX shapes_index_id ON shapes(id);
CREATE INDEX sightings_index_id ON sightings(id);
CREATE INDEX sightings_index_shape_id ON sightings(shape_id);
CREATE INDEX sightings_index_city_id ON sightings(city_id);
CREATE INDEX sightings_index_occurred_at ON sightings(occurred_at);
<file_sep>#!/usr/bin/env ruby
require 'rubygems'
require 'nokogiri'
require 'uri'
require 'net/http'
require 'chronic'
require "sqlite3"
require 'progressbar'
require 'fastercsv'
require 'date'
#TODO add method that will write the data into flat file OR database
module Scraper
#Downloads data and parses it into three buckets seasons, episodes, and phrases
DUMP_FILE_NAME = "scraped_rb_dump.bin".freeze
SITE_DIRECTORY = "/webreports".freeze
BANNED_LOCATIONS = ["UNSPECIFIED/INTERNATIONAL", "ALBERTA,CANADA", "BRITISH COLUMBIA,CAN", "MANITOBA,CANADA", "NEW BRUNSWICK,CAN",
"NEWFOUNDLAND,CAN", "NOVA SCOTIA,CAN", "ONTARIO,CAN", "PROV OF QUE,CAN", "SASKATCHEWAN,CAN"].freeze
def self.dump_file_path
File.join File.expand_path(File.dirname(__FILE__)), DUMP_FILE_NAME
end
def self.update_coordinates_counties_from_api
db = SQLite3::Database.new("ufo.db")
find_county = lambda do |county_name|
county_result = db.execute("SELECT id FROM counties WHERE name like ? ", county_name)
unless county_result.empty?
county_id = county_result.first.first
else
nil
end
end
#http://dev.virtualearth.net/REST/v1/Locations/Skokie,IL?o=xml&key=<KEY>
#url = URI.encode("http://maps.googleapis.com/maps/api/geocode/xml?address=#{row[2].gsub(/(\(.*?\))/, '')}, #{row[1]}&sensor=false")
db.execute("SELECT c.id, s.name_abbreviation, c.name, s.id FROM cities c JOIN states s ON c.state_id = s.id WHERE lat is null or lon is null or c.county_id is null").each do |row|
url = URI.encode("http://maps.googleapis.com/maps/api/geocode/xml?address=#{row[2].gsub(/(\(.*?\))/, '')},#{row[1]}&sensor=false")
#url = URI.encode("http://dev.virtualearth.net/REST/v1/Locations/#{row[2].gsub(/(\(.*?\))/, '')},#{row[1]}?o=xml&key=<KEY>")
html = Nokogiri.HTML(open(url))
lat_doc, lon_doc, county_doc = nil, nil, nil
if url.include? "google"
lat_doc = html.xpath("//geometry/location/lat").first
lon_doc = html.xpath("//geometry/location/lng").first
county_doc = html.xpath("//address_component[type='administrative_area_level_2']/long_name").first
else
lat_doc = html.xpath("//location/point/latitude").first
lon_doc = html.xpath("//location/point/longitude").first
county_doc = html.xpath("//address_co/admindistrict2").first
end
if lat_doc and lon_doc
lat = lat_doc.content
lon = lon_doc.content
county_id = nil
if county_doc
county = county_doc.content
county.gsub!("Co.", '')
county.strip!
county_id = find_county.call(county)
unless county_id
db.execute("INSERT INTO counties (name, state_id) VALUES ( ?, ? )", county, row[3])
county_id = find_county.call(county)
end
end
db.execute("UPDATE cities SET lat = ?, lon = ?, county_id = ? WHERE id = ? ", lat, lon, county_id, row[0])
else
puts html.content
end
end
end
def self.update_city_coordinates
i = 0
db = SQLite3::Database.new('ufo.db')
FasterCSV.foreach(File.join(File.expand_path(File.dirname(__FILE__)), "../data", "Gaz_places_national.csv"), :col_sep => "\t") do |line|
if i > 0
rows = db.execute("SELECT c.id FROM cities c JOIN states s ON s.id = c.state_id WHERE c.name like ? AND s.name_abbreviation like ? ",
"%#{line[3].gsub(/(CDP|city|town)/, '').strip}%", "%#{line[0]}%")
if rows.one?
db.execute("UPDATE cities SET lat = ?, lon = ? WHERE id = ?", line[8].to_f, line[9].to_f, rows.first.first)
end
end
i+=1
end
end
def self.open(url_string, j=0)
url = URI.parse(url_string)
#host_rel_path = "#{url.scheme}://#{url.host + SITE_DIRECTORY}"
request = Net::HTTP.new(url.host, url.port)
request.read_timeout = 60
try = 0
response = nil
begin
response = request.get(url.request_uri)
loc = response['location']
raise "Too many redirects" if j > 2
if loc and url_string.include? "findweather/getForecast?"
puts "ABOUT..."
x = open("#{url.scheme}://" + url.host + loc + "&format=xml", j+=1)
return x
else
response = response.body
end
rescue Exception => e
try+=1
if try < 10
retry
end
puts "FAILED TO OPEN: " + url_string.to_s
puts e
end
response
end
def self.scrape
year_2000 = Time.mktime(2000)
host_rel_path = "http://www.nuforc.org#{SITE_DIRECTORY}"
#Represent tables
states = []
sightings = []
rows = Nokogiri::HTML(open(host_rel_path + "/ndxloc.html")).xpath("//table/tbody/tr/td[1]//a")
pbar = ProgressBar.new("Loading...", rows.length - BANNED_LOCATIONS.length)
rows.each_with_index do |sighting_link_html, i|
state = {}
state[:sightings_url] = "#{host_rel_path}/#{sighting_link_html["href"]}"
state[:name] = sighting_link_html.content
next if BANNED_LOCATIONS.include? state[:name]
pbar.inc
states << state
html = open(state[:sightings_url])
next unless html
Nokogiri::HTML(html).xpath("//table/tbody/tr").each do |sighting_html|
sighting = {}
columns = sighting_html.xpath "td"
#ONLY 2 rows out of the whole set have these problems, really broken HTML in summary, lets ignore these records
if columns.length == 7
sighting[:occurred_at] = columns[0].content.strip_html.strip
if sighting[:occurred_at] and !sighting[:occurred_at].empty? and sighting[:occurred_at].to_date < year_2000
break
end
sighting[:city] = columns[1].content.strip_html.strip.downcase.capitalize
sighting[:state] = columns[2].content.strip_html.strip.upcase
state[:name_abbreviation] ||= sighting[:state].strip.upcase
sighting[:shape] = columns[3].content.strip_html.strip.downcase.capitalize
sighting[:duration] = columns[4].content.strip_html.strip
sighting[:summary_description] = columns[5].content.strip_html.strip
sighting[:posted_at] = columns[6].content.strip_html.strip
sighting[:sighting_detail_url] = "#{host_rel_path}/#{columns.first.xpath(".//a").first["href"]}"
else
sighting[:broken] = sighting_html.content.strip
end
sightings << sighting
if sighting[:sighting_detail_url]
html = open(sighting[:sighting_detail_url])
next unless html
details_html = Nokogiri::HTML(html).xpath "//table/tbody/tr/td"
if details_html.length > 1
reported_at = details_html.first.content.to_s.strip_html.scan /Reported:\s(.*?)\s.*[PAM]{2}\s(\d{1,2}:\d{1,2})/
if reported_at.one?
sighting[:reported_at] = reported_at.first.map(&:strip).join(" ").strip
end
full_description = details_html.last.content.strip_html.strip
unless full_description.empty?
sighting[:full_description] = full_description.strip
end
end
end
end
end
pbar.finish
result = {:states => states, :sightings => sightings}
cached_result = Marshal.dump result
file_path = self.dump_file_path
f = File.new file_path, "w"
f.write cached_result
f.close
result
end
def self.createdb
raise "#{DUMP_FILE_NAME} not found" unless File.exists? self.dump_file_path
result = Marshal.load IO.read(self.dump_file_path)
result[:sightings].delete_if{|sighting| !sighting[:broken].nil? }
db = SQLite3::Database.new('ufo.db')
db.transaction do
create_query = %{
DROP INDEX IF EXISTS states_index_id;
DROP INDEX IF EXISTS states_index_name_abbreviation;
DROP INDEX IF EXISTS states_index_lat_lon;
DROP INDEX IF EXISTS counties_index_id;
DROP INDEX IF EXISTS counties_index_state_id;
DROP INDEX IF EXISTS counties_index_name_state_id;
DROP INDEX IF EXISTS counties_index_lat_lon;
DROP INDEX IF EXISTS cities_index_id;
DROP INDEX IF EXISTS cities_index_state_id;
DROP INDEX IF EXISTS cities_index_county_id;
DROP INDEX IF EXISTS cities_index_lat_lon;
DROP INDEX IF EXISTS cities_index_name_state_id;
DROP INDEX IF EXISTS shapes_index_id;
DROP INDEX IF EXISTS sightings_index_id;
DROP INDEX IF EXISTS sightings_index_shape_id;
DROP INDEX IF EXISTS sightings_index_city_id;
DROP INDEX IF EXISTS sightings_index_occurred_at;
DROP INDEX IF EXISTS airports_index_id;
DROP INDEX IF EXISTS airports_index_lat_lon;
DROP INDEX IF EXISTS military_bases_id;
DROP INDEX IF EXISTS military_bases_lat_lon;
DROP INDEX IF EXISTS city_proximities_city_id_relation_id_relation;
DROP INDEX IF EXISTS city_proximities_distance;
DROP INDEX IF EXISTS weather_stations_index_id;
DROP INDEX IF EXISTS weather_stations_index_lat_lon;
DROP TABLE IF EXISTS states;
CREATE TABLE states (
id INTEGER PRIMARY KEY,
name_abbreviation STRING,
name STRING,
lat REAL,
lon REAL
);
DROP TABLE IF EXISTS counties;
CREATE TABLE counties (
id INTEGER PRIMARY KEY,
state_id INTEGER,
name STRING,
population_density INTEGER,
lat REAL,
lon REAL
);
DROP TABLE IF EXISTS city_proximities;
CREATE TABLE city_proximities (
city_id INTEGER,
distance REAL,
relation_id INTEGER,
relation STRING
);
DROP TABLE IF EXISTS cities;
CREATE TABLE cities (
id INTEGER PRIMARY KEY,
county_id integer,
state_id integer,
name STRING,
lat REAL,
lon REAL
);
DROP TABLE IF EXISTS sighting_types;
CREATE TABLE sighting_types (
id INTEGER PRIMARY KEY,
name STRING,
img_name STRING,
color STRING
);
DROP TABLE IF EXISTS shapes;
CREATE TABLE shapes (
id INTEGER PRIMARY KEY,
name STRING,
sighting_type_id INTEGER
);
DROP TABLE IF EXISTS sightings;
CREATE TABLE sightings (
id INTEGER PRIMARY KEY,
city_id INTEGER,
shape_id INTEGER,
summary_description STRING,
full_description STRING,
occurred_at TIMESTAMP,
reported_at TIMESTAMP,
posted_at TIMESTAMP,
temperature INTEGER,
weather_conditions STRING
);
DROP TABLE IF EXISTS airports;
CREATE TABLE airports(
ID INTEGER PRIMARY KEY,
name STRING,
city STRING,
lat REAL,
lon REAL);
DROP TABLE IF EXISTS military_bases;
CREATE TABLE military_bases(
ID INTEGER PRIMARY KEY,
name STRING,
lat REAL,
lon REAL
);
DROP TABLE IF EXISTS weather_stations;
CREATE TABLE weather_stations(
id INTEGER PRIMARY KEY,
name STRING,
key STRING,
state_id INTEGER,
lat REAL,
lon REAL
);
}
db.execute_batch create_query
# feeding data to database
puts "Inserting states"
result[:states].each do |state|
db.execute "INSERT INTO states (name, name_abbreviation) VALUES (?,?)", state[:name], state[:name_abbreviation]
end
#TODO find county for each city, insert conties into table, and map cities to counties
puts "Inserting cities"
result[:sightings].map{|sighting| [sighting[:city], sighting[:state]] }.uniq.each do |city_state|
db.execute "INSERT INTO cities (name, state_id) VALUES (?, (SELECT id FROM states WHERE name_abbreviation LIKE ?))", city_state.first, city_state.last
end
puts "Inserting shapes"
result[:sightings].map{|sighting| sighting[:shape] }.uniq.each do |shape|
db.execute "INSERT INTO shapes (name) VALUES (?)", shape
end
puts "Inserting sightings"
result[:sightings].each do |sighting|
db.execute "INSERT INTO sightings (city_id, shape_id, summary_description, full_description, occurred_at, reported_at, posted_at)
VALUES((SELECT id FROM cities WHERE name LIKE ?), (SELECT id FROM shapes WHERE name LIKE ?), ?, ?, ?, ?, ?)",
sighting[:city], sighting[:shape], sighting[:summary_description], sighting[:full_description],
sighting[:occurred_at].to_date(:db),
sighting[:reported_at] ? sighting[:reported_at].to_date(:db) : nil,
sighting[:posted_at].to_date(:db)
end
puts "Building indexes"
db.execute "CREATE INDEX states_index_id ON states(id);"
db.execute "CREATE UNIQUE INDEX states_index_name_abbreviation ON states(name_abbreviation);"
db.execute "CREATE UNIQUE INDEX states_index_lat_lon ON states(lat,lon);"
db.execute "CREATE INDEX counties_index_id ON counties(id);"
db.execute "CREATE INDEX counties_index_state_id ON counties(state_id);"
db.execute "CREATE UNIQUE INDEX counties_index_name_state_id ON counties(name, state_id);"
db.execute "CREATE INDEX counties_index_lat_lon ON counties(lat, lon)"
db.execute "CREATE INDEX cities_index_id ON cities(id);"
db.execute "CREATE INDEX cities_index_state_id ON cities(state_id);"
db.execute "CREATE INDEX cities_index_county_id ON cities(county_id);"
db.execute "CREATE INDEX cities_index_lat_lon ON cities(lat, lon);"
db.execute "CREATE UNIQUE INDEX cities_index_name_state_id ON cities(name, state_id);"
db.execute "CREATE INDEX shapes_index_id ON shapes(id)"
db.execute "CREATE INDEX sightings_index_id ON sightings(id)"
db.execute "CREATE INDEX sightings_index_shape_id ON sightings(shape_id)"
db.execute "CREATE INDEX sightings_index_city_id ON sightings(city_id)"
db.execute "CREATE INDEX sightings_index_occurred_at ON sightings(occurred_at);"
db.execute "CREATE INDEX airports_index_id ON airports(id)"
db.execute "CREATE INDEX airports_index_lat_lon ON airports(lat, lon)"
db.execute "CREATE INDEX military_bases_id ON military_bases(id)"
db.execute "CREATE INDEX military_bases_lat_lon ON military_bases(lat, lon)"
db.execute "CREATE INDEX city_proximities_city_id_relation_id_relation ON city_proximities(city_id, relation_id, relation)"
db.execute "CREATE INDEX city_proximities_distance ON city_proximities(distance)"
db.execute "CREATE INDEX weather_stations_index_id ON weather_stations(id)"
db.execute "CREATE INDEX weather_stations_index_lat_lon ON weather_stations(lat, lon)"
end
end
def self.calculate_distances
db = SQLite3::Database.new('ufo.db')
db.execute("DELETE FROM city_proximities")
relations = {}
%w(airports military_bases weather_stations).each do |relation|
relations[relation] = db.execute("SELECT id, lat, lon FROM #{relation} WHERE lat IS NOT NULL AND lon IS NOT NULL")
end
db.transaction do
db.execute("SELECT id, lat, lon FROM cities WHERE lat IS NOT NULL AND lon IS NOT NULL").each do |city|
relations.each do |relation, rows|
smallest_distance_query = nil
rows.each do |other|
d = distance(city[1].to_f, city[2].to_f, other[1].to_f, other[2].to_f)
#puts "#{city[0]}" #, #{other[0]}, #{relation}, #{d}"
query = ["INSERT INTO city_proximities (city_id, relation_id, relation, distance) VALUES (?, ?, ?, ?)",
city[0], other[0], relation, d]
if smallest_distance_query.nil? or smallest_distance_query.last > d
smallest_distance_query = query
end
end
if smallest_distance_query
db.execute(*smallest_distance_query)
end
end
end
end
end
def self.add_population_density
db = SQLite3::Database.new('ufo.db')
file_path = File.join(File.expand_path(File.dirname(__FILE__)), "../data", "population_density_by_county.csv")
FasterCSV.foreach(file_path, :headers => true) do |line|
puts "updating..."
db.execute("UPDATE counties SET population_density = ? WHERE id IN (SELECT c.id FROM counties c JOIN states s ON s.id = c.state_id WHERE c.name like ? AND s.name like ?)", line[6].to_f * 100 , line[5].gsub(/County.*/i, '').strip, line[2].strip)
end
end
def self.clear_banned_data
#UNSAFE, SQL INJECTIONS CAN BE DONE HERE!
db = SQLite3::Database.new('ufo.db')
db.transaction do
result = db.execute("SELECT s.id, c.id, si.id FROM states s JOIN cities c ON s.id = c.state_id JOIN sightings si ON si.city_id = c.id WHERE s.name IN ('#{ BANNED_LOCATIONS.join("', '") }')")
db.execute("DELETE FROM sightings WHERE id in (#{result.map{|m| m[2].to_i}.join(", ")})")
db.execute("DELETE FROM cities WHERE id in (#{result.map{|m| m[1].to_i}.join(", ")})")
db.execute("DELETE FROM states WHERE id in (#{result.map{|m| m[0].to_i}.join(", ")})")
end
end
def self.group_shapes
db = SQLite3::Database.new('ufo.db')
db.transaction do
query = %{
DELETE FROM sighting_types;
INSERT INTO sighting_types(name, img_name, color) VALUES('polygon', 'blue.png', '0000FF');
INSERT INTO sighting_types(name, img_name, color) VALUES('changing', 'red.png', 'FF0000');
INSERT INTO sighting_types(name, img_name, color) VALUES('unknown', 'green.png', '00FF00');
INSERT INTO sighting_types(name, img_name, color) VALUES('other', 'yellow.png', 'FFFF00');
INSERT INTO sighting_types(name, img_name, color) VALUES('round', 'orange.png', 'FF8000');
INSERT INTO sighting_types(name, img_name, color) VALUES('triangle', 'purple.png', '8000FF');
INSERT INTO sighting_types(name, img_name, color) VALUES('light', 'star.png', '00FFFF');
UPDATE shapes SET type_id = (SELECT id FROM sighting_types WHERE name like 'polygon')
WHERE name IN ('Rectangle', 'Diamond', 'Chevron');
UPDATE shapes SET type_id = (SELECT id FROM sighting_types WHERE name like 'changing')
WHERE name IN ('Changing');
UPDATE shapes SET type_id = (SELECT id FROM sighting_types WHERE name like 'unknown')
WHERE name IN ('Unknown', 'Other');
UPDATE shapes SET type_id = (SELECT id FROM sighting_types WHERE name like 'other')
WHERE name IN ('Teardrop', 'Cigar', 'Cylinder', 'Crescent');
UPDATE shapes SET type_id = (SELECT id FROM sighting_types WHERE name like 'round')
WHERE name IN ('Circle', 'Sphere', 'Oval', 'Egg', 'Disk');
UPDATE shapes SET type_id = (SELECT id FROM sighting_types WHERE name like 'triangle')
WHERE name IN ('Triangle', 'Cone');
UPDATE shapes SET type_id = (SELECT id FROM sighting_types WHERE name like 'light')
WHERE name IN ('Light', 'Fireball', 'Flash');
}
=begin
query = %{
UPDATE shapes SET group_reference=1, group_name='Polygon' WHERE name IN ('Rectangle','Hexagon','Diamond','Chevron');
UPDATE shapes SET group_reference=2, group_name='Variable' WHERE name IN ('changed','Changing','Unknown');
UPDATE shapes SET group_reference=3, group_name='Oval' WHERE name IN ('Crescent','Cylinder','Other','Teardrop','Cross','Cigar','Formation');
UPDATE shapes SET group_reference=4, group_name='Sphere' WHERE name in ('Disk','Round','Circle','Dome','Sphere','Egg','Oval');
UPDATE shapes SET group_reference=5, group_name='Cube' WHERE name in ('Delta','Triangle','pyramid','Cone');
UPDATE shapes SET group_reference=6, group_name='Flash' WHERE name in ('Flare','Light','Flash','Fireball');
}
=end
db.execute_batch query
end
end
def self.insert_airports
data = File.new(File.join("../", "data", "GlobalAirportDatabase.txt"))
db = SQLite3::Database.new('ufo.db')
db.transaction do
db.execute("DELETE FROM airports")
while line = data.gets do
columns = line.split(":")
if columns[4] == "USA"
lat = degrees_to_decimal(columns[5].to_f, columns[6].to_f, columns[7].to_f, columns[8])
lon = degrees_to_decimal(columns[9].to_f, columns[10].to_f, columns[11].to_f, columns[12])
db.execute("INSERT INTO airports(name,city,lat,lon) VALUES(?, ?, ?, ?)", columns[0], columns[2], lat, lon)
end
end
end
end
def self.add_weather_conditions
j = 0
db = SQLite3::Database.new('ufo.db')
db.execute('SELECT states.name_abbreviation, c.name, s.occurred_at, s.id AS sighting_id FROM sightings s JOIN cities c ON c.id = s.city_id JOIN states ON states.id = c.state_id WHERE temperature IS NULL or weather_conditions IS NULL').each do |sighting|
state = sighting[0]
#break if (j+=1) > 10
city = sighting[1]
puts sighting[2]
occurred_at = DateTime.parse sighting[2]
url = "http://www.wunderground.com/cgi-bin/findweather/getForecast?airportorwmo=query&historytype=DailyHistory&backurl=%2Fhistory%2Findex.html&code=#{URI.encode(city)}%2C+#{URI.encode(state)}&month=#{occurred_at.month}&day=#{occurred_at.day}&year=#{occurred_at.year}"
result = open(url)
if result and result.is_a? String
result = result.split "\n"
if result.length < 500
#find proper row
result.each_with_index do |row, i|
next if i < 2
fields = row.strip_html.split(",")
next if fields.empty?
next if fields[0].include? "No daily or hourly history data available"
day_time = DateTime.parse(fields[0])
#Get proper time
event = Time.mktime(occurred_at.year, occurred_at.month, occurred_at.day, day_time.strftime("%H"), day_time.strftime("%M")).to_datetime
if result.length == i + 1 or occurred_at < event
temperature = fields[1].to_f.round
condition = fields[11]
puts "temperature: #{temperature} condition: #{condition} #{i}/#{result.length}"
db.execute("UPDATE sightings SET temperature = ?, weather_conditions = ? WHERE id = ?", temperature, condition, sighting[3])
break
end
end
else
puts "Error took place with url: #{url}"
end
end
end
end
def self.insert_military_bases
data = IO.read(File.join("../", "data", "world_military_bases.kml"))
db = SQLite3::Database.new('ufo.db')
xml_doc = Nokogiri.XML(data)
db.transaction do
db.execute "DELETE FROM military_bases"
xml_doc.xpath("//xmlns:Placemark").each do |place_mark|
name = place_mark.xpath("xmlns:name").first.content
lon, lat = *place_mark.xpath("xmlns:Point/xmlns:coordinates").first.content.split(",").map{|x| x.to_f}
#puts "#{name} lat #{lat} lon#{lon}"
db.execute("INSERT INTO military_bases (name, lat, lon) VALUES( ?, ?, ?)", name, lat, lon)
end
end
end
def self.import_geographical_centers_states
data = IO.read(File.join("../", "data", "geographical_center_of_state.html"))
db = SQLite3::Database.new('ufo.db')
Nokogiri::HTML(data).xpath("//table/tbody/tr").each_with_index do |row,i|
if i==0
next
end
columns = row.xpath("td")
state = columns[0].content.strip_html
result = db.execute("SELECT id FROM states WHERE name like ?", state)
raise "Error, state #{state} not found" if result.empty?
lat_lon_raw = columns[1].content.strip_html
lat_lon_raw = lat_lon_raw.scan(/(\d+\.*\d*)'(\d+\.*\d*)'?(\d+\.*\d*)?'?(\D)/)
#In 100ths
lat,lon = degrees_to_decimal(*lat_lon_raw[1]), degrees_to_decimal(*lat_lon_raw[0])
puts "lat:#{lat} lon:#{lon}"
db.execute("UPDATE states SET lat = ?, lon = ? WHERE id = ?", lat, lon, result.first.first)
end
nil
end
def self.import_geographical_centers_counties
db = SQLite3::Database.new('ufo.db')
FasterCSV.foreach(File.join(File.expand_path(File.dirname(__FILE__)), "../data", "Gaz_counties_national.csv"), :col_sep => "\t", :headers => true) do |row|
county_record = db.execute("SELECT id FROM counties WHERE name like ?", '%' + row[3].gsub(/\s*county/i, '') + '%')
if county_record.empty?
puts "Import error, county record #{row[3]} not found"
next
end
puts "lat: #{row[8]} lon: #{row[9]}"
db.execute("UPDATE counties SET lat = ?, lon = ? WHERE id = ?", row[8].to_f, row[9].to_f, county_record.first.first)
end
end
def self.insert_weather_stations
db = SQLite3::Database.new('ufo.db')
db.execute("DELETE FROM weather_stations")
db.transaction do
rows = Nokogiri::HTML(open("http://weather.noaa.gov/cgi-bin/nsd_country_lookup.pl?country=United%20States")).xpath("//ul/ul/a").each_with_index do |s,i|
data_table_rows = Nokogiri::HTML(open(s["href"])).xpath("//ul/table/tr")
name,key,state_abbriviation,lat,lon = nil,nil,nil,nil,nil
data_table_rows.each do |row|
td = row.xpath("td")
if td.first.content.include?("Station Position")
lat_lon_raw = td.last.content.strip_html.squeeze(" ").gsub(/\(.*?\).*/, '')
lat_lon_raw = lat_lon_raw.scan(/(\d+)-(\d+)-?(\d+)?(\D)/)
lat,lon = degrees_to_decimal(*lat_lon_raw[0]), degrees_to_decimal(*lat_lon_raw[1])
elsif td.first.content.include?("State")
state_abbriviation = td.last.content.strip_html
elsif td.first.content.include?("Station Name")
name = td.last.content.strip_html
elsif td.first.content.include?("ICAO Location Indicator")
key = td.last.content.strip_html
end
end
query = ["INSERT INTO weather_stations (name,key,state_id,lat,lon) VALUES (?,?,(SELECT id FROM states WHERE name_abbreviation like ?),?,?)", name,key,state_abbriviation,lat,lon]
db.execute *query
end
end
end
#ENTIRE PROCESS CAN TAKE UPTO 24H
def self.migrate
=begin
Scraper.scrape
Scraper.createdb
Scraper.update_coordinates_counties_from_api
Scraper.add_population_density
Scraper.group_shapes
Scraper.add_weather_conditions
Scraper.insert_weather_stations
=end
#puts "update_city_coordinates"
#Scraper.update_city_coordinates
puts "insert_airports"
Scraper.insert_airports
puts "insert_military_bases"
Scraper.insert_military_bases
puts "import_geographical_centers_states"
Scraper.import_geographical_centers_states
puts "import_geographical_centers_counties"
Scraper.import_geographical_centers_counties
puts "calculate_distances"
#Scraper.calculate_distances
end
end
#Extens string class to be able to get rid of any text that is within HTML elements
class String
def strip_html
self.gsub(/<script[^>]*>(.|\s)*?<\/script>/i, "").
gsub(/<style[^>]*>(.|\s)*?<\/style>/i, "").
gsub(/<!--(.|\s)*?-->/, "").
gsub(/( )+|\s+/," ").
gsub(/<\/?[^>]*>/, "").
squeeze(" ")
end
def to_date(type = nil)
return nil if self.empty?
result = self.split("/")
least_significant_year = result.last
if "20#{least_significant_year}".to_i > Time.now.year
year = "19"
else
year = "20"
end
result = Chronic.parse [result[0], result[1], year + least_significant_year].join("/")
if type and type == :db and result
result = result.strftime "%Y.%m.%d %H:%M:%S"
end
result
end
end
class Time
def to_datetime
# Convert seconds + microseconds into a fractional number of seconds
seconds = sec + Rational(usec, 10**6)
# Convert a UTC offset measured in minutes to one measured in a
# fraction of a day.
offset = Rational(utc_offset, 60 * 60 * 24)
DateTime.new(year, month, day, hour, min, seconds, offset)
end
end
RAD_PER_DEG = 0.017453293 # PI/180
Rmiles = 3956 # radius of the great circle in miles
Rkm = 6371 # radius in kilometers...some algorithms use 6367
Rfeet = Rmiles * 5282 # radius in feet
Rmeters = Rkm * 1000 # radius in meters
def distance( lat1, lon1, lat2, lon2 )
# the great circle distance d will be in whatever units R is in
@distances = Hash.new # this is global because if computing lots of track point distances, it didn't make
# sense to new a Hash each time over potentially 100's of thousands of points
=begin rdoc
given two lat/lon points, compute the distance between the two points using the haversine formula
the result will be a Hash of distances which are key'd by 'mi','km','ft', and 'm'
=end
dlon = lon2 - lon1
dlat = lat2 - lat1
dlon_rad = dlon * RAD_PER_DEG
dlat_rad = dlat * RAD_PER_DEG
lat1_rad = lat1 * RAD_PER_DEG
lon1_rad = lon1 * RAD_PER_DEG
lat2_rad = lat2 * RAD_PER_DEG
lon2_rad = lon2 * RAD_PER_DEG
# puts "dlon: #{dlon}, dlon_rad: #{dlon_rad}, dlat: #{dlat}, dlat_rad: #{dlat_rad}"
a = (Math.sin(dlat_rad/2))**2 + Math.cos(lat1_rad) * Math.cos(lat2_rad) * (Math.sin(dlon_rad/2))**2
c = 2 * Math.atan2( Math.sqrt(a), Math.sqrt(1-a))
dMi = Rmiles * c # delta between the two points in miles
dKm = Rkm * c # delta in kilometers
dFeet = Rfeet * c # delta in feet
dMeters = Rmeters * c # delta in meters
@distances["mi"] = dMi
@distances["km"] = dKm
@distances["ft"] = dFeet
@distances["m"] = dMeters
return dKm
end
def degrees_to_decimal(d,m,s,dir)
deg = d.to_f+(((m.to_f*60)+(s.to_f))/3600.0)
deg *= -1 if %w(W U S).include?(dir.upcase)
return deg
end
if ARGV[0] == "scrape"
Scraper.scrape
end
<file_sep>import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from django.core import serializers
import datetime
views_path = 'views/'
#execfile("db.py")
#execfile("db2.py")
class Sighting(db.Model):
sighting_id = db.IntegerProperty()
full_description = db.TextProperty()
city_id = db.IntegerProperty()
shape_id = db.IntegerProperty()
summary_description = db.TextProperty()
temperature = db.IntegerProperty()
weather_conditions = db.StringProperty()
occurred_at = db.DateTimeProperty
reported_at = db.DateTimeProperty
posted_at = db.DateTimeProperty
def summary_description_short(self):
shortened = self.summary_description
if len(self.summary_description) > 50:
shortened = (self.summary_description[:50] + '..')
return shortened
def created_at_formatted(self):
return self.occurred_at.datetime.strftime("%m-%d-%y")
def show_date(self):
return False #hasattr(self.sighting.occurred_at.datetime, 'month')
class City(db.Model):
city_id = db.IntegerProperty()
county_id= db.IntegerProperty()
state_id = db.IntegerProperty()
name = db.StringProperty()
lat = db.FloatProperty()
lon = db.FloatProperty()
class Index(webapp.RequestHandler):
def get(self):
template_values = {'current_page': 'home' }
path = os.path.join(os.path.dirname(__file__), views_path + 'index.html')
self.response.out.write(template.render(path, template_values))
class Screenshots(webapp.RequestHandler):
def get(self):
template_values = {'current_page': 'screenshots' }
path = os.path.join(os.path.dirname(__file__), views_path + 'screenshots.html')
self.response.out.write(template.render(path, template_values))
class Download(webapp.RequestHandler):
def get(self):
template_values = {'current_page': 'download' }
path = os.path.join(os.path.dirname(__file__), views_path + 'download.html')
self.response.out.write(template.render(path, template_values))
class Search(webapp.RequestHandler):
def get(self):
city_name = self.request.get("city_name")
shape_id = self.request.get("shape_id")
cities = City.all().filter("name = ", city_name.lower().capitalize()).fetch(limit=10)
sightings = []
if len(cities) > 0:
sightings = Sighting.all().filter("city_id IN ", map((lambda x: x.city_id), cities)).fetch(limit=100)
if len(shape_id) > 0:
sightings = Sighting.all().filter("shape_id = ", int(shape_id)).fetch(limit=100)
template_values = {'current_page': 'search', 'sightings': sightings, 'city_name': city_name }
path = os.path.join(os.path.dirname(__file__), views_path + 'search.html')
self.response.out.write(template.render(path, template_values))
class DataExtraction(webapp.RequestHandler):
def get(self):
template_values = {'current_page': 'data_extraction'}
path = os.path.join(os.path.dirname(__file__), views_path + 'data_extraction.html')
self.response.out.write(template.render(path, template_values))
class Observations(webapp.RequestHandler):
def get(self):
template_values = {'current_page': 'observations'}
path = os.path.join(os.path.dirname(__file__), views_path + 'observations.html')
self.response.out.write(template.render(path, template_values))
class Sightings(webapp.RequestHandler):
def get(self):
template_values = {'main': 'selected' }
sighting_id = self.request.get("sighting_id")
response = -1
if sighting_id != '':
response = db.GqlQuery("SELECT * FROM Sighting WHERE sighting_id = :1", int(sighting_id)).get().to_xml()
self.response.out.write('<?xml version="1.0"?>');
self.response.out.write(response)
class Applet(webapp.RequestHandler):
def get(self):
template_values = {'current_page': 'applet' }
path = os.path.join(os.path.dirname(__file__), views_path + 'applet.html')
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication([('/', Index),
('/sightings', Sightings),
('/screenshots', Screenshots),
('/search', Search),
('/data_extraction', DataExtraction),
('/observations', Observations),
('/download', Download),
('/applet', Applet)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
|
039e93f05072f6e133a91da25b48ba782260a041
|
[
"SQL",
"Ruby",
"HTML",
"Python",
"Shell"
] | 8
|
Shell
|
TopazFist/cs424p3
|
33da34c35903f7580d5961864528ccbf89a5462d
|
982c1c03be53ce372b9b1ca6b978cce61a6f3645
|
refs/heads/master
|
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cGameMain.h */
/* @brief : ゲームメインシーン */
/* @written : s.kosugi */
/* @create : 2018/12/02 */
/* */
/*==============================================================================*/
#include "..\IBaseScene.h"
//================================================================================================
// ゲームメインシーン
class cGameMain : public IBaseScene
{
public:
cGameMain(IBaseObject* parent);
~cGameMain(void);
void Initialize(void) override;
void Update(void) override;
IBaseObject* Finalize(void) override;
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cEnmWhite.h */
/* @brief : 白い敵クラス */
/* @written : s.kosugi */
/* @create : 2020/06/16 */
/* */
/*==============================================================================*/
#include "..\IEnemy.h"
//================================================================================================
// 白い敵クラス
class cEnmWhite : public IEnemy
{
public:
cEnmWhite(IBaseObject* parent);
~cEnmWhite(void);
// 初期化
void Initialize(const cVector2& pos) override;
// 更新
void Update(void) override;
private:
//--------------------------------------------------------------------------------------------
// 定数
// 表示優先度
static const int PRIORITY;
// 基本移動力
static const float BASE_SPEED;
// 自転速度
static const float ROTATE_SPEED;
//--------------------------------------------------------------------------------------------
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cResult.h */
/* @brief : リザルトシーン */
/* @written : s.kosugi */
/* @create : 2020/07/20 */
/* */
/*==============================================================================*/
#include "..\IBaseScene.h"
//================================================================================================
// リザルトシーン
class cResult : public IBaseScene
{
public:
cResult(IBaseObject* parent);
~cResult(void);
void Initialize(void);
void Update(void);
IBaseObject* Finalize(void);
private:
static const int RANK_B_BORDER;
static const int RANK_A_BORDER;
static const int RANK_S_BORDER;
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cMouse.h */
/* @brief : マウス入力クラス */
/* @written : s.kosugi */
/* @create : 2018/11/24 */
/* */
/*==============================================================================*/
#include "..\..\BaseObject\IBaseObject.h"
#include <DxLib.h>
class cMouse : public IBaseObject
{
public :
void Initialize(void) override;
void Update(void) override;
// マウスボタン押下チェック
bool CheckButton(unsigned int kcode); // 押しているか
bool CheckTrigger(unsigned int kcode); // 押した瞬間
bool CheckRelease(unsigned int kcode); // 離した瞬間
// マウス座標の設定
void SetPoint( int x, int y);
void SetPoint( POINT pt);
// マウス座標の取得
POINT GetPoint( void );
// MouseButton state
int m_nButtonState;
int m_nPrevButtonState;
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cMouse(void) { }; // 他からの生成を禁止
cMouse(IBaseObject* parent) { };
cMouse(IBaseObject* parent, const std::string& name) { };
~cMouse(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cMouse(const cMouse& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cMouse& operator = (const cMouse& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
// シングルトンオブジェクトにはDELETEアクセスをさせない。
IBaseObject* Finalize(void) override { IBaseObject::Finalize(); return nullptr; };
static cMouse& GetInstance(void) {
static cMouse instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cTextObject.h */
/* @brief : テキストオブジェクト */
/* @written : s.kosugi */
/* @create : 2019/08/23 */
/* */
/*==============================================================================*/
#include "..\IBaseObject.h"
#include "DrawCtrl\Text\cText.h"
//================================================================================================
// テキストオブジェクト
// 1クラスにつき1つのテキストを持ちたい場合に使用する。
class cTextObject : public IBaseObject, public cText
{
public:
cTextObject(IBaseObject* parent, const std::string& objectname, const std::string& text);
cTextObject(IBaseObject* parent, const std::string& objectname, const std::string& text, const std::string& fontname, int fontsize, int Thick, int FontType, int EdgeSize, int Italic);
~cTextObject(void);
void Initialize(void) override;
void Initialize( const cVector2& pos );
void Update(void) override;
IBaseObject* Finalize(void) override;
private:
};
//================================================================================================
//================================================================================================
// オブジェクト生成関数
//================================================================================================
// デフォルトフォントでオブジェクト生成
// 親オブジェクトとオブジェクト名と表示テキストを指定する。
// return : 生成したオブジェクト
template <class T> T* CreateTextObject(IBaseObject* parent, const std::string& name, const std::string& text)
{
// ゲームオブジェクト生成
T* t = NEW T(parent, name, text);
// 親がいればリストに追加
if (parent) parent->AddChild(t);
// オブジェクトの返却
return t;
}
// 指定フォントオブジェクト生成
// 親オブジェクトとオブジェクト名と表示テキストとCreateFontToHandleで必要な引数を指定する。
// fontnameはフォント名を文字列で渡す。
// fontsize Thick FontType EdgeSizeは-1でデフォルト
// Italicは0がデフォルト
// return : 生成したオブジェクト
template <class T> T* CreateTextObject(IBaseObject* parent, const std::string& name, const std::string& text, const std::string& fontname, int fontsize, int Thick, int FontType, int EdgeSize, int Italic)
{
// ゲームオブジェクト生成
T* t = NEW T(parent, name, text, fontname, fontsize, Thick, FontType, EdgeSize, Italic);
// 親がいればリストに追加
if (parent) parent->AddChild(t);
// オブジェクトの返却
return t;
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cJoyPad.cpp */
/* @brief : コントローラー入力クラス */
/* @written : s.kosugi */
/* @create : 2018/11/24 */
/* */
/*==============================================================================*/
#include "cJoyPad.h"
#include "../../Utility/memory.h"
//==========================================================================================
// 初期化
//==========================================================================================
void cJoyPad::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "JoyPad";
// コントローラー接続数を取得
m_nJoyPadNum = GetJoypadNum();
// 接続されているコントローラー数分だけキー情報を作成する
m_diInputState = NEW int[m_nJoyPadNum];
m_diPrevInputState = NEW int[m_nJoyPadNum];
memset(m_diInputState, 0, m_nJoyPadNum * sizeof(int));
memset(m_diPrevInputState, 0, m_nJoyPadNum * sizeof(int));
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cJoyPad::Update(void)
{
for (int i = 1; i <= m_nJoyPadNum;i++)
{
// 入力状態を取得する
memcpy(&m_diPrevInputState[i-1], &m_diInputState[i-1],sizeof(int));
m_diInputState[i-1] = GetJoypadInputState(i);
}
IBaseObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject * cJoyPad::Finalize(void)
{
SAFE_DELETE_ARRAY(m_diInputState);
SAFE_DELETE_ARRAY(m_diPrevInputState);
IBaseObject::Finalize();
return nullptr;
}
//==========================================================================================
// ボタン押下チェック
//
// unsigned int kcode チェックするボタン
// PAD_INPUT_1 : ボタン1
// PAD_INPUT_DOWN : ↓キー
// …
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
//
// 戻り値 true:押されていた false:押されていない
//==========================================================================================
bool cJoyPad::CheckButton(unsigned int kcode, int InputType)
{
if( InputType > m_nJoyPadNum) return false;
// ボタンが押されているかどうか
if (m_diInputState[InputType-1] & kcode)
return true;
return false;
}
//==========================================================================================
// 押した瞬間をチェック
//
// unsigned int kcode チェックするボタン
// PAD_INPUT_1 : ボタン1
// PAD_INPUT_DOWN : ↓キー
// …
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
//
// 戻り値 true:押されていた
//==========================================================================================
bool cJoyPad::CheckTrigger(unsigned int kcode, int InputType)
{
if (InputType > m_nJoyPadNum) return false;
// ボタンが押された瞬間
if ( !(m_diPrevInputState[InputType-1] & kcode) && (m_diInputState[InputType-1] & kcode)) return true;
return false;
}
//==========================================================================================
// 離した瞬間をチェック
//
// unsigned int kcode チェックするボタン
// PAD_INPUT_1 : ボタン1
// PAD_INPUT_DOWN : ↓キー
// …
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
//
// 戻り値 true:離された瞬間
//==========================================================================================
bool cJoyPad::CheckRelease(unsigned int kcode, int InputType)
{
if (InputType > m_nJoyPadNum) return false;
// ボタンが離された瞬間
if ((m_diPrevInputState[InputType-1] & kcode) && !(m_diInputState[InputType-1] & kcode)) return true;
return false;
}
//==========================================================================================
// 振動の開始
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// Power : 0 〜 1000
// Time : 振動時間
//==========================================================================================
void cJoyPad::StartVibration(int InputType, int Power, int Time)
{
StartJoypadVibration(InputType, Power, Time);
}
//==========================================================================================
// 振動の停止
// InputType : パッド識別子 DX_INPUT_PAD1〜4
//==========================================================================================
void cJoyPad::StopVibration(int InputType)
{
StopJoypadVibration(InputType);
}
//==========================================================================================
// アナログ入力の取得
//
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 POINT -1000〜1000までの値
//
//==========================================================================================
POINT cJoyPad::GetAnalogInput(int InputType)
{
POINT pt;
int x = 0,y = 0;
pt.y = pt.x = 0;
if (InputType > m_nJoyPadNum) return pt;
GetJoypadAnalogInput(&x,&y,InputType);
pt.x = x;
pt.y = y;
return pt;
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cStageManager.h */
/* @brief : ステージ管理クラス */
/* @written : s.kosugi */
/* @create : 2020/08/19 */
/* */
/*==============================================================================*/
#include "..\..\IBaseObject.h"
#include "StageID.h"
#include "Utility/Vector/cVector2.h"
// 前方宣言
class IStage;
// ステージ管理クラス
class cStageManager : public IBaseObject
{
public:
// コンストラクタ
cStageManager(IBaseObject* pObj);
~cStageManager(void);
// 初期化
void Initialize(void);
// 更新
void Update(void);
// 破棄
IBaseObject* Finalize(void);
// ステージ生成
IStage* Create(STAGE_ID id, const cVector2& pos);
private:
// ステージオブジェクトのピクセルサイズ
static const int STAGE_PIXEL_SIZE;
};<file_sep>#pragma once
enum class EFFECT_ID
{
MIN = 0,
BOM = MIN,
MUZZLE,
LASER,
LASER_START,
MAX
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cDebugFunc.cpp */
/* @brief : デバッグ機能クラス */
/* @written : s.kosugi */
/* @create : 2019/03/24 */
/* */
/*==============================================================================*/
#ifdef DEBUG
#include "cDebugFunc.h"
#include "..\cGame.h"
#include "..\Input\Keyboard\cKeyboard.h"
#include "..\SceneManager\cSceneManager.h"
#include "DrawCtrl/cDrawCtrl.h"
#include <sstream>
#include <iomanip>
#include "Input/Touch/cTouch.h"
#include "Sensor/cSensor.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cDebugFunc::FPS_MODE_MAX = 5;
const int cDebugFunc::FONT_SIZE = 15;
const int cDebugFunc::LOG_MAX = 30;
//==========================================================================================
// 初期化
//==========================================================================================
void cDebugFunc::Initialize(void)
{
m_nStartTime = GetNowCount();
m_nFrameCount = 0;
m_fFrameLate = 0.0f;
m_listLog.clear();
m_nMaxLog = LOG_MAX;
m_nLogNum = 0;
m_eDebugPrintMode = DPRINT_ALL;
m_nFPSMode = 0;
m_listDrawCircle.clear();
m_listDrawBox.clear();
m_nDebugFontHandle = CreateFontToHandle("DebugFont", FONT_SIZE,-1, DX_FONTTYPE_NORMAL);
}
//==========================================================================================
// 更新
//==========================================================================================
void cDebugFunc::Update(void)
{
// デバッグ用更新速度変更
DebugChangeUpdateSpeed();
// デバッグ用シーンリセット
DebugSceneReset();
// フレームレート計算
CalcFrameRate();
// スクリーンショット保存
SaveScreenShot();
}
//==========================================================================================
// 描画
//==========================================================================================
void cDebugFunc::Draw(void)
{
DebugPrint();
}
//==========================================================================================
// デバッグログを追加
//==========================================================================================
void cDebugFunc::PushDebugLog(std::string str)
{
m_listLog.push_front(str);
str += "\n";
std::ostringstream oss;
oss << "[" << m_nLogNum << "]:" << str;
LogFileAdd(oss.str().c_str());
m_nLogNum++;
}
//==========================================================================================
// デバッグログを追加
//==========================================================================================
void cDebugFunc::PushDebugLog(std::string str, float num)
{
std::ostringstream oss;
oss << str << " " << num;
PushDebugLog(oss.str());
}
//==========================================================================================
// デバッグログを追加
//==========================================================================================
void cDebugFunc::PushDebugLog(std::string str, int num)
{
std::ostringstream oss;
oss << str << " " << num;
PushDebugLog(oss.str());
}
//==========================================================================================
// 円描画登録(1フレーム間描画)
// pos : 指定ポイント
// range : 指定ポイントからの範囲
// color : 描画色(ARGB)
//==========================================================================================
void cDebugFunc::RegistDrawCircle(const cVector2 & pos, float range,unsigned int color)
{
DebugCircle circle;
circle.pos = pos;
circle.range = range;
circle.color = color;
m_listDrawCircle.push_back(circle);
}
//==========================================================================================
// 矩形描画登録(1フレーム間描画)
// pos : 指定ポイント
// range : 指定ポイントからの範囲
// color : 描画色(ARGB)
//==========================================================================================
void cDebugFunc::RegistDrawBox(const cVector2 & pos, POINT range,unsigned int color)
{
DebugBox box;
box.pos = pos;
box.range = range;
box.color = color;
m_listDrawBox.push_back(box);
}
//==========================================================================================
// デバッグ用更新速度変更
//==========================================================================================
void cDebugFunc::DebugChangeUpdateSpeed(void)
{
// FPSモードの変更
if (cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_F2))
{
m_nFPSMode = 0;
}
if (cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_F3))
{
m_nFPSMode++;
}
if (cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_F4))
{
m_nFPSMode--;
}
// 最大値チェック
if (FPS_MODE_MAX <= m_nFPSMode) m_nFPSMode = FPS_MODE_MAX;
if (-FPS_MODE_MAX >= m_nFPSMode) m_nFPSMode = -FPS_MODE_MAX;
// ゲーム速度の変更
if (m_nFPSMode > 0)
{
cGame::GetInstance().SetFPS(60);
cGame::GetInstance().SetOneFrameUpdate(m_nFPSMode);
}
else if (m_nFPSMode == 0)
{
cGame::GetInstance().SetFPS(60);
cGame::GetInstance().SetOneFrameUpdate(1);
}
else if (m_nFPSMode < 0)
{
cGame::GetInstance().SetFPS(60 + m_nFPSMode * 10);
cGame::GetInstance().SetOneFrameUpdate(1);
}
}
//==========================================================================================
// デバッグシーンリセット
//==========================================================================================
void cDebugFunc::DebugSceneReset(void)
{
if (cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_F11))
{
cSceneManager::GetInstance().Reset(cSceneManager::CHANGE_TYPE::NOFADE);
}
}
//==========================================================================================
// デバッグ出力
//==========================================================================================
void cDebugFunc::DebugPrint(void)
{
// デバッグ出力の切り替え
if (cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_F1))
{
m_eDebugPrintMode = (DebugPrintMode)((m_eDebugPrintMode + 1) % DPRINT_MAX);
}
if (m_eDebugPrintMode <= DPRINT_NODESCRIPTION)
{
// デバッグ図形描画
DrawShape();
// 文字色
unsigned int nPrintColor = GetColor(255, 255, 255);
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
SetDrawBright(255, 255, 255);
//------------------------------------------------------------------------
// フレームレート表示
DrawFormatString(cGame::GetInstance().GetWindowWidth() - 75, cGame::GetInstance().GetWindowHeight() - 16, nPrintColor, "%2.2fFPS", m_fFrameLate * cGame::GetInstance().GetOneFrameUpdate());
//------------------------------------------------------------------------
// シーンIDの表示
cSceneManager& sm = cSceneManager::GetInstance();
DrawFormatString(cGame::GetInstance().GetWindowWidth() - 100, cGame::GetInstance().GetWindowHeight() - 64, nPrintColor, "SceneID %d", sm.GetCurrentSceneID());
//------------------------------------------------------------------------
// デバッグログの表示
if (!m_listLog.empty())
{
auto it = m_listLog.begin();
auto end = m_listLog.end();
int i = 0;
while (it != end)
{
if (i >= m_nMaxLog)
{
it = m_listLog.erase(it);
continue;
}
std::ostringstream oss;
oss << "[" << m_nLogNum - i << "]:" << (*it);
DrawFormatStringToHandle(0, cGame::GetInstance().GetWindowHeight() - FONT_SIZE * (i + 1),
nPrintColor,
m_nDebugFontHandle,
oss.str().c_str());
i++;
it++;
}
}
//------------------------------------------------------------------------
// タッチ情報の表示
auto mapTouch = cTouch::GetInstance().GetMapTouch();
int i = 0;
std::ostringstream oss;
for (auto it : mapTouch)
{
oss.str("");
oss.clear();
oss << "Touch" << it.first << "::X : " << it.second.pt.PositionX << " Y :" << it.second.pt.PositionY;
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 250, i * 15, oss.str().c_str(), nPrintColor, m_nDebugFontHandle);
i++;
}
cVector3 vec = cSensor::GetInstance().GetAccele();
oss << "Accele ::X : "<< std::setw(6) << std::right << vec.x << " Y :"<< std::setw(6) << std::right << vec.y << " Z :"<< std::setw(6) << std::right << vec.z;
// 加速度センサー情報の表示
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 550, 15 , oss.str().c_str(),nPrintColor, m_nDebugFontHandle);
oss.str("");
oss.clear();
vec = cSensor::GetInstance().GetGyro();
oss << "Gyro ::X : " << std::setw(4) << vec.x << " Y :" << std::setw(4) << vec.y << " Z :" << std::setw(4) << vec.z;
// ジャイロセンサー情報の表示
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 550, 30 , oss.str().c_str(),nPrintColor, m_nDebugFontHandle);
oss.str("");
oss.clear();
vec = cSensor::GetInstance().GetMagnet();
oss << "Magnet ::X : " << std::setw(4) << vec.x << " Y :" << std::setw(4) << vec.y << " Z :" << std::setw(4) << vec.z;
// 磁界センサー情報の表示
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 550, 45 , oss.str().c_str(),nPrintColor, m_nDebugFontHandle);
oss.str("");
oss.clear();
vec = cSensor::GetInstance().GetLight();
oss << "Light ::X : " << std::setw(4) << vec.x << " Y :" << std::setw(4) << vec.y << " Z :" << std::setw(4) << vec.z;
// 照度センサー情報の表示
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 550, 60 , oss.str().c_str(),nPrintColor, m_nDebugFontHandle);
oss.str("");
oss.clear();
vec = cSensor::GetInstance().GetProximity();
oss << "Proximity ::X : " << std::setw(4) << vec.x << " Y :" << std::setw(4) << vec.y << " Z :" << std::setw(4) << vec.z;
// 近接センサー情報の表示
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 550, 75 , oss.str().c_str(),nPrintColor, m_nDebugFontHandle);
oss.str("");
oss.clear();
vec = cSensor::GetInstance().GetPressure();
oss << "Pressure ::X : " << std::setw(4) << vec.x << " Y :" << std::setw(4) << vec.y << " Z :" << std::setw(4) << vec.z;
// 加圧センサー情報の表示
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 550, 90 , oss.str().c_str(),nPrintColor, m_nDebugFontHandle);
oss.str("");
oss.clear();
vec = cSensor::GetInstance().GetTemperature();
oss << "Temperature ::X : " << std::setw(4) << vec.x << " Y :" << std::setw(4) << vec.y << " Z :" << std::setw(4) << vec.z;
// 加圧センサー情報の表示
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 550, 105 , oss.str().c_str(),nPrintColor, m_nDebugFontHandle);
// ヘルプの表示
if (m_eDebugPrintMode == DPRINT_ALL)
{
/*std::string str;
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 250, 0, " F1 : デバッグ表示の切り替え", nPrintColor, m_nDebugFontHandle);
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 250, 15, " F2 : FPSリセット", nPrintColor, m_nDebugFontHandle);
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 250, 30, " F3 : FPS増加", nPrintColor, m_nDebugFontHandle);
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 250, 45, " F4 : FPS減少", nPrintColor, m_nDebugFontHandle);
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 250, 60, " F11 : シーンリセット", nPrintColor, m_nDebugFontHandle);
DrawStringToHandle(cGame::GetInstance().GetWindowWidth() - 250, 75, " PrtScr : スクリーンショット", nPrintColor, m_nDebugFontHandle);*/
}
}
// デバッグ図形リストのクリア
m_listDrawBox.clear();
m_listDrawCircle.clear();
}
//==========================================================================================
// デバッグ図形描画
//==========================================================================================
void cDebugFunc::DrawShape(void)
{
// 矩形の描画
if (!m_listDrawBox.empty())
{
for (auto it = m_listDrawBox.begin();it != m_listDrawBox.end();it++)
{
SetDrawBlendMode(DX_BLENDMODE_ALPHA,(*it).color >> 24);
SetDrawBright(255, 255, 255);
DrawBox((int)((*it).pos.x - (*it).range.x / 2),
(int)((*it).pos.y - (*it).range.y / 2),
(int)((*it).pos.x + (*it).range.x / 2),
(int)((*it).pos.y + (*it).range.y / 2),
(*it).color,
true);
}
}
// 円の描画
if (!m_listDrawCircle.empty())
{
for (auto it = m_listDrawCircle.begin();it != m_listDrawCircle.end();it++)
{
SetDrawBlendMode(DX_BLENDMODE_ALPHA,(*it).color >> 24);
SetDrawBright(255, 255, 255);
DrawCircle((int)((*it).pos.x),
(int)((*it).pos.y),
(int)((*it).range),
(*it).color);
}
}
}
//==========================================================================================
// フレームレート計算
//==========================================================================================
void cDebugFunc::CalcFrameRate(void)
{
// フレームレート計算
int nNowTime = GetNowCount();
m_nFrameCount++;
// 1秒毎に更新
if (nNowTime > m_nStartTime + 1000)
{
m_fFrameLate = m_nFrameCount / ((float)(nNowTime - m_nStartTime) / 1000.0f);
m_nFrameCount = 0;
m_nStartTime = nNowTime;
}
}
//==========================================================================================
// 現在フレームのスクリーンショットを保存する
//==========================================================================================
void cDebugFunc::SaveScreenShot(void)
{
if (cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_SYSRQ))
{
cDrawCtrl::GetInstance().RequestScreenShot();
}
}
#endif // DEBUG<file_sep>/*==============================================================================*/
/* */
/* @file title : cKeyboard.cpp */
/* @brief : キーボード入力クラス */
/* @written : s.kosugi */
/* @create : 2018/11/24 */
/* */
/*==============================================================================*/
#include "cKeyboard.h"
#include <DxLib.h>
//==========================================================================================
// 定数
//==========================================================================================
const int cKeyboard::KEY_STATE_NUM = 256;
//==========================================================================================
// 初期化
//==========================================================================================
void cKeyboard::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "Keyboard";
memset(m_diKeyState,0, KEY_STATE_NUM);
memset(m_diPrevKeyState, 0, KEY_STATE_NUM);
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cKeyboard::Update(void)
{
// 前フレーム情報の保存
memcpy(m_diPrevKeyState,m_diKeyState, KEY_STATE_NUM);
// キー状態の取得
GetHitKeyStateAll(m_diKeyState);
IBaseObject::Update();
}
//==========================================================================================
// キー押下チェック
//
// unsigned int kcode チェックするキーコード
// KEY_INPUT_A : キーボードAキー
// KEY_INPUT_B : キーボードBキー
// …
//
// 戻り値 true:押されていた false:押されていない
//==========================================================================================
bool cKeyboard::CheckButton(unsigned int kcode)
{
// キーが押されているかどうか
if(m_diKeyState[kcode] == 1) return true;
return false;
}
//==========================================================================================
// 押した瞬間をチェック
//
// unsigned int kcode チェックするキーコード
// KEY_INPUT_A : キーボードAキー
// KEY_INPUT_B : キーボードBキー
// …
//
// 戻り値 true:押した瞬間
//==========================================================================================
bool cKeyboard::CheckTrigger(unsigned int kcode)
{
if (m_diPrevKeyState[kcode] == 0 && m_diKeyState[kcode] == 1) return true;
return false;
}
//==========================================================================================
// 離した瞬間をチェック
//
// unsigned int kcode チェックするキーコード
// KEY_INPUT_A : キーボードAキー
// KEY_INPUT_B : キーボードBキー
// …
//
// 戻り値 true:離した瞬間
//==========================================================================================
bool cKeyboard::CheckRelease(unsigned int kcode)
{
if (m_diPrevKeyState[kcode] == 1 && m_diKeyState[kcode] == 0) return true;
return false;
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cCsvReader.h */
/* @brief : CSV読み込みクラス */
/* @written : s.kosugi */
/* @create : 2018/12/08 */
/* */
/*==============================================================================*/
#include "BaseObject\IBaseObject.h"
#include <string>
#include <vector>
class cCsvReader : public IBaseObject
{
public:
// 初期化
void Initialize(void);
// CSVファイル読み込み
int LoadFile(const std::string filepath, std::vector<std::string>& buf);
private:
// 1行単位の文字列を項目毎に分割する
int SplitCsv(const std::string & str, std::vector<std::string>& buf);
// 定数
static const int LINE_CHAR_MAX; // 1行当たりの最大文字数
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cCsvReader(void) { }; // 他からの生成を禁止
cCsvReader(IBaseObject* parent) { };
cCsvReader(IBaseObject* parent, const std::string& name) { };
~cCsvReader(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cCsvReader(const cCsvReader& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cCsvReader& operator = (const cCsvReader& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public :
// シングルトンオブジェクトにはDELETEアクセスをさせない。
IBaseObject* Finalize(void) { IBaseObject::Finalize(); return nullptr; };
static cCsvReader& GetInstance(void) {
static cCsvReader instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cSensor.h */
/* @brief : センサークラス */
/* @written : s.kosugi */
/* @create : 2019/07/27 */
/* */
/*==============================================================================*/
#include "BaseObject\IBaseObject.h"
#include <DxLib.h>
#include "Utility/Vector/cVector3.h"
class cSensor : public IBaseObject
{
public:
void Initialize(void) override;
// 加速度センサー値の取得
inline cVector3 GetAccele( void ) { VECTOR v = GetAndroidSensorVector(DX_ANDROID_SENSOR_ACCELEROMETER); return cVector3(v.x, v.y, v.z);};
// 磁界センサー値の取得
inline cVector3 GetMagnet( void ) { VECTOR v = GetAndroidSensorVector(DX_ANDROID_SENSOR_MAGNETIC_FIELD); return cVector3(v.x, v.y, v.z);};
// ジャイロセンサー値の取得
inline cVector3 GetGyro( void ) { VECTOR v = GetAndroidSensorVector(DX_ANDROID_SENSOR_GYROSCOPE); return cVector3(v.x, v.y, v.z);};
// 照度センサー値の取得
inline cVector3 GetLight( void ) { VECTOR v = GetAndroidSensorVector(DX_ANDROID_SENSOR_LIGHT); return cVector3(v.x, v.y, v.z);};
// 近接センサー値の取得
inline cVector3 GetProximity( void ) { VECTOR v = GetAndroidSensorVector(DX_ANDROID_SENSOR_PROXIMITY); return cVector3(v.x, v.y, v.z);};
// 加圧センサー値の取得
inline cVector3 GetPressure( void ) { VECTOR v = GetAndroidSensorVector(DX_ANDROID_SENSOR_PRESSURE); return cVector3(v.x, v.y, v.z);};
// 温度センサー値の取得
inline cVector3 GetTemperature( void ) { VECTOR v = GetAndroidSensorVector(DX_ANDROID_SENSOR_AMBIENT_TEMPERATURE); return cVector3(v.x, v.y, v.z);};
private:
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cSensor(void) { }; // 他からの生成を禁止
cSensor(IBaseObject* parent) { };
cSensor(IBaseObject* parent, const std::string& name) { };
~cSensor(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cSensor(const cSensor& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cSensor& operator = (const cSensor& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
// シングルトンオブジェクトにはDELETEアクセスをさせない。
IBaseObject* Finalize(void) override { IBaseObject::Finalize(); return nullptr; };
static cSensor& GetInstance(void) {
static cSensor instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>/*==============================================================================*/
/* */
/* @file title : IButton.cpp */
/* @brief : タッチボタン基底クラス */
/* @written : s.kosugi */
/* @create : 2020/07/17 */
/* */
/*==============================================================================*/
#include"IButton.h"
#include "Input/Touch/cTouch.h"
// コンストラクタ
IButton::IButton(IBaseObject * parent, std::string objectname, std::string filename)
: cSpriteObject(parent, objectname, filename)
, m_eButtonState(BUTTON_STATE::NEUTRAL)
{
}
// デストラクタ
IButton::~IButton(void)
{
}
// 初期化
void IButton::Initialize(void)
{
m_vPos = { 0,0 };
SetPriority(PRIORITY);
cSpriteObject::Initialize();
}
// 初期化
void IButton::Initialize(const cVector2& pos)
{
Initialize();
m_vPos = pos;
}
// 更新
void IButton::Update(void)
{
POINT Size = { GetSpriteSize().x , GetSpriteSize().y };
cTouch* touch = (cTouch*)GetRoot()->FindChild("Touch");
if (touch)
{
// タッチ状態によってボタンの状態を変更する
if (touch->CheckHitBox(m_vPos, cTouch::TOUCH_STATE::TRIGGER, Size))
{
m_eButtonState = BUTTON_STATE::TRIGGER;
Trigger();
}
else if (touch->CheckHitBox(m_vPos, cTouch::TOUCH_STATE::RELEASE, Size))
{
m_eButtonState = BUTTON_STATE::RELEASE;
Release();
}
else if (touch->CheckHitBox(m_vPos, cTouch::TOUCH_STATE::BUTTON, Size))
{
m_eButtonState = BUTTON_STATE::PRESSED;
Pressed();
}
else
{
m_eButtonState = BUTTON_STATE::NEUTRAL;
Neutral();
}
} cSpriteObject::Update();
}
// 破棄
IBaseObject* IButton::Finalize(void)
{
cSpriteObject::Finalize();
return this;
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cGameMain.h */
/* @brief : ゲームメインシーン */
/* @written : s.kosugi */
/* @create : 2018/12/02 */
/* */
/*==============================================================================*/
#include "..\IBaseScene.h"
//================================================================================================
// ゲームメインシーン
class cGameMain : public IBaseScene
{
public:
enum STATE
{
START, // 開始演出中
PLAY, // ゲームメイン中
OVER, // ゲームオーバー中
};
cGameMain(IBaseObject* parent);
~cGameMain(void);
void Initialize(void);
void Update(void);
IBaseObject* Finalize(void);
inline const short GetDifficult(void) { return m_nDifficult; };
private:
static const short MAX_DIFFICULT; // 最大難易度
static const float LEVELUP_TIME; // ゲームレベルが上がる間隔
short m_nDifficult;
STATE m_eState;
void ControlGameLevel(void);
void Start(void);
void Play(void);
void Over(void);
};
//================================================================================================<file_sep>/*==============================================================================*/
/* */
/* @file title : cEnmRed.cpp */
/* @brief : 赤い敵クラス */
/* @written : s.kosugi */
/* @create : 2020/07/20 */
/* */
/*==============================================================================*/
#include "cEnmRed.h"
#include "cGame.h"
#include "Utility/Timer/cTimer.h"
#include "Utility/Easing/Easing.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cEnmRed::PRIORITY = 300;
const float cEnmRed::BASE_SPEED = 2.5f;
const float cEnmRed::ROTATE_SPEED = 8.0f;
const float cEnmRed::STOP_DIST = 400.0f;
const float cEnmRed::STOP_TIME = 3.0f;
const float cEnmRed::RESTART_TIME = 2.0f;
const float cEnmRed::RESTART_MAX_SPEED = 10.0f;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cEnmRed::cEnmRed(IBaseObject * parent)
: IEnemy(parent, "EnmRed", "data\\graphic\\enemy_04.png")
, m_eActionState( ACTION_STATE::START )
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cEnmRed::~cEnmRed(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cEnmRed::Initialize(const cVector2 & pos)
{
SetPriority(PRIORITY);
// 当たり判定を設定
m_fDist = GetSpriteSize().x / 2.0f;
// 位置を設定する
m_vPos = pos;
// 画面外配置処理
ArrangeOffScreen();
// 現在位置からプレイヤーに向かって移動させる
GotoPlayer(BASE_SPEED);
IEnemy::Initialize(m_vPos);
}
//==========================================================================================
// 更新
//==========================================================================================
void cEnmRed::Update(void)
{
// 自転処理
SetAngle(GetAngle() + ROTATE_SPEED);
switch (m_eActionState)
{
case ACTION_STATE::START: Start(); break;
case ACTION_STATE::STOP: Stop(); break;
case ACTION_STATE::RESTART: Restart(); break;
}
IEnemy::Update();
}
//==========================================================================================
// 開始状態
//==========================================================================================
void cEnmRed::Start(void)
{
cSpriteObject* pc = (cSpriteObject*)GetParent()->FindSibling("Player");
if (pc)
{
// 停止距離になったら状態を変更する
if (pc->GetPos().CalcTwoPointDist(m_vPos) < STOP_DIST)
{
m_eActionState = ACTION_STATE::STOP;
}
}
}
//==========================================================================================
// 停止状態
//==========================================================================================
void cEnmRed::Stop(void)
{
cTimer* timer = (cTimer*)FindChild("StopTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this, "StopTimer");
timer->Setup(STOP_TIME);
}
GotoPlayer(Easing::OutSine(timer->GetTime(), timer->GetLimit(), 0.0f, BASE_SPEED));
if (timer->Finished())
{
m_eActionState = ACTION_STATE::RESTART;
timer->DeleteObject();
}
}
//==========================================================================================
// 再始動状態
//==========================================================================================
void cEnmRed::Restart(void)
{
cTimer* timer = (cTimer*)FindChild("RestartTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this, "RestartTimer");
timer->Setup(RESTART_TIME);
}
// 時間で加速する
if (!timer->Finished())
{
GotoPlayer(Easing::InSine(timer->GetTime(),timer->GetLimit(), RESTART_MAX_SPEED,0.0f));
}
}
<file_sep>/*==============================================================================*/
/* */
/* @file title : cEnemyManager.cpp */
/* @brief : 敵管理クラス */
/* @written : s.kosugi */
/* @create : 2020/06/16 */
/* */
/*==============================================================================*/
#include "cEnemyManager.h"
#include "cGame.h"
#include "SceneManager/Scene/GameMain/cGameMain.h"
#include "EnmWhite/cEnmWhite.h"
#include "EnmBlue/cEnmBlue.h"
#include "EnmYellow/cEnmYellow.h"
#include "EnmRed/cEnmRed.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif
//==========================================================================================
// 定数
//==========================================================================================
const int cEnemyManager::DEFAULT_POP_INTERVAL = 120; // 初期出現間隔
const int cEnemyManager::DIFFICULT_POP_RATE = 10; // 難易度による敵の出現頻度の倍率
//==========================================================================================
// コンストラクタ
//==========================================================================================
cEnemyManager::cEnemyManager(IBaseObject* pObj)
:IBaseObject(pObj, "EnemyManager")
, m_nPopCounter(0)
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cEnemyManager::~cEnemyManager(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cEnemyManager::Initialize(void)
{
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cEnemyManager::Update(void)
{
// 敵の出現制御
ControlPop();
IBaseObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject * cEnemyManager::Finalize(void)
{
IBaseObject::Finalize();
return this;
}
//==========================================================================================
// 敵生成
// return : 生成した敵のポインタ 生成されなかった場合はnullptr
//==========================================================================================
IEnemy* cEnemyManager::Create(ENEMY_ID id, const cVector2& pos)
{
IEnemy* pObj = nullptr;
switch (id)
{
case ENEMY_ID::WHITE:
pObj = CreateObject<cEnmWhite>(this);
break;
case ENEMY_ID::BLUE:
pObj = CreateObject <cEnmBlue> (this);
break;
case ENEMY_ID::YELLOW:
pObj = CreateObject <cEnmYellow>(this);
break;
case ENEMY_ID::RED:
pObj = CreateObject <cEnmRed>(this);
break;
default:
break;
}
if (pObj)
{
pObj->Initialize(pos);
}
return pObj;
}
//==========================================================================================
// 当たり判定チェック
// pos : 判定をするオブジェクトの位置
// dist : 判定をするオブジェクトの半径
// ret : true 当たった false 当たってない
//==========================================================================================
bool cEnemyManager::CheckHit(const cVector2 & pos, float dist)
{
for (auto it = m_listChildObject.begin(); it != m_listChildObject.end();it++)
{
IEnemy* enm = (IEnemy*)(*it);
if ( enm->GetState() != IEnemy::STATE::DEAD && dist + enm->GetDist() > enm->GetPos().CalcTwoPointDist(pos))
{
enm->Damage();
return true;
}
}
return false;
}
//==========================================================================================
// 敵の出現制御
//==========================================================================================
void cEnemyManager::ControlPop(void)
{
m_nPopCounter++;
// 難易度によって敵の出現頻度を変更する
cGameMain* gm = (cGameMain*)GetParent();
if (m_nPopCounter % (DEFAULT_POP_INTERVAL - gm->GetDifficult() * DIFFICULT_POP_RATE) == 0)
{
cGame* game = (cGame*)GetRoot();
// 敵の位置をランダムに決定する
cVector2 pos;
pos.x = cGame::Random(0, game->GetWindowWidth());
pos.y = cGame::Random(0, game->GetWindowHeight());
// 敵の生成
Create((ENEMY_ID)(cGame::Random(0, (int)ENEMY_ID::MAX-1)), pos);
}
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : Easing.h */
/* @brief : イージング関数 */
/* @written : s.kosugi */
/* @create : 2019/03/16 */
/* */
/*==============================================================================*/
namespace Easing
{
enum class Type
{
INQUAD,
OUTQUAD,
INOUTQUAD,
INCUBIC,
OUTCUBIC,
INOUTCUBIC,
INQUART,
OUTQUART,
INOUTQUART,
INQUINT,
OUTQUINT,
INOUTQUINT,
INSINE,
OUTSINE,
INOUTSINE,
INEXP,
OUTEXP,
INOUTEXP,
INCIRC,
OUTCIRC,
INOUTCIRC,
INBACK,
OUTBACK,
INOUTBACK,
OUTBOUNCE,
INBOUNCE,
INOUTBOUNCE,
LINEAR,
MAX,
};
// t : 現在の経過時間
// totaltime : 最大値にたどり着くまでの時間
// max : イージング関数返す値の最大値
// min : 返す値の最小値
float InQuad(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float OutQuad(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InOutQuad(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InCubic(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float OutCubic(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InOutCubic(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InQuart(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float OutQuart(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InOutQuart(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InQuint(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float OutQuint(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InOutQuint(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InSine(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float OutSine(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InOutSine(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InExp(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float OutExp(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InOutExp(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InCirc(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float OutCirc(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InOutCirc(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InBack(float t, float totaltime , float max = 1.0f, float min = 0.0f, float s = 0.5f);
float OutBack(float t, float totaltime, float max = 1.0f, float min = 0.0f, float s = 0.5f);
float InOutBack(float t, float totaltime, float max = 1.0f, float min = 0.0f, float s = 0.5f);
float OutBounce(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InBounce(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float InOutBounce(float t, float totaltime, float max = 1.0f, float min = 0.0f);
float Linear(float t, float totaltime, float max = 1.0f, float min = 0.0f);
}<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cEnemyManager.h */
/* @brief : 敵管理クラス */
/* @written : s.kosugi */
/* @create : 2020/06/16 */
/* */
/*==============================================================================*/
#include "..\..\IBaseObject.h"
#include "EnemyID.h"
#include "Utility/Vector/cVector2.h"
// 前方宣言
class IEnemy;
// 敵管理クラス
class cEnemyManager : public IBaseObject
{
public:
// コンストラクタ
cEnemyManager(IBaseObject* pObj);
~cEnemyManager(void);
// 初期化
void Initialize(void);
// 更新
void Update(void);
// 破棄
IBaseObject* Finalize(void);
// 弾生成
IEnemy* Create(ENEMY_ID id, const cVector2& pos);
// 当たり判定チェック
// pos : 判定をするオブジェクトの位置
// dist : 判定をするオブジェクトの半径
// ret : true 当たった false 当たってない
bool CheckHit(const cVector2& pos, float dist);
private:
// 初期出現間隔
static const int DEFAULT_POP_INTERVAL;
// 難易度による敵の出現頻度の倍率
static const int DIFFICULT_POP_RATE;
// 敵の出現制御用フレームカウンター
int m_nPopCounter;
// 敵の出現制御
void ControlPop(void);
};<file_sep>/*==============================================================================*/
/* */
/* @file title : IBaseObject.cpp */
/* @brief : オブジェクトベース */
/* @written : s.kosugi */
/* @create : 2018/11/24 */
/* */
/*==============================================================================*/
#include "IBaseObject.h"
//==========================================================================================
// コンストラクタ
//==========================================================================================
IBaseObject::IBaseObject(void)
: m_pParentObject(nullptr)
, m_sObjectName("None")
, m_eObjectState(OBJECT_STATE::ACTIVE)
{
m_listChildObject.clear();
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
IBaseObject::IBaseObject(IBaseObject* parent)
: m_pParentObject(parent)
, m_sObjectName("None")
, m_eObjectState(OBJECT_STATE::ACTIVE)
{
m_listChildObject.clear();
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
IBaseObject::IBaseObject(IBaseObject* parent, const std::string& name)
: m_pParentObject(parent)
, m_sObjectName(name)
, m_eObjectState(OBJECT_STATE::ACTIVE)
{
m_listChildObject.clear();
}
//==========================================================================================
// デストラクタ
//==========================================================================================
IBaseObject::~IBaseObject(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void IBaseObject::Initialize(void)
{
// リストが空なら終了
if (m_listChildObject.empty()) return;
for (auto it : m_listChildObject)
{
it->Initialize();
}
}
//==========================================================================================
// 更新
//==========================================================================================
void IBaseObject::Update(void)
{
// リストが空なら終了
if (m_listChildObject.empty()) return;
auto it = m_listChildObject.begin();
auto end = m_listChildObject.end();
while (it != end)
{
IBaseObject* t = (*it);
// オブジェクトの状態がデッドならリストから除外
if (t->GetObjectState() == OBJECT_STATE::DEAD)
{
// 子オブジェクトをすべて解放
t->Finalize();
// メモリ解放
SAFE_DELETE(t);
// リストから削除
it = m_listChildObject.erase(it);
continue;
}
// オブジェクトの状態がアクティブなら更新
if (t->GetObjectState() == OBJECT_STATE::ACTIVE)
t->Update();
++it;
}
}
//==========================================================================================
// 解放
//==========================================================================================
IBaseObject* IBaseObject::Finalize(void)
{
// リストが空なら終了
if (m_listChildObject.empty()) return this;
for (auto it : m_listChildObject)
{
IBaseObject* obj = it->Finalize();
SAFE_DELETE(obj);
}
// リストのクリア
m_listChildObject.clear();
return this;
}
//==========================================================================================
// リセット
//==========================================================================================
void IBaseObject::Reset(void)
{
// リストが空なら終了
if (m_listChildObject.empty()) return;
for (auto it : m_listChildObject)
{
it->Reset();
}
}
//==========================================================================================
// ルートオブジェクトの取得
// ret : ルートオブジェクトのポインタ
//==========================================================================================
IBaseObject* IBaseObject::GetRoot(void)
{
IBaseObject* pObj = this;
while (pObj->GetParent()) pObj = pObj->GetParent();
return pObj;
}
//==========================================================================================
// 子オブジェクトの追加
// arg 追加する子オブジェクト
//==========================================================================================
void IBaseObject::AddChild(IBaseObject* obj)
{
if (!obj) return;
// 親オブジェクトの登録
obj->m_pParentObject = this;
// 子リストに追加
m_listChildObject.push_back(obj);
}
//==========================================================================================
// 子オブジェクトを先頭に追加
// arg 追加する子オブジェクト
//==========================================================================================
void IBaseObject::AddFrontChild(IBaseObject* obj)
{
if (!obj) return;
// 親オブジェクトの登録
obj->m_pParentObject = this;
// 子リストに追加
m_listChildObject.push_front(obj);
}
//==========================================================================================
// 子オブジェクトの削除
// arg 子オブジェクト名
// ret 削除した子のアドレス
//==========================================================================================
IBaseObject* IBaseObject::RemoveChild(const std::string& name)
{
// リストが空なら終了
if (m_listChildObject.empty()) return nullptr;
auto it = m_listChildObject.begin();
auto end = m_listChildObject.end();
while (it != end)
{
if ((*it)->m_sObjectName == name)
{
IBaseObject* t = *it;
// リストから削除
m_listChildObject.erase(it);
return t;
}
++it;
}
return nullptr;
}
//==========================================================================================
// 子オブジェクトの削除
// arg 関数ポインタ
// ret 削除した子のアドレス
//==========================================================================================
IBaseObject* IBaseObject::RemoveChild(FIND_METHOD func)
{
// リストが空なら終了
if (m_listChildObject.empty()) return nullptr;
auto it = m_listChildObject.begin();
auto end = m_listChildObject.end();
while (it != end)
{
if (func(*it))
{
IBaseObject* t = *it;
// リストから削除
m_listChildObject.erase(it);
return t;
}
++it;
}
return nullptr;
}
//==========================================================================================
// 子オブジェクトの検索
// arg オブジェクト名
// ret 検索オブジェクト 無い場合はnullptr
//==========================================================================================
IBaseObject* IBaseObject::FindChild(const std::string& name)
{
// ゲームオブジェクト名が同じなら、そのオブジェクトを返す
if (m_sObjectName == name) return this;
// リストが空なら終了
if (m_listChildObject.empty()) return nullptr;
for (auto it = m_listChildObject.begin(); it != m_listChildObject.end(); it++)
{
// ゲームオブジェクトIDによって子オブジェクトを検索する
IBaseObject* t = (*it)->FindChild(name);
// アドレスがあれば見つかった
if (t) return t;
}
return nullptr;
}
//==========================================================================================
// 子オブジェクトの検索
// arg 検索条件にする関数ポインタ
// ret 検索オブジェクト 無い場合はnullptr
//==========================================================================================
IBaseObject* IBaseObject::FindChild(FIND_METHOD func)
{
// 検索条件が真なら、そのオブジェクトを返す
if (func(this)) return this;
// リストが空なら終了
if (m_listChildObject.empty()) return nullptr;
for (auto it = m_listChildObject.begin(); it != m_listChildObject.end(); it++)
{
// 検索条件を与えて子オブジェクトを検索する
IBaseObject* t = (*it)->FindChild(func);
// アドレスがあれば見つかった
if (t) return t;
}
return nullptr;
}
//==========================================================================================
// 兄弟オブジェクトの検索
// arg オブジェクト名
// ret 検索オブジェクト 無い場合はnullptr
//==========================================================================================
IBaseObject* IBaseObject::FindSibling(const std::string& name)
{
// 親オブジェクトがいない
if (!m_pParentObject) return nullptr;
// 親のリストから兄弟を検索
return m_pParentObject->FindChild(name);
}
//==========================================================================================
// 兄弟オブジェクトの検索
// arg 検索条件にする関数ポインタ
// ret 検索オブジェクト 無い場合はnullptr
//==========================================================================================
IBaseObject* IBaseObject::FindSibling(FIND_METHOD func)
{
// 親オブジェクトがいない
if (!m_pParentObject) return nullptr;
// 親のリストから兄弟を検索
return m_pParentObject->FindChild(func);
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cGoFont.cpp */
/* @brief : Go文字クラス */
/* @written : s.kosugi */
/* @create : 2020/07/22 */
/* */
/*==============================================================================*/
#include "cGoFont.h"
#include "cGame.h"
#include "Utility/Timer/cTimer.h"
#include "Utility/Easing/Easing.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cGoFont::PRIORITY = 1000;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cGoFont::cGoFont(IBaseObject * parent)
: cSpriteObject(parent, "GoFont", "data\\graphic\\go.png")
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cGoFont::Initialize(void)
{
cSpriteObject::Initialize();
cGame* game = (cGame*)GetRoot();
m_vPos = game->GetWindowCenter();
//拡大しないGoの文字を生成する。
cSpriteObject* sorce = CreateDrawObject<cSpriteObject>(this, "GoFontSorce", m_sFileName);
sorce->SetPos(m_vPos);
sorce->SetPriority(PRIORITY - 1);
cTimer* timer = CreateObject<cTimer>(this, "GoTimer");
timer->Setup(2.0f);
SetPriority(PRIORITY);
}
//==========================================================================================
// 更新
//==========================================================================================
void cGoFont::Update(void)
{
cTimer* timer = (cTimer*)FindChild("GoTimer");
if (timer)
{
if (timer->Finished())
{
DeleteObject();
return;
}
// 徐々に大きくする
m_vScale.x = m_vScale.y = Easing::Linear(timer->GetTime(), timer->GetLimit(), 10.0f, 1.0f);
// 徐々に薄くする
SetAlpha(Easing::Linear(timer->GetTime(), timer->GetLimit(), 0, 255));
// 拡大しないGo文字は最後に一気に薄くする
cSpriteObject* sorce = (cSpriteObject*)FindChild("GoFontSorce");
if (sorce)
{
sorce->SetAlpha(Easing::InExp(timer->GetTime(), timer->GetLimit(), 0, 255));
}
}
cSpriteObject::Update();
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cReadyFont.h */
/* @brief : Ready文字クラス */
/* @written : s.kosugi */
/* @create : 2020/07/22 */
/* */
/*==============================================================================*/
#include "BaseObject/cSpriteObject.h"
// Ready文字クラス
class cReadyFont : public cSpriteObject
{
public:
cReadyFont(IBaseObject* parent);
void Initialize(void);
void Update(void);
private:
enum STATE {
APPEAR,
DISAPPEAR,
};
// 出現状態
void Appear(void);
// 消える状態
void Disappear(void);
STATE m_eState;
// 表示優先度
static const int PRIORITY;
};
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cSceneManager.h */
/* @brief : シーン管理クラス */
/* @written : s.kosugi */
/* @create : 2018/12/02 */
/* */
/*==============================================================================*/
#include "..\BaseObject\IBaseObject.h"
#include "SceneID.h"
#include "..\DrawCtrl\Transition\cTransition.h"
#include "Scene/IBaseScene.h"
//===============================================================================
// シーン管理クラス
class cSceneManager : public IBaseObject
{
public:
void Initialize(void);
void Update( void );
// シーン変更演出タイプ
enum class CHANGE_TYPE
{
NOFADE, // フェード無し
FADE, // フェード
UNITRANS, // ユニバーサルトランジション
};
// シーン変更
void ChangeScene(SCENE_ID id, CHANGE_TYPE type = cSceneManager::CHANGE_TYPE::FADE);
// シーン変更(ユニバーサルトランジション)
void ChangeSceneUniTrans(SCENE_ID id, std::string ruleFilename);
// 現在シーンの取得
inline SCENE_ID GetCurrentSceneID(void) {return m_eCurrentScene;};
// スタックしているシーンを取得(最後尾)
SCENE_ID GetStackSceneID(void);
// フェードアウトタイプの変更
inline void SetFadeOutType(CHANGE_TYPE type) { m_eChangeOutType = type; };
// フェードインタイプの変更
inline void SetFadeInType(CHANGE_TYPE type) { m_eChangeInType = type; };
// フェードアウト時間の変更
inline void SetFadeOutTime(float time) { m_nFadeOutTime = time; };
// フェードイン時間の変更
inline void SetFadeInTime(float time) { m_nFadeInTime = time; };
// フェードアウトトランジションファイルの変更
inline void SetFadeOutTrans(std::string filename) { m_sTransOutFileName = filename; };
// フェードイントランジションファイルの変更
inline void SetFadeInTrans(std::string filename) { m_sTransInFileName = filename; };
// シーンスタック関連
void PushScene( SCENE_ID id);
void PopScene( void );
void Reset(void) {};
// 現在のシーンをリセットする
void Reset(CHANGE_TYPE changeType);
private:
// シーン生成
IBaseScene* CreateScene(SCENE_ID id);
// フェードアウト前準備
void PrepareFadeOut( void );
//------------------------------------------------------------------------------
// シーン状態別処理
void FadeIn(void);
void UpdateScene(void);
void FadeOut(void);
void TransitionScene(void);
//------------------------------------------------------------------------------
enum class STATE
{
FADEIN, // フェードイン
UPDATE, // シーン更新
FADEOUT, // フェードアウト
TRANSITION, // シーン遷移
};
SCENE_ID m_eCurrentScene; // シーンID
SCENE_ID m_eNextScene; // 次シーンID
STATE m_eState; // シーン状態
CHANGE_TYPE m_eChangeOutType; // シーン変更(フェードアウト)演出タイプ
CHANGE_TYPE m_eChangeInType; // シーン変更(フェードイン)演出タイプ
cTransition* m_pTransObj; // トランジションクラス
std::string m_sTransOutFileName; // ルール画像(フェードアウト)ファイル名
std::string m_sTransInFileName; // ルール画像(フェードアウト)ファイル名
float m_nFadeInTime; // フェードイン時間
float m_nFadeOutTime; // フェードアウト時間
SCENE_ID m_ePushSceneID; // プッシュするシーンID
bool m_bPush; // シーンのプッシュが行われたかどうか
short m_nStackCount; // シーンスタックされている数をカウントする
//------------------------------------------------------------------------------
// 定数
// 初期フェード秒数
static const float DEFAULT_FADE_TIME;
//------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cSceneManager(void); // 他からの生成を禁止
cSceneManager(IBaseObject* parent);
cSceneManager(IBaseObject* parent, const std::string& name);
~cSceneManager(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cSceneManager(const cSceneManager& t); // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cSceneManager& operator = (const cSceneManager& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
// シングルトンオブジェクトにはDELETEアクセスをさせない。
IBaseObject* Finalize(void) { IBaseObject::Finalize(); return nullptr; };
static cSceneManager& GetInstance(void) {
static cSceneManager instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cEnmYellow.cpp */
/* @brief : 黄色い敵クラス */
/* @written : s.kosugi */
/* @create : 2020/07/20 */
/* */
/*==============================================================================*/
#include "cEnmYellow.h"
#include "cGame.h"
#include "Utility/Timer/cTimer.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cEnmYellow::PRIORITY = 300;
const float cEnmYellow::BASE_SPEED = 1.0f;
const float cEnmYellow::ROTATE_SPEED = 4.0f;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cEnmYellow::cEnmYellow(IBaseObject * parent)
: IEnemy(parent, "EnmYellow", "data\\graphic\\enemy_03.png")
, m_ePopDirection( DIRECTION::LEFT)
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cEnmYellow::~cEnmYellow(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cEnmYellow::Initialize(const cVector2 & pos)
{
SetPriority(PRIORITY);
// 当たり判定を設定
m_fDist = GetSpriteSize().x / 2.0f;
// 位置を設定する
m_vPos = pos;
// 画面外配置処理
m_ePopDirection = ArrangeOffScreen();
SetAngle((float)cGame::Random(0, 359));
IEnemy::Initialize(m_vPos);
}
//==========================================================================================
// 更新
//==========================================================================================
void cEnmYellow::Update(void)
{
// 自転処理
SetAngle(GetAngle() + ROTATE_SPEED);
if (m_eState == STATE::NORMAL)
{
cGame* game = (cGame*)GetRoot();
switch (m_ePopDirection)
{
case DIRECTION::LEFT:
m_vPosUp.x = BASE_SPEED;
m_vPos.y = cos(DEG_TO_RAD(GetAngle()*0.5f)) * game->GetWindowCenter().y + game->GetWindowCenter().y;
break;
case DIRECTION::RIGHT:
m_vPosUp.x = -BASE_SPEED;
m_vPos.y = cos(DEG_TO_RAD(GetAngle()*0.5f)) * game->GetWindowCenter().y + game->GetWindowCenter().y;
break;
case DIRECTION::TOP:
m_vPosUp.y = BASE_SPEED;
m_vPos.x = cos(DEG_TO_RAD(GetAngle()*0.5f)) * game->GetWindowCenter().x + game->GetWindowCenter().x;
break;
case DIRECTION::BOTTOM:
m_vPosUp.y = -BASE_SPEED;
m_vPos.x = cos(DEG_TO_RAD(GetAngle()*0.5f)) * game->GetWindowCenter().x + game->GetWindowCenter().x;
break;
}
}
IEnemy::Update();
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cStartFont.cpp */
/* @brief : スタートの文字クラス */
/* @written : s.kosugi */
/* @create : 2020/08/31 */
/* */
/*==============================================================================*/
#include "cStartFont.h"
#include "cGame.h"
#include "Utility/Timer/cTimer.h"
#include "Utility/Easing/Easing.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cStartFont::PRIORITY = 1000;
const float cStartFont::MOVE_TIME = 1.5f;
const float cStartFont::FADE_TIME = 0.5f;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cStartFont::cStartFont(IBaseObject* parent)
: cSpriteObject(parent, "StartFont", "data\\graphic\\start_font.png")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cStartFont::~cStartFont(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cStartFont::Initialize(void)
{
SetPriority(PRIORITY);
cGame* game = (cGame*)GetRoot();
// 中央左あたりに配置
SetPos(-GetSpriteSize().x / 2.0f, game->GetWindowCenter().y);
cSpriteObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cStartFont::Update(void)
{
cTimer* timer = (cTimer*)FindChild("StartFontMoveTimer");
cGame* game = (cGame*)GetRoot();
if (!timer)
{
timer = CreateObject<cTimer>(this, "StartFontMoveTimer");
timer->Setup(MOVE_TIME);
}
if (!timer->Finished())
{
float posx = Easing::OutBack(timer->GetTime(), timer->GetLimit(), game->GetWindowCenter().x, -GetSpriteSize().x / 2.0f);
SetPosX(posx);
}
else
{
SetPosX(game->GetWindowCenter().x);
// フェードアウト処理
timer = (cTimer*)FindChild("StartFontFadeTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this, "StartFontFadeTimer");
timer->Setup(FADE_TIME);
}
if (!timer->Finished())
{
SetAlpha((int)Easing::Linear(timer->GetTime(), timer->GetLimit(), 0.0f, 255.0f));
}
else
{
DeleteObject();
}
}
cSpriteObject::Update();
}<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cTouch.h */
/* @brief : タッチ入力クラス */
/* @written : s.kosugi */
/* @create : 2019/07/22 */
/* */
/*==============================================================================*/
#include "..\..\BaseObject\IBaseObject.h"
#include <DxLib.h>
#include <map>
#include "Utility/Vector/cVector2.h"
class cTouch : public IBaseObject
{
public:
// タッチ状態
enum class TOUCH_STATE
{
NONE = -1,
TRIGGER = 0,
BUTTON,
RELEASE
};
// タッチ構造体
struct TOUCHPTEX
{
TOUCHINPUTPOINT pt; // タッチ構造体
TOUCH_STATE state; // 現在のタッチ状態
};
void Initialize(void);
void Update(void);
// 特定箇所の範囲がタッチされているかを確認する(円判定)
// pos : 指定ポイント
// state : 調べたいタッチ状態
// range : 指定ポイントから調べたい範囲
// ret : true 指定箇所が該当の状態だった
bool CheckHitCircle( const cVector2& pos, TOUCH_STATE state, float range);
// 特定箇所の範囲がタッチされているかを確認する(矩形判定)
// pos : 指定ポイント
// state : 調べたいタッチ状態
// range : 指定ポイントから調べたい範囲
// ret : true 指定箇所が該当の状態だった
bool CheckHitBox( const cVector2& pos, TOUCH_STATE state, POINT range);
// タッチ情報配列を取得する
inline const std::map<int, TOUCHPTEX>& GetMapTouch(void) { return m_mapTouchPoint; };
// タッチ座標の取得
// touchID : 取得するタッチID
// pt : 取得する座標の参照
// state : タッチ状態
// ret : true タッチ情報が存在していた。 false タッチ情報が存在していない
bool GetTouchPos(int touchID, POINT& pt);
bool GetTouchPos(int touchID, POINT & pt, TOUCH_STATE& state);
// タッチ数取得
int GetTouchNum(void);
private:
std::map<int, TOUCHPTEX> m_mapTouchPoint; // タッチ情報連想配列 キー値 : タッチID
#ifdef DEBUG
// デバッグログにタッチのログを表示する
void DrawTouchDebugLog(void);
#endif // DEBUG
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cTouch(void) { }; // 他からの生成を禁止
cTouch(IBaseObject* parent) { };
cTouch(IBaseObject* parent, const std::string& name) { };
~cTouch(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cTouch(const cTouch& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cTouch& operator = (const cTouch& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
// シングルトンオブジェクトにはDELETEアクセスをさせない。
IBaseObject* Finalize(void) { IBaseObject::Finalize(); return nullptr; };
static cTouch& GetInstance(void) {
static cTouch instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cEnmBlue.h */
/* @brief : 青い敵クラス */
/* @written : s.kosugi */
/* @create : 2020/07/20 */
/* */
/*==============================================================================*/
#include "..\IEnemy.h"
//================================================================================================
// 青い敵クラス
class cEnmBlue : public IEnemy
{
public:
cEnmBlue(IBaseObject* parent);
~cEnmBlue(void);
// 初期化
void Initialize(const cVector2& pos) override;
// 更新
void Update(void) override;
// 通常状態
void Normal(void) override;
protected:
void AreaOutAllProc(void) override;
private:
//--------------------------------------------------------------------------------------------
// 定数
// 表示優先度
static const int PRIORITY;
// 自転速度
static const float ROTATE_SPEED;
// 基準距離
static const int BASE_DIST;
// 最小到達時間
static const int MIN_TIME;
// 最大到達時間
static const int MAX_TIME;
//--------------------------------------------------------------------------------------------
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cGame.h */
/* @brief : ゲームクラス */
/* @written : s.kosugi */
/* @create : 2018/11/14 */
/* */
/*==============================================================================*/
#include <DxLib.h>
#include "BaseObject\IBaseObject.h"
#include "Utility/Vector/cVector2.h"
//===============================================================================
// ゲームクラス
class cGame : public IBaseObject
{
public:
void Initialize(void);
void Update(void);
void Draw(void);
// 乱数の発生
static int Random(int min, int max);
//-----------------------------------------------------------------------------------------
// Getter
//-----------------------------------------------------------------------------------------
// FPSの取得
inline unsigned int GetFPS(void) { return m_nFPS; };
// プレイエリアの取得
inline RECT GetPlayArea(void) { return m_PlayArea; };
inline int GetPlayAreaWidth(void) { return m_PlayArea.right - m_PlayArea.left; };
inline int GetPlayAreaHeight(void) { return m_PlayArea.bottom - m_PlayArea.top; };
// ウィンドウサイズの取得
inline int GetWindowWidth(void) { return WINDOW_SIZE_X; };
inline int GetWindowHeight(void) { return WINDOW_SIZE_Y; };
// ウィンドウの中心位置を取得
inline cVector2 GetWindowCenter(void) { cVector2 ret((float)(WINDOW_SIZE_X / 2), (float)(WINDOW_SIZE_Y / 2)); return ret; };
// 更新の回数の取得(1Frame内)
inline int GetOneFrameUpdate(void) { return m_nOneFrameUpdate; };
// デルタタイム取得
inline float GetDeltaTime(void) const { return m_fDeltaTime * m_fDeltaTimeScale; };
//-----------------------------------------------------------------------------------------
// Setter
//-----------------------------------------------------------------------------------------
// FPSの設定
inline void SetFPS(unsigned int fps) { m_nFPS = fps; };
// FPSをリセット
inline void ResetFPS(void) { m_nFPS = DEFAULT_FPS; };
// 更新の回数のセット(1Frame内)
inline void SetOneFrameUpdate(int num) { m_nOneFrameUpdate = num; };
private:
// 更新するフレームカウントの計算
void CalcFrameCount( void );
//-----------------------------------------------------------------------------------------
// 変数
//-----------------------------------------------------------------------------------------
unsigned int m_nFPS; // FPS
int m_nOneFrameUpdate; // 更新回数(1Frame内)
float m_fDeltaTime; // デルタタイム
float m_fDeltaTimeScale; // デルタタイム倍率
int m_nFrameCount; // フレームカウント
int m_nStartTime; // フレーム計測開始時間
int m_nPrevTime; // 1フレーム前の時間
RECT m_PlayArea; // プレイエリア
//-----------------------------------------------------------------------------------------
// 定数
//-----------------------------------------------------------------------------------------
static const unsigned int DEFAULT_FPS = 60; // デフォルトFPS
static const float MAX_DELTA_TIME; // 最大デルタタイム
static const float ONE_MILL_SECOND; // 1ミリ秒
static const int CALC_FRAME_COUNT; // 平均を計算するフレームの数
static const int WINDOW_SIZE_X; // ウィンドウ幅
static const int WINDOW_SIZE_Y; // ウィンドウ高さ
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cGame(void) { }; // 他からの生成を禁止
cGame(IBaseObject* parent) { };
cGame(IBaseObject* parent, const std::string& name) { };
~cGame(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cGame(const cGame& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cGame& operator = (const cGame& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
// シングルトンオブジェクトにはDELETEアクセスをさせない。
IBaseObject* Finalize(void) { IBaseObject::Finalize(); return nullptr; };
static cGame& GetInstance(void) {
static cGame instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cScoreManager.h */
/* @brief : スコア管理クラス */
/* @written : s.kosugi */
/* @create : 2020/04/03 */
/* */
/*==============================================================================*/
#include "..\BaseObject\IBaseObject.h"
// スコア管理クラス
class cScoreManager : public IBaseObject
{
public:
// コンストラクタ
cScoreManager(IBaseObject* pObj);
// デストラクタ
~cScoreManager( void );
// 初期化
void Initialize( void );
// 破棄
IBaseObject* Finalize( void );
// スコアリセット
inline void ResetScore( void ) { m_nCurrentScore = 0; };
// スコア加算
inline void AddScore( int score ) { m_nCurrentScore += score; };
// スコア取得
inline int GetScore( void ) { return m_nCurrentScore; };
private:
// 現在スコア
int m_nCurrentScore;
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cSurface.cpp */
/* @brief : サーフェイスクラス */
/* @written : s.kosugi */
/* @create : 2019/02/26 */
/* */
/*==============================================================================*/
#include "cSurface.h"
#include "..\cDrawCtrl.h"
//==========================================================================================
// コンストラクタ
//==========================================================================================
cSurface::cSurface(int width, int height, int beginPriority, int endPriority, bool alpha) :
IDrawBase(),
m_vAngle(0.0f, 0.0f, 0.0f),
m_vCenter(0.0f, 0.0f),
m_Rect({ 0,0,0,0 }),
m_nBlendMode(DX_BLENDMODE_ALPHA),
m_vScale(1.0f, 1.0f),
m_bShow(true),
m_eFilterMode(FILTER_MODE::NONE),
m_nMonoBlue(0),
m_nMonoRed(0),
m_nGaussPixelWidth(8),
m_nGaussParam(1000)
{
m_Rect.left = 0;
m_Rect.top = 0;
m_Rect.right = width;
m_Rect.bottom = height;
m_vCenter.x = width / 2.0f;
m_vCenter.y = height / 2.0f;
SetPriority(endPriority);
m_cBeginPoint.SetPriority(beginPriority);
// サーフェイスはオブジェクト削除時にメモリからアンロードする
m_bUnload = true;
// 描画情報を登録
cDrawCtrl::GetInstance().RegistSurface(*this, width, height, alpha);
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cSurface::~cSurface()
{
cDrawCtrl::GetInstance().RemoveSurface(this);
}<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cEnmYellow.h */
/* @brief : 黄色い敵クラス */
/* @written : s.kosugi */
/* @create : 2020/07/20 */
/* */
/*==============================================================================*/
#include "..\IEnemy.h"
//================================================================================================
// 黄色い敵クラス
class cEnmYellow : public IEnemy
{
public:
cEnmYellow(IBaseObject* parent);
~cEnmYellow(void);
// 初期化
void Initialize(const cVector2& pos) override;
// 更新
void Update(void) override;
private:
//--------------------------------------------------------------------------------------------
// 定数
// 表示優先度
static const int PRIORITY;
// 基本移動力
static const float BASE_SPEED;
// 自転速度
static const float ROTATE_SPEED;
//--------------------------------------------------------------------------------------------
// 出現方向
IEnemy::DIRECTION m_ePopDirection;
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cClearFont.h */
/* @brief : クリアの文字クラス */
/* @written : s.kosugi */
/* @create : 2020/08/31 */
/* */
/*==============================================================================*/
#include "..\..\..\cSpriteObject.h"
//================================================================================================
// クリアの文字クラス
class cClearFont : public cSpriteObject
{
public:
cClearFont(IBaseObject* parent);
~cClearFont(void);
void Initialize(void);
void Update(void);
private:
//--------------------------------------------------------------------------------------------
// 定数
// 表示優先度
static const int PRIORITY;
static const float MOVE_TIME;
static const float FADE_TIME;
//--------------------------------------------------------------------------------------------
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cTitleCursol.h */
/* @brief : タイトルカーソルクラス */
/* @written : s.kosugi */
/* @create : 2020/07/22 */
/* */
/*==============================================================================*/
#include "BaseObject/cSpriteObject.h"
// タイトルカーソルクラス
class cTitleCursol : public cSpriteObject
{
public:
cTitleCursol(IBaseObject* parent);
void Initialize(void);
void Update(void);
// 初期設定
void Setup(const cVector2& pos, float angle);
private:
cVector2 m_vOriginPos;
// 表示優先度
static const int PRIORITY;
};
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cJoyPad.h */
/* @brief : コントローラー入力クラス */
/* @written : s.kosugi */
/* @create : 2018/11/24 */
/* */
/*==============================================================================*/
#include "..\..\BaseObject\IBaseObject.h"
#include <DxLib.h>
class cJoyPad : public IBaseObject
{
public:
// 初期化
void Initialize(void);
// 更新
void Update(void);
// 破棄
IBaseObject* Finalize(void);
// ボタン押下チェック
bool CheckButton(unsigned int kcode,int InputType = DX_INPUT_PAD1); // 押しているか
bool CheckTrigger(unsigned int kcode, int InputType = DX_INPUT_PAD1); // 押した瞬間
bool CheckRelease(unsigned int kcode, int InputType = DX_INPUT_PAD1); // 離した瞬間
// 振動の開始
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// Power : 0 〜 1000
// Time : 振動時間
void StartVibration(int InputType, int Power, int Time);
// 振動の停止
// InputType : パッド識別子 DX_INPUT_PAD1〜4
void StopVibration(int InputType);
// アナログ入力取得
POINT GetAnalogInput(int InputType);
// 接続台数取得
inline int GetConnectNum(void) { return m_nJoyPadNum; };
// DirectInput Joypad state
int* m_diInputState;
// 前フレーム情報
int* m_diPrevInputState;
// ジョイパッド接続数
short m_nJoyPadNum;
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cJoyPad(void) { }; // 他からの生成を禁止
cJoyPad(IBaseObject* parent) { };
cJoyPad(IBaseObject* parent, const std::string& name) { };
~cJoyPad(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cJoyPad(const cJoyPad& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cJoyPad& operator = (const cJoyPad& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
static cJoyPad& GetInstance(void) {
static cJoyPad instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cDrawCtrl.h */
/* @brief : 描画コントロールクラス */
/* @written : s.kosugi */
/* @create : 2018/09/17 */
/* */
/*==============================================================================*/
#include "IDrawBase.h"
#include "Sprite\cSprite.h"
#include "Surface/cSurface.h"
#include "Transition\cTransition.h"
#include "../BaseObject/IBaseObject.h"
#include <list>
#include "Text/cText.h"
//===============================================================================
// 描画コントロールクラス
class cDrawCtrl : public IBaseObject
{
public:
void Initialize(void);
void Draw(void);
IBaseObject* Finalize(void);
// 描画オブジェクトの登録
void RegistDrawObject(cSprite& obj, const std::string& filename);
// 描画オブジェクトの登録
//void RegistDrawObject(cEffect& obj, const std::string& filename);
// サーフェイスの登録
void RegistSurface(cSurface& obj, int width, int height, bool alpha);
// トランジションの登録
void RegistTransition(cTransition& obj, const std::string& filename);
// テキストの登録
void RegistDrawObject(cText& obj);
// テキストの登録(フォント生成あり)
void RegistDrawObject(cText& obj, const std::string& fontname, int Size, int Thick, int FontType, int EdgeSize, int Italic);
// 描画ファイル読込処理
// 戻り値 : グラフィックハンドル
int LoadDrawFile(const std::string& filename, DRAWTYPE type);
// 描画オブジェクトの登録抹消
void RemoveDrawObject(const IDrawBase* obj);
// サーフェイスの登録抹消
void RemoveSurface(const cSurface* obj);
// テキストの文字幅を取得する
int GetTextWidth(cText* obj);
// 描画リストのクリア
inline void ClearDrawList(void) { m_listDrawObject.clear(); m_listFileLoaded.clear(); };
// 描画優先変更要求
inline void RequestChangeDrawPriority(void) { m_bPriChageRequest = true; };
// スクリーンショットの撮影要求
inline void RequestScreenShot(void) { m_bScreenShot = true; };
private:
// スプライトの描画
void DrawSprite(cSprite* obj);
// エフェクトの描画
//void DrawEffect(cEffect* obj);
// サーフェイスの描画
// ret : サーフェイス描画成功 : true
bool DrawSurface(cSurface* obj);
// サーフェイスの描画開始
void BeginSurface(IDrawBase* obj);
// トランジションの描画
void DrawTransition(cTransition* obj);
// テキストの描画
void DrawTextObj(cText* obj);
//--------------------------------------------------------------------------------------
// リストの昇順比較関数
// DrawObjectの表示優先が低いものから先に描画をする
// staticをつけないとstdが非インスタンスで呼びたい為エラーが出る
static bool CompAscPriority(IDrawBase* left, IDrawBase* right) { return left->GetPriority() < right->GetPriority(); };
//--------------------------------------------------------------------------------------
// 同じグラフィックハンドルを持つオブジェクトがあるかを探す
// 戻り値 : true 見つかった false 見つからなかった
bool SearchSameGrHandle(const IDrawBase* obj);
// 生成済フォント構造体
struct FontCreated
{
std::string FontName;
int Size = 30;
int Thick = 0;
int FontType = 0;
int EdgeSize = 0;
int Italic = 0;
int Handle = -1; // 生成済みフォントハンドル
};
//--------------------------------------------------------------------------------------
// 同じフォントが生成済みかを探す
// 戻り値 : -1 同じフォントが見つからなかった -1以外 フォントハンドル
int SearchSameFont(FontCreated& font);
//--------------------------------------------------------------------------------------
// 読み込み済みファイルから抹消
void RemoveFileLoaded(std::string filename);
//--------------------------------------------------------------------------------------
// スクリーンショット保存
//void SaveScreenFile( void );
//--------------------------------------------------------------------------------------
// ファイル読み込み関連
// 読み込みファイル構造体
struct FileLoaded
{
std::string FileName;
int GraphHandle = -1;
DRAWTYPE Type = DRAWTYPE::SPRITE;
};
// 読み込み済みファイルリスト
std::list<FileLoaded> m_listFileLoaded;
//--------------------------------------------------------------------------------------
// 描画オブジェクトリスト
std::list<IDrawBase*> m_listDrawObject;
// 描画優先変更要求
bool m_bPriChageRequest;
// スクリーンショット保存要求
bool m_bScreenShot;
// 生成済みフォントリスト
std::list<FontCreated> m_listFontCreated;
// 処理中サーフェイスポインタ
IDrawBase* m_pBeginSurface;
// サーフェイス処理待ちリスト
std::list<IDrawBase*> m_listSurfaceWait;
//--------------------------------------------------------------------------------------
// 定数
const int LOADGRAPH_FAILED = -1; // 画像読込失敗
const int FONT_NOTFAUND = -1; // フォントが見つからない
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cDrawCtrl(void); // 他からの生成を禁止
cDrawCtrl(IBaseObject* parent);
cDrawCtrl(IBaseObject* parent, const std::string& name);
~cDrawCtrl(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cDrawCtrl(const cDrawCtrl& t); // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cDrawCtrl& operator = (const cDrawCtrl& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
static cDrawCtrl& GetInstance(void) {
static cDrawCtrl instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cGame.cpp */
/* @brief : ゲームクラス */
/* @written : s.kosugi */
/* @create : 2018/11/14 */
/* */
/*==============================================================================*/
#include "cGame.h"
#include "SoundCtrl\cSoundCtrl.h"
#include "DrawCtrl\cDrawCtrl.h"
#include "MovieManager/cMovieManager.h"
#include "Input\cControllerManager.h"
#include "Input/Touch/cTouch.h"
#include "SceneManager\cSceneManager.h"
#include "BaseObject/GameObject/Effect/cEffectManager.h"
#include "Utility\memory.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif // DEBUG
//==========================================================================================
// 定数
//==========================================================================================
const float cGame::MAX_DELTA_TIME = 0.16f; // 最大デルタタイム
const float cGame::ONE_MILL_SECOND = 1000.0f; // 1秒
const int cGame::CALC_FRAME_COUNT = 60; // 平均を計算するフレームの数
const int cGame::WINDOW_SIZE_X = 1280; // ウィンドウ幅
const int cGame::WINDOW_SIZE_Y = 720; // ウィンドウ高さ
//==========================================================================================
// 初期化
//==========================================================================================
void cGame::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "Game";
// FPS
m_nFPS = DEFAULT_FPS;
// 1フレーム内の更新回数
m_nOneFrameUpdate = 1;
// デルタタイム設定
m_fDeltaTime = 0.0f;
m_fDeltaTimeScale = 1.0f;
// 更新フレーム設定
m_nFrameCount = 0;
m_nStartTime = 0;
m_nPrevTime = 0;
// プレイエリアの設定(UI表示領域があることを想定)
m_PlayArea = { 0,0,GetWindowWidth(),GetWindowHeight() };
// 描画操作クラス
AddChild(&cDrawCtrl::GetInstance());
// エフェクト管理クラス
CreateObject<cEffectManager>(this);
// 動画管理クラス
AddChild(&cMovieManager::GetInstance());
// サウンド操作クラス
AddChild(&cSoundCtrl::GetInstance());
// 全サウンドの読み込み
cSoundCtrl::GetInstance().LoadAll();
// 入力管理クラス
AddChild(&cTouch::GetInstance());
AddChild(&cControllerManager::GetInstance());
// シーンマネージャークラス
AddChild(&cSceneManager::GetInstance());
#ifdef DEBUG
// デバッグ機能クラス
AddChild(&cDebugFunc::GetInstance());
#endif // DEBUG
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cGame::Update(void)
{
// フレームカウント算出
CalcFrameCount();
for (int i = 0; i < m_nOneFrameUpdate; i++)
{
// 通常の更新
IBaseObject::Update();
}
}
//==========================================================================================
// 描画
//==========================================================================================
void cGame::Draw(void)
{
cDrawCtrl::GetInstance().Draw();
#ifdef DEBUG
cDebugFunc::GetInstance().Draw();
#endif // DEBUG
}
//==========================================================================================
// 乱数の発生
//==========================================================================================
int cGame::Random(int min, int max)
{
int range;
range = max - min;
return GetRand(range) + min;
}
//==========================================================================================
// 更新するフレームカウントの計算
//==========================================================================================
void cGame::CalcFrameCount(void)
{
// 現在の時間を取得
int now_time = GetNowCount();
// 計算開始時
if (m_nFrameCount == 0)
{
m_nStartTime = now_time;
}
// 指定されたフレームカウント時
else if (m_nFrameCount == CALC_FRAME_COUNT)
{
m_nFrameCount = 0;
m_nStartTime = now_time;
}
// フレームカウントを更新
++m_nFrameCount;
// 前の処理との時間の差
int sub_time = now_time - m_nPrevTime;
// デルタタイムを算出
m_fDeltaTime = (float)sub_time / ONE_MILL_SECOND;
// 最大デルタタイムで制限する
if (m_fDeltaTime > MAX_DELTA_TIME) m_fDeltaTime = MAX_DELTA_TIME;
// 今の時間を保存
m_nPrevTime = now_time;
}<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cSpriteObject.h */
/* @brief : 描画オブジェクト */
/* @written : s.kosugi */
/* @create : 2018/12/01 */
/* */
/*==============================================================================*/
#include "IBaseObject.h"
#include "..\DrawCtrl\Sprite\cSprite.h"
//================================================================================================
// 描画オブジェクト
// 1クラスにつき1つのスプライトを持ちたい場合に使用する。
class cSpriteObject : public IBaseObject, public cSprite
{
public:
cSpriteObject(IBaseObject* parent, const std::string& objectname, const std::string& filename);
~cSpriteObject( void );
virtual void Initialize( void );
virtual void Initialize( const cVector2& pos );
virtual void Update( void );
virtual IBaseObject* Finalize( void );
};
//================================================================================================
//================================================================================================
// オブジェクト生成関数
//================================================================================================
// オブジェクト生成
// 親オブジェクトとオブジェクト名と画像ファイル名を指定する。
// return : 生成したオブジェクト
template <class T> T* CreateDrawObject(IBaseObject* parent, const std::string& name, const std::string& filename)
{
// ゲームオブジェクト生成
T* t = NEW T(parent, name,filename);
// 親がいればリストに追加
if (parent) parent->AddChild(t);
// オブジェクトの返却
return t;
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : IStage.h */
/* @brief : ステージベースクラス */
/* @written : s.kosugi */
/* @create : 2020/08/19 */
/* */
/*==============================================================================*/
#include "..\..\cSpriteObject.h"
//================================================================================================
// ステージベースクラス
class IStage : public cSpriteObject
{
public:
IStage(IBaseObject* parent, const std::string object_name, const std::string graphic_file_name);
~IStage(void);
// 初期化
void Initialize(void);
// 初期化
// pos : 生成位置
void Initialize(const cVector2& pos);
void Update(void);
IBaseObject* Finalize(void);
// 当たり判定の半径の取得
const inline float GetDist(void) { return m_fDist; };
protected:
// プレイヤーと衝突したかどうかのチェック
void CheckPlayerHit(void);
// プレイヤー衝突時の処理
virtual void HitPlayer(void);
// 当たり判定の半径
float m_fDist;
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cStartButton.h */
/* @brief : スタートボタンクラス */
/* @written : s.kosugi */
/* @create : 2020/07/17 */
/* */
/*==============================================================================*/
#include "..\IButton.h"
// スタートボタンクラス
class cStartButton : public IButton
{
public:
cStartButton(IBaseObject* parent);
void Initialize(void) override;
private:
void Neutral(void) override;
void Trigger(void) override;
void Pressed(void) override;
void Release(void) override;
// 表示優先度
static const int PRIORITY;
// 押されている状態から離れた状態になったかの確認フラグ
bool m_bPressed;
};
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cSoundCtrl.h */
/* @brief : サウンド操作クラス */
/* @written : s.kosugi */
/* @create : 2018/11/30 */
/* */
/*==============================================================================*/
#include "..\BaseObject\IBaseObject.h"
#include "SoundID.h"
//===============================================================================
// サウンド管理クラス
class cSoundCtrl : public IBaseObject
{
public:
// BGMのチャンネル定義
enum class BGMCHANNEL
{
MAIN = 0,
SWAP, // クロスフェードでの入れ替え用チャンネル
NUM
};
void Initialize(void);
void Update(void);
IBaseObject* Finalize(void);
// サウンドの読み込み
// 引数 : id サウンドのID bufnum 同時再生可能数
// 戻り値 : サウンドハンドル
int Load(SOUND_ID id,int bufnum = 3);
// サウンドの読み込み
// 引数 : filename サウンドファイルパス bufnum 同時再生可能数
// 戻り値 : サウンドハンドル
int Load(const std::string& filename,int bufnum = 3);
// 全サウンドの読み込み
void LoadAll( void );
// サウンドの削除処理
void Delete(SOUND_ID id);
void Delete(const std::string& filename);
// サウンドの再生
int Play(SOUND_ID id, bool loop = false);
int Play(const std::string& filename ,bool loop = false);
int BGMPlay(SOUND_ID id, BGMCHANNEL ch = BGMCHANNEL::MAIN);
int BGMPlay(const std::string& filename, BGMCHANNEL ch = BGMCHANNEL::MAIN);
// サウンドの停止
void Stop(SOUND_ID id);
void Stop(const std::string& filename );
void BGMStop(BGMCHANNEL ch = BGMCHANNEL::MAIN);
// マスターボリュームの変更
void ChangeMasterVolume( int vol );
// ボリュームの変更
void ChangeVolume( SOUND_ID id, int vol);
void ChangeVolume( const std::string& filename , int vol );
// BGMのフェードアウトの設定
void FadeOutBgm( unsigned int frame );
// BGMのフェードインの設定
void FadeInBgm( unsigned int frame,SOUND_ID id, BGMCHANNEL ch = BGMCHANNEL::MAIN);
// BGMのクロスフェードの設定
void CrossFadeBgm( unsigned int outframe,unsigned int inframe,SOUND_ID id);
// 周波数の設定
void SetFrequency( SOUND_ID id , int value );
void SetFrequency( const std::string& filename, int value);
// 周波数の取得
int GetFrequency(SOUND_ID id);
int GetFrequency(const std::string& filename);
// 指定したサウンドが再生中かどうかを調べる
bool CheckPlaySound(SOUND_ID id);
bool CheckPlaySound(const std::string& filename);
private:
//--------------------------------------------------------------------------------------
// ファイル読み込み関連
// 読み込みファイル構造体
struct SdLoaded
{
std::string FileName = "";
int SoundHandle = -1;
};
//--------------------------------------------------------------------------------------
// 定数
const int LOADSOUND_FAILED = -1; // LoaSoundMem失敗
const int DEFAULT_MASTER_VOLUME = 100;
// サウンド名テーブル
std::string SOUNDNAME_TABLE[(int)SOUND_ID::MAX] =
{
"data\\sound\\se00.ogg",
"data\\sound\\se01_bom.ogg",
"data\\sound\\se02_shot.ogg",
"data\\sound\\se03_kachi.ogg",
"data\\sound\\se04_laser.ogg",
"data\\sound\\bgm00.ogg",
};
//--------------------------------------------------------------------------------------
enum class BGMSTATE
{
NORMAL = 0,
FADEOUT,
FADEIN,
CROSSFADE,
};
// 読み込み済みサウンドリスト
std::list<SdLoaded> m_listSdLoaded;
// 再生中BGM名
std::string m_sPlayBgmName[(int)BGMCHANNEL::NUM];
// マスターボリューム
int m_nMasterVolume;
// BGMボリュームのフェード値(100分の1デシベル単位)
int m_nBgmVolumeFade[(int)BGMCHANNEL::NUM];
// BGMの状態
BGMSTATE m_eBgmState;
//--------------------------------------------------------------------------------------
// サウンドハンドルの検索
// 戻り値:サウンドハンドル LOADSOUND_FAILED:失敗
int SearchSoundHandle(const std::string& filename);
//--------------------------------------------------------------------------------------
// フェードアウトの更新処理
void UpdateFadeOut( void );
// フェードインの更新処理
void UpdateFadeIn(void);
// クロスフェードの更新処理
void UpdateCrossFade(void);
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cSoundCtrl(void); // 他からの生成を禁止
cSoundCtrl(IBaseObject* parent);
cSoundCtrl(IBaseObject* parent, const std::string& name);
~cSoundCtrl(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cSoundCtrl(const cSoundCtrl& t); // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cSoundCtrl& operator = (const cSoundCtrl& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
static cSoundCtrl& GetInstance(void) {
static cSoundCtrl instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>/*==============================================================================*/
/* */
/* @file title : IEnemy.cpp */
/* @brief : 敵ベースクラス */
/* @written : s.kosugi */
/* @create : 2020/06/16 */
/* */
/*==============================================================================*/
#include "IEnemy.h"
#include "cGame.h"
#include "ScoreManager/cScoreManager.h"
#include "..\Effect\cEffectManager.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif
//==========================================================================================
// 定数
//==========================================================================================
const int IEnemy::AREAOUT_ADJUST = 100; // エリアアウト距離
//==========================================================================================
// コンストラクタ
//==========================================================================================
IEnemy::IEnemy(IBaseObject * parent, const std::string object_name, const std::string graphic_file_name)
: cSpriteObject(parent, object_name, graphic_file_name)
, m_vPosUp(0.0f, 0.0f)
, m_fDist(0.0f)
, m_eState(STATE::NORMAL)
, m_nHp(1)
, m_nScore(1)
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
IEnemy::~IEnemy(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void IEnemy::Initialize(void)
{
Initialize({ 0.0f,0.0f });
}
//==========================================================================================
// 初期化
//==========================================================================================
void IEnemy::Initialize(const cVector2 & pos)
{
m_vPos = pos;
cSpriteObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void IEnemy::Update(void)
{
// 状態別処理
switch (m_eState)
{
case STATE::NORMAL:
Normal();
break;
case STATE::DEAD:
Dead();
break;
}
// 移動処理
m_vPos += m_vPosUp;
// エリアアウトしたら敵を削除する
AreaOutAllProc();
#ifdef DEBUG
// 当たり判定の描画
cDebugFunc::GetInstance().RegistDrawCircle(m_vPos, m_fDist, 0x77ff0000);
#endif
cSpriteObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject* IEnemy::Finalize(void)
{
cSpriteObject::Finalize();
return this;
}
//=================================================================
// 通常状態
//=================================================================
void IEnemy::Normal(void)
{
}
//=================================================================
// 死亡状態
//=================================================================
void IEnemy::Dead(void)
{
m_vPosUp = {0.0f,0.0f};
int alpha = GetAlpha();
alpha -= 8;
if (alpha <= 0)
{
DeleteObject();
}
else
{
SetAlpha((unsigned int)alpha);
}
}
//=================================================================
// 画面外配置処理
//=================================================================
IEnemy::DIRECTION IEnemy::ArrangeOffScreen(void)
{
DIRECTION direction = DIRECTION::LEFT;
cGame* game = (cGame*)GetRoot();
// 画面端から出すようにする為どの方向から出現するかをランダムで決定する
switch (cGame::Random(0, 3))
{
case 0:
// 左側の場合
m_vPos.x = -GetSpriteSize().x / 2.0f;
direction = DIRECTION::LEFT;
break;
case 1:
// 右側の場合
m_vPos.x = game->GetWindowWidth() + GetSpriteSize().x;
direction = DIRECTION::RIGHT;
break;
case 2:
// 上側の場合
m_vPos.y = -GetSpriteSize().y / 2.0f;
direction = DIRECTION::TOP;
break;
case 3:
// 下側の場合
m_vPos.y = game->GetWindowHeight() + GetSpriteSize().y;
direction = DIRECTION::BOTTOM;
break;
}
return direction;
}
//==========================================================================================
// プレイヤーへ向かう移動量を設定する
// speed : 基本移動力
//==========================================================================================
void IEnemy::GotoPlayer(float speed)
{
// プレイヤーに向かって移動
cSpriteObject* pc = (cSpriteObject*)GetParent()->FindSibling("Player");
if (pc)
{
cVector2 pcPos = pc->GetPos();
float angle = m_vPos.CalcTwoPointAngle(pcPos);
// 移動量を決定
m_vPosUp.x = cos(DEG_TO_RAD(angle)) * speed;
m_vPosUp.y = sin(DEG_TO_RAD(angle)) * speed;
}
}
//==========================================================================================
// ダメージ処理
//==========================================================================================
void IEnemy::Damage(void)
{
m_nHp--;
if (m_nHp <= 0)
{
m_eState = STATE::DEAD;
m_vPosUp.x = m_vPosUp.y = 0.0f;
// 加点処理
cScoreManager* sm = (cScoreManager*)GetRoot()->FindChild("ScoreManager");
sm->AddScore(m_nScore);
// エフェクト再生
cEffectManager* ef = (cEffectManager*)GetRoot()->FindChild("EffectManager");
ef->Create(EFFECT_ID::BOM,m_vPos);
}
}
//==========================================================================================
// 左エリアアウト処理
//==========================================================================================
void IEnemy::AreaOutLeftProc(void)
{
if (m_vPos.x + GetSpriteSize().x / 2 < ((cGame*)GetRoot())->GetPlayArea().left - AREAOUT_ADJUST)
{
DeleteObject();
}
}
//==========================================================================================
// 上エリアアウト処理
//==========================================================================================
void IEnemy::AreaOutUpProc(void)
{
if (m_vPos.y + GetSpriteSize().y / 2 < ((cGame*)GetRoot())->GetPlayArea().top - AREAOUT_ADJUST)
{
DeleteObject();
}
}
//==========================================================================================
// 右エリアアウト処理
//==========================================================================================
void IEnemy::AreaOutRightProc(void)
{
if (m_vPos.x - GetSpriteSize().x / 2 > ((cGame*)GetRoot())->GetPlayArea().right + AREAOUT_ADJUST)
{
DeleteObject();
}
}
//==========================================================================================
// 下エリアアウト処理
//==========================================================================================
void IEnemy::AreaOutBottomProc(void)
{
if (m_vPos.y - GetSpriteSize().y / 2 > ((cGame*)GetRoot())->GetPlayArea().bottom + AREAOUT_ADJUST)
{
DeleteObject();
}
}
//==========================================================================================
// 全方向エリアアウト処理
//==========================================================================================
void IEnemy::AreaOutAllProc(void)
{
AreaOutLeftProc();
AreaOutUpProc();
AreaOutRightProc();
AreaOutBottomProc();
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cPlayer.cpp */
/* @brief : プレイヤークラス */
/* @written : s.kosugi */
/* @create : 2018/12/03 */
/* */
/*==============================================================================*/
#include "cPlayer.h"
#include "Input\Touch\cTouch.h"
#include "cGame.h"
#include "SoundCtrl\cSoundCtrl.h"
#include "BaseObject/GameObject/Bullet/cBulletManager.h"
#include "BaseObject/GameObject/Enemy/cEnemyManager.h"
#include "BaseObject/GameObject/Effect/cEffectManager.h"
#include "BaseObject/GameObject/Effect/IEffect.h"
#include "SceneManager/cSceneManager.h"
#include "Utility/Timer/cTimer.h"
#ifdef DEBUG
#include "..\..\..\DebugFunc\cDebugFunc.h"
#include <sstream>
#endif // DEBUG
//==========================================================================================
// 定数
//==========================================================================================
const float cPlayer::NORMAL_BUL_SPD = 10.0f;
const float cPlayer::NORMAL_BUL_INTERVAL = 0.2f;
const float cPlayer::BUL_FIRE_POS = 80.0f;
const int cPlayer::PRIORITY = 200;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cPlayer::cPlayer(IBaseObject * parent)
: cSpriteObject(parent, "Player", "data\\graphic\\Turret.png")
, m_fDist( 1.0f )
, m_eState(STATE::NORMAL)
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cPlayer::~cPlayer(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cPlayer::Initialize(void)
{
cGame* game = (cGame*)GetRoot();
m_vPos = { game->GetWindowCenter().x,game->GetWindowCenter().y };
SetPriority(PRIORITY);
// 当たり判定の設定
m_fDist = GetSpriteSize().x / 3.0f;
// 弾発射間隔タイマーの生成
cTimer* timer = CreateObject<cTimer>(this,"BulletTimer");
timer->Setup(NORMAL_BUL_INTERVAL);
cSpriteObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cPlayer::Update(void)
{
switch (m_eState)
{
case STATE::NORMAL: Normal(); break;
case STATE::LASER: Laser(); break;
case STATE::DEAD: Dead(); break;
default: break;
}
cSpriteObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject* cPlayer::Finalize(void)
{
cSpriteObject::Finalize();
return this;
}
//==========================================================================================
// 通常状態
//==========================================================================================
void cPlayer::Normal(void)
{
cTouch* touch = (cTouch*)GetRoot()->FindChild("Touch");
cTimer* bulTimer = (cTimer*)FindChild("BulletTimer");
cSoundCtrl* sc = (cSoundCtrl*)GetRoot()->FindChild("SoundCtrl");
POINT pt;
// タッチ座標を取得
if (touch->GetTouchPos(0, pt))
{
// 自機の回転
cVector2 vec(pt);
m_fAngle = m_vPos.CalcTwoPointAngle(vec);
// 弾の発射間隔を過ぎていたら発射する
if (bulTimer && bulTimer->Finished())
{
bulTimer->Reset();
cBulletManager* bm = (cBulletManager*)FindSibling("BulletManager");
// 発射位置の調整
cVector2 firePos;
firePos.x = m_vPos.x + cos(DEG_TO_RAD(m_fAngle)) * BUL_FIRE_POS;
firePos.y = m_vPos.y + sin(DEG_TO_RAD(m_fAngle)) * BUL_FIRE_POS;
bm->Create(BULLET_ID::NORMAL, firePos, m_fAngle, NORMAL_BUL_SPD);
// エフェクトの生成
cEffectManager* em = (cEffectManager*)GetRoot()->FindChild("EffectManager");
IEffect* effect = em->Create(EFFECT_ID::MUZZLE, firePos);
effect->SetAngle(m_fAngle - 90.0f);
// 音声の再生
if (sc) sc->Play(SOUND_ID::SHOT);
}
}
// 2点タッチが押されたらレーザー状態にする
if (touch->GetTouchPos(1, pt))
{
StartLaser();
}
// 敵との当たり判定処理
CheckHitEnemy();
#ifdef DEBUG
cDebugFunc::GetInstance().RegistDrawCircle(m_vPos, m_fDist, 0x77ff0000);
#endif
}
//==========================================================================================
// レーザー発射状態
//==========================================================================================
void cPlayer::Laser(void)
{
cTimer* timer = (cTimer*)FindChild("LaserTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this, "LaserTimer");
timer->Setup(3.0f);
}
// タイマーが終わったので通常状態に戻す
if (timer->Finished())
{
m_eState = STATE::NORMAL;
timer->DeleteObject();
// レーザーエフェクトを削除する
cEffectManager* em = (cEffectManager*)GetRoot()->FindChild("EffectManager");
if (em) em->DeleteLaserEffect();
}
// 敵との当たり判定処理
CheckHitEnemy();
#ifdef DEBUG
cDebugFunc::GetInstance().RegistDrawCircle(m_vPos, m_fDist, 0x77ff0000);
#endif
}
//==========================================================================================
// 死亡状態
//==========================================================================================
void cPlayer::Dead(void)
{
cTimer* timer = (cTimer*)FindChild("DeadTimer");
// レーザーエフェクトを削除する
cEffectManager* em = (cEffectManager*)GetRoot()->FindChild("EffectManager");
if (em) em->DeleteLaserEffect();
if (!timer)
{
timer = CreateObject<cTimer>(this, "DeadTimer");
timer->Setup(2.0f);
}
// 死亡タイマーが経過したらシーンチェンジ
if (timer->Finished())
{
cSceneManager* sm = (cSceneManager*)GetRoot()->FindChild("SceneManager");
sm->ChangeSceneUniTrans(SCENE_ID::RESULT, "data\\graphic\\rule_00.png");
}
}
//==========================================================================================
// レーザー開始処理
//==========================================================================================
void cPlayer::StartLaser(void)
{
cGame* game = (cGame*)GetRoot();
cSoundCtrl* sc = (cSoundCtrl*)GetRoot()->FindChild("SoundCtrl");
// 自機をレーザー発射状態にする
m_eState = STATE::LASER;
// 音声の再生
if (sc) sc->Play(SOUND_ID::LASER);
// 発射位置の調整
cVector2 firePos;
cEffectManager* em = (cEffectManager*)GetRoot()->FindChild("EffectManager");
firePos.x = m_vPos.x + cos(DEG_TO_RAD(m_fAngle)) * BUL_FIRE_POS;
firePos.y = m_vPos.y + sin(DEG_TO_RAD(m_fAngle)) * BUL_FIRE_POS;
// レーザー始点エフェクトの作成
IEffect* effect = em->Create(EFFECT_ID::LASER_START, firePos);
effect->SetAngle(m_fAngle);
effect->SetLoop(true);
// レーザー本体エフェクトの作成
for (int i = 1;; i++)
{
firePos.x = m_vPos.x + cos(DEG_TO_RAD(m_fAngle)) * BUL_FIRE_POS + cos(DEG_TO_RAD(m_fAngle)) * i * 128;
firePos.y = m_vPos.y + sin(DEG_TO_RAD(m_fAngle)) * BUL_FIRE_POS + sin(DEG_TO_RAD(m_fAngle)) * i * 128;
// レーザーの弾の発生
cBulletManager* bm = (cBulletManager*)FindSibling("BulletManager");
bm->Create(BULLET_ID::LASER,firePos,m_fAngle,0.0f);
effect = em->Create(EFFECT_ID::LASER, firePos);
effect->SetAngle(m_fAngle);
// レーザーはループエフェクト
effect->SetLoop(true);
if (firePos.x + 128 < 0.0f ||
firePos.x - 128 > game->GetWindowWidth() ||
firePos.y + 128 < 0.0f ||
firePos.y - 128 > game->GetWindowHeight())
{
// 範囲外に出たら生成をやめる
break;
}
}
}
//==========================================================================================
// 当たり判定処理
//==========================================================================================
void cPlayer::CheckHitEnemy(void)
{
cEnemyManager* em = (cEnemyManager*)GetParent()->FindSibling("EnemyManager");
if (em)
{
// 当たったら死亡処理
if (em->CheckHit(m_vPos, m_fDist))
{
m_eState = STATE::DEAD;
m_bVisible = false;
// エフェクト再生
cEffectManager* ef = (cEffectManager*)GetRoot()->FindChild("EffectManager");
ef->Create(EFFECT_ID::BOM, m_vPos);
}
}
}<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cSurfaceObject.h */
/* @brief : サーフェイスオブジェクト */
/* @written : s.kosugi */
/* @create : 2020/03/03 */
/* */
/*==============================================================================*/
#include "IBaseObject.h"
#include "DrawCtrl/Surface/cSurface.h"
//================================================================================================
// 描画オブジェクト
// 1クラスにつき1つのサーフェイスを持ちたい場合に使用する。
class cSurfaceObject : public IBaseObject, public cSurface
{
public:
//---------------------------------------------
// コンストラクタ
// parent : 親オブジェクト
// name : オブジェクト名
// width : サーフェイスの横幅
// height : サーフェイスの高さ
// beginPriority : サーフェイスに含める開始の描画優先度
// endPriority : サーフェイスに含める終了の描画優先度
// alpha : 透明度を有効にするかどうか (TRUE : 有効 )
cSurfaceObject(IBaseObject* parent, const std::string& objectname, int width, int height, int beginPriority, int endPriority, int alpha);
~cSurfaceObject(void);
virtual void Initialize(void);
virtual void Initialize( const cVector2& pos );
virtual void Update(void);
virtual IBaseObject* Finalize(void);
};
//================================================================================================
//================================================================================================
// オブジェクト生成関数
//================================================================================================
// サーフェイスオブジェクト生成
// 親オブジェクトとオブジェクトとサーフェイスに必要な項目を指定する。
// parent : 親オブジェクト
// name : オブジェクト名
// width : サーフェイスの横幅
// height : サーフェイスの高さ
// beginPriority : サーフェイスに含める開始の描画優先度
// endPriority : サーフェイスに含める終了の描画優先度
// alpha : 透明度を有効にするかどうか (TRUE : 有効 )
// return : 生成したオブジェクト
template <class T> T* CreateSurfaceObject(IBaseObject* parent, const std::string& name, int width, int height, int beginPriority, int endPriority, int alpha)
{
// ゲームオブジェクト生成
T* t = NEW T(parent, name, width, height, beginPriority, endPriority, alpha);
// 親がいればリストに追加
if (parent) parent->AddChild(t);
// オブジェクトの返却
return t;
}
template <class T> T* CreateSurfaceObject(IBaseObject* parent, const std::string& name, int width, int height, int beginPriority, int endPriority)
{
// ゲームオブジェクト生成
T* t = NEW T(parent, name, width, height, beginPriority, endPriority, TRUE);
// 親がいればリストに追加
if (parent) parent->AddChild(t);
// オブジェクトの返却
return t;
}
<file_sep>/*==============================================================================*/
/* */
/* @file title : cTitle.cpp */
/* @brief : タイトルシーン */
/* @written : s.kosugi */
/* @create : 2018/12/02 */
/* */
/*==============================================================================*/
#include "..\..\..\cGame.h"
#include "cTitle.h"
#include "..\..\cSceneManager.h"
#include "..\..\..\BaseObject\cSpriteObject.h"
#include <DxLib.h>
#include "DataManager/cDataManager.h"
#include "BaseObject/GameObject/UI/cUIManager.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif
//==========================================================================================
// コンストラクタ
//==========================================================================================
cTitle::cTitle(IBaseObject * parent)
: IBaseScene(parent, "Title")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cTitle::~cTitle(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cTitle::Initialize(void)
{
// 背景スプライトの生成
cSpriteObject* obj = CreateDrawObject<cSpriteObject>(this, "TitleBack", "data\\graphic\\GameMainBack.png");
obj->SetPriority(-100);
obj->SetPos((float)cGame::GetInstance().GetWindowWidth() / 2, (float)cGame::GetInstance().GetWindowHeight() / 2);
// UI管理の生成
cUIManager* um = CreateObject<cUIManager>(this);
IBaseObject::Initialize();
// タイトルロゴの生成
um->Create(UIID::TITLE_LOGO);
// タッチしてスタートの文字生成
um->Create(UIID::TOUCH_FONT);
}
//==========================================================================================
// 更新
//==========================================================================================
void cTitle::Update(void)
{
IBaseObject::Update();
// ゲームメインシーンへ
if (1 <= GetTouchInputNum())
{
cSceneManager* sm = (cSceneManager*)GetParent();
sm->ChangeSceneUniTrans(SCENE_ID::GAMEMAIN,"data\\graphic\\rule_00.png");
}
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject* cTitle::Finalize(void)
{
IBaseObject::Finalize();
return this;
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cGameMain.h */
/* @brief : ゲームメインシーン */
/* @written : s.kosugi */
/* @create : 2018/12/02 */
/* */
/*==============================================================================*/
#include "..\IBaseScene.h"
//================================================================================================
// ゲームメインシーン
class cGameMain : public IBaseScene
{
public:
cGameMain(IBaseObject* parent);
~cGameMain(void);
void Initialize(void);
void Update(void);
IBaseObject* Finalize(void);
int GetOverTimeMinute(void);
int GetOverTimeSecond(void);
// ゲームメイン状態
enum class STATE {
START,
MAIN,
CLEAR,
OVER,
};
private:
static const float TIME_OVER_LIMIT;
static const float GOAL_TIME;
static const float DEAD_TIME;
static const float START_TIME;
// ゲームメイン状態
STATE m_eState;
// 状態別処理
// 開始
void Start(void);
// メイン
void Main(void);
// クリア
void Clear(void);
// ゲームオーバー
void Over(void);
};
//================================================================================================<file_sep>/*==============================================================================*/
/* */
/* @file title : cTitleCursol.cpp */
/* @brief : タイトルカーソルクラス */
/* @written : s.kosugi */
/* @create : 2020/07/22 */
/* */
/*==============================================================================*/
#include "cTitleCursol.h"
#include "Utility/Timer/cTimer.h"
#include "Utility/Easing/Easing.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cTitleCursol::PRIORITY = 1000;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cTitleCursol::cTitleCursol(IBaseObject * parent)
: cSpriteObject(parent, "TitleCursol", "data\\graphic\\cursol.png")
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cTitleCursol::Initialize(void)
{
cSpriteObject::Initialize();
cTimer* timer = CreateObject<cTimer>(this, "CursolTimer");
timer->Setup(1.5f);
SetPriority(PRIORITY);
}
//==========================================================================================
// 更新
//==========================================================================================
void cTitleCursol::Update(void)
{
cTimer* timer = (cTimer*)FindChild("CursolTimer");
if (timer)
{
if (timer->Finished()) timer->Reset();
float addPos;
addPos = fabs(sin(DEG_TO_RAD(Easing::Linear(timer->GetTime(), timer->GetLimit(), 360.0f, 0.0f))) * 30.0f);
if (m_fAngle > 0) addPos = -addPos;
m_vPos.x = m_vOriginPos.x + addPos;
}
cSpriteObject::Update();
}
//==========================================================================================
// 初期設定
//==========================================================================================
void cTitleCursol::Setup(const cVector2 & pos, float angle)
{
m_vOriginPos = m_vPos = pos;
m_fAngle = angle;
}
<file_sep>/*==============================================================================*/
/* */
/* @file title : cTitle.cpp */
/* @brief : タイトルシーン */
/* @written : s.kosugi */
/* @create : 2018/12/02 */
/* */
/*==============================================================================*/
#include "..\..\..\cGame.h"
#include "cTitle.h"
#include "..\..\cSceneManager.h"
#include "..\..\..\BaseObject\cSpriteObject.h"
#include <DxLib.h>
#include "DataManager/cDataManager.h"
#include "BaseObject/GameObject/UI/cUIManager.h"
#include "BaseObject/GameObject/GameStartObject/cTitleCursol.h"
#include "SoundCtrl/cSoundCtrl.h"
//==========================================================================================
// コンストラクタ
//==========================================================================================
cTitle::cTitle(IBaseObject * parent)
: IBaseScene(parent, "Title")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cTitle::~cTitle(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cTitle::Initialize(void)
{
// ゲームクラスの取得
cGame* game = (cGame*)GetRoot();
// 背景スプライトの生成
cSpriteObject* obj = CreateDrawObject<cSpriteObject>(this, "BackGround", "data\\graphic\\background.png");
obj->SetPriority(-101);
obj->SetPos((float)game->GetWindowWidth() / 2, (float)game->GetWindowHeight() / 2);
// タイトルロゴの生成
obj = CreateDrawObject<cSpriteObject>(this, "TitleBack", "data\\graphic\\title.png");
obj->SetPriority(-100);
obj->SetPos((float)game->GetWindowWidth() / 2, (float)game->GetWindowHeight() / 2);
// UI管理の生成
cUIManager* ui = CreateObject<cUIManager>(this);
cSpriteObject* button = ui->Create(UIID::START_BUTTON);
// BGMの再生
cSoundCtrl* sc = (cSoundCtrl*)GetRoot()->FindChild("SoundCtrl");
if (sc) sc->BGMPlay(SOUND_ID::BGM);
IBaseObject::Initialize();
//------------------------------------------------------------------
// ボタンの位置を基準にカーソルを配置
cTitleCursol* cursol = CreateObject<cTitleCursol>(this);
cursol->Initialize();
cVector2 buttonPos = button->GetPos();
buttonPos.x -= 250.0f;
cursol->Setup(buttonPos, 90.0f);
buttonPos = button->GetPos();
cursol = CreateObject<cTitleCursol>(this);
cursol->Initialize();
buttonPos.x += 250.0f;
cursol->Setup(buttonPos,-90.0f);
//------------------------------------------------------------------
}
//==========================================================================================
// 更新
//==========================================================================================
void cTitle::Update(void)
{
IBaseObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject* cTitle::Finalize(void)
{
IBaseObject::Finalize();
return this;
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cPlayer.h */
/* @brief : プレイヤークラス */
/* @written : s.kosugi */
/* @create : 2018/12/03 */
/* */
/*==============================================================================*/
#include "..\..\cSpriteObject.h"
//================================================================================================
// プレイヤークラス
class cPlayer : public cSpriteObject
{
public:
cPlayer(IBaseObject* parent);
~cPlayer(void);
void Initialize(void);
void Update(void);
IBaseObject* Finalize(void);
private:
// プレイヤー状態
enum STATE
{
NORMAL,
LASER,
DEAD
};
// 通常弾速度
static const float NORMAL_BUL_SPD;
// 弾発射間隔
static const float NORMAL_BUL_INTERVAL;
// 弾発射位置差分
static const float BUL_FIRE_POS;
// 表示優先度
static const int PRIORITY;
// 当たり判定の半径
float m_fDist;
// プレイヤー状態
STATE m_eState;
// 通常状態
void Normal(void);
// レーザー発射状態
void Laser(void);
// 死亡状態
void Dead(void);
// レーザー発射処理
void StartLaser(void);
// 敵との当たり判定処理
void CheckHitEnemy(void);
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cSprite.h */
/* @brief : スプライトクラス */
/* @written : s.kosugi */
/* @create : 2018/09/17 */
/* */
/*==============================================================================*/
#include <DxLib.h>
#include <iostream>
#include "..\IDrawBase.h"
//================================================================================================
// 描画スプライトクラス
class cSprite : public IDrawBase
{
public:
cSprite(const std::string& filename);
~cSprite();
void Initialize(void);
void Update(void);
void Finalize(void);
//---------------------------------------------------------------------------------------------
// Getter
POINT GetSpriteSize(void);
inline RECT GetSrcRect(void) { return m_SrcRect; };
inline cVector2 GetCenter(void) { return m_vCenter; };
inline cVector2 GetAnchor(void) { return m_vAnchor; };
inline int GetBlendMode(void) { return m_BlendMode; };
inline cVector2 GetScale(void) { return m_vScale; };
inline float GetAngle(void) { return m_fAngle; };
//---------------------------------------------------------------------------------------------
// Setter
void SetSrcRect(RECT rect);
void SetSrcRect(int Startx, int Starty, int Sizex, int Sizey);
inline void SetCenter(cVector2 vec) { m_vCenter = vec; };
inline void SetCenter(float x, float y) {m_vCenter.x = x; m_vCenter.y = y;};
inline void SetAnchor(cVector2 vec) { m_vAnchor = vec; };
inline void SetAnchor(float x, float y) { m_vAnchor.x = x; m_vAnchor.y = y; };
inline void SetBlendMode(int mode) {m_BlendMode = mode;};
inline void SetScale(cVector2 scale) { m_vScale = scale; };
inline void SetScale(float scale) { m_vScale.x = m_vScale.y = scale; };
inline void SetAngle(float angle) { m_fAngle = angle; };
protected:
//---------------------------------------------------------------------------------------------
// スプライト表示情報
RECT m_SrcRect; // 描画矩形の始点と終点
cVector2 m_vCenter; // 画像の中心位置
cVector2 m_vAnchor; // 回転と拡大の中心位置、vCenterからの差分がvAnchorとなる
int m_BlendMode; // 描画ブレンドモード
cVector2 m_vScale; // 拡大縮小
float m_fAngle; // スプライトの回転角度
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cGoFont.h */
/* @brief : Go文字クラス */
/* @written : s.kosugi */
/* @create : 2020/07/22 */
/* */
/*==============================================================================*/
#include "BaseObject/cSpriteObject.h"
// Go文字クラス
class cGoFont : public cSpriteObject
{
public:
cGoFont(IBaseObject* parent);
void Initialize(void);
void Update(void);
private:
// 表示優先度
static const int PRIORITY;
};
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : IEffect.h */
/* @brief : エフェクト基底クラス */
/* @written : s.kosugi */
/* @create : 2020/06/22 */
/* */
/*==============================================================================*/
#include "..\..\cSpriteObject.h"
//================================================================================================
// エフェクト基底クラス
class IEffect : public cSpriteObject
{
public:
IEffect(IBaseObject* parent, const std::string object_name, const std::string graphic_file_name);
// 初期化
void Initialize(void);
void Initialize(const cVector2& pos);
void Update(void);
IBaseObject* Finalize(void);
inline POINT GetAnimeSize(void) { return m_ptSize; };
inline short GetColumnNum(void) { return m_nColNum; };
inline short GetRowNum(void) { return m_nMaxAnimNum / m_nColNum; };
inline short GetMaxAnimNum(void) { return m_nMaxAnimNum; };
inline short GetAnimNo(void) { return m_nAnimNo; };
inline float GetFrameTime(void) { return m_fFrameTime; };
inline bool IsLoop(void) { return m_bLoop; };
void SetAnimNo(short animeNo);
void SetFrameTime(float time);
inline void SetLoop(bool loop) { m_bLoop = loop; };
// アニメーションの設定
void SetupAnime(const POINT& size, short col, short maxNum, float frameTime);
protected:
POINT m_ptSize; // 1アニメーション当たりの大きさ
short m_nColNum; // 横列の枚数
short m_nMaxAnimNum; // 最大アニメーション枚数
short m_nAnimNo; // 現在のアニメーション番号
float m_fFrameTime; // 1フレーム当たりの時間
bool m_bLoop; // ループ設定
// 現在のアニメーション番号にスプライトをあわせる
void UpdateAnime(void);
};
//================================================================================================<file_sep>/*==============================================================================*/
/* */
/* @file title : IEffect.cpp */
/* @brief : エフェクトオブジェクト */
/* @written : s.kosugi */
/* @create : 2020/06/22 */
/* */
/*==============================================================================*/
#include "IEffect.h"
#include "cGame.h"
#include "Utility/Timer/cTimer.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif
//==========================================================================================
// コンストラクタ
//==========================================================================================
IEffect::IEffect(IBaseObject* parent, const std::string object_name, const std::string graphic_file_name) :
cSpriteObject(parent, object_name, graphic_file_name)
, m_ptSize({ 64,64 })
, m_nColNum(1)
, m_nMaxAnimNum(1)
, m_nAnimNo(0)
, m_fFrameTime(0.05f)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void
IEffect::
Initialize(void)
{
cSpriteObject::Initialize();
}
//==========================================================================================
// 初期化
//==========================================================================================
void IEffect::Initialize(const cVector2& pos)
{
m_vPos = pos;
Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void IEffect::Update(void)
{
cTimer* timer = (cTimer*)FindChild("AnimeTimer");
if (timer && timer->Finished())
{
m_nAnimNo++;
// アニメーションが最大枚数を超えたら削除
if (m_nAnimNo >= m_nMaxAnimNum)
{
DeleteObject();
return;
}
// アニメーション更新
UpdateAnime();
timer->Reset();
}
cSpriteObject::Update();
}
//==========================================================================================
// 解放
//==========================================================================================
IBaseObject* IEffect::Finalize(void)
{
cSpriteObject::Finalize();
return this;
}
//==========================================================================================
// アニメーション番号のセット
//==========================================================================================
void IEffect::SetAnimNo(short animeNo)
{
if (m_nMaxAnimNum > animeNo)
{
m_nAnimNo = animeNo;
// アニメーション更新
UpdateAnime();
// アニメーションが切り替わったらタイマーをリセット
cTimer* timer = (cTimer*)FindChild("AnimeTimer");
if (timer) timer->Reset();
}
else
{
#ifdef DEBUG
cDebugFunc::GetInstance().PushDebugLog("error : SetAnime (MaxAnime < animeNo)");
#endif
}
}
//==========================================================================================
// 1フレーム当たりの時間のセット
//==========================================================================================
void IEffect::SetFrameTime(float time)
{
}
//==========================================================================================
// アニメーション初期設定
//==========================================================================================
void IEffect::SetupAnime(const POINT & size, short col, short maxNum, float frameTime)
{
m_ptSize = size;
m_nColNum = col;
m_nMaxAnimNum = maxNum;
m_fFrameTime = frameTime;
m_SrcRect = { 0,0,size.x,size.y };
m_vCenter.x = size.x / 2.0f;
m_vCenter.y = size.y / 2.0f;
// アニメーションタイマー作成
cTimer* timer = (cTimer*)FindChild("AnimeTimer");
if (!timer)
{
timer = (cTimer*)CreateObject<cTimer>(this, "AnimeTimer");
}
timer->Setup(m_fFrameTime);
}
//==========================================================================================
// 現在のアニメーション番号にスプライトをあわせる
//==========================================================================================
void IEffect::UpdateAnime(void)
{
m_SrcRect.left = (m_nAnimNo * m_ptSize.x) % (m_ptSize.x * m_nColNum);
m_SrcRect.right = m_SrcRect.left + m_ptSize.x;
m_SrcRect.top = ((m_nAnimNo * m_ptSize.x) / (m_ptSize.x * m_nColNum)) * m_ptSize.y;
m_SrcRect.bottom = m_SrcRect.top + m_ptSize.y;
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : IEnemy.h */
/* @brief : 敵ベースクラス */
/* @written : s.kosugi */
/* @create : 2020/06/16 */
/* */
/*==============================================================================*/
#include "..\..\cSpriteObject.h"
//================================================================================================
// 敵ベースクラス
class IEnemy : public cSpriteObject
{
public:
enum class STATE
{
NORMAL, // 通常状態
DEAD, // 死亡状態
};
enum class DIRECTION
{
LEFT,
RIGHT,
TOP,
BOTTOM,
};
public:
IEnemy(IBaseObject* parent, const std::string object_name, const std::string graphic_file_name);
~IEnemy(void);
// 初期化
void Initialize(void);
// 初期化
// pos : 生成位置
void Initialize(const cVector2& pos);
void Update(void);
IBaseObject* Finalize(void);
// ダメージ
void Damage(void);
// 当たり判定距離の取得
inline const float GetDist(void) { return m_fDist; };
// 状態の取得
inline const STATE GetState(void) { return m_eState; };
protected:
cVector2 m_vPosUp; // 移動ベクトル
float m_fDist; // 当たり判定の半径
STATE m_eState; // 状態
short m_nHp; // 耐久力
short m_nScore; // 獲得スコア
// エリアアウト処理
virtual void AreaOutLeftProc(void);
virtual void AreaOutUpProc(void);
virtual void AreaOutRightProc(void);
virtual void AreaOutBottomProc(void);
virtual void AreaOutAllProc(void);
// 状態別処理
virtual void Normal(void);
virtual void Dead(void);
// 画面外配置処理
// 戻り値 : 配置方向
DIRECTION ArrangeOffScreen(void);
// プレイヤーへ向かう移動量を設定する
// speed : 基本移動力
void GotoPlayer(float speed);
static const int AREAOUT_ADJUST; // エリアアウト距離
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cTransitionObject.h */
/* @brief : トランジションオブジェクト */
/* @written : s.kosugi */
/* @create : 2020/02/12 */
/* */
/*==============================================================================*/
#include "IBaseObject.h"
#include "..\DrawCtrl\Transition\cTransition.h"
#include "..\DrawCtrl\Sprite\cSprite.h"
//================================================================================================
// 描画オブジェクト
// 1クラスにつき1つのスプライトを持ちたい場合に使用する。
class cTransitionObject : public IBaseObject, public cTransition
{
public:
//---------------------------------------------
// コンストラクタ
// parent : 親オブジェクト
// name : オブジェクト名
// ruleFIlename : ルール画像ファイル名
// spriteFileName : スプライト画像のファイル名
// dir : トランジション方向
// transtime : トランジション時間
cTransitionObject(IBaseObject* parent, const std::string& objectname, const std::string& ruleFilename, const std::string& spriteFileName, TransDirection dir, float transtime);
//---------------------------------------------
// コンストラクタ
// parent : 親オブジェクト
// name : オブジェクト名
// ruleFIlename : ルール画像ファイル名
// transObj : 遷移先オブジェクト
// dir : トランジション方向
// transtime : トランジション時間
cTransitionObject(IBaseObject* parent, const std::string& objectname, const std::string& ruleFilename, IDrawBase* pTransObj, TransDirection dir, float transtime);
~cTransitionObject(void);
virtual void Initialize(void);
virtual void Initialize(const cVector2& pos);
virtual void Update(void);
virtual IBaseObject* Finalize(void);
private:
cSprite* m_pSprite; // 画像クラスへのポインタ
};
//================================================================================================
//================================================================================================
// オブジェクト生成関数
//================================================================================================
// トランジションオブジェクト生成
// 親オブジェクトとオブジェクトとトランジションに必要な項目を指定する。
// parent : 親オブジェクト
// name : オブジェクト名
// ruleFIlename : ルール画像ファイル名
// spriteFileName : スプライト画像のファイル名
// dir : トランジション方向
// transtime : トランジション時間(秒)
// return : 生成したオブジェクト
template <class T> T* CreateTransitionObject(IBaseObject* parent, const std::string& name, const std::string& ruleFilename, const std::string& spriteFileName, cTransition::TransDirection dir, float transtime)
{
// ゲームオブジェクト生成
T* t = NEW T(parent, name, ruleFilename, spriteFileName, dir, transtime);
// 親がいればリストに追加
if (parent) parent->AddChild(t);
// オブジェクトの返却
return t;
}
// トランジションオブジェクト生成
// 親オブジェクトとオブジェクトとトランジションに必要な項目を指定する。
// parent : 親オブジェクト
// name : オブジェクト名
// ruleFIlename : ルール画像ファイル名
// 遷移先画像ポインタ
// dir : トランジション方向
// transtime : トランジション時間
// return : 生成したオブジェクト
template <class T> T* CreateTransitionObject(IBaseObject* parent, const std::string& name, const std::string& ruleFilename, IDrawBase* pTransObj, cTransition::TransDirection dir, float transtime)
{
// ゲームオブジェクト生成
T* t = NEW T(parent, name, ruleFilename, pTransObj, dir, transtime);
// 親がいればリストに追加
if (parent) parent->AddChild(t);
// オブジェクトの返却
return t;
}
<file_sep>/*==============================================================================*/
/* */
/* @file title : cTouch.cpp */
/* @brief : タッチ入力クラス */
/* @written : s.kosugi */
/* @create : 2019/07/22 */
/* */
/*==============================================================================*/
#include "cTouch.h"
#include "Utility/Vector/cVector2.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#include <sstream>
#endif
//==========================================================================================
// 初期化
//==========================================================================================
void cTouch::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "Touch";
m_mapTouchPoint.clear();
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cTouch::Update(void)
{
//--------------------------------------------------------------------------------------
// タッチ情報取得前更新
int touchNum = GetTouchInputNum();
// タッチされなかった状態を判定するために一旦タッチ状態をダミーにする
if (!m_mapTouchPoint.empty())
{
for (auto it = m_mapTouchPoint.begin(); it != m_mapTouchPoint.end(); it++)
{
if ((*it).second.state != TOUCH_STATE::RELEASE)
{
(*it).second.state = TOUCH_STATE::NONE;
} else
{
// 前フレームでRELEASE状態のタッチは削除する
it = m_mapTouchPoint.erase(it);
if( it == m_mapTouchPoint.end() ) break;
}
}
}
//--------------------------------------------------------------------------------------
// タッチ情報更新
for (int i = 0;i < touchNum;i++)
{
int x, y, id,dev;
GetTouchInput(i, &x, &y, &id, &dev);
#ifdef DEBUG
// タッチのポイントを表示する
cDebugFunc::GetInstance().RegistDrawCircle({ (float)x,(float)y },3.0f,0x77ffffff);
#endif
auto it = m_mapTouchPoint.find(id);
// 要素が登録されていない場合は新規タッチを登録する
if (it == m_mapTouchPoint.end())
{
TOUCHPTEX data;
data.pt.Device = dev;
data.pt.ID = id;
data.pt.PositionX = x;
data.pt.PositionY = y;
data.state = TOUCH_STATE::TRIGGER;
// 連想配列にデータを追加する
//m_mapTouchPoint.insert(std::make_pair(id,data)); // insert関数を使う方法
m_mapTouchPoint[id] = data; // 要素番号(キー)を指定する方法
} else
// 既にあるタッチの場合は連想配列の座標を更新する
{
(*it).second.pt.PositionX = x;
(*it).second.pt.PositionY = y;
(*it).second.state = TOUCH_STATE::BUTTON;
}
}
//--------------------------------------------------------------------------------------
// タッチ情報取得後状態更新
// タッチされてなかったらタッチが離れた判定にする
for (auto it = m_mapTouchPoint.begin(); it != m_mapTouchPoint.end(); it++)
{
if ((*it).second.state == TOUCH_STATE::NONE) (*it).second.state = TOUCH_STATE::RELEASE;
}
IBaseObject::Update();
}
//==========================================================================================
// 特定箇所の範囲がタッチされているかを確認する(円判定)
// pos : 指定ポイント
// state : 調べたいタッチ状態
// range : 指定ポイントから調べたい範囲
// ret : true 指定箇所が該当の状態だった
//==========================================================================================
bool cTouch::CheckHitCircle(const cVector2& pos, TOUCH_STATE state, float range)
{
if( m_mapTouchPoint.empty()) return false;
for (auto it : m_mapTouchPoint)
{
if (it.second.state != state) continue;
cVector2 touch((float)it.second.pt.PositionX, (float)it.second.pt.PositionY);
// タッチが指定範囲内にあった
if (range >= touch.CalcTwoPointDist(pos)) return true;
}
return false;
}
//==========================================================================================
// 特定箇所の範囲がタッチされているかを確認する(矩形判定)
// pos : 指定ポイントの中心点
// state : 調べたいタッチ状態
// range : 指定ポイントから調べたい範囲
// ret : true 指定箇所が該当の状態だった
//==========================================================================================
bool cTouch::CheckHitBox(const cVector2 & pos, TOUCH_STATE state, POINT range)
{
if (m_mapTouchPoint.empty()) return false;
for (auto it : m_mapTouchPoint)
{
if (it.second.state != state) continue;
cVector2 touch((float)it.second.pt.PositionX, (float)it.second.pt.PositionY);
// タッチが指定範囲内にあった
if (pos.x - range.x / 2 <= touch.x &&
pos.x + range.x / 2 >= touch.x &&
pos.y - range.y / 2 <= touch.y &&
pos.y + range.y / 2 >= touch.y
)
{
return true;
}
}
return false;
}
//==========================================================================================
// タッチ座標の取得
// touchID : 取得するタッチID
// pt : 取得する座標の参照
// ret : true タッチ情報が存在していた。 false タッチ情報が存在していない
//==========================================================================================
bool cTouch::GetTouchPos(int touchID, POINT & pt)
{
if (m_mapTouchPoint.empty()) return false;
auto it = m_mapTouchPoint.find(touchID);
if (it == m_mapTouchPoint.end()) return false;
pt.x = (*it).second.pt.PositionX;
pt.y = (*it).second.pt.PositionY;
return true;
}
//==========================================================================================
// タッチ座標の取得
// touchID : 取得するタッチID
// pt : 取得する座標の参照
// ret : true タッチ情報が存在していた。 false タッチ情報が存在していない
//==========================================================================================
bool cTouch::GetTouchPos(int touchID, POINT & pt, cTouch::TOUCH_STATE& state)
{
if (m_mapTouchPoint.empty()) return false;
auto it = m_mapTouchPoint.find(touchID);
if (it != m_mapTouchPoint.end())
{
pt.x = it->second.pt.PositionX;
pt.y = it->second.pt.PositionY;
state = it->second.state;
return true;
}
return false;
}
//==========================================================================================
// タッチ数取得
//==========================================================================================
int cTouch::GetTouchNum(void)
{
return GetTouchInputNum();
}
#ifdef DEBUG
//==========================================================================================
// デバッグログにタッチのログを表示する
//==========================================================================================
void cTouch::DrawTouchDebugLog(void)
{
// タッチされている座標をデバッグログで表示する
for (auto it : m_mapTouchPoint)
{
std::ostringstream oss;
oss << "Touch" << it.first << "::X : " << it.second.pt.PositionX << " Y :" << it.second.pt.PositionY;
cDebugFunc::GetInstance().PushDebugLog(oss.str().c_str());
}
}
#endif // DEBUG
<file_sep>/*==============================================================================*/
/* */
/* @file title : cTransition.cpp */
/* @brief : トランジションクラス */
/* @written : s.kosugi */
/* @create : 2019/03/11 */
/* */
/*==============================================================================*/
#include "cTransition.h"
#include "..\cDrawCtrl.h"
#include "Utility/Easing/Easing.h"
//==========================================================================================
// 定数
const float cTransition::BORDER_MAX = 255;
const int cTransition::DEFAULT_PRIORITY = 30000;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cTransition::cTransition(const std::string& filename, IDrawBase* pObj, TransDirection dir, float transtime) :
IDrawBase(filename),
m_pTransObj(pObj),
m_eBorderRange(BorderRange::RANGE_64),
m_fBorderParam(0.0f),
m_eTransDirection(dir),
m_fTransTime(transtime),
m_cTimer(nullptr, "TransTimer")
{
// トランジション方向によって初期境界位置を変更する
if (dir == TransDirection::TRANS_IN) m_fBorderParam = 0.0f;
else m_fBorderParam = (float)BORDER_MAX;
// トランジションはオブジェクト削除時にメモリからアンロードする
m_bUnload = true;
// タイマーのセット
m_cTimer.Setup(m_fTransTime);
SetPriority(DEFAULT_PRIORITY);
// 描画情報を登録
cDrawCtrl::GetInstance().RegistTransition(*this, filename);
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cTransition::~cTransition()
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cTransition::Initialize(void)
{
}
//==========================================================================================
// 更新
//==========================================================================================
void cTransition::Update(void)
{
m_cTimer.Update();
if (m_eTransDirection == TransDirection::TRANS_IN)
{
m_fBorderParam = Easing::Linear(m_cTimer.GetTime(), m_cTimer.GetLimit(), BORDER_MAX, 0.0f);
}
else
{
m_fBorderParam = Easing::Linear(m_cTimer.GetTime(), m_cTimer.GetLimit(), 0.0f, BORDER_MAX);
}
}
//==========================================================================================
// 解放
//==========================================================================================
void cTransition::Finalize(void)
{
m_cTimer.Finalize();
}
//==========================================================================================
// トランジションが終了したかどうか
//==========================================================================================
bool cTransition::IsEnd(void)
{
if (m_eTransDirection == TransDirection::TRANS_IN)
{
if (m_fBorderParam >= BORDER_MAX) return true;
return false;
}
if (m_eTransDirection == TransDirection::TRANS_OUT)
{
if (m_fBorderParam <= 0) return true;
return false;
}
return false;
}
//==========================================================================================
// トランジション方向の設定
//==========================================================================================
void cTransition::SetTransDirection(cTransition::TransDirection value)
{
m_eTransDirection = value;
if (value == TransDirection::TRANS_IN)
{
m_fBorderParam = 0.0f;
}
else
{
m_fBorderParam = (float)BORDER_MAX;
}
m_cTimer.Reset();
}<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cUIManager.h */
/* @brief : UI管理クラス */
/* @written : s.kosugi */
/* @create : 2020/04/03 */
/* */
/*==============================================================================*/
#include "..\..\IBaseObject.h"
#include "UIID.h"
#include "Utility/Vector/cVector2.h"
// 前方宣言
class cSpriteObject;
// UI管理クラス
class cUIManager : public IBaseObject
{
public:
// コンストラクタ
cUIManager(IBaseObject* pObj);
~cUIManager(void);
// 初期化
void Initialize(void);
// UI生成
cSpriteObject* Create(UIID id, const cVector2& pos);
cSpriteObject* Create(UIID id);
private:
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cEffectManager.h */
/* @brief : エフェクト管理クラス */
/* @written : s.kosugi */
/* @create : 2020/06/22 */
/* */
/*==============================================================================*/
#include "..\..\IBaseObject.h"
#include "EffectID.h"
#include "..\..\..\Utility\Vector\cVector2.h"
class IEffect;
// エフェクト管理クラス
class cEffectManager : public IBaseObject
{
public:
// コンストラクタ
cEffectManager(IBaseObject* pObj);
~cEffectManager(void);
// 初期化
void Initialize(void) override;
// 更新
void Update(void) override;
// 破棄
IBaseObject* Finalize(void) override;
// 生成
IEffect* Create(EFFECT_ID id,const cVector2& pos);
private:
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cNumber.h */
/* @brief : 数字オブジェクト */
/* @written : s.kosugi */
/* @create : 2018/12/28 */
/* */
/*==============================================================================*/
#include "BaseObject/cSpriteObject.h"
//================================================================================================
// 数字クラス
class cNumber : public cSpriteObject
{
public:
cNumber(IBaseObject* parent, std::string objectname, std::string filename);
~cNumber(void);
void Initialize(void);
void Update(void);
IBaseObject* Finalize(void);
// 数字の生成
void CreateNumber(short maxdigit, int value);
// 数値の設定
inline void SetValue(int value) { m_nValue = value; };
// 描画優先度の設定
void SetPriority( int priority );
protected:
static const int MAX_DIGIT; // 最大桁数初期値
int m_nValue; // 表示する数値
int m_nMaxDigit; // 最大桁数
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cTimer.h */
/* @brief : タイマークラス */
/* @written : s.kosugi */
/* @create : 2020/01/14 */
/* */
/*==============================================================================*/
#include "BaseObject/IBaseObject.h"
//================================================================================================
// タイマークラス
class cTimer : public IBaseObject
{
public:
cTimer( IBaseObject* parent, const std::string& name );
~cTimer(void);
// 初期化
// limit : 計測時間(秒)
void Setup(float limit);
// 初期化
// limit : 計測時間(秒)
// scale : タイムスケール(1.0が等速)
void Setup(float limit, float scale);
// 更新
void Update(void);
// リセット
inline void Reset(void) { m_fCurrentTime = 0.0f; };
// 終了判定
// ret : true 指定時間を経過した false 指定時間を経過していない
inline bool Finished(void)const { return (m_fCurrentTime >= m_fLimitTime); };
// 終了時間の取得
inline float GetTime(void) const { return m_fCurrentTime; };
// 指定した限界時間の取得
inline float GetLimit(void) const { return m_fLimitTime; };
// タイムスケールを取得
inline float GetTimeScale(void) const { return m_fTimeScale; };
// 限界時間の設定
void SetLimit(float limit);
// タイムスケールを設定
inline void SetTimeScale(float scale) { m_fTimeScale = scale; };
private:
static const float DEFAULT_TIME_SCALE; // 初期タイムスケール
float m_fCurrentTime; // 現在の時間
float m_fLimitTime; // 設定時間
float m_fTimeScale; // タイムスケール
};
//================================================================================================<file_sep>#pragma once
enum class ENEMY_ID
{
WHITE = 0,
BLUE,
YELLOW,
RED,
MAX
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cEnmBlue.cpp */
/* @brief : 青い敵クラス */
/* @written : s.kosugi */
/* @create : 2020/07/20 */
/* */
/*==============================================================================*/
#include "cEnmBlue.h"
#include "cGame.h"
#include "Utility/Timer/cTimer.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cEnmBlue::PRIORITY = 300;
const float cEnmBlue::ROTATE_SPEED = 6.0f;
const int cEnmBlue::BASE_DIST = 100;
const int cEnmBlue::MIN_TIME = 8;
const int cEnmBlue::MAX_TIME = 15;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cEnmBlue::cEnmBlue(IBaseObject * parent)
: IEnemy(parent, "EnmBlue", "data\\graphic\\enemy_02.png")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cEnmBlue::~cEnmBlue(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cEnmBlue::Initialize(const cVector2 & pos)
{
SetPriority(PRIORITY);
// 当たり判定を設定
m_fDist = GetSpriteSize().x / 2.0f;
// 位置を設定する
m_vPos = pos;
SetAngle((float)cGame::Random(0,359));
IEnemy::Initialize(m_vPos);
}
//==========================================================================================
// 更新
//==========================================================================================
void cEnmBlue::Update(void)
{
// 自転処理
SetAngle(GetAngle() + ROTATE_SPEED);
IEnemy::Update();
}
//==========================================================================================
// 通常状態
//==========================================================================================
void cEnmBlue::Normal(void)
{
// 自機接近タイマー
cTimer* timer = (cTimer*)FindChild("DistTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this, "DistTimer");
timer->Setup((float)cGame::Random(MIN_TIME, MAX_TIME));
}
// プレイヤーに向かって移動
cSpriteObject* pc = (cSpriteObject*)GetParent()->FindSibling("Player");
if (pc)
{
m_vPos.x = cos(DEG_TO_RAD(GetAngle()*0.1f)) * BASE_DIST * (timer->GetLimit() - timer->GetTime()) + pc->GetPos().x;
m_vPos.y = sin(DEG_TO_RAD(GetAngle()*0.1f)) * BASE_DIST * (timer->GetLimit() - timer->GetTime()) + pc->GetPos().y;
}
}
//==========================================================================================
// 範囲外処理
//==========================================================================================
void cEnmBlue::AreaOutAllProc(void)
{
// オーバーライドして何も処理しない
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cCoinEffect.h */
/* @brief : コインエフェクトクラス */
/* @written : s.kosugi */
/* @create : 2020/09/02 */
/* */
/*==============================================================================*/
#include "..\IEffect.h"
//================================================================================================
// コインエフェクトクラス
class cCoinEffect : public IEffect
{
public:
cCoinEffect(IBaseObject* parent);
// 初期化
void Initialize(const cVector2& pos) override;
// 更新
void Update(void) override;
private:
//--------------------------------------------------------------------------------------------
// 定数
// 表示優先度
static const int PRIORITY;
// 最大速度
static const float MAX_SPEED;
//--------------------------------------------------------------------------------------------
cVector2 m_vVelocity; // 移動量
float m_fScaleCurve; // スケーリング用sinカーブ値
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cPlayer.h */
/* @brief : プレイヤークラス */
/* @written : s.kosugi */
/* @create : 2020/08/18 */
/* */
/*==============================================================================*/
#include "..\..\cSpriteObject.h"
// プレイヤークラス
class cPlayer : public cSpriteObject
{
public:
// プレイヤー状態
enum class STATE {
START,
NORMAL,
DEAD,
GOAL,
};
cPlayer(IBaseObject* parent);
~cPlayer(void);
void Initialize(void);
void Update(void);
IBaseObject* Finalize(void);
// プレイヤー状態の変更
void ChangeState(STATE state);
// 状態の取得
const inline STATE GetState(void) { return m_eState; };
// 当たり判定の半径の取得
const inline float GetDist(void) { return DIST; };
private:
// 壁当たりの速度減衰率
static const float REFLECTION;
// 摩擦率
static const float FRICTION;
// 小さい傾き値の切り捨て
static const float SLOPE_MIN_ROUNDDOWN;
// センサーの値の大きさを使う大きさにあわせる
static const float SENSOR_RATE;
// 当たり判定の半径
static const float DIST;
// 死亡状態の時間
static const float DEAD_TIME;
// 死亡エフェクトの玉の数
static const int DEAD_EFFECT_NUM;
// 死亡エフェクトの移動スピード
static const float DEAD_EFFECT_SPEED;
// ゴール状態の時間
static const float GOAL_TIME;
// 表示優先度
static const int PRIORITY;
// 速度
cVector2 m_vVelocity;
// プレイヤー状態
STATE m_eState;
// 開始状態の処理
void Start();
// 通常状態処理
void Normal();
// 死亡状態
void Dead();
// ゴール状態
void Goal();
// AndroidSensorVectorの戻り値をcPlayerが使える値にする
cVector2 CalcSensorVector(VECTOR dxvector);
// 壁判定
void CheckHitWall(void);
// 時間切れチェック
void CheckTimeOver(void);
// アニメーション処理
void Animation(void);
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cGameMain.cpp */
/* @brief : ゲームメインシーン */
/* @written : s.kosugi */
/* @create : 2018/12/02 */
/* */
/*==============================================================================*/
#include "..\..\..\cGame.h"
#include "cGameMain.h"
#include "..\..\cSceneManager.h"
#include "..\..\..\BaseObject\cSpriteObject.h"
#include <DxLib.h>
#include "..\..\..\BaseObject\GameObject\Player\cPlayer.h"
#include "DataManager/cDataManager.h"
#include "BaseObject/GameObject/Effect/cEffectManager.h"
#include "BaseObject/GameObject/UI/cUIManager.h"
#include "Input/Touch/cTouch.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif
//==========================================================================================
// コンストラクタ
//==========================================================================================
cGameMain::cGameMain(IBaseObject * parent)
: IBaseScene(parent, "GameMain")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cGameMain::~cGameMain(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cGameMain::Initialize(void)
{
// 背景スプライトの生成
cSpriteObject* obj = CreateDrawObject<cSpriteObject>(this, "TitleBack", "data\\graphic\\title.png");
obj->SetPriority(-100);
obj->SetPos((float)cGame::GetInstance().GetWindowWidth()/2, (float)cGame::GetInstance().GetWindowHeight() / 2);
// プレイヤーキャラクターの生成
CreateObject<cPlayer>(this);
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cGameMain::Update(void)
{
IBaseObject::Update();
//----------------------------------------------------
// エフェクト再生
cTouch* touch = (cTouch*)GetRoot()->FindChild("Touch");
cEffectManager* em = (cEffectManager*)GetRoot()->FindChild("EffectManager");
if (touch && em)
{
POINT pt;
cTouch::TOUCH_STATE state;
if (touch->GetTouchPos(0, pt, state))
{
if (state == cTouch::TOUCH_STATE::TRIGGER) em->Create(EFFECT_ID::BOM, pt);
}
if (touch->GetTouchPos(1, pt, state))
{
if (state == cTouch::TOUCH_STATE::TRIGGER) em->Create(EFFECT_ID::MUZZLE, pt);
}
}
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject* cGameMain::Finalize(void)
{
IBaseObject::Finalize();
return this;
}
<file_sep>#include "cStartButton.h"
#include "cGame.h"
#include "SceneManager/cSceneManager.h"
#include "SoundCtrl/cSoundCtrl.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cStartButton::PRIORITY = 200;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cStartButton::cStartButton(IBaseObject * parent)
: IButton(parent, "StartButton", "data\\graphic\\start.png")
, m_bPressed(false)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cStartButton::Initialize(void)
{
IButton::Initialize();
cGame* game = (cGame*)GetRoot();
SetPos(game->GetWindowWidth() / 2.0f,game->GetWindowHeight() / 3 * 2);
// スプライトのRectを左半分にする
SetSrcRect(0,0,this->GetGraphichSize().x / 2.0f, this->GetSpriteSize().y);
// Rectの大きさを変えたので中心位置を変更
m_vCenter.x = GetSpriteSize().x / 2.0f;
SetPriority(PRIORITY);
}
//==========================================================================================
// 押されていない時
//==========================================================================================
void cStartButton::Neutral(void)
{
SetSrcRect(0,0,this->GetGraphichSize().x / 2.0f, this->GetSpriteSize().y);
m_bPressed = false;
}
//==========================================================================================
// 押された瞬間
//==========================================================================================
void cStartButton::Trigger(void)
{
SetSrcRect(this->GetGraphichSize().x / 2.0f,0,this->GetGraphichSize().x / 2.0f, this->GetSpriteSize().y);
m_bPressed = true;
cSoundCtrl::GetInstance().Play(SOUND_ID::BOM);
}
//==========================================================================================
// 押されている間
//==========================================================================================
void cStartButton::Pressed(void)
{
SetSrcRect(this->GetGraphichSize().x / 2.0f,0,this->GetGraphichSize().x / 2.0f, this->GetSpriteSize().y);
}
//==========================================================================================
// 離された瞬間
//==========================================================================================
void cStartButton::Release(void)
{
SetSrcRect(0,0,this->GetGraphichSize().x / 2.0f, this->GetSpriteSize().y);
// ボタンが押されてから離されたのでシーン遷移をする
if (m_bPressed)
{
cSceneManager* sm = (cSceneManager*)GetRoot()->FindChild("SceneManager");
if (sm)
{
sm->ChangeSceneUniTrans(SCENE_ID::GAMEMAIN, "data\\graphic\\rule_00.png");
}
}
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cTitleLogo.h */
/* @brief : タイトルロゴクラス */
/* @written : s.kosugi */
/* @create : 2020/09/02 */
/* */
/*==============================================================================*/
#include "..\..\..\cSpriteObject.h"
//================================================================================================
// タイトルロゴクラス
class cTitleLogo : public cSpriteObject
{
public:
cTitleLogo(IBaseObject* parent);
~cTitleLogo(void);
void Initialize(void) override;
void Update(void) override;
private:
enum STATE
{
SCALE,
WAIT,
};
// 状態別処理
// 拡大時処理
void Scale(void);
// 待機処理
void Wait(void);
// 状態
STATE m_eState;
// スケーリング用sinカーブ
float m_fScaleCurve;
//--------------------------------------------------------------------------------------------
// 定数
// 表示優先度
static const int PRIORITY;
static const float SCALE_INCREMENT;
static const float WAIT_TIME;
//--------------------------------------------------------------------------------------------
};
//================================================================================================<file_sep>/*==============================================================================*/
/* */
/* @file title : cDrawCtrl.cpp */
/* @brief : 描画コントロールクラス */
/* @written : s.kosugi */
/* @create : 2018/09/17 */
/* */
/*==============================================================================*/
#include "cDrawCtrl.h"
#include "..\Utility\memory.h"
#include "..\Utility\utility.h"
#include <algorithm>
#include <DxLib.h>
//#include "EffekseerForDXLib.h"
#include "SceneManager/cSceneManager.h"
//#include <direct.h>
#include "cGame.h"
#ifdef DEBUG
#include "..\DebugFunc\cDebugFunc.h"
#endif
//==========================================================================================
// 初期化
//==========================================================================================
void cDrawCtrl::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "DrawCtrl";
m_bPriChageRequest = false;
m_bScreenShot = false;
m_listFontCreated.clear();
IBaseObject::Initialize();
}
//==========================================================================================
// 描画
//==========================================================================================
void cDrawCtrl::Draw(void)
{
if (m_listDrawObject.empty()) return;
// 描画優先度変更要求があったら優先度順にソートする
if (m_bPriChageRequest) m_listDrawObject.sort(CompAscPriority);
for (auto it = m_listDrawObject.begin(); it != m_listDrawObject.end(); it++)
{
if ((*it)->GetVisible())
{
switch ((*it)->m_eDrawType)
{
case DRAWTYPE::SPRITE:
DrawSprite((cSprite*)(*it));
break;
/*case DRAW_TYPE_EFFECT:
DrawEffect((cEffect*)(*it));
break;*/
case DRAWTYPE::BEGINSURFACE:
BeginSurface(*it);
break;
case DRAWTYPE::SURFACE:
if (DrawSurface((cSurface*)(*it)))
{
// 処理待ちのサーフェイスがあった場合イテレーターを処理中のオブジェクトの場所まで戻す
if (!m_listSurfaceWait.empty())
{
it = std::find(m_listDrawObject.begin(), m_listDrawObject.end(), (*m_listSurfaceWait.begin()));
BeginSurface(*it);
m_listSurfaceWait.pop_front();
}
}
break;
case DRAWTYPE::TRANSITION:
DrawTransition((cTransition*)(*it));
break;
case DRAWTYPE::TEXT:
DrawTextObj((cText*)(*it));
break;
}
}
}
if (m_bScreenShot)
{
// スクリーンショット保存
//SaveScreenFile();
// スクリーンショット保存要求をリセット
m_bScreenShot = false;
}
// 変更要求をリセット
m_bPriChageRequest = false;
}
//==========================================================================================
// 解放
//==========================================================================================
IBaseObject* cDrawCtrl::Finalize(void)
{
IBaseObject::Finalize();
//------------------------------------------------------------------------------------
// 描画リストのクリア
m_listDrawObject.clear();
//------------------------------------------------------------------------------------
// 読み込み済み描画ファイルの解放
if (!m_listFileLoaded.empty())
{
// ※フルスクリーン時にエラー落ちする可能性がある為コメントアウト
/*for (auto it = m_listFileLoaded.begin(); it != m_listFileLoaded.end(); it++)
{
if( (*it).Type == DRAW_TYPE_EFFECT) DeleteEffekseerEffect((*it).GraphHandle);
}*/
InitGraph();
m_listFileLoaded.clear();
}
return nullptr;
}
//==========================================================================================
// 描画情報の登録(スプライト)
// obj : 描画情報を設定するスプライトオブジェクト
// filename : スプライトのリソースファイル名
//==========================================================================================
void cDrawCtrl::RegistDrawObject(cSprite& obj,const std::string& filename)
{
if(obj.IsFileLoaded()) return;
// 描画オブジェクトの登録
m_listDrawObject.push_front((IDrawBase*)&obj);
// 読み込み済みグラフィックハンドルを設定
obj.m_nGraphHandle = LoadDrawFile(filename, DRAWTYPE::SPRITE);
int x = 0, y = 0;
GetGraphSize(obj.m_nGraphHandle, &x, &y);
obj.SetCenter(x/2.0f,y/2.0f);
//obj.SetAnchor( obj.GetAnchor() );
// Rectを設定する
obj.SetSrcRect(0,0,x,y);
// 描画種別をスプライトに設定
obj.m_eDrawType = DRAWTYPE::SPRITE;
// 描画順の変更要求をする
m_bPriChageRequest = true;
}
//==========================================================================================
// 描画情報の登録(エフェクト)
// obj : 描画情報を設定するエフェクトオブジェクト
// filename : エフェクトのリソースファイル名
//==========================================================================================
//void cDrawCtrl::RegistDrawObject(cEffect & obj, const std::string & filename)
//{
// if (obj.IsFileLoaded()) return;
//
// // 描画オブジェクトの登録
// m_listDrawObject.push_front(&obj);
//
// // 読み込み済みグラフィックハンドルを設定
// obj.m_nGraphHandle = LoadDrawFile(filename, DRAW_TYPE_EFFECT);
//
// // 描画種別をエフェクトに設定
// obj.m_eDrawType = DRAW_TYPE_EFFECT;
//
// // 描画順の変更要求をする
// m_bPriChageRequest = true;
//}
//==========================================================================================
// 描画情報の登録(サーフェイス)
// obj : 描画情報を設定するサーフェイス
//==========================================================================================
void cDrawCtrl::RegistSurface(cSurface & obj,int width , int height ,bool alpha)
{
if (obj.IsFileLoaded()) return;
// 描画オブジェクトの登録
m_listDrawObject.push_front(&obj);
// 描画開始ポイントを登録
m_listDrawObject.push_front(obj.GetBeginPointer());
// 描画種別をサーフェイスに設定
obj.m_eDrawType = DRAWTYPE::SURFACE;
obj.GetBeginPointer()->m_eDrawType = DRAWTYPE::BEGINSURFACE;
// サーフェイスを作成する
obj.m_nGraphHandle = MakeScreen(width, height, alpha);
obj.GetBeginPointer()->m_nGraphHandle = obj.m_nGraphHandle;
// 描画順の変更要求をする
m_bPriChageRequest = true;
}
//==========================================================================================
// 描画情報の登録(トランジション)
// obj : 描画情報を設定するトランジションオブジェクト
// filename : ルール画像のリソースファイル名
//==========================================================================================
void cDrawCtrl::RegistTransition(cTransition & obj, const std::string & filename)
{
if (obj.IsFileLoaded()) return;
// 描画オブジェクトの登録
m_listDrawObject.push_front(&obj);
// 読み込み済みグラフィックハンドルを設定
obj.m_nGraphHandle = LoadDrawFile(filename, DRAWTYPE::TRANSITION);
// 描画種別をトランジションに設定
obj.m_eDrawType = DRAWTYPE::TRANSITION;
// 描画順の変更要求をする
m_bPriChageRequest = true;
}
//==========================================================================================
// 描画情報の登録(テキスト)
// obj : 描画情報を設定するテキストオブジェクト
//==========================================================================================
void cDrawCtrl::RegistDrawObject(cText & obj)
{
if (obj.IsFileLoaded()) return;
// 描画オブジェクトの登録
m_listDrawObject.push_front(&obj);
// デフォルトフォントを使用
obj.m_nGraphHandle = LOADGRAPH_FAILED;
// 描画種別をモデルに設定
obj.m_eDrawType = DRAWTYPE::TEXT;
// 描画順の変更要求をする
m_bPriChageRequest = true;
}
//==========================================================================================
// 描画情報の登録(テキスト)
// obj : 描画情報を設定するテキストオブジェクト
// 以降引数 : CreateFontに必要
//==========================================================================================
void cDrawCtrl::RegistDrawObject(cText & obj, const std::string& fontname, int Size, int Thick, int FontType, int EdgeSize, int Italic)
{
if (obj.IsFileLoaded()) return;
// 描画オブジェクトの登録
m_listDrawObject.push_front(&obj);
// フォント生成用の構造体を作成
FontCreated font;
font.FontName = fontname;
font.Size = Size;
font.Thick = Thick;
font.FontType = FontType;
font.EdgeSize = EdgeSize;
font.Italic = Italic;
// フォント生成済みでなければ作成
int handle = SearchSameFont(font);
if (handle == -1)
{
// 乗算済みα用のフォントハンドルを作成する
SetFontCacheUsePremulAlphaFlag(TRUE);
font.Handle = CreateFontToHandle(font.FontName.c_str(), font.Size, font.Thick, font.FontType, -1, font.EdgeSize, font.Italic);
handle = font.Handle;
m_listFontCreated.push_back(font);
}
obj.m_nGraphHandle = handle;
// 描画種別をモデルに設定
obj.m_eDrawType = DRAWTYPE::TEXT;
// 描画順の変更要求をする
m_bPriChageRequest = true;
}
//==========================================================================================
// 描画ファイルの読み込み
// filename : ファイル名
// type : 描画種別
// 戻り値 : 読み込み済みのグラフィックハンドル
//==========================================================================================
int cDrawCtrl::LoadDrawFile(const std::string & filename, DRAWTYPE type)
{
if (!m_listFileLoaded.empty())
{
std::list<FileLoaded>::iterator end = m_listFileLoaded.end();
std::list<FileLoaded>::iterator it = m_listFileLoaded.begin();
while (it != end)
{
// ロード済みのファイルは読み込みしない
if ((*it).FileName == filename) return (*it).GraphHandle;
it++;
}
}
// 新規読み込みファイルをリストに追加する
FileLoaded load;
load.FileName = filename;
load.Type = type;
switch (type)
{
case DRAWTYPE::SPRITE: load.GraphHandle = LoadGraph(filename.c_str(), FALSE); break;
//case DRAW_TYPE_EFFECT: load.GraphHandle = LoadEffekseerEffect(filename.c_str()); break;
case DRAWTYPE::TRANSITION: load.GraphHandle = LoadBlendGraph(filename.c_str()); break;
default: break;
}
// グラフィックハンドル読み込み失敗
if (LOADGRAPH_FAILED == load.GraphHandle)
{
#ifdef DEBUG
cDebugFunc::GetInstance().PushDebugLog("LOADGRAPH_FAILED : "+filename);
#endif
return LOADGRAPH_FAILED;
}
// 読み込み済みリストに追加
m_listFileLoaded.push_back(load);
return load.GraphHandle;
}
//==========================================================================================
// 描画情報の登録抹消
// obj : 描画情報を抹消したいオブジェクト自身
//==========================================================================================
void cDrawCtrl::RemoveDrawObject(const IDrawBase* obj)
{
//---------------------------------------------------------------------
// m_listDrawObjectからの抹消処理
std::list<IDrawBase*>::iterator it = m_listDrawObject.begin();
std::list<IDrawBase*>::iterator end = m_listDrawObject.end();
while (it != end)
{
if (obj == (*it))
{
if ((*it)->m_bUnload)
{
// 他に使っているオブジェクトがなければメモリからアンロードする
if (!SearchSameGrHandle(obj))
{
DeleteGraph(obj->m_nGraphHandle);
// 読み込み済みファイルリストから抹消
RemoveFileLoaded(obj->m_sFileName);
}
}
(*it)->m_nGraphHandle = LOADGRAPH_FAILED;
m_listDrawObject.remove(*it);
return;
}
it++;
}
}
//==========================================================================================
// サーフェイスの登録抹消
// obj : 登録を消すサーフェイス自身
//==========================================================================================
void cDrawCtrl::RemoveSurface(const cSurface* obj)
{
//---------------------------------------------------------------------
// m_listDrawObjectからの抹消処理
std::list<IDrawBase*>::iterator it = m_listDrawObject.begin();
std::list<IDrawBase*>::iterator end = m_listDrawObject.end();
while (it != end)
{
if (obj == (*it))
{
DeleteGraph((*it)->m_nGraphHandle);
(*it)->m_nGraphHandle = LOADGRAPH_FAILED;
RemoveDrawObject(((cSurface*)*it)->GetBeginPointer());
m_listDrawObject.remove(*it);
return;
}
it++;
}
}
//==========================================================================================
// テキストの文字幅を取得する
//==========================================================================================
int cDrawCtrl::GetTextWidth(cText* obj)
{
// デフォルトフォントの場合
if (obj->m_nGraphHandle == FONT_NOTFAUND)
{
return GetDrawStringWidth(obj->GetText().c_str(), (int)obj->GetText().length());
}
// 作成済みフォントの場合
else
{
return GetDrawStringWidthToHandle(obj->GetText().c_str(), (int)obj->GetText().length(), obj->m_nGraphHandle);
}
}
//==========================================================================================
// スプライトの描画
//==========================================================================================
void cDrawCtrl::DrawSprite(cSprite * obj)
{
if (obj->m_nGraphHandle != LOADGRAPH_FAILED)
{
SetDrawBlendMode(obj->GetBlendMode(), obj->GetAlpha());
RECT rect = obj->GetSrcRect();
unsigned int red = (obj->GetDrawColor() & 0x00ff0000) >> 16;
unsigned int green = (obj->GetDrawColor() & 0x0000ff00) >> 8;
unsigned int blue = (obj->GetDrawColor() & 0x000000ff);
// 色の設定
SetDrawBright(red, green, blue);
// 回転拡縮Rectを加味した描画
DrawRectRotaGraph3F(round(obj->GetPos().x), round(obj->GetPos().y), rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
round(obj->GetCenter().x + obj->GetAnchor().x), round(obj->GetCenter().y + obj->GetAnchor().y), obj->GetScale().x, obj->GetScale().y, DEG_TO_RAD(obj->GetAngle()), obj->m_nGraphHandle,
TRUE);
}
}
//==========================================================================================
// エフェクトの描画
//==========================================================================================
//void cDrawCtrl::DrawEffect(cEffect * obj)
//{
// if (obj->m_nGraphHandle != LOADGRAPH_FAILED)
// {
// if (obj->m_nPlayingEffectHandle != -1)
// {
// // シーンIDが一致しない場合にはエフェクトを停止する
// if (obj->m_ePlayScene != -1 && obj->m_ePlayScene != cSceneManager::GetInstance().GetStackSceneID())
// {
// SetSpeedPlayingEffekseer2DEffect(obj->m_nPlayingEffectHandle, 0.0f);
// } else
// {
// SetSpeedPlayingEffekseer2DEffect(obj->m_nPlayingEffectHandle, 1.0f);
// }
// // 再生終了
// if (IsEffekseer2DEffectPlaying(obj->m_nPlayingEffectHandle) == -1)
// {
// StopEffekseer2DEffect(obj->m_nPlayingEffectHandle);
// if (!obj->IsLoop())
// {
// return;
// } else {
//
// // ループ設定のエフェクトだったら再度再生
// obj->m_nPlayingEffectHandle = PlayEffekseer2DEffect(obj->m_nGraphHandle);
// }
// }
// } else
// {
// // エフェクトの再生開始
// obj->m_nPlayingEffectHandle = PlayEffekseer2DEffect(obj->m_nGraphHandle);
// }
// SetScalePlayingEffekseer2DEffect(obj->m_nPlayingEffectHandle, obj->m_vScale.x, obj->m_vScale.y, obj->m_vScale.z);
// SetPosPlayingEffekseer2DEffect(obj->m_nPlayingEffectHandle, obj->m_vPos.x, obj->m_vPos.y, 0);
// SetRotationPlayingEffekseer2DEffect(obj->m_nPlayingEffectHandle, obj->m_vAngle.x, obj->m_vAngle.y, obj->m_vAngle.z);
//
// unsigned int alpha = (obj->GetDrawColor() & 0xff000000) >> 24;
// unsigned int red = (obj->GetDrawColor() & 0x00ff0000) >> 16;
// unsigned int green = (obj->GetDrawColor() & 0x0000ff00) >> 8;
// unsigned int blue = (obj->GetDrawColor() & 0x000000ff);
//
// SetColorPlayingEffekseer2DEffect(obj->m_nPlayingEffectHandle, red, green, blue, alpha);
//
// // エフェクトを描画する
// DrawEffekseer2D_Begin();
// DrawEffekseer2D_Draw(obj->m_nPlayingEffectHandle);
// DrawEffekseer2D_End();
// }
//}
//==========================================================================================
// サーフェイスの描画
//==========================================================================================
bool cDrawCtrl::DrawSurface(cSurface * obj)
{
// 対象外のサーフェイスは一旦飛ばす
if (m_pBeginSurface != obj->GetBeginPointer()) return false;
// レンダーターゲットをバックバッファに戻す
SetDrawScreen(DX_SCREEN_BACK);
RECT rect = obj->GetRect();
SetDrawBlendMode(obj->GetBlendMode(), obj->GetAlpha());
unsigned int red = (obj->GetDrawColor() & 0x00ff0000) >> 16;
unsigned int green = (obj->GetDrawColor() & 0x0000ff00) >> 8;
unsigned int blue = (obj->GetDrawColor() & 0x000000ff);
// 色の設定
SetDrawBright(red, green, blue);
// フィルターの設定
switch (obj->GetFilterMode())
{
case cSurface::FILTER_MODE::MONO: GraphFilter(obj->m_nGraphHandle, DX_GRAPH_FILTER_MONO, obj->GetMonoBlue(), obj->GetMonoRed()); break;
case cSurface::FILTER_MODE::GAUSS: GraphFilter(obj->m_nGraphHandle, DX_GRAPH_FILTER_GAUSS, obj->GetGaussPixelWidth(), obj->GetGaussParam()); break;
case cSurface::FILTER_MODE::HSB: GraphFilter(obj->m_nGraphHandle, DX_GRAPH_FILTER_HSB, 0, obj->GetHSBHue(), obj->GetHSBSaturation(), obj->GetHSBBright()); break;
case cSurface::FILTER_MODE::INVERT: GraphFilter(obj->m_nGraphHandle, DX_GRAPH_FILTER_INVERT); break;
default: break;
}
// 表示フラグが立っている時のみ表示する
if (obj->IsShow())
{
// サーフェイスの内容を描画
DrawRectRotaGraph3F(obj->GetPos().x, obj->GetPos().y, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
obj->GetCenter().x, obj->GetCenter().y, obj->GetScale().x, obj->GetScale().y, DEG_TO_RAD(obj->GetAngle().x), obj->m_nGraphHandle,
TRUE);
}
// 処理中のサーフェイスポインタを初期化
m_pBeginSurface = nullptr;
return true;
}
//==========================================================================================
// サーフェイスの描画開始
//==========================================================================================
void cDrawCtrl::BeginSurface(IDrawBase * obj)
{
if (obj->IsFileLoaded())
{
// 処理中サーフェイスがあった場合にはサーフェイスを処理待ちにする
if (m_pBeginSurface)
{
// 未登録のサーフェイスの場合は処理待ちリストに追加する
if (m_listSurfaceWait.end() == std::find(m_listSurfaceWait.begin(), m_listSurfaceWait.end(), obj))
m_listSurfaceWait.push_back(obj);
return;
}
m_pBeginSurface = obj;
// レンダーターゲットをサーフェイスにする
SetDrawScreen(obj->m_nGraphHandle);
ClearDrawScreen();
}
}
//==========================================================================================
// トランジションの描画
//==========================================================================================
void cDrawCtrl::DrawTransition(cTransition * obj)
{
if (obj->m_nGraphHandle != LOADGRAPH_FAILED)
{
// トランジションはブレンドモードを設定しない
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
unsigned int red = (obj->GetDrawColor() & 0x00ff0000) >> 16;
unsigned int green = (obj->GetDrawColor() & 0x0000ff00) >> 8;
unsigned int blue = (obj->GetDrawColor() & 0x000000ff);
// 色の設定
SetDrawBright(red, green, blue);
// 描画
DrawBlendGraph((int)obj->m_vPos.x, (int)obj->m_vPos.y, obj->GetTransObject()->m_nGraphHandle, TRUE, obj->m_nGraphHandle, (int)obj->GetBorderParam(), (int)obj->GetBorderRange());
}
}
//==========================================================================================
// テキストの描画
//==========================================================================================
void cDrawCtrl::DrawTextObj(cText * obj)
{
// テキストはAlphaブレンドモードに変更
SetDrawBlendMode(DX_BLENDMODE_PMA_ALPHA, obj->GetAlpha());
unsigned int red = (obj->GetDrawColor() & 0x00ff0000) >> 16;
unsigned int green = (obj->GetDrawColor() & 0x0000ff00) >> 8;
unsigned int blue = (obj->GetDrawColor() & 0x000000ff);
// 色の設定
SetDrawBright(red, green, blue);
if (obj->m_nGraphHandle == LOADGRAPH_FAILED)
{
// 標準文字描画
DrawStringF(obj->GetPos().x, obj->GetPos().y, obj->GetText().c_str(), obj->GetDrawColor());
}
else
{
// フォントハンドルを用いた描画
DrawStringToHandle((int)obj->GetPos().x, (int)obj->GetPos().y, obj->GetText().c_str(), obj->GetDrawColor(), obj->m_nGraphHandle, obj->GetEdgeColor(), obj->GetVerticalFlag());
}
}
//==========================================================================================
// 同じグラフィックハンドルを持つオブジェクトがあるかを探す
// 戻り値 : true 見つかった false 見つからなかった
//==========================================================================================
bool cDrawCtrl::SearchSameGrHandle(const IDrawBase * obj)
{
auto it = m_listDrawObject.begin();
auto end = m_listDrawObject.end();
while (it != end)
{
if (obj != (*it))
{
if (obj->m_nGraphHandle == (*it)->m_nGraphHandle) return true;
}
it++;
}
return false;
}
//==========================================================================================
// 生成済みの同フォントがあるかを探す
// 戻り値 : -1 同じフォントが見つからなかった -1以外 フォントハンドル
//==========================================================================================
int cDrawCtrl::SearchSameFont(FontCreated & font)
{
auto it = m_listFontCreated.begin();
auto end = m_listFontCreated.end();
while (it != end)
{
if (font.FontName == (*it).FontName &&
font.Size == (*it).Size &&
font.Thick == (*it).Thick &&
font.FontType == (*it).FontType &&
font.EdgeSize == (*it).EdgeSize &&
font.Italic == (*it).Italic)
{
return (*it).Handle;
}
it++;
}
return -1;
}
//==========================================================================================
// 読み込み済みファイルリストから抹消する
// filename : 抹消するファイル名
//==========================================================================================
void cDrawCtrl::RemoveFileLoaded(std::string filename)
{
// アンロードしたら読み込み済みリストから抹消
if (!m_listFileLoaded.empty())
{
std::list<FileLoaded>::iterator end = m_listFileLoaded.end();
std::list<FileLoaded>::iterator it = m_listFileLoaded.begin();
while (it != end)
{
// ロード済みのファイルを抹消する
if ((*it).FileName == filename)
{
m_listFileLoaded.erase(it);
return;
}
it++;
}
}
}
//==========================================================================================
// スクリーンショット保存
//==========================================================================================
//void cDrawCtrl::SaveScreenFile(void)
//{
// // スクリーンショット要求があれば保存する
// DATEDATA date;
// GetDateTime(&date);
// _mkdir("ScreenShot");
// // 年以外は0埋めしておく
// char mon[8], day[8], hour[8], min[8], sec[8];
// sprintf_s(mon, 8, "%02d", date.Mon);
// sprintf_s(day, 8, "%02d", date.Day);
// sprintf_s(hour, 8, "%02d", date.Hour);
// sprintf_s(min, 8, "%02d", date.Min);
// sprintf_s(sec, 8, "%02d", date.Sec);
// // スクリーンショットを日付のファイル名にする
// std::string datestr = "ScreenShot\\" + std::to_string(date.Year) + mon + day + hour + min + sec + ".png";
//
// SaveDrawScreenToPNG(0, 0, cGame::GetInstance().GetWindowWidth(), cGame::GetInstance().GetWindowHeight(), datestr.c_str(), 0);
//}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cDrawCtrl::cDrawCtrl(void) :
m_bPriChageRequest(false),
m_bScreenShot(false),
m_pBeginSurface(nullptr)
{
m_listFileLoaded.clear();
m_listDrawObject.clear();
m_listFontCreated.clear();
m_listSurfaceWait.clear();
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cDrawCtrl::cDrawCtrl(IBaseObject* parent) :
cDrawCtrl::cDrawCtrl()
{
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cDrawCtrl::cDrawCtrl(IBaseObject* parent, const std::string& name) :
cDrawCtrl::cDrawCtrl(parent)
{
}
//==========================================================================================
// コピーコンストラクタ
//==========================================================================================
cDrawCtrl::cDrawCtrl(const cDrawCtrl& t) :
cDrawCtrl::cDrawCtrl()
{
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cClearFont.cpp */
/* @brief : クリアの文字クラス */
/* @written : s.kosugi */
/* @create : 2020/08/31 */
/* */
/*==============================================================================*/
#include "cClearFont.h"
#include "cGame.h"
#include "Utility/Timer/cTimer.h"
#include "Utility/Easing/Easing.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cClearFont::PRIORITY = 1000;
const float cClearFont::MOVE_TIME = 1.5f;
const float cClearFont::FADE_TIME = 0.5f;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cClearFont::cClearFont(IBaseObject* parent)
: cSpriteObject(parent, "ClearFont", "data\\graphic\\clearfont.png")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cClearFont::~cClearFont(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cClearFont::Initialize(void)
{
SetPriority(PRIORITY);
cGame* game = (cGame*)GetRoot();
// 中央右あたりに配置
SetPos(game->GetWindowWidth() + GetSpriteSize().x / 2.0f, game->GetWindowCenter().y);
cSpriteObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cClearFont::Update(void)
{
cTimer* timer = (cTimer*)FindChild("ClearFontMoveTimer");
cGame* game = (cGame*)GetRoot();
if (!timer)
{
timer = CreateObject<cTimer>(this, "ClearFontMoveTimer");
timer->Setup(MOVE_TIME);
}
if (!timer->Finished())
{
float posx = Easing::OutBack(timer->GetTime(), timer->GetLimit(), game->GetWindowCenter().x, game->GetWindowWidth() + GetSpriteSize().x / 2.0f);
SetPosX(posx);
}
else
{
SetPosX(game->GetWindowCenter().x);
// フェードアウト処理
timer = (cTimer*)FindChild("ClearFontFadeTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this, "ClearFontFadeTimer");
timer->Setup(FADE_TIME);
}
if (!timer->Finished())
{
SetAlpha((int)Easing::Linear(timer->GetTime(), timer->GetLimit(), 0.0f, 255.0f));
}
else
{
DeleteObject();
}
}
cSpriteObject::Update();
}<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cMovieManager.h */
/* @brief : 動画管理クラス */
/* @written : s.kosugi */
/* @create : 2019/03/06 */
/* */
/*==============================================================================*/
#include "..\BaseObject\IBaseObject.h"
#include "MovieID.h"
class cMovieManager : public IBaseObject
{
public:
// 動画の再生状態
enum PlayState {
STATE_WAIT = 0,
STATE_PLAY,
STATE_STOP,
};
// 初期化
void Initialize(void);
// 更新
void Update(void);
// 破棄
IBaseObject* Finalize(void);
// 動画ファイルの読み込み
void Load(std::string filename);
void Load(MovieID id);
// 動画の再生開始
void Start( void );
// 動画の再生
void Play(void);
// 動画の停止
void Stop(void);
// 動画データの解放
void Unload( void );
// 動画の再生状態を取得
inline PlayState GetPlayState(void) { return m_ePlayState; };
private:
int m_nGraphHandle; // 動画ファイルのハンドル
PlayState m_ePlayState; // 動画の再生状態
// 動画再生中の実行速度
static const int PLAYMOVIE_FPS = 30;
// ハンドル未取得
static const int LOADMOVIE_NONE = -1;
// 動画ファイル名テーブル
std::string MOVIEFILE_TABLE[MOVIE_MAX] =
{
"data\\movie\\Start.avi",
};
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cMovieManager(void) { }; // 他からの生成を禁止
cMovieManager(IBaseObject* parent) { };
cMovieManager(IBaseObject* parent, const std::string& name) { };
~cMovieManager(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cMovieManager(const cMovieManager& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cMovieManager& operator = (const cMovieManager& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
static cMovieManager& GetInstance(void) {
static cMovieManager instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cMouse.cpp */
/* @brief : マウス入力クラス */
/* @written : s.kosugi */
/* @create : 2018/11/24 */
/* */
/*==============================================================================*/
#include "cMouse.h"
//==========================================================================================
// 初期化
//==========================================================================================
void cMouse::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "Mouse";
m_nButtonState = 0;
m_nPrevButtonState = 0;
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cMouse::Update(void)
{
// 前フレーム情報の保存
memcpy(&m_nPrevButtonState, &m_nButtonState, sizeof(int));
// マウス入力状態の取得
m_nButtonState = GetMouseInput();
IBaseObject::Update();
}
//==========================================================================================
// キー押下チェック
//
// unsigned int kcode チェックするキーコード
// MOUSE_INPUT_LEFT : 左ボタン
// MOUSE_INPUT_RIGHT : 右ボタン
// MOUSE_INPUT_MIDDLE : マウス中央ボタン
//
// 戻り値 true:押されていた FALSE:押されていない
//==========================================================================================
bool cMouse::CheckButton(unsigned int kcode)
{
// ボタンが押されているかどうか
if (m_nButtonState & kcode) return true;
return false;
}
//==========================================================================================
// 押した瞬間をチェック
//
// unsigned int kcode チェックするキーコード
//
// 戻り値 true:押されていた FALSE:押されていない
//==========================================================================================
bool cMouse::CheckTrigger(unsigned int kcode)
{
if (!(m_nPrevButtonState & kcode) && (m_nButtonState & kcode)) return true;
return false;
}
//==========================================================================================
// 離した瞬間をチェック
//
// unsigned int kcode チェックするキーコード
//
// 戻り値 true:押されていた FALSE:押されていない
//==========================================================================================
bool cMouse::CheckRelease(unsigned int kcode)
{
if ((m_nPrevButtonState & kcode) && !(m_nButtonState & kcode)) return true;
return false;
}
//==========================================================================================
// マウス座標の設定
//==========================================================================================
void cMouse::SetPoint(int x, int y)
{
SetMousePoint(x,y);
}
void cMouse::SetPoint(POINT pt)
{
SetPoint(pt.x,pt.y);
}
//==========================================================================================
// マウス座標の取得
//==========================================================================================
POINT cMouse::GetPoint(void)
{
int x = 0 , y = 0;
POINT pt;
GetMousePoint(&x,&y);
pt.x = x;
pt.y = y;
return pt;
}
<file_sep>/*==============================================================================*/
/* */
/* @file title : cTitleButton.cpp */
/* @brief : タイトルボタンクラス */
/* @written : s.kosugi */
/* @create : 2020/07/20 */
/* */
/*==============================================================================*/
#include "cTitleButton.h"
#include "cGame.h"
#include "SceneManager/cSceneManager.h"
#include "SoundCtrl/cSoundCtrl.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cTitleButton::PRIORITY = 200;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cTitleButton::cTitleButton(IBaseObject * parent)
: IButton(parent, "TitleButton", "data\\graphic\\title_button.png")
, m_bPressed(false)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cTitleButton::Initialize(void)
{
IButton::Initialize();
cGame* game = (cGame*)GetRoot();
SetPos(game->GetWindowWidth() / 2.0f, game->GetWindowHeight() / 3 * 2);
// スプライトのRectを左半分にする
SetSrcRect(0, 0, this->GetGraphichSize().x / 2.0f, this->GetSpriteSize().y);
// Rectの大きさを変えたので中心位置を変更
m_vCenter.x = GetSpriteSize().x / 2.0f;
SetPriority(PRIORITY);
}
//==========================================================================================
// 押されていない時
//==========================================================================================
void cTitleButton::Neutral(void)
{
SetSrcRect(0, 0, this->GetGraphichSize().x / 2.0f, this->GetSpriteSize().y);
m_bPressed = false;
}
//==========================================================================================
// 押された瞬間
//==========================================================================================
void cTitleButton::Trigger(void)
{
SetSrcRect(this->GetGraphichSize().x / 2.0f, 0, this->GetGraphichSize().x / 2.0f, this->GetSpriteSize().y);
m_bPressed = true;
// スイッチ音
cSoundCtrl* sound = (cSoundCtrl*)GetRoot()->FindChild("SoundCtrl");
sound->Play(SOUND_ID::KACHI);
}
//==========================================================================================
// 押されている間
//==========================================================================================
void cTitleButton::Pressed(void)
{
if (m_bPressed) SetSrcRect(this->GetGraphichSize().x / 2.0f, 0, this->GetGraphichSize().x / 2.0f, this->GetSpriteSize().y);
else SetSrcRect(0, 0, this->GetGraphichSize().x / 2.0f, this->GetSpriteSize().y);
}
//==========================================================================================
// 離された瞬間
//==========================================================================================
void cTitleButton::Release(void)
{
SetSrcRect(0, 0, this->GetGraphichSize().x / 2.0f, this->GetSpriteSize().y);
// ボタンが押されてから離されたのでシーン遷移をする
if (m_bPressed)
{
cSceneManager* sm = (cSceneManager*)GetRoot()->FindChild("SceneManager");
if (sm)
{
sm->ChangeSceneUniTrans(SCENE_ID::TITLE, "data\\graphic\\rule_00.png");
}
}
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cPlayer.h */
/* @brief : プレイヤークラス */
/* @written : s.kosugi */
/* @create : 2018/12/03 */
/* */
/*==============================================================================*/
#include "..\..\cSpriteObject.h"
//================================================================================================
// プレイヤークラス
class cPlayer : public cSpriteObject
{
public:
cPlayer(IBaseObject* parent);
~cPlayer(void);
void Initialize(void) override;
void Update(void) override;
IBaseObject* Finalize(void) override;
private:
// プレイヤーの移動速度
static const float MOVE_SPEED;
// ゲーム開始位置
static const float START_POS_X;
static const float START_POS_Y;
// 表示優先度
static const int PRIORITY;
// プレイヤーのサイズ
static const short SIZE_X;
static const short SIZE_Y;
// 範囲外処理
void ProcAreaOut( void );
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cDataManager.h */
/* @brief : データ管理クラス */
/* @written : s.kosugi */
/* @create : 2020/01/27 */
/* */
/*==============================================================================*/
/* データ管理クラスの使い方
〇共通事項
1.データ管理クラスのセーブデータ構造体のメンバに事前に保存したい内容を追加しておく。
〇書き込み
1.データ管理クラスのセーブデータ変数の値を書き込んでおく(SetSaveData)
2.データ管理クラスを通してセーブファイルに書き込む(SaveFile)
〇読み込み
1.データ管理クラスにセーブファイルを読み込む(LoadFile)
2.データ管理クラスからセーブデータ変数を読み込む(GetSaveData)
*/
#include "..\BaseObject\IBaseObject.h"
class cDataManager : public IBaseObject
{
public:
// 破棄
IBaseObject* Finalize(void);
// セーブデータ構造体
// 保存対象の物をメンバに追加しておくこと
struct SaveData
{
int Score;
};
// セーブデータの取得
inline SaveData GetSaveData(void) { return m_SaveData; };
// セーブデータの設定
inline void SetSaveData(SaveData data) { m_SaveData = data; };
// ファイルへの保存
// 事前にSetSaveDataで中身を保存し、m_SaveDataの中身をファイルへと保存する
// filename : 書き込みファイル名
void SaveFile(std::string filename);
// ファイルの読み込み
// ファイルからm_SaveDataへと読み込む
// 読み込み後GetSaveDataで値を取得する
// filename : 読み込みファイル名
void LoadFile(std::string filename);
private:
SaveData m_SaveData; // セーブデータ構造体
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cDataManager(void) { }; // 他からの生成を禁止
cDataManager(IBaseObject* parent) { };
cDataManager(IBaseObject* parent, const std::string& name) { };
~cDataManager(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cDataManager(const cDataManager& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cDataManager& operator = (const cDataManager& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
static cDataManager& GetInstance(void) {
static cDataManager instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cSoundCtrl.cpp */
/* @brief : サウンド操作クラス */
/* @written : s.kosugi */
/* @create : 2018/11/30 */
/* */
/*==============================================================================*/
#include "cSoundCtrl.h"
#include <DxLib.h>
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif
//==========================================================================================
// 定数
//==========================================================================================
const int cSoundCtrl::LOADSOUND_FAILED = -1; // LoaSoundMem失敗
const int cSoundCtrl::DEFAULT_MASTER_VOLUME = 100; // 初期の全体音量
//==========================================================================================
// 初期化
//==========================================================================================
void cSoundCtrl::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "SoundCtrl";
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cSoundCtrl::Update(void)
{
switch (m_eBgmState)
{
case BGMSTATE::NORMAL:
break;
case BGMSTATE::FADEOUT:
UpdateFadeOut();
break;
case BGMSTATE::FADEIN:
UpdateFadeIn();
break;
case BGMSTATE::CROSSFADE:
UpdateCrossFade();
break;
}
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject* cSoundCtrl::Finalize(void)
{
IBaseObject::Finalize();
//------------------------------------------------------------------------------------
// 読み込み済みサウンドの解放
if (!m_listSdLoaded.empty())
{
InitSoundMem();
m_listSdLoaded.clear();
}
return nullptr;
}
//==========================================================================================
// サウンドの読み込み
// 戻り値 : 読み込み済みのサウンドハンドル
//==========================================================================================
int cSoundCtrl::Load(SOUND_ID id, int bufnum)
{
return Load(SOUNDNAME_TABLE[(int)id]);;
}
//==========================================================================================
// サウンドの読み込み
// 戻り値 : 読み込み済みのサウンドハンドル
//==========================================================================================
int cSoundCtrl::Load(const std::string & filename, int bufnum)
{
int handle = SearchSoundHandle(filename);
if (handle != LOADSOUND_FAILED) return handle;
// 新規読み込み音声をリストに追加する
SdLoaded load;
load.FileName = filename;
load.SoundHandle = LoadSoundMem(filename.c_str(), bufnum);
// サウンドハンドル読み込み失敗
if (LOADSOUND_FAILED == load.SoundHandle)
{
#ifdef DEBUG
cDebugFunc::GetInstance().PushDebugLog("LoadSoundFailed : " + filename);
#endif
return LOADSOUND_FAILED;
}
// 読み込み済みリストに追加
m_listSdLoaded.push_back(load);
return load.SoundHandle;
}
//==========================================================================================
// 全サウンドの読み込み
//==========================================================================================
void cSoundCtrl::LoadAll(void)
{
for (int i = 0; i < (int)SOUND_ID::MAX; i++)
{
Load(SOUNDNAME_TABLE[i]);
}
}
//==========================================================================================
// サウンドの削除
//==========================================================================================
void cSoundCtrl::Delete(SOUND_ID id)
{
Delete(SOUNDNAME_TABLE[(int)id]);
}
//==========================================================================================
// サウンドの削除
//==========================================================================================
void cSoundCtrl::Delete(const std::string & filename)
{
if (!m_listSdLoaded.empty()) {
//---------------------------------------------------------------------
std::list<SdLoaded>::iterator it = m_listSdLoaded.begin();
std::list<SdLoaded>::iterator end = m_listSdLoaded.end();
while (it != end)
{
if (it->FileName.compare(filename))
{
// メモリから削除
DeleteSoundMem(it->SoundHandle);
// リストから削除
m_listSdLoaded.erase(it);
return;
}
it++;
}
}
}
//==========================================================================================
// サウンドの再生
// return : 再生中の音声のハンドル
//==========================================================================================
int cSoundCtrl::Play(SOUND_ID id, bool loop)
{
return Play(SOUNDNAME_TABLE[(int)id], loop);
}
//==========================================================================================
// サウンドの再生
// return : 再生中の音声のハンドル
//==========================================================================================
int cSoundCtrl::Play(const std::string & filename, bool loop)
{
int handle = SearchSoundHandle(filename);
if (handle == LOADSOUND_FAILED)
{
// 未読み込みのサウンドだったら読み込む
handle = Load(filename);
// ロード失敗
if (handle == LOADSOUND_FAILED) return handle;
}
// マスターボリュームを設定する
ChangeVolumeSoundMem(m_nMasterVolume, handle);
// フェードアウト設定を初期化
m_nBgmVolumeFade[(int)BGMCHANNEL::MAIN] = 0;
// 再生タイプの設定
int PlayType;
if (loop) PlayType = DX_PLAYTYPE_LOOP;
else PlayType = DX_PLAYTYPE_BACK;
// サウンドの再生
PlaySoundMem(handle, PlayType, TRUE);
return handle;
}
//==========================================================================================
// BGMの再生
// return : 再生中の音声のハンドル
//==========================================================================================
int cSoundCtrl::BGMPlay(SOUND_ID id, BGMCHANNEL ch)
{
int handle = BGMPlay(SOUNDNAME_TABLE[(int)id], ch);
return handle;
}
//==========================================================================================
// BGMの再生
// return : 再生中の音声のハンドル
//==========================================================================================
int cSoundCtrl::BGMPlay(const std::string & filename, BGMCHANNEL ch)
{
int chHandle = SearchSoundHandle(filename);
// 再生中のBGMが設定された場合には処理をせずに音声ハンドルを返す
if (chHandle != -1 && CheckSoundMem(chHandle) == 1 && m_sPlayBgmName[(int)ch] == filename)
return chHandle;
int handle = Play(filename, true);
if (handle != LOADSOUND_FAILED)
{
BGMStop(ch);
m_sPlayBgmName[(int)ch] = filename;
}
return handle;
}
//==========================================================================================
// サウンドの停止
//==========================================================================================
void cSoundCtrl::Stop(SOUND_ID id)
{
Stop(SOUNDNAME_TABLE[(int)id]);
}
//==========================================================================================
// サウンドの停止
//==========================================================================================
void cSoundCtrl::Stop(const std::string & filename)
{
int handle = SearchSoundHandle(filename);
if (handle != LOADSOUND_FAILED)
{
StopSoundMem(handle);
}
}
//==========================================================================================
// BGMの停止
//==========================================================================================
void cSoundCtrl::BGMStop(BGMCHANNEL ch)
{
Stop(m_sPlayBgmName[(int)ch]);
}
//==========================================================================================
// マスターボリュームの変更
// int vol : 0〜255 0は無音 255は最大音量
//==========================================================================================
void cSoundCtrl::ChangeMasterVolume(int vol)
{
m_nMasterVolume = vol;
// 現在鳴っている音も変更する
for (int i = 0; i < (int)SOUND_ID::MAX; i++)
{
ChangeVolumeSoundMem(m_nMasterVolume, SearchSoundHandle(SOUNDNAME_TABLE[i]));
}
}
//==========================================================================================
// ボリュームの変更
// int vol : 0〜255 0は無音 255は最大音量
//==========================================================================================
void cSoundCtrl::ChangeVolume(SOUND_ID id, int vol)
{
ChangeVolume(SOUNDNAME_TABLE[(int)id], vol);
}
//==========================================================================================
// ボリュームの変更
// int vol : 0〜255 0は無音 255は最大音量
//==========================================================================================
void cSoundCtrl::ChangeVolume(const std::string & filename, int vol)
{
int handle = SearchSoundHandle(filename);
if (LOADSOUND_FAILED == handle) return;
ChangeVolumeSoundMem(vol, handle);
}
//==========================================================================================
// BGMのフェードアウトの設定
// int frame : フェードアウト時間
//==========================================================================================
void cSoundCtrl::FadeOutBgm(unsigned int frame)
{
int handle = SearchSoundHandle(m_sPlayBgmName[(int)BGMCHANNEL::MAIN]);
if (handle == LOADSOUND_FAILED) return;
int volume = GetVolumeSoundMem(handle);
m_nBgmVolumeFade[(int)BGMCHANNEL::MAIN] = (int)(((float)volume / frame) + 0.5f);
m_eBgmState = BGMSTATE::FADEOUT;
}
//==========================================================================================
// BGMのフェードインの設定
// int frame : フェードイン時間
// 同じBGMIDをフェードインさせる場合は前フレームで停止してある必要がある(DXLibの再生の仕様)
//==========================================================================================
void cSoundCtrl::FadeInBgm(unsigned int frame, SOUND_ID id, BGMCHANNEL ch)
{
int handle = BGMPlay(id, ch);
if (handle == LOADSOUND_FAILED) return;
// マスターボリュームを100分の1デシベル単位で取得
ChangeVolumeSoundMem(m_nMasterVolume, handle);
int volume = GetVolumeSoundMem(handle);
ChangeVolume(id, 0);
m_nBgmVolumeFade[(int)ch] = (int)(((float)volume / frame) + 0.5f);
m_eBgmState = BGMSTATE::FADEIN;
}
//==========================================================================================
// BGMのフェードインの設定
// int outframe : フェードイン時間
// int inframe : フェードアウト時間
// SoundID id : フェードインさせるSoundID
//==========================================================================================
void cSoundCtrl::CrossFadeBgm(unsigned int outframe, unsigned int inframe, SOUND_ID id)
{
FadeOutBgm(outframe);
FadeInBgm(inframe, id, BGMCHANNEL::SWAP);
m_eBgmState = BGMSTATE::CROSSFADE;
}
//==========================================================================================
// 周波数の設定
//==========================================================================================
void cSoundCtrl::SetFrequency(SOUND_ID id, int value)
{
SetFrequencySoundMem(value, SearchSoundHandle(SOUNDNAME_TABLE[(int)id]));
}
//==========================================================================================
// 周波数の設定
//==========================================================================================
void cSoundCtrl::SetFrequency(const std::string & filename, int value)
{
SetFrequencySoundMem(value, SearchSoundHandle(filename));
}
//==========================================================================================
// 周波数の取得
//==========================================================================================
int cSoundCtrl::GetFrequency(SOUND_ID id)
{
return GetFrequencySoundMem(SearchSoundHandle(SOUNDNAME_TABLE[(int)id]));
}
//==========================================================================================
// 周波数の取得
//==========================================================================================
int cSoundCtrl::GetFrequency(const std::string & filename)
{
return GetFrequencySoundMem(SearchSoundHandle(filename));
}
//==========================================================================================
// 指定した音声が再生中かを調べる
//==========================================================================================
bool cSoundCtrl::CheckPlaySound(SOUND_ID id)
{
return CheckPlaySound(SOUNDNAME_TABLE[(int)id]);
}
//==========================================================================================
// 指定した音声が再生中かを調べる
//==========================================================================================
bool cSoundCtrl::CheckPlaySound(const std::string& filename)
{
int handle = SearchSoundHandle(filename);
if (handle != LOADSOUND_FAILED)
{
if (CheckSoundMem(handle)) return true;
}
return false;
}
//==========================================================================================
// サウンドハンドルの検索
// 戻り値:サウンドハンドル LOADSOUND_FAILED:失敗
//==========================================================================================
int cSoundCtrl::SearchSoundHandle(const std::string & filename)
{
if (!m_listSdLoaded.empty())
{
//---------------------------------------------------------------------
std::list<SdLoaded>::iterator it = m_listSdLoaded.begin();
std::list<SdLoaded>::iterator end = m_listSdLoaded.end();
while (it != end)
{
SdLoaded load = ((SdLoaded)(*it));
if (load.FileName == filename)
{
return load.SoundHandle;
}
it++;
}
}
return LOADSOUND_FAILED;
}
//==========================================================================================
// フェードアウトの更新処理
//==========================================================================================
void cSoundCtrl::UpdateFadeOut(void)
{
if (m_nBgmVolumeFade[(int)BGMCHANNEL::MAIN] > 0)
{
int handle = SearchSoundHandle(m_sPlayBgmName[(int)BGMCHANNEL::MAIN]);
if (handle != LOADSOUND_FAILED)
{
int volume = GetVolumeSoundMem(handle);
volume -= m_nBgmVolumeFade[(int)BGMCHANNEL::MAIN];
if (volume <= 0)
{
volume = 0;
m_nBgmVolumeFade[(int)BGMCHANNEL::MAIN] = 0;
m_eBgmState = BGMSTATE::NORMAL;
BGMStop(BGMCHANNEL::MAIN);
// 減らしたボリュームを戻しておく
ChangeVolumeSoundMem(m_nMasterVolume, handle);
return;
}
SetVolumeSoundMem(volume, handle);
}
}
else
{
m_eBgmState = BGMSTATE::NORMAL;
}
}
//==========================================================================================
// フェードインの更新処理
//==========================================================================================
void cSoundCtrl::UpdateFadeIn(void)
{
if (m_nBgmVolumeFade[(int)BGMCHANNEL::MAIN] > 0)
{
int handle = SearchSoundHandle(m_sPlayBgmName[(int)BGMCHANNEL::MAIN]);
if (handle != LOADSOUND_FAILED)
{
int volume = GetVolumeSoundMem(handle);
volume += m_nBgmVolumeFade[(int)BGMCHANNEL::MAIN];
// マスターボリュームを100分の1デシベル単位で取得する
ChangeVolumeSoundMem(m_nMasterVolume, handle);
int masterVolume = GetVolumeSoundMem(handle);
if (volume >= masterVolume)
{
volume = masterVolume;
m_nBgmVolumeFade[(int)BGMCHANNEL::MAIN] = 0;
m_eBgmState = BGMSTATE::NORMAL;
}
SetVolumeSoundMem(volume, handle);
}
}
else
{
m_eBgmState = BGMSTATE::NORMAL;
}
}
//==========================================================================================
// クロスフェードの更新処理
//==========================================================================================
void cSoundCtrl::UpdateCrossFade(void)
{
bool fadeOutComp = false;
bool fadeInComp = false;
//-----------------------------------------------------------------------------
// フェードアウト部分
if (m_nBgmVolumeFade[(int)BGMCHANNEL::MAIN] > 0)
{
int handle = SearchSoundHandle(m_sPlayBgmName[(int)BGMCHANNEL::MAIN]);
if (handle != LOADSOUND_FAILED)
{
int volume = GetVolumeSoundMem(handle);
volume -= m_nBgmVolumeFade[(int)BGMCHANNEL::MAIN];
if (volume <= 0)
{
volume = 0;
m_nBgmVolumeFade[(int)BGMCHANNEL::MAIN] = 0;
fadeOutComp = true;
BGMStop(BGMCHANNEL::MAIN);
// 減らしたボリュームを戻しておく
ChangeVolumeSoundMem(m_nMasterVolume, handle);
}
if (!fadeOutComp) SetVolumeSoundMem(volume, handle);
}
}
else
{
fadeOutComp = true;
}
//-----------------------------------------------------------------------------
// フェードイン部分
if (m_nBgmVolumeFade[(int)BGMCHANNEL::SWAP] > 0)
{
int handle = SearchSoundHandle(m_sPlayBgmName[(int)BGMCHANNEL::SWAP]);
if (handle != LOADSOUND_FAILED)
{
int volume = GetVolumeSoundMem(handle);
volume += m_nBgmVolumeFade[(int)BGMCHANNEL::SWAP];
// マスターボリュームを100分の1デシベル単位で取得する
ChangeVolumeSoundMem(m_nMasterVolume, handle);
int masterVolume = GetVolumeSoundMem(handle);
if (volume >= masterVolume)
{
volume = masterVolume;
m_nBgmVolumeFade[(int)BGMCHANNEL::SWAP] = 0;
fadeInComp = true;
}
SetVolumeSoundMem(volume, handle);
}
}
else
{
fadeInComp = true;
}
// クロスフェード終了
if (fadeOutComp && fadeInComp)
{
m_sPlayBgmName[(int)BGMCHANNEL::MAIN] = m_sPlayBgmName[(int)BGMCHANNEL::SWAP];
m_sPlayBgmName[(int)BGMCHANNEL::SWAP] = "";
m_eBgmState = BGMSTATE::NORMAL;
}
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cSoundCtrl::cSoundCtrl(void) :
m_nMasterVolume(DEFAULT_MASTER_VOLUME),
m_nBgmVolumeFade(),
m_eBgmState(BGMSTATE::NORMAL)
{
for (int i = 0; i < (int)BGMCHANNEL::NUM; i++) m_nBgmVolumeFade[i] = 0;
m_listSdLoaded.clear();
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cSoundCtrl::cSoundCtrl(IBaseObject* parent) :
cSoundCtrl::cSoundCtrl()
{
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cSoundCtrl::cSoundCtrl(IBaseObject* parent, const std::string& name) :
cSoundCtrl::cSoundCtrl(parent)
{
}
//==========================================================================================
// コピーコンストラクタ
//==========================================================================================
cSoundCtrl::cSoundCtrl(const cSoundCtrl& t) :
cSoundCtrl::cSoundCtrl()
{
}
<file_sep>/*==============================================================================*/
/* */
/* @file title : cGameMain.cpp */
/* @brief : ゲームメインシーン */
/* @written : s.kosugi */
/* @create : 2018/12/02 */
/* */
/*==============================================================================*/
#include "cGameMain.h"
#include "cGame.h"
#include "..\..\cSceneManager.h"
#include "BaseObject\cSpriteObject.h"
#include "BaseObject\GameObject\Player\cPlayer.h"
#include "BaseObject/GameObject/Bullet/cBulletManager.h"
#include "BaseObject/GameObject/Enemy/cEnemyManager.h"
#include "DataManager/cDataManager.h"
#include "BaseObject/GameObject/UI/cUIManager.h"
#include "ScoreManager/cScoreManager.h"
#include "BaseObject/GameObject/GameStartObject/cReadyFont.h"
#include "BaseObject/GameObject/GameStartObject/cGoFont.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif
//==========================================================================================
// 定数
//==========================================================================================
const short cGameMain::MAX_DIFFICULT = 10; // 最大難易度
const float cGameMain::LEVELUP_TIME = 10.0f; // 難易度が上がるまでの時間(秒)
//==========================================================================================
// コンストラクタ
//==========================================================================================
cGameMain::cGameMain(IBaseObject * parent)
: IBaseScene(parent, "GameMain")
, m_nDifficult( 0 )
, m_eState( STATE::START )
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cGameMain::~cGameMain(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cGameMain::Initialize(void)
{
// ゲームクラスの取得
cGame* game = (cGame*)GetRoot();
// 背景スプライトの生成
cSpriteObject* obj = CreateDrawObject<cSpriteObject>(this, "BackGround", "data\\graphic\\background.png");
obj->SetPriority(-100);
obj->SetPos((float)game->GetWindowWidth()/2, (float)game->GetWindowHeight() / 2);
// プレイヤーキャラクターの生成
CreateObject<cPlayer>(this);
// 弾管理クラスの生成
CreateObject<cBulletManager>(this);
// スコア管理クラスの取得
cScoreManager* score = (cScoreManager*)GetRoot()->FindChild("ScoreManager");
// スコアリセット
score->ResetScore();
// UI管理クラスの生成
cUIManager* um = CreateObject<cUIManager>(this);
// スコアボードの生成
um->Create(UIID::SCORE_BOARD,{ 100,50 });
// ゲーム開始演出用文字スプライト生成
CreateObject<cReadyFont>(this);
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cGameMain::Update(void)
{
switch (m_eState) {
case START: Start(); break;
case PLAY: Play(); break;
case OVER: Over(); break;
default: break;
}
IBaseObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject* cGameMain::Finalize(void)
{
ControlGameLevel();
IBaseObject::Finalize();
return this;
}
//==========================================================================================
// ゲームレベル制御関数
//==========================================================================================
void cGameMain::ControlGameLevel(void)
{
// 段階的にゲームを難しくするための処理
cTimer* lvTimer = (cTimer*)FindChild("LevelUpTimer");
if (lvTimer)
{
if (lvTimer->Finished())
{
// レベルアップタイマーを初期化して難易度を1段階上げる
lvTimer->Reset();
m_nDifficult++;
if (m_nDifficult >= MAX_DIFFICULT) m_nDifficult = MAX_DIFFICULT;
}
}
else
{
// レベルアップタイマーの生成
lvTimer = CreateObject<cTimer>(this, "LevelUpTimer");
lvTimer->Setup(LEVELUP_TIME);
}
}
//==========================================================================================
// ゲーム開始時
//==========================================================================================
void cGameMain::Start(void)
{
cReadyFont* ready = (cReadyFont*)FindChild("ReadyFont");
cGoFont* go = (cGoFont*)FindChild("GoFont");
// 演出終了したらゲームプレイ状態にする
if (ready == nullptr && go == nullptr)
{
m_eState = STATE::PLAY;
// 敵管理クラスの生成
CreateObject<cEnemyManager>(this);
}
}
//==========================================================================================
// プレイ中
//==========================================================================================
void cGameMain::Play(void)
{
// ゲームレベルの制御
ControlGameLevel();
}
//==========================================================================================
// ゲームオーバー
//==========================================================================================
void cGameMain::Over(void)
{
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cEnmRed.h */
/* @brief : 赤い敵クラス */
/* @written : s.kosugi */
/* @create : 2020/07/20 */
/* */
/*==============================================================================*/
#include "..\IEnemy.h"
//================================================================================================
// 赤い敵クラス
class cEnmRed : public IEnemy
{
public:
cEnmRed(IBaseObject* parent);
~cEnmRed(void);
// 初期化
void Initialize(const cVector2& pos) override;
// 更新
void Update(void) override;
enum class ACTION_STATE
{
START,
STOP,
RESTART
};
private:
//--------------------------------------------------------------------------------------------
// 定数
// 表示優先度
static const int PRIORITY;
// 基本移動力
static const float BASE_SPEED;
// 自転速度
static const float ROTATE_SPEED;
// 停止距離
static const float STOP_DIST;
// 停止にかかる時間
static const float STOP_TIME;
// 再始動にかかる時間
static const float RESTART_TIME;
// 再始動最大速度
static const float RESTART_MAX_SPEED;
//--------------------------------------------------------------------------------------------
ACTION_STATE m_eActionState;
void Start(void);
void Stop(void);
void Restart(void);
};
//================================================================================================<file_sep>#pragma once
enum class SOUND_ID
{
BOM, // ”𔉹
BGM, // BGM
MAX
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cStartFont.h */
/* @brief : スタートの文字クラス */
/* @written : s.kosugi */
/* @create : 2020/08/31 */
/* */
/*==============================================================================*/
#include "..\..\..\cSpriteObject.h"
//================================================================================================
// スタートの文字クラス
class cStartFont : public cSpriteObject
{
public:
cStartFont(IBaseObject* parent);
~cStartFont(void);
void Initialize(void) override;
void Update(void) override;
private:
//--------------------------------------------------------------------------------------------
// 定数
// 表示優先度
static const int PRIORITY;
static const float MOVE_TIME;
static const float FADE_TIME;
//--------------------------------------------------------------------------------------------
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cXController.h */
/* @brief : XBoxコントローラー入力クラス */
/* @written : s.kosugi */
/* @create : 2019/03/22 */
/* */
/*==============================================================================*/
#include "..\..\BaseObject\IBaseObject.h"
#include <DxLib.h>
class cXController : public IBaseObject
{
public:
//--------------------------------------------------------------------
// スティック入力方向
enum class STICK_DIRECTION
{
LEFT = 0,
RIGHT,
UP,
DOWN,
};
// 初期化
void Initialize(void) override;
// 更新
void Update(void) override;
// ボタン押下チェック
bool CheckButton(unsigned int kcode, int InputType = DX_INPUT_PAD1); // 押しているか
bool CheckTrigger(unsigned int kcode, int InputType = DX_INPUT_PAD1); // 押した瞬間
bool CheckRelease(unsigned int kcode, int InputType = DX_INPUT_PAD1); // 離した瞬間
// 振動の開始
// Power : 0 〜 1000
// Time : 振動時間
// InputType : パッド識別子 DX_INPUT_PAD1〜4
void StartVibration(int Power, int Time, int InputType = DX_INPUT_PAD1);
// 振動の停止
// InputType : パッド識別子 DX_INPUT_PAD1〜4
void StopVibration(int InputType = DX_INPUT_PAD1);
// 左スティックの取得
// InputType : パッド識別子 DX_INPUT_PAD1〜4
POINT GetLeftAnalogInput(int InputType = DX_INPUT_PAD1);
// 右スティックの取得
// InputType : パッド識別子 DX_INPUT_PAD1〜4
POINT GetRightAnalogInput(int InputType = DX_INPUT_PAD1);
// 左アナログスティックのトリガー判定
// direction direction 方向ID
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 : true 倒された瞬間
bool IsTriggerLeftAnalog(STICK_DIRECTION direction, int InputType = DX_INPUT_PAD1);
// 右アナログスティックのトリガー判定
// direction direction 方向ID
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 : true 倒された瞬間
bool IsTriggerRightAnalog(STICK_DIRECTION direction, int InputType = DX_INPUT_PAD1);
// 左トリガーの取得
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// 戻り値 : 左トリガー入力値
unsigned char GetLeftTriggerInput(int InputType = DX_INPUT_PAD1);
// 右トリガーの取得
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// 戻り値 : 右トリガー入力値
unsigned char GetRightTriggerInput(int InputType = DX_INPUT_PAD1);
// 左トリガーのトリガー判定
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 : true 押された瞬間
bool IsTriggerLeftTrigger(int InputType = DX_INPUT_PAD1);
// 右トリガーのトリガー判定
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 : true 押された瞬間
bool IsTriggerRightTrigger(int InputType = DX_INPUT_PAD1);
// 左トリガーのボタン判定
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 : true 押されてる間
bool IsButtonLeftTrigger(int InputType = DX_INPUT_PAD1);
// 右トリガーのボタン判定
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 : true 押されてる間
bool IsButtonRightTrigger(int InputType = DX_INPUT_PAD1);
// 左トリガーのリリース判定
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 : true 離された瞬間
bool IsReleaseLeftTrigger(int InputType = DX_INPUT_PAD1);
// 右トリガーのリリース判定
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 : true 離された瞬間
bool IsReleaseRightTrigger(int InputType = DX_INPUT_PAD1);
// 接続台数取得
// 戻り値 : 接続台数
inline int GetConnectNum(void) { return m_nJoyPadNum; };
private:
// XInput Joypad state
XINPUT_STATE* m_xiInputState;
// 前フレーム情報
XINPUT_STATE* m_xiPrevInputState;
// Xコントローラー接続数
short m_nJoyPadNum;
//--------------------------------------------------------------------
// 定数
static const int LIMIT_CANT_ANALOG; // アナログスティックの遊び
static const int LIMIT_CANT_TRIGGER; // トリガーの遊び
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cXController(void); // 他からの生成を禁止
cXController(IBaseObject* parent);
cXController(IBaseObject* parent, const std::string& name);
~cXController(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cXController(const cXController& t); // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cXController& operator = (const cXController& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
// シングルトンオブジェクトにはDELETEアクセスをさせない。
IBaseObject* Finalize(void) override { IBaseObject::Finalize(); return nullptr; };
static cXController& GetInstance(void) {
static cXController instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cMovieManager.cpp */
/* @brief : 動画管理クラス */
/* @written : s.kosugi */
/* @create : 2019/03/06 */
/* */
/*==============================================================================*/
#include "cMovieManager.h"
#include "..\cGame.h"
#include <DxLib.h>
//==========================================================================================
// 定数
//==========================================================================================
// 初期化
//==========================================================================================
void cMovieManager::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "MovieManager";
m_ePlayState = STATE_WAIT;
m_nGraphHandle = LOADMOVIE_NONE;
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cMovieManager::Update(void)
{
IBaseObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject * cMovieManager::Finalize(void)
{
IBaseObject::Finalize();
Unload();
return nullptr;
}
//==========================================================================================
// 動画ファイルの読み込み
//==========================================================================================
void cMovieManager::Load(std::string filename)
{
// 既に読み込まれている動画がある場合は削除してからロード
if (m_nGraphHandle != LOADMOVIE_NONE) DeleteGraph(m_nGraphHandle);
m_nGraphHandle = LoadGraph(filename.c_str());
m_ePlayState = STATE_WAIT;
}
//==========================================================================================
// 動画ファイルの読み込み
//==========================================================================================
void cMovieManager::Load(MovieID id)
{
Load(MOVIEFILE_TABLE[id]);
}
//==========================================================================================
// 動画の再生開始
//==========================================================================================
void cMovieManager::Start(void)
{
if ( m_nGraphHandle == LOADMOVIE_NONE ) return;
if (0 == GetMovieStateToGraph(m_nGraphHandle) && m_ePlayState == STATE_WAIT)
{
// 再生開始
PlayMovieToGraph(m_nGraphHandle);
m_ePlayState = STATE_PLAY;
}
}
//==========================================================================================
// 動画データの再生
//==========================================================================================
void cMovieManager::Play(void)
{
if( m_nGraphHandle == LOADMOVIE_NONE ) return;
// 動画再生中は実行速度を落とす
cGame::GetInstance().SetFPS(PLAYMOVIE_FPS);
// 再生終了
if(0 == GetMovieStateToGraph(m_nGraphHandle))
{
// 動画が終了したので停止
Stop();
return;
}
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 255);
SetDrawBright(255, 255, 255);
// 動画の描画
DrawExtendGraph(0,0,cGame::GetInstance().GetWindowWidth(),cGame::GetInstance().GetWindowHeight(),m_nGraphHandle,FALSE);
}
//==========================================================================================
// 動画停止
//==========================================================================================
void cMovieManager::Stop(void)
{
m_ePlayState = STATE_STOP;
cGame::GetInstance().ResetFPS();
Unload();
}
//==========================================================================================
// 動画データの解放
//==========================================================================================
void cMovieManager::Unload(void)
{
if (m_nGraphHandle != LOADMOVIE_NONE) DeleteGraph(m_nGraphHandle);
m_nGraphHandle = LOADMOVIE_NONE;
}
<file_sep>/*==============================================================================*/
/* */
/* @file title : cTitleLogo.cpp */
/* @brief : タイトルロゴクラス */
/* @written : s.kosugi */
/* @create : 2020/09/02 */
/* */
/*==============================================================================*/
#include "cTitleLogo.h"
#include "cGame.h"
#include "Utility/Timer/cTimer.h"
#include "Utility/Easing/Easing.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cTitleLogo::PRIORITY = 1000;
const float cTitleLogo::SCALE_INCREMENT = 7.5f;
const float cTitleLogo::WAIT_TIME = 1.0f;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cTitleLogo::cTitleLogo(IBaseObject* parent)
: cSpriteObject(parent, "TitleLogo", "data\\graphic\\TitleLogo.png")
, m_eState( STATE::SCALE)
, m_fScaleCurve( 0.0f )
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cTitleLogo::~cTitleLogo(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cTitleLogo::Initialize(void)
{
SetPriority(PRIORITY);
cGame* game = (cGame*)GetRoot();
// 中央に配置
SetPos(game->GetWindowCenter());
cSpriteObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cTitleLogo::Update(void)
{
switch (m_eState)
{
case STATE::SCALE: Scale(); break;
case STATE::WAIT: Wait(); break;
default: break;
}
cSpriteObject::Update();
}
//==========================================================================================
// 拡大時処理
//==========================================================================================
void cTitleLogo::Scale(void)
{
m_fScaleCurve += SCALE_INCREMENT;
float scale = sin(DEG_TO_RAD(m_fScaleCurve)) * 0.5f + 1.0f;
if (scale <= 1.0f)
{
scale = 1.0f;
m_eState = STATE::WAIT;
// sinカーブに使う値をリセット
m_fScaleCurve = 0.0f;
}
SetScale(scale);
}
//==========================================================================================
// 待機処理
//==========================================================================================
void cTitleLogo::Wait(void)
{
cTimer* timer = (cTimer*)FindChild("TitleWaitTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this,"TitleWaitTimer");
timer->Setup(WAIT_TIME);
}
if (timer->Finished())
{
timer->DeleteObject();
m_eState = STATE::SCALE;
}
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cCsvReader.h */
/* @brief : CSV読み込みクラス */
/* @written : s.kosugi */
/* @create : 2018/12/08 */
/* */
/*==============================================================================*/
#include "BaseObject\IBaseObject.h"
#include <string>
#include <vector>
// CSV読み込みクラス
class cCsvReader : public IBaseObject
{
public:
cCsvReader(IBaseObject* parent);
~cCsvReader();
// CSVファイル読み込み
void LoadFile(const std::string filepath);
// 指定されたデータを文字列で取得
const std::string GetString(int row, int col);
// 指定されたデータを整数で取得
const int GetInt(int row, int col);
// 指定されたデータを小数で取得
const float GetFloat(int row, int col);
// 列数の取得
const int GetRowNum(void);
// 行数の取得
const int GetColNum(void);
// 項目数の取得
const int GetDataNum(void);
private:
// 定数
static const int LINE_CHAR_MAX; // 1行当たりの最大文字数
// 読み込みデータ
std::vector<std::string> m_Buffer;
// 行数
int m_RowNum;
};<file_sep>#pragma once
enum class BULLET_ID
{
NORMAL = 0,
LASER,
MAX
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cXController.cpp */
/* @brief : XBOXコントローラー入力クラス */
/* @written : s.kosugi */
/* @create : 2019/03/22 */
/* */
/*==============================================================================*/
#include "cXController.h"
#include "../../Utility/memory.h"
//==========================================================================================
// 定数
const int cXController::LIMIT_CANT_ANALOG = 30000;
const int cXController::LIMIT_CANT_TRIGGER = 200;
//==========================================================================================
// 初期化
//==========================================================================================
void cXController::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "XController";
// コントローラー接続数を取得
m_nJoyPadNum = GetJoypadNum();
// 接続されているコントローラー数分だけキー情報を作成する
m_xiInputState = NEW XINPUT_STATE[m_nJoyPadNum];
m_xiPrevInputState = NEW XINPUT_STATE[m_nJoyPadNum];
memset(m_xiInputState, 0, m_nJoyPadNum * sizeof(XINPUT_STATE));
memset(m_xiPrevInputState, 0, m_nJoyPadNum * sizeof(XINPUT_STATE));
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cXController::Update(void)
{
for (int i = 1; i <= m_nJoyPadNum; i++)
{
// 入力状態を取得する
memcpy(&m_xiPrevInputState[i - 1], &m_xiInputState[i - 1], sizeof(XINPUT_STATE));
GetJoypadXInputState(i, &m_xiInputState[i - 1]);
}
IBaseObject::Update();
}
//==========================================================================================
// ボタン押下チェック
//
// unsigned int kcode チェックするボタン
// XINPUT_BUTTON_A : Aボタン
// XINPUT_BUTTON_DPAD_UP : 上ボタン
// …
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
//
// 戻り値 true:押されていた false:押されていない
//==========================================================================================
bool cXController::CheckButton(unsigned int kcode, int InputType)
{
if (InputType > m_nJoyPadNum) return false;
// ボタンが押されているかどうか
if (m_xiInputState[InputType - 1].Buttons[kcode])
return true;
return false;
}
//==========================================================================================
// 押した瞬間をチェック
//
// unsigned int kcode チェックするボタン
// XINPUT_BUTTON_A : Aボタン
// XINPUT_BUTTON_DPAD_UP : 上ボタン
// …
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
//
// 戻り値 true:押されていた
//==========================================================================================
bool cXController::CheckTrigger(unsigned int kcode, int InputType)
{
if (InputType > m_nJoyPadNum) return false;
// ボタンが押された瞬間
if (!(m_xiPrevInputState[InputType - 1].Buttons[kcode]) && (m_xiInputState[InputType - 1].Buttons[kcode])) return true;
return false;
}
//==========================================================================================
// 離した瞬間をチェック
//
// unsigned int kcode チェックするボタン
// XINPUT_BUTTON_A : Aボタン
// XINPUT_BUTTON_DPAD_UP : 上ボタン
// …
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
//
// 戻り値 true:離された瞬間
//==========================================================================================
bool cXController::CheckRelease(unsigned int kcode, int InputType)
{
if (InputType > m_nJoyPadNum) return false;
// ボタンが離された瞬間
if ((m_xiPrevInputState[InputType - 1].Buttons[kcode]) && !(m_xiInputState[InputType - 1].Buttons[kcode])) return true;
return false;
}
//==========================================================================================
// 振動の開始
// Power : 0 〜 1000
// Time : 振動時間
// InputType : パッド識別子 DX_INPUT_PAD1〜4
//==========================================================================================
void cXController::StartVibration(int Power, int Time, int InputType)
{
StartJoypadVibration(InputType, Power, Time);
}
//==========================================================================================
// 振動の停止
// InputType : パッド識別子 DX_INPUT_PAD1〜4
//==========================================================================================
void cXController::StopVibration(int InputType)
{
StopJoypadVibration(InputType);
}
//==========================================================================================
// 左スティックの取得
//
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 POINT -32768 〜 32767までの値
//
//==========================================================================================
POINT cXController::GetLeftAnalogInput(int InputType)
{
POINT pt;
pt.x = m_xiInputState[InputType - 1].ThumbLX;
pt.y = m_xiInputState[InputType - 1].ThumbLY;
return pt;
}
//==========================================================================================
// 右スティックの取得
//
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 POINT -32768 〜 32767までの値
//
//==========================================================================================
POINT cXController::GetRightAnalogInput(int InputType)
{
POINT pt;
pt.x = m_xiInputState[InputType - 1].ThumbRX;
pt.y = m_xiInputState[InputType - 1].ThumbRY;
return pt;
}
//==========================================================================================
// 左アナログスティックのトリガー判定
// STICK_DIRECTION direction 方向ID
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 : true 倒された瞬間
//==========================================================================================
bool cXController::IsTriggerLeftAnalog(STICK_DIRECTION direction, int InputType)
{
switch (direction)
{
case STICK_DIRECTION::LEFT:
return (m_xiInputState[InputType - 1].ThumbLX < LIMIT_CANT_ANALOG&& m_xiPrevInputState[InputType - 1].ThumbLX > LIMIT_CANT_ANALOG);
case STICK_DIRECTION::RIGHT:
return (m_xiInputState[InputType - 1].ThumbLX > LIMIT_CANT_ANALOG && m_xiPrevInputState[InputType - 1].ThumbLX < LIMIT_CANT_ANALOG);
case STICK_DIRECTION::UP:
return (m_xiInputState[InputType - 1].ThumbLY < LIMIT_CANT_ANALOG&& m_xiPrevInputState[InputType - 1].ThumbLY > LIMIT_CANT_ANALOG);
case STICK_DIRECTION::DOWN:
return (m_xiInputState[InputType - 1].ThumbLY > LIMIT_CANT_ANALOG && m_xiPrevInputState[InputType - 1].ThumbLY < LIMIT_CANT_ANALOG);
}
return false;
}
//==========================================================================================
// 右アナログスティックのトリガー判定
// STICK_DIRECTION direction 方向ID
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 : true 倒された瞬間
//==========================================================================================
bool cXController::IsTriggerRightAnalog(STICK_DIRECTION direction, int InputType)
{
switch (direction)
{
case STICK_DIRECTION::LEFT:
return (m_xiInputState[InputType - 1].ThumbRX < LIMIT_CANT_ANALOG&& m_xiPrevInputState[InputType - 1].ThumbRX > LIMIT_CANT_ANALOG);
case STICK_DIRECTION::RIGHT:
return (m_xiInputState[InputType - 1].ThumbRX > LIMIT_CANT_ANALOG && m_xiPrevInputState[InputType - 1].ThumbRX < LIMIT_CANT_ANALOG);
case STICK_DIRECTION::UP:
return (m_xiInputState[InputType - 1].ThumbRY < LIMIT_CANT_ANALOG&& m_xiPrevInputState[InputType - 1].ThumbRY > LIMIT_CANT_ANALOG);
case STICK_DIRECTION::DOWN:
return (m_xiInputState[InputType - 1].ThumbRY > LIMIT_CANT_ANALOG && m_xiPrevInputState[InputType - 1].ThumbRY < LIMIT_CANT_ANALOG);
}
return false;
}
//==========================================================================================
// 左トリガーの取得
//
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 unsigned char 0 〜 255までの値
//
//==========================================================================================
unsigned char cXController::GetLeftTriggerInput(int InputType)
{
return m_xiInputState[InputType - 1].LeftTrigger;
}
//==========================================================================================
// 右トリガーの取得
//
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 unsigned char 0 〜 255までの値
//
//==========================================================================================
unsigned char cXController::GetRightTriggerInput(int InputType)
{
return m_xiInputState[InputType - 1].RightTrigger;
}
//==========================================================================================
// 左トリガーのトリガー判定
//
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 bool true 押した瞬間
//
//==========================================================================================
bool cXController::IsTriggerLeftTrigger(int InputType)
{
return (m_xiInputState[InputType - 1].LeftTrigger > LIMIT_CANT_TRIGGER && m_xiPrevInputState[InputType - 1].LeftTrigger < LIMIT_CANT_TRIGGER);
}
//==========================================================================================
// 右トリガーのトリガー判定
//
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 bool true 押した瞬間
//
//==========================================================================================
bool cXController::IsTriggerRightTrigger(int InputType)
{
return (m_xiInputState[InputType - 1].RightTrigger > LIMIT_CANT_TRIGGER && m_xiPrevInputState[InputType - 1].RightTrigger < LIMIT_CANT_TRIGGER);
}
//==========================================================================================
// 左トリガーのボタン判定
//
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 bool true 押している間
//
//==========================================================================================
bool cXController::IsButtonLeftTrigger(int InputType)
{
return (m_xiInputState[InputType - 1].LeftTrigger > LIMIT_CANT_TRIGGER);
}
//==========================================================================================
// 右トリガーのボタン判定
//
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 bool true 押している間
//
//==========================================================================================
bool cXController::IsButtonRightTrigger(int InputType)
{
return (m_xiInputState[InputType - 1].RightTrigger > LIMIT_CANT_TRIGGER);
}
//==========================================================================================
// 左トリガーのリリース判定
//
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 bool true 離された瞬間
//
//==========================================================================================
bool cXController::IsReleaseLeftTrigger(int InputType)
{
return (m_xiInputState[InputType - 1].LeftTrigger < LIMIT_CANT_TRIGGER&& m_xiPrevInputState[InputType - 1].LeftTrigger > LIMIT_CANT_TRIGGER);
}
//==========================================================================================
// 右トリガーのリリース判定
//
// int InputType パッド識別子
// DX_INPUT_PAD1 : パッド1
// DX_INPUT_PAD1 : パッド2
// …
// 戻り値 bool true 離された瞬間
//
//==========================================================================================
bool cXController::IsReleaseRightTrigger(int InputType)
{
return (m_xiInputState[InputType - 1].RightTrigger < LIMIT_CANT_TRIGGER&& m_xiPrevInputState[InputType - 1].RightTrigger > LIMIT_CANT_TRIGGER);
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cXController::cXController(void) :
m_xiInputState(nullptr),
m_xiPrevInputState(nullptr),
m_nJoyPadNum(0)
{
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cXController::cXController(IBaseObject* parent) :
cXController::cXController()
{
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cXController::cXController(IBaseObject* parent, const std::string& name) :
cXController::cXController(parent)
{
}
//==========================================================================================
// コピーコンストラクタ
//==========================================================================================
cXController::cXController(const cXController& t) :
cXController::cXController()
{
}
<file_sep>#pragma once
enum class SOUND_ID
{
DECISION, // 決定音
BOM, // 爆発音
SHOT, // ショット
KACHI, // スイッチの音
LASER, // レーザー
BGM, // BGM
MAX
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cBomLaser.cpp */
/* @brief : レーザー(ボム)クラス */
/* @written : s.kosugi */
/* @create : 2020/07/20 */
/* */
/*==============================================================================*/
#include "cBomLaser.h"
#include "Utility/Timer/cTimer.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cBomLaser::PRIORITY = 300;
const float cBomLaser::HIT_DIST = 52.0f;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cBomLaser::cBomLaser(IBaseObject * parent)
: IBullet(parent, "LaserBom", "data\\graphic\\laser.png")
{
SetPriority(PRIORITY);
m_fDist = HIT_DIST;
m_bInvincible = true;
m_bVisible = false;
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cBomLaser::~cBomLaser(void)
{
}
//==========================================================================================
// 更新
//==========================================================================================
void cBomLaser::Update(void)
{
cTimer* timer = (cTimer*)FindChild("LifeTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this,"LifeTimer");
timer->Setup(3.0f);
}
if (timer->Finished())
{
DeleteObject();
}
IBullet::Update();
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cCamera.h */
/* @brief : カメラクラス */
/* @written : s.kosugi */
/* @create : 2019/05/22 */
/* */
/*==============================================================================*/
#include "DxLib.h"
#include "BaseObject\IBaseObject.h"
#include "Utility/Vector/cVector3.h"
//===============================================================================
// カメラクラス
class cCamera : public IBaseObject
{
public:
void Initialize(void);
void Update(void);
// カメラの回転
// 現在の位置から注視点を基準に水平回転した位置にカメラを変更する
void RotateHorizon( float angle );
//-----------------------------------------------------------------------------------------
// Getter
//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
// Setter
//-----------------------------------------------------------------------------------------
private:
//-----------------------------------------------------------------------------------------
// 変数
//-----------------------------------------------------------------------------------------
// カメラ座標
cVector3 m_vPos;
// 注視点
cVector3 m_vTargetPos;
//-----------------------------------------------------------------------------------------
// 定数
//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cCamera(void) { }; // 他からの生成を禁止
cCamera(IBaseObject* parent) { };
cCamera(IBaseObject* parent, const std::string& name) { };
~cCamera(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cCamera(const cCamera& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cCamera& operator = (const cCamera& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
// シングルトンオブジェクトにはDELETEアクセスをさせない。
IBaseObject* Finalize(void) { IBaseObject::Finalize(); return nullptr; };
static cCamera& GetInstance(void) {
static cCamera instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cText.h */
/* @brief : テキストクラス */
/* @written : s.kosugi */
/* @create : 2019/08/23 */
/* */
/*==============================================================================*/
#include <DxLib.h>
#include <iostream>
#include "..\IDrawBase.h"
//================================================================================================
// テキスト描画クラス
class cText : public IDrawBase
{
public:
cText(const std::string& text);
cText(const std::string& text,const std::string& fontname,int fontsize,int Thick,int FontType,int EdgeSize,int Italic);
~cText();
void Initialize(void);
void Update(void);
void Finalize(void);
//---------------------------------------------------------------------------------------------
// Getter
inline std::string GetText(void) { return m_sText; };
inline unsigned int GetEdgeColor(void) { return m_nEdgeColor; };
inline int GetVerticalFlag(void) { return m_nVerticalFlag; }; // 縦方向に描画するかの設定 FALSE : 横方向 TRUE : 縦方向
int GetWidth(void); // 文字列の幅を取得する。指定のフォントデータで描画する文字列の幅(ドット単位)を得る
//---------------------------------------------------------------------------------------------
// Setter
inline void SetText(std::string text) { m_sText = text; }; // 文字列の設定 デフォルトフォントでは無効
inline void SetEdgeColor(unsigned int color) { m_nEdgeColor = color; }; // 縁の色の設定 デフォルトフォントでは無効
inline void SetVerticalFlag(int flag) { m_nVerticalFlag = flag; }; // 縦方向かどうかの設定 FALSE : 横方向 TRUE : 縦方向 デフォルトフォントでは無効
protected:
//---------------------------------------------------------------------------------------------
// テキスト表示情報
std::string m_sText; // テキスト内容
unsigned int m_nEdgeColor; // 文字の縁の色
int m_nVerticalFlag;// 縦方向かどうか FALSE : 横方向 TRUE : 縦方向
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cVector3.h */
/* @brief : 2次元ベクトルクラス */
/* @written : s.kosugi */
/* @create : 2019/03/04 */
/* */
/*==============================================================================*/
#include <DxLib.h>
//================================================================================================
// ベクトルクラス
class cVector3
{
public:
float x;
float y;
float z;
cVector3(void);
cVector3(float x, float y);
cVector3(float x, float y,float z);
cVector3(const cVector3& v );
~cVector3();
//------------------------------------------------------------------------------------
// オペレーターオーバーロード
// 代入
inline cVector3& operator=(const cVector3& v)
{
x = v.x; y = v.y; z = v.z;
return *this;
};
// 加算
inline cVector3& operator+=(const cVector3& v)
{
x += v.x; y += v.y; z += v.z;
return *this;
};
// 減算
inline cVector3& operator-=(const cVector3& v)
{
x -= v.x; y -= v.y; z -= v.z;
return *this;
};
// 乗算(スカラー倍)
inline cVector3& operator*=(float scalar)
{
x *= scalar; y *= scalar; z *= scalar;
return *this;
};
// 等価
inline bool operator==(cVector3 v) const { return ( x == v.x && y == v.y && z == v.z); };
// 不等
inline bool operator!=(cVector3 v) const { return (x != v.x && y != v.y && z != v.z); };
// 加算
inline cVector3 operator+(const cVector3& v) {
cVector3 ret;
ret.x = x + v.x; ret.y = y + v.y; ret.z = z + v.z;
return ret;
};
// 減算
inline cVector3 operator-(const cVector3& v) {
cVector3 ret;
ret.x = x - v.x; ret.y = y - v.y; ret.z = z - v.z;
return ret;
};
// 乗算
inline cVector3 operator*(const cVector3& v) {
cVector3 ret;
ret.x = x * v.x; ret.y = y * v.y; ret.z = z * v.z;
return ret;
};
// 乗算(スカラー倍)
inline cVector3 operator*(float scalar) {
cVector3 ret;
ret.x = x * scalar; ret.y = y * scalar; ret.z = z * scalar;
return ret;
};
// 除算
inline cVector3 operator/(const cVector3& v) {
cVector3 ret;
ret.x = x / v.x; ret.y = y / v.y; ret.z = z / v.z;
return ret;
};
// 除算(スカラー)
inline cVector3 operator/(float scalar) {
cVector3 ret;
ret.x = x / scalar; ret.y = y / scalar; ret.z = z / scalar;
return ret;
};
// 負符号
inline cVector3 operator-( void ) {
return cVector3(-x,-y,-z);
};
// キャスト演算子
// DXLib用のベクトル構造体にキャストする
operator VECTOR() const { return VECTOR{ x,y,z }; };
//------------------------------------------------------------------------------------
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : memory.h */
/* @brief : メモリ関係マクロ */
/* @written : s.kosugi */
/* @create : 2018/09/18 */
/* */
/*==============================================================================*/
#ifndef NEW
//#ifdef DEBUG
//#define NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
//#else
#define NEW new
//#endif
#endif
#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if (p!=nullptr) { delete (p); (p) = nullptr; } }
#endif
#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY(p) { if (p!=nullptr) { delete[] (p); (p) = nullptr; } }
#endif<file_sep>/*==============================================================================*/
/* */
/* @file title : cEffectManager.cpp */
/* @brief : エフェクト管理クラス */
/* @written : s.kosugi */
/* @create : 2020/06/22 */
/* */
/*==============================================================================*/
#include "cEffectManager.h"
#include "BomEffect/cBomEffect.h"
#include "MuzzleFlashEffect/cMuzzleFlashEffect.h"
#include "LaserEffect/cLaserEffect.h"
#include "LaserStartEffect/cLaserStartEffect.h"
//==========================================================================================
// 定数
//==========================================================================================
//==========================================================================================
// コンストラクタ
//==========================================================================================
cEffectManager::cEffectManager(IBaseObject* pObj)
:IBaseObject(pObj, "EffectManager")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cEffectManager::~cEffectManager(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cEffectManager::Initialize(void)
{
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cEffectManager::Update(void)
{
IBaseObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject * cEffectManager::Finalize(void)
{
return IBaseObject::Finalize();
}
//==========================================================================================
// 生成
//==========================================================================================
IEffect* cEffectManager::Create(EFFECT_ID id,const cVector2& pos)
{
IEffect* obj = nullptr;
switch (id)
{
case EFFECT_ID::BOM: obj = CreateObject<cBomEffect>(this); break;
case EFFECT_ID::MUZZLE: obj = CreateObject<cMuzzleFlashEffect>(this); break;
case EFFECT_ID::LASER: obj = CreateObject<cLaserEffect>(this); break;
case EFFECT_ID::LASER_START: obj = CreateObject<cLaserStartEffect>(this); break;
default: break;
}
if (obj != nullptr)
{
obj->Initialize(pos);
}
return obj;
}
//==========================================================================================
// レーザーエフェクトの削除
//==========================================================================================
void cEffectManager::DeleteLaserEffect(void)
{
for (auto it = GetChildList()->begin(); it != GetChildList()->end(); it++)
{
if ((*it)->GetObjectName() == "LaserEffect" || (*it)->GetObjectName() == "LaserStartEffect")
{
(*it)->DeleteObject();
}
}
}
<file_sep>/*==============================================================================*/
/* */
/* @file title : cScoreBoard.cpp */
/* @brief : スコアボードクラス */
/* @written : s.kosugi */
/* @create : 2020/04/03 */
/* */
/*==============================================================================*/
#include "cScoreBoard.h"
#include "Utility/Number/cNumber.h"
#include "ScoreManager/cScoreManager.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cScoreBoard::PRIORITY = 500;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cScoreBoard::cScoreBoard( IBaseObject* parent )
: cSpriteObject( parent, "ScoreBoard", "data\\graphic\\ScoreFrame.png" )
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cScoreBoard::~cScoreBoard( void )
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cScoreBoard::Initialize( void )
{
SetPriority( PRIORITY );
cNumber* num = CreateDrawObject<cNumber>( this, "ScoreNumber", "data\\graphic\\Number.png" );
num->CreateNumber( 5, 0 );
num->SetPriority( PRIORITY + 10 );
cSpriteObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cScoreBoard::Update( void )
{
cNumber* num = (cNumber*)FindChild("ScoreNumber");
cScoreManager* sm = (cScoreManager*)GetRoot()->FindChild("ScoreManager");
if( num && sm )
{
num->SetValue(sm->GetScore());
cVector2 vec = m_vPos;
vec.x += 55.0f;
vec.y += 0.0f;
num->SetPos( vec );
}
cSpriteObject::Update();
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cUIManager.cpp */
/* @brief : UI管理クラス */
/* @written : s.kosugi */
/* @create : 2020/04/03 */
/* */
/*==============================================================================*/
#include "cUIManager.h"
#include "ScoreBoard/cScoreBoard.h"
#include "Button/StartButton/cStartButton.h"
#include "Button/TitleButton/cTitleButton.h"
//==========================================================================================
// 定数
//==========================================================================================
//==========================================================================================
// コンストラクタ
//==========================================================================================
cUIManager::cUIManager( IBaseObject* pObj )
:IBaseObject( pObj, "UIManager" )
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cUIManager::~cUIManager( void )
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cUIManager::Initialize( void )
{
}
//==========================================================================================
// UI生成(位置指定あり)
// return : 生成したUIのポインタ 生成されなかった場合はnullptr
//==========================================================================================
cSpriteObject* cUIManager::Create( UIID id ,const cVector2& pos)
{
cSpriteObject* pObj = Create(id);
// 生成されていたら位置を設定
if( pObj )
{
pObj->SetPos( pos );
}
return pObj;
}
//==========================================================================================
// UI生成
// return : 生成したUIのポインタ 生成されなかった場合はnullptr
//==========================================================================================
cSpriteObject * cUIManager::Create(UIID id)
{
cSpriteObject* pObj = nullptr;
switch (id)
{
case UIID::SCORE_BOARD: pObj = CreateObject<cScoreBoard>(this); break;
case UIID::START_BUTTON: pObj = CreateObject<cStartButton>(this); break;
case UIID::TITLE_BUTTON: pObj = CreateObject<cTitleButton>(this); break;
default: break;
}
if (pObj)
{
pObj->Initialize();
}
return pObj;
}
<file_sep>/*==============================================================================*/
/* */
/* @file title : cCoinEffect.cpp */
/* @brief : コインエフェクトクラス */
/* @written : s.kosugi */
/* @create : 2020/09/02 */
/* */
/*==============================================================================*/
#include "cCoinEffect.h"
#include "cGame.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cCoinEffect::PRIORITY = 400;
const float cCoinEffect::MAX_SPEED = 20.0f;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cCoinEffect::cCoinEffect(IBaseObject * parent)
: IEffect(parent, "CoinEffect", "data\\graphic\\coin.png")
, m_vVelocity()
, m_fScaleCurve( 0.0f )
{
SetPriority(PRIORITY);
}
//==========================================================================================
// 初期化
//==========================================================================================
void cCoinEffect::Initialize(const cVector2 & pos)
{
// アニメーション処理を使わないためセットしない
// アニメーション初期設定
//SetupAnime({ 128,128 }, 4, 23, 0.02f);
IEffect::Initialize(pos);
}
//==========================================================================================
// 更新
//==========================================================================================
void cCoinEffect::Update(void)
{
cGame* game = (cGame*)GetRoot();
// 重力加速度をつける
m_vVelocity.y += 0.45f;
//最大速度
if (m_vVelocity.y >= MAX_SPEED)
{
m_vVelocity.y = MAX_SPEED;
}
//
m_fScaleCurve += 5.0f;
m_vScale.x = sin(DEG_TO_RAD(m_fScaleCurve));
m_vPos += m_vVelocity;
// 画面外消去
if (game->GetWindowHeight() < m_vPos.y + GetSpriteSize().y / 2.0f)
{
DeleteObject();
}
IEffect::Update();
}<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : UIID.h */
/* @brief : UIIDリスト */
/* @written : s.kosugi */
/* @create : 2020/04/03 */
/* */
/*==============================================================================*/
enum class UIID {
OVER_TIMER = 0, // ゲームオーバーまでの時間UI
MISS_FONT, // ミスの文字
CLEAR_FONT, // クリアの文字
START_FONT, // スタートの文字
TITLE_LOGO, // タイトルロゴ
TOUCH_FONT, // タッチしてスタート文字
MAX
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cCamera.cpp */
/* @brief : カメラクラス */
/* @written : s.kosugi */
/* @create : 2019/05/22 */
/* */
/*==============================================================================*/
#include "cCamera.h"
#include "math.h"
//==========================================================================================
// 初期化
//==========================================================================================
void cCamera::Initialize(void)
{
m_vPos = { 0, 10,-20 };
m_vTargetPos = { 0, 10,0 };
//奥行0.1〜1000までをカメラの描画範囲とする
SetCameraNearFar(0.1f, 1000.0f);
}
//==========================================================================================
// 更新
//==========================================================================================
void cCamera::Update(void)
{
//第一引数の視点から第二引数のターゲットを見る角度にカメラを設置
SetCameraPositionAndTarget_UpVecY(VGet(m_vPos.x, m_vPos.y, m_vPos.z), VGet(m_vTargetPos.x, m_vTargetPos.y, m_vTargetPos.z));
}
//==========================================================================================
// カメラの回転
// 現在の位置から注視点を基準に回転した位置にカメラを変更する
//==========================================================================================
void cCamera::RotateHorizon(float angle)
{
float ox = m_vPos.x - m_vTargetPos.x;
float oy = m_vPos.z - m_vTargetPos.z;
m_vPos.x = ox * cos(angle) + oy * sin(angle);
m_vPos.z = -ox * sin(angle) + oy * cos(angle);
m_vPos.x += m_vTargetPos.x;
m_vPos.z += m_vTargetPos.z;
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cTouchFont.h */
/* @brief : タッチの文字クラス */
/* @written : s.kosugi */
/* @create : 2020/09/14 */
/* */
/*==============================================================================*/
#include "..\..\..\cSpriteObject.h"
//================================================================================================
// タッチの文字クラス
class cTouchFont : public cSpriteObject
{
public:
cTouchFont(IBaseObject* parent);
~cTouchFont(void);
void Initialize(void) override;
void Update(void) override;
private:
//--------------------------------------------------------------------------------------------
// 定数
// 表示優先度
static const int PRIORITY;
//--------------------------------------------------------------------------------------------
float m_fSinAngle; // sin計算で使う角度
};
//================================================================================================<file_sep>/*==============================================================================*/
/* */
/* @file title : cDataManager.cpp */
/* @brief : データ管理クラス */
/* @written : s.kosugi */
/* @create : 2020/01/27 */
/* */
/*==============================================================================*/
#include "cDataManager.h"
#include <DxLib.h>
//==========================================================================================
// 定数
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject * cDataManager::Finalize(void)
{
IBaseObject::Finalize();
return nullptr;
}
//==========================================================================================
// データの保存
//==========================================================================================
void cDataManager::SaveFile(std::string filename)
{
FILE* fp;
char FilePath[256];
// GetExternalDataPathでデータセーブ用のフォルダーパスを取得
GetExternalDataPath(FilePath, sizeof(FilePath));
strcat(FilePath,"/");
// セーブファイルパスを文字の後ろに付ける
strcat(FilePath,filename.c_str());
// ファイルを書き込み新規作成で開く
fp = fopen(FilePath,"wb");
if (fp != NULL)
{
// データを書き込み
fwrite(&m_SaveData, sizeof(m_SaveData), 1, fp);
fclose(fp);
}
}
//==========================================================================================
// データの読み込み
//==========================================================================================
void cDataManager::LoadFile(std::string filename)
{
FILE* fp;
char FilePath[256];
// GetExternalDataPathでデータセーブ用のフォルダーパスを取得
GetExternalDataPath(FilePath, sizeof(FilePath));
strcat(FilePath, "/");
// セーブファイルパスを文字の後ろに付ける
strcat(FilePath, filename.c_str());
// ファイルを読み込み新規作成で開く
fp = fopen(FilePath, "rb");
if (fp != NULL)
{
// データを読み込み
fread(&m_SaveData, sizeof(m_SaveData), 1, fp);
fclose(fp);
}
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cStartButton.h */
/* @brief : スタートボタンクラス */
/* @written : s.kosugi */
/* @create : 2020/07/20 */
/* */
/*==============================================================================*/
#include "..\IButton.h"
// スタートボタンクラス
class cStartButton : public IButton
{
public:
cStartButton(IBaseObject* parent);
void Initialize(void);
private:
void Neutral(void);
void Trigger(void);
void Pressed(void);
void Release(void);
// 表示優先度
static const int PRIORITY;
// 押されている状態から離れた状態になったかの確認フラグ
bool m_bPressed;
};
<file_sep>/*==============================================================================*/
/* */
/* @file title : cSprite.cpp */
/* @brief : スプライトクラス */
/* @written : s.kosugi */
/* @create : 2018/09/17 */
/* */
/*==============================================================================*/
#include "cSprite.h"
#include "..\cDrawCtrl.h"
//==========================================================================================
// コンストラクタ
//==========================================================================================
cSprite::cSprite(const std::string& filename):
IDrawBase(filename),
m_SrcRect({ 0,0,0,0 }),
m_vCenter( 0.0f,0.0f ),
m_vAnchor( 0.0f,0.0f ),
m_BlendMode(DX_BLENDMODE_ALPHA),
m_vScale( 1.0f,1.0f ),
m_fAngle(0.0f)
{
// ASSファイルでない場合にはそのまま描画情報を登録
//if (!Ends_With(filename, ".ass"))
cDrawCtrl::GetInstance().RegistDrawObject(*this,filename);
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cSprite::~cSprite()
{
cDrawCtrl::GetInstance().RemoveDrawObject(this);
}
//==========================================================================================
// 初期化
//==========================================================================================
void
cSprite::
Initialize(void)
{
IDrawBase::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cSprite::Update(void)
{
IDrawBase::Update();
}
//==========================================================================================
// 解放
//==========================================================================================
void cSprite::Finalize(void)
{
IDrawBase::Finalize();
}
//==========================================================================================
// スプライトの矩形情報をセット
//==========================================================================================
void cSprite::SetSrcRect(RECT rect)
{
m_SrcRect = rect;
// Rectが変わったのでスプライトの中心位置を自動的に変える
SetCenter(GetSpriteSize().x / 2.0f, GetSpriteSize().y / 2.0f);
}
//==========================================================================================
// スプライトの矩形情報をセット
//==========================================================================================
void cSprite::SetSrcRect(int Startx, int Starty, int Sizex, int Sizey)
{
m_SrcRect.left = Startx;
m_SrcRect.right = m_SrcRect.left + Sizex;
m_SrcRect.top = Starty;
m_SrcRect.bottom = m_SrcRect.top + Sizey;
// Rectが変わったのでスプライトの中心位置を自動的に変える
SetCenter( GetSpriteSize().x / 2.0f, GetSpriteSize().y / 2.0f );
}
//=========================================================================
// スプライトのサイズの取得
// return POINT
//=========================================================================
POINT cSprite::GetSpriteSize(void)
{
POINT pt;
pt.x = 0;
pt.y = 0;
if (IsFileLoaded())
{
pt.x = (m_SrcRect.right - m_SrcRect.left);
pt.y = (m_SrcRect.bottom - m_SrcRect.top);
}
else
{
//ErrorLogAdd("GetSpriteSize Error! m_nGraphHandle is None\n");
}
return pt;
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cOverTimer.cpp */
/* @brief : ゲームメインタイマーUIクラス */
/* @written : s.kosugi */
/* @create : 2020/08/26 */
/* */
/*==============================================================================*/
#include "cOverTimer.h"
#include "Utility/Number/cNumber.h"
#include "SceneManager/Scene/GameMain/cGameMain.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cOverTimer::PRIORITY = 500;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cOverTimer::cOverTimer(IBaseObject* parent)
: cSpriteObject(parent, "OverTimer", "data\\graphic\\timerFrame.png")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cOverTimer::~cOverTimer(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cOverTimer::Initialize(void)
{
// このクラス自身はタイマーのフレームを表示する
SetPriority(PRIORITY);
// 分の部分の生成
cNumber* num = CreateDrawObject<cNumber>(this, "MinuteNumber", "data\\graphic\\Number.png");
num->CreateNumber(2, 0);
num->SetPriority(PRIORITY + 10);
// 秒の部分の生成
num = CreateDrawObject<cNumber>(this, "SecondNumber", "data\\graphic\\Number.png");
num->CreateNumber(2, 0);
num->SetPriority(PRIORITY + 10);
cSpriteObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cOverTimer::Update(void)
{
cNumber* num = (cNumber*)FindChild("MinuteNumber");
cGameMain* gm = (cGameMain*)GetParent()->GetParent();
if (num && gm)
{
num->SetValue(gm->GetOverTimeMinute());
cVector2 vec = m_vPos;
vec.x -= 25.0f;
vec.y += 0.0f;
num->SetPos(vec);
}
num = (cNumber*)FindChild("SecondNumber");
if( num)
{
num->SetValue(gm->GetOverTimeSecond());
cVector2 vec = m_vPos;
vec.x += 50.0f;
vec.y += 0.0f;
num->SetPos(vec);
}
cSpriteObject::Update();
}<file_sep>/*==============================================================================*/
/* */
/* @file title : IBullet.cpp */
/* @brief : 弾ベースクラス */
/* @written : s.kosugi */
/* @create : 2020/06/16 */
/* */
/*==============================================================================*/
#include "IBullet.h"
#include "cGame.h"
#include "BaseObject/GameObject/Enemy/cEnemyManager.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif
//==========================================================================================
// 定数
//==========================================================================================
const int IBullet::AREAOUT_ADJUST = 100; // エリアアウト距離
//==========================================================================================
// コンストラクタ
//==========================================================================================
IBullet::IBullet(IBaseObject * parent, const std::string object_name, const std::string graphic_file_name)
: cSpriteObject(parent, object_name, graphic_file_name)
,m_vPosUp(0.0f, 0.0f)
,m_fDist(0.0f)
,m_bInvincible( false )
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
IBullet::~IBullet(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void IBullet::Initialize(void)
{
Initialize({ 0.0f,0.0f }, 0.0f, 1.0f);
}
//==========================================================================================
// 初期化
//==========================================================================================
void IBullet::Initialize(const cVector2 & pos)
{
Initialize(pos, 0.0f, 1.0f);
}
//==========================================================================================
// 初期化
//==========================================================================================
void IBullet::Initialize(const cVector2& pos, float angle, float speed)
{
// 弾の移動量
m_vPosUp.x = cos(DEG_TO_RAD(angle)) * speed;
m_vPosUp.y = sin(DEG_TO_RAD(angle)) * speed;
// 弾の回転
m_fAngle = angle;
m_vPos = pos;
cSpriteObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void IBullet::Update(void)
{
// 移動処理
m_vPos += m_vPosUp;
// エリアアウトしたら弾を削除する
AreaOutAllProc();
// 敵との当たり判定処理をする
CheckHitEnemy();
#ifdef DEBUG
// 当たり判定の描画
cDebugFunc::GetInstance().RegistDrawCircle(m_vPos,m_fDist,0x77ff0000);
#endif
cSpriteObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject* IBullet::Finalize(void)
{
cSpriteObject::Finalize();
return this;
}
//==========================================================================================
// 当たり判定処理
//==========================================================================================
void IBullet::CheckHitEnemy(void)
{
cEnemyManager* em = (cEnemyManager*)GetParent()->FindSibling("EnemyManager");
if (em)
{
// 当たったら弾を消す
if (em->CheckHit(m_vPos, m_fDist))
{
// 無敵フラグ
if (!m_bInvincible) DeleteObject();
}
}
}
//==========================================================================================
// 左エリアアウト処理
//==========================================================================================
void IBullet::AreaOutLeftProc(void)
{
if (m_vPos.x + GetSpriteSize().x / 2 < ((cGame*)GetRoot())->GetPlayArea().left - AREAOUT_ADJUST)
{
DeleteObject();
}
}
//==========================================================================================
// 上エリアアウト処理
//==========================================================================================
void IBullet::AreaOutUpProc(void)
{
if (m_vPos.y + GetSpriteSize().y / 2 < ((cGame*)GetRoot())->GetPlayArea().top - AREAOUT_ADJUST)
{
DeleteObject();
}
}
//==========================================================================================
// 右エリアアウト処理
//==========================================================================================
void IBullet::AreaOutRightProc(void)
{
if (m_vPos.x - GetSpriteSize().x / 2 > ((cGame*)GetRoot())->GetPlayArea().right + AREAOUT_ADJUST)
{
DeleteObject();
}
}
//==========================================================================================
// 下エリアアウト処理
//==========================================================================================
void IBullet::AreaOutBottomProc(void)
{
if (m_vPos.y - GetSpriteSize().y / 2 > ((cGame*)GetRoot())->GetPlayArea().bottom + AREAOUT_ADJUST)
{
DeleteObject();
}
}
//==========================================================================================
// 全方向エリアアウト処理
//==========================================================================================
void IBullet::AreaOutAllProc(void)
{
AreaOutLeftProc();
AreaOutUpProc();
AreaOutRightProc();
AreaOutBottomProc();
}<file_sep>#pragma once
enum class SCENE_ID
{
NONE = -1, // ダミー
TITLE = 0, // タイトル
GAMEMAIN, // ゲームメイン
RESULT, // イージングテスト
PAUSE, // ポーズ
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cControllerManager.cpp */
/* @brief : 入力管理クラス */
/* @written : s.kosugi */
/* @create : 2018/12/03 */
/* */
/*==============================================================================*/
#include "cControllerManager.h"
#include "Keyboard\cKeyboard.h"
#include "Mouse\cMouse.h"
#include "JoyPad\cJoyPad.h"
#include "XController/cXController.h"
//==========================================================================================
// 初期化
//==========================================================================================
void cControllerManager::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "ControllerManager";
// キーボードクラス
AddChild(&cKeyboard::GetInstance());
// マウスクラス
AddChild(&cMouse::GetInstance());
// ジョイパッドクラス
AddChild(&cJoyPad::GetInstance());
// Xコントローラークラス
AddChild(&cXController::GetInstance());
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cControllerManager::Update(void)
{
IBaseObject::Update();
}
//==========================================================================================
// キー押下チェック(1P+キーボード用)
//
// KEY_DEFINE kcode チェックするキーコード
// MOUSE_INPUT_LEFT : 左ボタン
// MOUSE_INPUT_RIGHT : 右ボタン
//
// 戻り値 true:押されていた FALSE:押されていない
//==========================================================================================
bool cControllerManager::CheckButton(KEY_DEFINE kcode)
{
// ボタンが押されているかどうか
bool ret = false;
switch (kcode)
{
case KEY_LEFT:
ret |= cKeyboard::GetInstance().CheckButton(KEY_INPUT_LEFT);
ret |= cJoyPad::GetInstance().CheckButton(PAD_INPUT_LEFT);
ret |= cXController::GetInstance().CheckButton(XINPUT_BUTTON_DPAD_LEFT);
break;
case KEY_UP:
ret |= cKeyboard::GetInstance().CheckButton(KEY_INPUT_UP);
ret |= cJoyPad::GetInstance().CheckButton(PAD_INPUT_UP);
ret |= cXController::GetInstance().CheckButton(XINPUT_BUTTON_DPAD_UP);
break;
case KEY_RIGHT:
ret |= cKeyboard::GetInstance().CheckButton(KEY_INPUT_RIGHT);
ret |= cJoyPad::GetInstance().CheckButton(PAD_INPUT_RIGHT);
ret |= cXController::GetInstance().CheckButton(XINPUT_BUTTON_DPAD_RIGHT);
break;
case KEY_DOWN:
ret |= cKeyboard::GetInstance().CheckButton(KEY_INPUT_DOWN);
ret |= cJoyPad::GetInstance().CheckButton(PAD_INPUT_DOWN);
ret |= cXController::GetInstance().CheckButton(XINPUT_BUTTON_DPAD_DOWN);
break;
case KEY_1:
ret |= cKeyboard::GetInstance().CheckButton(KEY_INPUT_Z);
ret |= cJoyPad::GetInstance().CheckButton(PAD_INPUT_1);
ret |= cXController::GetInstance().CheckButton(XINPUT_BUTTON_A);
break;
case KEY_2:
ret |= cKeyboard::GetInstance().CheckButton(KEY_INPUT_X);
ret |= cJoyPad::GetInstance().CheckButton(PAD_INPUT_2);
ret |= cXController::GetInstance().CheckButton(XINPUT_BUTTON_B);
break;
case KEY_3:
ret |= cKeyboard::GetInstance().CheckButton(KEY_INPUT_C);
ret |= cJoyPad::GetInstance().CheckButton(PAD_INPUT_3);
ret |= cXController::GetInstance().CheckButton(XINPUT_BUTTON_X);
break;
case KEY_4:
ret |= cKeyboard::GetInstance().CheckButton(KEY_INPUT_V);
ret |= cJoyPad::GetInstance().CheckButton(PAD_INPUT_4);
ret |= cXController::GetInstance().CheckButton(XINPUT_BUTTON_Y);
break;
case KEY_PAUSE:
ret |= cKeyboard::GetInstance().CheckButton(KEY_INPUT_P);
ret |= cKeyboard::GetInstance().CheckButton(KEY_INPUT_SPACE);
ret |= cJoyPad::GetInstance().CheckButton(PAD_INPUT_5);
ret |= cXController::GetInstance().CheckButton(XINPUT_BUTTON_START);
break;
case KEY_ANY:
for (int i = 0; i < KEY_MAX; i++)
{
ret |= CheckButton((KEY_DEFINE)i);
}
break;
}
return ret;
}
//==========================================================================================
// 押した瞬間をチェック(1P+キーボード用)
//
// KEY_DEFINE kcode チェックするキーコード
//
// 戻り値 true:押されていた FALSE:押されていない
//==========================================================================================
bool cControllerManager::CheckTrigger(KEY_DEFINE kcode)
{
bool ret = false;
switch (kcode)
{
case KEY_LEFT:
ret |= cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_LEFT);
ret |= cJoyPad::GetInstance().CheckTrigger(PAD_INPUT_LEFT);
ret |= cXController::GetInstance().CheckTrigger(XINPUT_BUTTON_DPAD_LEFT);
break;
case KEY_UP:
ret |= cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_UP);
ret |= cJoyPad::GetInstance().CheckTrigger(PAD_INPUT_UP);
ret |= cXController::GetInstance().CheckTrigger(XINPUT_BUTTON_DPAD_UP);
break;
case KEY_RIGHT:
ret |= cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_RIGHT);
ret |= cJoyPad::GetInstance().CheckTrigger(PAD_INPUT_RIGHT);
ret |= cXController::GetInstance().CheckTrigger(XINPUT_BUTTON_DPAD_RIGHT);
break;
case KEY_DOWN:
ret |= cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_DOWN);
ret |= cJoyPad::GetInstance().CheckTrigger(PAD_INPUT_DOWN);
ret |= cXController::GetInstance().CheckTrigger(XINPUT_BUTTON_DPAD_DOWN);
break;
case KEY_1:
ret |= cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_Z);
ret |= cJoyPad::GetInstance().CheckTrigger(PAD_INPUT_1);
ret |= cXController::GetInstance().CheckTrigger(XINPUT_BUTTON_A);
break;
case KEY_2:
ret |= cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_X);
ret |= cJoyPad::GetInstance().CheckTrigger(PAD_INPUT_2);
ret |= cXController::GetInstance().CheckTrigger(XINPUT_BUTTON_B);
break;
case KEY_3:
ret |= cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_C);
ret |= cJoyPad::GetInstance().CheckTrigger(PAD_INPUT_3);
ret |= cXController::GetInstance().CheckTrigger(XINPUT_BUTTON_X);
break;
case KEY_4:
ret |= cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_V);
ret |= cJoyPad::GetInstance().CheckTrigger(PAD_INPUT_4);
ret |= cXController::GetInstance().CheckTrigger(XINPUT_BUTTON_Y);
break;
case KEY_PAUSE:
ret |= cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_P);
ret |= cKeyboard::GetInstance().CheckTrigger(KEY_INPUT_SPACE);
ret |= cJoyPad::GetInstance().CheckTrigger(PAD_INPUT_5);
ret |= cXController::GetInstance().CheckTrigger(XINPUT_BUTTON_START);
break;
case KEY_ANY:
for (int i = 0; i < KEY_MAX; i++)
{
ret |= CheckTrigger((KEY_DEFINE)i);
}
break;
}
return ret;
}
//==========================================================================================
// 離した瞬間をチェック(1P+キーボード用)
//
// KEY_DEFINE kcode チェックするキーコード
//
// 戻り値 true:押されていた FALSE:押されていない
//==========================================================================================
bool cControllerManager::CheckRelease(KEY_DEFINE kcode)
{
bool ret = false;
switch (kcode)
{
case KEY_LEFT:
ret |= cKeyboard::GetInstance().CheckRelease(KEY_INPUT_LEFT);
ret |= cJoyPad::GetInstance().CheckRelease(PAD_INPUT_LEFT);
ret |= cXController::GetInstance().CheckRelease(XINPUT_BUTTON_DPAD_LEFT);
break;
case KEY_UP:
ret |= cKeyboard::GetInstance().CheckRelease(KEY_INPUT_UP);
ret |= cJoyPad::GetInstance().CheckRelease(PAD_INPUT_UP);
ret |= cXController::GetInstance().CheckRelease(XINPUT_BUTTON_DPAD_UP);
break;
case KEY_RIGHT:
ret |= cKeyboard::GetInstance().CheckRelease(KEY_INPUT_RIGHT);
ret |= cJoyPad::GetInstance().CheckRelease(PAD_INPUT_RIGHT);
ret |= cXController::GetInstance().CheckRelease(XINPUT_BUTTON_DPAD_RIGHT);
break;
case KEY_DOWN:
ret |= cKeyboard::GetInstance().CheckRelease(KEY_INPUT_DOWN);
ret |= cJoyPad::GetInstance().CheckRelease(PAD_INPUT_DOWN);
ret |= cXController::GetInstance().CheckRelease(XINPUT_BUTTON_DPAD_DOWN);
break;
case KEY_1:
ret |= cKeyboard::GetInstance().CheckRelease(KEY_INPUT_Z);
ret |= cJoyPad::GetInstance().CheckRelease(PAD_INPUT_1);
ret |= cXController::GetInstance().CheckRelease(XINPUT_BUTTON_A);
break;
case KEY_2:
ret |= cKeyboard::GetInstance().CheckRelease(KEY_INPUT_X);
ret |= cJoyPad::GetInstance().CheckRelease(PAD_INPUT_2);
ret |= cXController::GetInstance().CheckRelease(XINPUT_BUTTON_B);
break;
case KEY_3:
ret |= cKeyboard::GetInstance().CheckRelease(KEY_INPUT_C);
ret |= cJoyPad::GetInstance().CheckRelease(PAD_INPUT_3);
ret |= cXController::GetInstance().CheckRelease(XINPUT_BUTTON_X);
break;
case KEY_4:
ret |= cKeyboard::GetInstance().CheckRelease(KEY_INPUT_V);
ret |= cJoyPad::GetInstance().CheckRelease(PAD_INPUT_4);
ret |= cXController::GetInstance().CheckRelease(XINPUT_BUTTON_Y);
break;
case KEY_PAUSE:
ret |= cKeyboard::GetInstance().CheckRelease(KEY_INPUT_P);
ret |= cKeyboard::GetInstance().CheckRelease(KEY_INPUT_SPACE);
ret |= cJoyPad::GetInstance().CheckRelease(PAD_INPUT_5);
ret |= cXController::GetInstance().CheckRelease(XINPUT_BUTTON_START);
break;
case KEY_ANY:
for (int i = 0; i < KEY_MAX; i++)
{
ret |= CheckRelease((KEY_DEFINE)i);
}
break;
}
return ret;
}
//==========================================================================================
// 振動の開始
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// Power : 0 〜 1000
// Time : 振動時間
//==========================================================================================
void cControllerManager::StartVibration(int InputType, int Power, int Time)
{
StartJoypadVibration(InputType, Power, Time);
}
//==========================================================================================
// 振動の開始
// InputType : パッド識別子 DX_INPUT_PAD1〜4
//==========================================================================================
void cControllerManager::StopVibration(int InputType)
{
StopJoypadVibration(InputType);
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cSceneManager.cpp */
/* @brief : シーン管理クラス */
/* @written : s.kosugi */
/* @create : 2018/12/02 */
/* */
/*==============================================================================*/
#include "cSceneManager.h"
#include "Scene\Title\cTitle.h"
#include "Scene\GameMain\cGameMain.h"
#include "Scene/Pause/cPause.h"
#include "..\cGame.h"
#include "Utility/Easing/Easing.h"
#include "../BaseObject/cSpriteObject.h"
//==========================================================================================
// 定数
//==========================================================================================
const float cSceneManager::DEFAULT_FADE_TIME = 1.0f;
//==========================================================================================
// 初期化
//==========================================================================================
void cSceneManager::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "SceneManager";
//フェードアウト用
cSpriteObject* obj = CreateDrawObject<cSpriteObject>(this, "black", "data\\graphic\\black.png");
obj->SetPos((float)cGame::GetInstance().GetWindowWidth() / 2, (float)cGame::GetInstance().GetWindowHeight() / 2);
obj->SetVisible(false);
IBaseObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cSceneManager::Update(void)
{
switch (m_eState)
{
case STATE::FADEIN: FadeIn(); break;
case STATE::UPDATE: UpdateScene(); break;
case STATE::FADEOUT: FadeOut(); break;
case STATE::TRANSITION: TransitionScene(); break;
}
}
//==========================================================================================
// シーン変更
//==========================================================================================
void cSceneManager::ChangeScene(SCENE_ID id, CHANGE_TYPE type)
{
m_eNextScene = id;
m_eChangeOutType = type;
m_eChangeInType = type;
}
//==========================================================================================
// シーン変更(ユニバーサルトランジション)
//==========================================================================================
void cSceneManager::ChangeSceneUniTrans(SCENE_ID id, std::string ruleFilename)
{
m_eNextScene = id;
m_eChangeOutType = CHANGE_TYPE::UNITRANS;
m_eChangeInType = CHANGE_TYPE::UNITRANS;
m_sTransOutFileName = ruleFilename;
m_sTransInFileName = ruleFilename;
}
//==========================================================================================
// スタックしているシーンの最後尾を取得
//==========================================================================================
SCENE_ID cSceneManager::GetStackSceneID(void)
{
if (m_nStackCount < 1) return m_eCurrentScene;
if (m_listChildObject.empty()) return m_eCurrentScene;
auto end = m_listChildObject.end();
end--;
IBaseScene* scene = (IBaseScene*)(*end);
return scene->GetSceneID();
}
//==========================================================================================
// シーンのスタック
//==========================================================================================
void cSceneManager::PushScene(SCENE_ID id)
{
// 同フレーム中にすでにプッシュされている
if (m_bPush || m_ePushSceneID != SCENE_ID::NONE) return;
// 直前のシーンの更新を止める
if (!m_listChildObject.empty())
{
auto end = m_listChildObject.end();
end--;
IBaseScene* scene = (IBaseScene*)(*end);
scene->SetObjetState(OBJECT_STATE::WAIT);
}
// プッシュフラグをON
m_bPush = true;
// スタックするシーンIDを保存
m_ePushSceneID = id;
m_nStackCount++;
}
//==========================================================================================
// スタックしたシーンの削除
//==========================================================================================
void cSceneManager::PopScene(void)
{
// 子のシーンが1つの場合はポップできない
if (m_nStackCount <= 1)
return;
// 末尾のシーンのイテレータ取得
auto it = m_listChildObject.rbegin();
IBaseScene* scene = (IBaseScene*)(*it);
// 末尾のシーンを削除対象に設定
scene->DeleteObject();
// 1つ前のシーンを取得
scene = (IBaseScene*)(*(++it));
// 1つ前のシーンをアクティブ状態に変更
scene->SetObjetState(OBJECT_STATE::ACTIVE);
m_nStackCount--;
}
//==========================================================================================
// リセット
//==========================================================================================
void cSceneManager::Reset(CHANGE_TYPE changeType)
{
// 指定したフェードでシーンをリセットする(デフォルト無し)
m_eChangeOutType = changeType;
PrepareFadeOut();
}
//==========================================================================================
// シーン生成
// id : 生成するシーンID
// return : 生成したシーンのポインタ
//==========================================================================================
IBaseScene* cSceneManager::CreateScene(SCENE_ID id)
{
IBaseScene* pscene = nullptr;
switch (id)
{
case SCENE_ID::TITLE: pscene = CreateObject<cTitle>(this); break;
case SCENE_ID::GAMEMAIN: pscene = CreateObject<cGameMain>(this); break;
case SCENE_ID::PAUSE: pscene = CreateObject<cPause>(this); break;
default: break;
}
if( pscene != nullptr ) pscene->SetSceneID(id);
return pscene;
}
//==========================================================================================
// フェードアウト前準備
//==========================================================================================
void cSceneManager::PrepareFadeOut(void)
{
m_eState = STATE::FADEOUT;
cSpriteObject* obj = (cSpriteObject*)FindChild("black");
obj->SetAlpha(0);
switch (m_eChangeOutType)
{
case CHANGE_TYPE::NOFADE:
obj->SetVisible(false);
break;
case CHANGE_TYPE::FADE:
obj->SetVisible(true);
break;
case CHANGE_TYPE::UNITRANS:
if (m_pTransObj == nullptr)
{
m_pTransObj = new cTransition(m_sTransOutFileName, obj, cTransition::TransDirection::TRANS_OUT, (float)m_nFadeOutTime);
m_pTransObj->Initialize();
}
break;
}
}
//==========================================================================================
// フェードイン
//==========================================================================================
void cSceneManager::FadeIn(void)
{
cSpriteObject* obj = (cSpriteObject*)FindChild("black");
int alpha = obj->GetAlpha();
cTimer* timer = (cTimer*)FindChild("FadeInTimer");
switch (m_eChangeInType)
{
// フェードイン演出なし
case CHANGE_TYPE::NOFADE:
m_eState = STATE::UPDATE;
break;
// フェードイン
case CHANGE_TYPE::FADE:
if (timer == nullptr)
{
timer = CreateObject<cTimer>(this, "FadeInTimer");
timer->Setup(m_nFadeOutTime);
}
timer->Update();
alpha = (int)Easing::Linear(timer->GetTime(), timer->GetLimit(), 0.0f, 255.0f);
if (alpha <= 0)
{
alpha = 0;
timer->DeleteObject();
m_eState = STATE::UPDATE;
}
obj->SetAlpha(alpha);
break;
case CHANGE_TYPE::UNITRANS:
if (m_pTransObj != nullptr)
{
m_pTransObj->Update();
if (m_pTransObj->IsEnd())
{
m_eState = STATE::UPDATE;
SAFE_DELETE(m_pTransObj);
}
}
else
{
m_eState = STATE::UPDATE;
}
break;
}
}
//==========================================================================================
// シーン更新
//==========================================================================================
void cSceneManager::UpdateScene(void)
{
// プッシュ処理がある
if (m_bPush)
{
// 新しいシーンを生成してスタックする
IBaseScene* pscene = CreateScene(m_ePushSceneID);
if (pscene)
{
pscene->Initialize();
}
m_ePushSceneID = SCENE_ID::NONE;
m_bPush = false;
}
IBaseObject::Update();
// シーン変更の検知
if (m_eCurrentScene != m_eNextScene)
{
// フェードアウト準備
PrepareFadeOut();
}
}
//==========================================================================================
// フェードアウト
//==========================================================================================
void cSceneManager::FadeOut(void)
{
cSpriteObject * obj = (cSpriteObject*)FindChild("black");
int alpha = obj->GetAlpha();
cTimer* timer = (cTimer*)FindChild("FadeOutTimer");
switch (m_eChangeOutType)
{
// フェードアウト演出なし
case CHANGE_TYPE::NOFADE:
m_eState = STATE::TRANSITION;
break;
// フェードアウト
case CHANGE_TYPE::FADE:
if (timer == nullptr)
{
timer = CreateObject<cTimer>(this, "FadeOutTimer");
timer->Setup(m_nFadeOutTime);
}
timer->Update();
alpha = (int)Easing::Linear(timer->GetTime(), timer->GetLimit(), 255.0f, 0.0f);
if (alpha > 255)
{
alpha = 255;
timer->DeleteObject();
m_eState = STATE::TRANSITION;
}
obj->SetAlpha(alpha);
break;
case CHANGE_TYPE::UNITRANS:
if (m_pTransObj != nullptr)
{
m_pTransObj->Update();
if (m_pTransObj->IsEnd()) m_eState = STATE::TRANSITION;
}
else
{
m_eState = STATE::TRANSITION;
}
break;
}
}
//==========================================================================================
// シーン遷移
//==========================================================================================
void cSceneManager::TransitionScene(void)
{
IBaseObject::Finalize();
SAFE_DELETE(m_pTransObj);
// フェード用スプライトの生成
cSpriteObject* obj = CreateDrawObject<cSpriteObject>(this, "black", "data\\graphic\\black.png");
obj->SetAlpha(255);
obj->SetPriority(60000);
obj->SetPos((float)cGame::GetInstance().GetWindowWidth() / 2, (float)cGame::GetInstance().GetWindowHeight() / 2);
CreateScene(m_eNextScene);
switch (m_eChangeOutType)
{
case CHANGE_TYPE::NOFADE: obj->SetVisible(false); break;
case CHANGE_TYPE::FADE: obj->SetVisible(true); break;
case CHANGE_TYPE::UNITRANS:
m_pTransObj = new cTransition(m_sTransOutFileName, obj, cTransition::TransDirection::TRANS_IN, (float)m_nFadeInTime);
m_pTransObj->Initialize();
obj->SetVisible(false);
break;
}
m_eCurrentScene = m_eNextScene;
m_eState = STATE::FADEIN;
m_nStackCount = 1;
IBaseObject::Initialize();
IBaseObject::Update();
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cSceneManager::cSceneManager(void) :
m_eCurrentScene(SCENE_ID::NONE),
m_eNextScene(SCENE_ID::TITLE),
m_eState(STATE::TRANSITION),
m_eChangeOutType(CHANGE_TYPE::NOFADE),
m_eChangeInType(CHANGE_TYPE::NOFADE),
m_pTransObj(nullptr),
m_sTransOutFileName(""),
m_sTransInFileName(""),
m_nFadeInTime(DEFAULT_FADE_TIME),
m_nFadeOutTime(DEFAULT_FADE_TIME),
m_ePushSceneID(SCENE_ID::NONE),
m_bPush(false),
m_nStackCount(0)
{
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cSceneManager::cSceneManager(IBaseObject* parent) :
cSceneManager()
{
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cSceneManager::cSceneManager(IBaseObject* parent, const std::string& name) :
cSceneManager(parent)
{
}
//==========================================================================================
// コピーコンストラクタ
//==========================================================================================
cSceneManager::cSceneManager(const cSceneManager& t) :
cSceneManager()
{
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cCsvReader.cpp */
/* @brief : CSV読み込みクラス */
/* @written : s.kosugi */
/* @create : 2018/12/08 */
/* */
/*==============================================================================*/
#include "cCsvReader.h"
#include <DxLib.h>
#include <sstream>
//==========================================================================================
// 定数
//==========================================================================================
const int cCsvReader::LINE_CHAR_MAX = 1024; // 1行当たりの最大文字数
//==========================================================================================
// コンストラクタ
//==========================================================================================
cCsvReader::cCsvReader(IBaseObject * parent)
: IBaseObject(parent, "CsvReader")
, m_RowNum(0)
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cCsvReader::~cCsvReader()
{
}
//==========================================================================================
// ファイル読み込み
// fiepath : 読み込むファイルのパス
//==========================================================================================
void cCsvReader::LoadFile(const std::string filepath)
{
int handle = FileRead_open(filepath.c_str());
// エラー
if (handle == 0)
{
ErrorLogAdd("FileLoadError! FileHandle is None\n");
return;
}
// 読み込むのでバッファをクリア
m_Buffer.clear();
m_RowNum = 0;
// 1行ごとのデータを格納しておく
char line[LINE_CHAR_MAX];
// ファイル終端まで1行ずつ読み込む
while (FileRead_gets(line, LINE_CHAR_MAX, handle) != -1)
{
// 文字列ストリーム
std::istringstream iss(line);
std::string readStr;
bool readFlg = false;
// ,毎にgetlineで文字列を読み込み
while (std::getline(iss, readStr, ',')) {
m_Buffer.push_back(readStr);
readFlg = true;
}
// 読み込み行の中に項目があれば行数カウントする
if (readFlg) m_RowNum++;
}
FileRead_close(handle);
}
//==========================================================================================
// 指定されたデータを文字列で取得
//==========================================================================================
const std::string cCsvReader::GetString(int row, int col)
{
return m_Buffer[row * GetColNum() + col];
}
//==========================================================================================
// 指定されたデータを整数で取得
//==========================================================================================
const int cCsvReader::GetInt(int row, int col)
{
// 文字列を整数に変換
std::istringstream iss(m_Buffer[row * GetColNum() + col]);
int ret = 0;
iss >> ret;
return ret;
}
//==========================================================================================
// 指定されたデータを小数で取得
//==========================================================================================
const float cCsvReader::GetFloat(int row, int col)
{
// 文字列を整数に変換
std::istringstream iss(m_Buffer[row * GetColNum() + col]);
float ret = 0;
iss >> ret;
return ret;
}
//==========================================================================================
// 行数の取得
//==========================================================================================
const int cCsvReader::GetRowNum(void)
{
return m_RowNum;
}
//==========================================================================================
// 列数の取得
//==========================================================================================
const int cCsvReader::GetColNum(void)
{
return m_Buffer.size() / m_RowNum;
}
//==========================================================================================
// 項目数の取得
//==========================================================================================
const int cCsvReader::GetDataNum(void)
{
return m_Buffer.size();
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : IBaseObject.h */
/* @brief : オブジェクトベース */
/* @written : s.kosugi */
/* @create : 2018/11/21 */
/* */
/*==============================================================================*/
#include <list>
#include <string>
#include "..\Utility\memory.h"
// オブジェクトクラスの前方宣言
class IBaseObject;
// 検索関数登録用関数ポインタ
typedef bool(*FIND_METHOD)(IBaseObject* arg);
// オブジェクト状態ID
enum class OBJECT_STATE
{
WAIT, // 待機(更新なし、描画のみ)
ACTIVE, // 更新・描画
DEAD, // 死亡(子オブジェクトもすべて解放)
};
//================================================================================================
// オブジェクトベース
class IBaseObject
{
public:
// コンストラクタ
IBaseObject();
IBaseObject(IBaseObject* parent);
IBaseObject(IBaseObject* parent, const std::string& name);
virtual ~IBaseObject();
virtual void Initialize(void);
virtual void Update(void);
virtual IBaseObject* Finalize(void);
virtual void Reset(void);
// 親オブジェクトの取得 ルートの場合はnull
inline IBaseObject* GetParent(void) { return m_pParentObject; };
// ルートオブジェクトの取得
IBaseObject* GetRoot(void);
// 子オブジェクトリストの取得
inline std::list<IBaseObject*>* GetChildList(void) { return &m_listChildObject; };
// 子オブジェクトの追加
void AddChild(IBaseObject* obj);
// 子オブジェクトを先頭に追加する
void AddFrontChild(IBaseObject* obj);
// 子オブジェクトの削除
// 名前を指定して子オブジェクトを削除する。
// return : リストから削除した子のオブジェクト
IBaseObject* RemoveChild(const std::string& name);
// 子オブジェクトの削除
// 検索条件を関数ポインタで指定する
// return : リストから削除した子のオブジェクト
IBaseObject* RemoveChild(FIND_METHOD func);
// 子オブジェクトの検索
// 子オブジェクトの名前を指定する
// return : 検索オブジェクト 見つからなかった場合はnull
IBaseObject* FindChild(const std::string& name);
// 子オブジェクトの検索
// 検索条件を関数ポインタで指定する
// return : 検索オブジェクト 見つからなかった場合はnull
IBaseObject* FindChild(FIND_METHOD func);
// 兄弟オブジェクトの検索
// 子オブジェクトの名前を指定する
// return : 検索オブジェクト 見つからなかった場合はnull
IBaseObject* FindSibling(const std::string& name);
// 兄弟オブジェクトの検索
// 検索条件を関数ポインタで指定する
// return : 検索オブジェクト 見つからなかった場合はnull
IBaseObject* FindSibling(FIND_METHOD func);
// オブジェクト名の取得
inline std::string GetObjectName(void) const { return m_sObjectName; };
// オブジェクト状態の取得
inline OBJECT_STATE GetObjectState(void) const { return m_eObjectState; };
// オブジェクトの破棄
inline void DeleteObject(void) { m_eObjectState = OBJECT_STATE::DEAD; };
// オブジェクト状態の設定
inline void SetObjetState(OBJECT_STATE state) { m_eObjectState = state; };
protected:
IBaseObject* m_pParentObject; // 親のオブジェクト
std::list<IBaseObject*> m_listChildObject; // 子オブジェクトリスト
std::string m_sObjectName; // オブジェクト名
OBJECT_STATE m_eObjectState; // オブジェクト状態
};
//================================================================================================
// オブジェクト生成関数
//================================================================================================
// オブジェクト生成
// 親オブジェクトを指定する。
// return : 生成したオブジェクト
template <class T> T* CreateObject(IBaseObject* parent)
{
// ゲームオブジェクト生成
T* t = NEW T(parent);
// 親がいればリストに追加
if (parent) parent->AddChild(t);
// オブジェクトの返却
return t;
}
// オブジェクト生成
// 親オブジェクトとオブジェクト名指定する。
// return : 生成したオブジェクト
template <class T> T* CreateObject(IBaseObject* parent, const std::string& name)
{
// ゲームオブジェクト生成
T* t = NEW T(parent, name);
// 親がいればリストに追加
if (parent) parent->AddChild(t);
// オブジェクトの返却
return t;
}
// オブジェクト生成(前方に追加)
// 親オブジェクトを指定する。
// return : 生成したオブジェクト
template <class T> T* CreateObjectF(IBaseObject* parent)
{
// ゲームオブジェクト生成
T* t = NEW T(parent);
// 親がいればリストに追加
if (parent) parent->AddFrontChild(t);
// オブジェクトの返却
return t;
}
// オブジェクト生成(前方に追加)
// 親オブジェクトとオブジェクト名指定する。
// return : 生成したオブジェクト
template <class T> T* CreateObjectF(IBaseObject* parent, const std::string& name)
{
// ゲームオブジェクト生成
T* t = NEW T(parent, name);
// 親がいればリストに追加
if (parent) parent->AddFrontChild(t);
// オブジェクトの返却
return t;
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cNumber.cpp */
/* @brief : 数字オブジェクト */
/* @written : s.kosugi */
/* @create : 2018/12/28 */
/* */
/*==============================================================================*/
#include "cNumber.h"
#include <sstream>
//==========================================================================================
// 定数
//==========================================================================================
const int cNumber::MAX_DIGIT = 3;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cNumber::cNumber(IBaseObject* parent, std::string objectname, std::string filename) :
cSpriteObject(parent, objectname, filename),
m_nValue(0),
m_nMaxDigit( MAX_DIGIT )
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cNumber::~cNumber(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void
cNumber::
Initialize(void)
{
// このクラス自身の表示はしない
m_bVisible = false;
cSpriteObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cNumber::Update(void)
{
int i = 0;
int value = m_nValue;
for (auto it = m_listChildObject.begin(); it != m_listChildObject.end(); it++, i++)
{
cSpriteObject* pNumber = ((cSpriteObject*)*it);
int num = value % 10;
int width = pNumber->GetSpriteSize().x;
// 数値の場所の設定
pNumber->SetPos(m_vPos.x - width * i, m_vPos.y);
pNumber->SetSrcRect(num * width, 0, width, pNumber->GetSpriteSize().y);
pNumber->SetDrawColor(m_nColor);
value /= 10;
}
cSpriteObject::Update();
}
//==========================================================================================
// 解放
//==========================================================================================
IBaseObject* cNumber::Finalize(void)
{
cSpriteObject::Finalize();
return this;
}
//==========================================================================================
// 数字の生成
// filename : 表示する画像
// maxdigit : 最大桁数
// value : 表示する数値
//==========================================================================================
void cNumber::CreateNumber(short maxdigit, int value)
{
for (int i = 0; i < maxdigit; i++)
{
std::ostringstream oss;
oss << m_sObjectName << i;
cSpriteObject* obj = CreateDrawObject<cSpriteObject>(this, oss.str().c_str(), m_sFileName);
obj->Initialize();
// 画像を1数字分に設定する
obj->SetSrcRect(0, 0, obj->GetSrcRect().right / 10, obj->GetSrcRect().bottom);
obj->SetPriority(GetPriority());
}
m_nMaxDigit = maxdigit;
m_nValue = value;
}
//==========================================================================================
// 描画優先度の設定
//==========================================================================================
void cNumber::SetPriority( int priority )
{
for( auto it : m_listChildObject )
{
cSpriteObject* obj = (cSpriteObject*)it;
obj->SetPriority(priority);
}
IDrawBase::SetPriority(priority);
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cKeyboard.h */
/* @brief : キーボード入力クラス */
/* @written : s.kosugi */
/* @create : 2018/11/24 */
/* */
/*==============================================================================*/
#include "..\..\BaseObject\IBaseObject.h"
class cKeyboard : public IBaseObject
{
public:
// 初期化
void Initialize(void);
// 更新
void Update( void );
// キー押下チェック
bool CheckButton(unsigned int kcode); // 押しているか
bool CheckTrigger(unsigned int kcode); // 押した瞬間
bool CheckRelease(unsigned int kcode); // 離した瞬間
// DirectInput keyboard state
char m_diKeyState[256];
// 前フレーム情報
char m_diPrevKeyState[256];
// 定数
const int KEY_STATE_NUM = 256;
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cKeyboard(void) { }; // 他からの生成を禁止
cKeyboard(IBaseObject* parent) { };
cKeyboard(IBaseObject* parent, const std::string& name) { };
~cKeyboard(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cKeyboard(const cKeyboard& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cKeyboard& operator = (const cKeyboard& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
// シングルトンオブジェクトにはDELETEアクセスをさせない。
IBaseObject* Finalize(void) { IBaseObject::Finalize(); return nullptr; };
static cKeyboard& GetInstance(void) {
static cKeyboard instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>#include "Easing.h"
#include "..\utility.h"
#define _USE_MATH_DEFINES
#include <math.h>
namespace Easing
{
float InQuad( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime;
return max * t*t + min;
}
float OutQuad( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime;
return -max * t*( t - 2.0f ) + min;
}
float InOutQuad( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime / 2.0f;
if ( t < 1.0f)
return max / 2.0f * t * t + min;
--t;
return -max / 2.0f * ( t * ( t - 2.0f ) - 1.0f ) + min;
}
float InCubic( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime;
return max * t*t*t + min;
}
float OutCubic( float t , float totaltime , float max , float min )
{
max -= min;
t = t / totaltime - 1.0f;
return max * ( t*t*t + 1.0f ) + min;
}
float InOutCubic( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime / 2.0f;
if ( t < 1.0f )
return max / 2.0f * t*t*t + min;
t -= 2.0f;
return max / 2.0f * ( t*t*t + 2.0f ) + min;
}
float InQuart( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime;
return max * t*t*t*t + min;
}
float OutQuart( float t , float totaltime , float max , float min )
{
max -= min;
t = t / totaltime - 1.0f;
return -max * ( t*t*t*t - 1.0f ) + min;
}
float InOutQuart( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime / 2.0f;
if ( t < 1.0f )
return max / 2.0f * t*t*t*t + min;
t -= 2.0f;
return -max / 2.0f * ( t*t*t*t - 2.0f ) + min;
}
float InQuint( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime;
return max * t*t*t*t*t + min;
}
float OutQuint( float t , float totaltime , float max , float min )
{
max -= min;
t = t / totaltime - 1.0f;
return max * ( t*t*t*t*t + 1.0f ) + min;
}
float InOutQuint( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime / 2.0f;
if ( t < 1.0f )
return max / 2.0f * t*t*t*t*t + min;
t -= 2.0f;
return max / 2.0f * ( t*t*t*t*t + 2.0f ) + min;
}
float InSine( float t , float totaltime , float max , float min )
{
max -= min;
return -max * cosf( ( t*DEG_TO_RAD( 90 ) ) / totaltime ) + max + min;
}
float OutSine( float t , float totaltime , float max , float min )
{
max -= min;
return max * sinf( ( t*DEG_TO_RAD( 90 ) ) / totaltime ) + min;
}
float InOutSine( float t , float totaltime , float max , float min )
{
max -= min;
return -max / 2.0f * ( cosf( t* (float)M_PI / totaltime ) - 1.0f ) + min;
}
float InExp( float t , float totaltime , float max , float min )
{
max -= min;
return t == 0.0f ? min : max * powf( 2.0f , 10.0f * ( t / totaltime - 1.0f ) ) + min;
}
float OutExp( float t , float totaltime , float max , float min )
{
max -= min;
return t == totaltime ? max + min : max * ( -powf( 2.0f , -10.0f * t / totaltime ) + 1.0f ) + min;
}
float InOutExp( float t , float totaltime , float max , float min )
{
if ( t == 0.0f ) return min;
if ( t == totaltime ) return max;
max -= min;
t /= totaltime / 2.0f;
if ( t < 1.0f ) return max / 2.0f * powf( 2.0f , 10.0f * ( t - 1.0f ) ) + min;
--t;
return max / 2.0f * ( -powf( 2.0f , -10.0f * t ) + 2.0f ) + min;
}
float InCirc( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime;
return -max * ( sqrtf( 1.0f - t * t ) - 1.0f ) + min;
}
float OutCirc( float t , float totaltime , float max , float min )
{
max -= min;
t = t / totaltime - 1.0f;
return max * sqrtf( 1.0f - t * t ) + min;
}
float InOutCirc( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime / 2.0f;
if ( t < 1.0f ) return -max / 2.0f * ( sqrtf( 1.0f - t * t ) - 1.0f ) + min;
t -= 2.0f;
return max / 2.0f * ( sqrtf( 1.0f - t * t ) + 1.0f ) + min;
}
float InBack( float t , float totaltime , float max , float min , float s )
{
max -= min;
t /= totaltime;
return max * t*t*( ( s + 1.0f )*t - s ) + min;
}
float OutBack( float t , float totaltime , float max , float min , float s )
{
max -= min;
t = t / totaltime - 1.0f;
return max * ( t*t* ( ( s + 1.0f ) * t + s ) + 1.0f) + min;
}
float InOutBack( float t , float totaltime , float max , float min , float s )
{
max -= min;
s *= 1.525f;
t /= totaltime / 2.0f;
if ( t < 1.0f ) return max / 2.0f * ( t*t*( ( s + 1.0f )*t - s ) ) + min;
t -= 2.0f;
return max / 2.0f * ( t*t*( ( s + 1.0f )*t + s ) + 2.0f ) + min;
}
float OutBounce( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime;
if ( t < 1.0f / 2.75f )
return max * ( 7.5625f*t*t ) + min;
else if ( t < 2.0f / 2.75f )
{
t -= 1.5f / 2.75f;
return max * ( 7.5625f*t*t + 0.75f ) + min;
}
else if ( t < 2.5f / 2.75f )
{
t -= 2.25f / 2.75f;
return max * ( 7.5625f*t*t + 0.9375f ) + min;
}
else
{
t -= 2.625f / 2.75f;
return max * ( 7.5625f*t*t + 0.984375f ) + min;
}
}
float InBounce( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime;
return max * powf( 2.0f , 6.0f * ( t - 1.0f ) ) * fabsf( sinf( t * (float)M_PI * 3.5f ) ) + min;
}
float InOutBounce( float t , float totaltime , float max , float min )
{
max -= min;
t /= totaltime;
if ( t < 0.5f )
return max * 8.0f * powf( 2.0f , 8.0f * ( t - 1.0f ) ) * fabsf( sinf( t * (float)M_PI * 7.0f ) ) + min;
else
return max * ( 1.0f - 8.0f * powf( 2.0f , -8.0f * t ) * fabsf( sinf( t * (float)M_PI * 7.0f ) ) ) + min;
}
float Linear( float t , float totaltime , float max , float min )
{
return ( max - min )*t / totaltime + min;
}
}<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : IBullet.h */
/* @brief : 弾ベースクラス */
/* @written : s.kosugi */
/* @create : 2020/06/16 */
/* */
/*==============================================================================*/
#include "..\..\cSpriteObject.h"
//================================================================================================
// 弾ベースクラス
class IBullet : public cSpriteObject
{
public:
IBullet(IBaseObject* parent, const std::string object_name, const std::string graphic_file_name);
~IBullet(void);
// 初期化
void Initialize(void);
void Initialize(const cVector2& pos);
//------------------------------------------------------------------
// 初期化
// pos : 発生位置
// angle : 発射角度(DEGREE)
// speed : 弾速
void Initialize(const cVector2& pos,float angle,float speed);
void Update(void);
IBaseObject* Finalize(void);
// 無敵フラグの設定
inline void SetInvincible(bool flag) { m_bInvincible = flag; };
// 当たり判定の半径の取得
inline const float GetDist(void) { return m_fDist; };
// 無敵フラグの取得
inline const bool IsInvincivble(void) { return m_bInvincible; };
protected:
cVector2 m_vPosUp; // 移動ベクトル
float m_fDist; // 当たり判定の半径
bool m_bInvincible; // 無敵フラグ
// 当たり判定処理
void CheckHitEnemy(void);
// エリアアウト処理
void AreaOutLeftProc(void);
void AreaOutUpProc(void);
void AreaOutRightProc(void);
void AreaOutBottomProc(void);
void AreaOutAllProc(void);
static const int AREAOUT_ADJUST; // エリアアウト距離
};
//================================================================================================<file_sep>/*==============================================================================*/
/* */
/* @file title : cReadyFont.cpp */
/* @brief : Ready文字クラス */
/* @written : s.kosugi */
/* @create : 2020/07/22 */
/* */
/*==============================================================================*/
#include "cReadyFont.h"
#include "cGame.h"
#include "Utility/Timer/cTimer.h"
#include "Utility/Easing/Easing.h"
#include "cGoFont.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cReadyFont::PRIORITY = 1000;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cReadyFont::cReadyFont(IBaseObject * parent)
: cSpriteObject(parent, "ReadyFont", "data\\graphic\\ready.png")
, m_eState(STATE::APPEAR)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cReadyFont::Initialize(void)
{
cSpriteObject::Initialize();
cGame* game = (cGame*)GetRoot();
m_vPos = game->GetWindowCenter();
cTimer* timer = CreateObject<cTimer>(this,"ReadyTimer");
timer->Setup(1.5f);
SetPriority(PRIORITY);
}
//==========================================================================================
// 更新
//==========================================================================================
void cReadyFont::Update(void)
{
switch (m_eState)
{
case STATE::APPEAR: Appear(); break;
case STATE::DISAPPEAR: Disappear(); break;
default: break;
}
cSpriteObject::Update();
}
void cReadyFont::Appear(void)
{
cTimer* timer = (cTimer*)FindChild("ReadyTimer");
if (timer)
{
// タイマー終了時にGoFontをゲームメインを親として生成する
if (timer->Finished())
{
timer->Setup(0.5f);
m_eState = STATE::DISAPPEAR;
m_SrcRect.top = 0;
return;
}
// 徐々に出現させる
m_SrcRect.top = (int)Easing::OutSine(timer->GetTime(), timer->GetLimit(), 0.0f, GetGraphichSize().y);
}
}
void cReadyFont::Disappear(void)
{
cTimer* timer = (cTimer*)FindChild("ReadyTimer");
if (timer)
{
// タイマー終了時にGoFontをゲームメインを親として生成する
if (timer->Finished())
{
CreateObject<cGoFont>(GetParent())->Initialize();
DeleteObject();
return;
}
SetAlpha((int)Easing::Linear(timer->GetTime(), timer->GetLimit(), 0.0f, 255));
}
}
<file_sep>/*==============================================================================*/
/* */
/* @file title : cMissFont.cpp */
/* @brief : ミスの文字クラス */
/* @written : s.kosugi */
/* @create : 2020/08/31 */
/* */
/*==============================================================================*/
#include "cMissFont.h"
#include "cGame.h"
#include "Utility/Timer/cTimer.h"
#include "Utility/Easing/Easing.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cMissFont::PRIORITY = 1000;
const float cMissFont::FALL_TIME = 1.5f;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cMissFont::cMissFont(IBaseObject* parent)
: cSpriteObject(parent, "MissFont", "data\\graphic\\miss_font.png")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cMissFont::~cMissFont(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cMissFont::Initialize(void)
{
SetPriority(PRIORITY);
cGame* game = (cGame*)GetRoot();
// 中央上あたりに配置
SetPos(game->GetWindowCenter().x, -GetSpriteSize().y / 2.0f);
cSpriteObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cMissFont::Update(void)
{
cTimer* timer = (cTimer*)FindChild("MissFontFallTimer");
cGame* game = (cGame*)GetRoot();
if (!timer)
{
timer = CreateObject<cTimer>(this,"MissFontFallTimer");
timer->Setup(FALL_TIME);
}
if (!timer->Finished())
{
float posy = Easing::OutBounce(timer->GetTime(), timer->GetLimit(), game->GetWindowCenter().y, -GetSpriteSize().y / 2.0f);
SetPosY(posy);
}
else
{
SetPosY(game->GetWindowCenter().y);
}
cSpriteObject::Update();
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cCsvReader.cpp */
/* @brief : CSV読み込みクラス */
/* @written : s.kosugi */
/* @create : 2018/12/08 */
/* */
/*==============================================================================*/
#include "cCsvReader.h"
#include <DxLib.h>
#include <sstream>
// 定数
const int cCsvReader::LINE_CHAR_MAX = 256; // 1行当たりの最大文字数
//==========================================================================================
// 初期化
//==========================================================================================
void cCsvReader::Initialize(void)
{
m_listChildObject.clear();
m_eObjectState = OBJECT_STATE::ACTIVE;
m_sObjectName = "CsvReader";
IBaseObject::Initialize();
}
//==========================================================================================
// ファイル読み込み
// fiepath : 読み込むファイルのパス
// buf : 読み込んだファイルが文字列配列として入る
// return : 読み込んだ行数を返す
//==========================================================================================
int cCsvReader::LoadFile(const std::string filepath, std::vector<std::string>& buf)
{
int handle = FileRead_open(filepath.c_str());
// エラー
if (handle == 0)
{
ErrorLogAdd("FileLoadError! FileHandle is None\n");
return 0;
}
// 1行ごとのデータを格納しておく
char line[LINE_CHAR_MAX];
int linecount = 0;
// ファイル終端まで1行ずつ読み込む
while (FileRead_gets(line, LINE_CHAR_MAX, handle) != -1)
{
if (SplitCsv(line, buf)) {
// 読み込み行の中に項目があればカウントする
linecount++;
}
}
FileRead_close(handle);
return linecount;
}
//==========================================================================================
// 1行単位の文字列を項目毎に分割する
// str : 行単位での文字列
// buf : 読み込んだ文字を格納するバッファ
// ret : 読み込み項目数を返す
//==========================================================================================
int cCsvReader::SplitCsv(const std::string & str, std::vector<std::string>& buf)
{
// 文字列ストリーム
std::istringstream iss(str);
std::string readStr;
// 項目数カウント
int itemcount = 0;
// ,毎にgetlineで文字列を読み込み
while (std::getline(iss, readStr, ',')) {
buf.push_back(readStr);
itemcount++;
}
return itemcount;
}
<file_sep>/*==============================================================================*/
/* */
/* @file title : cTransitionObject.cpp */
/* @brief : トランジションオブジェクト */
/* @written : s.kosugi */
/* @create : 2020/02/12 */
/* */
/*==============================================================================*/
#include "cTransitionObject.h"
//==========================================================================================
// コンストラクタ
//==========================================================================================
cTransitionObject::cTransitionObject(IBaseObject* parent, const std::string& objectname, const std::string& ruleFilename, const std::string& spriteFileName, TransDirection dir, float transTime) :
IBaseObject(parent, objectname),
cTransition(ruleFilename, m_pSprite = new cSprite(spriteFileName), dir, transTime)
{
// 元画像のスプライト画像は非表示にする
m_pSprite->SetVisible(false);
}
//==========================================================================================
// コンストラクタ
//==========================================================================================
cTransitionObject::cTransitionObject(IBaseObject* parent, const std::string& objectname, const std::string& ruleFilename, IDrawBase* pTransObj, TransDirection dir, float transTime) :
IBaseObject(parent, objectname),
cTransition(ruleFilename, pTransObj, dir, transTime),
m_pSprite(nullptr)
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cTransitionObject::~cTransitionObject(void)
{
SAFE_DELETE(m_pSprite);
}
//==========================================================================================
// 初期化
//==========================================================================================
void
cTransitionObject::
Initialize(void)
{
IBaseObject::Initialize();
cTransition::Initialize();
}
//==========================================================================================
// 初期化
//==========================================================================================
void cTransitionObject::Initialize(const cVector2& pos)
{
m_vPos = pos;
Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cTransitionObject::Update(void)
{
IBaseObject::Update();
cTransition::Update();
}
//==========================================================================================
// 解放
//==========================================================================================
IBaseObject* cTransitionObject::Finalize(void)
{
IBaseObject::Finalize();
cTransition::Finalize();
return this;
}<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cControllerManager.h */
/* @brief : 入力管理クラス */
/* @written : s.kosugi */
/* @create : 2018/12/03 */
/* */
/*==============================================================================*/
#include "..\BaseObject\IBaseObject.h"
class cControllerManager : public IBaseObject
{
public:
// 初期化
void Initialize(void);
// 更新
void Update(void);
// キー定義
enum KEY_DEFINE
{
KEY_LEFT = 0,
KEY_UP,
KEY_RIGHT,
KEY_DOWN,
KEY_1,
KEY_2,
KEY_3,
KEY_4,
KEY_PAUSE,
KEY_ANY, // 全てのキー
KEY_MAX = KEY_ANY
};
// キー押下チェック(1P+キーボード用)
bool CheckButton(KEY_DEFINE kcode);
bool CheckTrigger(KEY_DEFINE kcode);
bool CheckRelease(KEY_DEFINE kcode);
// 振動開始
// InputType : パッド識別子 DX_INPUT_PAD1〜4
// Power : 0 〜 1000
// Time : 振動時間
void StartVibration(int InputType, int Power, int Time);
// 振動停止
// InputType : パッド識別子 DX_INPUT_PAD1〜4
void StopVibration(int InputType);
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cControllerManager(void) { }; // 他からの生成を禁止
cControllerManager(IBaseObject* parent) { };
cControllerManager(IBaseObject* parent, const std::string& name) { };
~cControllerManager(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cControllerManager(const cControllerManager& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cControllerManager& operator = (const cControllerManager& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
// シングルトンオブジェクトにはDELETEアクセスをさせない。
IBaseObject* Finalize(void) { IBaseObject::Finalize(); return nullptr; };
static cControllerManager& GetInstance(void) {
static cControllerManager instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cBulletManager.h */
/* @brief : 弾管理クラス */
/* @written : s.kosugi */
/* @create : 2020/06/16 */
/* */
/*==============================================================================*/
#include "..\..\IBaseObject.h"
#include "BulletID.h"
#include "Utility/Vector/cVector2.h"
// 前方宣言
class IBullet;
// 弾管理クラス
class cBulletManager : public IBaseObject
{
public:
// コンストラクタ
cBulletManager(IBaseObject* pObj);
~cBulletManager(void);
// 初期化
void Initialize(void);
// 更新
void Update(void);
// 破棄
IBaseObject* Finalize(void);
// 弾生成
// id : 弾の種類
// pos : 弾の生成位置
// angle : 弾の発射角度
// speed : 弾の移動速度
IBullet* Create(BULLET_ID id,const cVector2& pos,float angle,float speed);
private:
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cSurface.h */
/* @brief : サーフェイスクラス */
/* @written : s.kosugi */
/* @create : 2019/02/26 */
/* */
/*==============================================================================*/
#include "..\IDrawBase.h"
#include "..\..\Utility\Vector\cVector3.h"
//================================================================================================
// サーフェイスクラス
// m_cBeginPointに登録されているPriorityからcSurfaceのPriorityまでの範囲の描画オブジェクトを1オブジェクトとして操作ができる
// 主に画面効果や多人数プレイでの画面分割に使う
class cSurface : public IDrawBase
{
public:
cSurface(int width, int height, int beginPriority, int endPriority, bool alpha);
~cSurface();
// フィルターモード
enum class FILTER_MODE {
NONE,
MONO, // モノトーン
GAUSS, // ガウス
HSB, // 色相・再度・明度
INVERT, // 階調の反転
};
// Getter
inline cVector3 GetAngle(void) { return m_vAngle; };
inline cVector2 GetCenter(void) { return m_vCenter; };
inline RECT GetRect(void) { return m_Rect; };
inline int GetBlendMode(void) { return m_nBlendMode; };
inline cVector2 GetScale(void) { return m_vScale; };
inline IDrawBase* GetBeginPointer(void) { return &m_cBeginPoint; };
inline FILTER_MODE GetFilterMode(void) { return m_eFilterMode; };
inline int GetMonoBlue(void) { return m_nMonoBlue; };
inline int GetMonoRed(void) { return m_nMonoRed; };
inline int GetGaussPixelWidth(void) { return m_nGaussPixelWidth; };
inline int GetGaussParam(void) { return m_nGaussParam; };
inline int GetHSBHue(void) { return m_nHSBHue; }
inline int GetHSBSaturation(void) { return m_nHSBSaturation; }
inline int GetHSBBright(void) { return m_nHSBBright; }
inline bool IsShow(void) { return m_bShow; };
// Setter
inline void SetAngle(cVector3 angle) { m_vAngle = angle; };
inline void SetCenter(float x, float y) { m_vCenter.x = x; m_vCenter.y = y; };
inline void SetCenter(cVector2 center) { m_vCenter = center; };
inline void SetRect(RECT rect) { m_Rect = rect; };
inline void SetBlendMode(int mode) { m_nBlendMode = mode; };
inline void SetScale(cVector2 scale) { m_vScale = scale; };
inline void SetScale(float scale) { m_vScale.x = m_vScale.y = scale; };
inline void SetBeginPriority(int pri) { m_cBeginPoint.SetPriority(pri); };
inline void SetFilterMode(FILTER_MODE mode) { m_eFilterMode = mode; };
inline void SetMonoBlue(int param) { m_nMonoBlue = param; };
inline void SetMonoRed(int param) { m_nMonoRed = param; };
inline void SetGaussPixelWidth(int param) { m_nGaussPixelWidth = param; };
inline void SetGaussParam(int param) { m_nGaussParam = param; };
inline void SetHSBHue(int hue) { m_nHSBHue = hue; };
inline void SetHSBSaturation(int saturation) { m_nHSBSaturation = saturation; };
inline void SetHSBBright(int bright) { m_nHSBBright = bright; };
inline void SetShow(bool flg) { m_bShow = flg; };
protected:
cVector3 m_vAngle; // 回転
cVector2 m_vCenter; // 中心位置
RECT m_Rect; // 描画矩形の始点と終点
int m_nBlendMode; // 描画ブレンドモード
cVector2 m_vScale; // 拡大縮小
IDrawBase m_cBeginPoint; // サーフェイスの描画開始ポイントの設定(Priorityで指定)
bool m_bShow; // 生成したサーフェイスを表示するかどうか(cTransition等で作成をしておくが表示をしない場合に使用)
//----------------------------------------------------------------------------------
// フィルターモード用変数
FILTER_MODE m_eFilterMode;
// モノトーンフィルタ用青色差(-255〜255)
int m_nMonoBlue;
// モノトーンフィルタ用赤色差(-255〜255)
int m_nMonoRed;
// ガウスフィルタ用使用ピクセル幅(8,16,32の何れか)
int m_nGaussPixelWidth;
// ガウスフィルタ用ぼかしパラメータ(100で1ピクセル分の幅)
int m_nGaussParam;
// HSB用色相設定(-180〜180)
int m_nHSBHue;
// HSB用彩度設定(-255〜)
int m_nHSBSaturation;
// HSB用明度設定(-255〜255)
int m_nHSBBright;
};<file_sep>#pragma once
#define DEG_TO_RAD(angle) ( (angle) * 3.141592f / 180.0f ) // ラジアン変換
#define RAD_TO_DEG(rad) ( (rad) * 180.0f / 3.141592f ) // ラジアン→角度<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cDeadEffect.h */
/* @brief : 死亡エフェクトクラス */
/* @written : s.kosugi */
/* @create : 2020/08/26 */
/* */
/*==============================================================================*/
#include "..\IEffect.h"
//================================================================================================
// 死亡エフェクトクラス
class cDeadEffect : public IEffect
{
public:
cDeadEffect(IBaseObject* parent);
// 初期化
void Initialize(const cVector2& pos) override;
// 更新
void Update(void) override;
// 移動設定
// angle : degree値の角度 power : 移動力
void SetMove(float angle, float power);
private:
//--------------------------------------------------------------------------------------------
// 定数
// 表示優先度
static const int PRIORITY;
//--------------------------------------------------------------------------------------------
cVector2 m_vVelocity; // 移動量
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cVector2.h */
/* @brief : 2次元ベクトルクラス */
/* @written : s.kosugi */
/* @create : 2019/03/04 */
/* */
/*==============================================================================*/
#include <DxLib.h>
#include <math.h>
#include "..\utility.h"
//================================================================================================
// ベクトルクラス
class cVector2
{
public:
float x;
float y;
cVector2(void);
cVector2(float x, float y);
cVector2(const cVector2& v);
cVector2(const POINT& p);
~cVector2();
// ベクトルの大きさ取得
static inline float Length(const cVector2& vec, const cVector2& tvec) { return CalcTwoPointDist(vec, tvec); };
inline float Length(const cVector2& vec) { return CalcTwoPointDist(vec); };
// 2点間の距離
// pos , tpos 求めたい2点間
// return : 距離
static inline float CalcTwoPointDist(const cVector2& vec, const cVector2& tvec) { return (float)sqrtf((tvec.x - vec.x) * (tvec.x - vec.x) + (tvec.y - vec.y) * (tvec.y - vec.y)) ;};
// 2点間の距離
// pos : 求めたい対象の位置
// return : 距離
inline float CalcTwoPointDist(const cVector2& vec) { return (float)sqrtf((vec.x - x) * (vec.x - x) + (vec.y - y) * (vec.y - y)) ;};
// 2点間の角度
// pos , tpos 求めたい2点間
// return : Degree値
float CalcTwoPointAngle(const cVector2& vec, const cVector2& tvec);
// 2点間の角度(自身の位置との差)
// pos : 求めたい対象の位置
// return : Degree値
float CalcTwoPointAngle(const cVector2& vec);
// 内積
// pos , tpos 内積を求める2つのベクトル
inline float DotProduct(const cVector2& vec, const cVector2& tvec) { return vec.x * tvec.x + vec.y * tvec.y;};
// 内積
// pos : 自身と内積を求めるベクトル
inline float DotProduct(const cVector2 & vec) { return vec.x * x + vec.y * y; };
// 正規化
inline void Normalize( void ){ x *= 1.0f / sqrtf( x * x + y * y ); y *= 1.0f / sqrtf( x * x + y * y ); };
//------------------------------------------------------------------------------------
// オペレーターオーバーロード
// 代入
inline cVector2& operator=(const cVector2& v)
{
x = v.x; y = v.y;
return *this;
};
// 加算
inline cVector2& operator+=(const cVector2& v)
{
x += v.x; y += v.y;
return *this;
};
// 減算
inline cVector2& operator-=(const cVector2& v)
{
x -= v.x; y -= v.y;
return *this;
};
// 乗算(スカラー倍)
inline cVector2& operator*=(float scalar)
{
x *= scalar; y *= scalar;
return *this;
};
inline bool operator==(cVector2 v) const { return (x == v.x && y == v.y); }; // 等価
inline bool operator!=(cVector2 v) const { return (x != v.x && y != v.y); }; // 不等
// 加算
inline cVector2 operator+(const cVector2& v) {
cVector2 ret;
ret.x = x + v.x; ret.y = y + v.y;
return ret;
};
// 減算
inline cVector2 operator-(const cVector2& v) {
cVector2 ret;
ret.x = x - v.x; ret.y = y - v.y;
return ret;
};
// 乗算
inline cVector2 operator*(const cVector2& v) {
cVector2 ret;
ret.x = x * v.x; ret.y = y * v.y;
return ret;
};
// 乗算(スカラー倍)
inline cVector2 operator*(float scalar) {
cVector2 ret;
ret.x = x * scalar; ret.y = y * scalar;
return ret;
};
// 除算
inline cVector2 operator/(const cVector2& v) {
cVector2 ret;
ret.x = x / v.x; ret.y = y / v.y;
return ret;
};
// 除算(スカラー)
inline cVector2 operator/(float scalar) {
cVector2 ret;
ret.x = x / scalar; ret.y = y / scalar;
return ret;
};
// 負符号
inline cVector2 operator-(void) {
return cVector2(-x, -y);
};
// キャスト演算子
// DXLib用のベクトル構造体にキャストする
operator VECTOR() const { return VECTOR{ x,y,0.0f }; };
//------------------------------------------------------------------------------------
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cPlayer.cpp */
/* @brief : プレイヤークラス */
/* @written : s.kosugi */
/* @create : 2020/08/18 */
/* */
/*==============================================================================*/
#include "cPlayer.h"
#include "cGame.h"
#include "Utility/Timer/cTimer.h"
#include "BaseObject/GameObject/Effect/cEffectManager.h"
#include "BaseObject/GameObject/Effect/DeadEffect/cDeadEffect.h"
#include "SceneManager/Scene/GameMain/cGameMain.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif
//==================================================================================
// 定数
//==================================================================================
const float cPlayer::REFLECTION = 0.7f; // 反射減衰率
const float cPlayer::FRICTION = 0.96f; // 摩擦率
const float cPlayer::SLOPE_MIN_ROUNDDOWN = 0.45f; // 最小傾き値
const float cPlayer::SENSOR_RATE = 0.05f; // センサー減衰率
const float cPlayer::DIST = 20.0f; // 当たり判定の半径
const float cPlayer::DEAD_TIME = 2.0f; // 死亡状態の時間
const float cPlayer::GOAL_TIME = 2.0f; // ゴール状態の時間
const int cPlayer::DEAD_EFFECT_NUM = 12; // 死亡エフェクトの数
const float cPlayer::DEAD_EFFECT_SPEED = 5.0f; // 死亡エフェクトの移動スピード
const int cPlayer::PRIORITY = 400; // 表示優先度
//==================================================================================
// コンストラクタ
//==================================================================================
cPlayer::cPlayer(IBaseObject * parent):
cSpriteObject(parent,"Player","data\\graphic\\val_01.png")
, m_vVelocity(0.0f,0.0f)
, m_eState( STATE::START)
{
}
//==================================================================================
// デストラクタ
//==================================================================================
cPlayer::~cPlayer(void)
{
}
//==================================================================================
// 初期化
//==================================================================================
void cPlayer::Initialize(void)
{
SetPriority(PRIORITY);
m_vVelocity = {0.0f,0.0f};
}
//==================================================================================
// 更新
//==================================================================================
void cPlayer::Update(void)
{
switch (m_eState)
{
case STATE::START: Start(); break;
case STATE::NORMAL: Normal(); break;
case STATE::DEAD: Dead(); break;
case STATE::GOAL: Goal(); break;
default: break;
}
#ifdef DEBUG
// 当たり判定の表示
cDebugFunc::GetInstance().RegistDrawCircle(m_vPos, DIST, 0x77ff0000);
#endif
cSpriteObject::Update();
}
//==================================================================================
// 破棄
//==================================================================================
IBaseObject * cPlayer::Finalize(void)
{
cSpriteObject::Finalize();
return this;
}
//==================================================================================
// プレイヤー状態の変更
//==================================================================================
void cPlayer::ChangeState(STATE state)
{
m_eState = state;
}
//==================================================================================
// 開始状態
//==================================================================================
void cPlayer::Start()
{
}
//==================================================================================
// 通常状態
//==================================================================================
void cPlayer::Normal()
{
// 加速度センサーの値を取得
VECTOR v = GetAndroidSensorVector(DX_ANDROID_SENSOR_ACCELEROMETER);
// 移動量として使える値に計算する
cVector2 velocity = CalcSensorVector(v);
// 横画面なのでx,yを反転して入れる
m_vVelocity.x += velocity.y;
m_vVelocity.y += velocity.x;
// 摩擦
m_vVelocity *= FRICTION;
// 移動値を入れ込む
m_vPos += m_vVelocity;
// 時間切れ判定
CheckTimeOver();
// 壁判定
CheckHitWall();
// キャラクターのアニメーション処理
Animation();
}
//==================================================================================
// 死亡状態
//==================================================================================
void cPlayer::Dead()
{
cTimer* timer = (cTimer*)FindChild("DeadTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this,"DeadTimer");
timer->Setup(DEAD_TIME);
// タイマーを生成した瞬間に振動をさせる
Vibrator_vibrate(DEAD_TIME * 1000,128);
// 死亡状態ではキャラクターを非表示にする
m_bVisible = false;
// エフェクト生成
cEffectManager* em = (cEffectManager*)GetRoot()->FindChild("EffectManager");
if (em)
{
for (int i = 0; i < DEAD_EFFECT_NUM; i++)
{
cDeadEffect* ef = (cDeadEffect*)em->Create(EFFECT_ID::DEAD, m_vPos);
ef->SetMove(360 / DEAD_EFFECT_NUM * i, DEAD_EFFECT_SPEED);
}
}
}
}
//==================================================================================
// ゴール状態
//==================================================================================
void cPlayer::Goal()
{
}
//==================================================================================
// AndroidSensorVectorの戻り値をcPlayerが使える値にする
//==================================================================================
cVector2 cPlayer::CalcSensorVector(VECTOR dxvector)
{
cVector2 ret;
// 小さい値を切りすて、傾きが微小な時は動かないようにする
if (fabs(dxvector.x) <= SLOPE_MIN_ROUNDDOWN)
{
dxvector.x = 0.0f;
}
if (fabs(dxvector.y) <= SLOPE_MIN_ROUNDDOWN)
{
dxvector.y = 0.0f;
}
// 力が強すぎるので1/10にする
dxvector.x *= SENSOR_RATE;
dxvector.y *= SENSOR_RATE;
ret.x = dxvector.x;
ret.y = dxvector.y;
return ret;
}
//==================================================================================
// 壁判定
//==================================================================================
void cPlayer::CheckHitWall(void)
{
cGame* gm = (cGame*)GetRoot();
if (m_vPos.x - GetSpriteSize().x / 2.0f < 0.0f)
{
// 壁の内側へ戻す
m_vPos.x = GetSpriteSize().x / 2.0f;
// 反射する毎に加速を減衰させる
m_vVelocity.x = -m_vVelocity.x * REFLECTION;
}
if (m_vPos.x + GetSpriteSize().x / 2.0f > gm->GetWindowWidth())
{
// 壁の内側へ戻す
m_vPos.x = gm->GetWindowWidth() - GetSpriteSize().x / 2.0f;
// 反射する毎に加速を減衰させる
m_vVelocity.x = -m_vVelocity.x * REFLECTION;
}
if (m_vPos.y - GetSpriteSize().y / 2.0f < 0.0f)
{
// 壁の内側へ戻す
m_vPos.y = GetSpriteSize().y / 2.0f;
// 反射する毎に加速を減衰させる
m_vVelocity.y = -m_vVelocity.y * REFLECTION;
}
if (m_vPos.y + GetSpriteSize().y / 2.0f > gm->GetWindowHeight())
{
// 壁の内側へ戻す
m_vPos.y = gm->GetWindowHeight() - GetSpriteSize().y / 2.0f;
// 反射する毎に加速を減衰させる
m_vVelocity.y = -m_vVelocity.y * REFLECTION;
}
}
//==================================================================================
// 時間切れチェック
//==================================================================================
void cPlayer::CheckTimeOver(void)
{
cGameMain* gm = (cGameMain*)GetParent();
if (gm->GetObjectName() == "GameMain")
{
// 時間切れだったら死亡にする
if (gm->GetOverTimeSecond() <= 0 && gm->GetOverTimeMinute() <= 0)
{
m_eState = STATE::DEAD;
}
}
}
//==================================================================================
// アニメーション処理
//==================================================================================
void cPlayer::Animation(void)
{
if (m_vVelocity.x < 0)
{
m_vScale.x = -1.0f;
}
else if (m_vVelocity.x > 0)
{
m_vScale.x = 1.0f;
}
}
<file_sep>#pragma once
// マップチップID
enum class STAGE_ID
{
EMPTY = 0,
NEEDLE,
START,
GOAL,
};<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : IDrawBase.h */
/* @brief : 描画ベースクラス */
/* @written : s.kosugi */
/* @create : 2018/12/14 */
/* */
/*==============================================================================*/
#include <DxLib.h>
#include <iostream>
#include "..\Utility\Vector\cVector2.h"
//===============================================================================
// 描画種別
enum class DRAWTYPE
{
SPRITE = 0,
//EFFECT,
SURFACE,
BEGINSURFACE,
TRANSITION,
//MODEL,
TEXT,
};
//================================================================================================
// 描画ベースクラス
class IDrawBase
{
friend class cDrawCtrl; // 描画操作クラスのみによってハンドルの操作を行う
public:
IDrawBase();
IDrawBase(const std::string& filename);
virtual ~IDrawBase();
void Initialize(void);
void Update(void);
void Finalize(void);
inline bool IsFileLoaded(void) { if(m_nGraphHandle != LOADGRAPH_NONE) return true; return false;};
//---------------------------------------------------------------------------------------------
// Getter
inline cVector2 GetPos(void) { return m_vPos; };
inline int GetPriority(void) { return m_nPri; };
inline bool GetVisible(void) { return m_bVisible; };
inline unsigned int GetDrawColor(void) { return m_nColor; };
inline unsigned int GetAlpha(void) { return m_nColor >> 24; };
inline unsigned int GetColorRed(void) { return (m_nColor & 0x00ff0000) >> 16; };
inline unsigned int GetColorGreen(void) { return (m_nColor & 0x0000ff00) >> 8; };
inline unsigned int GetColorBlue(void) { return (m_nColor & 0x000000ff); };
inline POINT GetGraphichSize(void) {POINT pt; int x, y;GetGraphSize(m_nGraphHandle, &x, &y); pt.x = x; pt.y = y; return pt;};
//---------------------------------------------------------------------------------------------
// Setter
inline void SetPos(cVector2 vPos) { m_vPos = vPos; };
inline void SetPos(float x, float y) { m_vPos.x = x; m_vPos.y = y; };
inline void SetPosX(float x) { m_vPos.x = x; };
inline void SetPosY(float y) { m_vPos.y = y; };
void SetPriority(int pri);
inline void SetVisible(bool visible) { m_bVisible = visible; };
inline void SetDrawColor(unsigned int color) { m_nColor = color; };
inline void SetAlpha(unsigned int alpha) { m_nColor = (m_nColor & 0x00ffffff) | (alpha << 24); };
inline void SetColorRed(unsigned int red) { m_nColor = (m_nColor & 0xff00ffff) | (red << 16); };
inline void SetColorGreen(unsigned int green) { m_nColor = (m_nColor & 0xffff00ff) | (green << 8); };
inline void SetColorBlue(unsigned int blue) { m_nColor = (m_nColor & 0xffffff00) | (blue); };
//---------------------------------------------------------------------------------------------
// 定数
// 色の定義
static const unsigned int COLOR_DEFAULT = 0xffffffff;
static const unsigned int COLOR_RED = 0xffff0000;
static const unsigned int COLOR_GREEN = 0xff00ff00;
static const unsigned int COLOR_BLUE = 0xff0000ff;
static const unsigned int COLOR_PURPLE = 0xffff00ff;
static const unsigned int COLOR_YELLOW = 0xffffff00;
static const unsigned int COLOR_BLACK = 0xff262626;
static const unsigned int COLOR_FULL_BLACK = 0xff000000;
// 透明度の定義
static const unsigned int ALPHA_MAX = 0xff;
protected:
//---------------------------------------------------------------------------------------------
// スプライト表示情報
cVector2 m_vPos; // 表示位置
std::string m_sFileName; // ファイル名
unsigned int m_nColor; // 色 0xARGB
bool m_bVisible; // 表示有無
bool m_bUnload; // アンロードフラグ true : オブジェクト削除時にメモリからアンロードする
private:
int m_nPri; // 描画優先度
int m_nGraphHandle; // 読み込み済みの描画のハンドル。未ロードの場合は-1 cDrawCtrlで設定する
DRAWTYPE m_eDrawType; // 描画種別
//---------------------------------------------------------------------------------------------
// 定数
static const int LOADGRAPH_NONE = -1; // 描画ファイルのロード失敗または未ロード
};
//================================================================================================<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : IButton.h */
/* @brief : タッチボタン基底クラス */
/* @written : s.kosugi */
/* @create : 2020/07/17 */
/* */
/*==============================================================================*/
#include "..\..\..\cSpriteObject.h"
// ボタンクラス
class IButton : public cSpriteObject
{
public:
IButton(IBaseObject* parent, std::string objectname, std::string filename);
~IButton(void);
virtual void Initialize(void);
virtual void Initialize(const cVector2& pos);
virtual void Update(void);
virtual IBaseObject* Finalize(void);
protected:
enum class BUTTON_STATE
{
NEUTRAL, // 押されていない
TRIGGER, // 押した瞬間
PRESSED, // 押されている間
RELEASE, // 離した瞬間
};
virtual void Neutral(void) = 0;
virtual void Trigger(void) = 0;
virtual void Pressed(void) = 0;
virtual void Release(void) = 0;
BUTTON_STATE m_eButtonState; // 現在のボタン状態
private:
static const int PRIORITY = 100;
};
<file_sep>/*==============================================================================*/
/* */
/* @file title : cPlayer.cpp */
/* @brief : プレイヤークラス */
/* @written : s.kosugi */
/* @create : 2018/12/03 */
/* */
/*==============================================================================*/
#include "cPlayer.h"
#include "..\..\..\Input\cControllerManager.h"
#include "..\..\..\cGame.h"
#include "..\..\..\SoundCtrl\cSoundCtrl.h"
#ifdef DEBUG
#include "..\..\..\DebugFunc\cDebugFunc.h"
#include <sstream>
#endif // DEBUG
//==========================================================================================
// 定数
//==========================================================================================
const float cPlayer::MOVE_SPEED = 3.0f;
const float cPlayer::START_POS_X = 300.0f;
const float cPlayer::START_POS_Y = 300.0f;
const int cPlayer::PRIORITY = 200;
const short cPlayer::SIZE_X = 64;
const short cPlayer::SIZE_Y = 64;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cPlayer::cPlayer(IBaseObject * parent)
: cSpriteObject(parent, "Player", "data\\graphic\\player_01.png")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cPlayer::~cPlayer(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cPlayer::Initialize(void)
{
m_vPos = { START_POS_X,START_POS_Y };
SetPriority(PRIORITY);
SetSrcRect(0, 0, SIZE_X, SIZE_Y);
cSpriteObject::Initialize();
}
//==========================================================================================
// 更新
//==========================================================================================
void cPlayer::Update(void)
{
if (cControllerManager::GetInstance().CheckButton(cControllerManager::KEY_RIGHT))
{
m_vPos.x += MOVE_SPEED;
}
if (cControllerManager::GetInstance().CheckButton(cControllerManager::KEY_LEFT))
{
m_vPos.x -= MOVE_SPEED;
}
if (cControllerManager::GetInstance().CheckButton(cControllerManager::KEY_UP))
{
m_vPos.y -= MOVE_SPEED;
}
if (cControllerManager::GetInstance().CheckButton(cControllerManager::KEY_DOWN))
{
m_vPos.y += MOVE_SPEED;
}
// 範囲外処理
ProcAreaOut();
cSpriteObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject* cPlayer::Finalize(void)
{
cSpriteObject::Finalize();
return this;
}
//==========================================================================================
// 範囲外処理
//==========================================================================================
void cPlayer::ProcAreaOut(void)
{
if (m_vPos.x - SIZE_X / 2 < 0.0f)
{
m_vPos.x = (float)SIZE_X / 2;
}
if (m_vPos.y - SIZE_Y / 2 < 0.0f)
{
m_vPos.y = (float)SIZE_Y / 2;
}
if (m_vPos.x + SIZE_X / 2 >= cGame::GetInstance().GetWindowWidth())
{
m_vPos.x = (float)cGame::GetInstance().GetWindowWidth() - SIZE_X /2;
}
if (m_vPos.y + SIZE_Y / 2 >= cGame::GetInstance().GetWindowHeight())
{
m_vPos.y = (float)cGame::GetInstance().GetWindowHeight() - SIZE_Y / 2;
}
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cTitleButton.h */
/* @brief : タイトルボタンクラス */
/* @written : s.kosugi */
/* @create : 2020/07/20 */
/* */
/*==============================================================================*/
#include "..\IButton.h"
// タイトルボタンクラス
class cTitleButton : public IButton
{
public:
cTitleButton(IBaseObject* parent);
void Initialize(void);
private:
void Neutral(void);
void Trigger(void);
void Pressed(void);
void Release(void);
// 表示優先度
static const int PRIORITY;
// 押されている状態から離れた状態になったかの確認フラグ
bool m_bPressed;
};
<file_sep>#include "DxLib.h"
#include "cGame.h"
#include "DrawCtrl\cDrawCtrl.h"
void MainLoop(void);
// プログラムは android_main から始まります
int android_main(void)
{
// ウィンドウタイトル
//SetWindowText("FMGameBase");
// 画面サイズとカラービット数の指定
SetGraphMode(cGame::GetInstance().GetWindowWidth(), cGame::GetInstance().GetWindowHeight(), 32);
// DXライブラリ初期化処理
if (DxLib_Init() == -1)
return -1; // エラーが起きたら直ちに終了
//描画先を裏画面に設定(ダブルバッファ)
if (SetDrawScreen(DX_SCREEN_BACK) == -1)
return -1;
// ウィンドウが非アクティブ状態でも動作させる
SetAlwaysRunFlag(TRUE);
// 描画リストの生成、初期化
cDrawCtrl::GetInstance().ClearDrawList();
// ゲームクラスの作成
cGame& game = cGame::GetInstance();
// 初期化
game.Initialize();
#ifdef DEBUG
//cDebugFunc::GetInstance().PushDebugLog("ShaderVersion = " + std::to_string(GetValidShaderVersion()));
//cDebugFunc::GetInstance().PushDebugLog("MultiDrawScreenNum = " + std::to_string(GetMultiDrawScreenNum()));
#endif
// メインループ
MainLoop();
// 破棄
game.Finalize();
DxLib_End(); // DXライブラリ使用の終了処理
return 0; // ソフトの終了
}
//==========================================================================================
// メインループ
//==========================================================================================
void MainLoop(void)
{
cGame& game = cGame::GetInstance();
for (;;) {
int StartTime;
// 計測開始時刻を保存
StartTime = GetNowCount();
// 画面のクリア
ClearDrawScreen();
// ゲームの更新
game.Update();
// 描画
game.Draw();
// 画面を更新(垂直同期+裏画面の内容を表画面にコピー)
ScreenFlip();
// メッセージ処理
if (ProcessMessage() != 0)
return;
// 1/60秒を越えるまで待機させる
while (GetNowCount() < StartTime + 1000 / (int)game.GetFPS());
}
}<file_sep>/*==============================================================================*/
/* */
/* @file title : cStageManager.cpp */
/* @brief : ステージ管理クラス */
/* @written : s.kosugi */
/* @create : 2020/08/19 */
/* */
/*==============================================================================*/
#include "cStageManager.h"
#include "Utility/CsvReader/cCsvReader.h"
#include "IStage.h"
#include "Needle/cNeedle.h"
#include "StageStart/cStageStart.h"
#include "StageGoal/cStageGoal.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif
//==========================================================================================
// 定数
//==========================================================================================
const int cStageManager::STAGE_PIXEL_SIZE = 64;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cStageManager::cStageManager(IBaseObject* pObj)
:IBaseObject(pObj, "StageManager")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cStageManager::~cStageManager(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cStageManager::Initialize(void)
{
IBaseObject::Initialize();
// ステージ生成
cCsvReader* csv = CreateObject<cCsvReader>(this);
csv->LoadFile("data\\csv\\maingame_1.csv");
for (int i = 0; i < csv->GetRowNum(); i++)
{
for (int j = 0; j < csv->GetColNum(); j++)
{
Create((STAGE_ID)csv->GetInt(i, j),
{ j * STAGE_PIXEL_SIZE + STAGE_PIXEL_SIZE / 2.0f,
i * STAGE_PIXEL_SIZE + STAGE_PIXEL_SIZE / 2.0f });
}
}
}
//==========================================================================================
// 更新
//==========================================================================================
void cStageManager::Update(void)
{
IBaseObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject * cStageManager::Finalize(void)
{
IBaseObject::Finalize();
return this;
}
//==========================================================================================
// ステージオブジェクト生成
// return : 生成した敵のポインタ 生成されなかった場合はnullptr
//==========================================================================================
IStage* cStageManager::Create(STAGE_ID id, const cVector2& pos)
{
IStage* pObj = nullptr;
switch (id)
{
case STAGE_ID::EMPTY: break;
case STAGE_ID::NEEDLE: pObj = CreateObject<cNeedle>(this); break;
case STAGE_ID::START: pObj = CreateObject<cStageStart>(this); break;
case STAGE_ID::GOAL: pObj = CreateObject<cStageGoal>(this); break;
default: break;
}
if (pObj)
{
pObj->Initialize(pos);
}
return pObj;
}<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : IBaseScene.h */
/* @brief : シーン基底クラス */
/* @written : s.kosugi */
/* @create : 2019/04/20 */
/* */
/*==============================================================================*/
#include "..\SceneID.h"
#include "BaseObject/IBaseObject.h"
//================================================================================================
// シーン基底クラス
class IBaseScene : public IBaseObject
{
public:
// コンストラクタ
IBaseScene(IBaseObject* parent, const std::string& name);
// デストラクタ
virtual ~IBaseScene(void);
// シーン変更 スタックされているシーンは全て破棄
void Change(SCENE_ID id);
// シーンのスタック
void Push(SCENE_ID id);
// スタックされたシーンの削除
void Pop(void);
// シーンIDの設定
inline void SetSceneID(SCENE_ID id) { m_eSceneID = id; };
// シーンIDの取得
inline SCENE_ID GetSceneID(void) { return m_eSceneID; };
private:
SCENE_ID m_eSceneID; // シーンID
};
<file_sep>/*==============================================================================*/
/* */
/* @file title : cUIManager.cpp */
/* @brief : UI管理クラス */
/* @written : s.kosugi */
/* @create : 2020/04/03 */
/* */
/*==============================================================================*/
#include "cUIManager.h"
#include "OverTimer/cOverTimer.h"
#include "MissFont/cMissFont.h"
#include "StartFont/cStartFont.h"
#include "ClearFont/cClearFont.h"
#include "TitleLogo/cTitleLogo.h"
#include "TouchFont/cTouchFont.h"
//==========================================================================================
// 定数
//==========================================================================================
//==========================================================================================
// コンストラクタ
//==========================================================================================
cUIManager::cUIManager(IBaseObject* pObj)
:IBaseObject(pObj, "UIManager")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cUIManager::~cUIManager(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cUIManager::Initialize(void)
{
}
//==========================================================================================
// UI生成(位置指定あり)
// return : 生成したUIのポインタ 生成されなかった場合はnullptr
//==========================================================================================
cSpriteObject* cUIManager::Create(UIID id, const cVector2& pos)
{
cSpriteObject* pObj = Create(id);
// 生成されていたら位置を設定
if (pObj)
{
pObj->SetPos(pos);
}
return pObj;
}
//==========================================================================================
// UI生成
// return : 生成したUIのポインタ 生成されなかった場合はnullptr
//==========================================================================================
cSpriteObject * cUIManager::Create(UIID id)
{
cSpriteObject* pObj = nullptr;
switch (id)
{
case UIID::OVER_TIMER: pObj = CreateObject<cOverTimer>(this); break;
case UIID::MISS_FONT: pObj = CreateObject<cMissFont>(this); break;
case UIID::START_FONT: pObj = CreateObject<cStartFont>(this); break;
case UIID::CLEAR_FONT: pObj = CreateObject<cClearFont>(this); break;
case UIID::TITLE_LOGO: pObj = CreateObject<cTitleLogo>(this); break;
case UIID::TOUCH_FONT: pObj = CreateObject<cTouchFont>(this); break;
default: break;
}
if (pObj)
{
pObj->Initialize();
}
return pObj;
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cDebugFunc.h */
/* @brief : デバッグ機能クラス */
/* @written : s.kosugi */
/* @create : 2019/03/24 */
/* */
/*==============================================================================*/
#ifdef DEBUG
#include "..\BaseObject\IBaseObject.h"
#include "Utility/Vector/cVector2.h"
//===============================================================================
// デバッグ機能クラス
class cDebugFunc : public IBaseObject
{
public:
void Initialize(void) override;
void Update(void) override;
void Draw(void);
// デバッグログ追加
void PushDebugLog(std::string str);
// デバッグログ追加 str : 出力したい文字列 num : 出力したい数値
void PushDebugLog(std::string str,float num);
// デバッグログ追加 str : 出力したい文字列 num : 出力したい数値
void PushDebugLog(std::string str, int num);
// デバッグログ最大出力数設定
inline void SetDebugLogMax(int num) { m_nMaxLog = num; };
// 円描画登録(1フレーム間描画)
// pos : 指定ポイント
// range : 指定ポイントからの範囲(半径)
// color : 描画色(ARGB)
void RegistDrawCircle(const cVector2& pos, float range,unsigned int color);
// 矩形描画登録(1フレーム間描画)
// pos : 指定ポイント
// range : 指定ポイントからの範囲
// color : 描画色(ARGB)
void RegistDrawBox(const cVector2& pos, POINT range,unsigned int color);
private:
enum DebugPrintMode
{
DPRINT_ALL, // 説明表示あり
DPRINT_NODESCRIPTION, // 説明表示なし
DPRINT_NO, // デバッグ表示オフ
DPRINT_MAX
};
// デバッグ用円描画構造体
struct DebugCircle {
cVector2 pos;
float range;
unsigned int color;
};
// デバッグ用矩形描画構造体
struct DebugBox {
cVector2 pos;
POINT range;
unsigned int color;
};
// デバッグ用更新速度変更
void DebugChangeUpdateSpeed(void);
// デバッグシーンリセット
void DebugSceneReset(void);
// デバッグ出力
void DebugPrint(void);
// デバッグ図形描画
void DrawShape(void);
// フレームレート計算
void CalcFrameRate(void);
// スクリーンショット撮影
void SaveScreenShot(void);
//---------------------------------------------------------
// フレームレート計算用
int m_nStartTime;
int m_nFrameCount;
float m_fFrameLate;
//---------------------------------------------------------
std::list<std::string> m_listLog; // デバッグログ
int m_nMaxLog; // デバッグログ最大表示行数
int m_nLogNum; // ログNo
DebugPrintMode m_eDebugPrintMode; // デバッグ表示の切り替え 0:ログ、ヘルプ表示 1:ログのみ表示 2:非表示
int m_nFPSMode; // 0:初期値 1:少し早い 2:速い -1:少し遅い -2:遅い
int m_nDebugFontHandle; // フォントのハンドル
std::list<DebugCircle> m_listDrawCircle;// デバッグ円描画リスト
std::list<DebugBox> m_listDrawBox; // デバッグ矩形描画リスト
static const int FPS_MODE_MAX; // 更新フレームモード最大
static const int FONT_SIZE; // フォントサイズ
static const int LOG_MAX; // ログ表示最大数
//-----------------------------------------------------------------------------------------------------
// シングルトン用
private:
cDebugFunc(void) { }; // 他からの生成を禁止
cDebugFunc(IBaseObject* parent) { };
cDebugFunc(IBaseObject* parent, const std::string& name) { };
~cDebugFunc(void) {}; // 他からの削除を禁止(デストラクタをprivateにする事で外部削除不可)
cDebugFunc(const cDebugFunc& t) {}; // オブジェクトの複製禁止(コピーコンストラクタのオーバライド)
cDebugFunc& operator = (const cDebugFunc& t) { return *this; }; // オブジェクトの複製禁止(代入演算子のオーバーロード)
public:
// シングルトンオブジェクトにはDELETEアクセスをさせない。
IBaseObject* Finalize(void) override { IBaseObject::Finalize(); return nullptr; };
static cDebugFunc& GetInstance(void) {
static cDebugFunc instance; // 唯一の実体であるオブジェクト、static変数を使用する事で1つの共有の変数となる
return instance; // 常に共通のインスタンスを返す
};
//-----------------------------------------------------------------------------------------------------
};
#endif // DEBUG<file_sep>/*==============================================================================*/
/* */
/* @file title : cGameMain.cpp */
/* @brief : ゲームメインシーン */
/* @written : s.kosugi */
/* @create : 2018/12/02 */
/* */
/*==============================================================================*/
#include "cGame.h"
#include "cGameMain.h"
#include "..\..\cSceneManager.h"
#include "..\..\..\BaseObject\cSpriteObject.h"
#include "BaseObject/GameObject/Player/cPlayer.h"
#include "BaseObject/GameObject/Stage/cStageManager.h"
#include "Utility/Timer/cTimer.h"
#include "BaseObject/GameObject/UI/cUIManager.h"
#include "BaseObject/GameObject/Effect/cEffectManager.h"
#ifdef DEBUG
#include "DebugFunc/cDebugFunc.h"
#endif
//==========================================================================================
// 定数
//==========================================================================================
const float cGameMain::TIME_OVER_LIMIT = 90.0f;
const float cGameMain::GOAL_TIME = 2.0f;
const float cGameMain::DEAD_TIME = 2.0f;
const float cGameMain::START_TIME = 2.0f;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cGameMain::cGameMain(IBaseObject * parent)
: IBaseScene(parent, "GameMain")
, m_eState( STATE::START )
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cGameMain::~cGameMain(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cGameMain::Initialize(void)
{
// 背景スプライトの生成
cSpriteObject* obj = CreateDrawObject<cSpriteObject>(this, "GameMainBack", "data\\graphic\\GameMainBack.png");
obj->SetPriority(-100);
obj->SetPos((float)cGame::GetInstance().GetWindowWidth()/2, (float)cGame::GetInstance().GetWindowHeight() / 2);
CreateObject<cPlayer>(this);
CreateObject<cStageManager>(this);
// ゲームタイマーの設定
cTimer* timer = CreateObject<cTimer>(this, "GameOverTimer");
timer->Setup(TIME_OVER_LIMIT);
// UI管理の生成
cUIManager* um = CreateObject<cUIManager>(this);
IBaseObject::Initialize();
cGame* game = (cGame*)GetRoot();
um->Create(UIID::OVER_TIMER, { game->GetWindowCenter().x,28 });
}
//==========================================================================================
// 更新
//==========================================================================================
void cGameMain::Update(void)
{
switch (m_eState)
{
case STATE::START: Start(); break;
case STATE::MAIN: Main(); break;
case STATE::CLEAR: Clear(); break;
case STATE::OVER: Over(); break;
}
IBaseObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject* cGameMain::Finalize(void)
{
IBaseObject::Finalize();
return this;
}
//==========================================================================================
// ゲームオーバーまでの分を取得
//==========================================================================================
int cGameMain::GetOverTimeMinute(void)
{
int ret = 0;
cTimer* timer = (cTimer*)FindChild("GameOverTimer");
if (timer)
{
if (!timer->Finished())
{
ret = (int)(timer->GetLimit() - timer->GetTime()) / 60;
}
}
return ret;
}
//==========================================================================================
// ゲームオーバーまでの秒を取得
//==========================================================================================
int cGameMain::GetOverTimeSecond(void)
{
int ret = 0;
cTimer* timer = (cTimer*)FindChild("GameOverTimer");
if (timer)
{
if (!timer->Finished())
{
ret = (int)(timer->GetLimit() - timer->GetTime()) % 60;
}
}
return ret;
}
//==========================================================================================
// 開始
//==========================================================================================
void cGameMain::Start(void)
{
cTimer* timer = (cTimer*)FindChild("GameStartTimer");
cTimer* gameOverTimer = (cTimer*)FindChild("GameOverTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this, "GameStartTimer");
timer->Setup(START_TIME);
// スタート文字の生成
cUIManager* ui = (cUIManager*)FindChild("UIManager");
ui->Create(UIID::START_FONT);
// オブジェクトの状態を更新を止めておく
gameOverTimer->SetObjetState(OBJECT_STATE::WAIT);
}
// ゲーム開始状態が終わったらタイマーを戻す
if (timer->Finished())
{
if( gameOverTimer)
// オブジェクトの状態を更新を開始する
gameOverTimer->SetObjetState(OBJECT_STATE::ACTIVE);
// プレイヤーをゲーム実行状態にする
cPlayer* player = (cPlayer*)FindChild("Player");
if (player) player->ChangeState(cPlayer::STATE::NORMAL);
m_eState = STATE::MAIN;
}
}
//==========================================================================================
// メイン
//==========================================================================================
void cGameMain::Main(void)
{
cPlayer* player = (cPlayer*)FindChild("Player");
if (player)
{
// プレイヤーの状態に応じてゲームメインの状態を変更する
if (player->GetState() == cPlayer::STATE::GOAL)
{
m_eState = STATE::CLEAR;
}
if (player->GetState() == cPlayer::STATE::DEAD)
{
m_eState = STATE::OVER;
}
}
}
//==========================================================================================
// クリア
//==========================================================================================
void cGameMain::Clear(void)
{
cTimer* timer = (cTimer*)FindChild("GoalTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this, "GoalTimer");
timer->Setup(GOAL_TIME);
cUIManager* ui = (cUIManager*)FindChild("UIManager");
if (ui)
{
ui->Create(UIID::CLEAR_FONT);
}
}
// 時間が経過したらシーン移行
if (timer->Finished())
{
cSceneManager* sm = (cSceneManager*)GetRoot()->FindChild("SceneManager");
if (sm) sm->ChangeSceneUniTrans(SCENE_ID::TITLE, "data\\graphic\\rule_00.png");
}
cTimer* coinTimer = (cTimer*)FindChild("CoinTimer");
if (!coinTimer)
{
coinTimer = CreateObject<cTimer>(this,"CoinTimer");
coinTimer->Setup(0.02f);
}
if (coinTimer->Finished())
{
coinTimer->Reset();
cEffectManager* em = (cEffectManager*)GetRoot()->FindChild("EffectManager");
cGame* game = (cGame*)GetRoot();
em->Create(EFFECT_ID::COIN, { (float)cGame::Random(0,game->GetWindowWidth()),0.0f - 32.0f });
em->Create(EFFECT_ID::COIN, { (float)cGame::Random(0,game->GetWindowWidth()),0.0f - 32.0f });
}
}
//==========================================================================================
// オーバー
//==========================================================================================
void cGameMain::Over(void)
{
cTimer* timer = (cTimer*)FindChild("MainDeadTimer");
if (!timer)
{
timer = CreateObject<cTimer>(this, "MainDeadTimer");
timer->Setup(DEAD_TIME);
cUIManager* ui = (cUIManager*)FindChild("UIManager");
if (ui)
{
ui->Create(UIID::MISS_FONT);
}
}
// 死亡状態の時間が経過したらシーン移行
if (timer->Finished())
{
cSceneManager* sm = (cSceneManager*)GetRoot()->FindChild("SceneManager");
if (sm) sm->ChangeSceneUniTrans(SCENE_ID::TITLE, "data\\graphic\\rule_00.png");
}
}
<file_sep>#pragma once
/*==============================================================================*/
/* */
/* @file title : cTransition.h */
/* @brief : トランジションクラス */
/* @written : s.kosugi */
/* @create : 2019/03/11 */
/* */
/*==============================================================================*/
#include "..\IDrawBase.h"
#include "Utility/Timer/cTimer.h"
//================================================================================================
// トランジションクラス
// ユニバーサルトランジションを行い、出現や消失演出の制御を行う
class cTransition : public IDrawBase
{
public:
// トランジションを行う方向
enum class TransDirection {
TRANS_IN = 0,
TRANS_OUT,
};
// -------------------------------------------------------------------------------------------
// コンストラクタ
// filename : ルール画像のファイル名
// pObj : ブレンドする元画像のオブジェクトのポインタ
// dir : TRANS_IN フェードイン TRANS_OUT フェードアウト
// transtime : トランジション時間
cTransition(const std::string& filename, IDrawBase* pObj, TransDirection dir, float transtime);
// デストラクタ
~cTransition();
// 初期化
void Initialize(void);
// 更新
void Update(void);
// 破棄
void Finalize(void);
//---------------------------------------------------------------------
// 定数
// DrawBlendGraphで使う境界幅
enum class BorderRange {
RANGE_1 = 1,
RANGE_64 = 64,
RANGE_128 = 128,
RANGE_255 = 255,
};
//--------------------------------------------------------------------
// Getter
inline IDrawBase* GetTransObject(void) { return m_pTransObj; };
inline float GetBorderParam(void) { return m_fBorderParam; };
inline BorderRange GetBorderRange(void) { return m_eBorderRange; };
// トランジションが終了したかどうか?
// ret : true 終了した false : 再生中
bool IsEnd(void);
//---------------------------------------------------------------------
// Setter
inline void SetTransTime(float time) { m_fTransTime = time; };
// トランジション方向の設定
void SetTransDirection(TransDirection value);
// トランジションの最大時間の設定
inline void SetLimitTime(float time) { m_cTimer.SetLimit(time); };
// トランジション経過時間のリセット
inline void ResetTimer(void) { m_cTimer.Reset(); };
private:
//---------------------------------------------------------------------
// 定数
static const float BORDER_MAX; // 境界位置の最大値
static const int DEFAULT_PRIORITY; // 表示優先度
IDrawBase* m_pTransObj; // 遷移先の画像のポインタ
BorderRange m_eBorderRange; // DrawBlendGraphで使う境界幅
float m_fBorderParam; // DrawBlendGraphで使う境界位置
TransDirection m_eTransDirection; // トランジションを行う方向(フェードインかアウトか)
float m_fTransTime; // 合計トランジション時間(秒)
cTimer m_cTimer; // トランジションタイマー
};<file_sep>/*==============================================================================*/
/* */
/* @file title : cResult.cpp */
/* @brief : リザルトシーン */
/* @written : s.kosugi */
/* @create : 2018/12/02 */
/* */
/*==============================================================================*/
#include "..\..\..\cGame.h"
#include "cResult.h"
#include "..\..\cSceneManager.h"
#include "..\..\..\BaseObject\cSpriteObject.h"
#include <DxLib.h>
#include "DataManager/cDataManager.h"
#include "BaseObject/GameObject/UI/cUIManager.h"
#include "BaseObject/GameObject/GameStartObject/cTitleCursol.h"
#include "SoundCtrl/cSoundCtrl.h"
#include "ScoreManager/cScoreManager.h"
//==========================================================================================
// 定数
//==========================================================================================
const int cResult::RANK_B_BORDER = 10;
const int cResult::RANK_A_BORDER = 40;
const int cResult::RANK_S_BORDER = 80;
//==========================================================================================
// コンストラクタ
//==========================================================================================
cResult::cResult(IBaseObject * parent)
: IBaseScene(parent, "Title")
{
}
//==========================================================================================
// デストラクタ
//==========================================================================================
cResult::~cResult(void)
{
}
//==========================================================================================
// 初期化
//==========================================================================================
void cResult::Initialize(void)
{
// ゲームクラスの取得
cGame* game = (cGame*)GetRoot();
// 背景スプライトの生成
cSpriteObject* obj = CreateDrawObject<cSpriteObject>(this, "BackGround", "data\\graphic\\background.png");
obj->SetPriority(-101);
obj->SetPos((float)game->GetWindowWidth() / 2, (float)game->GetWindowHeight() / 2);
// UI管理の生成
cUIManager* ui = CreateObject<cUIManager>(this);
cSpriteObject* button = ui->Create(UIID::TITLE_BUTTON);
// スコアの取得
cScoreManager* scoreman = (cScoreManager*)GetRoot()->FindChild("ScoreManager");
int score = scoreman->GetScore();
// ランク画像のパス決定
std::string file_name;
if (score < RANK_B_BORDER) file_name = "data\\graphic\\rank_c.png";
if (score >= RANK_B_BORDER) file_name = "data\\graphic\\rank_b.png";
if (score >= RANK_A_BORDER) file_name = "data\\graphic\\rank_a.png";
if (score >= RANK_S_BORDER) file_name = "data\\graphic\\rank_s.png";
// ランク画像の生成
cSpriteObject* rank = CreateDrawObject<cSpriteObject>(this, "Rank", file_name.c_str());
rank->SetPos(game->GetWindowCenter().x,game->GetWindowHeight() / 4);
IBaseObject::Initialize();
//------------------------------------------------------------------
// ボタンの位置を基準にカーソルを配置(タイトルカーソルを流用)
cTitleCursol* cursol = CreateObject<cTitleCursol>(this);
cursol->Initialize();
cVector2 buttonPos = button->GetPos();
buttonPos.x -= 250.0f;
cursol->Setup(buttonPos, 90.0f);
buttonPos = button->GetPos();
cursol = CreateObject<cTitleCursol>(this);
cursol->Initialize();
buttonPos.x += 250.0f;
cursol->Setup(buttonPos, -90.0f);
//------------------------------------------------------------------
}
//==========================================================================================
// 更新
//==========================================================================================
void cResult::Update(void)
{
IBaseObject::Update();
}
//==========================================================================================
// 破棄
//==========================================================================================
IBaseObject* cResult::Finalize(void)
{
IBaseObject::Finalize();
return this;
}
|
38ac816be546215996fbe05089c3d2dab373a72b
|
[
"C",
"C++"
] | 135
|
C++
|
s-kosugi/FMAndroidBase
|
5b3d62fb71942995dcbc7e9c19aa250ecb735094
|
105381f3834cf781b63e965c5b3b1f8ae4a38a25
|
refs/heads/master
|
<file_sep>
Given /^that the following animals exist:$/ do |fields|
fields.hashes.each do |dog|
Dog.create!(dog)
end
end<file_sep>require 'spec_helper'
describe "Add" do
before do
click_link 'Enter a new dog'
fill_in "Title", :with => "Munar"
fill_in "Description", :with => "dark but lovely"
click_button 'Create Dog'
end
it "add a new animal" do
should see "Munar"
should see "Entered by <EMAIL>"
end
end
end
# Scenario: Add an animal
# Given I am on the new dog page
# When I fill in "Title" with "Munar"
# And I fill in "Description" with "dark but lovely"
# And I press "Create Dog"
# Then I should see "Munar"
# Then I should see "Entered by <EMAIL>"<file_sep>class DogsController < ApplicationController
before_action :find_dog, only: [:show, :edit, :update, :destroy]
def index
@dogs = Dog.all.order("created_at DESC")
end
def new
@dog=current_user.dogs.build
end
def show
end
def edit
end
def update
if @dog.update(dog_params)
redirect_to @dog, notice: " You have succesfully updated the dog information"
else
render 'edit'
end
end
def destroy
@dog.destroy
redirect_to root_path
end
def create
@dog =current_user.dogs.build(dog_params)
if @dog.save
redirect_to @dog, notice: " You have succesfully added the Dog"
else
render 'new'
end
end
private
def dog_params
params.require(:dog).permit(:title,:description,:image,:document)
end
def find_dog
@dog = Dog.find(params[:id])
end
end
<file_sep>class Dog < ActiveRecord::Base
attr_accessible :title, :description, :breed #idk
belongs_to :user
has_attached_file :image,styles: {medium: "300x300"}
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
has_attached_file :document
validates_attachment :document, :content_type => { :content_type => %w(application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document) }
end
<file_sep># dogswhocode - cs169 project | group 30
#entry interview video link: <http://youtu.be/TU3Op3IDYGk>
<file_sep>require 'spec_helper'
describe "sort animals" do
context "sort" do
before do
dog1 = Dog.create(:title => "Bryan")
dog2 = Dog.create(:title => "Max")
dog3 = Dog.create(:title => "Munar")
click_button "Title"
end
it "sorted in alphabetical order" do
dog1.appears_before(dog2)
dog2.appears_before(dog3)
end
end
end
# Scenario: Sorting animals by field
# Given that I am on the “All Animals” page
# And I click on the field “name”
# Then I should see “Bryan” before “Max”
# Then I should see “Max” before “Munar”<file_sep>require 'spec_helper'
describe "View all animals" do
before do
#how do we populate it beforehand for rspec... this is getting repetitive
dog1 = Dog.create!(:title => "Max", :breed => "Chihuahua")
dog2 = Dog.create!(:title => "Munar", :breed => "Chocolate Labrador")
end
it "see all the existing animals" do
expect(dog1).to exist
expect(dog2).to exist
end
end
# Scenario: View all animals
# Given I am on the home page
# Then I should see “Max”
# Then I should see “Munar”<file_sep>
When /^(?:|I )press on the field "([^"]*)"$/ do |button|
click_button(button)
end
Then /I should see "(.*)" before "(.*)"/ do |e1, e2|
# ensure that that e1 occurs before e2.
# page.body is the entire content of the page as a string.
pos_e1 = page.body =~ /\b#{e1}/
pos_e2 = page.body =~ /\b#{e2}/
assert pos_e1 < pos_e2
end<file_sep>
Given /^I am logged in as an admin$/ do
User.create!({:email=>"<EMAIL>",
:password=>"<PASSWORD>"})
step "I am on the sign in page"
step %Q|I fill in "Email" with "<EMAIL>"|
step %Q|I fill in "Password" with "<PASSWORD>"|
step %Q|I press "Log in"|
end<file_sep>require 'spec_helper'
describe "filter animals" do
context "filter" do
before do
dog1 = Dog.create(:title => "Bryan", :breed => "Chocolate Labrador")
dog2 = Dog.create(:title => "Max", :breed => "Chihuahua")
dog3 = Dog.create(:title => "Munar", :breed => "Chocolate Labrador")
#how are we going to implement filtering
#fill_in "Breed", :with => "Chocolate Labrador" // if we do it by text fill with autocomplete
end
it "filter the dog by specified field" do
expect(dog1).to exist
expect(dog2).not_to exist
expect(dog3).to exist
end
end
end
# Scenario: Filter animals by field
# When I filter by breed=”Chocolate Labrador”
# Then I should see “Bryan”
# And I should see “Munar”
# And I should not see “Max”<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Dog.create(:title => 'Bryan', :breed => 'Chocolate Labrador')
Dog.create(:title => 'Munar', :breed => 'Chocolate Labrador')
Dog.create(:title => 'Max', :breed => 'Golden Retriever')
|
67bbed0fba0187ceb26d1686d354b8a180704f73
|
[
"Markdown",
"Ruby"
] | 11
|
Ruby
|
imranyousuf/nonprofit_pet
|
7f5bd085352e9e3d3fe4e53ff7f7007f0e686203
|
6ca5513cb0caba5ea43ead30d52412a169e5a8b2
|
refs/heads/gh-pages
|
<repo_name>RathanKumar/uptown<file_sep>/js/custom.js
// Closes the sidebar menu
$("#menu-close").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
// Opens the sidebar menu
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
// Scrolls to the selected menu item on the page
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
// Map scrolling behaviour
$(document).ready(function() {
$('#map_iframe').addClass('scrolloff');
$('#map').on('click', function () {
$('#map_iframe').removeClass('scrolloff');
});
$('#map_iframe').mouseleave(function () {
$('#map_iframe').addClass('scrolloff');
});
typedAnim();
});
// odometer
setTimeout(function(){
odometer.innerHTML = 46;
}, 1000);
function typedAnim () {
$("#typed").typed({
strings: ["Studios", "Photography", "Videography", "Candid", "Studios"],
startDelay: 1500,
// loop: true,
typeSpeed: 150,
backSpeed: 50,
backDelay: 800
});
}
|
d2f38c0a0885cc7371caa59e35f69d83b002942b
|
[
"JavaScript"
] | 1
|
JavaScript
|
RathanKumar/uptown
|
cb79d32c7afecb71b5325e998cce4f9a7af8d1ed
|
7b225816a861ad4b136694a2a0c83c1423868f3a
|
refs/heads/master
|
<file_sep>'use strict';
$(document).ready(function() {
$.ajax({
url: "https://savingsmultipliedssh.firebaseio.com/items.json",
dataType: "jsonp",
success: function(data){
// data.preventDefault();
console.log(data);
console.log(data[0].title);
$("#item1").append("<img class='auction-size' src='" + data[0].image +"'>");
$("#item1").append("<br>");
$("#item1").append(data[0].title);
$("#item1").append(data[0].price);
$("#item1").append(data[0].seller);
$("#item1").append(data[0].endDate);
$("#item2").append("<img class='auction-size' src='" + data[1].image +"'>");
$("#item2").append("<br>");
$("#item2").append(data[1].title);
$("#item2").append(data[1].price);
$("#item2").append(data[1].seller);
$("#item2").append(data[1].endDate);
$("#item3").append("<img class='auction-size' src='" + data[2].image +"'>");
$("#item3").append("<br>");
$("#item3").append(data[2].title);
$("#item3").append(data[2].price);
$("#item3").append(data[2].seller);
$("#item3").append(data[2].endDate);
$("#item4").append("<img class='auction-size' src='" + data[3].image +"'>");
$("#item4").append("<br>");
$("#item4").append(data[3].title);
$("#item4").append(data[3].price);
$("#item4").append(data[3].seller);
$("#item4").append(data[3].endDate);
$("#item5").append("<img src='" + data[4].image +"'>");
$("#item5").append(data[4].title);
$("#item5").append(data[4].price);
$("#item5").append(data[4].seller);
$("#item5").append(data[4].endDate);
$("#item6").append("<img src='" + data[5].image +"'>");
$("#item6").append(data[5].title);
$("#item6").append(data[5].price);
$("#item6").append(data[5].seller);
$("#item6").append(data[5].endDate);
$("#item7").append("<img src='" + data[6].image +"'>");
$("#item7").append(data[6].title);
$("#item7").append(data[6].price);
$("#item7").append(data[6].seller);
$("#item7").append(data[6].endDate);
$("#item8").append("<img src='" + data[7].image +"'>");
$("#item8").append(data[7].title);
$("#item8").append(data[7].price);
$("#item8").append(data[7].seller);
$("#item8").append(data[7].endDate);
$("#item9").append("<img src='" + data[8].image +"'>");
$("#item9").append(data[8].title);
$("#item9").append(data[8].price);
$("#item9").append(data[8].seller);
$("#item9").append(data[8].endDate);
$("#item10").append("<img src='" + data[9].image +"'>");
$("#item10").append(data[9].title);
$("#item10").append(data[9].price);
$("#item10").append(data[9].seller);
$("#item10").append(data[9].endDate);
$("#item11").append("<img src='" + data[10].image +"'>");
$("#item11").append(data[10].title);
$("#item11").append(data[10].price);
$("#item11").append(data[10].seller);
$("#item11").append(data[10].endDate);
$("#item12").append("<img src='" + data[11].image +"'>");
$("#item12").append(data[11].title);
$("#item12").append(data[11].price);
$("#item12").append(data[11].seller);
$("#item12").append(data[11].endDate);
}
})
});
|
161eca64429e23827361eb7b4430549fa746e5a8
|
[
"JavaScript"
] | 1
|
JavaScript
|
jlsears/savings-multiplied_part2
|
73dbf3665b7c1abe5cd6b1d2af22ff576f00d1fc
|
ce07f74f916d429bf1a06538080d98b4c8019d56
|
refs/heads/master
|
<repo_name>ServantBrea/canvas-api-test<file_sep>/README.md
# canvas-api-test
# this code is trying to build a game engine API.
# How to use this code...
## install typescript and operation "tsc" in terminal<file_sep>/src/api-for-canvas.ts
class EventObserver {
static eventObserver: EventObserver;
targetList: DisplayObject[];
constructor() { }
static getInstance() {
if (EventObserver.eventObserver) {
return EventObserver.eventObserver;
} else {
EventObserver.eventObserver = new EventObserver();
EventObserver.eventObserver.targetList = new Array();
return EventObserver.eventObserver;
}
}
}
class Events {
eventType = "";
func: Function;
target: DisplayObject;
ifGet = false;
constructor(eventType: string, func: Function, target: DisplayObject, ifGet: boolean) {
this.eventType = eventType;
this.func = func;
this.target = target;
this.ifGet = ifGet;
}
}
interface Drawable {
draw(context2D: CanvasRenderingContext2D);
}
abstract class DisplayObject implements Drawable {
x = 0;
y = 0;
scaleX = 1;
scaleY = 1;
rotation = 0;
alpha = 1;
globalAlpha = 1;
matrix: math.Matrix = new math.Matrix();
globalMatrix: math.Matrix = new math.Matrix();
parent: DisplayObject = null;
eventList: Events[] = [];
//模版draw方法
draw(context2D: CanvasRenderingContext2D) {
this.matrix.updateFromDisplayObject(
this.x, this.y, this.scaleX, this.scaleY, this.rotation);
if (this.parent) {
this.globalAlpha =
this.parent.globalAlpha * this.alpha;
this.globalMatrix =
math.matrixAppendMatrix(this.matrix, this.parent.globalMatrix);
} else {
this.globalAlpha = this.alpha;
this.globalMatrix = this.matrix;
}
context2D.globalAlpha = this.globalAlpha;
context2D.setTransform(this.globalMatrix.a,
this.globalMatrix.b,
this.globalMatrix.c,
this.globalMatrix.d,
this.globalMatrix.tx,
this.globalMatrix.ty);
//console.log(this.globalMatrix.toString());
this.render(context2D);
}
addEventListener(eventType: string, func: Function, target: DisplayObject, ifGet: boolean) {
let evt = new Events(eventType, func, target, ifGet);
this.eventList.push(evt);
}
//子类重载渲染
abstract render(context2D: CanvasRenderingContext2D);
abstract getClick(point: math.Point);
}
class DisplayObjectContainer extends DisplayObject {
children: DisplayObject[] = new Array();
constructor() {
super();
}
render(context2D: CanvasRenderingContext2D) {
for (var child of this.children) {
child.draw(context2D);
}
}
addChild(child: DisplayObject) {
if (this.children.indexOf(child) == -1) {
this.children.push(child);
child.parent = this;
}
}
removeChild(child: DisplayObject) {
var tempChildren = this.children.concat();
for (var element of tempChildren) {
if (element == child) {
var index = this.children.indexOf(element);
tempChildren.splice(index, 1);
this.children = tempChildren;
return;
}
}
}
getClick(point: math.Point) {
let eventObserver = EventObserver.getInstance();
if (this.eventList.length != 0) {
eventObserver.targetList.push(this);
}
for (var i = 0; i < this.children.length; i++) {
let child = this.children[i];
let childMatrix = new math.Matrix();
childMatrix = math.invertMatrix(child.matrix);
let invertPoint = math.pointAppendMatrix(point, childMatrix);
let clickResult = child.getClick(invertPoint);
if (clickResult) {
return clickResult;
}
}
return null
}
}
class Bitmap extends DisplayObject {
private image: HTMLImageElement = null;
private hasLoaded = false;
private _src = "";
constructor() {
super();
this.image = new Image();
}
set src(src: string) {
this._src = "/resource/assets/" + src;
this.hasLoaded = false;
}
render(context2D: CanvasRenderingContext2D) {
if (this.hasLoaded) {
context2D.drawImage(
this.image, 0, 0, this.image.width, this.image.height);
} else {
this.image.src = this._src;
this.image.onload = () => {
context2D.drawImage(
this.image, 0, 0, this.image.width, this.image.height);
this.hasLoaded = true;
}
}
}
getClick(point: math.Point) {
if (this.image) {
let rect = new math.Rectangle(0, 0, this.image.width, this.image.height);
if (rect.ifPointBelong(point)) {
let eventObserver = EventObserver.getInstance();
if (this.eventList.length != 0) {
eventObserver.targetList.push(this);
}
return this;
} else {
return null;
}
}
}
}
class TextField extends DisplayObject {
text = "";
color = "";
fontSize = 10;
font = "Georgia";
constructor() {
super();
}
render(context2D: CanvasRenderingContext2D) {
context2D.fillStyle = this.color;
context2D.font = this.fontSize.toString() + "px " + this.font.toString();
context2D.fillText(this.text, this.x, this.y + this.fontSize);
}
getClick(point: math.Point) {
let rect = new math.Rectangle(0, 0, this.text.length * 10, 40);
if (rect.ifPointBelong(point)) {
let eventObserver = EventObserver.getInstance();
if (this.eventList.length != 0) {
eventObserver.targetList.push(this);
}
return this;
} else {
return null;
}
}
}<file_sep>/src/main.ts
window.onload = () => {
var context = document.getElementById("myCanvas") as HTMLCanvasElement;
var context2D = context.getContext("2d");
var background = new DisplayObjectContainer();
var container = new DisplayObjectContainer();
container.x = 0;
container.y = 0;
container.alpha = 1;
container.addEventListener("onMouseMove",(e:MouseEvent) => {
let dy = currentY - tempY;
let dx = currentX - tempX;
container.x += dx;
container.y += dy;
},this,false);
var text1 = new TextField();
text1.x = 0;
text1.y = 0;
text1.alpha = 0.8;
text1.color = "#FF0000";
text1.fontSize = 30;
text1.font = "Arial";
text1.text = "I lose my game of life!";
text1.addEventListener("onClick",()=> {
console.log("Text is clicked");
},this,false);
var text2 = new TextField();
text2.x = 0;
text2.y = 20;
text2.alpha = 1;
text2.color = "#0000FF";
text2.fontSize = 30;
text2.font = "Arial";
text2.text = "落命.....";
var bitmap = new Bitmap();
bitmap.x = 0;
bitmap.y = 0;
bitmap.alpha = 0.8;
bitmap.scaleX = 0.5;
bitmap.scaleY = 0.5;
bitmap.src = "codmw.png";
bitmap.addEventListener("onClick",()=> {
console.log("Bitmap is clicked");
},this,false);
container.addChild(bitmap);
container.addChild(text2);
background.addChild(container);
background.addChild(text1);
background.draw(context2D);
setInterval(() => {
context2D.clearRect(0, 0, context.width, context.height);
background.draw(context2D);
}, 30)
//CLICK API USING
let clickResult:DisplayObject;
let currentX:number;
let currentY:number;
let tempX:number;
let tempY:number;
let ifMouseDown = false;
window.onmousedown = (e) => {
ifMouseDown = true;
let targetList = EventObserver.getInstance().targetList;
targetList.splice(0,targetList.length);
clickResult = background.getClick(new math.Point(e.offsetX,e.offsetY));
currentX = e.offsetX;
currentY = e.offsetY;
console.log("Click position : " + currentX + " / " +currentY);
}
window.onmousemove = (e) => {
let targetList = EventObserver.getInstance().targetList;
tempX = currentX;
tempY = currentY;
currentX = e.offsetX;
currentY = e.offsetY;
if(ifMouseDown) {
for(var i = 0;i < targetList.length;i++) {
for(let temp of targetList[i].eventList) {
if(temp.eventType.match("onMouseMove") && temp.ifGet == true) {
temp.func(e);
}
}
}
for(var i = 0;i < targetList.length - 1;i++) {
for(let temp of targetList[i].eventList) {
if(temp.eventType.match("onMouseMove") && temp.ifGet == false) {
temp.func(e);
}
}
}
}
}
window.onmouseup = (e) => {
ifMouseDown = false;
let targetList = EventObserver.getInstance().targetList;
targetList.splice(0,targetList.length);
let anotherClickResult = background.getClick(new math.Point(e.offsetX,e.offsetY));
for (var i = 0;i < targetList.length;i++) {
for (let temp of targetList[i].eventList) {
if(temp.eventType.match("onClick") && anotherClickResult == clickResult) {
temp.func(e);
}
}
}
}
};
|
d6ed7cccca5d19e9f932151222c46ff8d4f60899
|
[
"Markdown",
"TypeScript"
] | 3
|
Markdown
|
ServantBrea/canvas-api-test
|
05a4d62ad139b3df0e39c18f83378162de790484
|
45b2ad70c15a5c78ff52c3ff0b167f0c0f8a7c0f
|
refs/heads/master
|
<repo_name>ADever/Career-Center-Log-In-Forms<file_sep>/Form3.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsAttempt4
{
public partial class Form3 : Form
{
public static string keyName = "";
public Form3()
{
InitializeComponent();
}
private void submit_Click(object sender, EventArgs e)
{
keyName = name.Text;
SqlConnection con = new SqlConnection("Data Source=localhost; initial Catalog = usrinfo; Integrated Security = true");
SqlCommand cmd = new SqlCommand("select count(*) from usrinfo where name = '"+name.Text+"' and socialNum = '"+socialNum.Text+"'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
Form u = new Form5();
u.Show();
this.Hide();
} else if (dt.Rows[0][0].ToString() == "0")
{
MessageBox.Show("Invalid information");
}
}
private void socialNum_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
private void Form3_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsAttempt4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=localhost; initial Catalog = usrinfo; Integrated Security = true");
con.Open();
SqlCommand command = new SqlCommand("insert into usrinfo(name, socialNum, age)values('" + this.name.Text + "', '" + this.socialNum.Text + "', '" + this.age.Text + "')", con);
int i = command.ExecuteNonQuery();
if (i!=0)
{
MessageBox.Show("Saved");
}
else
{
MessageBox.Show("error");
}
con.Close();
}
}
}
<file_sep>/Form5.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsAttempt4
{
public partial class Form5 : Form
{
private SqlConnection connection;
private SqlCommand command;
private SqlConnection connection2;
private SqlCommand command2;
private DateTime myDate = DateTime.Now.Date;
//DBAccess objDbAccess = new DBAccess();
public Form5()
{
InitializeComponent();
}
private void submit_Click(object sender, EventArgs e)
{
connection = new SqlConnection(" Data Source=localhost; initial Catalog = usrinfo; Integrated Security = true; pooling = false");
connection2 = new SqlConnection(" Data Source=localhost; initial Catalog = usrinfo; Integrated Security = true; pooling = false");
connection.Open();
connection2.Open();
command = new SqlCommand("UPDATE usrinfo SET testInt = @a1 WHERE name = @name", connection);
command2 = new SqlCommand("UPDATE usrinfo SET date = @a2 WHERE name = @name", connection2);
command.Parameters.AddWithValue("a1", testTry.Text);
command.Parameters.AddWithValue("name", Form3.keyName);
command2.Parameters.AddWithValue("a2", myDate);
command2.Parameters.AddWithValue("name", Form3.keyName);
command.ExecuteNonQuery();
command2.ExecuteNonQuery();
/*
int row = objDbAccess.executeQuery(updateCommand);
if (row == 1)
{
MessageBox.Show("Info updated well");
} else
{
MessageBox.Show("error, try again");
}
*/
}
}
}
|
d5de853d43dd141642314a1f9cb876f434d53ff0
|
[
"C#"
] | 3
|
C#
|
ADever/Career-Center-Log-In-Forms
|
bcfe05fee10f7bd3d5f32f97f88dbc2771001465
|
2a395028d7accc9f5c8e6155e83d1e5b179c9b56
|
refs/heads/master
|
<repo_name>ychen1012/online-judge<file_sep>/src/test/java/cn/oj/onlinejudge/OnlineJudgeApplicationTests.java
package cn.oj.onlinejudge;
import cn.oj.onlinejudge.service.JudgeService;
import cn.oj.onlinejudge.vo.JudgeTask;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class OnlineJudgeApplicationTests {
@Autowired
private JudgeService service;
@Test
public void judgeTest() {
List<String> input = new ArrayList<>();
input.add("111\n11\n");
input.add("222\n22\n");
input.add("333\n33\n");
JudgeTask task = new JudgeTask(null,input,input,1000l,65535l,1,"#include <stdio.h>\n" +
"int main()\n" +
"{\n" +
"\tint a,b;\n" +
"\tscanf(\"%d%d\",&a,&b);\n" +
"\tint sum=0;\n" +
"\tsum = a + b;\n" +
"\tprintf(\"%d\",sum);\n" +
"\treturn 0;\n" +
"}");
System.out.println(service.judge(task));
task.setJudgeId(2);
System.out.println(service.judge(task));
task.setJudgeId(3);
System.out.println(service.judge(task));
task.setJudgeId(4);
System.out.println(service.judge(task));
task.setJudgeId(5);
System.out.println(service.judge(task));
task.setJudgeId(6);
System.out.println(service.judge(task));
task.setJudgeId(7);
System.out.println(service.judge(task));
}
}
<file_sep>/src/main/java/cn/oj/onlinejudge/util/ExecutorUtil.java
package cn.oj.onlinejudge.util;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
public class ExecutorUtil {
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class ExecMessage {
private String error;
private String stdout;
}
public static ExecMessage exec(String cmd, long milliseconds) {
Runtime runtime = Runtime.getRuntime();
final Process exec;
try {
exec = runtime.exec(cmd);
if (!exec.waitFor(milliseconds, TimeUnit.MILLISECONDS)) {
if (exec.isAlive()) {
exec.destroy();
}
throw new InterruptedException();
}
} catch (IOException e) {
return new ExecMessage(e.getMessage(), null);
} catch (InterruptedException e) {
return new ExecMessage("timeOut", null);
}
ExecMessage res = new ExecMessage();
res.setError(message(exec.getErrorStream()));
res.setStdout(message(exec.getInputStream()));
return res;
}
private static String message(InputStream inputStream) {
ByteArrayOutputStream buffer = null;
try {
buffer = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes)) != -1) {
buffer.write(bytes, 0, len);
}
String result = buffer.toString("UTF-8").trim();
if (result.equals("")) {
return null;
}
return result;
} catch (IOException e) {
return e.getMessage();
} finally {
try {
inputStream.close();
buffer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
<file_sep>/src/main/java/cn/oj/onlinejudge/handler/base/JavaHandler.java
package cn.oj.onlinejudge.handler.base;
import cn.oj.onlinejudge.util.ExecutorUtil;
import cn.oj.onlinejudge.util.FileUtils;
import cn.oj.onlinejudge.vo.JudgeTask;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
@Service
public class JavaHandler extends Handler {
/*
* PATH作为标记,实际运行中听过String.replace()替换掉PATH
*
* */
@Value("${judge.Javaword}")
private String javaCompileCommand;
@Value("${judge.Javarun}")
private String javaRunCommand;
@Override
protected void createSrc(JudgeTask task, File path) throws IOException {
File srcPath = new File(path, "main.java");
FileUtils.write(task.getSrc(), srcPath);
}
@Override
protected ExecutorUtil.ExecMessage HandlerCompiler(File path) {
String realCommandCommand = javaCompileCommand.replace("PATH", path.getPath());
ExecutorUtil.ExecMessage msg = ExecutorUtil.exec(realCommandCommand, 1000);
return msg;
}
@Override
protected String getRunCommand(File path) {
return javaRunCommand.replace("PATH", path.getPath());
}
}
<file_sep>/src/main/java/cn/oj/onlinejudge/handler/Main.java
package cn.oj.onlinejudge.handler;
import cn.oj.onlinejudge.util.ExecutorUtil;
import lombok.extern.log4j.Log4j;
import java.io.File;
@Log4j
public class Main {
public static void main(String[] args) {
File file = new File("C:\\Users\\Administrator\\Desktop\\test\\test");
ExecutorUtil.exec("rm -rf " + file.getPath(),500);
}
}
<file_sep>/src/main/java/cn/oj/onlinejudge/handler/base/Python3Handler.java
package cn.oj.onlinejudge.handler.base;
import cn.oj.onlinejudge.util.ExecutorUtil;
import cn.oj.onlinejudge.util.FileUtils;
import cn.oj.onlinejudge.vo.JudgeTask;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
@Service
public class Python3Handler extends Handler {
@Value("$(python2 PATH/main.py)")
private String python2RunCommand;
@Override
protected void createSrc(JudgeTask task, File path) throws IOException {
File srcPath = new File(path, "main.py");
FileUtils.write(task.getSrc(), srcPath);
}
@Override
protected ExecutorUtil.ExecMessage HandlerCompiler(File path) {
return new ExecutorUtil.ExecMessage();
}
@Override
protected String getRunCommand(File path) {
return python2RunCommand.replace("PATH", path.getPath());
}
}
<file_sep>/src/main/resources/judge.py
import sys
import json
import lorun
import shlex
RESULT_STR = [
'Accepted',
'Presentation Error',
'Time Limit Exceeded',
'Memory Limit Exceeded',
'Wrong Answer',
'Runtime Error',
'Output Limit Exceeded',
'Compile Error',
'System Error'
]
def run(cmd, stdIn, stdOut, userOut, timeLimit, memoryLimit):
result, fileIn, fileOut = None, None, None
try:
fileIn = open(stdIn, 'r')
fileOut = open(userOut, 'w')
runcfg = {
'args': shlex.split(cmd),
'fd_in': fileIn.fileno(),
'fd_out': fileOut.fileno(),
'timelimit': timeLimit,
'memorylimit': memoryLimit,
}
result = lorun.run(runcfg)
except Exception as e:
result = {'memoryused': 0, 'timeused': 0, 'result': 8,'errormessage': str(e)}
finally:
if fileIn is not None:
fileIn.close()
if fileOut is not None:
fileOut.close()
if result['result'] == 0:
file1, file2 = None, None
try:
file1 = open(userOut, 'r')
file2 = open(stdOut, 'r')
rst = lorun.check(file2.fileno(), file1.fileno())
if rst != 0:
result = {'memoryused': 0, 'timeused': 0, 'result': rst}
except Exception as e:
result = {'memoryused': 0, 'timeused': 0, 'result': 8, 'errormessage': str(e)}
finally:
if file1 is not None:
file1.close()
if file2 is not None:
file2.close()
else:
result['memoryused'], result['timeused'] = 0, 0
return result
if __name__ == '__main__':
param = {
'cmd': sys.argv[1].replace('@', ' '),
'tmp': sys.argv[2],
'timeused': int(sys.argv[3]),
'memory': int(sys.argv[4]),
'stdIn': sys.argv[5],
'stdOut': sys.argv[6]
}
res = json.dumps(run(param['cmd'],
param['stdIn'],
param['stdOut'],
param['tmp'],
param['timeused'],
param['memory']))
print(res)
|
2a72941fa206a7cf862c25660f87be8e505349f6
|
[
"Java",
"Python"
] | 6
|
Java
|
ychen1012/online-judge
|
07e758c28b6898ce2146c7d8176a4f27331aef39
|
c53e8703d6869e0d3d3e0e42c6675d07e8ba19e5
|
refs/heads/master
|
<repo_name>lgv-0/cs-module-project-iterative-sorting<file_sep>/src/searching/searching.py
def linear_search(arr, target):
for z in range(0, len(arr)):
if arr[z] == target:
return z
return -1 # not found
import math
# Write an iterative implementation of Binary Search
def binary_search(arr, target):
if (len(arr) < 1):
return -1
_min = 0
_max = len(arr) - 1
# Your code here
if arr[_max] == target:
return len(arr) - 1
elif arr[_min] == target:
return 0
else:
while _min != _max:
_next = math.floor((_min + _max) / 2)
if arr[_next] == target:
return _next
elif arr[_next] < target:
_min = _next
else:
_max = _next
return -1 # not found
|
1e1b2172680a76cb739dbb9d04ac08a312cc5705
|
[
"Python"
] | 1
|
Python
|
lgv-0/cs-module-project-iterative-sorting
|
be562f85dad0beceebfb749998f7498637f01ac9
|
f6300eca7284b6dd0c4aa07290c29570deb738d5
|
refs/heads/master
|
<repo_name>xlhector10/Python<file_sep>/README.md
# Python
This directory contains personal proyects based totaly or parcialy on Python.
These proyects were made for personal interest or just booring, so everyone who needs can make use of them.
Some of proyects where made with help of OpenSource libreries.
<file_sep>/DeclaracionAnual/DeclaracionAnual.py
#!/usr/bin/python
import xml.etree.ElementTree as ET, glob, sys, os
files = glob.glob("*.xml")
TotalSueldos = 0
TotalExento = 0
TotalGravado = 0
TotalImpuestosRetenidos = 0
Deducciones = 0
SueldoDeclaracion = 0
LimiteInferior = 0
CuotaFija = 0
Excedente = 0
ImpuestosPagarSubtotal = 0
ImpuestosPagarTotal = 0
Tasa = 0
SaldoFinal = 0
for file in files:
tree = ET.parse(file)
root = tree.getroot()
renglon = ''
stamp = root.find('.//*[@TotalGravado]')
if stamp is not None:
TotalGravado = TotalGravado + float(stamp.attrib.get('TotalGravado'))
if stamp is not None:
TotalSueldos = TotalSueldos + float(stamp.attrib.get('TotalSueldos'))
if stamp is not None:
TotalExento = TotalExento + float(stamp.attrib.get('TotalExento'))
stamp = root.find('.//*[@TotalImpuestosRetenidos]')
if stamp is not None:
TotalImpuestosRetenidos = TotalImpuestosRetenidos + float(stamp.attrib.get('TotalImpuestosRetenidos'))
Deducciones = float(input('Ingrese Deducciones:'))
SueldoDeclaracion = TotalGravado - Deducciones
if SueldoDeclaracion < float(103550.44):
LimiteInferior = float(58922.17)
CuotaFija = float(3460.01)
Tasa = float(10.88) / 100
elif SueldoDeclaracion < float(120372.83):
LimiteInferior = float(103550.45)
CuotaFija = float(8315.57)
Tasa = float(16.00) / 100
elif SueldoDeclaracion < float(144119.23):
LimiteInferior = float(120372.84)
CuotaFija = float(11007.14)
Tasa = float(17.92) / 100
elif SueldoDeclaracion < float(290667.75):
LimiteInferior = float(144119.24)
CuotaFija = float(15262.49)
Tasa = float(21.36) / 100
elif SueldoDeclaracion < float(458132.29):
LimiteInferior = float(290667.76)
CuotaFija = float(46565.26)
Tasa = float(23.52) / 100
Excedente = SueldoDeclaracion - LimiteInferior
ImpuestosPagarSubtotal = Excedente * Tasa
ImpuestosPagarTotal = ImpuestosPagarSubtotal + CuotaFija
SaldoFinal = TotalImpuestosRetenidos - ImpuestosPagarTotal
print " + Total Sueldo:" + str(TotalSueldos)
print " - Total Exento:" + str(TotalExento)
print "-------------------------------"
print " = Total Gravado:" + str(TotalGravado)
print " - Deducciones:" + str(Deducciones)
print "-------------------------------"
print "Ingreso Anual para la declaracion:" + str(SueldoDeclaracion)
print "Limite inferior:" + str(LimiteInferior)
print " Excedente:" + str(Excedente)
print " ImpuestosPagarSubtotal:" + str(ImpuestosPagarSubtotal)
print " + Couta fija:" + str(CuotaFija)
print "-------------------------------"
print " Impuestos A pagar:" + str(ImpuestosPagarTotal)
print " Impuestos Retenidos:" + str(TotalImpuestosRetenidos)
print "---------------RESULTADO--------------------"
print " Saldo Final:" + str(SaldoFinal)
|
2159442085ccfe55ef7aecf42947c2e1564f3514
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
xlhector10/Python
|
ff1e8cadbfa6fbc2b877eaa8ab6d360ed48f3beb
|
a3a96d47f8655c7db2da3f838d1033f095557a5e
|
refs/heads/master
|
<repo_name>MarinaKrivova/basic_projects<file_sep>/Document_Retrieval/my_retriever.py
class Retrieve:
# Create new Retrieve object storing index and termWeighting scheme
def __init__(self,index, termWeighting):
self.index = index
self.termWeighting = termWeighting
def count_docs_in_collection(self, index):
"""Counts number of unique documents in the index file"""
doc_in_collection = set([])
for main_key in self.index:
doc_in_collection.update(self.index[main_key].keys())
return len(doc_in_collection)
def cosine_similarity_final(self, dict_qi_di, dict_len_doc):
"""Computes cosine similarities of documnets vectors and returns top10 most similar documents"""
# similarity ~ sum(q_i*d_i)/sum(d_i^2) = sum(q_i*d_i)/len_doc
import math
doc_sim_dict = {}
for doc_index in dict_qi_di:
doc_sim_dict[doc_index] = dict_qi_di[doc_index] / math.sqrt(dict_len_doc[doc_index])
sorted_docs = sorted(doc_sim_dict, key = lambda w: doc_sim_dict[w], reverse=True)
if len(sorted_docs)>=10:
return sorted_docs[:10]
else:
return sorted_docs
def BinaryModel(self, query):
"""Computes similarity of a query and documents based on binary term weighting
and return indexes of top 10 relevant documents"""
# similarity ~ sum(q_i*d_i)/sum(d_i^2) = sum(q_i*d_i)/len_doc
# q_i*d_i = terms 0 or 1 for query and a document
# retreive unique documents that have at least one word from the query
# and immediatly compute product of word frequencies in query and this document
doc_index_qi_di = {}
words_in_query_and_index = list(query & self.index.keys())
for word_query in words_in_query_and_index:
for doc_index in self.index[word_query]:
doc_index_qi_di[doc_index] = doc_index_qi_di.setdefault(doc_index,0) + 1 * 1
# The retrieved documents have obviously more words than presented in the query,
# so to access full length of a document (sum(d_i^2),
# we need to go through the whole index files and find other words in each retrieved document
doc_len_dict = {}
for word_general in self.index:
key_doc_in_index_word_general = list(doc_index_qi_di.keys() & self.index[word_general].keys())
for key_doc in key_doc_in_index_word_general:
doc_len_dict[key_doc] = doc_len_dict.setdefault(key_doc, 0) + 1**2
retrieved_docs = self.cosine_similarity_final(doc_index_qi_di, doc_len_dict)
return retrieved_docs
def tfModel(self, query):
"""Computes similarity of a query and documents based on frequency term weighting
and return indexes of top 10 relevant documents"""
# similarity ~ sum(q_i*d_i)/sum(d_i^2) = sum(q_i*d_i)/len_doc
# q_i*d_i = tf (frequencies) for query and a document
doc_index_tfqi_tfdi = {}
words_in_query_and_index = list(query & self.index.keys())
for word_query in words_in_query_and_index:
for doc_index in self.index[word_query]:
doc_index_tfqi_tfdi[doc_index] = doc_index_tfqi_tfdi.setdefault(doc_index, 0) + query[word_query] * self.index[word_query][doc_index]
doc_len_dict = {}
for word_general in self.index:
key_doc_in_index_word_general = list(doc_index_tfqi_tfdi.keys() & self.index[word_general].keys())
for key_doc in key_doc_in_index_word_general:
doc_len_dict[key_doc] = doc_len_dict.setdefault(key_doc,0) + self.index[word_general][key_doc]**2
retrieved_docs = self.cosine_similarity_final(doc_index_tfqi_tfdi, doc_len_dict)
return retrieved_docs
def tfidfModel(self, query):
"""Computes similarity of a query and documents based on frequency term weighting
and return indexes of top 10 relevant documents"""
# similarity ~ sum(q_i*d_i)/sum(d_i^2) = sum(q_i*d_i)/len_doc
# q_i*d_i = tfidf for query and a document
# df - number of doc containg term
# tf - number of times term in the doc
# idf = math.log10(D/df)
# D - number of documents in the collection
import math
D = self.count_docs_in_collection(self.index)
tfidf_doc_query = {}
query_in_index = list(query.keys() & self.index.keys())
for word_query in query_in_index:
df = len(self.index[word_query])
# idf is identical for query and document
idf = math.log10(D/df)
for doc_index in self.index[word_query]:
tf_doc = self.index[word_query][doc_index]
tf_query = query[word_query]
tfidf_doc_query[doc_index] = tfidf_doc_query.setdefault(doc_index, 0) + tf_query*idf*tf_doc*idf
doc_tfidf_len = {}
for word_general in self.index:
df_general = len(self.index[word_general])
idf_general = math.log10(D/df_general)
key_word_query_index_word_doc = list(tfidf_doc_query.keys() & self.index[word_general].keys())
for key_doc in key_word_query_index_word_doc:
tf_doc_general = self.index[word_general][key_doc]
doc_tfidf_len[key_doc] = doc_tfidf_len.setdefault(key_doc, 0) + (tf_doc_general*idf_general)**2
retrieved_docs = self.cosine_similarity_final(tfidf_doc_query, doc_tfidf_len)
return retrieved_docs
def forQuery(self, query):
if self.termWeighting == 'binary':
return self.BinaryModel(query)
elif self.termWeighting == 'tf':
return self.tfModel(query)
elif self.termWeighting == 'tfidf':
return self.tfidfModel(query)
else:
print("ERROR: term weighting schemes is not recognized")
return<file_sep>/README.md
## Basic ML projects in Python
Performed as Assignments in MSc Data Analytics courses at the University of Sheffield:
- Air quality prediction with regularised regression (Closed Form and SGD)
- Cifar10 image classification with PyTorch
- simple Document retrieval system
- Text Classification with Logistic Regression
- Text Classification with a Feedforward Network
|
398f3731e56c178d4fb55710ca9dbfd886f28525
|
[
"Markdown",
"Python"
] | 2
|
Python
|
MarinaKrivova/basic_projects
|
62d2e531ab01f991d0b438bcb41c0a0dc4d13152
|
c5abe0e0b3cbe571ca5d10e1ed159a44de58599f
|
refs/heads/master
|
<file_sep>from flask import Flask, render_template, request
import requests
import datetime
import json
app = Flask(__name__)
x = datetime.datetime.today()
date = x.strftime("%d-%m-%Y")
@app.route('/')
def index():
return render_template('index.html')
@app.route('/suggestions')
def suggestions():
available_list = []
import datetime
import json
import requests
browser_header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
pincode = '410206'
x = datetime.datetime.today()
date = x.strftime("%d-%m-%Y")
URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={pincode}&date={date}".format(
pincode=pincode, date=date)
response = requests.get(URL, headers=browser_header)
if (response.ok) and ('centers' in json.loads(response.text)):
resp_json = json.loads(response.text)['centers']
if resp_json is not None:
for each in resp_json:
for session in each['sessions']:
if session['min_age_limit'] == 18:
print(each['name'], ":")
# if session['available_capacity'] > 0:
# print(session)
final_list = {each['name']: session['available_capacity']}
available_list.append(final_list)
print(available_list)
return render_template('available.html', suggestions=available_list)
if __name__ == '__main__':
app.run(debug=True)
<file_sep>import datetime
import json
import requests
browser_header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
pincode = '410206'
x = datetime.datetime.today()
date = x.strftime("%d-%m-%Y")
URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode={pincode}&date={date}".format(
pincode=pincode, date=date)
response = requests.get(URL, headers=browser_header)
if (response.ok) and ('centers' in json.loads(response.text)):
resp_json = json.loads(response.text)['centers']
if resp_json is not None:
for each in resp_json:
for session in each['sessions']:
if session['min_age_limit'] == 18:
print(each['name'], ":")
# if session['available_capacity'] > 0:
# print(session)
print("Avaialble : ", session['available_capacity'])<file_sep>import requests
import json
import wikipedia
import random
import nltk
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
higreeting = ["नमस्ते ", "नमस्कार", "आपले स्वागत आहे"]
token = ''
base = "https://api.telegram.org/bot{}/".format(token)
def get_updates(offset=None):
url = base + "getUpdates?timeout=100"
if offset:
url = url + "&offset={}".format(offset + 1)
r = requests.get(url)
return json.loads(r.content)
def send_message(msg, chat_id):
url = base + "sendMessage?chat_id={}&text={}".format(chat_id, msg)
if msg is not None:
requests.get(url)
def tokenit(msg):
try:
tokens = nltk.word_tokenize(msg)
tagged = nltk.pos_tag(tokens)
except Exception as e:
tagged = []
return tagged
def make_reply(msg):
reply = None
tokenize = tokenit(msg)
msg = [lis[0].lower() for lis in tokenize if lis[1] == 'NN' or lis[1] == 'NNP' or
lis[1] == 'JJ' or lis[1] == 'NNS' or lis[1] == 'VBN']
if len(msg) is not 0:
msg = "_".join(msg)
msg = msg.replace("something_", "")
if "/start" in msg:
reply = "Hello"
elif msg == "hi" or msg == "hello":
reply = random.choice(higreeting)
elif msg is not None:
try:
print("searching for :", msg)
reply = wikipedia.summary(msg, sentences=2)
except Exception as e:
search = wikipedia.search(str(msg), results=2)
if search:
reply = ",".join(search)
reply = "Do you mean : " + reply
else:
reply = "Hey buddy,Try again with a different word" # wikipedia.summary(msg+ "(greeting)", sentences=2)
return reply
update_id = None
while True:
updates = get_updates(offset=update_id)
updates = updates["result"]
if updates:
for item in updates:
update_id = item["update_id"]
try:
message = str(item["message"]["text"])
# message = message.split(" ")[-1]
print(message, "message received ", type(message))
except:
message = None
from_ = item["message"]["from"]["id"]
reply = make_reply(message)
print("Replying....")
send_message(reply, from_)
print("repoply send... :", reply)
<file_sep>from flask import Flask, render_template, Response
import cv2
ds_factor=0.6
app = Flask(__name__)
face_cascade=cv2.CascadeClassifier(r"haarcascade_frontalface_default.xml")
@app.route('/')
def index():
return render_template('index.html')
def gen(video):
while True:
ret, frame = video.read()
frame = cv2.resize(frame, None, fx=ds_factor, fy=ds_factor,
interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face_rects = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in face_rects:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
break
ret, jpeg = cv2.imencode('.jpg', frame)
frame = jpeg.tobytes()
# frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/video_feed')
def video_feed():
video = cv2.VideoCapture(0)
return Response(gen(video),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
<file_sep>from flask import Flask, render_template, request
import speech_recognition as sr
r = sr.Recognizer()
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index5.html')
@app.route('/result', methods=['POST', 'GET'])
def result():
if request.method == 'GET':
with sr.Microphone() as source:
print("Speak Anything :")
audio = r.listen(source)
print(audio)
try:
text = r.recognize_google(audio)
print(text)
print("You said : {}".format(text))
except Exception as e:
print("Sorry could not recognize what you said")
return render_template("index5.html", result=text)
if __name__ == '__main__':
app.run(debug=True)
<file_sep>import numpy as np
import os
import cv2
filename = 'video.avi'
frames_per_second = 24.0
res = '720p'
face_cascade=cv2.CascadeClassifier(r"haarcascade_frontalface_default.xml")
SMILE_CASCADE = cv2.CascadeClassifier(r"haarcascade_smile.xml")
# Set resolution for the video capture
# Function adapted from https://kirr.co/0l6qmh
def change_res(cap, width, height):
cap.set(3, width)
cap.set(4, height)
# Standard Video Dimensions Sizes
STD_DIMENSIONS = {
"480p": (640, 480),
"720p": (1280, 720),
"1080p": (1920, 1080),
"4k": (3840, 2160),
}
# grab resolution dimensions and set video capture to it.
def get_dims(cap, res='1080p'):
width, height = STD_DIMENSIONS["480p"]
if res in STD_DIMENSIONS:
width,height = STD_DIMENSIONS[res]
## change the current caputre device
## to the resulting resolution
change_res(cap, width, height)
return width, height
# Video Encoding, might require additional installs
# Types of Codes: http://www.fourcc.org/codecs.php
VIDEO_TYPE = {
'avi': cv2.VideoWriter_fourcc(*'XVID'),
#'mp4': cv2.VideoWriter_fourcc(*'H264'),
'mp4': cv2.VideoWriter_fourcc(*'XVID'),
}
def get_video_type(filename):
filename, ext = os.path.splitext(filename)
if ext in VIDEO_TYPE:
return VIDEO_TYPE[ext]
return VIDEO_TYPE['avi']
cap = cv2.VideoCapture(0)
out = cv2.VideoWriter(filename, get_video_type(filename), 25, get_dims(cap, res))
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face_rects = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in face_rects:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
region_of_interest_bw = gray[y:y + h, x:x + w]
region_of_interest_color = frame[y:y + h, x:x + w]
smiles = SMILE_CASCADE.detectMultiScale(region_of_interest_bw, 1.7, 22)
for sx, sy, sw, sh in smiles:
print(sx, sy, sw, sh)
cv2.rectangle(region_of_interest_color, (sx, sy),
(sx + sw, sy + sh), (0, 0, 255), 2)
break
ret, jpeg = cv2.imencode('.jpg', frame)
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
<file_sep>from flask import Flask, render_template, request
from textblob import TextBlob
app = Flask(__name__)
@app.route('/')
def func1():
result = ""
return render_template('index.html', result=result)
@app.route('/result', methods=['POST', 'GET'])
def func2():
if request.method == 'POST':
result = request.form['Name']
blob = TextBlob(result)
for sentence in blob.sentences:
result = sentence.sentiment.polarity
ok = sentence.sentiment.polarity
print(result)
if 0 < result < 1:
result = "Positive"
elif result == 0:
result = "Neutral"
else:
result = "Negative"
return render_template('index.html', result=result+ " "+str(ok))
else:
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
<file_sep>import cv2
import sys
import logging as log
import datetime as dt
from time import sleep
cascPath = r"haarcascade_frontalface_default.xml"
SMILE_CASCADE = cv2.CascadeClassifier(r"haarcascade_smile.xml")
faceCascade = cv2.CascadeClassifier(cascPath)
log.basicConfig(filename='webcam.log', level=log.INFO)
video_capture = cv2.VideoCapture(0)
anterior = 0
img_counter = 1
while True:
if not video_capture.isOpened():
print('Unable to load camera.')
sleep(5)
pass
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
region_of_interest_bw = gray[y:y + h, x:x + w]
region_of_interest_color = frame[y:y + h, x:x + w]
smiles = SMILE_CASCADE.detectMultiScale(region_of_interest_bw, 1.7, 22)
for sx, sy, sw, sh in smiles:
cv2.rectangle(region_of_interest_color, (sx, sy),
(sx + sw, sy + sh), (0, 0, 255), 2)
if anterior != len(faces):
anterior = len(faces)
log.info("faces: " + str(len(faces)) + " at " + str(dt.datetime.now()))
# Display the resulting frame
cv2.imshow('Video', frame)
k = cv2.waitKey(1)
if k%256 == 32:
# SPACE pressed
img_name = "opencv_frame_{}.png".format(img_counter)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
if cv2.waitKey(1) & 0xFF == ord('s'):
check, frame = video_capture.read()
cv2.imshow("Capturing", frame)
cv2.imwrite(filename='saved_img.jpg', img=frame)
video_capture.release()
img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
img_new = cv2.imshow("Captured Image", img_new)
cv2.waitKey(1650)
print("Image Saved")
print("Program End")
cv2.destroyAllWindows()
break
elif cv2.waitKey(1) & 0xFF == ord('q'):
print("Turning off camera.")
video_capture.release()
print("Camera off.")
print("Program ended.")
cv2.destroyAllWindows()
break
# Display the resulting frame
cv2.imshow('Video', frame)
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
<file_sep># facedetection
Reads the face using the opencv using python.
Use spacebar to capture image.
Pres Esc to exit the camera window.
|
83127665d88f069febb1ee376189614954167606
|
[
"Markdown",
"Python"
] | 9
|
Python
|
AbhijeetArde/Overall
|
367a96cb03cc465e69362ff9294e1effae73216f
|
0e32364176bff929cc999298688f6ae650c54d6d
|
refs/heads/master
|
<repo_name>aeoril/aeoril.github.io.old<file_sep>/hallidayResnick/2-2/index.html
---
layout: default
scripts: mathjax
css: hallidayResnick-2-2
navhilite: projects
title: QuarksCode | <NAME> and Walker 2-2
---
<div class="page">
<h1 class="title"><NAME> and Walker Chapter 2 Section 2</h1>
<div class="content">
{% capture page %}
{% include hallidayResnick-2-2.md %}
{% endcapture %}
{{ page | markdownify }}
</div>
<div class="content">
{% capture page %}
{% include hallidayResnick-legal.md %}
{% endcapture %}
{{ page | markdownify }}
</div>
</div>
<file_sep>/README.md
## Aeoril's Github Pages
This repo serves up http://en.quarkscode.com<file_sep>/_includes/hallidayResnick-legal.md
### Important Legal Notice
These tutorials and simulations are based on concepts related to
*The Fundamentals of Physics - Fifth Edition* by Halliday, <NAME> Walker. The book is Copyright © 1997 by
<NAME> & Sons, Inc. All rights reserved. ISBN: 0-471-10559-7. QuarksCode is unaffiliated with the authors and
publisher and the content of these web pages is a completely independent effort. Appropriate permissions have been
obtained in writing from the publisher to reference the book as seen in these web pages.<file_sep>/_includes/about.md
QuarksCode is engaged in a variety of Free and Open Source Software (FOSS) projects.
They can be found on [GitHub][github], a repository site for developers. Click on the [Projects][projects] link above
to see all about them.
<div>
<figure class="inlineBlock centerInside">
<img class="quarksImg" src="/images/quarks_proton.svg" />
<figcaption>Proton Valence Quarks</figcaption>
</figure>
<figure class="inlineBlock centerInside">
<img class="quarksImg" src="/images/quarks_neutron.svg" />
<figcaption>Neutron Valence Quarks</figcaption>
</figure>
</div>
## Science, Math and Code
QuarksCode's science, math and code projects are all about having fun and learning science and math - and learning
them with computers. See more via the [Projects][projects] link above.
[projects]: /projects
[github]: https://github.com/aeoril
<file_sep>/static/spiroche/src/spiroche.js
/**
* Created by Scott on 8/24/14.
*/
(function() {
'use strict';
var LINE_LENGTH = 200,
MINIMUM_LINE_SEPARATION = 6,
ANGLE_DIVISOR = 300,
BLACK='rgb(0, 0, 0)',
GRAY = 'rgb(128, 128, 128)',//'rgb(100, 100, 100)',
FONT = 'normal 48pt "Droid Sans", sans-serif',
INSTRUCTIONS = 'Drag pointer or finger here to draw',
length,
separation,
divisor,
color,
sizeElem,
isSizable = false,
menuClearElem,
menuResetElem,
clearElem,
resetElem,
lengthElem,
separationElem,
divisorElem,
colorElem,
canvasElem,
context,
mouseDownPos,
mousePos = null,
prevMousePos,
mouseIsDown = false,
isClean = true,
startingPointAngle;
function calcDistance(point1, point2) {
var deltaX = point2.x - point1.x,
deltaY = point2.y - point1.y;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
}
function calcMousePos(e, element, isTouch) {
var top = 0,
left = 0,
mousePos = {},
canvasScale = canvasElem.clientWidth / canvasElem.width;
if (isTouch) {
mousePos.x = (e.targetTouches[0].pageX - element.offsetLeft) / canvasScale;
mousePos.y = (e.targetTouches[0].pageY - element.offsetTop) / canvasScale;
return mousePos;
}
// get canvas position
while (element.tagName != 'BODY') {
top += element.offsetTop;
left += element.offsetLeft;
element = element.offsetParent;
}
// return relative mouse position
mousePos.x = (e.clientX - left + window.pageXOffset) / canvasScale;
mousePos.y = (e.clientY - top + window.pageYOffset) / canvasScale;
return mousePos;
}
function fromPolar(mag, angle) {
return {x: Math.cos(angle) * mag, y: Math.sin(angle) * mag};
}
function calcPoints(stationaryPoint, point, lineLength) {
var radius = calcDistance(stationaryPoint, point),
angle = Math.PI * (radius / divisor),
point1 = fromPolar(lineLength, angle),
point2 = fromPolar(lineLength, angle + Math.PI);
return {point1: {x: point.x + point1.x, y: point.y + point1.y},
point2: {x: point.x + point2.x, y: point.y + point2.y}};
}
function drawInstructions() {
if (isSizable) {
return;
}
context.save();
context.fillStyle = GRAY;
context.font = FONT;
context.fillText(INSTRUCTIONS, (canvasElem.width - context.measureText(INSTRUCTIONS).width) / 2,
canvasElem.height / 2);
context.restore();
}
function size() {
if (isSizable) {
isSizable = false;
if (isClean) {
drawInstructions();
}
sizeElem.value = 'Size';
} else {
isSizable = true;
mouseIsDown = false;
if (isClean) {
context.clearRect(0, 0, canvasElem.width, canvasElem.height);
}
sizeElem.value = 'Draw';
}
}
function mouseMove(e, isTouch) {
var newMousePos,
points;
if (isSizable) {
return;
}
if (isTouch) {
e.preventDefault();
}
if (!mouseIsDown) {
return;
}
newMousePos = calcMousePos(e, canvasElem, isTouch);
if (calcDistance(newMousePos, mousePos) < separation) {
return;
}
if (mousePos) {
prevMousePos = mousePos;
}
mousePos = newMousePos;
mousePos.x = Math.min(mousePos.x, canvasElem.width);
mousePos.y = Math.min(mousePos.y, canvasElem.height);
if (prevMousePos !== null) {
points = calcPoints(mouseDownPos, mousePos, length);
context.strokeStyle = color;
context.beginPath();
context.moveTo(points.point1.x, points.point1.y);
context.lineTo(points.point2.x, points.point2.y);
context.stroke();
if (isClean) {
isClean = false;
context.clearRect(0, 0, canvasElem.width, canvasElem.height);
}
}
}
function mouseDown(e, isTouch) {
if (isSizable) {
return;
}
mouseDownPos = calcMousePos(e, canvasElem, isTouch);
mouseIsDown = true;
mousePos = mouseDownPos;
startingPointAngle = 0;
if (isTouch) {
e.preventDefault();
}
}
function mouseUp(e, isTouch) {
if (isSizable) {
return;
}
mouseIsDown = false;
if (isTouch) {
e.preventDefault();
}
}
function clear() {
isClean = true;
context.clearRect(0, 0, canvasElem.width, canvasElem.height);
drawInstructions();
}
function change() {
var value = Math.max(this.value, this.min);
value = Math.min(value, this.max);
switch(this.id) {
case 'length':
lengthElem.value = value;
length = value;
break;
case 'separation':
separationElem.value = value;
separation = value;
break;
case 'divisor':
divisorElem.value = value;
divisor = value;
break;
default:
break;
}
}
function colorInput() {
color = colorElem.value;
}
function reset() {
lengthElem.value = LINE_LENGTH;
separationElem.value = MINIMUM_LINE_SEPARATION;
divisorElem.value = ANGLE_DIVISOR;
colorElem.value = BLACK;
change.call(lengthElem);
change.call(separationElem);
change.call(divisorElem);
colorInput();
}
window.addEventListener('load', function () {
sizeElem = document.getElementById('size');
menuClearElem = document.getElementById('menuClear');
menuResetElem = document.getElementById('menuReset');
clearElem = document.getElementById('clear');
resetElem = document.getElementById('reset');
lengthElem = document.getElementById('length');
separationElem = document.getElementById('separation');
divisorElem = document.getElementById('divisor');
menuClearElem.addEventListener('click', clear, false);
menuResetElem.addEventListener('click', reset, false);
colorElem = document.getElementById('color');
canvasElem = document.getElementById('canvas');
context = canvasElem.getContext('2d');
drawInstructions();
reset();
sizeElem.addEventListener('click', size, false);
clearElem.addEventListener('click', clear, false);
resetElem.addEventListener('click', reset, false);
lengthElem.addEventListener('change', change, false);
separationElem.addEventListener('change', change, false);
divisorElem.addEventListener('change', change, false);
colorElem.addEventListener('change', colorInput, false);
canvasElem.addEventListener('mousedown', function(e) { mouseDown(e, false); }, false);
canvasElem.addEventListener('mousemove', function(e) { mouseMove(e, false); }, false);
canvasElem.addEventListener('mouseup', function(e) { mouseUp(e, false); }, false);
canvasElem.addEventListener('mouseleave', function(e) { mouseUp(e, false); }, false);
canvasElem.addEventListener('touchstart', function(e) { mouseDown(e, true); }, false);
canvasElem.addEventListener('touchmove', function(e) { mouseMove(e, true); }, false);
canvasElem.addEventListener('touchend', function (e) { mouseUp(e, true); }, false);
}, false);
}());<file_sep>/static/hallidayResnick/2-3/mathBasics.js
// Copyright © 2014 QuarksCode. MIT License - see http://opensource.org/licenses/MIT or LICENSE.md file
// Original Author: aeoril
//
// BasicShapes.js - 1 motion: displacement and time interactive lesson
var mathBasics = {
calcDistance: function(point1, point2) {
'use strict';
var deltaX = point2.x - point1.x,
deltaY = point2.y - point1.y;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
}
};<file_sep>/_posts/2014-09-25-spiroche-spiral-action-spider-web-graphics-fun.md
---
layout: post
navhilite: blog
title: "Spiroche Spiral Action Spider Web Graphics Fun"
desc: "Make fun and colorful spider-webby graphics"
date: 2014-09-25 12:34:56
categories: javascript
image: spiroche.png
img-width: 308px
img-height: 96px
---
This is a fun, interactive graphics web page implemented using HTML5, CSS3 and JavaScript. Draw multi-colored
spider-webby graphics using tunable spiral action.
### Link to Spiroche Web Page
Click [here][spiroche] or on the image below to view and play with the web page.
### Example Picture
<a href="/static/spiroche/src/spiroche.html">
<img style="width: 920px;" src="/images/spiroche/spiroche.png" alt="Spiroche Screenshot" />
</a>
<br>
If you want to look at the source code, please find it on GitHub [here][source]
Happy Coding!
[spiroche]: /static/spiroche/src/spiroche.html
[source]: https://github.com/aeoril/spiroche/tree/master/src
<file_sep>/static/logServer/log.php
<h3>Thank you! Your data has been logged!</h3>
<?php
switch ($_SERVER["HTTP_ORIGIN"]) {
case "http://aeoril.com": case "https://aeoril.com":
header("Access-Control-Allow-Origin: ".$_SERVER["HTTP_ORIGIN"]);
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: Content-Type");
break;
}
function dateStr($dateFmt = null, $timeZone = null) {
if (is_null($dateFmt)) {
$dateFmt = DATE_ISO8601;
}
if (!is_null($timeZone)) {
date_default_timezone_set($timeZone);
} else {
date_default_timezone_set("UTC");
}
$dateStr = date($dateFmt);
if ($dateStr) {
return $dateStr;
} else {
return "";
}
}
function getLogEntry($logData, $logKeys, $fmtStrs,
$dateFmt, $timeZone, $maxEntrySize) {
$logEntry = dateStr($dateFmt, $timeZone) . ": New Log Entry:";
$logEntry = $logEntry . "\r\n" . $logData . "\r\n";
/*
foreach ($logKeys as $key) {
if (isset($logData[$key])) {
$logEntry = $logEntry . $fmtStrs[$key] . $logData[$key];
} else {
return FALSE;
}
}
$logEntry = $logEntry . "\r\n";
*/
$logEntryLen = strLen($logEntry);
if ($logEntryLen > 0 && $logEntryLen <= $maxEntrySize) {
return $logEntry;
} else {
return FALSE;
}
}
function freeLogFile($logFileHandle) {
flock($logFileHandle, LOCK_UN);
fclose($logFileHandle);
}
function prepareLogFile($logFileName, $maxLogFileSize, $trimSize) {
function trimLogFile($logFileHandle, $logFileSize,
$maxLogFileSize, $trimSize) {
$actualTrimSize = $logFileSize - $maxLogFileSize
+ $trimSize;
if (fseek($logFileHandle, $actualTrimSize, SEEK_SET) != 0) {
return FALSE;
}
$dataStr = fread($logFileHandle,
$logFileSize - $actualTrimSize);
if ($dataStr == FALSE) {
return FALSE;
}
if (!ftruncate($logFileHandle, 0)) {
return FALSE;
}
if (fseek($logFileHandle, 0, SEEK_SET) != 0) {
return FALSE;
}
if (!fwrite($logFileHandle, $dataStr)) {
return FALSE;
}
return TRUE;
}
$logFileHandle = fopen($logFileName, "c+");
if ($logFileHandle == FALSE) {
return FALSE;
}
if (flock($logFileHandle, LOCK_EX) == FALSE) {
fclose($logFileHandle);
return FALSE;
}
if (fseek($logFileHandle, 0, SEEK_END) != 0) {
freeLogFile($logFileHandle);
return FALSE;
}
$fStats = fstat($logFileHandle);
if ($fStats == FALSE) {
freeLogFile($logFileHandle);
return FALSE;
}
$logFileSize = $fStats["size"];
if ($logFileSize >= $maxLogFileSize) {
if (trimLogFile($logFileHandle, $logFileSize,
$maxLogFileSize, $trimSize) == FALSE) {
freeLogFile($logFileHandle);
return FALSE;
}
}
return $logFileHandle;
}
function logRequest($logData) {
$logDataKeys = array("type", "sev", "msg");
$fmtStrs = array("type" => " Type: ",
"sev" => " Severity: ", "msg" => "\r\n");
$dateFmt = DATE_ISO8601;
// $timeZone = "America/Chicago";
$timeZone = "UTC";
// $timeZone = null;
$logFileName = dateStr("Ym-", $timeZone) . "errorLog.txt";
$oneKB = 1024;
$maxLogFileSize = $oneKB * $oneKB;//$oneKB * $oneKB * $oneKB;
$trimSize = 100 * $oneKB;
$maxEntrySize = 8 * $oneKB;
$logEntry = getLogEntry($logData, $logDataKeys, $fmtStrs,
$dateFmt, $timeZone, $maxEntrySize);
if ($logEntry == FALSE) {
return FALSE;
}
$logFileHandle = prepareLogFile(
$logFileName, $maxLogFileSize, $trimSize);
if ($logFileHandle != FALSE) {
fwrite($logFileHandle, $logEntry);
freeLogFile($logFileHandle);
}
return FALSE;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//var_dump($_POST);
//var_export(file_get_contents("php://input"));
//print "\r\n";
//var_dump(json_decode(file_get_contents("php://input"), true));
//logRequest($_POST);
//logRequest(json_decode(file_get_contents("php://input"), true));
logRequest(file_get_contents("php://input"), true);
} else {
if ($_SERVER["REQUEST_METHOD"] == "GET") {
logRequest($_SERVER["QUERY_STRING"], true);
}
}<file_sep>/_posts/2014-03-09-harmonia-2d-newtonian-motion-animation.md
---
layout: post
navhilite: blog
title: "Harmonia 2D Newtonian Motion Animation"
desc: "Fun with lots of accelerating and bouncing baseballs"
date: 2014-03-09 18:14:50
categories: physics
image: harmonia.png
img-width: 256px
img-height: 96px
---
<div class="note">
<table>
<tr>
<td>
NOTE:
</td>
<td>
Although the simulation works reasonably well, the text portion
of this post is out of date. Enjoy the visuals of the simulation,
but please disregard the discussion until I update it and remove
this note.
</td>
</tr>
</table>
</div>
Here is the Harmonia animation based on my Vector2D and Motion2D math and physics library code:
<div id="container" style="width: 920px; text-align: center;"></div>
<script src="/static/harmonia/Vector2D.js"></script>
<script src="/static/harmonia/Motion2D.js"></script>
<script src="/static/harmonia/harmonia.js"></script>
It features use of real physics from the [Motion2D][motion2d] object from my [PhysicsLibrary][physics-library] project.
Motion2D in turn relies on the [Vector2D][vector2d] object from my [MathLibrary][math-library] project. See the source
code for Harmonia [here][harmonia].
All the code for Harmonia is pure JavaScript, including the libraries.
Harmonia and the libraries it relies on use a JavaScript *Object Based* (OB) style. I borrowed this style from an
excellent article series by <NAME> you can view [here][kyleSimpson].
I changed it somewhat per the suggestions of [<NAME>][ljharb] who is known by the nick *ljharb* on and
<NAME> who is known by the nick *ImBcmDth* both of whom frequent the ##javascript channel on
[freenode.net][freenode]. Thanks to both of you, and the rest of the crew on ##javascript for all the continuing help.
### The Code
And now some code. The main simulation that runs the animation is called *Universe*. It is in two parts both of which
are just standard JavaScript *object* variables. The first is very simple:
{% highlight js %}
var Universe = {
create: function (containerElem, width, height) {
return Object.create(UniverseProto).init(containerElem, width, height)
}
};
{% endhighlight %}
It contains a single *property* called *create* that is passed the *arguments* necessary to build new objects that
contain state data and "inherit" the *prototype* properties necessary to implement the bulk of the processing on that
state from the object variable called *UniverseProto* (see below).
*UniverseProto* is passed as the *prototype object* to the *Object.create()* method. *Object.create()* is an ES5
addition to JavaScript that simply returns an new object whose *prototype* object property points to the object passed
in as its lone argument, or *null* if given the argument *null*.
Once *Object.create()* creates our new object with the *prototype* property pointing to *UniverseProto*, we I chain
a call the *init()* *function* that is a *property* of the *UniverseProto* prototype object. I pass in the necessary
arguments to it and it does pretty much the same functionality as a constructor would do in legacy code that
uses them instead of *Object.create()*.
There are many benefits to doing it this way versus the legacy way of using a *constructor* function with *new*. If
you wish to understand why better than I can explain, please read <NAME>'s article I link to above.
Although in my libraries there is a lot of functionality included in the first object of the pair that contains
the *.create()* function, there is no need here, so it only contains the one function.
#### The Prototype Code
Here is the first part of the code from *UniverseProto*:
{% highlight js %}
var UniverseProto = {
init: function (containerElem, width, height) {
'use strict';
var i,
k,
NUM_BALL_4GROUPS = 40,
resize = this.resize.bind(this, true);
this.status = 'started';
// ... more init code here
return this;
},
updateStatus: function (status, name) {
'use strict';
// ... code here
},
draw: function () {
'use strict';
this.ctx.clearRect(0, 0, this.canvasElem.width, this.canvasElem.height);
this.figures.forEach(function (figure) {
figure.draw();
});
this.ctx.fillText(this.framesPerSec, (this.canvasElem.width - this.measuredFramesPerSec.width) / 2, 10);
},
// ... more prototype methods here
}
{% endhighlight %}
The *.init()* function adds state variables to the object created by *Universe.create()* and does all the necessary
setup to get the *Universe* ready to run (explode, as in "Big Bang".)
Many more properties are defined on the prototype object that become available through the *prototype chain* to the
object variable created by *Universe.create()*, like *.updateStatus()* and *.draw()*.
Notice the following line in the code above
{% highlight js %}
Universe.prototype.draw = function () {
this.ctx.clearRect(0, 0, this.canvasElem.width, this.canvasElem.height);
this.figures.forEach(function (figure) {
figure.draw();
});
this.ctx.fillText(this.framesPerSec, (this.canvasElem.width - this.measuredFramesPerSec.width) / 2, 10);
};
{% endhighlight %}
Note the line above:
{% highlight js %}
figure.draw();
{% endhighlight %}
*figure* is itself an *instance* of another class called *Figures* that is used to encapsulate the state and
functionality of the baseball figures you see bouncing around in the simulation:
{% highlight js %}
function Figure(src, motion2D, universe) {
this.MAX_SPEED = 90;
this.src = src;
this.img = document.createElement('img');
this.motion2D = motion2D;
this.universe = universe;
// ... rest of instance variable declarations (internal state data) and instance setup code
}
{% endhighlight %}
The state of the Universe and its various components are all self contained, or "encapsulated" in OOP speak,
within the various *class instances* that make up the animation, including objects instantiated from the library
classes *Vector2D* and *Motion2D*.
Since all these things are set up before hand and ready to trigger, it takes actually only two "user code" lines to
instantiate and start a simulation:
{% highlight js %}
var universe = new Universe(document.getElementById('container'), 800, 300);
universe.explode();
{% endhighlight %}
The first line declares a *variable* called *universe* and assigns it to the *instance object* returned by
*new Universe( ... )*. The second "explodes" the universe (starts the universe with a Big Bang ....)
Multiple instances of the animation could easily be instantiated and displayed on different parts of the web page.
Interactive capabilities such as universe.pause(), universe.continue(), universe.stop(), universe.reset(), etc.
will all be added and interacted with by the web page user via buttons similar to video controls on a video website.
Other controls to change acceleration, add or remove balls, etc. will also be added. Record and rewind/fast forward
could also easily be added.
Note how the first argument passed into Universe is the containing *element*, which in this case is a <div>
element with id "container" Any suitable *element* could be used for flexibility, for instance, the document.body
element or a <td> element in an *HTML* *table*.
Happy coding!.
[motion2d]: https://github.com/aeoril/PhysicsLibrary/blob/master/src/Motion2D.js
[physics-library]: https://github.com/aeoril/PhysicsLibrary
[vector2d]: https://github.com/aeoril/MathLibrary/blob/master/src/Vector2D.js
[math-library]: https://github.com/aeoril/MathLibrary
[kylesimpson]: http://davidwalsh.name/javascript-objects
[ljharb]: https://github.com/ljharb
[ImBcmDth]: https://github.com/ImBcmDth
[freenode]: http://freenode.net/
[harmonia]: https://github.com/aeoril/PhysicsLibrary/blob/master/test/custom/harmonia/harmonia.js
<file_sep>/static/JSLearning/src/changeIFrame/myFrame.js
window.addEventListener('load', function () {
'use strict';
var buttonElem = document.getElementById('button'),
myFrameElem = window.parent.document.getElementById('myFrame'),
width = 100,
height = 100;
buttonElem.addEventListener('click', function() {
myFrameElem.width = width + 'px';
myFrameElem.height = height + 'px';
width += 10;
height += 10;
}, false);
}, false);
<file_sep>/_posts/2014-12-27-how-to-exit-the-node-console-repl.md
---
layout: post
navhilite: blog
title: "How to Exit the Node Console (REPL)"
desc: "Seems so simple, doesn't it?"
date: 2014-12-27 12:34:56
categories: node
image: nodejs_exit.png
img-width: 263px
---
To exit the node.js console (REPL), use the [process.exit()][processExit] function call:
What it looks like in Windows:
{% highlight text %}
C:\user\username>node
> console.log('Hello, World!');
Hello, World!
undefined
> process.exit();
C:\user\username>
{% endhighlight %}
What it looks like in Linux:
{% highlight text %}
username@hostname:~/$ node
> console.log('Hello, World!');
Hello, World!
undefined
> process.exit()
username@hostname:~/$
{% endhighlight %}
Happy Coding!
[processExit]: http://nodejs.org/api/process.html#process_event_exit
<file_sep>/_posts/2015-04-26-javlin-pure-vector-library.md
---
layout: post
navhilite: blog
title: "javlin-pure N-dimensional Vector Library for Node and NPM"
desc: "Pure, stateless and modular Javascript n-dimensional vector library for Node.js"
date: 2015-04-26 12:34:56
categories: math
image: vector.gif
---
### javlin-pure (Just Another Vector Library in Node - Pure) is here!
This project allows manipulation of n-dimensional vectors using pure, stateless functions that take simple arrays
as arguments and returns new arrays.
Written in Javascript and implemented as Node modules. Featuring unit testing using [Tape][tape] (TAP output).
Easily usable in regular browsers with [Browserify][browserify].
Packaged for NPM, it is hosted on both GitHub and the NPM website:
* [GitHub project page][github]
* [NPM project page][npm]
Happy coding!
[browserify]: https://www.npmjs.com/package/browserify
[tape]: https://www.npmjs.com/package/tape
[github]: https://github.com/aeoril/javlin-pure
[npm]: https://www.npmjs.com/package/javlin-pure
<file_sep>/_includes/hallidayResnick-2-3.md
### <a name="overview"></a>Interactive Tutorial - Average Velocity and Speed
This is a simple interactive tutorial that discusses average velocity and average speed
(in one dimension.) The concepts are taken directly out of Chapter 2 Section 3 (2-3) of
[The Fundamentals of Physics Extended - Fifth Edition][book] by Halliday, Resnick and Walker
(© 1997 <NAME> & Sons, Inc - ISBN: 0-471-10559-7)
### <a name="contents"></a>Contents
* [Interactive Tutorial - Average Velocity and Speed][overview]
* [Contents][contents]
* [Try It!][try]
* [Thanks][thanks]
### <a name="try"></a>Try it!
The graph determines the motion of the bunny when you hit the "Animate!" button. The vertical axis is the \\(x\\)
position of the bunny. The horizontal axis is time \\(t\\). Using the pointer, drag the black dots around the graph to,
change the motion of the bunny.
<div class="canvasDiv">
<canvas id="splineCanvas" width="920" height="400"></canvas><br>
<canvas id="splineBackgroundCanvas" width="920" height="400"></canvas>
<form id="form" action="#" method="get">
<span class="nowrap">
<label id="t1Label" for="t1">t1</label>
<input id="t1" name="t1" type="text" readonly value="-20"/>
</span>
<span class="nowrap">
<label id="x1Label" for="x1">x1</label>
<input id="x1" name="x1" type="text" readonly value="-10"/>
</span>
<span class="nowrap">
<label id="t2Label" for="t2">t2</label>
<input id="t2" name="t2" type="text" readonly value="-8"/>
</span>
<span class="nowrap">
<label id="x2Label" for="x2">x2</label>
<input id="x2" name="x2" type="text" readonly value="10"/>
</span>
<span class="nowrap">
<label id="t3Label" for="t3">t3</label>
<input id="t3" name="t3" type="text" readonly value="8"/>
</span>
<span class="nowrap">
<label id="x3Label" for="x3">x3</label>
<input id="x3" name="x3" type="text" readonly value="-10"/>
</span>
<span class="nowrap">
<label id="t4Label" for="t4">t4</label>
<input id="t4" name="t4" type="text" readonly value="20"/>
</span>
<span class="nowrap">
<label id="x4Label" for="x4">x4</label>
<input id="x4" name="x4" type="text" readonly value="10"/>
</span>
<span class="nowrap">
<label id="tensionLabel" for="tension">tension</label>
<input id="tension" name="tension" type="text" readonly value="50"/>
</span>
<input type="button" id="animate" value="Animate!">
</form>
<br>
<canvas id="bunnyCanvas" height="130" width="920"></canvas><br>
<canvas id="bunnyBackgroundCanvas" height="130" width="920"></canvas>
</div>
<script src="/hallidayResnick/2-3/geometry.js"></script>
<script src="/hallidayResnick/2-3/BasicShapes.js"></script>
<script src="/hallidayResnick/2-3/AdvancedShapes.js"></script>
<script src="/hallidayResnick/2-3/Knots.js"></script>
<script src="/hallidayResnick/2-3/MultiSegmentSpline.js"></script>
<script src="/hallidayResnick/2-3/BunnyBackground.js"></script>
<script src="/hallidayResnick/2-3/hallidayResnick-2-3.js"></script>
### <a name="thanks"></a>Thanks
Underlying math code for splines by <NAME>:
<a href="http://scaledinnovation.com/analytics/splines/aboutSplines.html">http://scaledinnovation.com/analytics/splines/aboutSplines.html</a><br>
His code is copyrighted with all rights reserved - see his site for details. Thanks, Rob!
[book]: http://www.amazon.com/Fundamentals-Physics-Extended-David-Halliday/dp/0471105597/ref=sr_1_8?s=books&ie=UTF8&qid=1396899157&sr=1-8&keywords=halliday+resnick+walker+fundamentals+of+physics+5th+edition
[overview]: #overview
[contents]: #contents
[try]: #try
[thanks]: #thanks
<file_sep>/_includes/hallidayResnick.md
### First Year Physics Based on Halliday, Resnick and Walker
This is a series of interactive tutorials, simulations and discussions of the code behind them
based on [Fundamentals of Physics Extended Fifth Edition][book] by Halliday, Resnick and Walker. These
web pages are intended for first year college physics, physical science and engineering students and are an independently
created adjunct to the book that provide interactive methods to help understand the various concepts in the book more
in-depth than can be done by reading alone. Additionally, computer science students can benefit from the in-depth
discussions of how the science and math are coded.
#### Chapter 2 - Motion Along a Straight Line
* [Chapter 2 section 2 - Position and Displacement][2-2]
* [Chapter 2 section 3 - Average Velocity and Speed][2-3]
[book]: http://www.amazon.com/Fundamentals-Physics-Extended-David-Halliday/dp/0471105597/ref=sr_1_8?s=books&ie=UTF8&qid=1396899157&sr=1-8&keywords=halliday+resnick+walker+fundamentals+of+physics+5th+edition
[2-2]: /hallidayResnick/2-2
[2-3]: /hallidayResnick/2-3
<file_sep>/static/harmonia/harmonia.js
// Copyright © 2014 QuarksCode. MIT License - see http://opensource.org/licenses/MIT or LICENSE.md file
// Original Author: aeoril
//
// harmonia.js - 2D Newtonian motion animation
var Figure = {
create: function(src, motion2D, universe) {
return Object.create(FigureProto).init(src, motion2D, universe);
}
};
var FigureProto = {
init: function(src, motion2D, universe) {
'use strict';
this.MAX_SPEED = 90;
this.src = src;
this.img = document.createElement('img');
this.motion2D = motion2D;
this.universe = universe;
this.edgePos = Vector2D.create(0, 0);
this.bounceVel0DiagMul = Vector2D.create(1, 1);
this.bounceAccDiagMul = Vector2D.create(1, 1);
this.status = 'loading';
this.img.onload = function() {
this.status = 'ready';
if (universe.statusUpdateCallback) {
universe.statusUpdateCallback(this.status, this.src);
}
}.bind(this);
this.img.onerror = function() {
this.status = 'error';
if (universe.statusUpdateCallback) {
universe.statusUpdateCallback(this.status, this.src);
}
}.bind(this);
this.img.src = src;
return this;
},
checkSide: function() {
'use strict';
if (this.motion2D.pos().x <= 0) {
this.edgePos.x = 0;
this.bounceVel0DiagMul.x = -1;
} else if (this.motion2D.pos().x + this.img.width >= this.universe.canvasElem.width) {
this.edgePos.x = this.universe.canvasElem.width - this.img.width;
this.bounceVel0DiagMul.x = -1;
} else {
this.edgePos.x = this.motion2D.pos().x;
this.bounceVel0DiagMul.x = 1;
}
if (this.motion2D.pos().y <= 0) {
this.edgePos.y = 0;
this.bounceVel0DiagMul.y = -1;
} else if (this.motion2D.pos().y + this.img.height >= this.universe.canvasElem.height) {
this.edgePos.y = this.universe.canvasElem.height - this.img.height;
this.bounceVel0DiagMul.y = -1;
} else {
this.edgePos.y = this.motion2D.pos().y;
this.bounceVel0DiagMul.y = 1;
}
},
draw: function() {
'use strict';
if (!(this.status === 'ready')) {
console.log('Error: Could not draw image ' + this.src + ': status was: ' + this.status);
return;
}
if (this.motion2D.vel().mag() >= this.MAX_SPEED && this.bounceAccDiagMul.x === 1) {
this.bounceAccDiagMul.x = -1;
this.bounceAccDiagMul.y = -1;
this.motion2D.pos().copy(this.motion2D.pos0);
this.motion2D.vel().copy(this.motion2D.vel0);
this.motion2D.acc.diagMul(this.bounceAccDiagMul);
this.motion2D.accT0 = this.universe.time;
//this.motion2D.acc.fromPolar(this.motion2D.acc.mag(), this.motion2D.vel().angle);
} else if (this.motion2D.vel().angle().toFixed(7) !== this.motion2D.vel0.angle().toFixed(7) && this.bounceAccDiagMul.x === -1) {
this.motion2D.pos().copy(this.motion2D.pos0);
this.motion2D.vel().copy(this.motion2D.vel0);
this.motion2D.acc.fromPolar(this.motion2D.acc.mag(), this.motion2D.vel().angle());
this.motion2D.accT0 = this.universe.time;
this.bounceAccDiagMul.x = 1;
this.bounceAccDiagMul.y = 1;
}
this.checkSide();
if (this.bounceVel0DiagMul.x < 0 || this.bounceVel0DiagMul.y < 0) {
this.motion2D.bounce(this.bounceVel0DiagMul, this.edgePos, true, this.bounceAccDiagMul);
}
this.universe.ctx.save();
this.universe.ctx.translate(this.motion2D.pos().x, this.motion2D.pos().y);
this.universe.ctx.drawImage(this.img, 0, 0);
this.universe.ctx.restore();
}
};
var Universe = {
create: function(containerElem, width, height) {
return Object.create(UniverseProto).init(containerElem, width, height)
}
};
var UniverseProto = {
init: function(containerElem, width, height) {
'use strict';
var i,
k,
NUM_BALL_4GROUPS = 40,
resize = this.resize.bind(this, true);
this.status = 'started';
this.statusUpdateCallback = this.updateStatus;
this.statusCallback = null;
this.figureCount = 0;
this.containerElem = containerElem;
this.width = width;
this.height = height;
this.canvasElem = document.createElement('canvas');
this.measureFramesOn = 20;
this.DEL_T_SCALE = .003;
this.ANGLE = Math.PI / 8;
this.VEL0 = Vector2D.fromPolar(1, this.ANGLE).norm();
this.ACC = Vector2D.fromPolar(1, this.ANGLE);
this.figures = [];
this.requestID = null;
this.boundAnimate = this.animate.bind(this);
this.containerElem.appendChild(this.canvasElem);
this.ctx = this.canvasElem.getContext('2d');
this.resize(false);
for (i = 0, k = 8; i < NUM_BALL_4GROUPS; i++, k /= 1.1) {
this.figures.push(Figure.create('/images/harmonia/baseball.png',
Motion2D.create(Vector2D.create(1, 1),
this.VEL0, Vector2D.scale(this.ACC, k), this, 0), this));
this.figureCount++;
this.figures.push(Figure.create('/images/harmonia/baseball.png',
Motion2D.create(Vector2D.create(1, this.canvasElem.height),
this.VEL0, Vector2D.scale(this.ACC, k), this, 0), this));
this.figureCount++;
this.figures.push(Figure.create('/images/harmonia/baseball.png',
Motion2D.create(Vector2D.create(this.canvasElem.width, 1),
this.VEL0, this.ACC.clone().scale(k), this, 0), this));
this.figureCount++;
this.figures.push(Figure.create('/images/harmonia/baseball.png',
Motion2D.create(Vector2D.create(this.canvasElem.width, this.canvasElem.height),
this.VEL0, Vector2D.scale(this.ACC, k), this, 0), this));
this.figureCount++;
}
if (this.status !== 'error') {
this.status = 'loading';
}
window.addEventListener('resize', resize, false);
return this;
},
updateStatus: function(status, src) {
'use strict';
if (status === 'error') {
alert('Unable to configure the universe: Error loading figure: ' + src);
this.status = 'error';
return;
}
this.figureCount--;
if (this.figureCount <= 0 && this.status === 'loading') {
this.status = 'ready';
if (this.statusCallback) {
this.statusCallback();
}
}
},
draw: function() {
'use strict';
this.ctx.clearRect(0, 0, this.canvasElem.width, this.canvasElem.height);
this.figures.forEach(function(figure) {
figure.draw();
});
this.ctx.fillText(this.framesPerSec, (this.canvasElem.width - this.measuredFramesPerSec.width) / 2, 10);
},
animate: function(timeStamp) {
'use strict';
var deltaT;
if (this.prevTimeStamp == null) {
this.prevTimeStamp = timeStamp;
this.requestID = window.requestAnimationFrame(this.boundAnimate);
return;
}
deltaT = timeStamp - this.prevTimeStamp;
this.prevTimeStamp = timeStamp;
this.delFramesT += deltaT;
if (!(++this.frames % this.measureFramesOn)) {
this.framesPerSec = ((this.measureFramesOn / this.delFramesT) * 1000).toFixed(2);
this.measuredFramesPerSec = this.ctx.measureText(this.framesPerSec);
this.delFramesT = 0;
}
this.time += this.DEL_T_SCALE * deltaT;
this.draw();
this.requestID = window.requestAnimationFrame(this.boundAnimate);
},
resize: function(doDraw) {
'use strict';
this.canvasElem.width = this.width > 0 ? this.width : this.containerElem.clientWidth;
this.canvasElem.height = this.height > 0 ? this.height : this.containerElem.clientHeight;
if (doDraw) {
this.draw();
}
},
explodeNow: function() {
'use strict';
this.time = 0;
this.frames = 0;
this.framesPerSec = '0.00';
this.measuredFramesPerSec = 0;
this.delFramesT = 0;
this.prevTimeStamp = null;
this.requestID = window.requestAnimationFrame(this.boundAnimate);
},
explode: function() {
'use strict';
if (this.status === 'error') {
return;
}
this.statusCallback = this.explodeNow.bind(this);
if (this.status === 'ready') {
this.explodeNow();
}
},
stop: function() {
'use strict';
clearInterval(this.requestID);
}
};
window.addEventListener('load', function () {
'use strict';
var universe = Universe.create(document.getElementById('container'), 800, 300);
universe.explode();
}, false);<file_sep>/static/delegates/delegatesConstructor.js
function Vector2D (x, y) {
this.x = x;
this.y = y;
}
Vector2D.add = function(vec1, vec2) {
return new Vector2D(vec1.x + vec2.x, vec1.y + vec2.y);
};
Vector2D.prototype.add = function(vec) {
this.x += vec.x;
this.y += vec.y;
};
var vec1 = new Vector2D(3, 4), // vec1 -> [3, 4]
vec2 = new Vector2D(6, 8); // vec2 -> [6, 8]
vec1.add(vec2); // vec1 -> [9, 12]<file_sep>/_includes/projects.md
### Learning
Here are some links to my learning projects
- [Physics Tutorials and Simulations based on Halliday, Resnick and Walker][halliday-resnick]
### Coding
Here are some links to my coding projects
- [All Repositories][all]
- [javlin-pure Vector Library][javlin-pure]
- [simpleMotion Newtonian Physics Library][simpleMotion]
- [harmonia][harmonia]
- [Javascript Learning Library][jslearning]
[halliday-resnick]: /hallidayResnick
[all]: https://github.com/aeoril?tab=repositories
[javlin-pure]: https://github.com/aeoril/javlin-pure
[simpleMotion]: https://github.com/aeoril/simpleMotion
[harmonia]: https://github.com/aeoril/PhysicsLibrary/tree/master/test/custom/harmonia
[jslearning]: https://github.com/aeoril/JSLearning<file_sep>/static/harmonia/Motion2D.js
// Copyright © 2014 QuirksCode. MIT License - see http://opensource.org/licenses/MIT and see COPYRIGHT.md
// Original Author: aeoril
//
// Motion2D.js - 2D constant acceleration class
var Motion2D = {
create: function (pos0, vel0, acc, universe, accT0) {
return Object.create(Motion2DProto).init(pos0, vel0, acc, universe, accT0);
},
copy: function (from, to) {
return from.copy(to);
},
pos0: function (motion2D) {
return motion2D.pos0.clone();
},
vel0: function (motion2D) {
return motion2D.vel0.clone();
},
acc: function (motion2D) {
return motion2D.acc.clone();
},
pos: function (motion2D) {
return motion2D.clone().pos.clone();
},
vel: function (motion2D) {
return motion2D.clone().vel.clone();
},
displacement: function (motion2D) {
return motion2D.clone().displacement.clone();
},
angle: function (motion2D) {
return motion2D.clone().angle();
},
bounce: function (motion2D, vel0DiagVec, edgePos, alignAcc, accDiagVec) {
return motion2D.clone().bounce(vel0DiagVec, edgePos, alignAcc, accDiagVec);
}
};
var Motion2DProto = {
init: function (pos0, vel0, acc, universe, accT0) {
this.pos0 = pos0.clone();
this.vel0 = vel0.clone();
this.acc = acc.clone();
this.universe = universe;
this.accT0 = accT0;
this.accT = this.universe.time - this.accT0;
this._pos = pos0.clone();
this._vel = vel0.clone();
this._displacement = Vector2D.create(0, 0);
return this;
},
copy: function (to) {
this.pos0.copy(to.pos0);
this.vel0.copy(to.vel0);
this.acc.copy(to.acc);
to.universe = this.universe; // Reference to external object - copy reference, not object properties
to.accT0 = this.accT0; // Primitive type (not an object)
to.accT = this.accT; // Primitive type (not an object)
this.pos().copy(to._pos);
this.vel().copy(to._vel);
this.displacement().copy(to._displacement);
return to;
},
clone: function () {
return this.copy(Motion2D.create(
Vector2D.create(0, 0),
Vector2D.create(0, 0),
Vector2D.create(0, 0),
0,
0
));
},
calcAccT: function () {
this.accT = this.universe.time - this.accT0;
},
pos: function () {
this.calcAccT();
this._pos.x = this.pos0.x + this.vel0.x * this.accT + 0.5 * this.acc.x * this.accT * this.accT;
this._pos.y = this.pos0.y + this.vel0.y * this.accT + 0.5 * this.acc.y * this.accT * this.accT;
return this._pos;
},
vel: function () {
this.calcAccT();
this._vel.x = this.vel0.x + this.acc.x * this.accT;
this._vel.y = this.vel0.y + this.acc.y * this.accT;
return this._vel;
},
displacement: function () {
return this.pos().copy(this._displacement).sub(this.pos0);
},
angle: function () {
return this.vel().angle();
},
bounce: function (vel0DiagVec, edgePos, alignAcc, accDiagVec) {
edgePos.copy(this.pos0);
this.vel().copy(this.vel0).diagMul(vel0DiagVec);
if (alignAcc) {
this.acc.fromPolar(this.acc.mag(), this.vel0.angle());
}
if (accDiagVec) {
this.acc.diagMul(accDiagVec);
}
this.accT0 = this.universe.time;
}
};<file_sep>/hallidayResnick/index.html
---
layout: default
navhilite: projects
title: QuarksCode | Halliday, Resnick and Walker Interactive
---
<div class="page">
<h1 class="title">Halliday, Resnick and Walker Interactive</h1>
<div class="content">
{% capture page %}
{% include hallidayResnick.md %}
{% endcapture %}
{{ page | markdownify }}
</div>
<div class="content">
{% capture page %}
{% include hallidayResnick-legal.md %}
{% endcapture %}
{{ page | markdownify }}
</div>
</div>
<file_sep>/_includes/hallidayResnick-2-2.md
### <a name="overview"></a>Interactive Tutorial - Position and Displacement
This is a simple interactive tutorial that discusses position, displacement and magnitude of motion along a line
(in one dimension.) The concepts are taken directly out of Chapter 2 Section 2 (2-2) of
[The Fundamentals of Physics Extended - Fifth Edition][book] by Halliday, Resnick and Walker
(© 1997 <NAME> & Sons, Inc - ISBN: 0-471-10559-7)
### <a name="contents"></a>Contents
* [Interactive Tutorial - Position and Displacement][overview]
* [Contents][contents]
* [Instructions for Interactive Tutorial][instructions]
* [Discussion of Math and Physics Concepts][physics-discussion]
* [Try It!][try]
* [Code Discussion][code-discussion]
* [Overview][code-overview]
* [Laying the Groundwork: Separation of Concerns][separation-groundwork]
* [More Groundwork: Immediately Invoked Function Expression (IIFE)][iife-groundwork]
* [My JavaScript Code][my-code]
* [Thanks][thanks]
### <a name="instructions"></a>Instructions for Interactive Tutorial
Enter starting and ending positions (\\(x1\\) and \\(x2\\)) below, figure up the signed displacement (\\(\\Delta x\\))
and the unsigned magnitude and plug those in, then check your answers. If answers are correct, they will be plotted.
Red highlighting means incorrect, green means correct. If you are not sure how to do this, please read the discussion
below.
<div class="canvasDiv">
<canvas id="canvas" height="200" width="920"></canvas><br>
<form id="form" action="#" method="get">
<label id="x1Label" for="x1">Position 1 (x1)</label>
<input id="x1" name="x1" type="text" />
<label id="x2Label" for="x2">Position 2 (x2)</label>
<input id="x2" name="x2" type="text" />
<label id="displacementLabel" for="displacement">Displacement (Δx)</label>
<input id="displacement" name="displacement" type="text" />
<label id="magnitudeLabel" for="magnitude">Magnitude</label>
<input id="magnitude" name="magnitude" type="text" /><br>
<button type="submit">Check Answers</button>
</form>
</div>
<script src="/hallidayResnick/2-2/hallidayResnick-2-2.js"></script>
### <a name="physics-discussion"></a>Discussion of Math and Physics Concepts
To locate an object we can use an axis with an origin, normally indicated by 0, as follows:
<img style="width: 920px;" src="/images/hallidayResnick-2-2/x_axis_annotated.svg" alt="Annotated x-axis" />
<br>
Given two variables \\(x1 = -3\\) and \\(x2 = 5\\) we can locate these variable's positions on this x-axis relative
to the origin \\(0\\) as follows:
<img style="width: 920px;" src="/images/hallidayResnick-2-2/x_axis_annotated_with_x1_x2.svg" alt="Annotated x-axis with x1 and x2" />
<br>
The *displacement* of motion travelled from \\(x1\\) to \\(x2\\), or \\(\\Delta x\\) (pronounced "delta x") is
calculated as follows:
$$ \Delta x = x2 - x1 $$
This *displacement* has both direction (it can be either positive or negative along the x-axis) and *magnitude*. The
*magnitude* is the same value calculated as above but is always positive, never negative. It represents the *distance*
travelled without the *direction* associated with it.
*Displacement* is a [vector][vector] and *magnitude* is a [scalar][scalar].
Here is everything together. Note that the *displacement* has an arrow to indicate either positive or negative
direction and in this case the motion is *positive* from left to right with the arrow pointing to the right:
<img style="width: 920px;" src="/images/hallidayResnick-2-2/x_axis_annotated_with_x1_x2_delx_mag.svg" alt="Annotated x-axis with x1 and x2" />
<br>
To illustrate that the *displacement* can be negative, below we switch out \\(x1\\) and \\(x2\\) so that now
\\(x1 = 5\\) and \\(x2 = -3\\). We will now travel from the right to the left in the negative direction. Note that
the *magnitude* is still positive:
<img style="width: 920px;" src="/images/hallidayResnick-2-2/x_axis_annotated_with_x1_x2_delx_mag_switched.svg" alt="Annotated x-axis with x1 and x2" />
<br>
#### <a name="try"></a>Try it!
If you did not try to run the interactive tutorial above, try it now. Try putting the values in the discussion in
and see that the tutorial works with them. Try the values in *Checkpoint 1* in the book using the interactive tutorial
above to see how they look graphed. Make sure you understand the concepts presented in the book in-depth.
### <a name="code-discussion"></a>Code Discussion
You will find the full source code for this project on Github [here][github].
#### <a name="code-overview"></a>Overview
I use three languages to implement this tutorial: JavaScript for the *behavior* (making things happen), HTML for the
*content* (putting elements on the web page) and CSS for the *styling* (how things look):
* The JavaScript is based on the [ECMAScript 5 specification][es5]
* The HTML is based on the [HTML5 specification][html5]
* The CSS is based on the [W3C CSS Specs][w3c-css]
Here are some great resources that may be more "friendly" to use from the Mozilla Developer Network (MDN):
* The MDN JavaScript page is [here][mdn-javascript]
* The MDN HTML page is [here][mdn-html]
* The MDN CSS page is [here][mdn-css]
The above links are very good and you might consider bookmarking them and using them ongoing.
#### <a name="separation-groundwork"></a>Laying the Groundwork: Separation of Concerns
I carefully do not mix any JavaScript, HTML or CSS together. That is, JavaScript code is in its own separate file,
markup (HTML) is in its own separate file, and CSS styling in its own separate file. This separation of concerns is
very important for a large variety of reasons.
Discussions of those reasons and other good stuff:
* On a W3C Wiki about [why separate][w3c-separate]
* On this outdated but still good link to [The Future of the Web presentation][the-future-of-the-web]
* On this best practices link on [Cats Who Code][cats-who-code]
If you look at the code on [github][github], I *never* mix code like so:
{% highlight html linenos %}
<head>
<!-- various HTML code here -->
</head>
<body>
<form id="form" action="#" style="margin-left: 40px;" method="get"
onsubmit="checkAnswers(event);">
<!-- more HTML code here -->
</form>
<script language="javascript" type="text/javascript">
function checkAnswers(event) {
// JavaScript code here
}
</script>
</body>
{% endhighlight %}
Notice in line numbers **5-6** I have included a *style* attribute that mixes CSS directly in with the HTML. I have
also included the *onsubmit* attribute which has JavaScript code directly mixed in with the HTML. Also, in lines
**12-16** I have included direct JavaScript code mixed in with the HTML code. It is not a link, but direct JavaScript.
If you have read the above links, you will know that this is a bad idea for a variety of reasons. Instead, do the
following - first the HTML:
{% highlight html linenos %}
<head>
<!-- various HTML code here -->
<link href="hallidayResnick-2-2.css" rel="stylesheet" type="text/css">
</head>
<body>
<form id="form" action="#" method="get">
<!-- more HTML code here -->
</form>
<script src="hallidayResnick-2-2.js"></script>
</body>
{% endhighlight %}
Notice how on line **7** there is no longer any mixed in CSS or JavaScript - it is clean. Also, there is now on line
**3** in the header a link that brings in external CSS (below) from a separate file and on line **12** a link that
brings in external JavaScript from a separate file.
Now, here is part of the JavaScript:
{% highlight js linenos %}
function checkAnswers(event) {
// JavaScript code here
}
document.getElementById('form').addEventListener('submit', checkAnswers, false);
{% endhighlight %}
Now, we have only JavaScript in the appropriate file. We declare our function, then attach it as an *event listener*
to the form in line 5 instead of using the *onsubmit* attribute.
Now, here is the separate CSS to style the form:
{% highlight css %}
form {
margin-left: 40px;
}
{% endhighlight %}
Once again, we have only CSS in its own file. You can easily see that if the CSS gets very big, it is much easier to
handle in this format.
This may seem like a lot of trouble, but these are trivial examples. When the web page becomes more sizable, as does
the code on [GitHub][github], the utility of doing it this way becomes apparent.
#### <a name="iife-groundwork"></a>More Groundwork: Immediately Invoked Function Expression (IIFE)
My code uses an Immediately Invoked Function Expression ([IIFE][iife]) similar to this pattern:
{% highlight js %}
// IIFE - runs immediately
(function () {
// some JavaScript here
}())
{% endhighlight %}
This pattern is discussed in excellent detail in the [<NAME>'s IIFE post][iife]. If you are unfamiliar with this
pattern, I suggest highly you read it. Basically, the outer surrounding parentheses let the JavaScript interpreter
know that what is inside is an *expression*, and an *anonymous function* is defined which is then immediately invoked
by including the *()* invocation right after the definition.
#### <a name="my-code"></a>My JavaScript Code
If you look at the [github JavaScript code][github-javascript] you will see that *all* my code is inside an IIFE
like so:
{% highlight js %}
(function () {
'use strict';
var SIG_DIGITS = 8,
MARGIN = 80,
SCALAR = 20,
//
// lots of variables
//
actualDisplacement = NaN,
actualMagnitude = NaN;
function draw() {
// JavaScript code here
}
function checkAnswers(e) {
// JavaScript code here
}
window.addEventListener('load', function() {
canvasElem = document.getElementById('canvas');
formElem = document.getElementById('form');
//
// Other inditialization code here (runs after DOM is fully loaded
//
formElem.addEventListener('submit', checkAnswers, false);
draw();
x1Elem.focus();
}, false);
}());
{% endhighlight %}
When the JavaScript file is included via a link at the end of the HTML body, the IIFE above runs as soon as that
JavaScript file is loaded by the browser. Some things to note:
* All variables and functions this file are [encapsulated][encapsulated] within an IIFE [closure][closure]
* All the stuff inside the IIFE is private to its [function scope][function-scope]
* Therefore, there is no [global namespace pollution][pollution] by all those variables and functions inside it
* There is a *load* [event listener][add-event-listener] that runs only after the [DOM][dom] is fully loaded
* The *load* event listener runs to interact with elements that must already be loaded by the browser
* I put all the code I can directly in the IIFE, not the *load* event handler for performance and cleanliness.
After all the initialization is done to set things up, I make the *checkAnswers()* function the event listener for the
*form* *submit* event using *addEventListener()* then call my *draw()* function to put up the initial canvas contents.
I then put the focus in the first text input so the user will not have to click to get to it.
Whenever the form is submitted, either by hitting the *enter* key or by clicking the "Check Answers" button, the form's
*submit* event is triggered which calls the attached event listener (the *checkAnswers()* function). This does some
validation of the user input, processes the inputs to get them ready for further use then calls the *draw()* function
to update the *canvas* with the appropriate graphics.
### <a name="thanks"></a>Thanks
Thanks to <NAME> (nickname ljharb on the ##javascript channel on [freenode][freenode]) for excellent editorial and
technical review of this article and the code which helped improve them immensely.
Happy coding!
[book]: http://www.amazon.com/Fundamentals-Physics-Extended-David-Halliday/dp/0471105597/ref=sr_1_8?s=books&ie=UTF8&qid=1396899157&sr=1-8&keywords=halliday+resnick+walker+fundamentals+of+physics+5th+edition
[overview]: #overview
[contents]: #contents
[instructions]: #instructions
[physics-discussion]: #physics-discussion
[try]: #try
[code-discussion]: #code-discussion
[code-overview]: #code-overview
[separation-groundwork]: #separation-groundwork
[iife-groundwork]: #iife-groundwork
[my-code]: #my-code
[thanks]: #thanks
[vector]: http://www.mathwords.com/v/vector.htm
[scalar]: http://www.mathwords.com/s/scalar.htm
[github]: https://github.com/aeoril/physicsLearning/tree/master/HallidayResnick/chapter2/2-2
[es5]: http://es5.github.io/
[html5]: http://developers.whatwg.org/
[w3c-css]: http://www.w3.org/Style/CSS/#specs
[mdn-javascript]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
[mdn-html]: https://developer.mozilla.org/en-US/docs/Web/HTML
[mdn-css]: https://developer.mozilla.org/en-US/docs/Web/CSS
[w3c-separate]: http://www.w3.org/wiki/The_web_standards_model_-_HTML_CSS_and_JavaScript#Why_separate.3F
[the-future-of-the-web]: http://www.thefutureoftheweb.com/talks/2006-10-ajax-experience/slides/
[cats-who-code]: http://www.catswhocode.com/blog/best-practices-for-modern-javascript-development
[github-javascript]: https://github.com/aeoril/physicsLearning/blob/master/HallidayResnick/chapter2/2-2/hallidayResnick-2-2.js
[iife]: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
[encapsulated]: https://leanpub.com/javascript-allonge/read#encapsulation
[closure]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
[pollution]: http://www.yuiblog.com/blog/2006/06/01/global-domination/
[function-scope]: http://ryanmorr.com/understanding-scope-and-context-in-javascript/
[add-event-listener]: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
[dom]: https://developer.mozilla.org/en-US/docs/DOM
[freenode]: http://freenode.net/
<file_sep>/_posts/2013-03-31-javascript-data-hiding-object-state-integrity-and-contracts.md
---
layout: post
navhilite: blog
title: "JavaScript Data Hiding, Object State Integrity and Contracts"
desc: "Or just another attempt at classic OOP in JavaScript ..."
date: 2013-03-31 12:34:56
categories: javascript
image: object_heirarchy.jpg
img-width: 144px
---
<div class="note">
<table>
<tr>
<td>
NOTE:
</td>
<td>
This post is for historical purposes only. Subsequent to writing this post, I have found attempting
classical OOP in Javascript to be less than optimal.
</td>
</tr>
</table>
</div>
Recently, I was playing around with doing data hiding, ensuring internal state integrity of objects and enforcing
contracts (interfaces) all in the same small amount of code.
### Library Object - abstracts Object.defineProperty()
Here is a utility object I use to lightly abstract Object.defineProperty(). It allows for easy construction of objects
that enforce contracts since all properties created with this abstraction are non-configurable.
{% highlight js %}
// Copyright © 2014 QuarksCode. MIT License (see http://opensource.org/licenses/MIT)
// Original Author: QuarksCode
// Object.interfaces provides a light abstraction layer on top
// of Object.defineProperty() and Object.defineProperties()
//
// Designed to be used to create enforceable contracts
// (interfaces) while still allowing extensions via new
// properties, mixins, etc.
// Library object variable provides interface to library
// Create as null object initially in the Object object
interfaces = Object.create(null);
(function () {
// Anonymous function is immediately invoked to add properties
// that implement the functionality of the object
'use strict';
Object.defineProperty(this, 'defineInterfaceProperty',
// Create property that is a function that creates
// single property using Object.defineProperty()
// using passed in attributes but enforcing interfaces
// descriptor object with attributes that define this method
{
value:function (propertyThis, attr) {
// This function is run when the property is invoked with ()
'use strict';
// Initialize variable to null object that will hold the descriptor
var desc = Object.create(null);
// Construct the property descriptor to pass into
// Object.defineProperty()
if (typeof attr.dataGet !== 'undefined') {
// if the dataGet attribute is included, create a data descriptor
desc.get = attr.dataGet;
} else if (typeof attr.method !== 'undefined') {
// if the method attribute is included create a method descriptor
desc.get = function () {
return attr.method;
};
desc.set = attr.dataSet ||
function (newValue) {
throw new Error('Attempted to write to read-only property');
};
} else {
throw new Error('encapsulation.js::defineInterfaceProperties():'
+ ' no get function')
}
desc.set = attr.dataSet ||
function (newValue) {
throw new Error('Attempted to write to read-only property');
};
desc.enumerable = attr.enumerable || true;
// Finally, create the property
Object.defineProperty(propertyThis, attr.name, desc);
},
enumerable:true
}
);
Object.defineProperty(this, 'defineInterfaceProperties',
// Create property that is a function that creates
// multiple properties using Object.defineProperties()
// using passed in attributes but enforcing interfaces
// descriptor object with attributes that define this method
{
value:function (propertyThis, attr) {
// This function is run when the property is invoked with ()
'use strict';
// Initialize variable to null object that will hold descriptors
var descs = Object.create(null);
// Construct the property descriptors to pass into
// Object.defineProperties()
Object.getOwnPropertyNames(attr).forEach(function (key) {
descs[key] = Object.create(null);
if (typeof attr[key].dataGet !== 'undefined') {
// if the dataGet attribute is included,
// create a data descriptor
descs[key].get = attr[key].dataGet;
} else if (typeof attr[key].method !== 'undefined') {
// if the method attribute is included
// create a method descriptor
descs[key].get = function () {
return attr[key].method;
};
} else {
throw new Error('encapsulation.js::defineInterfaceProperties():'
+ ' no get function')
}
descs[key].set = attr[key].dataSet ||
function (newValue) {
throw new Error('Attempted to write to read-only property');
};
descs[key].enumerable = attr[key].enumerable || true;
});
// Finally, create the properties
Object.defineProperties(propertyThis, descs);
},
enumerable:true
}
);
}).call(interfaces);
{% endhighlight %}
### Example code
Here is an example that illustrates use of the above library code to implement mixins, data hiding, internal state
consistency assurance and contract enforcement (interfaces)
{% highlight js %}
// Copyright © 2014 QuarksCode. MIT License (see http://opensource.org/licenses/MIT)
// Original Author: QuarksCode
// Constructor for the creating a person
function Person(nam) {
'use strict';
// Closure variables only visible in this function scope
var that = this,
nameValue = typeof nam === 'string' ? nam : '';
interfaces.defineInterfaceProperties(
this,
{
// Allow read-only access to this at time of construction backed
// by closure variable. Using that ensures return of proper this
// even if called with .call(), .apply() or bound with bind()
personThis:{
dataGet:function () {
return that;
}
},
name:{
dataGet:function () {
return nameValue;
},
dataSet:function (newValue) {
nameValue = newValue;
}
},
talk:{
method:function () {
return 'Hello, I\'m ' + this.name;
}
}
}
);
// return resultant object for chaining
return this;
}
function Swim(spd) {
'use strict';
// Closure variables only visible in this function scope
var that = this,
speedValue = typeof spd === 'number' ? spd : 0;
// Allow read-only access to 'this' at time of construction backed
// by closure variable. Using internal variable 'that' ensures return
// of proper 'this' even if called with .call(), .apply() or bound with bind()
interfaces.defineInterfaceProperty(
this,
{
name:'speedThis',
dataGet:function () {
return that;
}
}
);
// Read/write data property through getter and setter
// Backed by closure variable
interfaces.defineInterfaceProperty(
this,
{
name:'speed',
dataGet:function () {
return speedValue;
},
dataSet:function (newValue) {
speedValue = newValue;
}
}
);
interfaces.defineInterfaceProperty(
this,
{
name:'swim',
method:function () {
return this.talk() + ' and I am swimming at speed ' + this.speed;
}
}
);
interfaces.defineInterfaceProperty(
this,
{
name:'swimTalk',
method:function () {
return this.talk() + ' and I can swim at speed ' + this.speed;
}
}
);
// return resultant object for chaining
return this;
}
function WorkingPerson(occ) {
'use strict';
// Closure variables only visible in this function scope
var that = this,
occupationValue = typeof occ === 'string' ? occ : '';
// Allow read-only access to this at time of construction backed
// by closure variable. Using that ensures return of proper this
// even if called with .call(), .apply() or bound with bind()
interfaces.defineInterfaceProperties(
this,
{
workingPersonThis:{
dataGet:function () {
return that;
}
},
// Read/write data property through getter and setter
// Backed by closure variable
occupation:{
dataGet:function () {
return occupationValue;
},
dataSet:function (newValue) {
occupationValue = newValue;
}
},
// Uses immediate parent's talk method to chain string
// into overall output. Using .call(this) ensures parent
// talk will still use properties that depend on how this method
// is called (for instance, data properties overridden here)
// not just limited to the prototype's own this
talk:{
method:function () {
return Object.getPrototypeOf(this).talk.call(this) +
' and I am a ' + this.occupation;
}
},
blabber:{
method:function (blabberIn) {
return (typeof blabberIn === 'string' ? blabberIn : '') +
Object.getPrototypeOf(this).talk.call(this) +
' and I am a ' + this.occupation;
}
}
}
);
// return resultant object for chaining
return this;
}
// Set prototype to empty object, clone Swim and Person
// properties into WorkingPerson's prototype using chaining
// which makes new closures for backing variables for each
WorkingPerson.prototype = Object.create(null);
Swim.call(Person.call(WorkingPerson.prototype, 'workingPerson1_1'), 1);
var workingPerson1 = new WorkingPerson('occupation1_1');
// Note we must clear out WorkingPerson's prototype to
// successfully clone new copies of Swim's and Person's
// properties and get new closures. If we used the same
// prototype, the prototype resulting from new would be ===
// the above prototype and data collision would result
WorkingPerson.prototype = Object.create(null);
Swim.call(Person.call(WorkingPerson.prototype, 'workingPerson2_1'), 2);
var workingPerson2 = new WorkingPerson('occupation2_1');
// Note how we can have a complete, functional constructable object
// that includes the functionality of both resulting from cloning
// Swim's properties into Person.prototype
Person.prototype = Object.create(null);
Swim.call(Person.prototype, 1);
var swimmer1 = new Person('swimmer1_1');
// Or, cloning Person's properties into Swim.prototype. Both
// retain essentially same functionality but reverse which
// properties are own vs. inherited
Person.prototype = Object.create(null);
Swim.prototype = Object.create(null);
Person.call(Swim.prototype, 'swimmer2_1');
var swimmer2 = new Swim(2);
// These fail because of data hiding and contract enforcement
console.log([delete swimmer1.name]);
try {
workingPerson1.workingPersonThis = null;
} catch (e) {
console.log(e.message);
}
try {
workingPerson2.talk = null;
} catch (e) {
console.log(e.message);
}
console.log([swimmer1, swimmer2]);
console.log([swimmer1.name, swimmer1.talk(), swimmer1.swim()]);
console.log([swimmer2.name, swimmer2.talk(), swimmer2.swim()]);
console.log([workingPerson1, workingPerson2]);
console.log([workingPerson1.name,
workingPerson1.occupation,
workingPerson1.speed,
workingPerson1.talk(),
workingPerson1.blabber('<NAME> '),
workingPerson1.swim(),
workingPerson1.swimTalk()]);
console.log([workingPerson2.name,
workingPerson2.occupation, workingPerson2.speed,
workingPerson2.talk(), workingPerson2.blabber('<NAME> '),
workingPerson2.swim(), workingPerson2.swimTalk()]);
workingPerson1.name = 'workingPerson1_2';
workingPerson1.occupation = 'occupation1_2';
workingPerson1.speed = 3;
console.log([workingPerson1.name, workingPerson1.occupation, workingPerson1.speed,
workingPerson1.talk(), workingPerson1.blabber('<NAME> '),
workingPerson1.swim(), workingPerson1.swimTalk()]);
console.log([workingPerson2.name, workingPerson2.occupation, workingPerson2.speed,
workingPerson2.talk(), workingPerson2.blabber('<NAME> '),
workingPerson2.swim(), workingPerson2.swimTalk()]);
workingPerson2.name = 'workingPerson2_2';
workingPerson2.occupation = 'occupation2_2';
workingPerson2.speed = 4;
console.log([workingPerson1.name, workingPerson1.occupation, workingPerson1.speed,
workingPerson1.talk(), workingPerson1.blabber('<NAME> '),
workingPerson1.swim(), workingPerson1.swimTalk()]);
console.log([workingPerson2.name, workingPerson2.occupation, workingPerson2.speed,
workingPerson2.talk(), workingPerson2.blabber('<NAME> '),
workingPerson2.swim(), workingPerson2.swimTalk()]);
{% endhighlight %}
Happy Coding!
<file_sep>/static/spiroche/README.md
## Spiroche
This repo is under construction. Parts of it may be broken.
### Fun interactive graphics program
Use the mouse to make multi-colored eye-popping graphics. Uses and HTML5 Canvas, JavaScript and CSS.<file_sep>/static/JSLearning/src/changeIFrame/myFrameCross.js
window.addEventListener('load', function () {
'use strict';
var width = 100,
height = 100;
console.log('0');
document.getElementById('button').addEventListener('click', function() {
console.log('1');
parent.postMessage(JSON.stringify({
width: width,
height: height
}), '*');
width += 10;
height += 10;
console.log(width, height);
}, false);
}, false);
<file_sep>/_posts/2014-03-28-object-based-vs-constructor-based-coding-in-javascript.md
---
layout: post
navhilite: blog
title: "Object Based vs. Constructor Based Coding in JavaScript"
desc: "Or how I broke the function dictatorship over my objects"
date: 2014-03-28 20:10:00
categories: javascript
image: constructor_and_prototypes_detailed.png
img-width: 164px
---
### <a name="overview"></a>Overview
This article describes a specific way of encapsulating state data, shared behaviors and *pure*, non-mutating functions
using JavaScript objects.
Two alternate approaches are discussed. One uses the traditional constructor approach. The other, called object based
here, uses just objects and [Object.create()][object-create] (new in [ECMAScript 5][ecmascript-5] (ES5)).
I have come to prefer that latter mainly because of the more concise [object literal syntax][object-literal-syntax] but
also because it seems more consistent, using objects all around without the need for constructor functions that are
used as objects as well.
### <a name="toc"></a>Table of Contents
* [Overview][overview]
* [Table of Contents][toc]
* [Reading Prerequisite][reading-prerequisite]
* [Constructor Method][constructor-method]
* [The Constructor][the-constructor]
* [The Prototype][the-prototype]
* [Non-mutating (Pure) Functions Defined on the Constructor Object][non-mutating-functions]
* [All Together Now][all-together-now]
* [The Good Parts][good-parts]
* [Now for the Messy Parts][messy-parts]
* [The Object Based Way][object-way]
* [The Prototype Object][prototype-object]
* [Adding State Data and Initializing It][adding-state-data]
* [Helper Functions to the Rescue][helper-functions]
* [We Can Do Even Better!][we-can-do-better]
* [Adding Purity][adding-purity]
* [All Together Now - Again][all-together-now-again]
* [A Major Difference][major-difference]
* [A Note on Compatibility][a-note-on-compatibility]
* [Links to Real World Code][real-world-links]
* [Thanks][thanks]
<br>
### <a name="reading-prerequisite"></a>Reading Prerequisite
Before you read this article, I *strongly encourage* you to read the series of articles written by <NAME>
that lay the groundwork for this article [here][kyle-simpson-articles]. However, I do expand on what he did in those
articles so coming back here and reading to the end is worthwhile. If you are already familiar with how constructors
and the prototype chain work in JavaScript, you can skip now to the [object based way][object-way] suggested as an
alternative.
### <a name="constructor-method"></a>Constructor Method
Before the [Object.create()][object-create] function came along in the [ECMAScript 5][ecmascript-5] standard, when
one wanted to create a JavaScript object using a specific [prototype][prototype], one did so using a
constructor function with the [new operator][new-operator] with its prototype property pointing to an object that
had properties that implemented the shared behaviors you desired.
#### <a name="the-constructor"></a>The Constructor
Here is some typical code that defines a constructor function and uses it to create an object:
{% highlight js %}
function Vector2D (x, y) {
this.x = x;
this.y = y;
}
var vec = new Vector2D(3, 4); // vec -> [3, 4]
{% endhighlight %}
When the `Vector2D()` constructor is called via the `new` operator a brand new object is created to which
the keyword [this][this] refers. The code in the `Vector2D()` constructor function explicitly creates two new
properties (`x` and `y`) on the object pointed to by `this` and assigns them the values of the corresponding
`x` and `y` arguments passed into the constructor. These two properties (`this.x` and `this.y`) contain the state
data for the object which will be manipulated by the shared behaviors we will define on its prototype object.
When `Vector2D()` returns, its return value is implicitly set to the newly created object pointed to by `this`.
It is this returned object that is assigned to the variable `vec` (which is the whole point, really.)
Note: One could explicitly create an object in the constructor if one wished and return it instead of the implicit
object created by the constructor when called with `new`. Not returning anything or returning a non-object value will
result in the constructor returning the implicit `this` as normal.
Here is a diagram that shows what has happened in the above code:
<img style="width: 640px;" src="/images/delegate_based/constructor_simplified.png" alt="Constructor Diagram" />
<br>
#### <a name="the-prototype"></a>The Prototype
Here is some code that shows how we add a property to the prototype object of the `Vector2D()` function object:
{% highlight js %}
Vector2D.prototype.add = function(vec) {
this.x += vec.x;
this.y += vec.y;
};
{% endhighlight %}
All functions have a [prototype][prototype] property. The constructor function exposes this property as
`Vector2D.prototype`. The prototype property's value will become the prototype object pointed to by the
[[[Prototype]]][prototype-internal] implicit internal object reference of the object created
by the constructor (see table 8 in the spec). All objects have a *[[Prototype]]* implicit internal
object reference, which has been historically exposed by many JavaScript implementations using the
*__proto__* property.
The *__proto__* property is non-standard in *ES5*, but will become a standard in the next version,
*ES6*. However, some current implementations let you set the *[[Prototype]]* reference by setting the
*__proto__* property. This could swap out the entire prototype chain. In *ES6* setting
*__proto__* will not set *[[Prototype]]* and the chain will remain intact.
Note that JavaScript functions (including constructors) are objects and have a *[[Prototype]]*
reference too. Also note that a function's prototype property does not necessarily point to the same object
as its *[[Prototype]]* reference (although it can). That is, a constructor's prototype property
determines what the *[[Prototype]]* reference of the object created by the constructor points to, while
the constructor function's *[[Prototype]]* reference is for the constructor itself.
The code above creates a new property called `add` on the prototype object of the `Vector2D` constructor function.
It then assigns it a function value. When the newly constructed object's *[[Prototype]]* reference
is pointed to the constructor function's prototype object, the `add` function will become accessible via
JavaScript's [prototypal inheritance][prototypal-inheritance] mechanism via the [prototype chain][prototype-chain]
(see below).
<NAME> refers to the object pointed to by the *[[Prototype]]* reference as a delegate object
and the `add` behavior as being delegated to it. So, instead of saying "the `add` behavior is inherited from the
object's prototype object," one would say "the `add` behavior is delegated to the delegate object of the newly
created object."
To illustrate:
{% highlight js %}
var vec1 = new Vector2D(3, 4), // vec1 -> [3, 4]
vec2 = new Vector2D(6, 8); // vec2 -> [6, 8]
vec1.add(vec2); // vec1 -> [9, 12]
{% endhighlight %}
The last line that invokes `vec1.add(...)` will cause a search for the `add` property on first the `vec1` object
itself. Not finding it there, `vec1`'s prototype object will be searched and `add` will be found on it and
its function value will be returned and invoked.
`vec1`'s prototype object is just the first one in the prototype chain of linked prototype objects that is
ultimately terminated by `null`. If `add` had not been found to be a property of `vec1`'s prototype object, the
prototype object of `vec1`'s prototype object would have been checked to see if it were `null`. If it were `null`,
`undefined` would have been returned. If not, it would have been searched for `add` and if found its value would have
been returned. And so on and so forth on up the chain until the either `null` were hit or `add` found.
Looking at the code that defines `add` above, we see that it uses `this.x` and `this.y`. However, here the `this`
keyword returns the root object, or `vec1`, not `vec1`'s prototype object. Therefore, the references to `this.x`
and `this.y` resolve to `vec1.x` and `vec1.y`. `vec1` is correctly updated with the sum of the `x`s and `y`s of `vec1`
and `vec2`. This happens no matter how deep into the prototype chain one must dig to find a given property.
Here is a diagram that illustrates what is going on here:
<img style="width: 720px;" src="/images/delegate_based/constructor_and_prototypes_simplified_1.png" alt="Constructor Based Object Creation Simplified View" />
<br>
#### <a name="non-mutating-functions"></a>Non-mutating "Pure" Functions Defined on the Constructor Object
Here I add a non-mutating or pure function called `add` directly on the `Vector2D` function object itself:
{% highlight js %}
Vector2D.add = function(vec1, vec2) {
return new Vector2D(vec1.x + vec2.x, vec1.y + vec2.y);
};
{% endhighlight %}
We can do this because all functions are also objects and can have properties defined on them. This function does
not mutate any existing objects. Instead, it creates a brand new vector whose `x` and `y` values are the sum of the
`x` and `y` values of the two passed in vector arguments and returns it. One could say it has no side effects.
Here is a sample usage:
{% highlight js %}
var vec1 = new Vector2D(3, 4), // vec1 -> [3, 4]
vec2 = new Vector2D(6, 8), // vec2 -> [6, 8]
vec3 = Vector2D.add(vec1, vec2); // vec3 -> [9, 12]
{% endhighlight %}
Adding non-mutating versions of the functions that reside in the prototype object of an object can be very handy for
certain ways of coding that many consider to be less error prone and easier to understand. See
[functional programming][functional-programming] for more information.
However, often in JavaScript it is necessary for performance reasons to eschew such coding practices for more
traditional stateful methods that use prototypes as described above to avoid the creation of temporary objects which
must be garbage collected in current implementations. In my math and physics libraries, I make both available and leave
the choice of coding style up to the user.
Creating these non-mutating versions of functions directly on the constructor object along with any other utility
functions that make sense to put there is a good way to avoid polluting the global namespace and organize them.
There are two important things to note here. First, if we invoke `add` using `Vector2D.add(...)`, since `Vector2D` now
has `add` directly defined on it, the prototype object will not be searched for `add` - it will already be found as
an [own property][own-property] (a property directly defined on an object, not found in its prototype chain)
directly on `Vector2D`.
The second thing to note is that this is *not* the case for objects created using the `Vector2D` constructor.
The `Vector2D` constructor on which the non-mutating version of `add` is defined is not in the prototype chain
of the objects created by the `Vector2D` constructor (except as the prototype of the constructor property -
see below - which will not cause `Vector2D.add` to be found in the prototype chain search for `add`).
A brand new object is created whose prototype object is the same as `Vector2D.prototype`. That is
certainly searched as part of the prototype chain. However, `Vector2D`'s own properties added by user code do not
get searched as part of the prototype chain lookup for `add`.
(Note that the above code is not *DRY* (Don't Repeat Yourself) - I repeat the addition calculation in both `add`
functions above. But, it suffices for brevity. See my full working [Vector2D object][vector2d] to see how I do
it *DRY*.)
#### <a name="all-together-now"></a>All Together Now
Here is all the above code put together:
{% highlight js %}
function Vector2D (x, y) {
this.x = x;
this.y = y;
}
Vector2D.add = function(vec1, vec2) {
return new Vector2D(vec1.x + vec2.x, vec1.y + vec2.y);
};
Vector2D.prototype.add = function(vec) {
this.x += vec.x;
this.y += vec.y;
};
var vec1 = new Vector2D(3, 4), // vec1 -> [3, 4]
vec2 = new Vector2D(6, 8); // vec2 -> [6, 8]
vec1.add(vec2); // vec1 -> [9, 12]
{% endhighlight %}
#### <a name="good-parts"></a>The Good Parts
We have a good setup. We have an easy and concise way of creating new vectors with `Vector2D()`. We have a
conveniently placed function `Vector2D.add()` if we want to add but not mutate. And `vec1` and `vec2` contain
the state data (the `x` and `y` properties) and an appropriate prototype object that contains a function (`add`)
that has the behavior necessary to manipulate them.
We have a nice separation of concerns as well: the non-mutating functionality directly in Vector2D(), the state data
in the objects created by `new Vector2D( ... )` and the shared functionality in their prototype object that mutates
the object's state.
Here is a diagram that shows all the good parts together:
<img style="width: 720px;" src="/images/delegate_based/constructor_and_prototypes_simplified_2.png" alt="Constructor Based Object Creation Simplified View" />
<br>
#### <a name="messy-parts"></a>Now for the Messy Parts
Behind the scenes, however, the reality of the object hierarchy is very complex. Below is a diagram that shows
it in detail:
<img style="width: 920px;" src="/images/delegate_based/constructor_and_prototypes_detailed.png" alt="Messy Constructor Diagram" />
### <a name="object-way"></a>The Object Based Way
An alternative way is to use just objects instead of constructors along with `Object.create()`. I
also include some helper functions to make the user code less cumbersome.
#### <a name="prototype-object"></a>The Prototype Object
Consider the following code:
{% highlight js %}
var vector2DPrototype = {
add: function(vec) {
this.x += vec.x;
this.y += vec.y;
}
},
vec = Object.create(vector2DPrototype);
{% endhighlight %}
I create two variables. The first will be used as the prototype object to be fed into the `Object.create()`
function which will create a new object variable called `vec` whose prototype object points to `vector2DPrototype`.
Just like using `new` and a constructor, I have created a brand new object with a prototype object that
contains the properties I desire.
The diagram below shows things as they stand now:
<img style="width: 720px;" src="/images/delegate_based/objects_and_prototypes_simplified_1.png" alt="Object Based Object Creation Simplified View" />
<br>
Notice that the `vec` object has no state properties yet - it has no `this.x` or `this.y`, and even if it did, no way to
initialize them on creation of the `vec` object.
#### <a name="adding-state-data"></a>Adding State Data and Initializing It
Here is the same code as above but with the addition of a function to create and initialize the state data:
{% highlight js %}
var vector2DPrototype = {
init: function(x, y) {
this.x = x;
this.y = y;
},
add: function(vec) {
this.x += vec.x;
this.y += vec.y;
}
},
vec1 = Object.create(vector2DPrototype),
vec2 = Object.create(vector2DPrototype);
vec1.init(3, 4); // vec1 -> [3, 4]
vec2.init(6, 8); // vec2 -> [6, 8]
vec1.add(vec2); // vec1 -> [9, 12]
{% endhighlight %}
Notice how I have added a `vector2DPrototype.init()` to both create and initialize the state data.
Now we have code that can do *roughly* what the constructor based code above can do, minus the `Vector2D.add()` pure
function. There is a major difference in that this code does not include a constructor property on the prototype object,
and I will discuss the ramifications of that below.
Here is a diagram of how things stand now:
<img style="width: 920px;" src="/images/delegate_based/objects_and_prototypes_simplified_2.png" alt="Object Based Object Creation Simplified View" />
<br>
#### <a name="helper-functions"></a>Helper Functions to the Rescue
But ouch! It sure seems clunky and repetitive in how we have to code it up! And eewww! The diagram!
Consider the following changes in the `vector2DPrototype` functions:
{% highlight js %}
var vector2DPrototype = {
init: function(x, y) {
this.x = x;
this.y = y;
return this;
},
add: function(vec) {
this.x += vec.x;
this.y += vec.y;
return this;
}
};
{% endhighlight %}
All we have done is added the line:
{% highlight js %}
return this;
{% endhighlight %}
to each of those functions. By doing this, both of those functions return the object on which they are called.
We do this so we can either use the returned object in an assignment or chain function calls.
In the case of a variable assignment, we can be assured we will will return `this` even if we chain `init` after
the `Object.create()` call that constructs the object:
{% highlight js %}
var vec = Object.create(vector2DPrototype).init(3, 4); // vec -> [3, 4]
{% endhighlight %}
In the case of `add` we can chain subsequent additions conveniently:
{% highlight js %}
var vec1 = Object.create(vector2DPrototype).init(3, 4), // vec1 -> [3, 4]
vec2 = Object.create(vector2DPrototype).init(6, 8), // vec2 -> [6, 8]
vec3 = Object.create(vector2DPrototype).init(1, 2); // vec3 -> [1, 2]
vec1.add(vec2).add(vec3); // vec1 -> [10, 14]
{% endhighlight %}
#### <a name="we-can-do-better"></a>We Can Do Even Better!
Now that we have fixed up `init` for chaining, we can make a new object `Vector2D` that includes a helper function
property called `create` that wraps it all up nicely:
{% highlight js %}
var Vector2D = {
create: function(x, y) {
return Object.create(vector2DPrototype).init(x, y);
}
};
{% endhighlight %}
`Vector2D.create()` first creates an object with the appropriate prototype object, then creates its state and
initializes it, then returns that value for assignment, chaining or both.
Now we can do this:
{% highlight js %}
var vec = Vector2D.create(3, 4); // vec -> [3, 4]
{% endhighlight %}
Using these helper functions, we have cleaned up the usage and made it just as easy as constructors. Now we can use
objects only without the need to create constructor functions and using the arguably cleaner and less verbose
[object literal syntax][object-literal-syntax].
Here is the current diagram:
<img style="width: 720px;" src="/images/delegate_based/objects_and_prototypes_simplified_3.png" alt="Object Based Object Creation Simplified View" />
<br>
#### <a name="adding-purity"></a>Adding Purity
Now, I will create another property on `Vector2D` that will hold the pure non-mutating function `add`:
{% highlight js %}
var Vector2D = {
create: function(x, y) {
return Object.create(vector2DPrototype).init(x, y);
},
add: function(vec1, vec2) {
return Vector2D.create(vec1.x, vec1.y).add(vec2);
}
};
{% endhighlight %}
Note how the static `add` function above uses the mutating `add` function from its prototype instead of repeating code,
keeping things *DRY* (Don't Repeat Yourself).
We now have pretty much all the same functionality as the above constructor based code. We have already shown how to
use the mutating `add` from the prototype. Here is how using the non-mutating `add` looks:
{% highlight js %}
var vec1 = Vector2D.create(3, 4), // vec1 -> [3, 4]
vec2 = Vector2D.create(6, 8), // vec2 -> [6, 8]
vec3;
vec3 = Vector2D.add(vec1, vec2); // vec3 -> [9, 12]
{% endhighlight %}
Although basically functionally equivalent to the constructor based code above, you can see the differences in the
two approaches in the diagram below:
<img style="width: 920px;" src="/images/delegate_based/objects_and_prototypes_simplified_4.png" alt="Object Based Object Creation Simplified View" />
<br>
#### <a name="all-together-now-again"></a>All Together Now - Again
Here is all the code now put together:
{% highlight js %}
var Vector2D = {
create: function(x, y) {
return Object.create(vector2DPrototype).init(x, y);
},
add: function(vec1, vec2) {
return Vector2D.create(vec1.x, vec1.y).add(vec2);
}
},
vector2DPrototype = {
init: function(x, y) {
this.x = x;
this.y = y;
return this;
},
add: function(vec) {
this.x += vec.x;
this.y += vec.y;
return this;
}
},
vec1 = Vector2D.create(3, 4), // vec1 -> [3, 4]
vec2 = Vector2D.create(6, 8), // vec2 -> [6, 8]
vec3;
vec1.add(vec2); // vec1 -> [9, 12]
vec3 = Vector2D.add(vec1, vec2); // vec3 -> [15, 20]
{% endhighlight %}
And below is a diagram showing how the above code looks visually. Notice that everything is objects. The only
functions are properties of objects. It is very clean:
<img style="width: 920px;" src="/images/delegate_based/objects_and_prototypes_simplified_5.png" alt="Object Based Object Creation Simplified View" />
<br>
### <a name="major-difference"></a>A Major Difference
[instanceof][instanceof] is a JavaScript operator that tells whether any of the prototype objects in the
prototype chain of the first operand, which is an object, is pointed to by the prototype property of the second
operand, which is a constructor. Since we have no constructors in our setup, this capability is broken.
However, one could argue using `instanceof` as a valid test may be questionable because the prototype object of the
constructor could have been changed after any objects tested were created by it. Also, with the
*[[Prototype]]* reference of objects exposed by many implementations of JavaScript, the entire
prototype chain could be changed arbitrarily, also invalidating this check.
### <a name="a-note-on-compatibility"></a>A Note on Compatibility
`Object.create()` is new to the *ES5* standard. It is not backward compatible with all browsers still in use today.
Specifically, Internet Explorer versions less than 9 do not have it. Here is the
[MDN compatibility table][mdn-compatibility-table] for `Object.create()`. You can find a shim in the same MDN
article [here][object-create-shim]. For a link to a complete *ES5* shim capability, look at
[es5-shim][es5-shim].
### <a name="real-world-links"></a>Links to Real World Code
You can see full working examples of the methods discussed here in my Harmonia sample animation [here][harmonia].
It in turn uses the [Motion2D][motion2d] object from my [PhysicsLibrary][physics-library] project which in turn
uses the [Vector2D][vector2d] object from my [MathLibrary][math-library] project. Both of those libraries
use the same methods discussed here as well as the Harmonia example animation.
### <a name="thanks"></a>Thanks
Including the heavy debt I owe to <NAME>, I learned most of the important parts of this style that are additions
to those found in Kyle's articles from [<NAME>][ljharb]. He is known by the nick *ljharb* on the ##javascript
channel on [freenode.net][freenode]. *ljharb* also reviewed this article.
I also had a good amount of help for this style from [<NAME>][imbcmdth] whose nick is *ImBcmDth* on the same
channel on *freenode*. I also borrowed and altered his diagram of the *constructor mess* for my needs with his
permission, and used it as the basis for my other diagrams. And thanks to all the rest of the crew on *freenode* that
helped me with this as well!
<div class="note noteBottom">
<table>
<tr>
<td>
NOTE:
</td>
<td>
A great alternative that I use when appropriate is to use
<a href="http://browserify.org/">browserify</a> with <a href="http://nodejs.org/">node.js</a>
modules and <a href="https://www.npmjs.com/">NPM</a>
</td>
</tr>
</table>
</div>
Happy coding!
[object-create]: http://es5.github.io/#x15.2.3.5
[ecmascript-5]: http://es5.github.io/
[overview]: #overview
[toc]: #toc
[reading-prerequisite]: #reading-prerequisite
[constructor-method]: #constructor-method
[the-constructor]: #the-constructor
[the-prototype]: #the-prototype
[non-mutating-functions]: #non-mutating-functions
[all-together-now]: #all-together-now
[good-parts]: #good-parts
[messy-parts]: #messy-parts
[object-way]: #object-way
[prototype-object]: #prototype-object
[adding-state-data]: #adding-state-data
[helper-functions]: #helper-functions
[we-can-do-better]: #we-can-do-better
[adding-purity]: #adding-purity
[all-together-now-again]: #all-together-now-again
[major-difference]: #major-difference
[a-note-on-compatibility]: #a-note-on-compatibility
[real-world-links]: #real-world-links
[thanks]: #thanks
[kyle-simpson-articles]: http://davidwalsh.name/javascript-objects
[object-create]: http://es5.github.io/#x15.2.3.5
[new-operator]: http://es5.github.io/#x11.2.2
[this]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
[prototype]: http://es5.github.io/#x4.3.5
[prototype-internal]: http://es5.github.io/#x8.6.2
[prototypal-inheritance]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain
[prototype-chain]: http://es5.github.io/#x4.2.1
[functional-programming]: http://en.wikipedia.org/wiki/Functional_programming
[own-property]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
[object-literal-syntax]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Object_literals
[instanceof]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
[mdn-compatibility-table]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Browser_compatibility
[object-create-shim]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill
[es5-shim]: https://github.com/es-shims/es5-shim/blob/master/es5-shim.js
[harmonia]: /physics/2014/03/09/harmonia-2d-newtonian-motion-animation.html
[motion2d]: https://github.com/aeoril/PhysicsLibrary/blob/master/src/Motion2D.js
[physics-library]: https://github.com/aeoril/PhysicsLibrary
[vector2d]: https://github.com/aeoril/MathLibrary/blob/master/src/Vector2D.js
[math-library]: https://github.com/aeoril/MathLibrary
[ljharb]: https://github.com/ljharb
[imbcmdth]: https://github.com/ImBcmDth
[freenode]: http://freenode.net/
<file_sep>/static/harmonia/Vector2D.js
// Copyright © 2014 QuirksCode. MIT License - see http://opensource.org/licenses/MIT and see COPYRIGHT.md
// Original Author: aeoril
//
// Vector2D.js - 2D vector class
var Vector2D = {
create: function (x, y) {
return Object.create(Vector2DProto).init(x, y);
},
copy: function (from, to) {
return from.copy(to);
},
add: function (vec1, vec2) {
return vec1.clone().add(vec2);
},
sub: function (vec1, vec2) {
return vec1.clone().sub(vec2);
},
diagMul: function (vec1, vec2) {
return vec1.clone().diagMul(vec2);
},
scale: function (vec, factor) { // , vec1, vec2, ... vecN
return vec.clone().scale(factor);
},
norm: function (vec) {
return vec.clone().norm();
},
dot: function (vec1, vec2) {
return vec1.dot(vec2);
},
// Vector of the projection of vec1 along vec2
proj: function (vec1, vec2) {
return vec1.clone().proj(vec2);
},
fromPolar: function (mag, angle) {
return Vector2D.create(0, 0).fromPolar(mag, angle);
},
xFromPolar: function (mag, angle) {
return mag * Math.cos(angle);
},
// Y from polar coordinates without allocation
yFromPolar: function (mag, angle) {
return mag * Math.sin(angle);
}
};
var Vector2DProto = {
init: function (x, y) {
this.x = x;
this.y = y;
return this;
},
copy: function (to) {
to.x = this.x;
to.y = this.y;
return to;
},
clone: function () {
return Vector2D.create(this.x, this.y);
},
add: function (vec) {
this.x += vec.x;
this.y += vec.y;
return this;
},
sub: function (vec) {
this.x -= vec.x;
this.y -= vec.y;
return this;
},
diagMul: function (vec) {
this.x *= vec.x;
this.y *= vec.y;
return this;
},
scale: function (factor) {
this.x *= factor;
this.y *= factor;
return this;
},
norm: function () {
var mag = this.mag();
if (mag === 0) {
throw new RangeError('Cannot normalize the zero vector');
}
this.scale(1 / mag);
return this;
},
// Mutate instance to the projection of instance along argument
proj: function (vec) {
var vecMag = vec.mag(),
dot = this.dot(vec);
return Vector2D.copy(vec, this).scale(dot / (vecMag * vecMag));
},
dot: function (vec) {
return this.x * vec.x + this.y * vec.y;
},
mag: function () {
return Math.sqrt(this.dot(this));
},
angle: function () {
return Math.atan2(this.y, this.x);
},
fromPolar: function (mag, angle) {
this.x = Math.cos(angle);
this.y = Math.sin(angle);
this.scale(mag);
return this;
}
};<file_sep>/_posts/2015-04-27-first-halliday-and-resnick-interactive-physics-tutorials.md
---
layout: post
navhilite: blog
title: "First Halliday and Resnick Interactive Physics Tutorials"
desc: "Halliday, Resnick and Walker Chapter 2 sections 2-2 and 2-3 Physics Tutorials"
date: 2015-04-27 12:34:56
categories: physics
image: halliday_resnick-2-3.png
img-width: 206px
---
The first of my [learning projects][projects] is now in full swing. You will find them on the
[Halliday and Resnick project web page][hallidayResnick]
This project entails interactive tutorials to accompany the classic and de facto standard first year physics book
[The Fundamentals of Physics Extended][book] by Halliday, Resnick and Walker. I am basing my tutorials on the fifth
edition. I start with chapter 2 which is entitled "Motion Along a Straight Line" and you will find links to sections 2 and 3
below:
* [Halliday and Resnick Chapter 2 Section 2 - Position and Displacement][2-2]
* [Halliday and Resnick Chapter 2 Section 3 - Average Velocity and Speed][2-3]
I hope you find these interactive tutorials helpful, fun and exciting!
Happy coding!
[projects]: /projects
[hallidayResnick]: /hallidayResnick
[book]: http://www.amazon.com/Fundamentals-Physics-Extended-David-Halliday/dp/0471105597/ref=sr_1_8?s=books&ie=UTF8&qid=1396899157&sr=1-8&keywords=halliday+resnick+walker+fundamentals+of+physics+5th+edition
[2-2]: /hallidayResnick/2-2
[2-3]: /hallidayResnick/2-3
<file_sep>/static/JavaScript/simpleMixin.js
// Copyright © 2015 QuarksCode. MIT License - see http://opensource.org/licenses/MIT or LICENSE.md file
// Original Author: aeoril
//
// simpleMixin.js - simple object and array mixing
function simpleMixin(from, to) {
'use strict';
var newTo = false;
if (!to) {
if (from === null || typeof from !== 'object') {
return from;
}
to = Array.isArray(from) ? [] : {};
newTo = true;
} else if ((to === null || typeof to !== 'object') || (from === null || typeof from !== 'object')) {
return to;
}
return Object.keys(from).reduce(function (result, key) {
if (typeof from[key] === 'object' && from[key] !== null) {
if (!Object.prototype.hasOwnProperty.call(result, key)) {
result[key] = Array.isArray(from[key]) ? [] : {};
}
result[key] = simpleMixin(from[key], result[key]);
} else {
result[key] = from[key];
}
return result;
}, newTo ? to : simpleMixin(to));
}
function simpleMixinBindFrom(from) {
'use strict';
return Function.prototype.bind.call(simpleMixin, null, simpleMixin(from));
}
<file_sep>/static/logServer/log.js
// Copyright 2012 © <NAME>. See COPYRIGHT file for details
// Original Author: <NAME> - <EMAIL>
window.addEventListener('load', function () {
"use strict";
document.getElementById('button').addEventListener('click', function () {
var type = document.getElementById('type').value,
sev = document.getElementById('sev').value,
msg = document.getElementById('msg').value,
num = document.getElementById('num').value,
ms = document.getElementById('ms').value,
whatObj = {type: type, sev: sev, msg: msg},
whatJSON = JSON.stringify(whatObj);
function log() {
// function ajaxPost(what, url, how) {
function ajaxPost(what, contentType, url, how) {
var xhr;
xhr = new XMLHttpRequest();
xhr.open(how, url, true);
xhr.setRequestHeader('Content-Type', contentType);
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
xhr.send(what);
}
// ajaxPost(new Blob(['{"logType":"Type", "logSev":"logSev", "logMsg":"Msg"}'], {type:'text/plain'}),
// ajaxPost(new Blob(['abcdefg'], {type: 'text/plain'}),
// ajaxPost('{"logType":"Type", "logSev":"logSev", "logMsg":"Msg"}',
// ajaxPost('{"logType":"Long","logSev":"John","logMsg":"Silver"}',
ajaxPost(whatJSON,
"application/json",
// "application/x-www-form-urlencoded; charset=UTF-8",
// "http://www.sanbarcomputing.com/flat/logServer/log.php", "GET");
// 'text/plain',
"log.php", "POST");
// "application/json", "http://www.sanbarcomputing.com/flat/logServer/log.php");
// "application/json", "http://query.yahooapis.com/v1/public/yql");
// var img = new Image();
// img.src = "log.php?logType=" + encodeURIComponent(type) + "&logSev="
// + encodeURIComponent(sev) + "&logMsg=" + encodeURIComponent(msg);
if (--num > 0) {
setTimeout(function () {
log();
}, ms);
}
}
log();
}, false);
}, false);<file_sep>/_drafts/test.md
---
layout: post
navhilite: blog
title: "RedCarpet Markdown Test"
desc: "Finding the bugs in RedCarpet"
date: 2014-04-02 12:12:12
categories: test
---
{% highlight js %}
function myfunc(x) {
x += 5;
return x;
}
{% endhighlight %}
### This is a Markdown Header
This is some markdown text with an inline code block: `var v = myFunc(10)`. This markdown *is not* properly processed.
<div>
<img style="width: 640px;" src="/images/delegate_based/constructor_simplified.png" alt="Constructor Diagram" />
</div>
### This is a Markdown Header
This is some markdown text with an inline code block: `var v = myFunc(10)`. This markdown *is* properly processed.
<file_sep>/static/JavaScript/debounce.js
// Copyright © 2016 QuarksCode.
// MIT License - see http://opensource.org/licenses/MIT and LICENSE.MD file
// Original Author: aeoril
// return a debounced version of a function. timeout is milliseconds
function debounce(fun, timeout) {
'use strict';
var timeoutID = null;
return function () {
var args = arguments;
if (timeoutID) {
clearTimeout(timeoutID);
}
timeoutID = setTimeout(function () { fun.apply(null, args); }, timeout);
};
}
<file_sep>/hallidayResnick/2-2/test2/hallidayResnick-2-2.js
// Copyright © 2014 QuarksCode. MIT License - see http://opensource.org/licenses/MIT and see COPYRIGHT.md
// Original Author: aeoril
//
window.addEventListener('load', function () {
function checkAnswers(event) {
// JavaScript code here
console.log(event.target);
}
document.getElementById('form').addEventListener('submit', checkAnswers, false);
}, false);
|
de52298f1b44a543c69c5c77dd432bc551a8347c
|
[
"Markdown",
"JavaScript",
"HTML",
"PHP"
] | 31
|
HTML
|
aeoril/aeoril.github.io.old
|
b37698587e4cbe59f17948af9e87da5429838e15
|
968c52e6f3b2c4b8ff76c1d03e017a43c900c642
|
refs/heads/master
|
<file_sep># SNU Chainer
Spiking neural unit implemented with Chainer-v5
See: https://arxiv.org/abs/1812.07040
## Requirements
- Chainer v5
- cupy
- tqdm
## Usage
### Train the network
Run, `python train.py -g 0 -b 128 -e 100 -t 10`
(gpu, batch, epoch, simulation time steps)
<img src="https://github.com/takyamamoto/SNU_Chainer/blob/master/imgs/loss_acc.png" width=60%>
### Test output activity
Run, `python analysis.py -g 0 -m ./results/model`
<img src="https://github.com/takyamamoto/SNU_Chainer/blob/master/imgs/results.png" width=60%>
### Check SNU layer
Run, `python check_snu_layer.py`
<img src="https://github.com/takyamamoto/SNU_Chainer/blob/master/imgs/Check_SNU_result.png" width=50%>
### Check Jittered MNIST
Run, `check_jittered_mnist.py`
<img src="https://github.com/takyamamoto/SNU_Chainer/blob/master/imgs/JitteredMNIST.png" width=50%>
<file_sep># -*- coding: utf-8 -*-
import os
import numpy as np
import matplotlib.pyplot as plt
from model import snu_layer
from chainer import Variable
img_save_dir = "./imgs/"
os.makedirs(img_save_dir, exist_ok=True)
""" Build Spiking Neural Unit """
num_time = 100 # simulation time step
V_th = 2.5
tau = 25e-3 # sec
dt = 1e-3 # sec
snu_l = snu_layer.SNU(n_in=1, n_out=1, l_tau=(1-dt/tau),
soft=False, initial_bias=-V_th)
snu_l.Wx.W = Variable(np.array([[1.0]], dtype=np.float32))
""" Generate Poisson Spike Trains """
fr = 100 # Hz
x = np.where(np.random.rand(1, num_time) < fr*dt, 1, 0)
x = np.expand_dims(x, 0).astype(np.float32)
""" Simulation """
s_arr = np.zeros(num_time) # array to save membrane potential
y_arr = np.zeros(num_time) # array to save output
for i in range(num_time):
y = snu_l(x[:, :, i])
s_arr[i] = snu_l.s.array
y_arr[i] = y.array
""" Plot results """
plt.figure(figsize=(6,6))
plt.subplot(3,1,1)
plt.title("Spiking Neural Unit")
plt.plot(x[0,0])
plt.ylabel("Input")
plt.subplot(3,1,2)
plt.plot(s_arr)
plt.ylabel('Membrane\n Potential')
plt.subplot(3,1,3)
plt.plot(y_arr)
plt.ylabel("Output")
plt.xlabel("Time (ms)")
plt.tight_layout()
plt.savefig(img_save_dir+"Check_SNU_result.png")<file_sep># -*- coding: utf-8 -*-
import numpy
from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class Step(function_node.FunctionNode):
"""Step function."""
def check_type_forward(self, in_types):
type_check._argname(in_types, ('x',))
type_check.expect(in_types[0].dtype.kind == 'f')
def forward_cpu(self, x):
self.retain_inputs((0,))
y = utils.force_array(numpy.heaviside(x[0], 0))
self.retain_outputs((0,))
self._use_cudnn = False
return y,
def forward_gpu(self, x):
y = cuda.cupy.empty_like(x[0])
self.retain_inputs((0,))
cuda.cupy.maximum(cuda.cupy.sign(x[0]), 0, out=y)
self._use_cudnn = False
self.retain_outputs((0,))
return y,
def backward(self, indexes, grad_outputs):
x, = self.get_retained_inputs()
return PseudoStepGrad(x.data).apply(grad_outputs)
class PseudoStepGrad(function_node.FunctionNode):
def __init__(self, x):
self.x = x
def check_type_forward(self, in_types):
type_check._argname(in_types, ('gy',))
type_check.expect(
in_types[0].dtype.kind == 'f',
in_types[0].dtype == self.x.dtype
)
def forward_cpu(self, inputs):
gy, = inputs
gx = ((-0.5 < self.x) & (self.x < 0.5)) * gy * 1
return utils.force_array(gx, self.x.dtype),
def forward_gpu(self, inputs):
gy, = inputs
return cuda.elementwise(
'T x, T g', 'T gx',
'gx = fabs(x) < 0.5 ? 1 * g : 0',
'step_pseudo_bwd'
)(self.x, gy),
def backward(self, indexes, grad_outputs):
return PseudoStepGrad(self.x).apply(grad_outputs)
def step(x):
return Step().apply((x,))[0]<file_sep># -*- coding: utf-8 -*-
import os
import chainer
import numpy as np
import matplotlib.pyplot as plt
img_save_dir = "./imgs/"
os.makedirs(img_save_dir, exist_ok=True)
# Load the MNIST dataset
train, _ = chainer.datasets.get_mnist()
i = 2
y = train[i][0]
y = np.heaviside(y, 0)
label = train[i][1]
num_time = 20
fr = 100 # Hz
dt = 1e-3 # sec
y_fr = fr * np.repeat(np.expand_dims(y, 1), num_time, axis=1)
x = np.where(np.random.rand(784, num_time) < y_fr*dt, 1, 0)
sum_x = np.sum(x, axis=1)
fig = plt.figure(figsize=(6, 3))
ax1 = fig.add_subplot(1, 3, 1)
ax1.set_title("Binarized")
ax1.imshow(np.reshape(y, (28, 28)))
ax2 = fig.add_subplot(1, 3, 2)
ax2.set_title("Jittered\n (one time step)")
ax2.imshow(np.reshape(x[:, 1], (28, 28)))
ax3 = fig.add_subplot(1, 3, 3)
ax3.set_title("Jittered\n (sum all time step)")
ax3.imshow(np.reshape(sum_x, (28, 28)))
#plt.show()
plt.savefig(img_save_dir+"JitteredMNIST")<file_sep># -*- coding: utf-8 -*-
import chainer
import chainer.functions as F
#import chainer.links as L
from chainer import reporter
from . import snu_layer
#import numpy as xp
from chainer import cuda
xp = cuda.cupy
#from chainer import Variable
# Network definition
class SNU_Network(chainer.Chain):
def __init__(self, n_in=784, n_mid=256, n_out=10,
num_time=20, l_tau=0.8, soft=False, gpu=False,
test_mode=False):
super(SNU_Network, self).__init__()
with self.init_scope():
self.l1 = snu_layer.SNU(n_in, n_mid, l_tau=l_tau, soft=soft, gpu=gpu)
self.l2 = snu_layer.SNU(n_mid, n_mid, l_tau=l_tau, soft=soft, gpu=gpu)
self.l3 = snu_layer.SNU(n_mid, n_mid, l_tau=l_tau, soft=soft, gpu=gpu)
self.l4 = snu_layer.SNU(n_mid, n_out, l_tau=l_tau, soft=soft, gpu=gpu)
self.n_out = n_out
self.num_time = num_time
self.gamma = (1/(num_time*n_out))*1e-2
self.test_mode = test_mode
def _reset_state(self):
self.l1.reset_state()
self.l2.reset_state()
self.l3.reset_state()
self.l4.reset_state()
def forward(self, x, y):
loss = None
accuracy = None
sum_out = None
self._reset_state()
if self.test_mode == True:
h1_list = []
h2_list = []
h3_list = []
out_list = []
for t in range(self.num_time):
x_t = x[:, :, t]
h1 = self.l1(x_t)
h2 = self.l2(h1)
h3 = self.l3(h2)
out = self.l4(h3)
if self.test_mode == True:
h1_list.append(h1)
h2_list.append(h2)
h3_list.append(h3)
out_list.append(out)
sum_out = out if sum_out is None else sum_out + out
loss = F.softmax_cross_entropy(sum_out, y)
loss += self.gamma*F.sum(sum_out**2)
accuracy = F.accuracy(sum_out, y)
reporter.report({'loss': loss}, self)
reporter.report({'accuracy': accuracy}, self)
if self.test_mode == True:
return loss, accuracy, h1_list, h2_list, h3_list, out_list
else:
return loss
<file_sep># -*- coding: utf-8 -*-
import chainer
import chainer.functions as F
import chainer.links as L
import numpy as np
from chainer import cuda
from chainer import Parameter
from chainer import initializers
from chainer import Variable
from . import step_func
# Building Spiking Neural Unit
class SNU(chainer.Chain):
"""
Args:
n_in (int): The number of input.
n_out (int): The number of output.
l_tau (floot): Degree of leak (From 0 to 1).
soft (bool): Change output activation to sigmoid func (True)
or Step func. (False)
rec (bool): Adding recurrent connection or not.
"""
def __init__(self, n_in, n_out, l_tau=0.8, soft=False,
rec=False, nobias=False, initial_bias=None,
gpu=False):
super(SNU, self).__init__()
initializer = chainer.initializers.GlorotUniform()
with self.init_scope():
self.Wx = L.Linear(n_in, n_out, nobias=True, initialW=initializer)
if rec:
self.Wy = L.Linear(n_out, n_out, nobias=True)
if nobias:
self.b = None
else:
if initial_bias is None:
bias_initializer = initializers.Uniform()
self.b = Parameter(bias_initializer, n_out)
else:
bias_initializer = initializers._get_initializer(initial_bias)
self.b = Parameter(bias_initializer, n_out)
self.n_out = n_out
self.l_tau = l_tau
self.rec = rec
self.soft = soft
self.gpu = gpu
self.s = None
self.y = None
def reset_state(self, s=None, y=None):
self.s = s
self.y = y
def initialize_state(self, shape):
if self.gpu:
xp = cuda.cupy
else:
xp = np
self.s = initializers.generate_array(initializers.Normal(), (shape[0], self.n_out),
xp, dtype=xp.float32)
self.y = Variable(xp.zeros((shape[0], self.n_out), dtype=xp.float32))
def __call__(self, x):
if self.s is None:
self.initialize_state(x.shape)
if self.rec:
s = F.elu(self.Wx(x) + self.Wy(self.y) + self.l_tau * self.s * (1 - self.y))
else:
s = F.elu(self.Wx(x) + self.l_tau * self.s * (1 - self.y))
if self.soft:
y = F.sigmoid(F.bias(s, self.b))
else:
y = step_func.step(F.bias(s, self.b))
#y = F.relu(F.sign(F.bias(s, self.b)))
self.s = s
self.y = y
return y<file_sep># -*- coding: utf-8 -*-
""" Analysis. """
import os
import argparse
import chainer
from chainer import serializers
from chainer import cuda
#import chainer.functions as F
xp = cuda.cupy
from model import network
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
def load_data(N=1, dt=5e-3, num_time=20, max_fr=60):
""" geneate input data. """
_, test = chainer.datasets.get_mnist()
x = np.zeros((N, 784, num_time)) # 784=28x28
y = np.zeros(N)
for i in tqdm(range(N)):
fr = max_fr * np.repeat(np.expand_dims(np.heaviside(test[i][0],0), 1), num_time, axis=1)
x[i] = np.where(np.random.rand(784, num_time) < fr*dt, 1, 0)
y[i] = test[i][1]
return x.astype(np.float32), y.astype(np.int8)
def plot_activation(model, N, dt, num_time, n_mid,
n_out, max_fr, gpu, savefigname):
x, y = load_data(N=N, dt=dt, num_time=num_time, max_fr=max_fr)
idx = 0
check_x = np.sum(x[idx], axis=1)
fig = plt.figure(figsize=(6, 4))
ax1 = fig.add_subplot(1, 2, 1)
ax1.set_title("Sum of all input spikes\n label : "+str(y[idx]))
ax1.imshow(np.reshape(check_x, (28, 28)))
if gpu >= 0:
cuda.get_device_from_id(0).use()
model.to_gpu()
x = cuda.cupy.array(x)
y = cuda.cupy.array(y)
with chainer.using_config('train', False):
loss, accuracy, h1_list, h2_list, h3_list, out_list = model(x, y)
h1_all = np.zeros((num_time, N, n_mid))
h2_all = np.zeros((num_time, N, n_mid))
out_all = np.zeros((num_time, N, n_out))
for i in tqdm(range(num_time), desc="Getting activation"):
h1_all[i] = cuda.to_cpu(h1_list[i].data)
h2_all[i] = cuda.to_cpu(h2_list[i].data)
out_all[i] = cuda.to_cpu(out_list[i].data)
t = np.arange(1, num_time+1)*dt*1000
"""
plt.figure(figsize=(4,4))
plt.ylim(-0.5, n_mid-0.5)
plt.ylabel("# Unit")
plt.xlabel("Simulation Time(ms)")
for i in range(n_mid):
spk = np.where(h1_all[:, idx, i]==1, i, -1)
plt.scatter(t, spk, color="r",
s=0.1)
plt.savefig("h1.png")
plt.figure(figsize=(4,4))
plt.ylim(-0.5, n_mid-0.5)
plt.ylabel("# Unit")
plt.xlabel("Simulation Time(ms)")
for i in range(n_mid):
spk = np.where(h2_all[:, idx, i]==1, i, -1)
plt.scatter(t, spk, color="r",
s=0.1)
plt.savefig("h2.png")
"""
ax2 = fig.add_subplot(1, 2, 2)
ax2.set_title("Spikes of the output units")
ax2.set_ylabel("Output unit #")
ax2.set_xlabel("Simulation Time(ms)")
ax2.set_ylim(-0.5, n_out-0.5)
ax2.set_xlim(0, num_time+1)
ax2.set_yticks(np.arange(0, n_out).tolist())
for i in range(n_out):
spk = np.where(out_all[:, idx, i]==1, i, -1)
ax2.scatter(t, spk, color="r", marker="|")
plt.tight_layout()
plt.savefig(savefigname)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', '-g', type=int, default=-1,
help='GPU number to training.')
parser.add_argument('--model', '-m', type=str, default='./results/model',
help='Load saved model (model filename).')
parser.add_argument('--batch', '-b', type=int, default=32,
help='Mini batch size.')
parser.add_argument('--epoch', '-e', type=int, default=100,
help='Total training epoch.')
parser.add_argument('--dt', '-dt', type=int, default=1e-3,
help='Simulation time step size (sec).')
parser.add_argument('--ndata', '-nd', type=int, default=1,
help='The number of analysis trials.')
parser.add_argument('--freq', '-f', type=float, default=100,
help='Input signal maximum frequency (Hz).')
parser.add_argument('--time', '-t', type=int, default=100,
help='Total simulation time steps.')
args = parser.parse_args()
img_save_dir = "./imgs/"
os.makedirs(img_save_dir, exist_ok=True)
n_mid = 256
n_out = 10
chainer.global_config.autotune = True
if args.gpu >= 0:
# Make a specified GPU current
model = network.SNU_Network(n_in=784, n_mid=n_mid, n_out=n_out,
num_time=args.time, gpu=True,
test_mode=True)
chainer.backends.cuda.get_device_from_id(args.gpu).use()
model.to_gpu() # Copy the model to the GPU
else:
model = network.SNU_Network(n_in=784, n_mid=n_mid, n_out=n_out,
num_time=args.time, gpu=False,
test_mode=True)
if args.model != None:
print( "Loading model from " + args.model)
serializers.load_npz(args.model, model)
plot_activation(model=model, N=args.ndata, dt=args.dt,
num_time=args.time, n_mid=n_mid,
n_out=n_out,
max_fr=args.freq, gpu=args.gpu,
savefigname=img_save_dir+"results.png")
if __name__ == '__main__':
main()
<file_sep># -*- coding: utf-8 -*-
import argparse
import chainer
from chainer import training
from chainer.training import extensions
from chainer import iterators, optimizers, serializers
import numpy as np
from chainer import dataset
from tqdm import tqdm
from chainer import cuda
xp = cuda.cupy
#import matplotlib.pyplot as plt
from model import network
np.random.seed(seed=0)
class LoadDataset(dataset.DatasetMixin):
def __init__(self, N=60000, dt=1e-3, num_time=100, max_fr=60):
train, _ = chainer.datasets.get_mnist()
x = np.zeros((N, 784, num_time)) # 784=28x28
y = np.zeros(N)
for i in tqdm(range(N)):
fr = max_fr * np.repeat(np.expand_dims(np.heaviside(train[i][0],0), 1), num_time, axis=1)
x[i] = np.where(np.random.rand(784, num_time) < fr*dt, 1, 0)
y[i] = train[i][1]
self.x = x.astype(np.float32)
self.y = y.astype(np.int8)
self.N = N
def __len__(self):
return self.N
def get_example(self, i):
return self.x[i], self.y[i]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', '-g', type=int, default=-1)
parser.add_argument('--model', '-m', type=str, default=None)
parser.add_argument('--batch', '-b', type=int, default=128)
parser.add_argument('--epoch', '-e', type=int, default=100)
parser.add_argument('--ndata', '-nd', type=int, default=60000,
help='The number of analysis trials (<=60000).')
parser.add_argument('--time', '-t', type=int, default=10,
help='Total simulation time steps.')
parser.add_argument('--dt', '-dt', type=float, default=1e-3,
help='Simulation time step size (sec).')
parser.add_argument('--freq', '-f', type=float, default=100,
help='Input signal maximum frequency (Hz).')
parser.add_argument('--lr', '-l', type=float, default=1e-4)
parser.add_argument('--noplot', dest='plot', action='store_false',
help='Disable PlotReport extension')
args = parser.parse_args()
print("Loading datas")
dataset = LoadDataset(N=args.ndata, dt=args.dt,
num_time=args.time, max_fr=args.freq)
#plt.imshow(np.reshape(dataset[1][0][:, 0], (28, 28)))
#plt.show()
val_rate = 0.2
split_at = int(len(dataset) * (1-val_rate))
train, val = chainer.datasets.split_dataset(dataset, split_at)
train_iter = iterators.SerialIterator(train, batch_size=args.batch, shuffle=True)
test_iter = iterators.SerialIterator(val, batch_size=args.batch, repeat=False, shuffle=False)
chainer.global_config.autotune = True
# Set up a neural network to train.
print("Building model")
if args.gpu >= 0:
# Make a specified GPU current
model = network.SNU_Network(n_in=784, n_mid=256, n_out=10,
num_time=args.time, gpu=True)
chainer.backends.cuda.get_device_from_id(args.gpu).use()
model.to_gpu() # Copy the model to the GPU
else:
model = network.SNU_Network(n_in=784, n_mid=256, n_out=10,
num_time=args.time, gpu=False)
optimizer = optimizers.Adam(alpha=args.lr)
#optimizer = optimizers.SGD(lr=args.lr)
#optimizer = optimizers.RMSprop(lr=args.lr, alpha=0.9)
optimizer.setup(model)
optimizer.add_hook(chainer.optimizer_hooks.WeightDecay(1e-4))
if args.model != None:
print( "loading model from " + args.model)
serializers.load_npz(args.model, model)
updater = training.StandardUpdater(train_iter, optimizer, device=args.gpu)
trainer = training.Trainer(updater, (args.epoch, 'epoch'), out='results')
trainer.extend(extensions.Evaluator(test_iter, model, device=args.gpu))
trainer.extend(extensions.LogReport(trigger=(100, 'iteration')))
# Snapshot
trainer.extend(extensions.snapshot_object(model, 'model_snapshot_{.updater.epoch}'),
trigger=(1,'epoch'))
trainer.extend(extensions.ExponentialShift('alpha', 0.5),trigger=(5, 'epoch'))
# Save two plot images to the result dir
if args.plot and extensions.PlotReport.available():
trainer.extend(
extensions.PlotReport(['main/loss', 'validation/main/loss'],
'epoch', file_name='loss.png'), trigger=(1, 'epoch'))
trainer.extend(
extensions.PlotReport(
['main/accuracy', 'validation/main/accuracy'],
'epoch', file_name='accuracy.png'), trigger=(1, 'epoch'))
trainer.extend(extensions.PrintReport(
['epoch', 'main/loss', 'validation/main/loss',
'main/accuracy', 'validation/main/accuracy', 'elapsed_time']), trigger=(1, 'iteration'))
trainer.extend(extensions.ProgressBar(update_interval=1))
# Train
trainer.run()
# Save results
print("Optimization Finished!")
modelname = "./results/model"
print( "Saving model to " + modelname)
serializers.save_npz(modelname, model)
if __name__ == '__main__':
main()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 12:57:00 2019
@author: yamamoto
"""
|
c48e26ce1c1bc7e5b5def38b967be5ac3dc6a9e0
|
[
"Markdown",
"Python"
] | 9
|
Markdown
|
takyamamoto/SNU_Chainer
|
124a81fd625b42fa530574c5c8a163946147a8d8
|
39742dfc2f46b3d67608093c3fe5c3d9f4d166ed
|
refs/heads/master
|
<repo_name>AyuJ01/forsk<file_sep>/day12/Ayushi_Jain_38.py
# -*- coding: utf-8 -*-
"""
Created on Mon May 28 22:48:56 2018
@author: Ayushi
"""
import numpy as np
import matplotlib.pyplot as plt
incomes = np.random.normal(150, 20, 1000)
print(plt.hist(incomes,100))
print('std ',np.std(incomes))
print('var ',np.var(incomes))
<file_sep>/day6/sub1 PANGRAM.py
alpha = "abcdefghijklmnopqrstuvwxyz "
str1= input().lower()
flag=0
for ch in alpha:
if ch not in str1:
flag=1
break
if flag==0:
print("PANGRAM")
else:
print("NOT PANGRAM")<file_sep>/day16 regression/Ayushi_Jain_51.py
# -*- coding: utf-8 -*-
"""
Created on Thu May 31 11:26:07 2018
@author: Ayushi
"""
#read csv
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
df = pd.read_csv("Bahubali2_vs_Dangal.csv")
features = df.iloc[:,0:1].values
label1 = df.iloc[:,1:2].values
label2 = df.iloc[:,2:].values
#predict for bahubali2
#splitting the data
features_train1,features_test1,labels_train1,labels_test1 = train_test_split(features,label1,test_size=0.2,random_state=0)
#fitting the linear regression to training set
regressor = LinearRegression()
regressor.fit(features_train1,labels_train1)
#predicting the test result
label1_predict = regressor.predict(features_test1)
#Model score
score = regressor.score(features_test1,labels_test1)
#Visulaizing the training set result
plt.scatter(features_train1,labels_train1,color='red')
plt.plot(features_train1,regressor.predict(features_train1),color='blue')
plt.title("day v/s collections of Bahubali-2 graph")
plt.xlabel("Day")
plt.ylabel("Collections")
plt.show()
plt.close()
#predict the 10th day collections of balubali2
bahu_10 = regressor.predict(10)
print("10th day collections of bahubali-2 in crore is : ",bahu_10)
#predict for dangal
#splitting the data
features_train2,features_test2,labels_train2,labels_test2 = train_test_split(features,label2,test_size=0.2,random_state=0)
#fitting the linear regression to training set
regressor2 = LinearRegression()
regressor2.fit(features_train2,labels_train2)
#predicting the test result
label2_predict = regressor2.predict(features_test2)
#Model score
score = regressor2.score(features_test2,labels_test2)
#Visulaizing the training set result
plt.scatter(features_train2,labels_train2,color='green')
plt.plot(features_train2,regressor2.predict(features_train2),color='yellow')
plt.title("day v/s collections of Dangal graph")
plt.xlabel("Day")
plt.ylabel("Collections")
plt.show()
plt.close()
#predict the 10th day collections of balubali2
dangal_10 = regressor2.predict(10)
print("10th day collections of dangal in crore is : ",dangal_10)
plt.plot(features,label1,color='green',label="Bahubali 2")
plt.plot(features,label2,color='red', label="Dangal")
plt.scatter(10,regressor.predict(10),color='green')
plt.scatter(10,regressor2.predict(10),color='red')
plt.title("day v/s collections of Dangal graph")
plt.xlabel("Day")
plt.ylabel("Collections")
plt.legend()
plt.show()
<file_sep>/day7/Ayushi_Jain_23.py
# -*- coding: utf-8 -*-
"""
Created on Fri May 18 12:30:39 2018
@author: Ayushi
"""
import facebook as fb
import PIL
# Facebook Graphic Explorer API user Access Token
access_token = "<KEY>"
# Message to post as status on Facebook
status = "Hello..!!"
# Authenticating
graph = fb.GraphAPI(access_token)
# Posting Status on your wall
post_id = graph.put_wall_post(status)
img = PIL.Image.open("img2.jpg")
post_id1 = graph.put_photo(image = open('k.jpg','rb'),message = "Memories :-* ")
<file_sep>/day4/sub4 dict.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 15 11:56:55 2018
@author: Ayushi
"""
dict1={}
keys=['<KEY>']
dict1['a']=int(input("Enter element a : "))
dict1['b']=int(input("Enter element b : "))
dict1['c']=int(input("Enter element c : "))
print(dict1)
count=0
def fix_teen(dict1):
count=0
for num in dict1.values():
if num in range(13,20):
if num==15 or num==16:
count=count+num
else:
count=count+0
else:
count=count+num
return count
print ("Sum = ",fix_teen(dict1))
"""
for num in dict1.values():
fix_teen(num)
print(count)
"""
"""
for num in dict1.values():
if num in range(13,20):
if num==15 or num==16:
count=count+num
else:
count=count+0
else:
count=count+num
print(count)
"""<file_sep>/day12/Ayushi_Jain_37.py
# -*- coding: utf-8 -*-
"""
Created on Fri May 25 11:06:45 2018
@author: Ayushi
"""
import numpy as np
import matplotlib.pyplot as plt
incomes = np.random.normal(100.0, 20.0, 10000)
print(plt.hist(incomes,50))
print('mean',np.mean(incomes))
print('median',np.median(incomes))
incomes = np.append(incomes,10000000)
print(incomes)
print('mean',np.mean(incomes))
print('median',np.median(incomes))<file_sep>/day26 k-folds classifier/Ayushi_Jain_66.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 15 12:57:50 2018
@author: Ayushi
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv("banknotes.csv")
features = df.iloc[:,1:-1].values
labels = df.iloc[:,-1:].values
#features Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
features = sc.fit_transform(features)
#splitting the data
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#Logistic Regression #score=95
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state=0)
classifier.fit(features_train,labels_train)
pred = classifier.predict(features_test)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(labels_test,pred)
score = classifier.score(features_test,labels_test)
# Applying k-Fold Cross Validation
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(estimator = classifier, X = features_train, y = labels_train, cv = 10)
print ("mean accuracy is",accuracies.mean())
print (accuracies.std())
<file_sep>/day22 decision tree and random forest classifier/Ayushi_Jain_59_a.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 10:21:21 2018
@author: Ayushi
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv("tree_addhealth.csv")
for i in df:
df[i] = df[i].fillna(df[i].mode()[0])
features = df.iloc[:,:-9]
labels = features.iloc[:,7:8].values
features = features.drop(df.columns[7], axis=1)
features = features.iloc[:,:].values
#split into training set and testing set
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#features scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
features_train = sc.fit_transform(features_train)
features_test = sc.transform(features_test)
#fitting decision tree classifier to dataset
from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion = 'entropy',random_state=0)
classifier.fit(features_train,labels_train)
labels_pred = classifier.predict(features_test)
score = classifier.score(features_test,labels_test)
#making the confusion matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(labels_test,labels_pred)
<file_sep>/Practice questions/horroscope prediction.py
# -*- coding: utf-8 -*-
"""
Created on Thu May 31 10:08:08 2018
@author: Ayushi
"""
import urllib
sign='0'
sun = input("Enter your zodiac sign: ").lower()
if sun== "aries":
sign='1'
if sun == "taurus":
sign='2'
elif sun== "gemini":
sign='3'
elif sun== "cancer":
sign='4'
elif sun== "leo":
sign='5'
elif sun== "virgo":
sign='6'
elif sun== "libra":
sign='7'
elif sun== "scorpio":
sign='8'
elif sun== "sagittarius":
sign='9'
elif sun== "capricorn":
sign='10'
elif sun== "aquarius":
sign='11'
elif sun== "pisces":
sign='12'
hor = "https://www.horoscope.com/us/horoscopes/general/horoscope-general-daily-today.aspx?sign="+sign
page = urllib.request.urlopen(hor)
from bs4 import BeautifulSoup as bs
soup = bs(page)
all_para = soup.find_all('div')
right_para = soup.find('div',class_='horoscope-content')
A= []
p= right_para.find("p")
A.append(p.text.strip())
s = ''.join(A)
print(s)
import twitter
api = twitter.Api(consumer_key="4An2yCQnINz57RC3e3vefArs5",consumer_secret="<KEY>",access_token_key="<KEY>",access_token_secret="<KEY>")
st = api.PostUpdates(s)<file_sep>/day19 decision tree & Random forest regressor/Ayushi_Jain_56.py
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 11:56:40 2018
@author: Ayushi
"""
#read file
import pandas as pd
df = pd.read_csv('Auto_mpg.txt', delim_whitespace=True, header=None)
df.columns = ["mpg", "cylinders", "displacement","horsepower","weight","acceleration", "model year", "origin", "car name" ]
high_mpg = max(df.iloc[:,0].values)
loc = df[df['mpg'] == 46.6].index.tolist()
car = df.iloc[322,-1]
print("car with highest mpg is : ",car)
#handle missing values
df["horsepower"][df["horsepower"]=='?'] = df["horsepower"].mode()[0]
df['horsepower'] = df['horsepower'].convert_objects(convert_numeric=True)
#split into labels and features
features = df.iloc[:,1:-1].values
labels = df.iloc[:,0:1].values
#split into training set and testing set
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
"""
#Decisiion tree regressor
from sklearn.tree import DecisionTreeRegressor
regressor = DecisionTreeRegressor(random_state=0)
regressor.fit(features_train,labels_train)
labels_pred_1 = regressor.predict(features_test)
score_1 = regressor.score(features_test,labels_test)
#fitting random forest regression
from sklearn.ensemble import RandomForestRegressor
reg = RandomForestRegressor(n_estimators=200,random_state=0)
reg.fit(features_train,labels_train)
labels_pred_2 = reg.predict(features_test)
score_2 = reg.score(features_test,labels_test)
#predicting the result
import numpy as np
pred1 = regressor.predict(np.array([6,215,100,2630,22.2,80,3]).reshape(1,-1))
pred2 = reg.predict(np.array([6,215,100,2630,22.2,80,3]).reshape(1,-1))
print("prediction from decision tree : ",pred1)
print("prediction from random forest : ",pred2)
"""
###
#features scaling
import numpy as np
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
features_train = sc.fit_transform(features_train)
features_test = sc.transform(features_test)
value = np.array([6,215,100,2630,22.2,80,3]).reshape(1,-1)
value = sc.transform(value)
#Decisiion tree regressor
from sklearn.tree import DecisionTreeRegressor
regressor1 = DecisionTreeRegressor(random_state=0)
regressor1.fit(features_train,labels_train)
labels_pred_3 = regressor1.predict(features_test)
score_3 = regressor1.score(features_test,labels_test)
#fitting random forest regression
from sklearn.ensemble import RandomForestRegressor
reg1 = RandomForestRegressor(n_estimators=200,random_state=0)
reg1.fit(features_train,labels_train)
labels_pred_4 = reg1.predict(features_test)
score_4 = reg1.score(features_test,labels_test)
#predicting the result
pred3 = regressor1.predict(value)
pred4 = reg1.predict(value)
print("prediction from decision tree : ",pred3)
print("prediction from random forest : ",pred4)
<file_sep>/day22 decision tree and random forest classifier/Ayushi_Jain_59_c.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 12:12:06 2018
@author: Ayushi
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv("tree_addhealth.csv")
for i in df:
df[i] = df[i].fillna(df[i].mode()[0])
features = df.iloc[:,1:6].values
labels = df.iloc[:,7].values
#split into training set and testing set
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#fitting random forest Classifier to the training set
from sklearn.ensemble import RandomForestClassifier as rf
classifier = rf(n_estimators = 10,criterion = 'entropy',random_state = 0)
classifier.fit(features_train,labels_train)
#predicting the test set results
labels_pred = classifier.predict(features_test)
score = classifier.score(features_test,labels_test)
#making the confusion matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(labels_test,labels_pred)
<file_sep>/day17 multiple regression/Ayushi_Jain_52.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 1 11:14:54 2018
@author: Ayushi
"""
import numpy as np
#read csv
import pandas as pd
df = pd.read_csv("iq_size.csv")
features = df.iloc[:,1:].values
labels = df.iloc[:,0].values
#splitting the dataset
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#fitting multiple regression to training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(features_train,labels_train)
#predicting the test set result
labels_pred = regressor.predict(features_test)
#getting score for multiple value regressor model
score = regressor.score(features_test,labels_test)
#calculate the IQ
iq_predict = regressor.predict(np.array([90,70,150]).reshape(1,-1))
print("Predicted IQ value is : ",iq_predict)
#Building the optimal model using backward elimination
import statsmodels.formula.api as sm
features = np.append(arr = np.ones((38,1)).astype(int),values = features,axis=1)
features_opt = features[:,[0,1,2,3]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
features_opt = features[:,[0,1,2]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
features_opt = features[:,[1,2]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
features_opt = features[:,[1]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
<file_sep>/Practice questions/Avg score of student in dict.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 6 00:20:58 2018
@author: Ayushi
"""
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
a = student_marks.get(query_name)
f = sum(a)/len(a)
f1 = round(f, 2)
print("%.2f" % f)
<file_sep>/day4/functions.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 15 10:44:56 2018
@author: Ayushi
"""
from functools import reduce
def explain_python():
"""Print a msg explaing what a python is"""
print("Python is not a snake")
print("python is a programming language")
explain_python()
explain_python.__doc__
#in python 2 explain_python.func_doc #display doc string
"""Filter function"""
def f(x): return x%3 == 0 or x%5 == 0
a = filter(f,range(2,25))
list(a)
"""Map function"""
def cube(x): return x*x*x
b = map(cube,range(1,11))
list(b)
"""reduce function"""
def add(x,y): return x+y
reduce(add,range(1,11))
"""lambda function"""
list(map(lambda x: x*x*x,range(1,11)))
"""Nested List comprehension"""
a=[1,2,3]
[x**2 for x in a]
[x+1 for x in [x**2 for x in a]]
"""length of character"""
words=['it','is','raining','cat','dog']
list(map(lambda x:len(x),words))
<file_sep>/day6/sub3 REST APIs.py
"""
import urllib
f= urllib.request.urlopen("http://13.127.155.43/api_v0.1/sending")
"""
import requests
#r = requests.urllib3.get_host("http://13.127.155.43/api_v0.1/sending")
#r+="?q=Phone_Number"
d = {
'Phone_Number' : '7894561230',
'Name' : 'Ayushi',
'College_Name' : 'PIET',
'Branch' : 'CS'
}
resp = requests.post("http://13.127.155.43/api_v0.1/sending",json = d)
print (resp.text)
url = "http://13.127.155.43/api_v0.1/receiving"
url += "?Phone_Number=7894561230"
r = requests.get(url)
print(r.text)
"""
#Method 2
import requests
import json
#r = requests.urllib3.get_host("http://13.127.155.43/api_v0.1/sending")
#r+="?q=Phone_Number"
d = {
'Phone_Number' : "7894561230",
'Name' : 'Ayushi',
'College_Name' : 'PIET',
'Branch' : 'CSE'
}
d = json.dumps(d)
resp = requests.post("http://13.127.155.43/api_v0.1/sending",data = d,headers={"Content-Type":"application/json"})
print (resp.text)
url = "http://13.127.155.43/api_v0.1/receiving"
url += "?Phone_Number=7894561230"
r = requests.get(url)
print(r.text)
"""<file_sep>/Practice questions/2nd max value.py
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 19:05:18 2018
@author: Ayushi
"""
arr = list(map(int, input().split()))
maxi = max(arr)
val=min(arr)
len(arr)
for i in range(0,len(arr)):
#if val!=maxi:
if arr[i]>val and arr[i]!=maxi:
val = arr[i]
print(val)
<file_sep>/day5/sub2 string translate.py
str11=input()
def translate(str1):
vowel="aeiou "
ch=0
str2=""
while(ch<len(str1)):
if str1[ch] in vowel:
str2=str2+str1[ch]
ch=ch+1
else:
str2= str2+str1[ch]+"o"+str1[ch]
ch=ch+1
return str2
print(translate(str11))
"""
Approach 2
vol = 'aeiouAEIOU '
print (''.join(i+"o"+i if i not in vol else i for i in str11))
"""
"""
approach 3
lst=[]
for i in str11:
if i in vol:
lst.append(i)
else:
lst.append(i+"o"+i)
print (''.join(lst))
"""
<file_sep>/day7/json.py
[
{
"First Name" : "Shruti",
"Last Name" : "Bijawat",
"Photo" : " " ,
"Department" : "CS",
"Research Areas" : ["Networking","image proocessing"],
"Contact Details" : ["9874563210","<EMAIL>"]
},
{
"First Name" : "Ajay",
"Last Name" : "saini",
"Photo" : " " ,
"Department" : "EC",
"Research Areas" : ["Iot","robotics"],
"Contact Details" : ["6321098745","<EMAIL>"]
},
{
"First Name" : "Pooja",
"Last Name" : "Sharma",
"Photo" : " " ,
"Department" : "IT",
"Research Areas" : ["deep learning"],
"Contact Details" : ["9856321074","<EMAIL>"]
}
]<file_sep>/day24 PCA principle component analysis/Ayushi_Jain_63.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 11:10:53 2018
@author: Ayushi
"""
#import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#read csv
df = pd.read_csv("crime_data.csv")
X = df.iloc[:,[1,2,4]].values
"""
#features Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X = sc.fit_transform(X)
"""
#PCA principle component Analysis
from sklearn.decomposition import PCA
"""
#explains the value of n_components
///only with high explained_variance are used
pca = PCA(n_components=None)
X = pca.fit_transform(X)
explained_variance = pca.explained_variance_ratio_
"""
pca = PCA(n_components=2)
X = pca.fit_transform(X)
explained_variance = pca.explained_variance_ratio_
#using the elbow method to find the optimal no. of clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
kmeans = KMeans(n_clusters = i,init = 'k-means++',random_state = 0)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
plt.plot(range(1,11),wcss)
plt.title("The Elbow Method")
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()
#fitting K-Means to the dataset with 4 clusters
kmeans = KMeans(n_clusters = 3,init = 'k-means++',random_state= 0)
y_kmeans = kmeans.fit_predict(X)
#Visulaing the clusters
plt.scatter(X[y_kmeans == 0,0],X[y_kmeans == 0,1],s = 100, c = 'red',label = 'Murder')
plt.scatter(X[y_kmeans == 1,0],X[y_kmeans == 1,1],s = 100, c = 'blue',label = 'Assault')
plt.scatter(X[y_kmeans == 2,0],X[y_kmeans == 2,1],s = 100, c = 'green',label = 'Rape')
plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1], s=300, c = 'yellow',label='Centroids')
plt.title("clusters of Crime")
plt.xlabel('pc1')
plt.ylabel('pc2')
plt.legend()
plt.show()
<file_sep>/day6/max and min sum.py
# -*- coding: utf-8 -*-
"""
Created on Thu May 17 20:16:18 2018
@author: Ayushi
"""
a = [1,2,3,4,5]
mini = min(a)
a.remove(mini)
sum1 = sum(a)
a.append(mini)
a.remove(max(a))
sum2 = sum(a)
print(sum2,sum1)<file_sep>/day8/default dict.py
from collections import defaultdict
from collections import Counter #
from collections import OrderedDict
from collections import namedtuple
s= [1,5,2,3,4,1,3,5,2,4,1,3,5,1,4]
dd = defaultdict(int)
for key in s:
dd[key]+=1
print(dd)
def sump(a,b):
return a+b, a*b
s, p = sump(2,3)
print(s,p)<file_sep>/day15/Ayushi_jain_48.py
# -*- coding: utf-8 -*-
"""
Created on Wed May 30 11:19:57 2018
@author: Ayushi
"""
import pandas as pd
#import the csv and name the missing columns name
df = pd.read_csv(
'https://raw.githubusercontent.com/rasbt/pattern_classification/master/data/wine_data.csv',
header=None,
usecols=[0,1,2],
sep = ',',
names=['Class label', 'Alcohol', 'Malic acid']
)
#split the data
from sklearn.model_selection import train_test_split
features = df.iloc[:,1:3].values
labels = df.iloc[:,0].values
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size = 0.2,random_state = 0)
"""
#feature scaling // standard scaler
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
features_train = sc.fit_transform(features_train)
features_test = sc.transform(features_test)
"""
#Min-max scaling
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler()
features_train = sc.fit_transform(features_train)
features_test = sc.transform(features_test)
<file_sep>/Practice questions/name of 2nd lowest score sorted.py
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 19:28:58 2018
@author: Ayushi
"""
if __name__ == '__main__':
ln=[]
ls=[]
for _ in range(int(input())):
name = input()
score = float(input())
ln.append(name)
ls.append(score)
mins = min(ls)
#ind_maxs = ls.index(maxs)
val=max(ls)
#len(arr)
for i in range(0,len(ls)):
#if val!=maxi:
if ls[i]<val and ls[i]!=mins:
val = ls[i]
index_list = []
for k in range(0,len(ls)):
if val == ls[k]:
index_list.append(k)
name_list=[]
for n in index_list:
name_list.append(ln[n])
name_l = sorted(name_list)
for a in name_l:
print(a)<file_sep>/day11/Ayushi_Jain_36.py
import pandas as pd
df=pd.read_csv("training_titanic.csv")
df['Child']=0
df['Child'][df['Age']<18]=1
c1=df[df['Child']==1]
s=c1["Survived"].value_counts(normalize=True)
print("child survived:",s[1]*100)
c2=df[df['Child']==0]
s1=c2["Survived"].value_counts(normalize=True)
print("old survived:",s1[1]*100)
#child=df['Survived'][df['Child']==1].value_counts()[1]
s<file_sep>/day9/atm no.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 13:04:25 2018
@author: Ayushi
"""
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 11:18:39 2018
@author: Ayushi
"""
import re
# re.compile converts regex pattern to variable,
# and makes it easier to reuse
lst = []
## Search
regex = re.compile(r'^[456](\d{15}| \d{3}(-\d{4}){3})')
while True:
string1 = input()
if not string1:
break
lst.append(string1)
for i in lst:
response = regex.match(i)
conti = re.search(r"(\d)\1{4,}", i.replace('-',''))
if response and not conti:
print("Valid")
else:
print ("Invalid")
<file_sep>/day4/Ayushi_Jain.py
dict1={} #initialize an empty dictionary
keys=['<KEY>'] #assign the keys
#Read input
dict1['a']=int(input("Enter element a : "))
dict1['b']=int(input("Enter element b : "))
dict1['c']=int(input("Enter element c : "))
#Calculate the sum of values if they are not teen(13,19) or if they are 15 and 16
def fix_teen(dict1):
count=0
for num in dict1.values():
if num in range(13,20):
if num==15 or num==16:
count=count+num
else:
count=count+0
else:
count=count+num
return count
print ("Sum = ",fix_teen(dict1))
<file_sep>/day8/pallindrome.py
# -*- coding: utf-8 -*-
"""
Created on Mon May 21 12:58:45 2018
@author: Ayushi
"""
flag = 0
count=1
str1 = input()
tup1 = str1.split(' ')
l = list(map(int,tup1))
for i in l:
if i<0:
break
a= str(i)
if a == a[::-1]:
#count +=1
flag = 1
if(flag==0):
print("False")
else:
#if(count==len(l)):
# print("True")
#else:
print("True")
<file_sep>/day10/MongoDB.py
# -*- coding: utf-8 -*-
"""
Created on Wed May 23 11:19:06 2018
@author: Ayushi
"""
#import MongoClient
from pymongo import MongoClient
#set up Connection
client = MongoClient('localhost', 27017)
#provide database name
mydb = client.db_University
#insert the data into Collections
def add_client(Student_Name, Student_Age, Student_Roll_no, Student_Branch):
unique_client = mydb.University_clients.find_one({"Student Roll_no":Student_Roll_no}, {"_id":0})
if unique_client:
return "Client already exists"
else:
mydb.University_clients.insert(
{
"Student Name" : Student_Name,
"Student Age" : Student_Age,
"Student Roll_no" : Student_Roll_no,
"Student Branch" : Student_Branch
})
return "Client added successfully"
#Read data
for i in range(0,10):
Student_Name = input("Enter Student Name: ")
Student_Age = input("Enter Student Age: ")
Student_Roll_no = input("Enter Student roll no: ")
Student_Branch = input("Enter Student Branch: ")
print(add_client(Student_Name, Student_Age, Student_Roll_no, Student_Branch))
<file_sep>/day8/email verify.py
# -*- coding: utf-8 -*-
"""
Created on Mon May 21 13:07:10 2018
@author: Ayushi
"""
lst=[]
while True:
l=[]
str1 = input()
if not str1:
break
n1 = str1.find('@')
n2 = str1.find('.')
s = str1[0 : n1]
s1 = str1[n1+1:n2]
s2 = str1[n2+1:]
for ch in s:
if ch.isalnum() or ch =='_' or ch =='-':
l.append(ch)
a = ''.join(l)
if a==s:
if s1.isalnum():
if(len(s2)<4 and len(s2)>0):
lst.append(str1)
print(lst)
<file_sep>/day7/untitled4.py
# -*- coding: utf-8 -*-
"""
Created on Fri May 25 11:06:45 2018
@author: Ayushi
"""
<file_sep>/day7/Ayushi_Jain_22.py
# -*- coding: utf-8 -*-
"""
Created on Fri May 18 11:42:10 2018
@author: Ayushi
"""
import oauth2
import time
import urllib
import json
url1 = "https://api.twitter.com/1.1/search/tweets.json"
params = {
"oauth_version": "1.0",
"oauth_nonce": oauth2.generate_nonce(),
"oauth_timestamp": int(time.time())
}
consumer = oauth2.Consumer(key="API_KEY", secret="SECRET_KEY")
token = oauth2.Token(key="TOKEN_KEY", secret="TOKEN_SECRET")
params["oauth_consumer_key"] = consumer.key
params["oauth_token"] = token.key
params["q"] = "ayushi"
req = oauth2.Request(method="GET", url=url1, parameters=params)
signature_method = oauth2.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)
url = req.to_url()
response = urllib.request.Request(url)
data = json.load(urllib.request.urlopen(response))
filename = params["q"]
f = open(filename + "_File.txt", "w") # SAVING DATA TO FILE
json.dump(data["statuses"], f)
f.close()
<file_sep>/day22 decision tree and random forest classifier/Ayushi_Jain_59_b.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 12:02:09 2018
@author: Ayushi
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 10:21:21 2018
@author: Ayushi
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df1 = pd.read_csv("tree_addhealth.csv")
for i in df1:
df1[i] = df1[i].fillna(df1[i].mode()[0])
df = df1[["BIO_SEX","VIOL1","EXPEL1"]]
features = df.iloc[:,0:2].values
labels = df.iloc[:,-1].values
#split into training set and testing set
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#fitting decision tree regressor to dataset
from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion = 'entropy',random_state=0)
classifier.fit(features_train,labels_train)
labels_pred = classifier.predict(features_test)
score = classifier.score(features_test,labels_test)
#making the confusion matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(labels_test,labels_pred)
<file_sep>/day21 Classification KNN/Ayushi_jain_58.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 10:59:33 2018
@author: Ayushi
"""
#import libraries
import pandas as pd
df_o = pd.read_csv("mushrooms.csv")
df = df_o.iloc[:,[0,5,-2,-1]]
#handle Categorical data
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
df["class"] = labelencoder.fit_transform(df["class"])
df = pd.get_dummies(df, columns=['odor'])
df = df.drop(df.columns[-1], axis=1)
df = pd.get_dummies(df, columns=['population'])
df = df.drop(df.columns[-1], axis=1)
df = pd.get_dummies(df, columns=['habitat'])
df = df.drop(df.columns[-1], axis=1)
features = df.iloc[:,1:].values
labels = df.iloc[:,0:1].values
#spliting the data
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,lebels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#fittig KNN to training set
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5,p=2)
knn.fit(features_train,labels_train)
pred = knn.predict(features_test)
#Making the confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(lebels_test,pred)
score = knn.score(features_test,lebels_test)
print("Accuracy of the model is: ",score*100,"%")
<file_sep>/day4/sub1 functions.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 15 00:24:09 2018
@author: Ayushi
"""
list1=input() #Read string
list2=list1.split(',') #split it into list
list3=list(map(int,list2)) #convert list into integer
#print(list3)
def add(l):
a = sum(l) #calculate sum of list
return(a)
def multiply(l):
m=1
for i in l:
m=m*i #multiply list
return m
def largest(l):
return max(l) #find maximum among list
def smallest(l):
return min(l) #find minimum among list
def sort(l):
#a=l.sort
return(sorted(l)) #sort the list
def remove_duplicates(l):
return(list(set(l))) #remove duplicates from the list
def display():
print("Sum = ",add(list3))
print("Multiply = ",multiply(list3))
print("Largest = ",largest(list3))
print("Smallest = ",smallest(list3))
print("Sorted = ",sort(list3))
print("Without Duplicates = ",remove_duplicates(list3))
display() #call display function<file_sep>/day3/submission/sub3.py
# -*- coding: utf-8 -*-
"""
Created on Mon May 14 10:11:52 2018
@author: Ayushi
"""
string1 = input("Enter the String") #Read the string
dict1={} #initialize an empty dictionary
for element in string1: #for each element in string1
if element in dict1.keys(): #if element is already present in the dictionary
dict1[element]+=1 #then increase its value
else: #else if element is not present
dict1[element]=1 #then add it to dictionary with value 1
print(dict1) #print dictionary<file_sep>/day8/Ayushi_Jain_25.py
list1= [] #Empty List
while True:
str1 = input() #Read Input
if not str1:
break
tup1 = str1.split(',')
list1.append((tup1[0],int(tup1[1]),int(tup1[2])))
sorted(list1)
<file_sep>/day8/sort list.py
list1= []
while True:
str1 = input()
if not str1:
break
tup1 = str1.split(',')
list1.append((tup1[0],int(tup1[1]),int(tup1[2])))
sorted(list1)
"""
list1= []
while True:
str1 = input()
if not str1:
break
tup1 = str1.split(',')
if tup1[2].isdigit() and tup1[1].isdigit():
list1.append((tup1[0],(tup1[1]),(tup1[2])))
if(tup[1] = isdigit()):
sorted(list1)
"""<file_sep>/day1/untitled0.py
# -*- coding: utf-8 -*-
"""
Created on Thu May 10 10:23:10 2018
@author: Ayushi
"""
str1 = "Hi from fine folks of forsk"
print(str1[4:])
print(str1[:15])
str2="Jaipur India"
print(str1,str2)
import math
print(math.log(16,2))
print(math.cos(0))
type(7)
#type 7#
type(1.25)
type('Hello')
len('abcd')
str(23)
int('125')
14/4
14//4
14%4
23%5
20%5
6//8
6%8
"hello"
'HI!'
'very'+'hot'
3*'very'
x=3
y=5
print('The sum of',x,'plus',y,'is',x+y)
print('a\nb\n\nc')
name=input("Enter Name" )
age=input("Enter age")
print(name)
print(age)
<file_sep>/day1/submission/sub4.py
str=input("Enter string: ") #Read string
a=str.split() #split the string with space
a=a[::-1] #reverse the list
print(' '.join(a)) #join the list
<file_sep>/Practice questions/diagonal difference.py
# -*- coding: utf-8 -*-
"""
Created on Thu May 17 18:56:23 2018
@author: Ayushi
"""
n=int(input())
i=0
lst = []
while i<n:
lst.append(list(map(int,input().rstrip().split())))
i+=1
#print(lst)
l = len(lst)
sum1=0
sum2=0
a=0
while a<l:
sum1=sum1+lst[a][a]
a=a+1
print(sum1)
b=0
while l>0:
sum2 = sum2+lst[b][l-1]
l-=1
b+=1
print(sum2)
sumf = abs(sum1-sum2)
print(sumf)<file_sep>/Practice questions/12 hr to 24 hr.py
str1 = input()
if 'AM' in str1 :
i = str1.find('AM')
str2 = str1[:i]
if ord(str1[0])==49 and ord(str1[1])==50:
y1 = chr(ord(str1[0]) - 1)
y2 = chr(ord(str1[1]) - 2)
y = str2.replace('12','00',1)
if 'PM' in str1 :
i = str1.find('PM')
str2 = str1[:i]
if ord(str2[0])==48 :
if ord(str2[1])<56:
y2 = chr(ord(str1[1]) + 2)
y = str2.replace('0','1',1)
y = y.replace(str2[1],y2,1)
else:
y2 = chr(ord(str1[1]) - 8)
y = str2.replace('0','2',1)
y = y.replace(str2[1],y2,1)
if ord(str2[0])==49 :
if ord(str2[1])== 50:
y=str2
else:
y2 = chr(ord(str1[1]) + 2)
y = str2.replace('1','2',1)
y = y.replace(str2[1],y2,1)
print(y)<file_sep>/day6/Ayushi_Jain_21.py
#Using requests and json library
import requests
import urllib
import json
#define dictionary
data = {
'Phone_Number' : "7894561230",
'Name' : '<NAME>',
'College_Name' : 'PIET',
'Branch' : 'CSE'
}
#convert json data into dictionary format
d = json.dumps(data)
####
"""
data1 ={
'Phone_Number' : "1234567890",
'Name' : 'Ayushi',
'College_Name' : 'PIET',
'Branch' : 'CS'
}
data1 = bytes( urllib.parse.urlencode( data1 ).encode() )
handler = urllib.request.urlopen( "http://13.127.155.43/api_v0.1/sending", data1 )
print( handler.read().decode( 'utf-8' ) )
import json
data = json.dumps(data1)
header = {"Content-Type":"application/json"}
req = urllib.request.Request("http://13.127.155.43/api_v0.1/sending", data=data,headers=header) # this will make the method "POST"
resp = urllib.request.urlopen(req)
print(resp.read().decode( 'utf-8' ))
###
"""
#Post request to REST API url
resp = requests.post("http://13.127.155.43/api_v0.1/sending",data = d,headers={"Content-Type":"application/json"})
print (resp.text) #print the server response
#REST API url
url = "http://13.127.155.43/api_v0.1/receiving"
url += "?Phone_Number=7894561230"
r = requests.get(url) #get request to REST API
print(r.text) #print the server response
<file_sep>/day3/submission/sub1.py
# -*- coding: utf-8 -*-
"""
Created on Mon May 14 00:23:21 2018
@author: Ayushi
"""
list1 = input("Enter numbers") #Read values
list2 = list1.split(",") #split them into new list
print(list2) #print list
print(tuple(list2)) #convert list into tuple and print it<file_sep>/day5/libraries.py
# -*- coding: utf-8 -*-
"""
Created on Wed May 16 10:58:23 2018
@author: Ayushi
"""
#for zip the content
import zlib
s="abcdef djffdkf sdnwiu s dad wejef ds,kaf fkj gk gkreger . Fmwem fjk mju j e rgjh d ehf m gl g. rtg gr r rewnj ir.Fnndf df dfgvgnog dfg."
len(s)
#t = zlib.compress(s) # error: a bytes-like object is required, not 'str'
t = zlib.compress(s.encode("ascii"))
zlib.decompress(t)
#to read the content of website
import urllib
#urllib.urlopen("http://www.forsk.in") in py2
#f = urllib.request("http://www.forsk.in") #error: 'module' object is not callable
f= urllib.request.urlopen("http://www.forsk.in")
f.read(1000)
#
import os
os.getcwd()
#image processing //python image library
#import PIL
from PIL import Image
from PIL import ImageFilter
img_filename = Image.open("sample1.png")
img_filename.show()
img_filename.filter(ImageFilter.BLUR).show()
img_filename.mode #A for transparancy<file_sep>/day14/Ayushi_Jain_47.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 29 11:19:10 2018
@author: Ayushi
"""
import pandas as pd
df=pd.read_csv("Loan.csv")
df = df.drop("Loan_ID",axis=1)
for i in df.columns:
if df[i].dtype == object:
df[i] = df[i].astype('category')
df[i] = df[i].cat.codes
df = pd.get_dummies(df, columns=['Property_Area'])
#%%
<file_sep>/day3/submission/sub6.py
# -*- coding: utf-8 -*-
"""
Created on Mon May 14 12:11:22 2018
@author: Ayushi
"""
list1=input("enter values separated by ',' : ") #Read Values
list2=list1.split(',') #split them into new list
list3=list(map(int,list2)) #convert the values in list into int
#print(list3)
count=0
flag=0
for item in list3:
flag+=1 #increment the value of flag
if item==13:
flag=0
if flag==0 or flag==1:
count=count
else:
count=count+item #calculate the sum
#print(flag)
print(count)
<file_sep>/day29 delhi weather prediction/untitled1.py
# -*- coding: utf-8 -*-
import urllib
#///----------------------
#----------Gurgaon ------------
w_gur = "https://www.worldweatheronline.com/gurgaon-weather-history/haryana/in.aspx"
page = urllib.request.urlopen(w_gur)
from bs4 import BeautifulSoup as bs
soup = bs(page)
all_div = soup.find_all('div',class_='tb_content')
#--time--
tim=[]
tim_div = soup.find_all('div',class_='tb_row tb_date')
for j in range(0,9):
a = tim_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split(":")
tim.append(int(cell[0]))
#--temp--
tem_gur=[]
tem_div = soup.find_all('div',class_='tb_row tb_temp')
for j in range(0,9):
a = tem_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split(" ")
tem_gur.append(int(cell[0]))
#--wind--
wind_div = soup.find_all('div',class_='tb_row tb_wind')
wind_gur=[]
for j in range(0,9):
a = wind_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split(" ")
wind_gur.append(int(cell[0]))
#--humidity--
hum_div = soup.find_all('div',class_='tb_row tb_humidity')
hum_gur=[]
for j in range(0,9):
a = hum_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split("%")
hum_gur.append(int(cell[0]))
#--pressure--
pres_div = soup.find_all('div',class_='tb_row tb_pressure')
#a = pres_div.findAll('div',class_='tb_cont_item')
pres_gur=[]
for j in range(0,9):
a = hum_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split("%")
pres_gur.append(int(cell[0]))
#--------------//
#///----------------------
#----------Delhi ------------
w_del = "https://www.worldweatheronline.com/delhi-weather-history/delhi/in.aspx"
page = urllib.request.urlopen(w_del)
soup = bs(page)
all_div = soup.find_all('div',class_='tb_content')
#--temp--
tem_del=[]
tem_div = soup.find_all('div',class_='tb_row tb_temp')
for j in range(0,9):
a = tem_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split(" ")
tem_del.append(int(cell[0]))
#--wind--
wind_div = soup.find_all('div',class_='tb_row tb_wind')
wind_del=[]
for j in range(0,9):
a = wind_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split(" ")
wind_del.append(int(cell[0]))
#--humidity--
hum_div = soup.find_all('div',class_='tb_row tb_humidity')
hum_del=[]
for j in range(0,9):
a = hum_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split("%")
hum_del.append(int(cell[0]))
#--pressure--
pres_div = soup.find_all('div',class_='tb_row tb_pressure')
#a = pres_div.findAll('div',class_='tb_cont_item')
pres_del=[]
for j in range(0,9):
a = hum_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split("%")
pres_del.append(int(cell[0]))
#--------------//
#///----------------------
#----------Noida ------------
w_noi = "https://www.worldweatheronline.com/noida-weather-history/uttar-pradesh/in.aspx"
page = urllib.request.urlopen(w_noi)
soup = bs(page)
all_div = soup.find_all('div',class_='tb_content')
#--temp--S
tem_noi=[]
tem_div = soup.find_all('div',class_='tb_row tb_temp')
for j in range(0,9):
a = tem_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split(" ")
tem_noi.append(int(cell[0]))
#--wind--
wind_div = soup.find_all('div',class_='tb_row tb_wind')
wind_noi=[]
for j in range(0,9):
a = wind_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split(" ")
wind_noi.append(int(cell[0]))
#--humidity--
hum_div = soup.find_all('div',class_='tb_row tb_humidity')
hum_noi=[]
for j in range(0,9):
a = hum_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split("%")
hum_noi.append(int(cell[0]))
#--pressure--
pres_div = soup.find_all('div',class_='tb_row tb_pressure')
#a = pres_div.findAll('div',class_='tb_cont_item')
pres_noi=[]
for j in range(0,9):
a = hum_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split("%")
pres_noi.append(int(cell[0]))
#--------------//
#----------Ghaziabad ------------
w_noi = "https://www.worldweatheronline.com/ghaziabad-weather-history/uttar-pradesh/in.aspx"
page = urllib.request.urlopen(w_noi)
soup = bs(page)
all_div = soup.find_all('div',class_='tb_content')
#--temp--
tem_gha=[]
tem_div = soup.find_all('div',class_='tb_row tb_temp')
for j in range(0,9):
a = tem_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split(" ")
tem_gha.append(int(cell[0]))
#--wind--
wind_div = soup.find_all('div',class_='tb_row tb_wind')
wind_gha=[]
for j in range(0,9):
a = wind_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split(" ")
wind_gha.append(int(cell[0]))
#--humidity--
hum_div = soup.find_all('div',class_='tb_row tb_humidity')
hum_gha=[]
for j in range(0,9):
a = hum_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split("%")
hum_gha.append(int(cell[0]))
#--pressure--
pres_div = soup.find_all('div',class_='tb_row tb_pressure')
#a = pres_div.findAll('div',class_='tb_cont_item')
pres_gha=[]
for j in range(0,9):
a = hum_div[j].find_all('div',class_='tb_cont_item')
for i in range(1,len(a)):
cel = a[i].text
cell = cel.split("%")
pres_gha.append(int(cell[0]))
#--------------//
import pandas as pd
df = pd.DataFrame(tim,columns = ['Time'])
df['Temp_Gurgaon'] = tem_gur
df['Wind_Gurgaon'] = wind_gur
df['Humidity_Gurgaon'] = hum_gur
df['Pressure_Gurgaon'] = pres_gur
df['Temp_Noida'] = tem_noi
df['Wind_Noida'] = wind_noi
df['Humidity_Noida'] = hum_noi
df['Pressure_Noida'] = pres_noi
df['Temp_Ghaziabad'] = tem_gha
df['Wind_Ghaziabad'] = wind_gha
df['Humidity_Ghaziabad'] = hum_gha
df['Pressure_Ghaziabad'] = pres_gha
df['Temp_Delhi'] = tem_del
df['Wind_Delhi'] = wind_del
df['Humidity_Delhi'] = hum_del
df['Pressure_Delhi'] = pres_del
#[12,39,3,25,999,38,3,25,999,37,3,27,999]
#print(df)
features = df.iloc[:,:-4].values
labels = df.iloc[:,-4:].values
#splitting the dataset
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#LinearRegression
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(features_train,labels_train)
pred = regressor.predict(features_test)
score = regressor.score(features_test,labels_test)
import numpy as np
val = np.array([39,3,25,999,38,3,25,999,37,3,27,999]).reshape(1,-1)
val2 = np.array([3,37,8,38,995,37,5,37,995,36,4,40,995]).reshape(1,-1)
pred2 = regressor.predict(val2)
pred1 = regressor.predict(val)
<file_sep>/day1/submission/sub2.py
a=input("Enter the string: ")
print("*".join(a))<file_sep>/day5/filehandling.py
# -*- coding: utf-8 -*-
"""
Created on Wed May 16 10:37:35 2018
@author: Ayushi
"""
fp = open("text.txt")
type(fp)
fp.read()
print(fp.read())
fp.close()
fp = open("text.txt")
fp.readline()
fp.readlines()
#fp.seek(offset, from_what)
fp.seek(0, 1) #error
#1: from current position #2:from end of the file #0: beginning of the file
fp.readline()
for line in fp:
print(line)
fp.close()
fp = open("text.txt",'w')
fp.write("machine learning clasS")
fp.close()<file_sep>/Practice questions/pattern.py
# -*- coding: utf-8 -*-
"""
Created on Thu May 17 19:30:12 2018
@author: Ayushi
"""
n = int(input())
lst=[]
for i in range(1,n+1):
print(("#"*i).rjust(n," "))
str1 = "abcd "
str1.rjust(10," ")
s = "#"
print('{' ':' 'nd}'.format(s))
<file_sep>/day4/sub3 pattern.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 15 00:31:58 2018
@author: Ayushi
"""
k=0
num=int(input()) #Read input
for i in range(1,2*(num+1)):
if i<=num:
k=k+1
else:
k=k-1
#print(i)
for j in range(1,k+1):
#print(j)
print("*",sep=' ',end=' ',flush='True') #print pattern
print("")
<file_sep>/day22 kmeans & unsupervised ml/Ayushi_Jain_61.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 13:00:50 2018
@author: Ayushi
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 12:26:54 2018
@author: Ayushi
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv("tshirts.csv")
features = df.iloc[:,1:3].values
#Using the elbow method to find the optimal no. of clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
kmeans = KMeans(n_clusters = i,init = 'k-means++',random_state = 0)
kmeans.fit(features)
wcss.append(kmeans.inertia_)
plt.plot(range(1,11),wcss)
plt.title("The Elbow Method")
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()
#fitting K-Means to the dataset with 3 clusters
kmeans = KMeans(n_clusters = 3,init = 'k-means++',random_state= 0)
y_kmeans = kmeans.fit_predict(features)
#Visulaing the clusters
plt.scatter(features[y_kmeans == 0,0],features[y_kmeans == 0,1],s = 100, c = 'red',label = 'medium ')
plt.scatter(features[y_kmeans == 1,0],features[y_kmeans == 1,1],s = 100, c = 'blue',label = 'large')
plt.scatter(features[y_kmeans == 2,0],features[y_kmeans == 2,1],s = 100, c = 'green',label = 'small')
plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1], s=300, c = 'yellow',label='Centroids')
plt.title("clusters of tshirts")
plt.xlabel('height')
plt.ylabel('weight')
plt.legend()
plt.show()
centers = kmeans.cluster_centers_
print("For small size :")
print("\tHeight is : ",centers[2][0])
print("\tWeight is : ",centers[2][1])
print("\nFor medium size :")
print("\tHeight is : ",centers[0][0])
print("\tWeight is : ",centers[0][1])
print("\nFor Large size :")
print("\tHeight is : ",centers[1][0])
print("\tWeight is : ",centers[1][1])
<file_sep>/day17 multiple regression/Ayushi_Jain_53.py
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 1 12:35:14 2018
@author: Ayushi
"""
import numpy as np
#read csv
import pandas as pd
df = pd.read_csv("stats_females.csv")
features = df.iloc[:,1:].values
labels = df.iloc[:,0].values
#splitting the dataset
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#fitting multiple regression to training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(features_train,labels_train)
#predicting the test set result
labels_pred = regressor.predict(features_test)
#getting score for multiple value regressor model
score = regressor.score(features_test,labels_test)
#Building the optimal model using backward elimination
import statsmodels.formula.api as sm
features = np.append(arr = np.ones((214,1)).astype(int),values = features,axis=1)
features_opt = features[:,[0,1,2]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
#regressor_OLS.params
print('when dad height is constant then increase in avg student height is: ', regressor_OLS.params[1])
print('when Mom height is constant then increase in avg student height is: ', regressor_OLS.params[2])<file_sep>/day2/reverse trim.py
# -*- coding: utf-8 -*-
"""
Created on Fri May 11 11:44:01 2018
@author: Ayushi
"""
str1=input('input: ')
str2=str1.strip()
b=str2.find(" ")
#s1=str2[b:].strip()
#s2=str2[:b].strip()
print("%s %s" %(str2[b:].strip(),str2[:b].strip()))
<file_sep>/day3/submission/sub5.py
# -*- coding: utf-8 -*-
"""
Created on Mon May 14 12:30:34 2018
@author: Ayushi
"""
list1=input("enter values separated by ',' : ") #Read string
list2=list1.split(',') #Convert it into list
list3=list(map(int,list2)) #convert the value of list into integer
print(list3)
small=min(list3) #select the minimum value from list
large=max(list3) #select the maximum value from list
list3.remove(small) #Remove the smallest element from list
list3.remove(large) #Remove the largest element from the list
#count=sum(list3)
print(sum(list3)/len(list3)) #calculate the average value
"""flag=0
for i in list3:
flag=flag+i
flag2=flag/(len(list3))
print(flag2)
"""
<file_sep>/Practice questions/list operations.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 14 22:43:37 2018
@author: Ayushi
"""
n = int(input())
l=[]
cmd = []
for i in range(0,n):
c = input()
cmd.append(list(c.split(" ")))
if cmd[-1][0] == "insert":
index = int(cmd[-1][1])
value = int(cmd[-1][2])
l.insert(index,value)
if cmd[-1][0] == "print":
print(l)
if cmd[-1][0] == "remove":
value = int(cmd[-1][1])
l.remove(value)
if cmd[-1][0] == "append":
value = int(cmd[-1][1])
l.append(value)
if cmd[-1][0] == "sort":
l = sorted(l)
if cmd[-1][0] == "pop":
l.pop()
if cmd[-1][0] == "reverse":
l.reverse()<file_sep>/day18 polynomial regression/Ayushi_Jain_54.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 4 11:28:36 2018
@author: Ayushi
"""
#read csv
import pandas as pd
df = pd.read_csv("bluegills.csv")
labels = df.iloc[:,1:].values
features = df.iloc[:,0:1].values
#fitting the linear regression to the dataset
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(features,labels)
#visualsing the linear Regression Result
import matplotlib.pyplot as plt
plt.scatter(features,labels,color='red')
plt.plot(features,regressor.predict(features),color='blue')
plt.show()
#fitting polynomial regressor to dataset
from sklearn.preprocessing import PolynomialFeatures
poln_object = PolynomialFeatures(degree=2)
features_poln = poln_object.fit_transform(features)
regressor_2 = LinearRegression()
regressor_2.fit(features_poln,labels)
#visualizing the Polynomial regression Result
plt.scatter(features,labels,color='red')
plt.plot(features,regressor_2.predict(poln_object.fit_transform(features)),color='blue')
plt.show()
#visualizing the Polynomial regression Result (for higher resolution and smoother curve
import numpy as np
features_grid = np.arange(min(features),max(features),0.1)
features_grid = features_grid.reshape((-1,1))
plt.scatter(features,labels,color='red')
plt.plot(features_grid,regressor_2.predict(poln_object.fit_transform(features_grid)),color='blue')
plt.show()
print("predicted length of five-year-old bluegill fish is : ")
print(regressor_2.predict(poln_object.fit_transform(5)))
<file_sep>/day14/Ayushi_Jain_45.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 29 12:26:47 2018
@author: Ayushi
"""
# -*- coding: utf-8 -*-
"""
Created on Tue May 29 12:00:57 2018
@author: Ayushi
"""
import pandas as pd
from sklearn.preprocessing import LabelEncoder
#Read csv
df=pd.read_csv("Automobile.csv")
#print datatypes
for i in df.columns:
print(i,df[i].dtype)
#new dataframe where datatype = object
df_new = df.select_dtypes(object)
#missing data handling
df_new[df_new.isnull().any(axis=1)]
df_new["num_doors"].value_counts()
df_new = df_new.fillna({"num_doors" : "four"})
#label encoding in body_style
labelencoder = LabelEncoder()
df_new["body_style"] = labelencoder.fit_transform(df_new["body_style"])
#one hot encoding
df_new = pd.get_dummies(df_new, columns=['drive_wheels'])
df_new = pd.get_dummies(df_new, columns=['body_style'])
<file_sep>/Practice questions/sms send.py
import datetime
import requests
pn = input("Enter Phone no. : ")
msg = input("Enter Message : ")
resp = requests.post("https://smsapi.engineeringtgr.com/send/?Mobile=7597476620&Password=<PASSWORD>&Message="+msg+"&To="+pn+"&Key=<KEY>")
print (resp.text)
#post data into mlab
myAPIKey = "<KEY>"
#Url
url = "https://api.mlab.com/api/1/databases/db_university/collections/reg?apiKey="+myAPIKey
data={
"mob_no":pn,
"sms":msg,
"Date-Time":str(datetime.datetime.now())
}
r=requests.post(url,json= data) #sending data on server and in parameter we send
#url and data in json format
print(r.text) <file_sep>/day10/MLab.py
# -*- coding: utf-8 -*-
"""
Created on Wed May 23 12:45:52 2018
@author: Ayushi
"""
#import Libraries
import json
import requests
#API KEY
myAPIKey = "<KEY>"
#Url
url = "https://api.mlab.com/api/1/databases/db_university/collections/reg?apiKey="+myAPIKey
data = {
"Student Name" : 'Ayushi',
"Student Age" : '18',
"Student Roll_no" : '1',
"Student Branch" : 'CS'
}
#convert json data into dictionary format
d = json.dumps(data)
#Post the data into url
resp = requests.post(url,data = d,headers={"Content-Type":"application/json"})
print (resp.text)
<file_sep>/day16 regression/Ayushi_Jain_50.py
# -*- coding: utf-8 -*-
"""
Created on Thu May 31 11:06:18 2018
@author: Ayushi
"""
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("Foodtruck.csv")
features = df.iloc[:,:-1].values
labels = df.iloc[:,-1].values
#Splitting the data
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state = 0)
#Fitting linear regression to training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(features_train,labels_train)
#predicting the test result
labels_pred = regressor.predict(features_test)
#Model score
score = regressor.score(features_test,labels_test)
#Visulaizing the training set result
plt.scatter(features_train,labels_train,color='red')
plt.plot(features_train,regressor.predict(features_train),color='blue')
plt.title("Population v/s profit graph")
plt.xlabel("Population")
plt.ylabel("profit")
plt.show()
plt.close()
#profit in jaipur
jaipur_pred = regressor.predict(3.073)
print("Profit in Jaipur : ",jaipur_pred)
<file_sep>/day6/Ayushi_Jain_20.py
str1=input() #Read Input
def reverse(s1):
return s1[::-1] #reverse the string
print(reverse(str1)) #call reverse function
<file_sep>/day25 SVM support vector machine/Ayushi_Jain_65.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 14 11:14:37 2018
@author: Ayushi
"""
#import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv("breast_cancer.csv")
#Handling missing values
for i in df:
df[i] = df[i].fillna(df[i].mode()[0])
features = df.iloc[:,1:-1].values
labels = df.iloc[:,-1].values
#splitting the dataset
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#Fitting SVM to training set
from sklearn.svm import SVC
classifier = SVC(kernel = "linear", random_state=0)
classifier.fit(features_train,labels_train)
#predict the test set results
pred = classifier.predict(features_test)
#Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(labels_test,pred)
#Calculating the score
score = classifier.score(features_test,labels_test)
pred_cancer = classifier.predict(np.array([6,2,5,3,2,7,9,2,4]).reshape(1,-1))
#PCA principle component Analysis
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
features_train = pca.fit_transform(features_train)
features_test = pca.transform(features_test)
explained_variance = pca.explained_variance_ratio_
#Fitting SVM to training set
from sklearn.svm import SVC
classifier1 = SVC(kernel = "linear", random_state=0)
classifier1.fit(features_train,labels_train)
# Visualising the Test set results
from matplotlib.colors import ListedColormap
features_set, labels_set = features_test, labels_test
X1, X2 = np.meshgrid(np.arange(start = features_set[:, 0].min() - 1, stop = features_set[:, 0].max() + 1, step = 0.01),
np.arange(start = features_set[:, 1].min() - 1, stop = features_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier1.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('green','red')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(labels_set)):
plt.scatter(features_set[labels_set == j, 0], features_set[labels_set == j, 1],
c = ListedColormap(('green','red'))(i), label = j)
plt.title('SVM (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()<file_sep>/Practice questions/no. prediction.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 13:54:25 2018
@author: Ayushi
"""
import glob
import numpy as np
import matplotlib.pyplot as plt
import os
listoffolders=os.listdir("E:\\data science\\datasets\\mnist\\mnist_png\\training")
#for SubFolder in listoffolders:
SubFolder=0
ListofImages=os.listdir("E:\\data science\\datasets\\mnist\\mnist_png\\training\\"+str(SubFolder))
print(ListofImages)
S=(plt.imread("E:\\data science\\datasets\\mnist\\mnist_png\\training\\"+str(0)+"\\"+"1.png")).shape
MeanImages=[]
for SubFolder in listoffolders:
Sum=np.zeros([S[0],S[1]])
ListofImages=os.listdir("E:\\data science\\datasets\\mnist\\mnist_png\\training\\"+str(SubFolder))
for Image in ListofImages:
Sum+=plt.imread("E:\\data science\\datasets\\mnist\\mnist_png\\training\\"+str(SubFolder)+"\\"+Image)
Sum=Sum/len(ListofImages)
MeanImages.append(Sum)
plt.imshow(MeanImages[0])
plt.show()
for SubFolder in listoffolders:
Sum=np.zeros([S[0],S[1]])
ListofImages=os.listdir("E:\\data science\\datasets\\mnist\\mnist_png\\training\\"+str(SubFolder))
for Image in ListofImages:
Sum+=plt.imread("E:\\data science\\datasets\\mnist\\mnist_png\\training\\"+str(SubFolder)+"\\"+Image)
Sum=Sum/len(ListofImages)
MeanImages.append(Sum)
plt.imshow(MeanImages[0])
plt.show()
<file_sep>/day24 PCA principle component analysis/Ayushi_Jain_64.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 11:51:32 2018
@author: Ayushi
"""
#import Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
iris = load_iris()
iris = iris.data
#PCA principle component Analysis
from sklearn.decomposition import PCA
"""
#explains the value of n_components
///only with high explained_variance are used
pca = PCA(n_components=None)
X = pca.fit_transform(X)
explained_variance = pca.explained_variance_ratio_
"""
pca = PCA(n_components=2)
iris = pca.fit_transform(iris)
explained_variance = pca.explained_variance_ratio_
#using the elbow method to find the optimal no. of clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
kmeans = KMeans(n_clusters = i,init = 'k-means++',random_state = 0)
kmeans.fit(iris)
wcss.append(kmeans.inertia_)
plt.plot(range(1,11),wcss)
plt.title("The Elbow Method")
plt.xlabel('Number of clusters')
plt.ylabel('WCSS')
plt.show()
#fitting K-Means to the dataset with 4 clusters
kmeans = KMeans(n_clusters = 3,init = 'k-means++',random_state= 0)
y_kmeans = kmeans.fit_predict(iris)
#Visulaing the clusters
plt.scatter(iris[y_kmeans == 0,0],iris[y_kmeans == 0,1],s = 100, c = 'red',label = 'Iris_setosa')
plt.scatter(iris[y_kmeans == 1,0],iris[y_kmeans == 1,1],s = 100, c = 'blue',label = 'Iris_versicolor')
plt.scatter(iris[y_kmeans == 2,0],iris[y_kmeans == 2,1],s = 100, c = 'green',label = 'Iris_virginica')
plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1], s=300, c = 'yellow',label='Centroids')
plt.title("clusters of Iris")
plt.xlabel('pc1')
plt.ylabel('pc2')
plt.legend()
plt.show()
<file_sep>/day1/submission/sub3.py
# -*- coding: utf-8 -*-
"""
Created on Thu May 10 13:01:21 2018
@author: Ayushi
"""
str="Welcome to Pink City Jaipur"
result=""
for ch in str:
result=result+ch+"*"
print(result[:-1]) <file_sep>/day6/Ayushi_Jain_19.py
alpha = "abcdefghijklmnopqrstuvwxyz "
str1= input().lower() #Read input and convert it into lower case
flag=0 #set the flag value to 0
for ch in alpha: #for each character in alphabet
if ch not in str1: #if any alphabet is not present in string
flag=1 #then set flag = 1
break #terminate the for loop
if flag==0:
print("PANGRAM")
else:
print("NOT PANGRAM")<file_sep>/day11/Ayushi_Jain_35.py
import pandas as pd
df=pd.read_csv("training_titanic.csv")
#no of persons survived
a=df["Survived"].value_counts()
a1=df["Survived"].value_counts(normalize=True)
print("survived",a1[1]*100)
print("dead",a1[0])
#no of male survived & died
d1=df[df["Sex"]=='male']
b=d1["Survived"].value_counts(normalize=True)
print("male survived:",b[1])
print("male dead:",b[0])
#no of female survived and died
d2=df[df["Sex"]=='female']
c=d2["Survived"].value_counts(normalize=True)
print("female survived:",c[1])
print("female dead:",c[0])<file_sep>/day20 Logistic Regression/57_using knn.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 12:06:02 2018
@author: Ayushi
"""
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 6 10:22:24 2018
@author: Ayushi
"""
import pandas as pd
import numpy as np
#read file
df=pd.read_csv("affairs.csv")
features = df.iloc[:,:-1].values
labels = df.iloc[:,-1:].values
#OneHot Encoding
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(categorical_features=[-2])
features =encoder.fit_transform(features).toarray()
features=features[:,1:]
encoder1 = OneHotEncoder(categorical_features=[-1])
features =encoder.fit_transform(features).toarray()
features=features[:,1:]
#splitting the dataset into training and testing set
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,lebels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#fittig KNN to training set
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=11,p=2)
knn.fit(features_train,labels_train)
pred = knn.predict(features_test)
#Making the confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(lebels_test,pred)
score = knn.score(features_test,lebels_test)
print("Accuracy of the model is: ",score*100,"%")
<file_sep>/day19 decision tree & Random forest regressor/Ayushi_Jain_55.py
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 5 11:03:38 2018
@author: Ayushi
"""
#read csv
import pandas as pd
df = pd.read_csv("PastHires.csv")
features = df.iloc[:,:-1].values
labels = df.iloc[:,-1:].values
#label encoding
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
features[:,1] = labelencoder.fit_transform(features[:,1])
features[:,3] = labelencoder.fit_transform(features[:,3])
features[:,4] = labelencoder.fit_transform(features[:,4])
features[:,5] = labelencoder.fit_transform(features[:,5])
labels[:,-1] = labelencoder.fit_transform(labels[:,-1])
#fitting decision tree regressor to dataset
from sklearn.tree import DecisionTreeRegressor
regressor = DecisionTreeRegressor(random_state=0)
regressor.fit(features,labels)
#fitting random forest regression
from sklearn.ensemble import RandomForestRegressor
reg = RandomForestRegressor(n_estimators=10,random_state=0)
reg.fit(features,labels)
#predicting the result
import numpy as np
pred1 = regressor.predict(np.array([10,1,4,0,1,0]).reshape(1,-1))
pred2 = reg.predict(np.array([10,1,4,0,1,0]).reshape(1,-1))
pred3 = regressor.predict(np.array([10,0,4,1,0,1]).reshape(1,-1))
pred4 = reg.predict(np.array([10,0,4,1,0,1]).reshape(1,-1))
<file_sep>/day9/email verify.py
# -*- coding: utf-8 -*-S
"""
Created on Tue May 22 11:47:38 2018
@author: Ayushi
"""
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 11:18:39 2018
@author: Ayushi
"""
import re
# re.compile converts regex pattern to variable,
# and makes it easier to reuse
regex = re.compile(r'[a-zA-Z0-9_-]+[@][a-zA-Z0-9]+[\.][a-zA-Z]{2,4}$')
lst = []
## Search
while True:
string1 = input()
if not string1:
break
# Gets the string from where the match is found
response = regex.match(string1)
if response:
# The groups contain the matched values.
# It always returns the fully matched string
lst.append(string1)
print(lst)<file_sep>/day4/sub2 bricks.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 15 11:52:35 2018
@author: Ayushi
"""
"""
small=int(input("Enter the no. of small bricks : "))
large=int(input("Enter the no. of large bricks : "))
target=int(input("Enter the target value : "))
"""
l=input()
l1=l.split(",")
l2=list(map(int,l1))
small=l2[0]
large=l2[1]
target=l2[2]
l,s=divmod(target,5)
if(l<=large):
if(s<=small):
print("true")
else:
print("False")
else:
print("False")
"""
if(((small*1)+(large*5))>=target):
print("True")
else:
print("False")
"""<file_sep>/day3/submission/sub4.py
string1 = input("Enter the String : ") #Read string
digit=0 #initialize digit
letter=0 #initialize letter
for element in string1: #for each element in string
if element.isdigit(): #if element is digit
digit+=1
elif(element.isalpha()): #if element is letter
letter+=1
#print the values
print("Letters %d"%letter)
print("Digits %d" %digit) <file_sep>/day8/web scrapping.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 12:01:58 2018
@author: Ayushi
"""
import urllib
wiki = "https://www.icc-cricket.com/rankings/mens/team-rankings/odi"
page = urllib.request.urlopen(wiki)
from bs4 import BeautifulSoup as bs
soup = bs(page)
all_tables = soup.find_all('table')
right_table = soup.find('table',class_='table')
A= []
B= []
C= []
D= []
E= []
F= []
for row in right_table.findAll("tr"):
cells = row.findAll("td")
if len(cells) ==5:
A.append(cells[0].text.strip())
B.append((cells[1].text.strip()))
C.append(cells[2].find(text=True))
D.append(cells[3].find(text=True))
E.append(cells[4].find(text=True))
import pandas as pd
df = pd.DataFrame(A,columns = ['Position'])
df['Team'] = B
df['Matches'] = C
df['Points'] = D
df['Rating'] = E
print(df)
<file_sep>/day29 delhi weather prediction/untitled0.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 22:21:24 2018
@author: Ayushi
"""
import urllib
#///----------------------
#----------Gurgaon ------------
w_gur = "https://www.worldweatheronline.com/gurgaon-weather-history/haryana/in.aspx"
page = urllib.request.urlopen(w_gur)
from bs4 import BeautifulSoup as bs
soup = bs(page)
all_div = soup.find_all('div',class_='tb_content')
#--time--
tim_div = soup.find('div',class_='tb_row tb_date')
a = tim_div.findAll('div',class_='tb_cont_item')
tim=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split(":")
#s = cells.text
tim.append(int(cell[0]))
#--temp--
tem_div = soup.find('div',class_='tb_row tb_temp')
a = tem_div.findAll('div',class_='tb_cont_item')
tem_gur=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split(" ")
#s = cells.text
tem_gur.append(int(cell[0]))
#--wind--
wind_div = soup.find('div',class_='tb_row tb_wind')
a = wind_div.findAll('div',class_='tb_cont_item')
wind_gur=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split(" ")
#s = cells.text
wind_gur.append(int(cell[0]))
#--humidity--
hum_div = soup.find('div',class_='tb_row tb_humidity')
a = hum_div.findAll('div',class_='tb_cont_item')
hum_gur=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split("%")
#s = cells.text
hum_gur.append(int(cell[0]))
#--pressure--
pres_div = soup.find('div',class_='tb_row tb_pressure')
a = pres_div.findAll('div',class_='tb_cont_item')
pres_gur=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split(" ")
#s = cells.text
pres_gur.append(int(cell[0]))
#--------------//
#///----------------------
#----------Delhi ------------
w_del = "https://www.worldweatheronline.com/delhi-weather-history/delhi/in.aspx"
page = urllib.request.urlopen(w_del)
soup = bs(page)
all_div = soup.find_all('div',class_='tb_content')
#--temp--
tem_div = soup.find('div',class_='tb_row tb_temp')
a = tem_div.findAll('div',class_='tb_cont_item')
tem_del=[]
for i in range(1,9):
cel = a[i].text
cell = cel.split(" ")
tem_del.append(int(cell[0]))
#--wind--
wind_div = soup.find('div',class_='tb_row tb_wind')
a = wind_div.findAll('div',class_='tb_cont_item')
wind_del=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split(" ")
#s = cells.text
wind_del.append(int(cell[0]))
#--humidity--
hum_div = soup.find('div',class_='tb_row tb_humidity')
a = hum_div.findAll('div',class_='tb_cont_item')
hum_del=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split("%")
#s = cells.text
hum_del.append(int(cell[0]))
#--pressure--
pres_div = soup.find('div',class_='tb_row tb_pressure')
a = pres_div.findAll('div',class_='tb_cont_item')
pres_del=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split(" ")
#s = cells.text
pres_del.append(int(cell[0]))
#--------------//
#///----------------------
#----------Noida ------------
w_noi = "https://www.worldweatheronline.com/noida-weather-history/uttar-pradesh/in.aspx"
page = urllib.request.urlopen(w_noi)
soup = bs(page)
all_div = soup.find_all('div',class_='tb_content')
#--temp--
tem_div = soup.find('div',class_='tb_row tb_temp')
a = tem_div.findAll('div',class_='tb_cont_item')
tem_noi=[]
for i in range(1,9):
cel = a[i].text
cell = cel.split(" ")
tem_noi.append(int(cell[0]))
#--wind--
wind_div = soup.find('div',class_='tb_row tb_wind')
a = wind_div.findAll('div',class_='tb_cont_item')
wind_noi=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split(" ")
#s = cells.text
wind_noi.append(int(cell[0]))
#--humidity--
hum_div = soup.find('div',class_='tb_row tb_humidity')
a = hum_div.findAll('div',class_='tb_cont_item')
hum_noi=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split("%")
#s = cells.text
hum_noi.append(int(cell[0]))
#--pressure--
pres_div = soup.find('div',class_='tb_row tb_pressure')
a = pres_div.findAll('div',class_='tb_cont_item')
pres_noi=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split(" ")
#s = cells.text
pres_noi.append(int(cell[0]))
#--------------//
#----------Ghaziabad ------------
w_noi = "https://www.worldweatheronline.com/ghaziabad-weather-history/uttar-pradesh/in.aspx"
page = urllib.request.urlopen(w_noi)
soup = bs(page)
all_div = soup.find_all('div',class_='tb_content')
#--temp--
tem_div = soup.find('div',class_='tb_row tb_temp')
a = tem_div.findAll('div',class_='tb_cont_item')
tem_gha=[]
for i in range(1,9):
cel = a[i].text
cell = cel.split(" ")
tem_gha.append(int(cell[0]))
#--wind--
wind_div = soup.find('div',class_='tb_row tb_wind')
a = wind_div.findAll('div',class_='tb_cont_item')
wind_gha=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split(" ")
#s = cells.text
wind_gha.append(int(cell[0]))
#--humidity--
hum_div = soup.find('div',class_='tb_row tb_humidity')
a = hum_div.findAll('div',class_='tb_cont_item')
hum_gha=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split("%")
#s = cells.text
hum_gha.append(int(cell[0]))
#--pressure--
pres_div = soup.find('div',class_='tb_row tb_pressure')
a = pres_div.findAll('div',class_='tb_cont_item')
pres_gha=[]
for i in range(1,9):
#print(row)
cel = a[i].text
cell = cel.split(" ")
#s = cells.text
pres_gha.append(int(cell[0]))
#--------------//
import pandas as pd
df = pd.DataFrame(tim,columns = ['Time'])
df['Temp_Gurgaon'] = tem_gur
df['Wind_Gurgaon'] = wind_gur
df['Humidity_Gurgaon'] = hum_gur
df['Pressure_Gurgaon'] = pres_gur
df['Temp_Noida'] = tem_noi
df['Wind_Noida'] = wind_noi
df['Humidity_Noida'] = hum_noi
df['Pressure_Noida'] = pres_noi
df['Temp_Ghaziabad'] = tem_gha
df['Wind_Ghaziabad'] = wind_gha
df['Humidity_Ghaziabad'] = hum_gha
df['Pressure_Ghaziabad'] = pres_gha
df['Temp_Delhi'] = tem_del
df['Wind_Delhi'] = wind_del
df['Humidity_Delhi'] = hum_del
df['Pressure_Delhi'] = pres_del
#print(df)
features = df.iloc[:,:-4].values
labels = df.iloc[:,-4:].values
#splitting the dataset
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#LinearRegression
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(features_train,labels_train)
pred = regressor.predict(features_test)
score = regressor.score(features_test,labels_test)
<file_sep>/day20 Logistic Regression/Ayushi_jain_57.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 6 10:22:24 2018
@author: Ayushi
"""
import pandas as pd
import numpy as np
#read file
df=pd.read_csv("affairs.csv")
features = df.iloc[:,:-1].values
labels = df.iloc[:,-1:].values
#OneHot Encoding
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(categorical_features=[-2])
features =encoder.fit_transform(features).toarray()
features=features[:,1:]
encoder1 = OneHotEncoder(categorical_features=[-1])
features =encoder.fit_transform(features).toarray()
features=features[:,1:]
#splitting the dataset into training and testing set
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,lebels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#fitting Logistic regression into training set
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state=0)
classifier.fit(features_train,labels_train)
#predicting the test set Result
labels_pred = classifier.predict(features_test)
#claculate the score
score = classifier.score(features_test,lebels_test)
#making the confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(lebels_test,labels_pred)
#percentage of affair
affair = df["affair"].value_counts(normalize=True)*100
#predict random result
pred_affair = classifier.predict_proba(np.array([1,0,0,0,0,0,0,1,0,0,3,25,3,1,4,16]).reshape(1,-1))
aff = list(pred_affair[0])
max_prob = max(aff)
index = aff.index(max_prob)
print("percentage of total women actually had an affair is : ", affair[1])
print("Prediction of women : ",index)
#optimal Model
import statsmodels.formula.api as sm
features = np.append(arr = np.ones((6366,1)).astype(int),values = features,axis=1)
features_opt = features[:,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
features_opt = features[:,[0,6,7,8,9,10,11,12,13,14,15,16]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
features_opt = features[:,[0,6,7,8,9,10,11,12,13,14,15]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
features_opt = features[:,[0,6,7,8,9,10,11,12,13,15]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
features_opt = features[:,[0,11,12,13,15]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
#We observe that children,education,occupation & occupation_husb columns are not impotant
#before One Hot Encoding
features = df.iloc[:,:-1].values
features_opt = features[:,[0,1,2,3,4,5,6,7,8]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
features_opt = features[:,[0,1,2,3,5,6,7,8]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
features_opt = features[:,[0,1,2,3,5,6,7]]
regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit()
regressor_OLS.summary()
#We observe that children & occupation_husb columns are not impotant
<file_sep>/day5/sub3 image.py
import PIL
#Read Image Convert it into greyscale and rotate 90 degree clockwise
img_filename = PIL.Image.open("sample.jpg").convert('L').rotate(-90)
#img_filename.show()
w = img_filename.size[0] / 2
h = img_filename.size[1] / 2
size = (w-80,h-102,w+80,h+102)
img_filename= img_filename.crop(size) #crop image from center of (width=160,height=204)
s=(75,75)
img_filename.thumbnail(s) #make thumbnail
img_filename.show()
<file_sep>/day29 delhi weather prediction/weather.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 11:00:29 2018
@author: KARIS
"""
# open weather api: ff1246fde51147b9eb2b662f6e613121
#new delhi ,gurgaon, gurugram , faridabad , noida, ghaziabad,panipat, sonipat,patparganj, burari
import urllib.request
url = "https://www.wunderground.com/history/airport/VIDP/2018/6/16/MonthlyHistory.html?&reqdb.zip=&reqdb.magic=&reqdb.wmo="
page = urllib.request.urlopen(url)
from bs4 import BeautifulSoup
soup = BeautifulSoup(page, "lxml")
right_table = soup.find('table',{'id':'obsTable'})
DateDel = []
TempDel= []
DewPointDel= []
HumiditypercentDel= []
SeaLevelDel= []
VisiblityDel = []
WindDel = []
rows = right_table.find_all("tr")
for row in rows:
cells = row.findAll('td')
if len(cells)==21:
DateDel.append(cells[0].text.strip())
TempDel.append(cells[2].text.strip())
DewPointDel.append(cells[5].text.strip())
HumiditypercentDel.append(cells[8].text.strip())
SeaLevelDel.append(cells[11].text.strip())
VisiblityDel.append(cells[14].text.strip())
WindDel.append(cells[17].text.strip())
import pandas as pd
labels = pd.DataFrame(DateDel,columns=['DateDel'])
labels['TempDel']=TempDel
labels['HumiditypercentDel']=HumiditypercentDel
labels['SeaLevelDel'] = SeaLevelDel
labels['VisiblityDel']= VisiblityDel
labels["WindDel"] = WindDel
labels.drop(labels.index[0],inplace = True, axis = 0)
fariurl = "https://www.wunderground.com/history/airport/VOHS/2018/6/20/MonthlyHistory.html?req_city=VOHS&req_statename=India&reqdb.zip=00000&reqdb.magic=242&reqdb.wmo=WVOHS"
page = urllib.request.urlopen(fariurl)
soup = BeautifulSoup(page, "lxml")
right_table = soup.find('table',{'id':'obsTable'})
DateFari = []
TempFari= []
DewPointFari= []
HumiditypercentFari= []
SeaLevelFari= []
VisiblityFari = []
WindFari = []
rows = right_table.find_all("tr")
for row in rows:
cells = row.findAll('td')
if len(cells)==21:
DateFari.append(cells[0].text.strip())
TempFari.append(cells[2].text.strip())
DewPointFari.append(cells[5].text.strip())
HumiditypercentFari.append(cells[8].text.strip())
SeaLevelFari.append(cells[11].text.strip())
VisiblityFari.append(cells[14].text.strip())
WindFari.append(cells[17].text.strip())
import pandas as pd
feat = pd.DataFrame(DateFari,columns=['DateFari'])
feat['TempFari']=TempFari
feat['HumiditypercentFari']=HumiditypercentFari
feat['SeaLevelFari'] = SeaLevelFari
feat['VisiblityFari']= VisiblityFari
feat["WindFari"] = WindFari
ghazurl = "https://www.wunderground.com/history/airport/VIDD/2018/6/20/MonthlyHistory.html?req_city=Safdarjung&req_state=DL&req_statename=India&reqdb.zip=00000&reqdb.magic=70&reqdb.wmo=42182"
page = urllib.request.urlopen(ghazurl)
soup = BeautifulSoup(page, "lxml")
right_table = soup.find('table',{'id':'obsTable'})
DateGhaz = []
TempGhaz= []
DewPointGhaz= []
HumiditypercentGhaz= []
SeaLevelGhaz= []
VisiblityGhaz = []
WindGhaz = []
rows = right_table.find_all("tr")
for row in rows:
cells = row.findAll('td')
if len(cells)==21:
DateGhaz.append(cells[0].text.strip())
TempGhaz.append(cells[2].text.strip())
DewPointGhaz.append(cells[5].text.strip())
HumiditypercentGhaz.append(cells[8].text.strip())
SeaLevelGhaz.append(cells[11].text.strip())
VisiblityGhaz.append(cells[14].text.strip())
WindGhaz.append(cells[17].text.strip())
import pandas as pd
feat['DateGhaz']=DateGhaz
feat['TempGhaz']=TempGhaz
feat['HumiditypercentGhaz']=HumiditypercentGhaz
feat['SeaLevelGhaz'] = SeaLevelGhaz
feat['VisiblityGhaz']= VisiblityGhaz
feat["WindGhaz"] = WindGhaz
feat.drop(feat.index[0],inplace = True, axis = 0)
from sklearn.model_selection import train_test_split as TTS
feat_train, feat_test , labels_train , labels_test = TTS(feat , labels ,test_size = 0.2 ,random_state = 0)
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
feat_train = sc.fit_transform(feat_train)
feat_test = sc.transform(feat_test)
from sklearn.tree import DecisionTreeRegressor
regressor = DecisionTreeRegressor(random_state=0)
regressor.fit(feat_train , labels_train)
labels_pred = regressor.predict(feat_test)
Score = regressor.score(feat_test, labels_test)
<file_sep>/day1/submission/sub1.py
str="This is a multi line string. This code challenge is to test your understanding about strings.You need to print some part of this string. From here print this text without manually counting the indexes."
ab=str.find("From here")
print(str[ab:])<file_sep>/day14/Ayushi_Jain_46.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 29 12:00:57 2018
@author: Ayushi
"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
df=pd.read_csv("Loan.csv")
df = df.drop("Loan_ID",axis=1)
X = df.iloc[:,:-1].values #features
y = df.iloc[:,-1].values #labels
labelencoder = LabelEncoder()
X[:,1] = labelencoder.fit_transform(X[:,1])
X[:,2] = labelencoder.fit_transform(X[:,2])
X[:,3] = labelencoder.fit_transform(X[:,3])
X[:,4] = labelencoder.fit_transform(X[:,4])
X[:,0] = labelencoder.fit_transform(X[:,0])
X[:,-1] = labelencoder.fit_transform(X[:,-1])
onehotencoder = OneHotEncoder(categorical_features=[-1])
X = onehotencoder.fit_transform(X).toarray()
y = labelencoder.fit_transform(y)
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=0)
<file_sep>/day15/Ayushi_jain_49.py
# -*- coding: utf-8 -*-
"""
Created on Wed May 30 11:52:56 2018
@author: Ayushi
"""
import pandas as pd
#Read csv
df = pd.read_csv("Red_Wine.csv",sep = ',')
#taking care of missing data
for i in df:
df[i] = df[i].fillna(df[i].mode()[0])
#split into features and labels
features = df.iloc[:,:-1].values
labels = df.iloc[:,-1].values
#Encoding the categorical data
from sklearn.preprocessing import OneHotEncoder,LabelEncoder
labelencoder = LabelEncoder()
features[:,0] = labelencoder.fit_transform(features[:,0])
onehotencoder = OneHotEncoder(categorical_features=[0])
features = onehotencoder.fit_transform(features).toarray()
#Split the data set into training and test set
from sklearn.model_selection import train_test_split
features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0)
#features scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
features_train = sc.fit_transform(features_train)
features_test = sc.transform(features_test)
<file_sep>/day5/PIL/crop and paste.py
# -*- coding: utf-8 -*-
"""
Created on Wed May 16 18:04:59 2018
@author: Ayushi
"""
import PIL
img= PIL.Image.open('sample.jpg')
w = int(img.size[0] / 2)
h = int(img.size[1] / 2)
size = (w-80,h-102,w+80,h+102)
#box = (100, 100, 400, 400)
region = img.crop(size)
region = region.transpose(PIL.Image.ROTATE_180)
img.paste(region, size)
img.show()
url="http://"
import requests
resp= requests.get(url)
print(resp.text)<file_sep>/day5/doctest.py
# -*- coding: utf-8 -*-
"""
Created on Thu May 17 11:16:30 2018
@author: Ayushi
"""
import doctest
def Add(p,q):
"""
Perform Addition
>>> Add(12,3)
15
>>> Add(4,5)
9
"""
return p*q
doctest.testmod()<file_sep>/day6/sub 2 Reverse of string.py
str1=input()
def reverse(s1):
s2=""
l=len(s1)
i=l
while(i!=0):
s2=s2+s1[i-1]
i=i-1
return s2
print(reverse(str1))
print(str1[::-1])
"""
s2=""
l=len(s1)
i=l
while(i!=0):
s2=s2+s1[i-1]
i=i-1
print(s2)
"""<file_sep>/day9/float number.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 11:18:39 2018
@author: Ayushi
"""
import re
# re.compile converts regex pattern to variable,
# and makes it easier to reuse
regex = re.compile(r'[+-]?\d*[\.][\d]+')
lst = []
## Search
while True:
string1 = input()
if not string1:
break
# Gets the string from where the match is found
response = regex.search(string1)
if response:
lst.append(True)
# The groups contain the matched values.
# It always returns the fully matched string
#print("True")
else:
lst.append(False)
#print ("False")
for i in lst:
print(i)<file_sep>/day7/Ayushi_Jain_24.py
# -*- coding: utf-8 -*-
"""
Created on Fri May 18 14:18:23 2018
@author: Ayushi
"""
import twitter
api = twitter.Api(consumer_key="CONSUMER_KEY",consumer_secret="CONSUMER_SECRET",access_token_key="TOKEN_KEY",access_token_secret="TOKEN_SECRET")
status = api.PostUpdate("Hello!!")
<file_sep>/day8/supermarket item price.py
from collections import OrderedDict
dd = OrderedDict()
while True:
str1 = input()
if not str1:
break
str2 = str1[::-1]
tup1 = str2.split(' ',1)
t0 = str(tup1[0])
t0= int(t0[::-1])
t1 = str(tup1[1])
t1= t1[::-1]
if t1 in dd:
dd[t1] = dd[t1]+t0
else:
dd[t1]=t0
for k,v in dd.items():
print(k,v)
"""
Alt
"""
from collections import OrderedDict
dd = OrderedDict()
while True:
str1 = input()
if not str1:
break
lst = str1.split(' ')
value = lst[-1]
key = ' '.join(lst[0:-1])
if key in dd:
dd[key] = dd[key]+int(value)
else:
dd[key] = int(value)
for k,v in dd.items():
print(k,v)
|
8ee02bc022107aba1cf7b247a7b9b2b060ed9112
|
[
"Python"
] | 87
|
Python
|
AyuJ01/forsk
|
94953d9c92ed3e380dc48ddfcf709581c2cd0fd4
|
5f2e9bb846648fd0efa6266718a56c37cf40610c
|
refs/heads/master
|
<repo_name>endlos/poly-api<file_sep>/README.rdoc
== Polymorphic associations sample
0. New app
rails-api new poly-api --skip-sprockets
1. Generate the models
rails g model client name company
rails g model organization name
rails g model person name position organization:references
rails g model contract details:text name client:references person:references
rails g model address street street_number zip_code state address_for addressable:references{polymorphic}
bundle exec rake db:migrate
2. Add the relationships
class Organization < ActiveRecord::Base
has_many :people
has_many :addresses, as: :addressable
end
class Person < ActiveRecord::Base
belongs_to :organization
has_many :contracts
has_many :clients, through: :contracts
has_many :addresses, as: :addressable
end
class Address < ActiveRecord::Base
belongs_to :addressable, polymorphic: true
end
3. Have fun in the console
p = Person.create(name: "Hugo", position: "CEO")
p.addresses.create(street: "Happy Street", street_number: "123", address_for: "Home")
p.addresses
o = Organization.create(name: "ABC")
o.addresses.create(street: "Corp Av", street_number: "123", address_for: "Office")
o.addresses
=== License
Released under the {MIT License}[https://opensource.org/licenses/MIT].
<file_sep>/app/models/organization.rb
class Organization < ActiveRecord::Base
has_many :people
has_many :addresses, as: :addressable
end
<file_sep>/app/models/person.rb
class Person < ActiveRecord::Base
belongs_to :organization
has_many :contracts
has_many :clients, through: :contracts
has_many :addresses, as: :addressable
end
|
4978413b1dfde41b8a21b65859ac8eca6f6b777f
|
[
"RDoc",
"Ruby"
] | 3
|
RDoc
|
endlos/poly-api
|
d37c28139798dedaba8aec8b405e40eedfa24bf4
|
9c753bad943865ef9a64dcbaac1d39bcccf28f97
|
refs/heads/master
|
<repo_name>serobalino/PortalDeLaVida<file_sep>/readme.md
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/5/5b/Lions_Clubs_International_logo.svg/1080px-Lions_Clubs_International_logo.svg.png" align="right" width="80"/>
# Club de Leónes - Portal de la Vida [](https://github.com/serobalino/PortalDeLaVida)
> Sistema Medico
## Acción Social - Facultad de Ingeniería PUCE Quito
- [BackEnd](https://github.com/serobalino/PortalDeLaVida) - Proyecto desarrollado en PHP con Framework *Laravel 5.4*.
- [FrontEnd](https://github.com/serobalino/PortalDeLaVida) - Librerías de node js con framework VUE js.
- [Base de Datos](https://github.com/serobalino/PortalDeLaVida) - Base de datos SQL diseñada en PowerDesigner para MySQL.
- [Artes](https://github.com/serobalino/PortalDeLaVida) - Diseños e imagenes para el sistema.
## Herramientas
- [PHPStorm](https://www.jetbrains.com/student/) - IDE para Back y Front.
- [Composer](https://getcomposer.org/) - Manejador de dependecias de PHP.
- [node js](https://nodejs.org/es/) - Manejador de dependecias js.
## Colaboradores
- <NAME>
- <NAME>
- <NAME>
- <NAME>
## Licencia

No se admite la comercialización de este producto ni la copia ilegitima del mismo.
<file_sep>/webpack.mix.js
let mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
mix //dependencias de usuario
.copyDirectory('resources/assets/usuario/img','public/img')
.scripts(
[
'node_modules/jquery/dist/jquery.min.js',
'resources/assets/usuario/js/bootstrap.min.js',
'resources/assets/usuario/js/material.min.js',
'node_modules/chartist/dist/chartist.min.js',
'node_modules/arrive/minified/arrive.min.js',
'node_modules/perfect-scrollbar/dist/js/perfect-scrollbar.jquery.min.js',
'node_modules/bootstrap-notify/bootstrap-notify.min.js',
'resources/assets/usuario/js/material-dashboard.js'
], 'public/js/usuario.vendor.js')
.js('resources/assets/js/usuario.js', 'public/js')
.sass('resources/assets/sass/usuario.scss', 'public/css')
//dependecias de invitado
.copyDirectory('resources/assets/invitado/img','public/img')
.scripts(
[
'node_modules/jquery/dist/jquery.min.js',
'resources/assets/invitado/js/bootstrap.min.js',
'resources/assets/invitado/js/material.min.js',
'resources/assets/invitado/js/nouislider.min.js',
'resources/assets/invitado/js/bootstrap-datepicker.js',
'resources/assets/invitado/js/material-kit.js'
], 'public/js/invitado.vendor.js')
.js('resources/assets/js/invitado.js', 'public/js')
.sass('resources/assets/sass/invitado.scss', 'public/css')
.sourceMaps();
|
5b5929b0db8047034dd0b9310eb3c16df7c0eb35
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
serobalino/PortalDeLaVida
|
52b5fa97951e10f32c06c37658dc908149e09ba5
|
0e7570302ac6f12763b84d351f157cbaebe9d75c
|
refs/heads/master
|
<repo_name>sam-obembe/react-1-afternoon<file_sep>/src/components/Topics/Sum.js
import React, {Component} from "react";
class Sums extends Component{
constructor(){
super();
this.state = {
number1: 0,
number2: 0,
sum: null
}
this.updateFirstNum = this.updateFirstNum.bind(this)
this.updateSecondNum = this.updateSecondNum.bind(this)
this.addition = this.addition.bind(this)
}
updateFirstNum(val){
this.setState({number1: parseInt(val,10)});
}
updateSecondNum(val){
this.setState({number2: parseInt(val,10)});
}
addition(){
let answer =this.state.number1 + this.state.number2;
this.setState({sum:answer.toString()})
}
render(){
return(
<div className = "puzzleBox sumPB">
<h4>Sum</h4>
<input className = "inputLine" type ="number" onChange = {(el) => this.updateFirstNum(el.target.value)}/>
<input className = "inputLine" type ="number" onChange = {(el) => this.updateSecondNum(el.target.value)}/>
<button className = "confirmationButton" onClick = {this.addition}>Add</button>
<span className = "resultsBox"> Sum: {this.state.sum} </span>
</div>
)
}
}
export default Sums;<file_sep>/src/components/Topics/FilterObject.js
import React, {Component} from 'react';
class FilterObject extends Component {
constructor(){
super();
this.state = {
videoGames :[
{
name:"Red Dead",
price:45,
ageRating: "M",
},
{
name: "<NAME>",
price:55,
ageRating: "3+",
},
{
name:"Battle Field 1",
price: 35,
ageRating: "M",
},
{
name: "Assassin's creed origins",
price:60,
ageRating: "M",
}
],
userInput : "",
filteredVideoGames: []
}
}
handleChange(val){
this.setState({userInput: val});
}
updater(prop){
var videoGames = this.state.videoGames.map;
var filteredGames = [];
for(var i = 0; i<videoGames.length;i++){
if(videoGames[i].hasOwnProperty(prop)){
filteredGames.push(videoGames[i]);
}
}
this.setState({filteredVideoGames:filteredGames})
}
render(){
return(
<div className = "puzzleBox filterObjectPB">
<h4>Filter Object</h4>
<span className = "puzzleText">Original: {JSON.stringify(this.state.videoGames,null,10)}</span>
<input className = "inputLine" onChange = {(e)=> this.handleChange(e.target.value)}></input>
<button className = "confirmationButton" onClick = {() => this.updater(this.state.userInput) }>Filter </button>
<span className = "resultsBox filterObjectRB">Filtered: {JSON.stringify(this.state.filteredVideoGames,null,10)}</span>
</div>
)
}
}
export default FilterObject;
|
71a8a55ad94dfc253acd888dd2483fb67bdaf4b5
|
[
"JavaScript"
] | 2
|
JavaScript
|
sam-obembe/react-1-afternoon
|
d5561a9cce1f50caa4e4c0d5e33efbe40371939b
|
38a2678cfa9fbb0f7abcd963bef06b8cd970127e
|
refs/heads/master
|
<file_sep>const app = document.getElementById("app");
const initApp = () => {
const navContainerId = util.uuid();
const btnAddEntryId = util.uuid();
const btnSettingsId = util.uuid();
const btnAboutId = util.uuid();
const totalBalanceId = util.uuid();
const totalCreditId = util.uuid();
const totalDebitId = util.uuid();
const budgetTableId = util.uuid();
let showAddEditBudgetForm = ()=>{};
let budgetsList = [];
util.setHtml(app.id, "");
util.appendHtml(app.id, templates.navBar(navContainerId));
util.appendHtml(navContainerId, templates.button(btnAddEntryId, "Add Entry", "btn-primary m-1"));
util.appendHtml(navContainerId, templates.button(btnSettingsId, "Budget Settings", "btn-dark m-1"));
util.appendHtml(navContainerId, templates.button(btnAboutId, "About", "btn-light m-1"));
util.appendHtml(app.id, templates.mainPage(totalBalanceId, totalCreditId, totalDebitId, budgetTableId));
const setDbId = (newId)=>{
let id = newId || util.uuid();
document.cookie = "id="+id;
return id;
};
let currentDatabaseId = setDbId(document.cookie.split("=")[1]);
const calculateBudget = () => {
let totalBalance = 0;
let totalCredit = 0;
let totalDebit = 0;
if(budgetsList.length !== 0){
budgetsList.forEach(bObject => {
if(bObject.type === "d"){
totalDebit += bObject.amount;
} else {
totalCredit += bObject.amount;
}
});
}
totalBalance = totalCredit - totalDebit;
util.setHtml(totalBalanceId, `${totalBalance} KWD`);
util.setHtml(totalCreditId, `${totalCredit} KWD`);
util.setHtml(totalDebitId, `${totalDebit} KWD`);
};
const updateBudget = (updatedBudgetObject) => {
for(let i = 0; i < budgetsList.length; i++){
if(budgetsList[i]._id === updatedBudgetObject._id){
budgetsList[i] = updatedBudgetObject;
break;
}
}
};
const renderBudgetTable = ()=>{
util.setHtml(budgetTableId, "");
if(budgetsList.length === 0){ util.setHtml(budgetTableId, templates.emptyTable()); }
const debitList = [];
const creditList = [];
budgetsList.forEach(bObj =>{
bObj.btnEdit = util.uuid();
bObj.btnDelete = util.uuid();
bObj.btnInfo = util.uuid();
bObj.containerId = util.uuid();
if(bObj.type === "d"){
debitList.push(bObj);
} else {
creditList.push(bObj);
}
});
const tempOrderedList = [...creditList, ...debitList];
tempOrderedList.forEach(bObject => {
util.appendHtml(budgetTableId, templates.budgetRecord(bObject));
util.onClick(bObject.btnDelete, ()=>{
if(confirm("Are you sure you want to delete this record?")){
if(api.deleteBudget(bObject._id)){
for(let i = 0; i< budgetsList.length; i++){
if(budgetsList[i]._id === bObject._id){
budgetsList.splice(i, 1); break;
}
}
renderBudgetTable();
}
}
});
util.onClick(bObject.btnInfo, ()=>{
const modalId = util.uuid();
const footerId = util.uuid();
const bodyId = util.uuid();
const btnCancelId = util.uuid();
util.initModal(modalId,
"Details",
bodyId,
footerId);
util.setHtml(bodyId, templates.budgetInfo(bObject));
util.setHtml(footerId, templates.button(btnCancelId, "Close", "btn-secondary"));
util.onClick(btnCancelId, ()=>{
util.hideModal(modalId);
});
util.showModal(modalId);
});
util.onClick(bObject.btnEdit, ()=>{
showAddEditBudgetForm(bObject);
});
});
calculateBudget();
};
const loadBudget = async () => {
util.setHtml(budgetTableId, templates.loadingTable());
budgetsList = await api.getBudgetsByGroup(currentDatabaseId);
renderBudgetTable();
};
showAddEditBudgetForm = async (formObject) => {
const modalId = util.uuid();
const footerId = util.uuid();
const bodyId = util.uuid();
const radioCreditId = util.uuid();
const radioDebitId = util.uuid();
const titleId = util.uuid();
const notesId = util.uuid();
const amountId = util.uuid();
const alertId = util.uuid();
const btnCancelId = util.uuid();
const btnSaveId = util.uuid();
const editMode = formObject ? true : false;
util.initModal(modalId,
editMode ? "Edit Budget" : "Add Budget",
bodyId,
footerId);
util.setHtml(bodyId, templates.formAddEditBudget(radioDebitId, radioCreditId, titleId, notesId, amountId, alertId));
util.setHtml(footerId, templates.button(btnCancelId, "Cancel", "btn-secondary") + templates.button(btnSaveId, editMode ? "Save" : "Add", "btn-primary"));
util.onClick(btnCancelId, ()=>{
util.hideModal(modalId);
});
if(editMode){
util.setVal(titleId, formObject.title);
util.setVal(notesId, formObject.notes);
util.setVal(amountId, formObject.amount);
util.setVal(radioDebitId, formObject.type === "d");
util.setVal(radioCreditId, formObject.type === "c");
}
util.onClick(btnSaveId, async () => {
const title = util.getVal(titleId);
const notes = util.getVal(notesId);
const amount = util.getVal(amountId);
const rDebit = util.getVal(radioDebitId);
const type = rDebit ? "d" : "c";
if(amount === "" || title === ""){
util.setHtml(alertId, templates.alert("Please fill required fields", "warning"));
return;
} else { util.setHtml(alertId, ""); }
util.setButton(btnSaveId, templates.loadingButton(), true);
util.setButton(btnCancelId, "Cancel", true);
let serverBudgetObject = null;
if(editMode) {
serverBudgetObject = await api.updateBudget({ id: formObject._id, amount, title, notes, type });
} else {
serverBudgetObject = await api.addBudget({ amount, title, notes, groupId: currentDatabaseId, type });
}
util.setButton(btnSaveId, "Save", false);
util.setButton(btnCancelId, "Cancel", false);
if(serverBudgetObject){
if(editMode){
updateBudget(serverBudgetObject);
} else {
budgetsList.push(serverBudgetObject);
}
renderBudgetTable();
util.hideModal(modalId);
} else {
console.log(editMode);
util.setHtml(alertId, templates.alert("Error Saving Data", "danger"));
}
});
util.showModal(modalId);
};
const showBudgetSettingsForm = () => {
const modalId = util.uuid();
const footerId = util.uuid();
const bodyId = util.uuid();
const btnCancelId = util.uuid();
const btnSaveId = util.uuid();
const sessionId = util.uuid();
const sessionInputId = util.uuid();
util.initModal(modalId,
"Budget Settings",
bodyId,
footerId);
util.setHtml(bodyId, templates.formBudgetSettings(sessionId, sessionInputId));
util.setHtml(footerId, templates.button(btnCancelId, "Cancel", "btn-secondary") + templates.button(btnSaveId, "Save", "btn-primary"));
util.setHtml(sessionId, currentDatabaseId);
util.onClick(btnCancelId, ()=>{
util.hideModal(modalId);
});
util.onClick(btnSaveId, ()=>{
currentDatabaseId = setDbId(util.getVal(sessionInputId));
util.hideModal(modalId);
loadBudget();
});
util.showModal(modalId);
};
const showAbout = () => {
const modalId = util.uuid();
const footerId = util.uuid();
const bodyId = util.uuid();
const btnCancelId = util.uuid();
util.initModal(modalId,
"About",
bodyId,
footerId);
util.setHtml(bodyId, templates.aboutBudget());
util.setHtml(footerId, templates.button(btnCancelId, "Close", "btn-secondary"));
util.onClick(btnCancelId, ()=>{
util.hideModal(modalId);
});
util.showModal(modalId);
};
util.onClick(btnAddEntryId, ()=>{
showAddEditBudgetForm(null);
});
util.onClick(btnSettingsId, ()=>{
showBudgetSettingsForm();
});
util.onClick(btnAboutId, ()=>{
showAbout();
});
loadBudget();
util.initMobileMenu();
};
initApp();<file_sep># Monthly Budget Calculator
Technology Stack: MongoDB, NodeJS, Express, Bootstrap, Native JavaScript.
<file_sep>module.exports = {
development: {
port: process.env.PORT || 3000,
saltingRounds: 10,
corsOptions: {
origin: [`http://localhost:8080`],
credentials: true
},
jwtSecure: false,
jwtCookieExpiry: new Date(Date.now() + 604800000),
jwtOption: { expiresIn: '1d', issuer: process.env.ISSUER },
jwtSecret: process.env.JWT_SECRET,
mongoUri: process.env.ATLAS_URI_RW
},
production: {
port: process.env.PORT || 80,
saltingRounds: 10,
corsOptions: {
origin: [`https://monthly-budget-calculator.herokuapp.com`],
credentials: true
},
jwtSecure: true,
jwtCookieExpiry: new Date(Date.now() + 604800000),
jwtOption: { expiresIn: '1d', issuer: process.env.ISSUER },
jwtSecret: process.env.JWT_SECRET,
mongoUri: process.env.ATLAS_URI_RW
}
}<file_sep>const api = {
endpoint: "/api/v1",
deleteBudget: async (id) => {
try {
const response = await fetch(`${api.endpoint}/budget/${id}`, {method: "DELETE"});
if(response.ok){
let data = await response.json();
if(data.deleted === 1) {
return true;
}
}
} catch (error) { return false; }
},
addBudget: async (objectToAdd) => {
try {
const response = await fetch(`${api.endpoint}/budget`,
{ method: 'POST', headers: {'Accept': 'application/json', 'Content-Type': 'application/json'}, body: JSON.stringify(objectToAdd)});
if(response.ok){
let data = await response.json();
return data.newRecord;
}
} catch (error) {
return null;
}
},
updateBudget: async (objectToAdd) => {
try {
const response = await fetch(`${api.endpoint}/budget`,
{ method: 'PUT', headers: {'Accept': 'application/json', 'Content-Type': 'application/json'}, body: JSON.stringify(objectToAdd)});
if(response.ok){
let data = await response.json();
return data.updatedRecord;
}
} catch (error) {
return null;
}
},
getBudgetsByGroup: async (groupId)=>{
try {
const response = await fetch(`${api.endpoint}/budget/group/${groupId}`);
if(response.ok){
const data = await response.json();
if(data.list.length > 0){
return data.list;
}
return [];
}
return [];
} catch (error) {
return [];
}
}
};<file_sep>
const Budget = require('../models/budget.model');
module.exports = (router) => {
router.route('/budget').get(async (request, response) => {
const strip = { '__v': 0};
try {
const list = await Budget.find({}, strip).exec();
response.json({ status: 1, list });
} catch (error) {
console.log(error);
response.json({ status: -1, error });
}
});
router.route('/budget/group/:id').get(async (request, response) => {
const {id} = request.params;
try {
const records = await Budget.find({ groupId: id }).exec();
if(records.length > 0){
response.json({
status: 1,
list: records
});
} else {
response.json({
status: 1,
list: []
});
}
} catch (error) {
response.json({ status: -1, error });
}
});
router.route('/budget').post(async (request, response) => {
try {
const newRecord = await new Budget(request.body).save();
response.json({
status: 1,
newRecord
});
} catch (error) {
response.json({
status: -1,
error
});
}
});
router.route('/budget/:id').delete(async (request, response) => {
const {id} = request.params;
try {
const records = await Budget.deleteOne({_id: id}).exec();
if(records.deletedCount > 0){
response.json({
status: 1,
deleted: records.deletedCount
});
} else {
response.json({
status: -1,
error: "not found"
});
}
} catch (error) {
response.json({
status: -1,
error
});
}
});
router.route('/budget').put(async (request, response) => {
const object = request.body;
try {
const budgets = await Budget.updateOne({ _id: object.id }, object).exec();
if(budgets.n > 0 || budgets.nModified > 0){
const records = await Budget.findOne({ _id: object.id }).exec();
response.json({
status: 1,
updatedRecord: records
});
} else {
response.json({
status: -1,
error: "not found"
});
}
} catch (error) {
response.json({
status: -1,
error
});
}
});
return router;
};
|
6c3688157d8b0d23d4b6b015fd351a75047b22ec
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
anasnajaa/Monthly-Budget-Calculator
|
e9f08d8fbd75f0256a858de2fb134914ed1d021a
|
f0134c428bf2bfa258ba194ea0a3a2e9f61d418d
|
refs/heads/main
|
<repo_name>parvez843/Robot-Leena<file_sep>/robot-control/demo.py
import time
import RPi.GPIO as GPIO
from adafruit_servokit import ServoKit
'''GPIO.setmode(GPIO.BCM)
GPIO.setup(11,GPIO.OUT)
servo1=GPIO.PWM(11,50)
servo1.start(2)'''
h = ServoKit(channels=16)
'''
servo move demo
servo1.ChangeDutyCycle(12) for gpio pin
kit.servo[0].angle = angle for I2C
'''
init = [0,90,20,0,180,160,170,180,60,0,0,150]
limit = [35, 180, 0, 180, 140, 180, 180, 180, 180, 180, 180, 180]
cur = init
def changeDegree(pin,newDegree):
maxChange = 0
pinSize = len(pin)
for i in range(0,pinSize):
maxChange = max(abs(cur[pin[i]]-newDegree[i]),maxChange)
for deg in range(0,maxChange,5):
for i in range(0,pinSize):
if cur[pin[i]]<newDegree[i]:
cur[pin[i]] += 5
elif cur[pin[i]]>newDegree[i]:
cur[pin[i]] -= 5
for i in range(0,pinSize):
h.servo[pin[i]].angle = cur[pin[i]]
time.sleep(0.05)
def takePosition():
for i in range(0,12):
h.servo[i].angle = init[i]
time.sleep(0.05)
def takePositionSlow():
for i in range(0,12):
changeDegree(i,init[i])
<file_sep>/robot-control/hands_up.py
import time
import RPi.GPIO as GPIO
from adafruit_servokit import ServoKit
h = ServoKit(channels=16)
direction = [1, 2, 1, 1, -1, -1, -1, -1, 1, 1, 1, -1]
init = [0,90,20,0,180,160,170,180,60,0,0,150]
limit = [35,180,180,0,0,40,0,0,180,180,180,30]
cur = init
def changeDeg(pin1,new1,pin2,new2):
now1 = cur[pin1]
now2 = cur[pin2]
for deg in range(0,max(abs(now1-new1),abs(now2-new2)),5):
if now1<new1:
now1=now1+5
elif now1>new1:
now1=now1-5
if now2<new2:
now2=now2+5
elif now2>new2:
now2=now2-5
h.servo[pin1].angle=now1
h.servo[pin2].angle=now2
time.sleep(0.05)
cur[pin1]=now1
cur[pin2]=now2
for i in range(0,12):
h.servo[i].angle = init[i]
time.sleep(1)
changeDeg(10,180,7,0)
changeDeg(5,40,2,140)
changeDeg(4,90,3,90)
changeDeg(10,130,7,70)
time.sleep(2)
changeDeg(10,0,7,180)
changeDeg(4,180,3,0)
changeDeg(5,160,2,20)
time.sleep(2)
for i in range(0,12):
h.servo[i].angle = init[i]
<file_sep>/README.md
# Robot Leena
## **It is Raspberry Pi based Humanoid Robot**
<!--lint ignore double-link-->
<img src="https://i.imgur.com/qI1Jfyl.gif" align="right" width="60%" />
<br/>
## It's made by team [robosouls](https://www.facebook.com/robosouls):
| Name | Post | Email |
| ------------------ | --------- | ----------------------------- |
| [**<NAME>**](https://www.facebook.com/shanjit.mondol.50) | [Circuit Designer](https://github.com/shanjit11) | <EMAIL> |
| [**<NAME>**](https://www.facebook.com/dev.jewel.5/) | [Programmer](https://github.com/DevJewel143) | <EMAIL> |
| [**<NAME>**](https://www.facebook.com/mestu.paul.812) | [Programmer](https://github.com/Mestu-Paul) |<EMAIL> |
<!--lint ignore double-link-->
<img src="Store/gif/robothand.gif" align="right" width="30%" />
## Here we used:
1. **Raspberry Pi** as a cpu of our robot
2. **Servo Motors** for various hand's move
3. **DC Motos** for runing
4. **Ultrasonic Sensors** for count distance
5. **LED** for indicators
6. **LCD Display** for showing message
7. **Aluminium** sheet, **Aluminum** angle, **SS** for making robot body
8. **Makeup Mannequin** as a robot face
<!--lint ignore double-link-->
<img src="Store/gif/pushup.gif" align="right" width="30%" />
<br />
## It's able to -
* Take a cammand and replay accrding to command
* Hand's UP
* Hand Shake
* Salute
* Go forward and backword
* Turn left and right
<!--lint ignore double-link-->
<img align="right" src="https://i.imgur.com/BzOnbkS.gif" />
## Programming Language and tools we used -
| Python | C++ | Bash | Terminal | Raspberry Pi | Arduino |
| ------ | ----| ------| -------- | ------------ | --------- |
|<img align="left" width="46px" src="https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/python/python.png" />|<img align="left" width="46px" src="https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/cpp/cpp.png" />|<img align="left" width="46px" src="https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/bash/bash.png" />|<img align="left" width="46px" src="https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/terminal/terminal.png" />|<img align="left" width="46px" src="https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/raspberry-pi/raspberry-pi.png" />|<img align="left" width="46px" src="https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/arduino/arduino.png" />|
<br />
<br />
## Servo move direcection:
### Servo Initial positions:
|servo no | position | Limitation |
| ----- | ------ | ---------- |
| 1 | 0 | 35 |
| 2 | 90 | 180|
|3 | 20 | 0 |
|4 | 0 | 180 |
|5 | 180 | 140 |
|6 | 160 | 180 |
|7 | 170 | 180 |
|8 | 180 | 180 |
|9 | 60 | 180 |
|10 | 0 | 180 |
|11 | 0 | 180 |
|12 | 150 | 180 |
|13 | - | - |
|14 | - | - |
|15 | - | - |
|16 | - | - |
|17 | - | - |
|18 | - | - |
|19 | - | - |
|20 | - | - |
|21 | - | - |
|22 | - | - |
### salute
>start.
| pin | degree |
| --- | ------ |
| 7 | 0 |
| 3 | 180 |
| 7 | 80 |
| 6 | 60 |
>normal
| pin | degree |
| --- | ------ |
| 7 | 180 |
| 3 | 0 |
| 6 | 170 |
<br/>
<br/>
### Hug
> start
| pin1 | degree | pin2 | degree |
| ---- | ------- | -----| -------|
| 7 | 0| 10 |180|
|3 |90 |4 |90 |
|2 |50 | 5 |150|
|7 | 50 | 10 |130|
|6 |90 |9 |90|
>stop
| pin1 | degree | pin2 | degree |
| ---- | ------- | -----| -------|
|7| 180| 10| 0|
|3 |0| 4| 180|
|2 |20 |5| 160|
|6 |170 | 9 |10|
<br/>
<br/>
### hand_shake
>start
| pin | degree |
| ----| ---- |
| 3 | 60 |
|7 |150|
>shake
```python
for i in range(0, 10):
if i&1:
pin 7 = 170
else:
pin 7 = 120
```
>normal
| pin | degree |
| ----| ---- |
| 7 | 180 |
|3 | 0|
<br/>
<br/>
### hand's_up.py
>start
| pin1 | degree | pin2 | degree |
| ---- | ------- | -----| -------|
|10| 180| 7| 0|
|5 |40 |2 |140|
|4 |90| 3| 90|
|10 |130| 7 |70|
>stop
| pin1 | degree | pin2 | degree |
| ---- | ------- | -----| -------|
|10 | 0 | 7 | 180 |
|4 | 180| 3| 0|
|5 | 160 | 2 | 20|
<br/>
<br/>
### Contributors :pray: :dizzy:

|
ea54d918c05e882187ecfcc58e020444bdc6e35d
|
[
"Markdown",
"Python"
] | 3
|
Python
|
parvez843/Robot-Leena
|
2f2e406bc5a7d87101f809c2e5ffc7aefe2b300e
|
a79e2d87dfa0497017500dc6f501a1f8e2324d21
|
refs/heads/master
|
<file_sep><?php
/*
* <NAME> (<EMAIL>)
* Github: https://github.com/alissonpelizaro/SkypePHP
*
* Pt: Classe principal de integração de baixo nivel
* En: Main class of low-level Skype integration
*/
class Skype extends Methods{
/* Public user data */
public $username;
/* Private user data */
private $password;
private $registrationToken;
private $skypeToken;
private $hashedUsername;
private $randId;
private $logged = false;
private $expiry = 0;
/* Private objects */
private $engine;
private $methods;
private $config;
public function getRandIdUrl($url){
$url = explode("cobrandid=", $url);
if(!isset($url[1])) return false;
$url = explode("&username", $url[1]);
if(!isset($url[0])) return false;
return $url[0];
}
public function login($username, $password, $folder = "skypephp"){
$this->username = $username;
$this->password = $<PASSWORD>;
$this->folder = $folder;
$this->hashedUsername = sha1($username);
if (file_exists($this->folder)) {
if (file_exists("{$this->folder}/auth_{$this->hashedUsername}")) {
$auth = json_decode(file_get_contents("{$this->folder}/auth_{$this->hashedUsername}"), true);
if (time() >= $auth["expiry"])
unset($auth);
}
} else {
if (!mkdir("{$this->folder}"))
exit(trigger_error("Skype : Unable to create the SkypePHP directoy.", E_USER_WARNING));
}
if (isset($auth)) {
$this->skypeToken = $auth["skypeToken"];
$this->registrationToken = $auth["registrationToken"];
$this->expiry = $auth["expiry"];
return true;
} else {
return $this->loginRequest();
}
return false;
}
private function loginRequest() {
$loginForm = $this->web("https://login.skype.com/login/oauth/microsoft?client_id=578134&redirect_uri=https%3A%2F%2Fweb.skype.com%2F&username={$this->username}", "GET", [], true, true);
preg_match("`urlPost:'(.+)',`isU", $loginForm, $loginURL);
$loginURL = $loginURL[1];
$this->randId = $this->getRandIdUrl($loginURL);
preg_match("`name=\"PPFT\" id=\"(.+)\" value=\"(.+)\"`isU", $loginForm, $ppft);
$ppft = $ppft[2];
preg_match("`t:\'(.+)\',A`isU", $loginForm, $ppsx);
$ppsx = $ppsx[1];
preg_match_all('`Set-Cookie: (.+)=(.+);`isU', $loginForm, $cookiesArray);
$cookies = "";
for ($i = 0; $i <= count($cookiesArray[1])-1; $i++)
$cookies .= "{$cookiesArray[1][$i]}={$cookiesArray[2][$i]}; ";
$post = [
"loginfmt" => $this->username,
"login" => $this->username,
"passwd" => $<PASSWORD>,
"type" => 11,
"PPFT" => $ppft,
"PPSX" => $ppsx,
"NewUser" => (int)1,
"LoginOptions" => 3,
"FoundMSAs" => "",
"fspost" => (int)0,
"i2" => (int)1,
"i16" => "",
"i17" => (int)0,
"i18" => "__DefaultLoginStrings|1,__DefaultLogin_Core|1,",
"i19" => 556374,
"i21" => (int)0,
"i13" => (int)0
];
$loginForm = $this->web($loginURL, "POST", $post, true, true, $cookies);
preg_match("`<input type=\"hidden\" name=\"NAP\" id=\"NAP\" value=\"(.+)\">`isU", $loginForm, $NAP);
preg_match("`<input type=\"hidden\" name=\"ANON\" id=\"ANON\" value=\"(.+)\">`isU", $loginForm, $ANON);
preg_match("`<input type=\"hidden\" name=\"t\" id=\"t\" value=\"(.+)\">`isU", $loginForm, $t);
if (!isset($NAP[1]) || !isset($ANON[1]) || !isset($t[1]))
exit(trigger_error("Skype : Authentication failed for {$this->username}", E_USER_WARNING));
$NAP = $NAP[1];
$ANON = $ANON[1];
$t = $t[1];
preg_match_all('`Set-Cookie: (.+)=(.+);`isU', $loginForm, $cookiesArray);
$cookies = "";
for ($i = 0; $i <= count($cookiesArray[1])-1; $i++)
$cookies .= "{$cookiesArray[1][$i]}={$cookiesArray[2][$i]}; ";
$post = [
"NAP" => $NAP,
"ANON" => $ANON,
"t" => $t
];
$loginForm = $this->web("https://lw.skype.com/login/oauth/proxy?client_id=578134&redirect_uri=https://web.skype.com/&site_name=lw.skype.com&wa=wsignin1.0", "POST", $post, true, true, $cookies);
preg_match("`<input type=\"hidden\" name=\"t\" value=\"(.+)\"/>`isU", $loginForm, $t);
$t = $t[1];
$post = [
"t" => $t,
"site_name" => "lw.skype.com",
"oauthPartner" => 999,
"form" => "",
"client_id" => 578134,
"redirect_uri" => "https://web.skype.com/"
];
$login = $this->web("https://login.skype.com/login/microsoft?client_id=578134&redirect_uri=https://web.skype.com/", "POST", $post);
preg_match("`<input type=\"hidden\" name=\"skypetoken\" value=\"(.+)\"/>`isU", $login, $skypeToken);
$this->skypeToken = $skypeToken[1];
$login = $this->web("https://client-s.gateway.messenger.live.com/v1/users/ME/endpoints", "POST", "{}", true);
preg_match("`registrationToken=(.+);`isU", $login, $registrationToken);
$this->registrationToken = $registrationToken[1];
$expiry = time()+21600;
$cache = [
"skypeToken" => $this->skypeToken,
"registrationToken" => $this->registrationToken,
"expiry" => $expiry
];
$this->expiry = $expiry;
$this->logged = true;
file_put_contents("{$this->folder}/auth_{$this->hashedUsername}", json_encode($cache));
return true;
}
private function web($url, $mode = "GET", $post = [], $showHeaders = false, $follow = true, $customCookies = "", $customHeaders = []) {
if (!function_exists("curl_init"))
exit(trigger_error("Skype : cURL is required", E_USER_WARNING));
if (!empty($post) && is_array($post))
$post = http_build_query($post);
if ($this->logged && time() >= $this->expiry) {
$this->logged = false;
$this->loginRequest();
}
$headers = $customHeaders;
if (isset($this->skypeToken)) {
$headers[] = "X-Skypetoken: {$this->skypeToken}";
$headers[] = "Authentication: skypetoken={$this->skypeToken}";
}
if (isset($this->registrationToken))
$headers[] = "RegistrationToken: registrationToken={$this->registrationToken}";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
if (!empty($headers))
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $mode);
if (!empty($post)) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
if ($customCookies)
curl_setopt($curl, CURLOPT_COOKIE, $customCookies);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36");
curl_setopt($curl, CURLOPT_HEADER, $showHeaders);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, $follow);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
public function logout() {
if (!$this->logged)
return true;
unlink("{$this->folder}/auth_{$this->username}");
unset($this->skypeToken);
unset($this->registrationToken);
return true;
}
public function getUnreadMessages(){
//$this->randId = "2befc4b5-19e3-46e8-8347-77317a16a5a5";
//$req = json_decode($this->web("https://client-s.gateway.messenger.live.com/v1/users/ME/endpoints/%7B".$this->randId."%7D"), true);
return false;
}
public function getConversationsList() {
$req = json_decode($this->web("https://client-s.gateway.messenger.live.com/v1/users/ME/conversations?view=supportsExtendedHistory%7Cmsnp24Equivalent&pageSize=25&startTime=1&targetType=Passport%7CSkype%7CLync%7CThread%7CAgent%7CShortCircuit%7CPSTN%7CSmsMms%7CFlxt%7CNotificationStream%7CCast%7CCortanaBot%7CModernBots%7CsecureThreads%7CInviteFree"), true);
return $req;
}
public function getLocalUserId(){
$req = json_decode($this->web("https://client-s.gateway.messenger.live.com/v1/users/ME/endpoints"), true);
if(isset($req[0]['id'])){
return $req[0]['id'];
}
return false;
}
private function URLToUser($url) {
$url = explode(":", $url, 2);
return end($url);
}
private function timestamp() {
return str_replace(".", "", microtime(1));
}
public function sendMessage($user, $message) {
$user = $this->URLtoUser($user);
$mode = strstr($user, "thread.skype") ? 19 : 8;
$messageID = $this->timestamp();
$post = [
"content" => $message,
"messagetype" => "RichText",
"contenttype" => "text",
"clientmessageid" => $messageID
];
$req = json_decode($this->web("https://client-s.gateway.messenger.live.com/v1/users/ME/conversations/$mode:$user/messages", "POST", json_encode($post)), true);
return isset($req["OriginalArrivalTime"]) ? $messageID : 0;
}
public function getMessagesList($user, $size = 100) {
$user = $this->URLtoUser($user);
if ($size > 199 or $size < 1)
$size = 199;
$mode = strstr($user, "thread.skype") ? 19 : 8;
$req = json_decode($this->web("https://client-s.gateway.messenger.live.com/v1/users/ME/conversations/$mode:$user/messages?startTime=0&pageSize=$size&view=msnp24Equivalent&targetType=Passport|Skype|Lync|Thread"), true);
return !isset($req["message"]) ? $req["messages"] : [];
}
public function createGroup($users = [], $topic = "") {
$members = [];
foreach ($users as $user)
$members["members"][] = ["id" => "8:".$this->URLtoUser($user), "role" => "User"];
$members["members"][] = ["id" => "8:{$this->username}", "role" => "Admin"];
$req = $this->web("https://client-s.gateway.messenger.live.com/v1/threads", "POST", json_encode($members), true);
preg_match("`19\:(.+)\@thread.skype`isU", $req, $group);
$group = isset($group[1]) ? "{$group[1]}@thread.skype" : "";
if (!empty($topic) && !empty($group))
$this->setGroupTopic($group, $topic);
return $group;
}
public function setGroupTopic($group, $topic) {
$group = $this->URLtoUser($group);
$post = [
"topic" => $topic
];
$this->web("https://client-s.gateway.messenger.live.com/v1/threads/19:$group/properties?name=topic", "PUT", json_encode($post));
}
public function getGroupInfo($group) {
$group = $this->URLtoUser($group);
$req = json_decode($this->web("https://client-s.gateway.messenger.live.com/v1/threads/19:$group?view=msnp24Equivalent", "GET"), true);
return !isset($req["code"]) ? $req : [];
}
public function addUserToGroup($group, $user) {
$user = $this->URLtoUser($user);
$post = [
"role" => "User"
];
$req = $this->web("https://client-s.gateway.messenger.live.com/v1/threads/19:$group/members/8:$user", "PUT", json_encode($post));
return empty($req);
}
public function kickUser($group, $user) {
$user = $this->URLtoUser($user);
$req = $this->web("https://client-s.gateway.messenger.live.com/v1/threads/19:$group/members/8:$user", "DELETE");
return empty($req);
}
public function leaveGroup($group) {
$req = $this->kickUser($group, $this->username);
return $req;
}
public function ifGroupHistoryDisclosed($group, $historydisclosed) {
$group = $this->URLtoUser($group);
$post = [
"historydisclosed" => $historydisclosed
];
$req = $this->web("https://client-s.gateway.messenger.live.com/v1/threads/19:$group/properties?name=historydisclosed", "PUT", json_encode($post));
return empty($req);
}
public function getContactsList() {
$userdata = $this->readMyProfile();
if(!isset($userdata['username'])) return [];
$req = json_decode($this->web("https://edge.skype.com/pcs-df/contacts/v2/users/{$userdata['username']}?reason=default"), true);
return isset($req['contacts']) ? $req['contacts'] : [];
}
public function readProfile($list) {
$contacts = "";
foreach ($list as $contact)
$contacts .= "contacts[]=$contact&";
$req = json_decode($this->web("https://api.skype.com/users/self/contacts/profiles", "POST", $contacts), true);
return !empty($req) ? $req : [];
}
public function readMyProfile() {
$req = json_decode($this->web("https://api.skype.com/users/self/profile"), true);
return !empty($req) ? $req : [];
}
public function searchSomeone($username) {
$username = $this->URLtoUser($username);
$req = json_decode($this->web("https://skypegraph.skype.com/search/v1.1/namesearch/swx/?requestid=skype.com-1.63.51&searchstring=$username"), true);
return !empty($req) ? $req : [];
}
public function addContact($username, $greeting = "Hello, I would like to add you to my contacts.") {
$username = $this->URLtoUser($username);
$post = [
"greeting" => $greeting
];
$req = $this->web("https://api.skype.com/users/self/contacts/auth-request/$username", "PUT", $post);
$data = json_decode($req, true);
return isset($data["code"]) && $data["code"] == 20100;
}
public function skypeJoin($id) {
$post = [
"shortId" => $id,
"type" => "wl"
];
$group = $this->web("https://join.skype.com/api/v2/conversation/", "POST", json_encode($post), false, false, false, ["Content-Type: application/json"]);
$group = json_decode($group, true);
if (!isset($group["Resource"]))
return "";
$group = str_replace("19:", "", $group["Resource"]);
return $this->addUserToGroup($group, $this->username);
}
}
?>
<file_sep>
SkypePHP
===========
<NAME> (<EMAIL>)\
Yes, it works!
NOTICE
======
It is a Skype PHP-API that is able to send and receive messages, get contacts, get conversations and much more!
It is still development and I am loneny in this project, so be patient...
Pull requests are always welcome!!
Warning: In the current version, only pure text messages work in chat.
Installation
============
We are suggesting you to use composer, with the following : `php composer.phar require alissonpelizaro/SkypePHP`.
Basic usage
============
Include `src/Core.php` before of all.
```php
$sk = new Skype;
$sk->login('username', 'password') or die ('Username or password is invalid');
```
Documentation
=============
Sorry, I have no time to publish a clean documentation at the moment. You can see `exemple/exemple.php` for technical details. For special support see: https://developer.microsoft.com/en-us/skype/bots/docs
Special Thanks
==============
Special thanks goes to @fujimoto, your low-level knowledge heps me a lot.
<file_sep><?php
/*
* <NAME> (<EMAIL>)
* Github: https://github.com/alissonpelizaro/SkypePHP
*
* Pt: Inclua esse arquivo para carregar toda a biblioteca no seu projeto
* En: Include this file to load whole library in your project
*/
require_once 'modules/Config.class.php';
require_once 'modules/Methods.class.php';
require_once 'modules/Engine.class.php';
require_once 'modules/Skype.class.php';
?>
<file_sep><?php
/*
* <NAME> (<EMAIL>)
* Github: https://github.com/alissonpelizaro/SkypePHP
*
* Pt: Arquivo de exemplo de utilização
* En: Exemple usage file
*/
include '../src/Core.php';
$sk = new Skype;
$sk->login('username', 'password') or die ('Username or password is invalid');
/*
* Pt: Enviar uma mensagen
* En: Send a message
*/
$sk->sendMessage('skype_id', 'Mensagem');
/*
* Pt: Obter array de todas as conversas
* En: Get array of all conversations
*/
//$sk->getConversationsList();
/*
* Pt: Obter mensagens de uma conversa
* En: Get conversation messages
*/
//$sk->getMessagesList('contact_id');
?>
|
515e48d250112e28fee1381de0bb5109876a9fad
|
[
"Markdown",
"PHP"
] | 4
|
PHP
|
AdoboFlush/SkypePHP
|
a75f5d4749185371ed788ee16f6fdd4830358f7f
|
e1619666c305c08ae56ff0d5ba385c4a3b1e7a76
|
refs/heads/master
|
<file_sep>const ethers = require("ethers");
const snarkjs = require("snarkjs");
const web3 = require("web3");
const {stringifyBigInts, unstringifyBigInts} = require("ffjavascript").utils;
const fs = require("fs");
const { Console } = require("console");
const { removeListener } = require("process");
const { createCode } = require("../circomlib/src/mimc_gencontract");
const mimc7 = require("./mimc7.js");
var provider = ethers.providers.getDefaultProvider("rinkeby");
var abi = [
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "subtractedValue",
"type": "uint256"
}
],
"name": "decreaseAllowance",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "spender",
"type": "address"
},
{
"internalType": "uint256",
"name": "addedValue",
"type": "uint256"
}
],
"name": "increaseAllowance",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_addressVerif",
"type": "address"
}
],
"name": "setAddressVerif",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "recipient",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transfer",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "from",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "to",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
},
{
"inputs": [
{
"internalType": "address",
"name": "_to",
"type": "address"
},
{
"internalType": "uint256",
"name": "value",
"type": "uint256"
},
{
"internalType": "string",
"name": "hashSenderBalanceAfter",
"type": "string"
},
{
"internalType": "string",
"name": "hashReceiverBalanceAfter",
"type": "string"
},
{
"components": [
{
"internalType": "uint256[2]",
"name": "a",
"type": "uint256[2]"
},
{
"internalType": "uint256[2][2]",
"name": "b",
"type": "uint256[2][2]"
},
{
"internalType": "uint256[2]",
"name": "c",
"type": "uint256[2]"
},
{
"internalType": "uint256[3]",
"name": "input",
"type": "uint256[3]"
}
],
"internalType": "struct myToken.VerifParameters",
"name": "vSender",
"type": "tuple"
},
{
"components": [
{
"internalType": "uint256[2]",
"name": "a",
"type": "uint256[2]"
},
{
"internalType": "uint256[2][2]",
"name": "b",
"type": "uint256[2][2]"
},
{
"internalType": "uint256[2]",
"name": "c",
"type": "uint256[2]"
},
{
"internalType": "uint256[3]",
"name": "input",
"type": "uint256[3]"
}
],
"internalType": "struct myToken.VerifParameters",
"name": "vReceiver",
"type": "tuple"
}
],
"name": "transferConfidentiel",
"outputs": [
{
"internalType": "bool",
"name": "val",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "sender",
"type": "address"
},
{
"internalType": "address",
"name": "recipient",
"type": "address"
},
{
"internalType": "uint256",
"name": "amount",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [
{
"internalType": "bool",
"name": "",
"type": "bool"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "owner",
"type": "address"
},
{
"internalType": "address",
"name": "spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "account",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "decimals",
"outputs": [
{
"internalType": "uint8",
"name": "",
"type": "uint8"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "getAddressVerif",
"outputs": [
{
"internalType": "address",
"name": "adr",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "_addr",
"type": "address"
}
],
"name": "getBalanceHash",
"outputs": [
{
"internalType": "bytes32",
"name": "",
"type": "bytes32"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "value",
"type": "uint256"
}
],
"name": "mimc",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "name",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "symbol",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
}
];
var abiVerifier = [
{
"inputs": [
{
"internalType": "uint256[2]",
"name": "a",
"type": "uint256[2]"
},
{
"internalType": "uint256[2][2]",
"name": "b",
"type": "uint256[2][2]"
},
{
"internalType": "uint256[2]",
"name": "c",
"type": "uint256[2]"
},
{
"internalType": "uint256[3]",
"name": "input",
"type": "uint256[3]"
}
],
"name": "verifyProofReceiver",
"outputs": [
{
"internalType": "bool",
"name": "r",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256[2]",
"name": "a",
"type": "uint256[2]"
},
{
"internalType": "uint256[2][2]",
"name": "b",
"type": "uint256[2][2]"
},
{
"internalType": "uint256[2]",
"name": "c",
"type": "uint256[2]"
},
{
"internalType": "uint256[3]",
"name": "input",
"type": "uint256[3]"
}
],
"name": "verifyProofSender",
"outputs": [
{
"internalType": "bool",
"name": "r",
"type": "bool"
}
],
"stateMutability": "view",
"type": "function"
}
];
// var addressContractOLD = '0xcA7977e12e736d4d228B4f33a7e9dAFEcb96A77e';
// var addressVerifierOLD = "0x4a97BA615e661aC592AF23d6D71706B8e1B97002";
var addressContract = "0xfa7724cf936f4658B045622bb5D5fE019DDEe66D";
var addressVerifier = "0x9656B7cD29b0<KEY>";
var privateKey = "0xA6D5A42D93548E651DADF701F254BADF58ECFA077CE5D0CE16B069D196F1DAAD"
var wallet = new ethers.Wallet(privateKey,provider);
var contract = new ethers.Contract(addressContract,abi,wallet);
var verifier = new ethers.Contract(addressVerifier,abiVerifier,wallet)
function p256(n) {
let nstr = n.toString(16);
while (nstr.length < 64) nstr = "0"+nstr;
nstr = `"0x${nstr}"`;
return nstr;
}
function generatecall(proofName, publicName) {
const public = unstringifyBigInts(publicName);
const proof = unstringifyBigInts(proofName);
let inputs = "";
for (let i=0; i<public.length; i++) {
if (inputs != "") inputs = inputs + ",";
inputs = inputs + p256(public[i]);
}
let S = [];
if ((typeof proof.protocol === "undefined") || (proof.protocol == "original")) {
S=`[${p256(proof.pi_a[0])}, ${p256(proof.pi_a[1])}],` +
`[${p256(proof.pi_ap[0])}, ${p256(proof.pi_ap[1])}],` +
`[[${p256(proof.pi_b[0][1])}, ${p256(proof.pi_b[0][0])}],[${p256(proof.pi_b[1][1])}, ${p256(proof.pi_b[1][0])}]],` +
`[${p256(proof.pi_bp[0])}, ${p256(proof.pi_bp[1])}],` +
`[${p256(proof.pi_c[0])}, ${p256(proof.pi_c[1])}],` +
`[${p256(proof.pi_cp[0])}, ${p256(proof.pi_cp[1])}],` +
`[${p256(proof.pi_h[0])}, ${p256(proof.pi_h[1])}],` +
`[${p256(proof.pi_kp[0])}, ${p256(proof.pi_kp[1])}],` +
`[${inputs}]`;
} else if ((proof.protocol == "groth16")||(proof.protocol == "kimleeoh")) {
S.push([`${p256(proof.pi_a[0])}`, `${p256(proof.pi_a[1])}`]);
S.push([[`${p256(proof.pi_b[0][1])}`, `${p256(proof.pi_b[0][0])}`],[`${p256(proof.pi_b[1][1])}`, `${p256(proof.pi_b[1][0])}`]]) +
S.push([`${p256(proof.pi_c[0])}`, `${p256(proof.pi_c[1])}`]) +
S.push([`${inputs}`]);
} else {
throw new Error("InvalidProof");
}
return(S);
}
// met en forme les deux fichiers générés par "generateCall"
function cleanCalls(vSender, vReceiver){
function removeElts(str) {
str = str.slice(1);
str = str.slice(0,str.length-1);
return str;
}
var len = vSender.length;
for( var i =0; i< len; i++){
if (i==3){
vSender[i] = vSender[i].toString().split(",");
}
for( var j =0, c = vSender[i].length;j < c; j++){
if(i == 1){
for (var k=0, d = vSender[i][j].length;k<d;k++){
vSender[i][j][k] = removeElts(vSender[i][j][k]);
}
}
else {
vSender[i][j] = removeElts(vSender[i][j]);
}
}
}
len = vReceiver.length;
for( var i =0; i< len; i++){
if (i == 3){
vReceiver[i] = vReceiver[i].toString().split(",");
}
for( var j =0, c = vReceiver[i].length;j < c; j++){
if(i == 1){
for (var k=0, d = vReceiver[i][j].length;k<d;k++){
vReceiver[i][j][k] = removeElts(vReceiver[i][j][k]);
}
}
else {
vReceiver[i][j] = removeElts(vReceiver[i][j]);
}
}
}
}
// cleanCalls(verifSender,verifReceiver);
async function setVerifier(){
await contract.setAddressVerif(addressVerifier).then(tx => console.log(tx));
}
async function interactWContract(){
contract.name().then(res => console.log(res));
contract.totalSupply().then(res => console.log(ethers.utils.formatUnits(res,0)));
contract.getAddressVerif().then(res => console.log(res));
}
async function getPublicData(value, addressSender, addressReceiver){
var publicReceiver= [];
var publicSender= [];
var hashSenderBalanceBefore = await contract.getBalanceHash(addressSender);
hashSenderBalanceBefore = ethers.BigNumber.from(hashSenderBalanceBefore).toString();
var balanceBefore = await contract.balanceOf(addressSender).then(res => res.toNumber());
publicSender = [
hashSenderBalanceBefore,
await contract.mimc(value).then(res => res.toString()),
await contract.mimc(balanceBefore - value).then(res => res.toString())
];
var hashReceiverBalanceBefore = await contract.getBalanceHash(addressReceiver);
hashReceiverBalanceBefore = ethers.BigNumber.from(hashReceiverBalanceBefore).toString();
balanceBefore = await contract.balanceOf(addressReceiver).then(res => res.toNumber());
publicReceiver = [
hashReceiverBalanceBefore,
await contract.mimc(value).then(res => res.toString()),
await contract.mimc(balanceBefore + value).then(res => res.toString())
];
return [publicSender,publicReceiver];
}
async function getPrivateData(senderBalanceBefore, valeur)
{
const { proof, publicSignals } = await snarkjs.groth16.fullProve({senderBalanceBefore: senderBalanceBefore, value: valeur}, "../circuitSender_v2/circuit.wasm", "../circuitSender_v2/circuit_final.zkey");
return JSON.stringify(proof, null, 1)
}
async function transfer(_to, value){
//To see if we can reach the contract
interactWContract();
//we can access the sender's private data not the receiver, receiver has to give the proof
var senderBalance = await contract.balanceOf(wallet.address).then(res => res.toNumber());
console.log("solde", senderBalance);
console.log("hash", await contract.mimc(senderBalance).then(res => res.toString()));
var proofSender = await getPrivateData(senderBalance, value).then(res => JSON.parse(res));
// var proofSender = JSON.parse(fs.readFileSync("../circuitSender_v2/proof.json"));
var proofReceiver = JSON.parse(fs.readFileSync("../circuitReceiver_v2/proof.json"));
//public data is available for everybody
var tmp = await getPublicData(value, wallet.address, _to);
var publicJsonSender = tmp[0];
var publicJsonReceiver = tmp[1];
console.log(publicJsonSender);
console.log(publicJsonReceiver);
//Used to call the verifier contract
var verifSender= generatecall(proofSender, publicJsonSender);
var verifReceiver= generatecall(proofReceiver, publicJsonReceiver);
cleanCalls(verifSender,verifReceiver);
var hashSenderBalanceAfter = publicJsonSender[2];
var hashReceiverBalanceAfter = publicJsonReceiver[2];
await contract.confidentialTransfer(_to, value,
verifSender, verifReceiver).then(res => console.log(res));
}
async function verify(value, _to){
var values = await getPublicData(value, wallet.address, _to);
var publicJsonSender = values[0];
var publicJsonReceiver = values[1];
var verifSender= generatecall(proofSender, publicJsonSender);
var verifReceiver= generatecall(proofReceiver, publicJsonReceiver);
cleanCalls(verifSender,verifReceiver)
console.log(verifSender);
console.log(verifReceiver);
await verifier.verifyProofSender(verifSender[0],verifSender[1],verifSender[2],verifSender[3]).then(res => console.log(res));
await verifier.verifyProofReceiver(verifReceiver[0], verifReceiver[1], verifReceiver[2], verifReceiver[3]).then(res => console.log(res));
}
var bob = "0<KEY>";
// verify(200000,bob);
// 11699975
// 0x0d0b51d13cf41f90f698449148f7b5734f26f50087d0<KEY>84f
transfer(bob,200000).then(() => {
process.exit(0);
});
// console.log("a", proofReceiver);
<file_sep>### ERC20 ZKP
## PROGRAMME NON FONCTIONNEL
Liste de ressources utiles pour la compréhension notamment sur théorie:
https://github.com/matter-labs/awesome-zero-knowledge-proofs
Programme insipré de cet article de Consensys: https://media.consensys.net/introduction-to-zksnarks-with-examples-3283b554fc3b
##### Prérequis:
- git
- node v14
```
npm install -g circom@latest
npm install -g snarkjs@latest
```
Repo of the library snarkjs: https://github.com/iden3/snarkjs
and circom: https://github.com/iden3/circom
En plus du contrat principal [myToken](https://github.com/AntoineMkr/ZKP_ERC20/blob/master/contracts/myToken.sol), j'ai modifié un peu le code du contrat [ERC20](https://github.com/AntoineMkr/ZKP_ERC20/blob/master/contracts/ERC20.sol) d'OpenZeppelin. J'ai aussi modifié le contrat "verifier.sol" pour qu'il puisse vérifier les preuves du sender et du receiver.
Pour déployer les contrats sur Remix:
- aller dans "file explorer"
- cliquer sur la petite icone représentant un dossier
- sélectionner les contrats nécessaires (ERC20 hérite d'autres contrats OpenZeppelin, il faut les ajouter aussi)
- modifier les liens "import" dans les contrats
- être Metamask ready avec un peu de faux ethers (https://faucet.rinkeby.io/)
- sur remix, compiler les contrats
- aller dans la section deploy&run et sélectionner "injected web" (javascript VM ne fonctionne pas très bien)
- sélectionner le contrat à déployer et boum "deploy"
Une fois le verifier.sol et myToken déployés, il faut entrer l'address du verifier dans la fonction setAddressVerif() de myToken.
Le dossier PTAU contient la cérémonie PowersOfTau.
Il devrait noramlement être nécessaire de cloner le répo circomlib: https://github.com/iden3/circomlib. Celui ci contient des cricuits pré-conçus par l'équipe de Circom.
Le dossier scipts contient:
- app.html (ce fichier aurait été utilisé pour créer une interface graphique web)
- genContract.js, utilisé pour publier le contrat mimc qui n'est finalement pas utilisé.
- mimc7.js, implémentation du hash mimc. Le code provient de circomlib.
- script.js, me sert à interagir avec le contrat.
Le dossier migrations contient des scripts migrations générés par Truffle. J'ai commencé à créer le projet en utilisant Truffle mais je ne l'utilise plus. Remix m'a paru bien plus pratique.
Les dossiers circuitReceiver/Sender contiennent tous les fichiers générés pas snarkjs ainsi que les circuits créés en utilisant circom.
Le fichier public.json contient:
- hash solde de départ
- hash valeur du transfert
- hash solde d'arrivée
Le fichier input.json contient:
- solde de départ
- valeur du transfert
Le transfert de fond est collaboratif, les deux parties ont des actions à réaliser. Ils doivent se communiquer la valeur du transfert et doivent publier le hash de leur solde d'arrivée, le hash du solde de départ étant normalement accessible à travers la fonction du smart-contract "getBalanceHash".
Il faudrait rendre la fonction native ERC20 "balanceOf" inaccessible sauf à l'utilisateur. (require(msg.sender == adresseEnParametre))
Comment cacher les sections en clair de cette page: https://rinkeby.etherscan.io/tx/0xf5800405c2b9d9c9ffe1948f39980990510e4234fadf6db48b4e7cc19fbdc62e#statechange ? On voit toujours le solde avant et après, on peut donc savoir le montant de la transaction. Soit on ajoute de la cryptographie pour cacher les soldes mais alors à quoi ça sert d'avoir et les soldes encryptés et les hashs sur la blockchain, autant en ne garder qu'un des deux. Soit on stocke les soldes on dehors de la chaîne mais s'il y a un bug et que les soldes sont modifiés on ne peut plus accéder aux données on-chain. Pourquoi pas créer un second token par dessus comme sur-couche.
Par rapport à la fonction confidentialTransfer, si les soldes sont stockés off-chain il faut entrer les hashs "après-transaction" en paramètre de la fonction et écrire: _balancesHashes[addr] = hashBalanceAfterTx <file_sep>const ethers = require("ethers");
const snarkjs = require("snarkjs");
const {stringifyBigInts, unstringifyBigInts} = require("ffjavascript").utils;
const fs = require("fs");
const { createCode } = require("../circomlib/src/mimc_gencontract");
const { abi } = require("../circomlib/src/mimc_gencontract");
const mimc7 = require("./mimc7.js");
let provider = ethers.providers.getDefaultProvider("rinkeby");
let privateKey = "0xA6D5A42D93548E651DADF701F254BADF58ECFA077CE5D0CE16B069D196F1DAAD"
let wallet = new ethers.Wallet(privateKey,provider);
async function deployC () {
var bytecode = createCode("mimc",91);
const factory = new ethers.ContractFactory(abi, bytecode, wallet);
var contract = await factory.deploy();
console.log(contract.address);
console.log(contract.deployTransaction.hash);
await contract.deployed();
}
// deployC();
console.log(mimc7.getConstants());
// var addressContract = "0xfdf88F12Ef292f88d9086DCA25E75e8538fdF34F";
// var cont = new ethers.Contract(addressContract,abi,wallet);
// (async function (){
// await cont.MiMCpe7(10,2).then(res => console.log(res.toString()));
// })();
<file_sep>#!/bin/bash
rm circuit_*
rm proof.json
rm public.json
rm verification_key.json
rm witness.wtns
<file_sep>const myToken = artifacts.require('myToken');
contracts('myToken', accounts =>{
const _name = 'MECKER';
const _symbol = "MKR";
const _decimals = 2;
it('should have the good name', () =>
myToken.deployed()
.then(instance => instance.name())
.then(nom => {
assert.equal(nom,_name,'pas le bon nom')
})
)
})
<file_sep>#!/bin/bash
snarkjs zkey new circuit.r1cs ../PTAU/pot12_final.ptau circuit_0000.zkey
snarkjs zkey contribute circuit_0000.zkey circuit_0001.zkey --name="1st Contributor Name" -e="bonjour" -v
snarkjs zkey contribute circuit_0001.zkey circuit_0002.zkey --name="Second contribution Name" -v -e="Another random entropy"
snarkjs zkey contribute circuit_0002.zkey circuit_0003.zkey --name="Third contribution Name" -v -e="Another random entropy"
snarkjs zkey verify circuit.r1cs ../PTAU/pot12_final.ptau circuit_0003.zkey
snarkjs zkey beacon circuit_0003.zkey circuit_final.zkey 0<KEY> 10 -n="Final Beacon phase2"
snarkjs zkey verify circuit.r1cs ../PTAU/pot12_final.ptau circuit_final.zkey
snarkjs zkey export verificationkey circuit_final.zkey verification_key.json
snarkjs wtns calculate circuit.wasm input.json witness.wtns
snarkjs wtns debug circuit.wasm input.json witness.wtns circuit.sym --trigger --get --set
snarkjs groth16 prove circuit_final.zkey witness.wtns proof.json public.json
|
d0ccecc5bdf04eca1b8ec869b2b85c62dea041ca
|
[
"JavaScript",
"Markdown",
"Shell"
] | 6
|
JavaScript
|
WillZhuang/ZKP_ERC20
|
87dbb8f8606dc38e4e5d1b51a2c4caec1691b44b
|
64c533d896b62098787df26581ad6db04b13f3a2
|
refs/heads/master
|
<file_sep># DEEP Neural Networks For Caribbean Based Accent Classification
This repo contains the code,csv files for each experimental sets as well as a link to the data collection tool we created. The code include the files we used to preprocess our dataset,the CNN model we created from the accents as well as the code to train the neural network.The goal of this project was to create a accent classifer that is able to classify different Caribbean accents correctly. We used a 2D-CNN as our neural network and we had to collect data from various Caribbean countries ourselves since there were not many available resources we could use on recordings of Caribbean Accents.
The Caribbean countries/islands we used were Trinidad, Tobago, St. Lucia and Barbados. We used these countries as we were able to collect the most recordings them.
## Table of Contents
1. [Data Collection tool](#datacollection)
2. [Dataset](#dataset)
3. [Code Explanation](#code)
* [Training](#training)
* [Preprocessing](#preprocessing)
4. [Results](#results)
## Data Collection tool
The code for our data collection system is available at https://github.com/Kerschel/Dataset-Speech-Collector
This code is hosted on a Digital Ocean cloud server and can be accessed at https://myaccent.app
The code in the [prediction](https://github.com/Kerschel/Accent-CAC/tree/prediction) branch is also used as an API endpoint to perform accent predictions inside the myaccent.app application which currently is not hosted but can be used locally by running the [flask server file](https://github.com/Kerschel/Accent-CAC/blob/prediction/prediction.py).
## Dataset
The files for dataset can be accessed at [Experimental Datasets](https://myuwi-my.sharepoint.com/:f:/g/personal/kerschel_james_my_uwi_edu/Ehq1AkMiCSxJqeOIXPIklsIBHs9uZrAkrXv3KkOoOMCQvA?e=lKdsa5).
## CSV File Format
Each csv file is used to link the accent (HomeCountry) to a corresponding filename. We also added the duration of the file to be able to filter out the files that were not useful to us i.e persons who submitted very short recordings by error.
This filtering was done in [trainmodel.py](training/trainmodel.py) on line 154-161.
## Code Explanation
### Training
Before running the code, all dependencies must be installed first from [requirements.txt](training/requirements.txt). Also ensure that you have python installed to perform the following commands:
```bash
pip install -r requirements.txt
```
To run the project use :
python trainmodel.py "experimental set csvfile" "modelname" "csvfilename for accuracy results"
* For Example:
```bash
python trainmodel.py ES1.csv test_model output.csv
```
Depending on which experimental set you wish to use the directory name needs to be changed in [helpers.py](training/helpers.py) on line 42 to reflect the folder (ES1,ES2,ES3).<br>
The csv file to check the validation and accuracy loss will be in the folder after running the code.
[trainmodel.py](training/trainmodel.py) - this is the main file that bring all the functions together to perform the classification.<br>
[helpers.py](training/helpers.py) - contains functions used for the MFCC processing as well as direction of which audio files are to be used in librosa.<br>
[accuracy.py](training/accuracy.py) - used for the prediction classification to detemine how accuracy the predictions were and to create a confusion matrix to display the results<br>
[getsplit.py](training/getsplit.py) - used to add or remove how many accents will be used in the classifier also to increase or decrease the training and test size.<br>
### Preprocessing
[duration.py](preprocessing/duration.py) - used to find the length of the audio files and save in a csvfile <br> <br>
Used for ES2 alone <br>
[ratereduce.py](preprocessing/ratereduce.py) was used make the audio file slower in order to extract the silence-noise-silence periods from the wave in with [extractwords.py](preprocessing/extractwords.py)
[originalrate.py](preprocessing/originalrate.py) - return the audio files to their original rate from what was lowerered previously<br> <br>
Used for ES2 and ES3 <br>
[padding.py](preprocessing/padding.py) - used for ES2 and ES3 to add silence to the end of the audio files to make them a uniform length<br>
## Results
After training our CNN we were able to acheive best average accuracies as follows on each experimental set:
ES1 - 38.9% on 4 accents<br>
ES2 - 41.25% on 4 accents<br>
ES3 - 68% on 4 accents, 83.3% on 3 accents and 84.1% on 2 accents
The breakdown of ES3 accuracies are as follows:<br>

<file_sep>import helpers as k
import pandas as pd
from collections import Counter
from keras.callbacks import CSVLogger
import sys
import getsplit
import csv
from keras import utils
import accuracy
import multiprocessing
import librosa
import numpy as np
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Flatten
from keras.layers.convolutional import MaxPooling2D, Conv2D
from keras.layers.normalization import BatchNormalization
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import EarlyStopping, TensorBoard
from keras.models import load_model
import tensorflow as tf
DEBUG = True
SILENCE_THRESHOLD = .01
RATE = 24000
N_MFCC = 13
COL_SIZE = 30
EPOCHS = 10 #35#250
def train_model(X_train,y_train,X_validation,y_validation, batch_size=128): #64
'''
Trains 2D convolutional neural network
:param X_train: Numpy array of mfccs
:param y_train: Binary matrix based on labels
:return: Trained model
'''
# Get row, column, and class sizes
rows = X_train[0].shape[0]
cols = X_train[0].shape[1]
val_rows = X_validation[0].shape[0]
val_cols = X_validation[0].shape[1]
num_classes = len(y_train[0])
# input image dimensions to feed into 2D ConvNet Input layer
input_shape = (rows, cols, 1)
X_train = X_train.reshape(X_train.shape[0], rows, cols, 1 )
X_validation = X_validation.reshape(X_validation.shape[0],val_rows,val_cols,1)
device_name = "/device:GPU:1"
# device_name = "/cpu:0"
with tf.device(device_name):
print("Using: {0}".format(device_name))
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'training samples')
# model = Sequential()
# model.add(Conv2D(32,
# kernel_size=(3,3),
# activation='relu',
# data_format="channels_last",
# input_shape=input_shape))
# model.add(BatchNormalization())
# model.add(MaxPooling2D(pool_size=(2, 2)))
# model.add(Conv2D(64,
# kernel_size=(3,3),
# activation='relu'))
# model.add(BatchNormalization())
# model.add(MaxPooling2D(pool_size=(2, 2)))
# model.add(Dropout(0.30))
# model.add(Flatten())
# model.add(Dense(256, activation='relu'))
# model.add(Dropout(0.30))
# model.add(Dense(num_classes, activation='softmax'))
# model.compile(loss='categorical_crossentropy',
# optimizer='adam',
# metrics=['accuracy'])
model = Sequential()
model.add(Conv2D(32, kernel_size=(3,3), activation='relu',
data_format="channels_last",
input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64,kernel_size=(3,3), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.30))
model.add(Flatten())
model.add(Dense(256,kernel_regularizer= keras.regularizers.l2(0.001) , activation='relu'))
model.add(Dropout(0.50))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# Stops training if loss gets worst
es = EarlyStopping(monitor='val_loss', patience=10, verbose=1, mode='auto')
# Creates log file for graphical interpretation using TensorBoard
tb = TensorBoard(log_dir='../logs', histogram_freq=0, batch_size=32, write_graph=True, write_grads=True,
write_images=True, embeddings_freq=0, embeddings_layer_names=None,
embeddings_metadata=None)
# Image shifting
datagen = ImageDataGenerator(width_shift_range=0.05)
# Fit model using ImageDataGenerator
csv_logger = CSVLogger('train-validation.csv', append=True, separator=',')
model.fit_generator(datagen.flow(X_train, y_train, batch_size=batch_size),
steps_per_epoch=len(X_train) / 32
, epochs=EPOCHS,
callbacks=[es,tb,csv_logger], validation_data=(X_validation,y_validation))
# model.fit(X_train,y_train,batch_size=batch_size,epochs=EPOCHS)
return (model)
def save_model(model, model_filename):
'''
Save model to file
:param model: Trained model to be saved
:param model_filename: Filename
:return: None
'''
model.save('{}.h5'.format(model_filename)) # creates a HDF5 file 'my_model.h5'
############################################################
#######################################
if __name__ == '__main__':
'''
Console command example:
python trainmodel.py bio_metadata.csv model50
'''
results=[]
acc = []
# Load arguments
file_name = sys.argv[1]
model_filename = sys.argv[2]
csvfile = sys.argv[3]
# Load metadata
df = k.pd.read_csv(file_name,encoding='ISO-8859-1')
df = df[df.Filename != 'undefined']
df = df[df.Words != 'undefined']
if (csvfile =="ES1.csv"):
df = df[df.duration >=10]
if (csvfile =="ES2.csv"):
df = df[df.duration >=1]
if (csvfile =="ES3.csv"):
df = df[df.duration >=2]
# # Filter metadata to retrieve only files desired
filtered_df = getsplit.filter_df(df)
# Train test split
X_train, X_test, y_train, y_test = k.getsplit.split_people(filtered_df)
# Get statistics
# print (y_train)
train_count = k.Counter(y_train)
test_count = k.Counter(y_test)
print("Entering main")
# import ipdb
# ipdb.set_trace()
acc_to_beat = test_count.most_common(1)[0][1] / float(np.sum(list(test_count.values())))
# print (y_train)
# To categorical
y_train = k.to_categorical(y_train)
# print (y_train)
y_test = k.to_categorical(y_test)
# Get resampled wav files using multiprocessing
if DEBUG:
print('Loading wav files....')
pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
X_train = pool.map(k.get_wav, X_train)
X_test = pool.map(k.get_wav, X_test)
# Convert to MFCC
if DEBUG:
print('Converting to MFCC....')
X_train = pool.map(k.to_mfcc, X_train)
X_test = pool.map(k.to_mfcc, X_test)
# Create segments from MFCCs
X_train, y_train = k.make_segments(X_train, y_train)
X_validation, y_validation = k.make_segments(X_test, y_test)
# print (X_train)
X_train, _, y_train, _ = train_test_split(X_train, y_train, test_size=0)
# trainer = (np.array(X_train) / np.amax(X_train)).astype(np.float32)
# Randomize training segments
# # print (np.array(X_train))
# # print ("MAX IS HERE ", np.amax(np.array(X_train)))
# # print (trainer)
for i in range (0,1):
print (y_train)
# # Train model
model = train_model(np.array(X_train), np.array(y_train), np.array(X_validation),np.array(y_validation))
# print (model.summary())
# score = model.evaluate(X_validation, y_validation, verbose=1)
# print (score)
# # model = load_model("model.h5")
# # predicted = model.predict (k.create_segmented_mfccs(X_test))
# # for i in predicted:
# # print (i)
# # Make predictions on full X_test MFCCs
y_predicted = accuracy.predict_class_all(k.create_segmented_mfccs(X_test), model)
print('Training samples:', train_count)
print('Testing samples:', test_count)
print('Accuracy to beat:', acc_to_beat)
print('Confusion matrix of total samples:\n', np.sum(accuracy.confusion_matrix(y_predicted, y_test),axis=1))
print('Confusion matrix:\n',accuracy.confusion_matrix(y_predicted, y_test))
print('Accuracy:', accuracy.get_accuracy(y_predicted,y_test))
results.append(accuracy.confusion_matrix(y_predicted, y_test))
acc.append(accuracy.get_accuracy(y_predicted,y_test))
with open(csvfile, 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow([i,accuracy.get_accuracy(y_predicted,y_test)])
# # Save model
# print (results)
# print (acc)
save_model(model, model_filename)<file_sep>import pandas as pd
import os
import wave
import contextlib
def getlength(fname):
try:
with contextlib.closing(wave.open("./ES1/"+fname,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
return duration
except:
return 0
# gets the length of the audio file and saves it in the csv file
df = pd.read_csv("./ES1.csv",encoding='ISO-8859-1')
dur = []
for name in df.Filename.values:
dur.append(getlength (name+".wav"))
df['duration'] = dur
df.to_csv("data.csv", sep=',', encoding='ISO-8859-1')
<file_sep>audioread==2.1.8
Click==7.0
decorator==4.4.0
Flask==1.0.3
Flask-Cors==3.0.8
itsdangerous==1.1.0
Jinja2==2.10.1
joblib==0.13.2
librosa==0.6.3
llvmlite==0.29.0
MarkupSafe==1.1.1
numba==0.44.0
numpy==1.16.4
pandas==0.24.2
python-dateutil==2.8.0
pytz==2019.1
resampy==0.2.1
scikit-learn==0.21.2
scipy==1.3.0
six==1.12.0
sklearn==0.0
Werkzeug==0.15.4
Keras==2.2.4
Keras-Applications==1.0.8
Keras-Preprocessing==1.0.9
<file_sep>from pydub import AudioSegment
import pandas as pd
import os
import wave
import contextlib
def getlength(fname):
with contextlib.closing(wave.open("./Countries/Caribbean/"+fname,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
return duration
for filename in os.listdir("./Countries/Caribbean"):
path = os.path.join("./Countries/Caribbean/", filename)
if not os.path.isdir(path):
audio = AudioSegment.from_wav("./Countries/Caribbean/"+filename)
length = getlength(filename)
# pad all files within range to be 1 second long
if length > .1 and length <= .8:
pad_ms = 1000 # milliseconds of silence needed
new = pad_ms - (length*1000)
pad_ms = abs(new)
silence = AudioSegment.silent(duration=pad_ms)
padded = audio + silence # Adding silence after the audio
padded.export('./Countries/Caribbean/padded/'+filename, format='wav')
else:
# if length of file >.8 keep else discard the others because they contain nothing
if length > .8:
audio.export('./Countries/Caribbean/padded/'+filename, format='wav')
<file_sep>import pandas as pd
from collections import Counter
import sys
sys.path.append('../speech-accent-recognition/src>')
import getsplit
import sklearn
from keras import utils
import librosa
import numpy as np
from sklearn.preprocessing import MinMaxScaler
DEBUG = True
SILENCE_THRESHOLD = .01
RATE = 24000
N_MFCC = 13
COL_SIZE = 30
EPOCHS = 10 #35#250
def to_categorical(y):
'''
Converts list of languages into a binary class matrix
:param y (list): list of languages
:return (numpy array): binary class matrix
'''
lang_dict = {}
# for index,language in enumerate(set(y)):
# print (index,language)
lang_dict["Trinidad"] = 0
lang_dict["Tobago"] = 1
lang_dict["Barbados"] = 2
lang_dict["St. Lucia"] = 3
y = list(map(lambda x: lang_dict[x],y))
print (y)
return utils.to_categorical(y, len(lang_dict))
def get_wav(language_num):
'''
Load wav file from disk and down-samples to RATE
:param language_num (list): list of file names
:return (numpy array): Down-sampled wav file
'''
filename = './ES1/{}.wav'.format(language_num)
print('Attempting to load file: {0}'.format(filename))
y, sr = librosa.load(filename)
print("File {0} successfully loaded".format(filename))
return(librosa.core.resample(y=y,orig_sr=sr,target_sr=RATE, scale=True))
def to_mfcc(wav):
'''
Converts wav file to Mel Frequency Ceptral Coefficients
:param wav (numpy array): Wav form
:return (2d numpy array: MFCC)
'''
mfcc = librosa.feature.mfcc(y=wav, sr=RATE, n_mfcc=N_MFCC)
mfcc = sklearn.preprocessing.scale(mfcc, axis=1)
return mfcc
def to_mfcc_norm(wav):
'''
Converts wav file to Mel Frequency Ceptral Coefficients
:param wav (numpy array): Wav form
:return (2d numpy array: MFCC
'''
return(librosa.feature.mfcc(y=wav, sr=RATE, n_mfcc=N_MFCC))
def remove_silence(wav, thresh=0.04, chunk=5000):
'''
Searches wav form for segments of silence. If wav form values are lower than 'thresh' for 'chunk' samples, the values will be removed
:param wav (np array): Wav array to be filtered
:return (np array): Wav array with silence removed
'''
tf_list = []
for x in range(len(wav) / chunk):
if (np.any(wav[chunk * x:chunk * (x + 1)] >= thresh) or np.any(wav[chunk * x:chunk * (x + 1)] <= -thresh)):
tf_list.extend([True] * chunk)
else:
tf_list.extend([False] * chunk)
tf_list.extend((len(wav) - len(tf_list)) * [False])
return(wav[tf_list])
def normalize_mfcc(mfcc):
'''
Normalize mfcc
:param mfcc:
:return:
'''
mms = MinMaxScaler()
return(mms.fit_transform(np.abs(mfcc)))
def make_segments(mfccs,labels):
'''
Makes segments of mfccs and attaches them to the labels
:param mfccs: list of mfccs
:param labels: list of labels
:return (tuple): Segments with labels
'''
segments = []
seg_labels = []
for mfcc,label in zip(mfccs,labels):
# print (mfcc.shape[1],label)
for start in range(0, int(mfcc.shape[1] / COL_SIZE)):
segments.append(mfcc[:, start * COL_SIZE:(start + 1) * COL_SIZE])
seg_labels.append(label)
return(segments, seg_labels)
def segment_one(mfcc):
'''
Creates segments from on mfcc image. If last segments is not long enough to be length of columns divided by COL_SIZE
:param mfcc (numpy array): MFCC array
:return (numpy array): Segmented MFCC array
'''
segments = []
for start in range(0, int(mfcc.shape[1] / COL_SIZE)):
segments.append(mfcc[:, start * COL_SIZE:(start + 1) * COL_SIZE])
return(np.array(segments))
def create_segmented_mfccs(X_train):
'''
Creates segmented MFCCs from X_train
:param X_train: list of MFCCs
:return: segmented mfccs
'''
segmented_mfccs = []
for mfcc in X_train:
segmented_mfccs.append(segment_one(mfcc))
return(segmented_mfccs)
<file_sep>from pydub import AudioSegment
from pydub.silence import split_on_silence
import os
country = ["Trinidad","Tobago","Barbados","St.Lucia"]
code = ["T","TB","B","S"]
index =0
for c in country:
i=0
for filename in os.listdir("./Countries/"+c+"/slow/"):
sound_file = AudioSegment.from_wav("./Countries/"+c+"/slow/"+filename)
audio_chunks = split_on_silence(sound_file,
# must be silent
# for at least 1/10 of a second
min_silence_len=100,
# consider it silent if quieter than -40 dBFS
silence_thresh=-40 )
for k,chunk in enumerate(audio_chunks):
out_file = "./Countries/"+c+"/segment/"+code[index]+"{0}.wav".format(i)
chunk.export(out_file, format="wav")
i=i+1
index = index +1
<file_sep>from pydub import AudioSegment
import os
def speed_change(sound, speed=1.0):
# Manually override the frame_rate. This tells the computer how many
# samples to play per second
sound_with_altered_frame_rate = sound._spawn(sound.raw_data, overrides={
"frame_rate": int(sound.frame_rate * speed)
})
# convert the sound with altered frame rate to a standard frame rate
# so that regular playback programs will work right.
return sound_with_altered_frame_rate.set_frame_rate(sound.frame_rate)
# slow down the list of countries audio file
country = ["St. Lucia"]
for c in country:
for filename in os.listdir("./Countries/"+c+"/segment/"):
sound = AudioSegment.from_file("./Countries/"+c+"/segment/"+filename)
fast_sound = speed_change(sound, 2.5)
fast_sound.export("./Countries/Caribbean/"+filename, format="wav")
<file_sep>from pydub import AudioSegment
import os
def speed_change(sound, speed=1.0):
# Manually override the frame_rate. This tells the computer how many
# samples to play per second
sound_with_altered_frame_rate = sound._spawn(sound.raw_data, overrides={
"frame_rate": int(sound.frame_rate * speed)
})
# convert the sound with altered frame rate to a standard frame rate
# so that regular playback programs will work right.
return sound_with_altered_frame_rate.set_frame_rate(sound.frame_rate)
# slow down the list of countries audio file
country = ["Trinidad", "Tobago", "Barbados", "St. Lucia"]
for c in country:
for filename in os.listdir("./Countries/"+c+"/normalized/"):
path = os.path.join("./Countries/"+c+"/normalized/", filename)
if not os.path.isdir(path):
sound = AudioSegment.from_file("./Countries/"+c+"/"+filename)
# reduce rate by a factor of 0.4
slow_sound = speed_change(sound, 0.4)
slow_sound.export("./Countries/"+c+"/slow/"+filename, format="wav")
|
201356a4b31c02a25d732d32428e35da869ab643
|
[
"Markdown",
"Python",
"Text"
] | 9
|
Markdown
|
Kerschel/Accent-CAC
|
67195c6025715cd03787c49501b035d23b7f7e49
|
abb361699cd4d73d6578b225e559fb2ba40d0af4
|
refs/heads/master
|
<file_sep># Hangman
A web version of the classic Hangman guessing game. A secret word is generated upon initialization. You have ten guesses to complete the word or you're hanged.
# Installation
To play online go here [Heroku](https://glacial-retreat-36955.herokuapp.com/?guess=p)
To run the game locally, first clone the repository in your command line, then enter the following:
```
$ cd hangman
$ ruby hangman.rb
```
Go to localhost:4567 in your browser.
# Running
The game is written in Ruby and uses file I/O to load a secret word from a dictionary file. It will only accept letters in the guess input, and won't allow the user to re-enter letters he/she has already guessed. If a letter is entered that is in the word, that letter will take it's appropriate place in the secret word as well as be added to the correct guesses list. The user will not lose a turn. Incorrect guesses will be added to the incorrect guesses list and the turns will decrement by one.
If the word is completely filled out or the turns get down to 0, a game over message will appear prompting the user to start a new game.
### Acknowledgments
[The Odin Project](https://www.theodinproject.com/courses/ruby-on-rails/lessons/sinatra-project)<file_sep>require 'sinatra'
require 'sinatra/reloader' if development?
class Game
attr_accessor :guesses, :correct_guesses, :incorrect_guesses, :secret_word
def initialize
@guesses = 10
@guess = ''
@correct_guesses = []
@incorrect_guesses = []
generate_word
end
# load dictionary and generate random word between 5 and 12 characters
def generate_word
good_words = []
File.readlines('dictionary.txt').each do |word|
if word.length >= 5 && word.length <= 12
good_words << word
end
end
@secret_word = good_words.sample.strip.downcase
@letters = @secret_word.split('') # separate letters
@blanks = Array.new(@secret_word.length, '_') # create blanks to fill in
end
# show the updated blanks after each turn
def display
@blanks.each { |letter| print "#{letter} " }
end
# prompt user for guesses and check for matches
def check_guess(guess)
if @correct_guesses.include?(guess) || @incorrect_guesses.include?(guess)
@message = "You tried that already!"
elsif !('a'..'z').cover?(guess)
@message = "Guess a letter!"
elsif @letters.include?guess
@letters.each_with_index do |letter, index|
@blanks[index] = letter if letter == guess
end
@correct_guesses << guess
@message = "You got one!"
else
@incorrect_guesses << guess
@guesses = @guesses -= 1
end
check_end
end
# if guesses run out or blanks get filled in, game_over is set to true, ending the game
def check_end
if @guesses == 0
@message = "Game over, you lose! The secret word was #{@secret_word}! Another word was generated.. Press guess to see it."
elsif @blanks.none? { |letter| letter == '_' }
@message = "You win! The secret word is #{@secret_word.upcase}! Another word was generated.. Press guess to see it."
else
@message = "Letters from a-z"
end
end
end
hangman = Game.new
get '/' do
guess = params['guess'].to_s
@message = hangman.check_guess(guess)
@guesses = hangman.guesses
@correct_guesses = hangman.correct_guesses
@incorrect_guesses = hangman.incorrect_guesses
@display = hangman.display
if @guesses == 0 || !@display.include?('_')
hangman = Game.new
end
erb :index, :locals => { :message => @message, :announce => @announce, :display => @display, :guesses => @guesses, :correct_guesses => @correct_guesses, :incorrect_guesses => @incorrect_guesses }
end
|
2deeb753ef1d1a1f7acb5162c1732f2d90e0785d
|
[
"Markdown",
"Ruby"
] | 2
|
Markdown
|
ks927/sinatra_hangman
|
ac3fa1ba351631aa6fcbef4c1e065ee6d33cf9f1
|
865d82d52af2b570ec66cc49f611081451014bac
|
refs/heads/master
|
<file_sep>"use strict";
var _ = require("lodash");
var errorHandler_1 = require("../../api/responses/errorHandler");
var successHandler_1 = require("../../api/responses/successHandler");
var dbErrorHandler_1 = require("../../config/dbErrorHandler");
var service_1 = require("./service");
var UserController = (function () {
function UserController() {
this.UserService = new service_1.User();
}
UserController.prototype.getAll = function (req, res) {
this.UserService.getAll()
.then(_.partial(successHandler_1.onSuccess, res))
.catch(_.partial(errorHandler_1.onError, res, 'Find all users failed'));
};
UserController.prototype.createUser = function (req, res) {
this.UserService.create(req.body)
.then(_.partial(successHandler_1.onSuccess, res))
.catch(_.partial(dbErrorHandler_1.dbErrorHandler, res))
.catch(_.partial(errorHandler_1.onError, res, "Could not create user"));
};
UserController.prototype.getById = function (req, res) {
var userId = parseInt(req.params.id);
this.UserService.getById(userId)
.then(_.partial(successHandler_1.onSuccess, res))
.catch(_.partial(errorHandler_1.onError, res, 'Not found'));
};
UserController.prototype.updateUser = function (req, res) {
var userId = parseInt(req.params.id);
var props = req.body;
this.UserService.update(userId, props)
.then(_.partial(successHandler_1.onSuccess, res))
.catch(_.partial(errorHandler_1.onError, res, 'Update User failed'));
};
UserController.prototype.deleteUser = function (req, res) {
var userId = req.params.id;
this.UserService.delete(userId)
.then(_.partial(successHandler_1.onSuccess, res))
.catch(_.partial(errorHandler_1.onError, res, 'An error ocurred to delete an User'));
};
return UserController;
}());
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = UserController;
<file_sep>import {Response} from 'express';
import * as HTTPStatus from 'http-status';
export function onSuccess(res:Response, data:any) {
res.status(HTTPStatus.OK).json({payload:data});
}
<file_sep>"use strict";
var passport = require("passport");
var service_1 = require("./modules/User/service");
var passport_jwt_1 = require("passport-jwt");
var config = require('./config/env/config')();
function AuthConfig() {
var UserService = new service_1.User();
var opts = {
secretOrKey: config.secret,
jwtFromRequest: passport_jwt_1.ExtractJwt.fromAuthHeader()
};
passport.use(new passport_jwt_1.Strategy(opts, function (jwtPayload, done) {
UserService.getById(jwtPayload.id)
.then(function (user) {
if (user) {
return done(null, {
id: user.id,
email: user.email
});
}
return done(null, false);
})
.catch(function (error) { return done(error, null); });
}));
return {
initialize: function () { return passport.initialize(); },
authenticate: function () { return passport.authenticate('jwt', { session: false }); },
};
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = AuthConfig;
<file_sep>"use strict";
var HTTPStatus = require("http-status");
function errorHandlerApi(err, req, res, next) {
console.error('API error handler was called: ', err);
res.status(HTTPStatus.INTERNAL_SERVER_ERROR).json({
errorCode: 'ERR-001',
message: 'Internal Server Error'
});
}
exports.errorHandlerApi = errorHandlerApi;
<file_sep>'use strict';
var Chai = require('chai');
var supertest = require('supertest');
var td = require('testdouble');
var api_1 = require('../../../api/api');
var app = api_1["default"];
exports.app = app;
var request = supertest;
exports.request = request;
var expect = Chai.expect;
exports.expect = expect;
var testDouble = td;
exports.testDouble = testDouble;
<file_sep>/* jshint esversion:6*/
module.exports = () => require(`../env/${process.env.NODE_ENV}.env.js`)
<file_sep>import {Request, Response} from 'express';
import * as _ from 'lodash';
import {onError} from '../../api/responses/errorHandler';
import {onSuccess} from '../../api/responses/successHandler';
import {dbErrorHandler} from '../../config/dbErrorHandler';
import {User} from './service';
export default class UserController {
public UserService;
constructor() {
this.UserService = new User();
}
getAll(req: Request, res: Response) {
this.UserService.getAll()
.then(_.partial(onSuccess, res))
.catch(_.partial(onError, res, 'Find all users failed'));
}
createUser(req: Request, res: Response) {
this.UserService.create(req.body)
.then(_.partial(onSuccess, res))
.catch(_.partial(dbErrorHandler, res))
.catch(_.partial(onError, res, `Could not create user`));
}
getById(req: Request, res: Response) {
const userId = parseInt(req.params.id);
this.UserService.getById(userId)
.then(_.partial(onSuccess, res))
.catch(_.partial(onError, res, 'Not found'));
}
updateUser(req: Request, res: Response){
const userId = parseInt(req.params.id);
const props = req.body;
this.UserService.update(userId, props)
.then(_.partial(onSuccess, res))
.catch(_.partial(onError, res, 'Update User failed'));
}
deleteUser(req: Request, res: Response){
const userId = req.params.id;
this.UserService.delete(userId)
.then(_.partial(onSuccess, res))
.catch(_.partial(onError, res, 'An error ocurred to delete an User'));
}
}
<file_sep>"use strict";
var express = require('express');
var logger = require('morgan');
var auth_1 = require('../auth');
var routes_1 = require('./routes/routes');
var bodyParser = require('body-parser');
var Api = (function () {
function Api() {
this.express = express();
this.auth = auth_1["default"]();
this.middleware();
this.router(this.express, this.auth);
}
Api.prototype.middleware = function () {
this.express.use(logger('dev'));
this.express.use(bodyParser.urlencoded({ extended: true }));
this.express.use(bodyParser.json());
this.express.use(this.auth.initialize());
};
Api.prototype.router = function (app, auth) {
new routes_1["default"](app, auth);
};
return Api;
}());
exports.__esModule = true;
exports["default"] = new Api().express;
<file_sep>"use strict";
var _ = require("lodash");
var service_1 = require("../User/service");
var authSuccess_1 = require("../../api/responses/authSuccess");
var UserService = new service_1.User();
var TokenRoutes = (function () {
function TokenRoutes() {
}
TokenRoutes.prototype.auth = function (req, res) {
var credentials = {
email: req.body.email,
password: <PASSWORD>
};
if (credentials.hasOwnProperty('email') && credentials.hasOwnProperty('password')) {
UserService
.getByEmail(credentials.email)
.then(_.partial(authSuccess_1.authSuccess, res, credentials))
.catch(_.partial(authSuccess_1.authFail, req, res));
}
};
return TokenRoutes;
}());
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = TokenRoutes;
<file_sep>import { testDouble, expect } from '../../config/tests/config/helpers';
import * as HTTPStatus from 'http-status';
import { User } from './service';
describe('Testes unitários no Service User', () => {
describe('Create Method', () => {
it('Should create an User', () => {
const requestUser = {
id: 100,
name: '<NAME>',
email: '<EMAIL>',
password: '123'
};
const userService = new User();
return userService
.create(requestUser)
.then( res => {
expect(res.dataValues).to.have.all.keys(
['id', 'name', 'email', 'password', 'createdAt', 'updatedAt']
);
});
});
});
});
<file_sep>import { Application } from 'express';
import UserRoutes from '../../modules/User/routes';
import TokenRoutes from '../../modules/auth/auth';
class Routes {
private router: UserRoutes;
private tokenRoute;
private auth;
constructor(app: Application, auth: any){
this.router = new UserRoutes();
this.tokenRoute = new TokenRoutes();
this.auth = auth;
this.getRoutes(app);
}
getRoutes(app: Application): void {
app.route('/api/users/all').all(this.auth.authenticate()).get(this.router.index);
app.route('/api/users/create').all(this.auth.authenticate()).post(this.router.create);
app.route('/api/users/:id').all(this.auth.authenticate()).get(this.router.findOne);
app.route('/api/users/:id/update').all(this.auth.authenticate()).put(this.router.update);
app.route('/api/users/:id/destroy').all(this.auth.authenticate()).delete(this.router.destroy);
app.route('/token').post(this.tokenRoute.auth);
}
}
export default Routes;<file_sep>import * as passport from 'passport';
import {User} from './modules/User/service';
import { Strategy, ExtractJwt } from 'passport-jwt';
const config = require('./config/env/config')();
export default function AuthConfig () {
const UserService = new User();
let opts = {
secretOrKey: config.secret,
jwtFromRequest: ExtractJwt.fromAuthHeader()
};
passport.use(new Strategy(opts, (jwtPayload, done) => {
UserService.getById(jwtPayload.id)
.then(user => {
if(user) {
return done(null, {
id: user.id,
email: user.email
});
}
return done(null, false);
})
.catch(error => done(error, null));
}));
return {
initialize: () => passport.initialize(),
authenticate: () => passport.authenticate('jwt', {session: false}),
};
}
<file_sep>import UserController from './controller';
import {Request, Response} from 'express';
let UserCtlr;
export default class UserRoutes {
constructor(){
UserCtlr = new UserController();
}
index(req:Request, res:Response) {
return UserCtlr.getAll(req, res);
}
create(req:Request, res:Response) {
return UserCtlr.createUser(req, res);
}
findOne(req:Request, res:Response) {
return UserCtlr.getById(req, res);
}
update(req:Request, res:Response) {
return UserCtlr.updateUser(req, res);
}
destroy(req:Request, res:Response){
return UserCtlr.deleteUser(req, res);
}
}
<file_sep>'use strict';
import * as mocha from 'mocha';
import * as Chai from 'chai';
const supertest = require('supertest');
import * as td from 'testdouble';
import App from '../../../api/api';
const app = App;
const request = supertest;
const expect = Chai.expect;
const testDouble = td;
export { app, expect, request, testDouble };
<file_sep>"use strict";
var HTTPStatus = require('http-status');
function onError(res, message, err) {
console.log('Error: ', err);
res.status(HTTPStatus.INTERNAL_SERVER_ERROR).send();
}
exports.onError = onError;
<file_sep>import {Request, Response} from 'express';
import * as _ from 'lodash';
import {User} from '../User/service';
import {authSuccess, authFail} from '../../api/responses/authSuccess';
const UserService = new User();
class TokenRoutes {
auth(req: Request, res: Response) {
const credentials = {
email: req.body.email,
password: <PASSWORD>
}
if (credentials.hasOwnProperty('email') && credentials.hasOwnProperty('password')) {
UserService
.getByEmail(credentials.email)
.then(_.partial(authSuccess, res, credentials))
.catch(_.partial(authFail, req, res));
}
}
}
export default TokenRoutes;
<file_sep>import * as express from 'express';
import * as path from 'path';
import * as logger from 'morgan';
import AuthConfig from '../auth';
import Routes from './routes/routes';
const bodyParser = require('body-parser');
class Api {
public express: express.Application;
public auth;
constructor(){
this.express = express();
this.auth = AuthConfig();
this.middleware();
this.router(this.express, this.auth);
}
middleware(): void {
this.express.use(logger('dev'));
this.express.use(bodyParser.urlencoded({extended: true}));
this.express.use(bodyParser.json());
this.express.use(this.auth.initialize());
}
private router(app: express.Application, auth: any): void {
new Routes(app, auth);
}
}
export default new Api().express;
<file_sep>"use strict";
var HTTPStatus = require("http-status");
function onSuccess(res, data) {
res.status(HTTPStatus.OK).json({ payload: data });
}
exports.onSuccess = onSuccess;
<file_sep>/* jshint esversion:6*/
module.exports = {
env: "development",
db: "db_name",
dialect: "dialect",
username: "username",
password: "<PASSWORD>",
host: "host",
server_port: 1234,
pg_port: 4321,
db_url: "db://username:password@host:pg_port/db_name",
secret: "secret",
};
<file_sep>import * as http from 'http';
import * as debug from 'debug';
import Api from './api/api';
import {errorHandlerApi} from './api/errorHandlerApi';
var models = require('./models');
const config = require('./config/env/config')();
debug('ts-api:server');
const port = normalizePort(config.server_port);
Api.set('port', port);
const server = http.createServer(Api);
models.sequelize.sync().then(() => {
server.listen(port);
server.on('error', onError);
server.on('listening', listen);
});
Api.use(errorHandlerApi);
function listen():void {
let address = server.address();
let bind = (typeof address === 'string') ? `Address ${address}` : `Port ${address.port}`;
debug(`Server is runnig on port ${bind}`);
console.log(`Server is runnig on port ${bind}`);
}
function onError(error: NodeJS.ErrnoException): void {
console.log('An error ocurred: ', error);
}
function normalizePort(portNumber: number | string): string|number|boolean {
let port: number = (typeof portNumber === 'string') ? parseInt(portNumber, 10) : portNumber;
if(isNaN(port)) return portNumber;
else if(port > 0) return port;
else return false;
}
<file_sep>"use strict";
var helpers_1 = require('../../config/tests/config/helpers');
var jwt = require('jwt-simple');
var HTTPStatus = require('http-status');
describe('## User Tests', function () {
'use strict';
var config = require('../../config/env/config')();
var model = require('../../models');
var id;
var token;
var userDefault = {
id: 1,
name: 'Test User',
email: '<EMAIL>',
password: '<PASSWORD>'
};
beforeEach(function (done) {
model
.User
.destroy({
where: {}
})
.then(function () { return model.User.create({
id: 50,
name: 'Raphael',
email: '<EMAIL>',
password: '<PASSWORD>'
}); })
.then(function (user) {
model
.User
.create(userDefault)
.then(function () {
token = jwt.encode({ id: user.id }, config.secret);
done();
});
});
});
describe('GET /api/users/all', function () {
it('Should return a array of Users', function (done) {
helpers_1.request(helpers_1.app)
.get('/api/users/all')
.set('Content-Type', 'application/json')
.set('Authorization', "JWT " + token)
.end(function (error, res) {
helpers_1.expect(res.status).to.equal(HTTPStatus.OK);
helpers_1.expect(res.body.payload).to.be.an('array');
helpers_1.expect(res.body.payload[0].name).to.be.equal('Raphael');
helpers_1.expect(res.body.payload[0].email).to.be.equal('<EMAIL>');
done(error);
});
});
});
describe('POST /token', function () {
it('Should receive a JWT', function (done) {
var credentials = {
email: '<EMAIL>',
password: '<PASSWORD>'
};
helpers_1.request(helpers_1.app)
.post('/token')
.send(credentials)
.end(function (error, res) {
helpers_1.expect(res.status).to.equal(HTTPStatus.OK);
helpers_1.expect(res.body.token).to.equal("" + token);
done(error);
});
});
it('Should not receive a JWT', function (done) {
var credentials = {
email: '<EMAIL>',
password: '<PASSWORD>'
};
helpers_1.request(helpers_1.app)
.post('/token')
.send(credentials)
.end(function (error, res) {
helpers_1.expect(res.status).to.equal(HTTPStatus.UNAUTHORIZED);
helpers_1.expect(res.body).to.empty;
done(error);
});
});
});
describe('POST /api/users/create', function () {
it('Should create a new user', function (done) {
var user = {
id: 2,
name: '<NAME>',
email: '<EMAIL>',
password: '<PASSWORD>'
};
helpers_1.request(helpers_1.app)
.post('/api/users/create')
.set('Authorization', "JWT " + token)
.send(user)
.end(function (error, res) {
helpers_1.expect(res.body.payload.id).to.eql(user.id);
helpers_1.expect(res.body.payload.name).to.eql(user.name);
helpers_1.expect(res.body.payload.email).to.eql(user.email);
done(error);
});
});
});
describe('GET /api/users/:id', function () {
it('Should return an User by its ID', function (done) {
helpers_1.request(helpers_1.app)
.get("/api/users/" + userDefault.id)
.set('Authorization', "JWT " + token)
.end(function (error, res) {
helpers_1.expect(res.status).to.equal(HTTPStatus.OK);
helpers_1.expect(res.body.payload.id).to.equal(userDefault.id);
helpers_1.expect(res.body.payload).to.have.all.keys([
'id',
'name',
'email',
'password'
]);
id = res.body.payload.id;
done(error);
});
});
});
describe('PUT /api/users/:id/update', function () {
it('Should update an User', function (done) {
var updatedUser = {
name: 'UpdatedName',
email: '<EMAIL>'
};
helpers_1.request(helpers_1.app)
.put("/api/users/" + userDefault.id + "/update")
.set('Authorization', "JWT " + token)
.send(updatedUser)
.end(function (error, res) {
helpers_1.expect(res.status).to.equal(HTTPStatus.OK);
helpers_1.expect(res.body.payload[0]).to.eql(1);
helpers_1.expect(res.body.payload[1][0].id).to.eql(userDefault.id);
helpers_1.expect(res.body.payload[1][0].name).to.eql(updatedUser.name);
helpers_1.expect(res.body.payload[1][0].email).to.eql(updatedUser.email);
done(error);
});
});
});
describe('DELETE /api/users/:id/destroy', function () {
it('Should delete an User', function (done) {
helpers_1.request(helpers_1.app)
.del("/api/users/" + userDefault.id + "/destroy")
.set('Authorization', "JWT " + token)
.end(function (error, res) {
helpers_1.expect(res.status).to.equal(HTTPStatus.OK);
helpers_1.expect(res.body.payload).to.eql(1);
done(error);
});
});
});
});
<file_sep>import {Response} from 'express';
import * as HTTPStatus from 'http-status';
const hri = require('human-readable-ids').hri;
export function dbErrorHandler(res:Response, err:any) {
const id = hri.random();
console.error("Database error ocurred: ", id, err);
res.status(HTTPStatus.INTERNAL_SERVER_ERROR).json({
code: 'ERR-002',
message: `Creation of user failed, error code ${id}`
});
}
<file_sep>import {Response} from 'express';
import * as HTTPStatus from 'http-status';
export function onError(res: Response, message:string, err:any) {
console.log('Error: ', err);
res.status(HTTPStatus.INTERNAL_SERVER_ERROR).send();
}
<file_sep>module.exports = {
env: "test",
db: "api_test",
dialect: "postgres",
username: "postgres",
password: "<PASSWORD>",
host: "localhost",
server_port: 3000,
pg_port: 5432,
db_url: "postgres://postgres:pgroot@localhost:5432/api_test",
secret: "secret",
};
<file_sep>FROM node:boron
MAINTAINER <NAME> <<EMAIL>>
RUN apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys B97B0AFCAA1<KEY>8
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" > /etc/apt/sources.list.d/pgdg.list
RUN apt-get update && apt-get install -y python-software-properties software-properties-common postgresql-9.3 postgresql-client-9.3 postgresql-contrib-9.3
USER postgres
RUN /etc/init.d/postgresql start
RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/9.3/main/pg_hba.conf
RUN echo "listen_addresses='*'" >> /etc/postgresql/9.3/main/postgresql.conf
EXPOSE 5432
VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
CMD ["/usr/lib/postgresql/9.3/bin/postgres", "-D", "/var/lib/postgresql/9.3/main", "-c", "config_file=/etc/postgresql/9.3/main/postgresql.conf"]
USER root
RUN mkdir -p /usr/src/ts-api
WORKDIR /usr/src/ts-api
COPY package.json /usr/src/ts-api
RUN npm install
COPY . /usr/src/ts-api
EXPOSE 4000
CMD npm run watch
<file_sep>/* jshint esversion:6*/
module.exports = {
env: "test",
db: "db_test",
dialect: "dialect",
username: "username",
password: "<PASSWORD>",
host: "host",
server_port: 1234,
pg_port: 4321,
db_url: "db://username:password@host:pg_port/db_test",
secret: "secret",
};
<file_sep>"use strict";
var interface_1 = require("./interface");
var models = require('../../models');
var User = (function () {
function User() {
}
User.prototype.create = function (user) {
return models.User.create(user);
};
User.prototype.getAll = function () {
return models.User.findAll({
order: ['name']
})
.then(interface_1.createUsers);
};
User.prototype.getById = function (id) {
return models.User.findOne({
where: { id: id }
})
.then(interface_1.createUserById);
};
User.prototype.getByEmail = function (email) {
return models.User.findOne({
where: { email: email }
})
.then(interface_1.createUserByEmail);
};
User.prototype.update = function (id, user) {
return models.User.update(user, {
where: { id: id },
fields: ['name', 'email', 'password'],
hooks: true,
individualHooks: true
});
};
User.prototype.delete = function (id) {
return models.User.destroy({
where: { id: id }
});
};
return User;
}());
exports.User = User;
<file_sep>import {Request, Response} from 'express';
import * as jwt from 'jwt-simple';
import * as HTTPStatus from 'http-status';
const config = require('../../config/env/config')();
const bcrypt = require('bcrypt');
export function authSuccess(res: Response, creadentials:any, data: any){
const isMatch = bcrypt.compareSync(creadentials.password, data.password);
if(isMatch){
const payload = {id: data.id};
res.json({
token: jwt.encode(payload, config.secret)
});
} else {
res.sendStatus(HTTPStatus.UNAUTHORIZED);
}
}
export function authFail(req: Request, res: Response){
res.sendStatus(HTTPStatus.UNAUTHORIZED);
}
<file_sep>"use strict";
var express = require("express");
var logger = require("morgan");
var auth_1 = require("../auth");
var routes_1 = require("./routes/routes");
var bodyParser = require('body-parser');
var Api = (function () {
function Api() {
this.express = express();
this.auth = auth_1.default();
this.middleware();
this.router(this.express, this.auth);
}
Api.prototype.middleware = function () {
this.express.use(logger('dev'));
this.express.use(bodyParser.urlencoded({ extended: true }));
this.express.use(bodyParser.json());
this.express.use(this.auth.initialize());
};
Api.prototype.router = function (app, auth) {
new routes_1.default(app, auth);
};
return Api;
}());
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = new Api().express;
<file_sep># TypeScript API Starter - Node + TypeScript + Sequelize + PostgreSQL
[](https://travis-ci.org/raphaellima8/typescript-api)
[](https://landscape.io/github/raphaellima8/typescript-api/master)
## Dependencies
* node
* npm
* typescript
* gulp
* PostgreSQL
* Sequelize
* Docker
## Getting Started
Clone this repo:
```
git clone https://github.com/raphaellima8/typescript-api.git ts-api && cd ts-api
```
Install dependencies:
```
npm i
```
Set the values to environment's properties in the below files:
```
/server/config/env/development.env.js
/server/config/env/test.env.js
```
Start server:
```
npm run watch
```
Integration Tests:
```
npm run integration-test
```
Unit Tests:
```
npm run unit-test
```
Coverage:
```
npm run test:coverage
```
## If Docker
Run:
```
[sudo] docker build -t <image_name> .
```
```
[sudo] docker run -d -p 9000:3000 --name <label> <image_name>
```
Connect to the container:
```
[sudo] docker exec -it <id_container> /bin/bash
```
Run the commands below in the container's terminal:
```
su postgres
/etc/init.d/postgresql start
psql -c "ALTER USER postgres WITH PASSWORD '<PASSWORD>'"
psql -c "CREATE DATABASE api OWNER postgres"
npm run watch
```
License: MIT
<file_sep>"use strict";
var HTTPStatus = require("http-status");
var hri = require('human-readable-ids').hri;
function dbErrorHandler(res, err) {
var id = hri.random();
console.error("Database error ocurred: ", id, err);
res.status(HTTPStatus.INTERNAL_SERVER_ERROR).json({
code: 'ERR-002',
message: "Creation of user failed, error code " + id
});
}
exports.dbErrorHandler = dbErrorHandler;
<file_sep>import * as bcrypt from 'bcrypt';
export default function(sequelize, DataTypes) {
var User = sequelize.define('User', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
email: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true,
}
},
password: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true,
}
}
}, {
classMethods: {
validatePassword: (encryptedPassword, password) => bcrypt.compareSync(password, encryptedPassword)
}
});
User.beforeCreate( user => hashPass(user) );
User.beforeUpdate( user => hashPass(user) );
function hashPass(user) {
const salt = bcrypt.genSaltSync(10);
user.set('password', <PASSWORD>.hashSync(user.password, salt));
console.log(`Password ${user.password}`)
}
return User;
};
<file_sep>export interface IUser {
readonly id: number,
name: string,
email: string,
password: string
}
export interface IUserDetail extends IUser{
id: number,
name: string,
email: string,
password: string
}
export function createUser({id, name, email, password}:any): IUser{
return {
id, name, email, password
}
}
export function createUsers(data: any[]): IUser []{
return data.map(createUser);
}
export function createUserById({id, name, email, password}:any): IUserDetail{
return {
id, name, email, password
}
}
export function createUserByEmail({id, name, email, password}:any): IUserDetail {
return {
id, name, email, password
}
}<file_sep>import {Request, Response, RequestHandler, ErrorRequestHandler, NextFunction} from 'express';
import * as HTTPStatus from 'http-status';
export function errorHandlerApi(
err: any,
req: Request,
res: Response,
next: NextFunction
) {
console.error('API error handler was called: ', err);
res.status(HTTPStatus.INTERNAL_SERVER_ERROR).json({
errorCode: 'ERR-001',
message: 'Internal Server Error'
});
}
<file_sep>import { app, request, expect } from '../../config/tests/config/helpers';
import * as jwt from 'jwt-simple';
import * as _ from 'lodash';
import * as HTTPStatus from 'http-status';
var model = require('../../models');
model.sequelize.sync().then(() => {});
describe('## User Tests', () => {
'use strict';
const config = require('../../config/env/config')();
let id;
let token;
const userDefault = {
id: 1,
name: 'Test User',
email: '<EMAIL>',
password: '<PASSWORD>'
};
before((done) => {
model
.User
.destroy({
where: {}
})
.then(() => model.User.create({
id: 50,
name: 'Raphael',
email: '<EMAIL>',
password: '<PASSWORD>'
}))
.then(user => {
model
.User
.create(userDefault)
.then(() => {
token = jwt.encode({id: user.id}, config.secret);
done();
});
});
});
describe('GET /api/users/all', () => {
it('Should return a array of Users', done => {
request(app)
.get('/api/users/all')
.set('Content-Type', 'application/json')
.set('Authorization', `JWT ${token}`)
.end((error, res) => {
expect(res.status).to.equal(HTTPStatus.OK);
expect(res.body.payload).to.be.an('array');
expect(res.body.payload[0].name).to.be.equal('Raphael')
expect(res.body.payload[0].email).to.be.equal('<EMAIL>')
done(error);
});
});
});
describe('POST /token', () => {
it('Should receive a JWT', done => {
const credentials = {
email: '<EMAIL>',
password: '<PASSWORD>'
};
request(app)
.post('/token')
.send(credentials)
.end((error, res) => {
expect(res.status).to.equal(HTTPStatus.OK);
expect(res.body.token).to.equal(`${token}`);
done(error);
});
});
it('Should not receive a JWT', done => {
const credentials = {
email: '<EMAIL>',
password: '<PASSWORD>'
};
request(app)
.post('/token')
.send(credentials)
.end((error, res) => {
expect(res.status).to.equal(HTTPStatus.UNAUTHORIZED);
expect(res.body).to.empty;
done(error);
});
});
});
describe('POST /api/users/create', () => {
it('Should create a new user', done => {
const user = {
id: 2,
name: '<NAME>',
email: '<EMAIL>',
password: '<PASSWORD>',
};
request(app)
.post('/api/users/create')
.set('Authorization', `JWT ${token}`)
.send(user)
.end((error, res) => {
expect(res.body.payload.id).to.eql(user.id);
expect(res.body.payload.name).to.eql(user.name);
expect(res.body.payload.email).to.eql(user.email);
done(error);
});
});
});
describe('GET /api/users/:id', () => {
it('Should return an User by its ID', done => {
request(app)
.get(`/api/users/${userDefault.id}`)
.set('Authorization', `JWT ${token}`)
.end((error, res) => {
expect(res.status).to.equal(HTTPStatus.OK);
expect(res.body.payload.id).to.equal(userDefault.id);
expect(res.body.payload).to.have.all.keys([
'id',
'name',
'email',
'password'
]);
id = res.body.payload.id;
done(error);
});
});
});
describe('PUT /api/users/:id/update', () => {
it('Should update an User', done => {
const updatedUser = {
name: 'UpdatedName',
email: '<EMAIL>'
};
request(app)
.put(`/api/users/${userDefault.id}/update`)
.set('Authorization', `JWT ${token}`)
.send(updatedUser)
.end((error, res) => {
expect(res.status).to.equal(HTTPStatus.OK);
expect(res.body.payload[0]).to.eql(1);
expect(res.body.payload[1][0].id).to.eql(userDefault.id);
expect(res.body.payload[1][0].name).to.eql(updatedUser.name);
expect(res.body.payload[1][0].email).to.eql(updatedUser.email);
done(error);
});
});
});
describe('DELETE /api/users/:id/destroy', () => {
it('Should delete an User', done => {
request(app)
.del(`/api/users/${userDefault.id}/destroy`)
.set('Authorization', `JWT ${token}`)
.end((error, res) => {
expect(res.status).to.equal(HTTPStatus.OK);
expect(res.body.payload).to.eql(1);
done(error);
});
});
});
});
<file_sep>module.exports = {
env: "development",
db: "api",
dialect: "postgres",
username: "postgres",
password: "<PASSWORD>",
host: "localhost",
server_port: 3000,
pg_port: 5432,
db_url: "postgres://postgres:pgroot@localhost:5432/api",
secret: "secret"
};
<file_sep>"use strict";
var helpers_1 = require("../../config/tests/config/helpers");
var service_1 = require("./service");
describe('Testes unitários no Service User', function () {
describe('Create Method', function () {
it('Should create an User', function () {
var requestUser = {
id: 100,
name: '<NAME>',
email: '<EMAIL>',
password: '123'
};
var userService = new service_1.User();
return userService
.create(requestUser)
.then(function (res) {
helpers_1.expect(res.dataValues).to.have.all.keys(['id', 'name', 'email', 'password', 'createdAt', 'updatedAt']);
});
});
});
});
<file_sep> var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var config = require('../config/env/config')();
var env = config.env || 'development';
var db = {};
var sequelize;
if (config.db_url) {
sequelize = new Sequelize(config.db_url);
} else {
sequelize = new Sequelize(config.db, config.username, config.password);
}
fs
.readdirSync(__dirname)
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function (file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
<file_sep>import {IUser, createUser, createUsers, createUserById, createUserByEmail, IUserDetail} from './interface';
var models = require('../../models');
import * as Bluebird from 'bluebird';
export class User implements IUser{
public id: number;
public name: string;
public email: string;
public password: string;
constructor(){}
create(user: any) {
return models.User.create(user);
}
getAll(): Bluebird<IUser[]> {
return models.User.findAll({
order: ['name']
})
.then(createUsers);
}
getById(id:number): Bluebird<IUserDetail> {
return models.User.findOne({
where: {id}
})
.then(createUserById);
}
getByEmail(email:string): Bluebird<IUserDetail> {
return models.User.findOne({
where: {email}
})
.then(createUserByEmail)
}
update(id: number, user: any) {
return models.User.update(user, {
where: {id},
fields: ['name', 'email', 'password'],
hooks: true,
individualHooks: true
});
}
delete(id: number) {
return models.User.destroy({
where: {id}
});
}
}
|
d7b2d9b44dad4ff18e96bb1596439e435f5debdf
|
[
"JavaScript",
"TypeScript",
"Dockerfile",
"Markdown"
] | 39
|
JavaScript
|
raphaellima8/typescript-api
|
d3f0a9a876d054e328cfbd54f5d20f6238a8c199
|
5ba6e195029876ce24623e6dc442991fa7a6dead
|
refs/heads/main
|
<file_sep># android-oom
Simple Android App that will crash by Out of Memory
|
e4495e2a2e16df83063001c4ee3c047a54e202e4
|
[
"Markdown"
] | 1
|
Markdown
|
fegoulart/android-oom
|
6bac1fe34290e14946dcacaf3a220b7b036dfa35
|
3b35f12aed89faaf9bbc2e5cc20f68b950c0f7bf
|
refs/heads/master
|
<repo_name>BreankingBad/ssm-crud<file_sep>/src/main/java/com/breaking/crud/bean/ResponseBean.java
package com.breaking.crud.bean;
import java.util.HashMap;
public class ResponseBean {
public static final int CODE_SUCCESS = 100;
public static final int CODE_FAIL = 300;
private int code;
private String msg;
HashMap<String, Object> data = new HashMap<>();
public static ResponseBean success() {
ResponseBean responseBean = new ResponseBean();
responseBean.setCode(CODE_SUCCESS);
return responseBean;
}
public static ResponseBean fail() {
ResponseBean responseBean = new ResponseBean();
responseBean.setCode(CODE_FAIL);
return responseBean;
}
public ResponseBean setData(String key,Object value) {
getData().put(key, value);
return this;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public ResponseBean setMsg(String msg) {
this.msg = msg;
return this;
}
public HashMap<String, Object> getData() {
return data;
}
public void setData(HashMap<String, Object> data) {
this.data = data;
}
}
<file_sep>/src/main/java/com/breaking/crud/test/MapperTest.java
package com.breaking.crud.test;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import java.util.Random;
import java.util.UUID;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.breaking.crud.bean.Department;
import com.breaking.crud.bean.Employee;
import com.breaking.crud.dao.DepartmentMapper;
import com.breaking.crud.dao.EmployeeMapper;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:applicationContext.xml"})
public class MapperTest {
@Autowired
DepartmentMapper departmentMapper;
@Autowired
EmployeeMapper employeeMapper;
@Autowired
SqlSession sqlSession;
@Test
public void testCRUD() {
System.out.println(departmentMapper);
/* departmentMapper.insertSelective(new Department(null, "研发部"));
departmentMapper.insertSelective(new Department(null, "测试部"));
*/
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
for (int i = 0; i < 1000; i++) {
String empName = i +UUID.randomUUID().toString().substring(0,6);
employeeMapper.insertSelective(new Employee(null, empName, "M", empName+"<EMAIL>", 25));
}
}
}
|
93caf9fd848f47f3aa6c835984ac53d03b3385e4
|
[
"Java"
] | 2
|
Java
|
BreankingBad/ssm-crud
|
3d8775bb804e5c9345ff22bfcb3b444bd75ba323
|
4e6df2a710c2eec0d0c0bff1ae2c19e91ac150b5
|
refs/heads/master
|
<repo_name>Abhishek-VG/Santoryu-React-Components<file_sep>/webpack.config.js
const path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
const mode = 'development'; // temp
module.exports = {
context: path.resolve('src'),
mode: 'development',
devtool: 'eval-source-map',
entry: {
santoryu: './index.tsx'
},
output: {
path: path.resolve('build'),
filename: mode === 'production' ? '[chunkhash].js' : '[name].[hash].js'
},
module: {
rules: [
{
test: /\.(js|jsx|ts|tsx)$/,
use: 'babel-loader'
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js', '.jsx']
},
plugins: [new HtmlWebpackPlugin({ template: path.resolve('public/index.html') })],
devServer: {
port: 1234,
open: true,
noInfo: false,
// hotOnly: true,
hot: true
}
};
|
58f2ab5c27ea232a87cc53f83fdbc105172e81c0
|
[
"JavaScript"
] | 1
|
JavaScript
|
Abhishek-VG/Santoryu-React-Components
|
96f5f07fe7b048988b7110eb39ab55e2e9b5009d
|
4d2fc6936427ec91e69298f8d56c58984d3ea658
|
refs/heads/master
|
<file_sep>let Service, Characteristic;
const packageJson = require('./package.json');
const request = require('request');
const ip = require('ip');
const http = require('http');
let globalHomebridge;
module.exports = function (homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory('homebridge-http-request-thermostat', 'HttpThermostat', Thermostat);
globalHomebridge = homebridge;
}
class Thermostat {
constructor(log, config) {
this.log = log
this.notificationID = config.notificationID;
this.name = config.name;
this.slug = config.slug;
this.pollInterval = config.pollInterval || 300;
this.listener = config.listener || false;
this.port = config.port || 2000;
this.requestArray = ['targetHeatingCoolingState', 'targetTemperature', 'coolingThresholdTemperature', 'heatingThresholdTemperature'];
this.manufacturer = config.manufacturer || packageJson.author.name;
this.serial = config.serial || this.slug;
this.model = config.model || packageJson.name;
this.firmware = config.firmware || packageJson.version;
this.request = config.request || null;
this.setTargetHeatingCoolingStateRequest = config.setTargetHeatingCoolingStateRequest || null;
this.setTargetTemperatureRequest = config.setTargetTemperatureRequest || null;
this.setCoolingThresholdTemperatureRequest = config.setCoolingThresholdTemperatureRequest || null;
this.setHeatingThresholdTemperatureRequest = config.setHeatingThresholdTemperatureRequest || null;
this.getStatusRequest = config.getStatusRequest || null;
this.timeout = config.timeout || 3000;
this.temperatureThresholds = config.temperatureThresholds || false;
this.validValues = config.validValues || null;
this.currentRelativeHumidity = config.currentRelativeHumidity || false;
this.temperatureDisplayUnits = config.temperatureDisplayUnits || 0;
this.maxTemp = config.maxTemp || 30;
this.minTemp = config.minTemp || 15;
this.minStep = config.minStep || 0.5;
if (this.listener) {
this.server = http.createServer(function (request, response) {
const baseURL = 'http://' + request.headers.host + '/';
const url = new URL(request.url, baseURL);
if (this.requestArray.includes(url.pathname.substr(1))) {
this.log.debug('Handling request');
response.end('Handling request');
this._httpHandler(url.pathname.substr(1), url.searchParams.get('value'))
} else {
this.log.warn('Invalid request: %s', request.url);
response.end('Invalid request');
}
}.bind(this))
this.server.listen(this.port, function () {
this.log('Listen server: http://%s:%s', ip.address(), this.port);
}.bind(this))
}
globalHomebridge.on('didFinishLaunching', function() {
// check if notificationRegistration is set, if not 'notificationRegistration' is probably not installed on the system
if (global.notificationRegistration && typeof global.notificationRegistration === 'function') {
try {
global.notificationRegistration(this.notificationID, this.handleNotification.bind(this));
} catch (error) {
// notificationID is already taken
}
}
}.bind(this));
this.service = new Service.Thermostat(this.name);
}
handleNotification(jsonRequest) {
const characteristic = jsonRequest.characteristic;
const value = jsonRequest.value;
let characteristicEnum = null;
switch (characteristic) {
case 'TargetTemperature':
characteristicEnum = Characteristic.TargetTemperature;
break;
case 'CurrentTemperature':
characteristicEnum = Characteristic.CurrentTemperature;
break;
case 'TargetHeatingCoolingState':
characteristicEnum = Characteristic.TargetHeatingCoolingState;
break;
case 'CurrentHeatingCoolingState':
characteristicEnum = Characteristic.CurrentHeatingCoolingState;
break;
case 'CoolingThresholdTemperature':
characteristicEnum = Characteristic.CoolingThresholdTemperature;
break;
case 'HeatingThresholdTemperature':
characteristicEnum = Characteristic.HeatingThresholdTemperature;
break;
case 'CurrentRelativeHumidity':
characteristicEnum = Characteristic.CurrentRelativeHumidity;
break;
default:
this.log(`Unknown characteristic when handling notification: ${characteristic}`);
break;
}
this.service.getCharacteristic(characteristicEnum).updateValue(value);
}
identify(callback) {
this.log('Identify requested!');
callback();
}
_httpRequest(requestOptions, body, callback) {
const options = {
...requestOptions
};
options.timeout = options.timeout || this.timeout;
options.rejectUnauthorized = false;
options.json = true;
if (body) {
options.body = body;
}
request(options, callback);
}
_getStatus(callback) {
this.log.debug('Getting status ...');
this._httpRequest(this.getStatusRequest, null, function (error, response, responseBody) {
if (error) {
this.log.warn('Error getting status: %s', error.message)
this.service.getCharacteristic(Characteristic.CurrentHeatingCoolingState).updateValue(new Error('Polling failed'))
callback(error)
} else {
this.log.debug('Device response: %s', responseBody)
this.service.getCharacteristic(Characteristic.TargetTemperature).updateValue(responseBody.targetTemperature)
this.log.debug('Updated TargetTemperature to: %s', responseBody.targetTemperature)
this.service.getCharacteristic(Characteristic.CurrentTemperature).updateValue(responseBody.currentTemperature)
this.log.debug('Updated CurrentTemperature to: %s', responseBody.currentTemperature)
this.service.getCharacteristic(Characteristic.TargetHeatingCoolingState).updateValue(responseBody.targetHeatingCoolingState)
this.log.debug('Updated TargetHeatingCoolingState to: %s', responseBody.targetHeatingCoolingState)
this.service.getCharacteristic(Characteristic.CurrentHeatingCoolingState).updateValue(responseBody.currentHeatingCoolingState)
this.log.debug('Updated CurrentHeatingCoolingState to: %s', responseBody.currentHeatingCoolingState)
if (this.temperatureThresholds) {
this.service.getCharacteristic(Characteristic.CoolingThresholdTemperature).updateValue(responseBody.coolingThresholdTemperature)
this.log.debug('Updated CoolingThresholdTemperature to: %s', responseBody.coolingThresholdTemperature)
this.service.getCharacteristic(Characteristic.HeatingThresholdTemperature).updateValue(responseBody.heatingThresholdTemperature)
this.log.debug('Updated HeatingThresholdTemperature to: %s', responseBody.heatingThresholdTemperature)
}
if (this.currentRelativeHumidity) {
this.service.getCharacteristic(Characteristic.CurrentRelativeHumidity).updateValue(responseBody.currentRelativeHumidity)
this.log.debug('Updated CurrentRelativeHumidity to: %s', responseBody.currentRelativeHumidity)
}
callback()
}
}.bind(this));
}
_httpHandler(characteristic, value) {
switch (characteristic) {
case 'targetHeatingCoolingState':
this.service.getCharacteristic(Characteristic.TargetHeatingCoolingState).updateValue(value)
this.log('Updated %s to: %s', characteristic, value)
break
case 'targetTemperature':
this.service.getCharacteristic(Characteristic.TargetTemperature).updateValue(value)
this.log('Updated %s to: %s', characteristic, value)
break
case 'coolingThresholdTemperature':
this.service.getCharacteristic(Characteristic.CoolingThresholdTemperature).updateValue(value)
this.log('Updated %s to: %s', characteristic, value)
break
case 'heatingThresholdTemperature':
this.service.getCharacteristic(Characteristic.HeatingThresholdTemperature).updateValue(value)
this.log('Updated %s to: %s', characteristic, value)
break
default:
this.log.warn('Unknown characteristic "%s" with value "%s"', characteristic, value)
}
}
setTargetHeatingCoolingState(value, callback) {
this.log.debug('Setting targetHeatingCoolingState ...');
this._httpRequest(this.setTargetHeatingCoolingStateRequest, {value}, function (error, response, responseBody) {
if (error) {
this.log.warn('Error setting targetHeatingCoolingState: %s', error.message)
callback(error)
} else {
this.log('Set targetHeatingCoolingState to: %s', value)
this.service.getCharacteristic(Characteristic.CurrentHeatingCoolingState).updateValue(value)
callback()
}
}.bind(this));
}
setTargetTemperature(value, callback) {
value = value.toFixed(1);
this.log.debug('Setting targetTemperature ...');
this._httpRequest(this.setTargetTemperatureRequest, {value}, function (error, response, responseBody) {
if (error) {
this.log.warn('Error setting targetTemperature: %s', error.message)
callback(error)
} else {
this.log('Set targetTemperature to: %s', value)
callback()
}
}.bind(this));
}
setCoolingThresholdTemperature(value, callback) {
value = value.toFixed(1);
this.log.debug('Setting coolingThresholdTemperature ...');
this._httpRequest(this.setCoolingThresholdTemperatureRequest, {value}, function (error, response, responseBody) {
if (error) {
this.log.warn('Error setting coolingThresholdTemperature: %s', error.message)
callback(error)
} else {
this.log('Set coolingThresholdTemperature to: %s', value)
callback()
}
}.bind(this));
}
setHeatingThresholdTemperature(value, callback) {
value = value.toFixed(1);
this.log.debug('Setting heatingThresholdTemperature ...')
this._httpRequest(this.setHeatingThresholdTemperatureRequest, {value}, function (error, response, responseBody) {
if (error) {
this.log.warn('Error setting heatingThresholdTemperature: %s', error.message)
callback(error)
} else {
this.log('Set heatingThresholdTemperature to: %s', value)
callback()
}
}.bind(this))
}
getServices() {
this.informationService = new Service.AccessoryInformation()
this.informationService
.setCharacteristic(Characteristic.Manufacturer, this.manufacturer)
.setCharacteristic(Characteristic.Model, this.model)
.setCharacteristic(Characteristic.SerialNumber, this.serial)
.setCharacteristic(Characteristic.FirmwareRevision, this.firmware);
this.service.getCharacteristic(Characteristic.TemperatureDisplayUnits).updateValue(this.temperatureDisplayUnits)
this.service
.getCharacteristic(Characteristic.TargetHeatingCoolingState)
.on('set', this.setTargetHeatingCoolingState.bind(this))
if (this.validValues) {
this.service.getCharacteristic(Characteristic.TargetHeatingCoolingState)
.setProps({
validValues: this.validValues
});
}
this.service
.getCharacteristic(Characteristic.TargetTemperature)
.on('set', this.setTargetTemperature.bind(this))
.setProps({
minValue: this.minTemp,
maxValue: this.maxTemp,
minStep: this.minStep
});
if (this.temperatureThresholds) {
this.service
.getCharacteristic(Characteristic.CoolingThresholdTemperature)
.on('set', this.setCoolingThresholdTemperature.bind(this))
.setProps({
minValue: this.minTemp,
maxValue: this.maxTemp,
minStep: this.minStep
});
this.service
.getCharacteristic(Characteristic.HeatingThresholdTemperature)
.on('set', this.setHeatingThresholdTemperature.bind(this))
.setProps({
minValue: this.minTemp,
maxValue: this.maxTemp,
minStep: this.minStep
});
}
this._getStatus(function () {});
setInterval(function () {
this._getStatus(function () {})
}.bind(this), this.pollInterval * 1000);
return [this.informationService, this.service];
}
}
|
59cad2930db47fa4db27e5a47976e3329e1a3ea6
|
[
"JavaScript"
] | 1
|
JavaScript
|
BossaGroove/homebridge-http-request-thermostat
|
fad4546afdf1f4b852f810c6c1fa30773f3b2684
|
0072a829eefee32d8eadc5bd4f769cd0071149d3
|
refs/heads/main
|
<repo_name>Esoteric918/simple_shell<file_sep>/_built_in.c
#include "shell.h"
/**
* _exit_command - this function closes the simple_shell when
* @arg: pointer with the direction argument.
* @lineptr: standar input string
* @_exit: value of exit
* Return: None
*/
void _exit_command(char **arg, char *lineptr, int _exit)
{
int exit_status = 0;
if (!arg[1])
{
free(lineptr);
free(arg);
exit(_exit);
}
exit_status = atoi(arg[1]);
free(lineptr);
free(arg);
exit(exit_status);
}
/**
*_getenv - function to get all env
*@env: enviroment
*Return: 0
*/
void _getenv(char **env)
{
size_t run = 0;
while (env[run])
{
write(STDOUT_FILENO, env[run], _strlen(env[run]));
write(STDOUT_FILENO, "\n", 1);
run++;
}
}
<file_sep>/README.md
# 0x17. C - Simple Shell
By <NAME>
> using resources provided by <NAME>, co-founder & CEO at Holberton School
## Concepts
For this project, students are expected to look at these concepts:
- *Approaching a Project*
- *Everything you need to know to start coding your own shell*
## Background Context
Write a simple UNIX command interpreter.
## Resources
### Read or watch:
- Unix shell
- Thompson shell
- <NAME>
- *Everything you need to know to start coding your own shell* concept page
### man or help:
- sh (Run sh as well)
## Learning Objectives
At the end of this project, you are expected to be able to explain to anyone, without the help of Google:
## General
- Who designed and implemented the original Unix operating system
- Who wrote the first version of the UNIX shell
- Who invented the B programming language (the direct predecessor to the C programming language)
- Who is <NAME>
- How does a shell work
- What is a pid and a ppid
- How to manipulate the environment of the current process
- What is the difference between a function and a system call
- How to create processes
- What are the three prototypes of main
- How does the shell use the PATH to find the programs
- How to execute another program with the execve system call
- How to suspend the execution of a process until one of its children terminates
- What is EOF / “end-of-file”?
## Requirements
## General
- Allowed editors: vi, vim, emacs
- All files will be compiled on Ubuntu 20.04 LTS using gcc, using the options -Wall -Werror -Wextra -pedantic -std=gnu89
- All files should end with a new line
- A README.md file, at the root of the folder of the project is mandatory
- Code should use the Betty style. It will be checked using betty-style.pl and betty-doc.pl
- Shell should not have any memory leaks
- No more than 5 functions per file
- All header files should be include guarded
- Use system calls only when need to (why?)
## GitHub
There should be one project repository per group. If you clone/fork/whatever a project repository with the same name before the second deadline, you risk a 0% score.
## More Info
## Output
- Unless specified otherwise, program must have the exact same output as sh (/bin/sh) as well as the exact same error output.
- The only difference is when print an error, the name of the program must be equivalent to argv[0] (See below)
Example of error with sh:
```
$ echo "qwerty" | /bin/sh
/bin/sh: 1: qwerty: not found
$ echo "qwerty" | /bin/../bin/sh
/bin/../bin/sh: 1: qwerty: not found
$
```
Same error with your program hsh:
```
$ echo "qwerty" | ./hsh
./hsh: 1: qwerty: not found
$ echo "qwerty" | ./././hsh
./././hsh: 1: qwerty: not found
$
```
## List of allowed functions and system calls
- access (man 2 access)
- chdir (man 2 chdir)
- close (man 2 close)
- closedir (man 3 closedir)
- execve (man 2 execve)
- exit (man 3 exit)
- _exit (man 2 _exit)
- fflush (man 3 fflush)
- fork (man 2 fork)
- free (man 3 free)
- getcwd (man 3 getcwd)
- getline (man 3 getline)
- getpid (man 2 getpid)
- isatty (man 3 isatty)
- kill (man 2 kill)
- malloc (man 3 malloc)
- open (man 2 open)
- opendir (man 3 opendir)
- perror (man 3 perror)
- read (man 2 read)
- readdir (man 3 readdir)
- signal (man 2 signal)
- stat (__xstat) (man 2 stat)
- lstat (__lxstat) (man 2 lstat)
- fstat (__fxstat) (man 2 fstat)
- strtok (man 3 strtok)
- wait (man 2 wait)
- waitpid (man 2 waitpid)
- wait3 (man 2 wait3)
- wait4 (man 2 wait4)
- write (man 2 write)
## Compilation
Your shell will be compiled this way:
```gcc -Wall -Werror -Wextra -pedantic -std=gnu89 *.c -o hsh
```
## Testing
Your shell should work like this in interactive mode:
```
$ ./hsh
($) /bin/ls
hsh main.c shell.c
($)
($) exit
$
```
But also in non-interactive mode:
```
$ echo "/bin/ls" | ./hsh
hsh main.c shell.c test_ls_2
$
$ cat test_ls_2
/bin/ls
/bin/ls
$
$ cat test_ls_2 | ./hsh
hsh main.c shell.c test_ls_2
hsh main.c shell.c test_ls_2
$
```
## Tasks
- [x] README.md
- [x] man\_1\_simple\_shell
- [x] AUTHORS
- [x] Write a beautiful code that passes the Betty checks
- [x] Write a UNIX command line interpreter
- [x] Handle command lines with arguments
- [ ] Handle the PATH
- [x] Implement the exit built-in, that exits the shell
- [x] Implement the env built-in, that prints the current environment
- [x] blog post describing step by step what happens when you type ls -l *.c and hit Enter in a sheLL
<file_sep>/_get_token.c
#include "shell.h"
/**
* _get_token - get token of string
* @lineptr: comman user
* Return: To a pointer
*/
char **_get_token(char *lineptr)
{
char **user_comm = NULL;
char *token = NULL;
size_t i = 0;
int size = 0;
if (lineptr == NULL)
return (NULL);
for (i = 0; lineptr[i]; i++)
{
if (lineptr[i] == ' ')
size++;
}
if ((size + 1) == _strlen(lineptr))
return (NULL);
user_comm = malloc(sizeof(char *) * (size + 2));
if (user_comm == NULL)
return (NULL);
token = strtok(lineptr, " \n\t\r");
for (i = 0; token != NULL; i++)
{
user_comm[i] = token;
token = strtok(NULL, " \n\t\r");
}
user_comm[i] = NULL;
return (user_comm);
}
<file_sep>/_getline_command.c
#include "shell.h"
/**
* _getline_command - print "simple_shell$ " and wait for input
* Return: line of string input for user
*/
char *_getline_command(void)
{
char *lineptr = NULL;
size_t shell_user = 0;
if (isatty(STDIN_FILENO))
write(STDOUT_FILENO, "simple_shell$ ", 14);
if (getline(&lineptr, &shell_user, stdin) == -1)
{
free(lineptr);
return (NULL);
}
return (lineptr);
}
<file_sep>/fork_function.c
#include "shell.h"
/**
* _frk_func - function that create a fork
*@arg: command and values path
*@av: Has the name of our program
*@env: environment
*@lineptr: command line for the user
*@np: id of proces
*@c: Checker add new test
*Return: 0 success
*/
int _frk_func(char **arg, char **av, char **env, char *lineptr, int np, int c)
{
pid_t child;
int status;
char *format = "%s: %d: %s: not found\n";
child = fork();
if (arg == NULL)
exit(errno);
if (child == 0)
{
if (execve(arg[0], arg, env) == -1)
{
fprintf(stderr, format, av[0], np, arg[0]);
if (!c)
free(arg[0]);
free(arg);
free(lineptr);
exit(errno);
}
}
else
{
wait(&status);
if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
return (WEXITSTATUS(status));
}
return (0);
}
<file_sep>/simple_shell.c
#include "shell.h"
/**
* main - main arguments functions
* @ac:count of argumnents
* @av: arguments
* @env: environment
* Return: _exit = 0.
*/
int main(int ac, char **av, char **env)
{
char *getcommand = NULL, **user_command = NULL;
int pathValue = 0, _exit = 0, n = 0;
(void)ac;
while (1)
{
getcommand = _getline_command();
if (getcommand)
{
pathValue++;
user_command = _get_token(getcommand);
if (!user_command)
{
free(getcommand);
continue;
}
if (!_strcmp(user_command[0], "exit") && user_command[1] == NULL)
_exit_command(user_command, getcommand, _exit);
if (!_strcmp(user_command[0], "env"))
_getenv(env);
else
{
n = _value_path(&user_command[0], env);
_exit = _frk_func(user_command, av, env, getcommand, pathValue, n);
if (n == 0)
free(user_command[0]);
}
free(user_command);
}
else
{
if (isatty(STDIN_FILENO))
write(STDOUT_FILENO, "\n", 1);
exit(_exit);
}
free(getcommand);
}
}
<file_sep>/str_funcs.c
#include "shell.h"
/**
* _strcat - concatenates two strings
*@dest: string appended by src
*@src: string appending dest
*
* Return: dest
*/
char *_strcat(char *dest, char *src)
{
int j, k;
j = 0;
k = 0;
while (dest[j] != '\0')
{
++j;
}
while (src[k] != '\0')
{
dest[j] = src[k];
++j;
++k;
}
dest[j] = '\0';
return (dest);
}
/**
* _strcmp - compares two strings
*@s1: dest of string
*@s2: src of string
*
* Return: n
*/
int _strcmp(char *s1, char *s2)
{
int i;
for (i = 0; s1[i] == s2[i] ; i++)
if (s1[i] == '\0')
return (0);
return (s1[i] - s2[i]);
}
/**
* _strcpy - copy string
* @dest: address pointed to
* @src: string being pointed to
* Return: dest
*/
char *_strcpy(char *dest, char *src)
{
int k = 0;
while (src[k] != '\0')
{
dest[k] = src[k];
++k;
}
dest[k] = '\0';
++k;
return (dest);
}
/**
*_strlen - function to return length of a string
*@s: pointer to the string
*Return: 0
*/
int _strlen(char *s)
{
int k = 0;
while (*(s + k) != '\0')
++k;
return (k);
}
/**
*_strncmp - function that compares two strings.
*@s1: string one
*@s2: string two
*@n: number of characters
* Return: diference
*/
size_t _strncmp(char *s1, char *s2, size_t n)
{
size_t i, j;
for (j = 0; s1[j] != '\0' && j < n; j++)
{
i = s1[j] - s2[j];
if (i != 0)
{
return (i);
}
}
return (0);
}
<file_sep>/shell.h
#ifndef SHELL_H
#define SHELL_H
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
extern char **environ;
/** command line functions**/
char *_get_path(char **env);
int _value_path(char **arg, char **env);
char *_getline_command(void);
void _getenv(char **env);
char **_get_token(char *lineptr);
void _exit_command(char **args, char *lineptr, int _exit);
int _frk_func(char **arg, char **av, char **env,
char *lineptr, int np, int c);
/** string functions **/
int _strcmp(char *s1, char *s2);
size_t _strncmp(char *s1, char *s2, size_t n);
int _strlen(char *s);
char *_strcpy(char *dest, char *src);
char *_strcat(char *dest, char *src);
int _putchar(char c);
#endif
<file_sep>/pathfinder.c
#include "shell.h"
/**
* _get_path - get variable PATH.
* @env: enviromente local
* Return: value of PATH.
*/
char *_get_path(char **env)
{
size_t index = 0, var = 0, count = 5;
char *path = NULL;
for (index = 0; _strncmp(env[index], "PATH=", 5); index++)
;
if (env[index] == NULL)
return (NULL);
for (count = 5; env[index][var]; var++, count++)
;
path = malloc(sizeof(char) * (count + 1));
if (path == NULL)
return (NULL);
for (var = 5, count = 0; env[index][var]; var++, count++)
path[count] = env[index][var];
path[count] = '\0';
return (path);
}
<file_sep>/_value_path.c
#include "shell.h"
/**
* _value_path - separate the path in new strings.
* @arg: command input of user.
* @env: enviroment.
* Return: a pointer to strings.
*/
int _value_path(char **arg, char **env)
{
char *token = NULL, *path_rela = NULL, *path_absol = NULL;
size_t value_path, command;
struct stat stat_lineptr;
if (stat(*arg, &stat_lineptr) == 0)
return (-1);
path_rela = _get_path(env);
if (!path_rela)
return (-1);
token = strtok(path_rela, ":");
command = _strlen(*arg);
while (token)
{
value_path = _strlen(token);
path_absol = malloc(sizeof(char) * (value_path + command + 2));
if (!path_absol)
{
free(path_rela);
return (-1);
}
path_absol = _strcpy(path_absol, token);
_strcat(path_absol, "/");
_strcat(path_absol, *arg);
if (stat(path_absol, &stat_lineptr) == 0)
{
*arg = path_absol;
free(path_rela);
return (0);
}
free(path_absol);
token = strtok(NULL, ":");
}
free(path_rela);
return (-1);
}
|
b67aef853e31623e8b1b9b2f20175b69034cc2a8
|
[
"Markdown",
"C"
] | 10
|
C
|
Esoteric918/simple_shell
|
491458ac754bca0301402af1ec33ed8c5f96045c
|
81eb42e9c5b37b456796053f0a62762b08b16a92
|
refs/heads/master
|
<repo_name>raminorujov/qafqaz-java-web-2014<file_sep>/20141025/SessionDemo/src/java/sessiondemo/MySessionAttributeListener.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sessiondemo;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
/**
* Web application lifecycle listener.
*
* @author raminorujov
*/
public class MySessionAttributeListener implements HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
System.out.println("New attribute added " + event.getName() + " = " + event.getValue());
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
System.out.println("Attribute " + event.getName() + " is removed");
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
System.out.println("Attribute replace " + event.getName() + " = " + event.getValue());
}
}
<file_sep>/Library System/src/java/org/library/utility/JdbcUtil.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.library.utility;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author raminorujov
*/
public class JdbcUtil {
public static void close(ResultSet rs, PreparedStatement ps, Connection con) {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
<file_sep>/Library System/src/java/org/library/domain/BaseDomain.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.library.domain;
import java.math.BigDecimal;
/**
*
* @author raminorujov
*/
public class BaseDomain {
protected BigDecimal id;
protected Status status;
public BigDecimal getId() {
return id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
@Override
public String toString() {
return "BaseDomain{" + "id=" + id + ", status=" + status + '}';
}
}
<file_sep>/Library System/src/java/org/library/domain/Status.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.library.domain;
/**
*
* @author raminorujov
*/
public enum Status {
Active("a"),
Deactive("d"),
Unknown("u");
private String value;
Status(String value) {
this.value = value;
}
public static Status fromValue(String value) {
if(value != null) {
if(value.equals("a")) {
return Active;
} else if(value.equals("d")) {
return Deactive;
}
}
return Unknown;
}
}
<file_sep>/20141025/SessionDemo/src/java/sessiondemo/SessionInfo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sessiondemo;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author raminorujov
*/
public class SessionInfo extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
HttpSession session = request.getSession();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SessionInfo</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet SessionInfo at " + request.getContextPath() + "</h1>");
out.println("Session id = " + session.getId() + "<br/>");
out.println("Session create time = " + session.getCreationTime() + " / " + new java.util.Date(session.getCreationTime()) + "<br/>");
out.println("Session last accessed time = " + session.getLastAccessedTime() + " / " + new java.util.Date(session.getLastAccessedTime()) + "<br/>");
out.println("Session max inactive interval " + session.getMaxInactiveInterval());
out.println("<br/><br/>Session attributes <br/>");
Enumeration<String> attributes = session.getAttributeNames();
while(attributes.hasMoreElements()) {
String name = attributes.nextElement();
out.println(name + " = " + session.getAttribute(name) + "<br/>");
}
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
<file_sep>/README.md
qafqaz-java-web-2014
====================
Projects developed during java web programming course for the Qafqaz University Computer Engineering 4th year students 2014.
<file_sep>/Library System/src/java/org/library/dao/DatabaseHelper.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.library.dao;
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
/**
*
* @author raminorujov
*/
public class DatabaseHelper {
public static Connection connect() throws Exception {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/librarydb");
Connection connection = ds.getConnection();
if (connection != null) {
connection.setAutoCommit(false);
} else {
throw new Exception("connect() Connection is null " + new java.util.Date());
}
return connection;
}
}
<file_sep>/Library System/nbproject/private/private.properties
deploy.ant.properties.file=/Users/raminorujov/Library/Application Support/NetBeans/8.0/tomcat70.properties
j2ee.server.home=/Users/raminorujov/tomcats/apache-tomcat-7.0.55
j2ee.server.instance=tomcat70:home=/Users/raminorujov/tomcats/apache-tomcat-7.0.55/
javac.debug=true
javadoc.preview=true
selected.browser=default
user.properties.file=/Users/raminorujov/Library/Application Support/NetBeans/8.0/build.properties
|
375e29bacf2443ddb6b690d30115bbbb4de063d0
|
[
"Markdown",
"Java",
"INI"
] | 8
|
Java
|
raminorujov/qafqaz-java-web-2014
|
408cc2e5dc70fe19f98e01f0fc9cf81c2603b9da
|
c66f2e7ca7d85f6202d6ca821431e1116389d96a
|
refs/heads/master
|
<repo_name>dlthdlthdlth/hackTheGap_CodeYourAvatar<file_sep>/Main2Activity.java
package thesohyproject.codeyouravatar;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.transition.Visibility;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
public static final String EXTRA_CASE = "";
public static String EXTRA_NAME = "";
RadioGroup radioGroup;
RelativeLayout relativeLayout;
int choiceOfClothing;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Set the entered name of the user to the next page
Intent intent = getIntent();
String usersName = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = (TextView) findViewById(R.id.usersName);
textView.setText(usersName);
EXTRA_NAME = usersName;
// change the image according to the user's click. If a wrong answer selected, don't do anything
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup_main2);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
switch (i) {
// choiceOfClothing = 1
case R.id.radioButton_dress_main3:
relativeLayout.getChildAt(1).setVisibility(View.VISIBLE);
relativeLayout.getChildAt(2).setVisibility(View.INVISIBLE);
choiceOfClothing = 1;
break;
// choiceOfClothing = 2
case R.id.radioButton_pants_main3:
relativeLayout.getChildAt(1).setVisibility(View.INVISIBLE);
relativeLayout.getChildAt(2).setVisibility(View.VISIBLE);
choiceOfClothing = 2;
break;
// choiceOfClothing = 3
default:
relativeLayout.getChildAt(1).setVisibility(View.INVISIBLE);
relativeLayout.getChildAt(2).setVisibility(View.INVISIBLE);
choiceOfClothing = 3;
break;
}
}
});
}
public void toNextPage(View view) {
Intent intent = new Intent(this, Main3Activity.class);
intent.putExtra(EXTRA_CASE, choiceOfClothing);
startActivity(intent);
}
}<file_sep>/README.md
# hackTheGap_CodeYourAvatar
This is an android app that my team created during Hack The Gap 2017 Beginner's Hackathon at BU
|
0338c6759486f9f5c33d869808aa1b4b611f8f8a
|
[
"Markdown",
"Java"
] | 2
|
Java
|
dlthdlthdlth/hackTheGap_CodeYourAvatar
|
7c36b8b0471d59d6dfeb492579bf2e4892795a7c
|
4d85ae8d2e9ef91c7736efaee77a50a1bb7b43a7
|
refs/heads/master
|
<repo_name>LeninGF/textClassificationTPU<file_sep>/trainWordCnn.py
"""
This script aims to train the model WordCNN migrated
from its tensorflow v1.X original version in Github
to its equivalent in Keras. Then it must be tested on TPU
Author: <NAME>
"""
#%% importing libraries
import tensorflow as tf
import os
import numpy as np
from data_utils import *
from sklearn.model_selection import train_test_split
print(tf.__version__)
#%% These are some constants in the project
NUM_CLASS = 14
BATCH_SIZE = 64
NUM_EPOCHS = 10
WORD_MAX_LEN = 100
CHAR_MAX_LEN = 1014
#%% Downloading the dataset
if not os.path.exists("dbpedia_csv"):
print("Downloading dbpedia dataset...")
download_dbpedia()
print("Creating dataset")
word_dict = build_word_dict()
vocabulary_size = len(word_dict)
x, y = build_word_dataset("train", word_dict, WORD_MAX_LEN)
train_x, valid_x, train_y, valid_y = train_test_split(x, y, test_size=0.15)
train_x = np.array(train_x)
valid_x = np.array(valid_x)
train_y = np.array(train_y)
valid_y = np.array(valid_y)
print("train and valid datasets created ...")
print("train x: {}, x[0]: {}, type:{}".format(train_x.shape, train_x[0], type(train_x[0])))
print("valid x: {}".format(np.shape(valid_x)))
print("train y: {}".format(np.shape(train_y)))
#%% Defining the model
"""
This section implements a function that creates WordCNN
model. Some constants are needed to the model work
"""
embedding_size = 128
num_filters = 100
filter_sizes = [3, 4, 5]
num_class = 14
def word_cnn_model_create(embedding_size=128,
num_filters=100,
filter_sizes=[3, 4, 5],
num_classes=14,
document_max_len=100):
x = tf.keras.Input(shape=(100, ))
embeddings = tf.keras.layers.Embedding(input_dim=vocabulary_size,
output_dim=embedding_size,
input_length=document_max_len,
embeddings_initializer='uniform')(x)
x_emb = tf.keras.layers.Reshape((100, 128, 1))(embeddings)
pooled_outputs = []
for filter_size in filter_sizes:
conv = tf.keras.layers.Conv2D(input_shape=(None, 100, 128, 1),
filters=num_filters,
kernel_size=[filter_size, embedding_size],
strides=(1, 1),
padding="valid",
activation="relu")(x_emb)
pool = tf.keras.layers.MaxPooling2D(pool_size=[document_max_len - filter_size + 1, 1],
strides=(1, 1),
padding='valid')(conv)
pooled_outputs.append(pool)
h_pool = tf.keras.layers.concatenate(pooled_outputs)
h_pool_flat = tf.keras.layers.Flatten()(h_pool)
h_drop = tf.keras.layers.Dropout(rate=0.5)(h_pool_flat)
output = tf.keras.layers.Dense(units=num_classes, activation="softmax")(h_drop)
model = tf.keras.Model(inputs=x, outputs=output)
return model
wordCNNModel = word_cnn_model_create(embedding_size=embedding_size,
num_filters=num_filters,
num_classes=num_class,
filter_sizes=filter_sizes,
document_max_len=WORD_MAX_LEN
)
print("Model to train has structure: ")
wordCNNModel.summary()
# tf.keras.utils.plot_model(model=wordCNNModel, to_file="wordCNNModel.png", show_shapes=True, show_layer_names=True)
wordCNNModel.compile(optimizer=tf.keras.optimizers.Adam(lr=1e-3),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['acc'])
print("training started")
wordCNNModel.fit(x=train_x,
y=train_y,
batch_size=BATCH_SIZE,
epochs=NUM_EPOCHS,
verbose=1)
print("training finished")
<file_sep>/README.md
# textClassificationTPU
This is a remake of WordCNN model in tensorflow keras version
|
2824785aa9a5f27e5a9dc7f8fe2eaa5424213258
|
[
"Markdown",
"Python"
] | 2
|
Python
|
LeninGF/textClassificationTPU
|
c0865f8de99766ec882174883fe6dceca0fd8287
|
4141a2c04de321fb599d0e2f0e754fc81c3c5198
|
refs/heads/master
|
<repo_name>GabrielMarcelino/mclweb<file_sep>/briefing.php
<!DOCTYPE html>
<html lang="pt-br" itemscope itemtype="https://schema.org/Article">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Mcl - Soluções Web | Sites Institucionais, Lojas Virtuais, Marketing Digital & Aplicativos Mobile Android e Ios. Solução está na Web, e nós te levamos onde todos estão !">
<meta name="keywords" content="mcl, mclweb, mcl soluções web, marketing, marketing digital, criação de site, sites baratos, e-commerce, loja virtual, aplicativo mobile, aplicativo android, marketing facebook, marketing google, marketing instagram, preciso da um up na minha empresa, solução para empresa, micro empreendedores, aumento de venda, divulgação de marca, gabriel marcelino, duque de caxias, site responsivo, site para celular, preciso de um site, email corporativo" />
<meta name="author" content="<NAME> | Mcl - Soluções Web">
<meta name="robots" content="index, follow"/>
<meta name="email" content="<EMAIL>">
<link rel="canonical" href="http://mclweb.com.br/">
<meta property="og:type" content="website" />
<meta property="og:title" content="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" />
<meta property="og:description" content="Mcl - Soluções Web | Sites Institucionais, Lojas Virtuais, Marketing Digital & Aplicativos Mobile Android e Ios. Solução está na Web, e nós te levamos onde todos estão !" />
<meta property="og:url" content="http://mclweb.com.br/" />
<meta property="og:site_name" content="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" />
<meta property="og:locale" content="pt-BR" />
<meta property="og:image" content="http://mclweb.com.br/img/Looogo.png" />
<meta property="og:keywords" content="mcl, mclweb, mcl soluções web, marketing, marketing digital, criação de site, sites baratos, e-commerce, loja virtual, aplicativo mobile, aplicativo android, marketing facebook, marketing google, marketing instagram, preciso da um up na minha empresa, solução para empresa, micro empreendedores, aumento de venda, divulgação de marca, gabriel marcelino, duque de caxias, site responsivo, site para celular, preciso de um site, email corporativo" />
<meta property="og:email" content="<EMAIL>" />
<meta property="og:publisher" content="https://www.facebook.com/mclsolucoesweb/" />
<title>Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital</title>
<!-- Bootstrap Core CSS -->
<link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="shortcut icon" href="img/favicon01.png" />
<!-- Custom Fonts -->
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Muli" rel="stylesheet">
<!-- Plugin CSS -->
<link rel="stylesheet" href="lib/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="lib/simple-line-icons/css/simple-line-icons.css">
<link rel="stylesheet" href="lib/device-mockups/device-mockups.min.css">
<!-- Theme CSS -->
<link href="css/new-age2.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<style>
nav{
padding: 0 0 0.5%;
}
</style>
</head>
<body id="page-top">
<!-- GOOGLE ANALYTICS -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-99837565-1', 'auto');
ga('send', 'pageview');
</script>
<h1 style="display: none!important;">Mcl - Soluções Web | Desenvolvimento Web e Marketing Digital</h1>
<nav id="mainNav" class="navbar navbar-default navbar-fixed-top bg-white">
<h2 style="display: none!important;">Mcl - Soluções Web | Menu</h2>
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
</button>
<a class="navbar-brand page-scroll" href="index.php"><img class="logo" alt="[Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital | Logo]" title="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital | Logo" src="img/Mcl-Solucoes-Web-Logo.png" /></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a class="page-scroll" href="#serviços">Serviços</a>
</li>
<li>
<a class="page-scroll" href="#diferenciais">Diferenciais</a>
</li>
<li>
<a class="page-scroll" href="#pessoal">Pessoal</a>
</li>
<li>
<a class="page-scroll" href="#portfolio">Portfólio</a>
</li>
<li>
<a class="page-scroll" href="#tramite">Tramite</a>
</li>
<li>
<a class="page-scroll" href="#contato">Contato</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<header class="header">
</header>
<section class="bg-primary form-briefing">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 class="text-center">Briefing</h1>
<p>Um briefing bem feito e executado pode determinar se um site será bom ou ruim<br> (baseado nas necessidades e expectativas do cliente).</p>
<h3 class="text-center">... Ou seja, não economize nas informações ;-)</h3>
</div>
</div>
</div>
</section>
<!-- 1-4 2-8 3-5 4-5 5-4 6-9 7-6-->
<section class="bg-white">
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<?php
if (isset($_POST['BTEnvia'])){
//REMETENTE --> ESTE EMAIL TEM QUE SER VALIDO DO DOMINIO
//====================================================
$email_remetente = "<EMAIL>"; // deve ser um email do dominio
//====================================================
//Configurações do email, ajustar conforme necessidade
//====================================================
$email_destinatario = "<EMAIL>"; // qualquer email pode receber os dados
$email_reply = "$email";
$email_assunto = "Contato do Site - Via Formulário.";
//====================================================
//Variaveis de POST, Alterar somente se necessário
//====================================================
$nome = $_POST['nome'];
$email = $_POST['email'];
$telefone = $_POST['telefone'];
$ramo = $_POST['ramo'];
$primeiro_a = $_POST['primeiro_a'];
$primeiro_b = $_POST['primeiro_b'];
$primeiro_c = $_POST['primeiro_c'];
$primeiro_d = $_POST['primeiro_d'];
$primeiro_e = $_POST['primeiro_e'];
$primeiro_f = $_POST['primeiro_f'];
$primeiro_g = $_POST['primeiro_g'];
$primeiro_h = $_POST['primeiro_h'];
$segundo_a = $_POST['segundo_a'];
$segundo_b = $_POST['segundo_b'];
$segundo_c = $_POST['segundo_c'];
$segundo_d = $_POST['segundo_d'];
$segundo_e = $_POST['segundo_e'];
$terceiro_a = $_POST['terceiro_a'];
$terceiro_b = $_POST['terceiro_b'];
$terceiro_c = $_POST['terceiro_c'];
$terceiro_d = $_POST['terceiro_d'];
$terceiro_e = $_POST['terceiro_e'];
$quarto_a = $_POST['quarto_a'];
$quarto_b = $_POST['quarto_b'];
$quarto_c = $_POST['quarto_c'];
$quarto_d = $_POST['quarto_d'];
$quinto_a = $_POST['quinto_a'];
$quinto_b = $_POST['quinto_a'];
$quinto_c = $_POST['quinto_a'];
$quinto_d = $_POST['quinto_a'];
$quinto_e = $_POST['quinto_a'];
$quinto_f = $_POST['quinto_a'];
$quinto_g = $_POST['quinto_a'];
$quinto_h = $_POST['quinto_a'];
$cores = $_POST['cores'];
$sexto_a = $_POST['sexto_a'];
$sexto_b = $_POST['sexto_b'];
$sexto_c = $_POST['sexto_c'];
$sexto_d = $_POST['sexto_d'];
$sexto_e = $_POST['sexto_e'];
$sexto_f = $_POST['sexto_f'];
//====================================================
//Monta o Corpo da Mensagem
//====================================================
$email_conteudo = "Nome = $nome \n";
$email_conteudo .= "Email = $email \n";
$email_conteudo .= "Telefone = $telefone \n";
$email_conteudo .= "Ramo de Atividades = $ramo \n";
$email_conteudo .= "Descreva o negócio/produto/empresa como se fosse uma pessoa. É sério? Jovem? Confiável? ...? Justifique. = $primeiro_a \n";
$email_conteudo .= "Quais são os pontos fortes e fracos do negócio/produto/empresa? Por quê? = $primeiro_b \n";
$email_conteudo .= "Qual a mensagem que melhor descreve o conteúdo/atuação do negócio/produto/empresa? = $primeiro_c \n";
$email_conteudo .= "É necessário obter dados dos visitantes? O quê é preciso saber? Por quê? = $primeiro_d \n";
$email_conteudo .= "O que o site irá oferecer ao seu público-alvo? = $primeiro_e \n";
$email_conteudo .= "O que os visitantes devem fazer no site? = $primeiro_f \n";
$email_conteudo .= "Qual o conhecimento que os visitantes do site tem de internet/web? E o conhecimento técnico? = $primeiro_g \n";
$email_conteudo .= "Qual a -capacidade técnica- de acesso de seus usuários (navegador, velocidade de acesso, tempo de acesso diário, etc)? = $primeiro_h \n";
$email_conteudo .= "Qual publico alvo. = $segundo_a \n";
$email_conteudo .= "Existe um publico alvo secundário ? = $segundo_b \n";
$email_conteudo .= "Qual interesse desse público alvo. = $segundo_c \n";
$email_conteudo .= "Qual a necessidade desse público alvo. = $segundo_d \n";
$email_conteudo .= "Qual a média de idade desse publico alvo. = $segundo_e \n";
$email_conteudo .= "Quais são os principais objetivos do site? Informar? Vender? Dar suporte? ...? = $terceiro_a \n";
$email_conteudo .= "Que tipo de site ele é? Puramente promocional? Coletor de Informações? Uma publicação? Exposição de marca ou produto? = $terceiro_b \n";
$email_conteudo .= "Quais são as mensagens mais importantes que o site deve passar aos visitantes? = $terceiro_c \n";
$email_conteudo .= "Quais são os planos para promover o site? = $terceiro_d \n";
$email_conteudo .= "Quais redes sociais seu negócio/produto/empresa tem hoje ? = $terceiro_e \n";
$email_conteudo .= "Que informação do site mudará? Com que freqüência e com que abrangência? = $quarto_a \n";
$email_conteudo .= "Quem se beneficia com as atualizações? = $quarto_b \n";
$email_conteudo .= "Qual são as seções e funcionalidades que precisam existir? = $quarto_c \n";
$email_conteudo .= "Qual é o -aceite- do site (o que precisa existir para -aceitar- que ele está pronto)? = $quarto_d \n";
$email_conteudo .= "Tem em mente alguma aparência para o web site? = $quinto_a \n";
$email_conteudo .= "Existem padrões existentes, como logotipos e cores, que devem estar presentes? Quais ?
= $quinto_b \n";
$email_conteudo .= "O site parte de um site maior ou grupo de sites com padrões de design que precisam ser correspondidos? Quais ? = $quinto_c \n";
$email_conteudo .= "Cite 03 sites da web que você gosta? = $quinto_d \n";
$email_conteudo .= "Cite o que você gosta dos sites que citou anteriormente. = $quinto_e \n";
$email_conteudo .= "Cite 03 sites da web que você NÃO gosta? = $quinto_f \n";
$email_conteudo .= "Cite o que você NÃO gosta dos sites que citou anteriormente. = $quinto_g \n";
$email_conteudo .= "Qual a -imagem- que você precisa transmitir para o usuário ? = $quinto_h \n";
$email_conteudo .= "Cores quentes ou frias ? = $cores \n";
$email_conteudo .= "Cite dois ou tres concorrentes maiores que você. = $sexto_a \n";
$email_conteudo .= "Cite dois ou tres concorrentes menores que você. = $sexto_b \n";
$email_conteudo .= "Quais são suas vantagens sobre esses concorrentes. = $sexto_c \n";
$email_conteudo .= "Quais são seus desvantagens sob esses concorrentes. = $sexto_d \n";
$email_conteudo .= "O que você precisa mostrar para ganhar vantagem em relação aos concorrentes. = $sexto_e \n";
$email_conteudo .= "O que você não pode mostrar em relação aos concorrente. = $sexto_f \n";
//====================================================
//Seta os Headers (Alerar somente caso necessario)
//====================================================
$email_headers = implode ( "\n",array ( "From: $email_remetente", "Reply-To: $email_reply", "Subject: $email_assunto","Return-Path: $email_remetente","MIME-Version: 1.0","X-Priority: 3","Content-Type: text/html; charset=UTF-8" ) );
//====================================================
//Enviando o email
//====================================================
if (mail ($email_destinatario, $email_assunto, nl2br($email_conteudo), $email_headers)){
echo "<script>alert('Foi enviado com sucesso $nome, em breve lhe responderemos ... Obrigado !');</script>";
}
else{
echo "</b>Falha no envio do E-Mail!</b>";
}
//====================================================
}
?>
<form class="form" action="<? $PHP_SELF; ?>" method="post" >
<h4 class="col-md-12">Informações do Cliente</h4>
<div class="form-group col-md-6">
<label for="nome">Nome:</label>
<input name="nome" placeholder="Nome" type="text" class="form-control" id="nome" required>
</div>
<div class="form-group col-md-6">
<label for="email">E-mail:</label>
<input name="email" placeholder="E-mail" type="email" class="form-control" id="email" required>
</div>
<div class="form-group col-md-6">
<label for="telefone">Telefone:</label>
<input name="telefone" placeholder="Telefone" type="phone" class="form-control" id="telefone" required>
</div>
<div class="form-group col-md-6">
<label for="ramo">Ramo de negócio:</label>
<input name="ramo" placeholder="Ramo de negócio" type="text" class="form-control" id="ramo" required>
</div>
<h4 class="col-md-12">Informações Gerais do Projeto</h4>
<div class="form-group col-md-6">
<label for="primeiro_a">Descreva o negócio/produto/empresa como se fosse uma pessoa. É sério? Jovem? Confiável? ...? Justifique.</label>
<textarea name="primeiro_a" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_a" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_b">Quais são os pontos fortes e fracos do negócio/produto/empresa? Por quê?</label>
<textarea name="primeiro_b" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_b" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_c">Qual a mensagem que melhor descreve o conteúdo/atuação do negócio/produto/empresa?</label>
<textarea name="primeiro_c" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_c" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_d">É necessário obter dados dos visitantes? O quê é preciso saber? Por quê?</label>
<textarea name="primeiro_d" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_d" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_e">O que o site irá oferecer ao seu público-alvo?</label>
<textarea name="primeiro_e" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_e" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_f">O que os visitantes devem fazer no site?</label>
<textarea name="primeiro_f" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_f" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_g">Qual o conhecimento que os visitantes do site tem de internet/web? E o conhecimento técnico?</label>
<textarea name="primeiro_g" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_g" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_h">Qual a "capacidade técnica" de acesso de seus usuários (navegador, velocidade de acesso, tempo de acesso diário, etc)?</label>
<textarea name="primeiro_h" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_h" required></textarea>
</div>
<h4 class="col-md-12">Público Alvo</h4>
<div class="form-group col-md-6">
<label for="segundo_a">Qual publico alvo.</label>
<textarea name="segundo_a" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="segundo_a" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="segundo_b">Existe um publico alvo secundário ?</label>
<textarea name="segundo_b" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="segundo_b" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="segundo_c">Qual interesse desse público alvo.</label>
<textarea name="segundo_c" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="segundo_c" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="segundo_d">Qual a necessidade desse público alvo.</label>
<textarea name="segundo_d" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="segundo_d" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="segundo_e">Qual a média de idade desse publico alvo.</label>
<textarea name="segundo_e" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="segundo_e" required></textarea>
</div>
<h4 class="col-md-12">Estratégia</h4>
<div class="form-group col-md-6">
<label for="terceiro_a">Quais são os principais objetivos do site? Informar? Vender? Dar suporte? ...?</label>
<textarea name="terceiro_a" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="terceiro_a" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="terceiro_b">Que tipo de site ele é? Puramente promocional? Coletor de Informações? Uma publicação? Exposição de marca ou produto?</label>
<textarea name="terceiro_b" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="terceiro_b" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="terceiro_c">Quais são as mensagens mais importantes que o site deve passar aos visitantes?</label>
<textarea name="terceiro_c" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="terceiro_c" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="terceiro_d">Quais são os planos para promover o site?</label>
<textarea name="terceiro_d" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="terceiro_d" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="terceiro_e">Quais redes sociais seu negócio/produto/empresa tem hoje ?</label>
<textarea name="terceiro_e" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="terceiro_e" required></textarea>
</div>
<h4 class="col-md-12">Conteúdo</h4>
<div class="form-group col-md-6">
<label for="quarto_a">Que informação do site mudará? Com que freqüência e com que abrangência?</label>
<textarea name="quarto_a" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quarto_a" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="quarto_b">Quem se beneficia com as atualizações?</label>
<textarea name="quarto_b" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quarto_b" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="quarto_c">Qual são as seções e funcionalidades que precisam existir?</label>
<textarea name="quarto_c" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quarto_c" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="quarto_d">Qual é o "aceite" do site (o que precisa existir para "aceitar" que ele está pronto)?</label>
<textarea name="quarto_d" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quarto_d" required></textarea>
</div>
<h4 class="col-md-12">Aparência (Design)</h4>
<div class="form-group col-md-6">
<label for="quinto_a">Tem em mente alguma aparência para o web site?</label>
<textarea name="quinto_a" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quinto_a" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="quinto_b">Existem padrões existentes, como logotipos e cores, que devem estar presentes? Quais ?</label>
<textarea name="quinto_b" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quinto_b" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="quinto_c">O site parte de um site maior ou grupo de sites com padrões de design que precisam ser correspondidos? Quais ?</label>
<textarea name="quinto_c" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quinto_c" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="quinto_d">Cite 03 sites da web que você gosta?</label>
<textarea name="quinto_d" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quinto_d" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="quinto_e">Cite o que você gosta dos sites que citou anteriormente.</label>
<textarea name="quinto_e" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quinto_e" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="quinto_f">Cite 03 sites da web que você NÃO gosta?</label>
<textarea name="quinto_f" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quinto_f" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="quinto_g">Cite o que você NÃO gosta dos sites que citou anteriormente.</label>
<textarea name="quinto_g" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quinto_g" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="quinto_h">Qual a "imagem" que você precisa transmitir para o usuário ?</label>
<textarea name="quinto_h" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="quinto_h" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="cores">Cores quentes ou frias ?</label>
<div class="aaaa col-md-6"><input name="gender" type="radio" class="form-control-radio" value="1" checked><span>Quentes</span></div>
<div class="aaaa col-md-6"><input name="gender" type="radio" class="form-control-radio" value="3"><span>Frias</span></div>
</div>
<h4 class="col-md-12">Concorrentes</h4>
<div class="form-group col-md-6">
<label for="sexto_a">Cite dois ou tres concorrentes maiores que você.</label>
<textarea name="sexto_a" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="sexto_a" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="sexto_b">Cite dois ou tres concorrentes menores que você.</label>
<textarea name="sexto_b" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="sexto_b" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="sexto_c">Quais são suas vantagens sobre esses concorrentes.</label>
<textarea name="sexto_c" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="sexto_c" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="sexto_d">Quais são seus desvantagens sob esses concorrentes.</label>
<textarea name="sexto_d" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="sexto_d" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="sexto_e">O que você precisa mostrar para ganhar vantagem em relação aos concorrentes.</label>
<textarea name="sexto_e" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="sexto_e" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="sexto_f">O que você não pode mostrar em relação aos concorrente.</label>
<textarea name="sexto_f" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="sexto_f" required></textarea>
</div>
<input class="col-md-12 submit-btn btn btn-primary" name="BTEnvia" type="submit" value="Enviar">
</form>
</div>
</div>
</div>
</section>
<footer>
<div class="container">
<div class="row">
<div class="col-md-12 footer-total">
<div class="footer-primeiro">
<h4>Facebook:</h4>
<div class="footer-face">
<div class="fb-page" data-href="https://www.facebook.com/mclsolucoesweb/" data-width="270" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"><blockquote cite="https://www.facebook.com/mclsolucoesweb/" class="fb-xfbml-parse-ignore"><a href="https://www.facebook.com/mclsolucoesweb/">Mcl - Soluções Web</a></blockquote></div>
</div>
</div>
<div class="footer-segundo">
<h4>Mcl - Soluções Web</h4>
<img alt="[Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" class="" src="img/Looogo-footer.png" />
</div>
<div class="footer-terceiro">
<h4>Redes Sociais:</h4>
<a href="https://www.facebook.com/mclsolucoesweb/"><div class="footer-face">
<span>Facebook</span>
</div></a>
<a href="https://twitter.com/MclSolucoesWeb"><div class="footer-twitter">
<span>Twitter</span>
</div></a>
<a href="https://plus.google.com/117280151570052113742"><div class="footer-google">
<span>Google-Plus</span>
</div></a>
</div>
</div>
</div>
<div class="row">
<p>© 2017 Mcl - Soluções Web. Developer by: <NAME>.</p>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="lib/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="lib/bootstrap/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<!-- Theme JavaScript -->
<script src="js/new-age.min.js"></script>
<!-- JAVASCRIPT FACEBOOK FOOTER -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v2.9";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
</body>
</html>
<file_sep>/README.md
# mclweb
Site - Mclweb - Agência de Desenvolvimento Web de <NAME>.
<file_sep>/briefing-loja-virtual.php
<!DOCTYPE html>
<html lang="pt-br" itemscope itemtype="https://schema.org/Article">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Mcl - Soluções Web | Sites Institucionais, Lojas Virtuais, Marketing Digital & Aplicativos Mobile Android e Ios. Solução está na Web, e nós te levamos onde todos estão !">
<meta name="keywords" content="mcl, mclweb, mcl soluções web, marketing, marketing digital, criação de site, sites baratos, e-commerce, loja virtual, aplicativo mobile, aplicativo android, marketing facebook, marketing google, marketing instagram, preciso da um up na minha empresa, solução para empresa, micro empreendedores, aumento de venda, divulgação de marca, gabriel marcelino, duque de caxias, site responsivo, site para celular, preciso de um site, email corporativo" />
<meta name="author" content="<NAME> | Mcl - Soluções Web">
<meta name="robots" content="index, follow"/>
<meta name="email" content="<EMAIL>">
<link rel="canonical" href="http://mclweb.com.br/">
<meta property="og:type" content="website" />
<meta property="og:title" content="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" />
<meta property="og:description" content="Mcl - Soluções Web | Sites Institucionais, Lojas Virtuais, Marketing Digital & Aplicativos Mobile Android e Ios. Solução está na Web, e nós te levamos onde todos estão !" />
<meta property="og:url" content="http://mclweb.com.br/" />
<meta property="og:site_name" content="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" />
<meta property="og:locale" content="pt-BR" />
<meta property="og:image" content="http://mclweb.com.br/img/Looogo.png" />
<meta property="og:keywords" content="mcl, mclweb, mcl soluções web, marketing, marketing digital, criação de site, sites baratos, e-commerce, loja virtual, aplicativo mobile, aplicativo android, marketing facebook, marketing google, marketing instagram, preciso da um up na minha empresa, solução para empresa, micro empreendedores, aumento de venda, divulgação de marca, gabriel marcelino, duque de caxias, site responsivo, site para celular, preciso de um site, email corporativo" />
<meta property="og:email" content="<EMAIL>" />
<meta property="og:publisher" content="https://www.facebook.com/mclsolucoesweb/" />
<title>Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital</title>
<!-- Bootstrap Core CSS -->
<link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="shortcut icon" href="img/favicon01.png" />
<!-- Custom Fonts -->
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Muli" rel="stylesheet">
<!-- Plugin CSS -->
<link rel="stylesheet" href="lib/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="lib/simple-line-icons/css/simple-line-icons.css">
<link rel="stylesheet" href="lib/device-mockups/device-mockups.min.css">
<!-- Theme CSS -->
<link href="css/new-age2.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<style>
nav{
padding: 0 0 0.5%;
}
</style>
</head>
<body id="page-top">
<!-- GOOGLE ANALYTICS -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-99837565-1', 'auto');
ga('send', 'pageview');
</script>
<h1 style="display: none!important;">Mcl - Soluções Web | Desenvolvimento Web e Marketing Digital</h1>
<nav id="mainNav" class="navbar navbar-default navbar-fixed-top bg-white">
<h2 style="display: none!important;">Mcl - Soluções Web | Menu</h2>
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
</button>
<a class="navbar-brand page-scroll" href="index.php"><img class="logo" alt="[Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital | Logo]" title="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital | Logo" src="img/Mcl-Solucoes-Web-Logo.png" /></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a class="page-scroll" href="#serviços">Serviços</a>
</li>
<li>
<a class="page-scroll" href="#diferenciais">Diferenciais</a>
</li>
<li>
<a class="page-scroll" href="#pessoal">Pessoal</a>
</li>
<li>
<a class="page-scroll" href="#portfolio">Portfólio</a>
</li>
<li>
<a class="page-scroll" href="#tramite">Tramite</a>
</li>
<li>
<a class="page-scroll" href="#contato">Contato</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<header class="header">
</header>
<section class="bg-primary form-briefing">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 class="text-center">Briefing Loja Virtual</h1>
<p>Um briefing bem feito e executado pode determinar se um site será bom ou ruim<br> (baseado nas necessidades e expectativas do cliente).</p>
<h3 class="text-center">... Ou seja, não economize nas informações ;-)</h3>
</div>
</div>
</div>
</section>
<!-- 1-4 2-8 3-5 4-5 5-4 6-9 7-6-->
<section class="bg-white">
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<?php
if (isset($_POST['BTEnvia'])){
//REMETENTE --> ESTE EMAIL TEM QUE SER VALIDO DO DOMINIO
//====================================================
$email_remetente = "<EMAIL>"; // deve ser um email do dominio
//====================================================
//Configurações do email, ajustar conforme necessidade
//====================================================
$email_destinatario = "<EMAIL>"; // qualquer email pode receber os dados
$email_reply = "$email";
$email_assunto = "Briefing - Loja Virtual.";
//====================================================
//Variaveis de POST, Alterar somente se necessário
//====================================================
$nome = $_POST['nome'];
$email = $_POST['email'];
$telefone = $_POST['telefone'];
$ramo = $_POST['ramo'];
$primeiro_a = $_POST['primeiro_a'];
$primeiro_b = $_POST['primeiro_b'];
$primeiro_c = $_POST['primeiro_c'];
$primeiro_d = $_POST['primeiro_d'];
$primeiro_e = $_POST['primeiro_e'];
$primeiro_f = $_POST['primeiro_f'];
$primeiro_g = $_POST['primeiro_g'];
$primeiro_h = $_POST['primeiro_h'];
//====================================================
//Monta o Corpo da Mensagem
//====================================================
$email_conteudo = "Nome = $nome \n";
$email_conteudo .= "Email = $email \n";
$email_conteudo .= "Telefone = $telefone \n";
$email_conteudo .= "Ramo de Atividades = $ramo \n";
$email_conteudo .= "O que a Loja Virtual irá vender ? = $primeiro_a \n";
$email_conteudo .= "Quantas categorias de produtos são ? = $primeiro_b \n";
$email_conteudo .= "Existe subcategorias ? quantas ? = $primeiro_c \n";
$email_conteudo .= "Existe algum site em que queira se espelhar ? Qual ? = $primeiro_d \n";
$email_conteudo .= "Mais ou menos, quantos produtos são ? = $primeiro_e \n";
$email_conteudo .= "Além dos produtos, o que mais terá de ter no site ? = $primeiro_f \n";
$email_conteudo .= "Além dos produtos, algo no site sofrerá atualizações ? O quê ? de quanto em quanto tempo ? = $primeiro_g \n";
$email_conteudo .= "Espaço livre para inserir qualquer informação a mais ... = $primeiro_h \n";
//====================================================
//Seta os Headers (Alerar somente caso necessario)
//====================================================
$email_headers = implode ( "\n",array ( "From: $email_remetente", "Reply-To: $email_reply", "Subject: $email_assunto","Return-Path: $email_remetente","MIME-Version: 1.0","X-Priority: 3","Content-Type: text/html; charset=UTF-8" ) );
//====================================================
//Enviando o email
//====================================================
if (mail ($email_destinatario, $email_assunto, nl2br($email_conteudo), $email_headers)){
echo "<script>alert('Foi enviado com sucesso $nome, em breve lhe responderemos ... Obrigado !');</script>";
}
else{
echo "</b>Falha no envio do E-Mail!</b>";
}
//====================================================
}
?>
<form class="form" action="<? $PHP_SELF; ?>" method="post" >
<h4 class="col-md-12">Informações do Cliente</h4>
<div class="form-group col-md-6">
<label for="nome">Nome:</label>
<input name="nome" placeholder="Nome" type="text" class="form-control" id="nome" required>
</div>
<div class="form-group col-md-6">
<label for="email">E-mail:</label>
<input name="email" placeholder="E-mail" type="email" class="form-control" id="email" required>
</div>
<div class="form-group col-md-6">
<label for="telefone">Telefone:</label>
<input name="telefone" placeholder="Telefone" type="phone" class="form-control" id="telefone" required>
</div>
<div class="form-group col-md-6">
<label for="ramo">Ramo de negócio:</label>
<input name="ramo" placeholder="Ramo de negócio" type="text" class="form-control" id="ramo" required>
</div>
<h4 class="col-md-12">Informações Gerais do Projeto</h4>
<div class="form-group col-md-6">
<label for="primeiro_a">O que a Loja Virtual irá vender ?</label>
<textarea name="primeiro_a" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_a" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_b">Quantas categorias de produtos são ?</label>
<textarea name="primeiro_b" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_b" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_c">Existe subcategorias ? quantas ?</label>
<textarea name="primeiro_c" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_c" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_d">Existe algum site em que queira se espelhar ? Qual ?</label>
<textarea name="primeiro_d" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_d" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_e">Mais ou menos, quantos produtos são ?</label>
<textarea name="primeiro_e" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_e" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_f">Além dos produtos, o que mais terá de ter no site ?</label>
<textarea name="primeiro_f" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_f" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_g">Além dos produtos, algo no site sofrerá atualizações ? O quê ? de quanto em quanto tempo ?</label>
<textarea name="primeiro_g" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_g" required></textarea>
</div>
<div class="form-group col-md-6">
<label for="primeiro_h">Espaço livre para inserir qualquer informação a mais ...</label>
<textarea name="primeiro_h" rows="4" placeholder="Digite aqui ..." type="text" class="form-control" id="primeiro_h"></textarea>
</div>
<input class="col-md-12 submit-btn btn btn-primary" name="BTEnvia" type="submit" value="Enviar">
</form>
</div>
</div>
</div>
</section>
<footer>
<div class="container">
<div class="row">
<div class="col-md-12 footer-total">
<div class="footer-primeiro">
<h4>Facebook:</h4>
<div class="footer-face">
<div class="fb-page" data-href="https://www.facebook.com/mclsolucoesweb/" data-width="270" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"><blockquote cite="https://www.facebook.com/mclsolucoesweb/" class="fb-xfbml-parse-ignore"><a href="https://www.facebook.com/mclsolucoesweb/">Mcl - Soluções Web</a></blockquote></div>
</div>
</div>
<div class="footer-segundo">
<h4>Mcl - Soluções Web</h4>
<img alt="[Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" class="" src="img/Looogo-footer.png" />
</div>
<div class="footer-terceiro">
<h4>Redes Sociais:</h4>
<a href="https://www.facebook.com/mclsolucoesweb/"><div class="footer-face">
<span>Facebook</span>
</div></a>
<a href="https://twitter.com/MclSolucoesWeb"><div class="footer-twitter">
<span>Twitter</span>
</div></a>
<a href="https://plus.google.com/117280151570052113742"><div class="footer-google">
<span>Google-Plus</span>
</div></a>
</div>
</div>
</div>
<div class="row">
<p>© 2017 Mcl - Soluções Web. Developer by: <NAME>.</p>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="lib/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="lib/bootstrap/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<!-- Theme JavaScript -->
<script src="js/new-age.min.js"></script>
<!-- JAVASCRIPT FACEBOOK FOOTER -->
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v2.9";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
</body>
</html><file_sep>/index.php
<!DOCTYPE html>
<html lang="pt-br" itemscope itemtype="https://schema.org/Article">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Mcl - Soluções Web | Sites Institucionais, Lojas Virtuais, Marketing Digital & Aplicativos Mobile Android e Ios. Solução está na Web, e nós te levamos onde todos estão !">
<meta name="keywords" content="mcl, mclweb, mcl soluções web, marketing, marketing digital, criação de site, sites baratos, e-commerce, loja virtual, aplicativo mobile, aplicativo android, marketing facebook, marketing google, marketing instagram, preciso da um up na minha empresa, solução para empresa, micro empreendedores, aumento de venda, divulgação de marca, gabriel marcelino, duque de caxias, site responsivo, site para celular, preciso de um site, email corporativo" />
<meta name="author" content="<NAME> | Mcl - Soluções Web">
<meta name="robots" content="index, follow" />
<meta name="email" content="<EMAIL>">
<link rel="canonical" href="http://mclweb.com.br/">
<meta property="og:type" content="website" />
<meta property="og:title" content="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" />
<meta property="og:description" content="Mcl - Soluções Web | Sites Institucionais, Lojas Virtuais, Marketing Digital & Aplicativos Mobile Android e Ios. Solução está na Web, e nós te levamos onde todos estão !" />
<meta property="og:url" content="http://mclweb.com.br/" />
<meta property="og:site_name" content="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" />
<meta property="og:locale" content="pt-BR" />
<meta property="og:image" content="http://mclweb.com.br/img/Looogo.png" />
<meta property="og:keywords" content="mcl, mclweb, mcl soluções web, marketing, marketing digital, criação de site, sites baratos, e-commerce, loja virtual, aplicativo mobile, aplicativo android, marketing facebook, marketing google, marketing instagram, preciso da um up na minha empresa, solução para empresa, micro empreendedores, aumento de venda, divulgação de marca, <NAME>, duque de caxias, site responsivo, site para celular, preciso de um site, email corporativo" />
<meta property="og:email" content="<EMAIL>" />
<meta property="og:publisher" content="https://www.facebook.com/mclsolucoesweb/" />
<title>Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital</title>
<!-- Bootstrap Core CSS -->
<link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="shortcut icon" href="img/favicon01.png" />
<!-- Custom Fonts -->
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Muli" rel="stylesheet">
<!-- Plugin CSS -->
<link rel="stylesheet" href="lib/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="lib/simple-line-icons/css/simple-line-icons.css">
<link rel="stylesheet" href="lib/device-mockups/device-mockups.min.css">
<!-- Theme CSS -->
<link href="css/new-age.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top">
<!-- GOOGLE ANALYTICS -->
<script>
(function(i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function() {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-99837565-1', 'auto');
ga('send', 'pageview');
</script>
<h1 style="display: none!important;">Mcl - Soluções Web | Desenvolvimento Web e Marketing Digital</h1>
<nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
<h2 style="display: none!important;">Mcl - Soluções Web | Menu</h2>
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
</button>
<a class="navbar-brand page-scroll" href="#page-top"><img class="logo" alt="[Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital | Logo]" title="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital | Logo" src="img/Mcl-Solucoes-Web-Logo.png" /></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a class="page-scroll" href="#serviços">Serviços</a>
</li>
<li>
<a class="page-scroll" href="#diferenciais">Diferenciais</a>
</li>
<li>
<a class="page-scroll" href="#pessoal">Pessoal</a>
</li>
<li>
<a class="page-scroll" href="#portfolio">Portfólio</a>
</li>
<li>
<a class="page-scroll" href="#tramite">Tramite</a>
</li>
<li>
<a class="page-scroll" href="#contato">Contato</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<header class="header">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="intro-text">
<div class="intro-heading">Mcl - Soluções Web</div>
<div class="intro-lead-in">Desenvolvimento Web e Marketing Digital</div>
<a href="#serviços" class="page-scroll btn btn-xl btn-primary">Saiba Mais</a>
</div>
</div>
</div>
</div>
</header>
<section id="serviços" class="download text-center">
<div class="container">
<div class="row">
<div class="section-heading">
<h2>Serviços</h2>
<p>Confira alguns dos serviços da Mcl- Soluções web</p>
<hr>
<br>
</div>
<div class="content-section-a">
<div class="container">
<div class="row">
<div class="col-lg-5 col-sm-6">
<hr class="section-heading-spacer">
<hr class="section-heading-spacer">
<div class="clearfix"></div>
<h3 class="section-heading1">E-Commerce <br>(Loja Virtual)</h3>
<p class="lead">Dê ao seu cliente o conforto de comprar também pela internet, você não vai ficar de fora do mercado que mais cresce no mundo não é ?!</p>
</div>
<div class="col-lg-5 col-lg-offset-2 col-sm-6">
<img class="img-responsive" src="img/loja-virtual.png" alt="[Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital - E-commerce, Loja Virtual]" title="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital - E-commerce, Loja Virtual">
</div>
</div>
</div>
<!-- /.container -->
</div>
<!-- /.content-section-a -->
<div class="content-section-b">
<div class="container">
<div class="row">
<div class="col-lg-5 col-lg-offset-1 col-sm-push-6 col-sm-6">
<hr class="section-heading-spacer">
<hr class="section-heading-spacer">
<div class="clearfix"></div>
<h3 class="section-heading2">Marketing Digital</h3>
<p class="lead">Já pensou na possibilidade de ter alguém precisando do seu PRODUTO ou SERVIÇO mas não tem oportunidade de chegar até seu estabelecimento ? Não perca mais tempo, nós te levamos até eles.</p>
</div>
<div class="col-lg-5 col-sm-pull-6 col-sm-6">
<img class="img-responsive" src="img/marketing-digital.png" alt="[Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital - Marketing Digital]" title="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital - Marketing Digital">
</div>
</div>
</div>
<!-- /.container -->
</div>
<!-- /.content-section-b -->
<div class="content-section-a">
<div class="container">
<div class="row">
<div class="col-lg-5 col-sm-6">
<hr class="section-heading-spacer">
<hr class="section-heading-spacer">
<div class="clearfix"></div>
<h3 class="section-heading1">Aplicativos Mobile</h3>
<p class="lead">Esteja a um clique do seu cliente, com Aplicativos Mobile Android/Ios você pode se comunicar por notificações diretamente no celular dos seus clientes.</p>
</div>
<div class="col-lg-5 col-lg-offset-2 col-sm-6">
<img class="img-responsive" src="img/app-mobile.png" alt="[Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital - Aplicativo Mobile]" title="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital - Aplicativo Mobile">
</div>
</div>
</div>
<!-- /.container -->
</div>
</div>
</div>
</section>
<section id="diferenciais" class="features">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<div class="section-heading">
<h2>Diferenciais</h2>
<p>Confira alguns dos Diferenciais da Mcl - Soluções Web</p>
<hr>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="container-fluid">
<div class="row">
<div class="diferenciais-item col-md-3">
<div class="feature-item">
<i class="fa fa-at" aria-hidden="true"></i>
<h3>E-mail Corporativo</h3>
<p class="text-muted">Garanta credibilidade ao se comunicar com seus clientes por emails corporativos.</p>
</div>
</div>
<div class="col-md-3">
<div class="feature-item">
<i class="fa fa-google" aria-hidden="true"></i>
<h3>Top Google</h3>
<p class="text-muted">Temos planos de Marketing Digital que dependendo da palavra você fica no topo.</p>
</div>
</div>
<div class="col-md-3">
<div class="feature-item">
<i class="icon-screen-smartphone text-primary"></i>
<h3>Layout Responsivo</h3>
<p class="text-muted">Todos os Sites Institucionais ou Lojas Virtuais são 100% responsivos.</p>
</div>
</div>
<div class="col-md-3">
<div class="feature-item">
<i class="fa fa-bullhorn" aria-hidden="true"></i>
<h3>Divulgações</h3>
<p class="text-muted">Fazemos toda parte de divulgação de seus eventos, seja qual for.</p>
</div>
</div>
<div class="col-md-3">
<div class="feature-item">
<i class="fa fa-share-alt" aria-hidden="true"></i>
<h3>Redes Sociais</h3>
<p class="text-muted">Integramos seu Site Institucional ou Loja Virtual à suas Redes Sociais.</p>
</div>
</div>
<div class="col-md-3">
<div class="feature-item">
<i class="fa fa-facebook" aria-hidden="true"></i>
<i class="fa fa-instagram" aria-hidden="true"></i>
<h3>Face/Insta Ads</h3>
<p class="text-muted">Expanda sua marca e aumente seus fãs promovendo campanhas.</p>
</div>
</div>
<div class="col-md-3">
<div class="feature-item">
<i class="fa fa-paint-brush" aria-hidden="true"></i>
<h3>Web Design</h3>
<p class="text-muted">Caso esteja começando, temos uma equipe de Web Design à disposição.</p>
</div>
</div>
<div class="col-md-3">
<div class="feature-item">
<i class="fa fa-code" aria-hidden="true"></i>
<h3>Linguagem Atual</h3>
<p class="text-muted">Utilizamos as mais atuais linguagens de programação do mercado.</p>
</div>
</div>
<div class="col-md-3">
<div class="feature-item">
<i class="fa fa-android" aria-hidden="true"></i>
<h3>App Mobile</h3>
<p class="text-muted">Criamos App Mobile Andriod/Ios de acordo com suas necessidades.</p>
</div>
</div>
<div class="col-md-3">
<div class="feature-item">
<i class="fa fa-lock" aria-hidden="true"></i>
<h3>SSL</h3>
<p class="text-muted">Sites Intitucionais e Lojas Virtuais seguras com certificado SSL.</p>
</div>
</div>
<div class="col-md-3">
<div class="feature-item">
<i class="fa fa-rss" aria-hidden="true"></i>
<h3>Blogs</h3>
<p class="text-muted">Criamos Blogs com Layout apropriado para o segmento e integrado a Redes Sociais.</p>
</div>
</div>
<div class="col-md-3">
<div class="feature-item">
<i class="fa fa-wrench" aria-hidden="true"></i>
<h3>Suporte</h3>
<p class="text-muted">Planos com suporte 24/7, sendo acionados por diferentes meios.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="pessoal" class="pessoal">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<div class="section-heading">
<h2>Pessoal</h2>
<p>Confira um pouco de <mark><NAME></mark>, Fundador da Mcl - Soluções Web</p>
<hr>
<h3 style="display: none!important;">Mcl - Soluções Web | Certificado por Ex-funcionários da Google</h3>
<h3 style="display: none!important;">Mcl - Soluções Web | Certificado de Google Adwords</h3>
<h3 style="display: none!important;">Mcl - Soluções Web | Certificado pela única parceira do Facebook Brasil</h3>
<h3 style="display: none!important;">Mcl - Soluções Web | Certificado da carreira SEO Expert</h3>
</div>
</div>
</div>
</div>
</section>
<section class="cta">
<div class="container">
<div class="row">
<div class="col-md-12 pessoal-item">
<div class="pessoal-item-foto">
<img src="img/Gabriel-Marcelino_Mcl.png" alt="[<NAME> | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="<NAME> | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" />
</div>
<div class="pessoal-item-desc">
<h3 style="display: none!important;"><NAME> | Mcl - Soluções Web |Certificações</h3>
<ul>
<li><span style="margin: 10px 0; float: left; display: inline-block; width: 10%;"><i class="fa fa-graduation-cap" aria-hidden="true"></i></span><span class="pessoal-item-li-text"> Certificado por Ex-funcionários da <span style="color: #dda31f;">Google</span></span><img class="pessoal-item-li-img" src="img/selo_de_qualidade.png" alt="[Selo de Qualidade | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="Selo de Qualidade | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" /></li>
<li><span style="margin: 10px 0; float: left; display: inline-block; width: 10%;"><i class="fa fa-graduation-cap" aria-hidden="true"></i></span><span class="pessoal-item-li-text"> Certificado
de <span style="color: #dda31f;">Google Adwords</span></span><img class="pessoal-item-li-img" src="img/selo_de_qualidade.png" alt="[Selo de Qualidade | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="Selo de Qualidade | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" /></li>
<li><span style="margin: 10px 0; float: left; display: inline-block; width: 10%;"><i class="fa fa-graduation-cap" aria-hidden="true"></i></span><span class="pessoal-item-li-text"> Certificado pela única parceira do <span style="color: #dda31f;">Facebook Brasil</span></span><img class="pessoal-item-li-img" src="img/selo_de_qualidade.png" alt="[Selo de Qualidade | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="Selo de Qualidade | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" /></li>
<li><span style="margin: 10px 0; float: left; display: inline-block; width: 10%;"><i class="fa fa-graduation-cap" aria-hidden="true"></i></span><span class="pessoal-item-li-text"> Certificado
da carreira <span style="color: #dda31f;">SEO Expert</span></span><img class="pessoal-item-li-img" src="img/selo_de_qualidade.png" alt="[Selo de Qualidade | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="Selo de Qualidade | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" /></li>
</ul>
</div>
</div>
</div>
</div>
<div class="overlay"></div>
</section>
<section id="portfolio">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<div class="section-heading">
<h2>Portfólio</h2>
<p>Confira alguns dos Portfólios da Mcl - Soluções Web</p>
<hr>
<br>
<br>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<article class="portfolio-item port-borda">
<img title="Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" alt="[Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" src="img/assadores-urbanos.jpg" />
<div class="retina retina01">
<h4>Assadores<br>Urbanos</h4>
<p>Site Institucional de Empresa de Venda de Cortes Nobres de Carne para Churrasco.</p>
<a target="_blank" href="http://assadoresurbanos.com.br/">Visite</a>
</div>
</article>
<article class="portfolio-item borda">
<img title="Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" alt="[Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" src="img/Congelados Light Sabor.jpg" />
<div class="retina retina01">
<h4>Congelados<br>Light Sabor</h4>
<p>E-commerce de comida light congelada.</p>
<a target="_blank" href="https://congeladoslightsabor.com.br/">Visite</a>
</div>
</article>
<article class="portfolio-item borda">
<img title="Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" alt="[Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" src="img/box35_logo.jpg" />
<div class="retina retina01">
<h4>Box35</h4>
<p>E-commerce de Sexshop</p>
<a target="_blank" href="http://box35.com.br/">Visite</a>
</div>
</article>
<article class="portfolio-item port-borda">
<img title="Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" alt="[Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" src="img/Logo_Excelencia-Publicidade.jpg" />
<div class="retina retina01">
<h4>Excelência<br>Publicidade</h4>
<p>Site Institucional de Empresa de Publicidade.</p>
<a target="_blank" href="http://excelenciapublicidade.com.br/">Visite</a>
</div>
</article>
<article class="portfolio-item borda">
<img title="Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" alt="[Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" src="img/Viabiliza%20-%20Gest%C3%A3o%20Tribut%C3%A1ria.png" />
<div class="retina retina01">
<h4> Viabiliza<br>Gestão Tributária </h4>
<p>Site Institucional de Gestão Tributária.</p>
<a target="_blank" href="http://viabiliza.net/">Vsite</a>
</div>
</article>
<article class="portfolio-item port-borda">
<img title="Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" alt="[Portfólio | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" src="img/Logo-Silgon.jpg" />
<div class="retina retina01">
<h4>Silgon<br>Construções</h4>
<p>Site Institucional de empresa de Construção Civil.</p>
<a target="_blank" href="http://silgonconstrucoes.com.br/">Visite</a>
</div>
</article>
</div>
</div>
</div>
</section>
<section id="contact" class="contact">
<div class="container">
<h3 style="display: none!important;">Mcl - Soluções Web | Desenvolvimento & Marketing Digital</h3>
<img alt="[Mcl - Soluções Web | Desenvolvimento & Marketing Digital]" title="Mcl - Soluções Web | Desenvolvimento & Marketing Digital" class="dobra-logo" src="img/Looogo.png" />
</div>
</section>
<section id="tramite">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<div class="section-heading">
<h2>Tramite</h2>
<p>Confira o Tramite de negociação da Mcl - Soluções Web</p>
<hr>
<br>
<br>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<ul class="timeline">
<li>
<div class="timeline-image">
<img class="img-circle img-responsive" src="img/contato-mclweb.jpg" alt="[Contato | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="Contato | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital">
</div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="subheading">Contato</h4>
</div>
<div class="timeline-body">
<p class="text-muted">Primeiro vocês fazem contato conosco pelas informações na parte de contatos, ou deixa uma mensagem para que possamos entrar em contato.</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-image">
<img class="img-circle img-responsive" src="img/cafezinho.jpg" alt="[Cafézinho | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="Cafézinho | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital">
</div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="subheading">Cafézinho</h4>
</div>
<div class="timeline-body">
<p class="text-muted">Após o primeiro contato é marcado um cafézinho ou uma reunião virtual para captação de mais informações do projeto.</p>
</div>
</div>
</li>
<li>
<div class="timeline-image">
<img class="img-circle img-responsive" src="img/orçamento.jpg" alt="[Orçamento | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="Orçamento | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital">
</div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="subheading">Orçamento</h4>
</div>
<div class="timeline-body">
<p class="text-muted">Após a captação de informações sobre o projeto, é feito e enviado um orçamento.</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-image">
<img class="img-circle img-responsive" src="img/acordo.jpg" alt="[Contrato | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="Contrato | Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital">
</div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="subheading">Contrato</h4>
</div>
<div class="timeline-body">
<p class="text-muted">Se aceito o orçamento, é preparado um contrato contendo prazos, serviços e valores, assim que o mesmo é assinado ...</p>
</div>
</div>
</li>
<li class="timeline-inverted">
<div class="timeline-image">
<h4>Início
<br>do
<br>projeto !</h4>
</div>
</li>
</ul>
</div>
</div>
</div>
</section>
<section id="contato" class="contato">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<div class="section-heading">
<h2>Contato</h2>
<p>Saiba como entrar em contato com a Mcl - Soluções Web</p>
<hr>
<br>
<br>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 contatos-total">
<div class="col-md-4 info-contatos">
<h3>Informações de Contato:</h3>
<br>
<ul>
<li><i class="fa fa-map-marker"></i> <b> Local:</b> Rio de Janeiro, Brasil.</li><br>
<li><i class="fa fa-calendar"></i> <b> Atendimento:</b> Horário Comercial.</li><br>
<li><i class="fa fa-envelope"></i> <b> E-mail:</b> <EMAIL></li><br>
<li><i style="color: #0F0;" class="fa fa-whatsapp"></i> <b> WhatsApp:</b> (21) 99130-8429</li>
</ul>
</div>
<div class="col-md-8 deixe-mensagem">
<h3>Deixe sua Mensagem:</h3>
<?php
if (isset($_POST['BTEnvia'])){
//REMETENTE --> ESTE EMAIL TEM QUE SER VALIDO DO DOMINIO
//====================================================
$email_remetente = "<EMAIL>"; // deve ser um email do dominio
//====================================================
//Configurações do email, ajustar conforme necessidade
//====================================================
$email_destinatario = "<EMAIL>"; // qualquer email pode receber os dados
$email_reply = "$email";
$email_assunto = "Contato do Site - Via Formulário.";
//====================================================
//Variaveis de POST, Alterar somente se necessário
//====================================================
$nome = $_POST['nome'];
$email = $_POST['email'];
$telefone = $_POST['telefone'];
$mensagem = $_POST['mensagem'];
//====================================================
//Monta o Corpo da Mensagem
//====================================================
$email_conteudo = "Nome = $nome \n";
$email_conteudo .= "Email = $email \n";
$email_conteudo .= "Telefone = $telefone \n";
$email_conteudo .= "Mensagem = $mensagem \n";
//====================================================
//Seta os Headers (Alerar somente caso necessario)
//====================================================
$email_headers = implode ( "\n",array ( "From: $email_remetente", "Reply-To: $email_reply", "Subject: $email_assunto","Return-Path: $email_remetente","MIME-Version: 1.0","X-Priority: 3","Content-Type: text/html; charset=UTF-8" ) );
//====================================================
//Enviando o email
//====================================================
if (mail ($email_destinatario, $email_assunto, nl2br($email_conteudo), $email_headers)){
echo "<script>alert('Foi enviado com sucesso $nome, em breve lhe responderemos ... Obrigado !');</script>";
}
else{
echo "</b>Falha no envio do E-Mail!</b>";
}
//====================================================
}
?>
<form class="form" action="<? $PHP_SELF; ?>" method="post">
<div class="form-group">
<label for="nome">Nome:</label>
<input name="nome" placeholder="Nome" type="text" class="form-control" id="nome" required>
</div>
<div class="form-group">
<label for="email">E-mail:</label>
<input name="email" placeholder="E-mail" type="email" class="form-control" id="email" required>
</div>
<div class="form-group">
<label for="telefone">Telefone:</label>
<input name="telefone" placeholder="Telefone" type="telefone" class="form-control" id="telefone" required>
</div>
<div class="form-group">
<label for="mensagem">Mensagem:</label>
<textarea name="mensagem" placeholder="Mensagem" type="text" class="form-control" id="mensagem" required></textarea>
</div>
<input class="submit-btn btn" name="BTEnvia" type="submit" value="Enviar">
</form>
</div>
</div>
</div>
</div>
</section>
<footer>
<div class="container">
<div class="row">
<div class="col-md-12 footer-total">
<div class="footer-primeiro">
<h4>Facebook:</h4>
<div class="footer-face">
<div class="fb-page" data-href="https://www.facebook.com/mclsolucoesweb/" data-width="270" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true">
<blockquote cite="https://www.facebook.com/mclsolucoesweb/" class="fb-xfbml-parse-ignore"><a href="https://www.facebook.com/mclsolucoesweb/">Mcl - Soluções Web</a></blockquote>
</div>
</div>
</div>
<div class="footer-segundo">
<h4>Mcl - Soluções Web</h4>
<img alt="[Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital]" title="Mcl -Soluções Web | Desenvolvimento Web & Marketing Digital" class="" src="img/Looogo-footer.png" />
</div>
<div class="footer-terceiro">
<h4>Redes Sociais:</h4>
<a href="https://www.facebook.com/mclsolucoesweb/">
<div class="footer-face">
<span>Facebook</span>
</div>
</a>
<a href="https://twitter.com/MclSolucoesWeb">
<div class="footer-twitter">
<span>Twitter</span>
</div>
</a>
<a href="https://plus.google.com/117280151570052113742">
<div class="footer-google">
<span>Google-Plus</span>
</div>
</a>
</div>
</div>
</div>
<div class="row">
<p>© 2017 Mcl - Soluções Web. Developer by: <NAME>.</p>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="lib/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="lib/bootstrap/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<!-- Theme JavaScript -->
<script src="js/new-age.min.js"></script>
<!-- JAVASCRIPT FACEBOOK FOOTER -->
<div id="fb-root"></div>
<script>
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/pt_BR/sdk.js#xfbml=1&version=v2.9";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API = Tawk_API || {},
Tawk_LoadStart = new Date();
(function() {
var s1 = document.createElement("script"),
s0 = document.getElementsByTagName("script")[0];
s1.async = true;
s1.src = 'https://embed.tawk.to/5d08ec7e53d10a56bd7aa81e/default';
s1.charset = 'UTF-8';
s1.setAttribute('crossorigin', '*');
s0.parentNode.insertBefore(s1, s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
|
f93ecba39e98e98c81e40c1cae82d1ddf43c8f68
|
[
"Markdown",
"PHP"
] | 4
|
PHP
|
GabrielMarcelino/mclweb
|
cab8b1282471da6ea5e3ba8c2828ab3658bc6e23
|
108a44f6ddf7ad0e025d7dc69f1a3193207a47ff
|
refs/heads/master
|
<file_sep>import random
from twython import Twython
import time
import pickle
george_lines = pickle.load(open( 'C:/Users/ben/Desktop/seinfeld/george.pickle', 'rb'))
george_filter = [line.strip() for line in george_lines if 20 < len(line) <= 140]
auth_dic = pickle.load(open('C:/Users/ben/Desktop/seinfeld/auth.pickle', 'rb'))
gbot = Twython(auth_dic['APP_KEY']
, auth_dic['APP_SECRET']
, auth_dic['OAUTH_TOKEN']
, auth_dic['OAUTH_TOKEN_SECRET'])
random_line = random.choice(george_filter)
gbot.update_status(status=random_line)
|
f58249df1229b146043a15b6457978306b5e93c2
|
[
"Python"
] | 1
|
Python
|
goodtimeslim/seinfeld_analysis
|
a6fcf777e4106873e2dc80887e033da35e02e73c
|
494d7970b3ee714e1b8aeeffa402da6887f6c714
|
refs/heads/master
|
<file_sep>/*
* Author: <NAME>
* Implement 2d kd tree for quick near neighbor search in RRT and submaps.
*
* TODO: Add rebalance method and make the clss more unisersal
*/
#ifndef kd_tree_h
#define kd_tree_h
#include <vector>
#include "geometry_msgs/Point.h"
namespace cartographer_ros {
namespace cartographer_ros_path_planner{
struct KdTreeNode{
geometry_msgs::Point point;
KdTreeNode* parent_node; // Used for plan planning
double distance; // Used for plan planning
KdTreeNode* left_node; // Used for kd tree
KdTreeNode* right_node; // used for kd tree
int trajectory_id; // used for submaps
int submap_index; // used for submaps
KdTreeNode();
KdTreeNode(geometry_msgs::Point p);
KdTreeNode(geometry_msgs::Point p, int trajectory_idx, int submap_idx);
};
class KdTree{
public:
// Return nearest node to target point
KdTreeNode* NearestKdTreeNode(const geometry_msgs::Point& target) const;
// Return near nodes around target within radius
std::vector<KdTreeNode*> NearKdTreeNode(const geometry_msgs::Point& target,
double radius) const;
// Add a new point into RRT tree
KdTreeNode* AddPointToKdTree(geometry_msgs::Point point);
KdTreeNode* AddPointToKdTree(geometry_msgs::Point point, KdTreeNode* parent, int depth);
KdTreeNode* AddPointToKdTree(geometry_msgs::Point point, int trajectory_idx, int submap_idx);
// Constructor
KdTree();
KdTree(geometry_msgs::Point start_point);
~KdTree(){DestroyRRT(root_);}
// For test
KdTreeNode* BruceNearestKdTreeNode(const geometry_msgs::Point& point);
std::vector<KdTreeNode*> BruceNearKdTreeNode(const geometry_msgs::Point& target, double radius);
private:
// Help function to go through kd tree
void SearchKdTreeNode(const geometry_msgs::Point& target,
KdTreeNode* current_node,
KdTreeNode*& current_nearest_node,
double& current_cloest_distance2,
int depth) const;
void SearchKdTreeNode(const geometry_msgs::Point& target,
KdTreeNode* current_node,
std::vector<KdTreeNode*>& near_nodes,
double radius,
int depth) const;
// Destroy RRT
void DestroyRRT(KdTreeNode* root);
KdTreeNode* const root_;
};
} // namespace cartographer_ros_path_planner
} // namespace cartographer_ros
#endif /* kd_tree_h */
<file_sep>/*
*/
#ifndef PATH_PLANNER_NODE_H
#define PATH_PLANNER_NODE_H
#include <map>
#include <vector>
#include "cartographer/common/mutex.h"
#include "cartographer/common/port.h"
#include "cartographer/mapping/id.h"
#include "cartographer_ros_msgs/SubmapEntry.h"
#include "cartographer_ros_msgs/SubmapList.h"
#include "cartographer_ros_msgs/SubmapQuery.h"
#include "cartographer_ros_msgs/RoadmapQuery.h"
#include "cartographer_ros_msgs/ConnectionQuery.h"
#include "cartographer_ros_msgs/PathPlan.h"
#include "cartographer_ros_msgs/ReconnectSubmaps.h"
#include "geometry_msgs/PointStamped.h"
#include "nav_msgs/Path.h"
#include "ros/ros.h"
#include "ros/serialization.h"
#include "kd_tree.h"
namespace cartographer_ros{
namespace cartographer_ros_path_planner {
using ::cartographer::mapping::SubmapId;
using SubmapIndex = int;
using Path = std::vector<geometry_msgs::Point>;
// Parameters obtained from ROS param server
struct Parameters{
int max_rrt_node_num;
int step_to_check_reach_endpoint;
double distance_threshold_for_adding;
double distance2_threshold_for_updating;
double rotation_threshold_for_updating;
double probability_of_choose_endpoint;
double rrt_grow_step;
double rrt_trim_radius;
double close_submap_radius;
};
// Core Node provide path plan for cartographer
class PathPlannerNode{
public:
PathPlannerNode();
~PathPlannerNode(){};
PathPlannerNode(const PathPlannerNode&) = delete;
PathPlannerNode& operator=(const PathPlannerNode&) = delete;
// Get Parameters from ROS param server
void SetParameters();
// Given a point in global map frame and its correspond submap id,
// return the intensity of the point in submap.
// val: -1 for unobserved or out of submap range
// 0 for definitely free and 100 for definitely occupied.
int GetPointIntensity(const geometry_msgs::Point& point,
const SubmapId& submap_id) const;
// Return whether a point in global map frame is free or not
bool IsFree(const geometry_msgs::Point& point) const;
// Return whether the straight line between two points are free or not
// in given submaps
bool IsPathLocalFree(const geometry_msgs::Point& start_point,
const geometry_msgs::Point& end_point,
const std::vector<SubmapId>& submap_ids) const;
// Return the closest submap to given point
SubmapId ClosestSubmap(const geometry_msgs::Point& point) const;
// Return a list of submaps whose origin is within a circle of radius
// to given point
// TODO: use centre instead of origin
std::vector<SubmapId> CloseSubmaps(const geometry_msgs::Point& point,
double radius) const;
// Return a free path from start point to end point using RRT*
Path PlanPathRRT(const geometry_msgs::Point& start,
const geometry_msgs::Point& end) const;
// Return a free path between two submaps' origin using RRT*
Path PlanPathRRT(const SubmapId& start_id, const SubmapId& end_id) const;
// Returan a path connecting two remote submaps using graph search
Path ConnectSubmap(const SubmapId& start_id, const SubmapId& end_id) const;
// Return a path between two points. It's' supposed that the submaps
// that the points are located are directly connected
Path LocalPlanPathRRT(const geometry_msgs::Point& start_point,
const geometry_msgs::Point& end_point) const;
// Return a path between two points in given submaps
Path LocalPlanPathRRT(const geometry_msgs::Point& start_point,
const geometry_msgs::Point& end_point,
const std::vector<SubmapId>& submap_ids) const;
// Publish and display the path in RVIZ
void AddDisplayPath(const Path& path);
private:
struct SubmapConnectState{
SubmapId start_submap_id;
SubmapId end_submap_id;
double length;
Path path;
SubmapConnectState(){};
SubmapConnectState(SubmapId start_id, SubmapId end_id, double d) :
start_submap_id(start_id),
end_submap_id(end_id),
length(d) {};
};
struct SubmapGrid{
SubmapId submap_id;
double resolution;
double x0;
double y0;
int width;
int height;
std::vector<int> data;
};
// Generate random free point in given submaps used in RRT*
geometry_msgs::Point RandomFreePoint(const std::vector<SubmapId>& submap_ids) const;
// Add submap grid into submap_grid_
void AddSubmapGrid(const SubmapId& submap_id);
// Discard existing path if existed and reconnect two submaps
// Return false if fail to connect two submaps
bool ReconnectSubmaps(const SubmapId& start_id, const SubmapId& end_id);
// Add a submap into road_map_
void AddRoadMapEntry(const SubmapId& submap_id);
// Update submap_, road_map_ and submap_grid_ every time receive submapList
void UpdateRoadMap(const cartographer_ros_msgs::SubmapList::ConstPtr& msg);
// ROS Agent
::cartographer::common::Mutex mutex_;
::ros::NodeHandle node_handle_ GUARDED_BY(mutex_);
::ros::Subscriber submap_list_subscriber_ GUARDED_BY(mutex_);
::ros::ServiceClient submap_query_client_ GUARDED_BY(mutex_);
Parameters parameters_;
// SubmapList
std::map<SubmapId,cartographer_ros_msgs::SubmapEntry> submap_ GUARDED_BY(mutex_);
// Kd tree for Submap position
KdTree submap_kdtree_;
// SubmapGrid
std::map<SubmapId, SubmapGrid> submap_grid_ GUARDED_BY(mutex_);
// Road map to store the connectivity of submaps and corresponding path
std::map<SubmapId,std::map<SubmapId,SubmapConnectState>> road_map_ GUARDED_BY(mutex_);
// ROS Server
::ros::ServiceServer roadmap_query_server_;
::ros::ServiceServer connection_query_server_;
::ros::ServiceServer plan_path_server_;
::ros::ServiceServer reconnect_submaps_server_;
bool QueryRoadmap(cartographer_ros_msgs::RoadmapQuery::Request &req,
cartographer_ros_msgs::RoadmapQuery::Response &res);
bool QueryConnection(cartographer_ros_msgs::ConnectionQuery::Request &req,
cartographer_ros_msgs::ConnectionQuery::Response &res);
bool PlanPath(cartographer_ros_msgs::PathPlan::Request &req,
cartographer_ros_msgs::PathPlan::Response &res);
bool ReconnectSubmapService(cartographer_ros_msgs::ReconnectSubmaps::Request &req,
cartographer_ros_msgs::ReconnectSubmaps::Response &res);
// Members to publish and display newest path
nav_msgs::Path path_to_display_;
::ros::WallTimer path_publisher_timer_;
::ros::Publisher path_publisher_;
void PublishPath(const ::ros::WallTimerEvent& timer_event);
// print out the current state for testing and debugging
::ros::Subscriber clicked_point_subscriber_ GUARDED_BY(mutex_);
void IsClickedPointFree(const geometry_msgs::PointStamped::ConstPtr& msg) const;
void NavigateToClickedPoint(const geometry_msgs::PointStamped::ConstPtr& msg);
};
} // namespace cartographer_ros_path_planner
} // namespace cartographer_ros
#endif /* path_planner_node.h */
<file_sep>/*
* Author: <NAME>
* Define some common basic functions
*/
#ifndef common_h
#define common_h
#include "geometry_msgs/Point.h"
#include "geometry_msgs/Pose.h"
namespace cartographer_ros {
namespace cartographer_ros_path_planner{
// Return distance2 in XY plane
double Distance2BetweenPoint(const geometry_msgs::Point& point1, const geometry_msgs::Point& point2);
double Distance2BetweenPose(const geometry_msgs::Pose& pose1, const geometry_msgs::Pose& pose2);
} // namespace cartographer_ros_path_planner
} // namespace cartographer_ros
#endif /* common_h */
<file_sep>/*
* Author: <NAME>
*/
#include <math.h>
#include <queue>
#include <string>
#include <set>
#include <stdlib.h>
#include <time.h>
#include <set>
#include "Eigen/Core"
#include "Eigen/Geometry"
#include "cairo/cairo.h"
#include "cartographer/io/image.h"
#include "cartographer/io/submap_painter.h"
#include "cartographer/transform/rigid_transform.h"
#include "cartographer_ros/msg_conversion.h"
#include "cartographer_ros/node_constants.h"
#include "cartographer_ros/submap.h"
#include "common.h"
#include "path_planner_node.h"
namespace cartographer_ros{
namespace cartographer_ros_path_planner {
namespace{
using ::cartographer::io::PaintSubmapSlicesResult;
using ::cartographer::io::SubmapSlice;
const char kSubmapListTopicName [] = "/submap_list";
const char kSubmapQueryServiceName [] = "/submap_query";
const char kRoadmapQueryServiceName [] = "/roadmap_query";
const char kConnectionQueryServiceName [] = "/connection_query";
const char kReconnectSubmapsServiceName [] = "/reconnect_submaps";
const char kPathPlanServiceName [] = "/plan_path";
const int kFinishVersion = 180;
const int kOccupyThreshold = 64;
const double kOccupyGridResolution = 0.05;
const double kProbabilityGridResolution = 0.05;
// Define add and scalar multiplication for Point
geometry_msgs::Point operator+(const geometry_msgs::Point& a, const geometry_msgs::Point& b){
geometry_msgs::Point sum;
sum.x = a.x + b.x;
sum.y = a.y + b.y;
sum.z = a.z + b.z;
return sum;
}
geometry_msgs::Point operator*(double a, const geometry_msgs::Point& b){
geometry_msgs::Point product;
product.x = a * b.x;
product.y = a * b.y;
product.z = a * b.z;
return product;
}
std::ostream& operator<<(std::ostream& os, const geometry_msgs::Point& point){
os<<" ("<<point.x<<","<<point.y<<","<<point.z<<") ";
return os;
}
std::ostream& operator<<(std::ostream& os, Path& path){
for(geometry_msgs::Point& point: path){
os<<point<<std::endl;
}
return os;
}
double RotationBetweenPose(const geometry_msgs::Pose& pose1, const geometry_msgs::Pose& pose2){
return abs(pose1.orientation.z-pose1.orientation.z);
}
// Judge intensity val free or not
bool IsValueFree(int val){
return 0<=val && val<kOccupyThreshold;
}
// Calculate L2 length of the path
double LengthOfPath(const Path& path){
double length = 0.0;
for(size_t i=0;i<path.size()-1;i++){
double distance2 = Distance2BetweenPoint(path[i],path[i+1]);
length += sqrt(distance2);
}
return length;
}
// Heuristic h = L2 distance
struct CustomPriorityCompare{
CustomPriorityCompare(std::map<SubmapId, double>& visited_submap_distance, const std::map<SubmapId,
cartographer_ros_msgs::SubmapEntry>& submap_, SubmapId end_id):
submap_distance(visited_submap_distance), submap_list(submap_){goal = submap_list.find(end_id)->second.pose.position;}
bool operator ()(const SubmapId& a, const SubmapId& b) {
double h_a = sqrt(Distance2BetweenPoint(submap_list.find(a)->second.pose.position, goal));
double h_b = sqrt(Distance2BetweenPoint(submap_list.find(b)->second.pose.position, goal));
return submap_distance[a] + h_a > submap_distance[b] + h_b;
}
private:
std::map<SubmapId, double>& submap_distance;
const std::map<SubmapId, cartographer_ros_msgs::SubmapEntry>& submap_list;
geometry_msgs::Point goal;
};
} // namespace
PathPlannerNode::PathPlannerNode(){
cartographer::common::MutexLocker lock(&mutex_);
submap_list_subscriber_ = node_handle_.subscribe<cartographer_ros_msgs::SubmapList>(kSubmapListTopicName,10, &PathPlannerNode::UpdateRoadMap,this);
submap_query_client_ = node_handle_.serviceClient<cartographer_ros_msgs::SubmapQuery>(kSubmapQueryServiceName);
roadmap_query_server_ = node_handle_.advertiseService(kRoadmapQueryServiceName,&PathPlannerNode::QueryRoadmap,this);
connection_query_server_ = node_handle_.advertiseService(kConnectionQueryServiceName, &PathPlannerNode::QueryConnection,this);
plan_path_server_ = node_handle_.advertiseService(kPathPlanServiceName,&PathPlannerNode::PlanPath,this);
reconnect_submaps_server_ = node_handle_.advertiseService(kReconnectSubmapsServiceName, &PathPlannerNode::ReconnectSubmapService,this);
path_publisher_ = node_handle_.advertise<::nav_msgs::Path>("/test_path", 10);
path_publisher_timer_ = node_handle_.createWallTimer(::ros::WallDuration(0.1), &PathPlannerNode::PublishPath, this);
SetParameters();
srand (time(NULL));
// For test
clicked_point_subscriber_ = node_handle_.subscribe<geometry_msgs::PointStamped>("/clicked_point",1,&PathPlannerNode::NavigateToClickedPoint, this);
std::cout<<"Successfully Create PathPlannerNode"<<std::endl;
}
void PathPlannerNode::SetParameters(){
if(!node_handle_.getParam("max_rrt_node_num" ,parameters_.max_rrt_node_num)){
std::cout<<"Error! Fail to get paramter: max_rrt_node_num"<<std::endl;
}
if(!node_handle_.getParam("step_to_check_reach_endpoint" ,parameters_.step_to_check_reach_endpoint)){
std::cout<<"Error! Fail to get paramter: step_to_check_reach_endpoint "<<std::endl;
}
if(!node_handle_.getParam("distance_threshold_for_adding" ,parameters_.distance_threshold_for_adding)){
std::cout<<"Error! Fail to get paramter: distance_threshold_for_adding"<<std::endl;
}
if(!node_handle_.getParam("distance_threshold_for_updating" ,parameters_.distance2_threshold_for_updating)){
std::cout<<"Error! Fail to get paramter: distance_threshold_for_updating"<<std::endl;
}
parameters_.distance2_threshold_for_updating *= parameters_.distance2_threshold_for_updating;
if(!node_handle_.getParam("rotation_threshold_for_updating" ,parameters_.rotation_threshold_for_updating)){
std::cout<<"Error! Fail to get paramter: rotation_threshold_for_updating"<<std::endl;
}
if(!node_handle_.getParam("probability_of_choose_endpoint" ,parameters_.probability_of_choose_endpoint)){
std::cout<<"Error! Fail to get paramter: probability_of_choose_endpoint"<<std::endl;
}
if(!node_handle_.getParam("rrt_grow_step" ,parameters_.rrt_grow_step)){
std::cout<<"Error! Fail to get paramter: rrt_grow_step"<<std::endl;
}
if(!node_handle_.getParam("rrt_trim_radius" ,parameters_.rrt_trim_radius)){
std::cout<<"Error! Fail to get paramter: rrt_trim_radius"<<std::endl;
}
if(!node_handle_.getParam("close_submap_radius" ,parameters_.close_submap_radius)){
std::cout<<"Error! Fail to get paramter: close_submap_radius"<<std::endl;
}
}
int PathPlannerNode::GetPointIntensity(const geometry_msgs::Point& point,
const SubmapId& submap_id) const{
if(submap_grid_.count(submap_id)==1){
const auto& submap_grid = submap_grid_.find(submap_id)->second;
int x = (point.x - submap_grid.x0) / submap_grid.resolution;
int y = (point.y - submap_grid.y0) / submap_grid.resolution;
if(x>=0 && x<submap_grid.width && y>=0 && y<submap_grid.height){
int val = submap_grid.data[y*submap_grid.width+x];
return val;
} else{
return -1;
}
} else{
std::cout<<"Submap "<<submap_id<<" not exist!"<<std::endl;
return -1;
}
}
bool PathPlannerNode::IsFree(const geometry_msgs::Point& point) const{
auto close_submaps = CloseSubmaps(point, parameters_.close_submap_radius);
bool is_free = false;
for(const auto& submap_id:close_submaps){
int val = GetPointIntensity(point,submap_id);
if(val>=kOccupyThreshold) return false;
if(val>=0) is_free = true;
}
return is_free;
}
bool PathPlannerNode::IsPathLocalFree(const geometry_msgs::Point& start_point,
const geometry_msgs::Point& end_point,
const std::vector<SubmapId>& submap_ids) const {
double distance2 = Distance2BetweenPoint(start_point,end_point);
double step = kOccupyGridResolution / sqrt(distance2);
for(double i=0;i<=1;i+=step){
geometry_msgs::Point point = (1.0-i) * start_point + i * end_point;
bool is_free = false;
for(const auto& submap_id:submap_ids){
int val = GetPointIntensity(point, submap_id);
if(val>=kOccupyThreshold) return false;
if(val>=0) is_free = true;
}
if(!is_free) return false;
}
return true;
}
SubmapId PathPlannerNode::ClosestSubmap(const geometry_msgs::Point& point) const{
const auto nearest_node = submap_kdtree_.NearestKdTreeNode(point);
return SubmapId {nearest_node->trajectory_id,nearest_node->submap_index};
}
std::vector<SubmapId> PathPlannerNode::CloseSubmaps(const geometry_msgs::Point& point,
double radius) const{
const auto& near_nodes = submap_kdtree_.NearKdTreeNode(point, radius);
std::vector<SubmapId> close_submaps;
close_submaps.reserve(near_nodes.size());
for(const auto near_node:near_nodes){
SubmapId submap_id {near_node->trajectory_id,near_node->submap_index};
close_submaps.push_back(std::move(submap_id));
}
return close_submaps;
}
Path PathPlannerNode::PlanPathRRT(const geometry_msgs::Point& start_point,
const geometry_msgs::Point& end_point) const {
::ros::WallTime begin_time = ::ros::WallTime::now();
// Check start and end point is free
if(!IsFree(start_point)){
std::cout<<"Start point is occupied!"<<std::endl;
return {};
}
if(!IsFree(end_point)){
std::cout<<"End point is occupied!"<<std::endl;
return {};
}
std::cout<<"Begin to plan a path from"<<start_point<<"to"<<end_point<<std::endl;
Path path;
SubmapId start_submap_id = ClosestSubmap(start_point);
SubmapId end_submap_id = ClosestSubmap(end_point);
std::cout<<"Locate start point at submap"<<start_submap_id<<std::endl;
std::cout<<"Locate end point at submap"<<end_submap_id<<std::endl;
// If start and end point are in the same submap, directly plan path in the submap
if(start_submap_id==end_submap_id){
path = LocalPlanPathRRT(start_point,end_point);
return path;
}
// Connect start point and the origin of start submap
Path start_path = LocalPlanPathRRT(start_point,submap_.find(start_submap_id)->second.pose.position);
if(!start_path.empty()){
path.insert(path.end(),start_path.begin(),start_path.end());
} else{
std::cout<<"Fail to connect start point to start_submap"<<std::endl;
return {};
}
// Connect start_submap to end_submap in road_map_
auto mid_path = ConnectSubmap(start_submap_id,end_submap_id);
if(!mid_path.empty()){
path.insert(path.end(),mid_path.begin(),mid_path.end());
} else{
std::cout<<"Fail to connect submap "<<start_submap_id<<" to submap "<<end_submap_id<<std::endl;
return {};
}
// Connect end_submap to end point
auto end_path = LocalPlanPathRRT(submap_.find(end_submap_id)->second.pose.position,end_point);
if(!end_path.empty()){
path.insert(path.end(),end_path.begin(),end_path.end());
} else{
std::cout<<" Fail to connect end point to end_submap"<<std::endl;
return {};
}
::ros::WallTime end_time = ::ros::WallTime::now();
long int used_time_ns = (end_time.sec-begin_time.sec)*1000000000+(end_time.nsec-begin_time.nsec);
std::cout<<"Successfully find a path! It took "<<used_time_ns<<" ns."<<std::endl;
return path;
}
Path PathPlannerNode::PlanPathRRT(const SubmapId& start_id, const SubmapId& end_id) const {
std::cout<<"Try to connect two submaps:"<<start_id<<","<<end_id<<std::endl;
const auto start_submap = submap_.find(start_id);
const auto end_submap = submap_.find(end_id);
if(start_submap==submap_.end()){
std::cout<<"Submap "<<start_id<<" not exist!"<<std::endl;
return {};
}
if(end_submap==submap_.end()){
std::cout<<"Submap "<<end_id<<" not exist!"<<std::endl;
return {};
}
geometry_msgs::Point start_point = start_submap->second.pose.position;
geometry_msgs::Point end_point = end_submap->second.pose.position;
Path path = LocalPlanPathRRT(start_point, end_point);
if(!path.empty()){
std::cout<<"Successfully connect submap "<<start_id<<" and "<<end_id<<std::endl;
} else{
std::cout<<"Fail to connect submap "<<start_id<<" and "<<end_id<<std::endl;
}
return path;
}
// Use BFS to connect two remote submaps
Path PathPlannerNode::ConnectSubmap(const SubmapId& start_id, const SubmapId& end_id) const {
std::map<SubmapId, double> visited_submap_distance;
std::map<SubmapId, SubmapId> previous_submap;
std::priority_queue<SubmapId,std::vector<SubmapId>,
CustomPriorityCompare> submap_to_visit ({visited_submap_distance, submap_, end_id});
for(const auto& pair:submap_) visited_submap_distance[pair.first] = DBL_MAX;
visited_submap_distance[start_id] = 0.0;
submap_to_visit.push(start_id);
bool find_end_id = false;
while(!submap_to_visit.empty()&&!find_end_id){
SubmapId current_submap = submap_to_visit.top();
submap_to_visit.pop();
auto& current_connections = road_map_.find(current_submap)->second;
for(const auto& entry:current_connections){
if(entry.second.length + visited_submap_distance[current_submap] <
visited_submap_distance[entry.first]){
visited_submap_distance[entry.first] = entry.second.length + visited_submap_distance[current_submap];
previous_submap[entry.first] = current_submap;
submap_to_visit.push(entry.first);
if(entry.first==end_id) {find_end_id = true;break;}
}
}
}
if(previous_submap.count(end_id)==0){
return {};
}
Path path;
SubmapId id = end_id;
while(previous_submap.count(id)==1){
SubmapId previous_id = previous_submap[id];
if(previous_submap.count(previous_id)==1){
auto connection = road_map_.find(previous_id)->second.find(id)->second;
path.insert(path.begin(),connection.path.begin(),connection.path.end());
}
id = previous_submap[id];
}
return path;
}
// Use RRT* to do local planning
Path PathPlannerNode::LocalPlanPathRRT(const geometry_msgs::Point& start_point,
const geometry_msgs::Point& end_point) const{
SubmapId start_submap_id = ClosestSubmap(start_point);
SubmapId end_submap_id = ClosestSubmap(end_point);
// Find local submaps used in later planning
auto start_submap_ids = CloseSubmaps(start_point, parameters_.close_submap_radius);
auto end_submap_ids = CloseSubmaps(end_point, parameters_.close_submap_radius);
std::set<SubmapId> union_submap_ids;
for(SubmapId& submap_id:start_submap_ids){
union_submap_ids.insert(submap_id);
}
for(SubmapId& submap_id:end_submap_ids){
union_submap_ids.insert(submap_id);
}
union_submap_ids.insert(start_submap_id);
union_submap_ids.insert(end_submap_id);
std::vector<SubmapId> submap_ids (union_submap_ids.begin(),union_submap_ids.end());
// Call local planner
return LocalPlanPathRRT(start_point,end_point,submap_ids);
}
Path PathPlannerNode::LocalPlanPathRRT(const geometry_msgs::Point& start_point,
const geometry_msgs::Point& end_point,
const std::vector<SubmapId>& submap_ids) const {
// Naively check the straight line between two points
if(IsPathLocalFree(start_point,end_point,submap_ids)) return {start_point,end_point};
// Build RRT using kd tree
KdTree kd_tree (start_point);
for(int node_num=1;node_num<=parameters_.max_rrt_node_num;node_num++){
// Generate random point in given submaps
// Better sample method can accerate the convergence
geometry_msgs::Point next_point;
if((rand() % 1000) / 1000.0 < parameters_.probability_of_choose_endpoint){
next_point = (end_point);
} else{
next_point = RandomFreePoint(submap_ids);
}
// Search the nearest tree node
KdTreeNode* nearest_node = kd_tree.NearestKdTreeNode(next_point);
// Or go ahead a given distance
next_point = (parameters_.rrt_grow_step)*next_point + (1-parameters_.rrt_grow_step)*nearest_node->point;
if(!IsPathLocalFree(nearest_node->point, next_point, submap_ids)){node_num--;continue;}
// Add next_node into RRT
KdTreeNode* next_node = kd_tree.AddPointToKdTree(next_point);
if(next_node==nullptr) std::cout<<"Fail to Add New Node"<<std::endl;
next_node->distance = nearest_node->distance + sqrt(Distance2BetweenPoint(next_point, nearest_node->point));
next_node->parent_node = nearest_node;
// Trim RRT
auto near_nodes = kd_tree.NearKdTreeNode(next_point, parameters_.rrt_trim_radius);
for(auto& near_node : near_nodes){
double edge_length = sqrt(Distance2BetweenPoint(next_point, near_node->point));
if(edge_length + next_node->distance < near_node->distance &&
IsPathLocalFree(near_node->point,next_point,submap_ids)){
near_node->parent_node = next_node;
near_node->distance = edge_length + next_node->distance;
}
}
// Try to connect RRT and end point
if(node_num % parameters_.step_to_check_reach_endpoint == 0){
//std::cout<<"Try to connect End point! Node Num:"<<node_num<<std::endl;
const KdTreeNode* path_node = kd_tree.NearestKdTreeNode(end_point);
if(IsPathLocalFree(path_node->point,end_point,submap_ids)){
// find the path!
Path path;
while(path_node!=nullptr){
path.insert(path.begin(),path_node->point);
path_node = path_node->parent_node;
}
path.push_back(end_point);
return path;
}
}
}
return {};
}
void PathPlannerNode::AddDisplayPath(const Path& path){
path_to_display_.header.stamp = ::ros::Time::now();
path_to_display_.header.frame_id = "/map";
path_to_display_.poses.clear();
for(auto& point : path){
geometry_msgs::PoseStamped pose_stamped;
pose_stamped.header.stamp = ::ros::Time::now();
pose_stamped.header.frame_id = "/map";
pose_stamped.pose.position = std::move(point);
pose_stamped.pose.orientation.w = 1.0;
pose_stamped.pose.orientation.x = 0.0;
pose_stamped.pose.orientation.y = 0.0;
pose_stamped.pose.orientation.z = 0.0;
path_to_display_.poses.push_back(std::move(pose_stamped));
}
}
// Return a random free point in given submaps
geometry_msgs::Point PathPlannerNode::RandomFreePoint(const std::vector<SubmapId>& submap_ids) const {
while(true){
int random_id = rand() % submap_ids.size();
auto& submap_grid = submap_grid_.find(submap_ids[random_id])->second;
int random_x = rand() % (submap_grid.width);
int random_y = rand() % (submap_grid.height);
int val = submap_grid.data[random_y * submap_grid.width + random_x];
if(val>=0 && val<kOccupyThreshold){
geometry_msgs::Point point;
point.x = random_x * submap_grid.resolution + submap_grid.x0;
point.y = random_y * submap_grid.resolution + submap_grid.y0;
point.z = 0.0;
// check if there's conflict in other submap
bool is_free = true;
for(auto other_submap:submap_ids){
if(GetPointIntensity(point,other_submap)>=kOccupyThreshold){
is_free = false;
break;
}
}
if(is_free) return point;
}
}
}
void PathPlannerNode::AddSubmapGrid(const SubmapId& submap_id){
// Clear the existing old data
submap_grid_.erase(submap_id);
// first fetch the submaptexture
cartographer_ros_msgs::SubmapEntry& submap_entry = submap_[submap_id];
auto fetched_textures = ::cartographer_ros::FetchSubmapTextures(submap_id, &submap_query_client_);
const auto submap_texture = fetched_textures->textures.begin();
// use fake map to do it (map only contain one element)
std::map<SubmapId, SubmapSlice> fake_submap_slices;
::cartographer::io::SubmapSlice& submap_slice = fake_submap_slices[submap_id];
submap_slice.pose = ToRigid3d(submap_entry.pose);
submap_slice.metadata_version = submap_entry.submap_version;
// push fetched texture to slice and draw the texture
submap_slice.version = fetched_textures->version;
submap_slice.width = submap_texture->width;
submap_slice.height = submap_texture->height;
submap_slice.slice_pose = submap_texture->slice_pose;
submap_slice.resolution = submap_texture->resolution;
submap_slice.cairo_data.clear();
submap_slice.surface = ::cartographer::io::DrawTexture(submap_texture->pixels.intensity,
submap_texture->pixels.alpha,
submap_texture->width, submap_texture->height,
&submap_slice.cairo_data);
// Paint the texture
auto painted_slices = cartographer::io::PaintSubmapSlices(fake_submap_slices, kOccupyGridResolution);
// Convert painted surface into occupied grid
auto& submap_grid = submap_grid_[submap_id];
const Eigen::Array2f& origin = painted_slices.origin;
cairo_surface_t* surface = painted_slices.surface.get();
const int width = cairo_image_surface_get_width(surface);
const int height = cairo_image_surface_get_height(surface);
submap_grid.submap_id = submap_id;
submap_grid.resolution = kOccupyGridResolution;
submap_grid.width = width;
submap_grid.height = height;
submap_grid.x0 = - origin.x() * kOccupyGridResolution;
submap_grid.y0 = (origin.y() - height) * kOccupyGridResolution;
const uint32_t* pixel_data = reinterpret_cast<uint32_t*>(cairo_image_surface_get_data(surface));
submap_grid.data.reserve(width*height);
for(int y=0;y<height;y++){
for(int x=0;x<width;x++){
const uint32_t packed = pixel_data[(height-y-1)*width+x];
const unsigned char color = packed >> 16;
const unsigned char observed = packed >> 8;
const int value =
observed == 0
? -1
: ::cartographer::common::RoundToInt((1. - color / 255.) * 100.);
submap_grid.data.push_back(value);
}
}
std::cout<<"Successfully Add Submap "<<submap_id<<" into submap_grid_"<<std::endl;
}
// Reconnect two submaps if necessary
bool PathPlannerNode::ReconnectSubmaps(const SubmapId& start_id, const SubmapId& end_id){
Path path = PlanPathRRT(start_id,end_id);
if(path.empty()) return false;
double path_length = LengthOfPath(path);
SubmapConnectState start_submap_connection_state (start_id,end_id,path_length);
SubmapConnectState end_submap_connection_state (end_id,end_id,path_length);
start_submap_connection_state.path = path;
std::reverse(path.begin(),path.end());
end_submap_connection_state.path = std::move(path);
road_map_[start_id][end_id] = std::move(start_submap_connection_state);
road_map_[end_id][start_id] = std::move(end_submap_connection_state);
return true;
}
void PathPlannerNode::AddRoadMapEntry(const SubmapId& submap_id){
std::cout<<"Try to add sumbap into road map "<<submap_id<<std::endl;
auto& submap_entry = submap_[submap_id];
if(submap_entry.submap_version!=kFinishVersion) return;
// Find neigbor submaps that are potential for adding
std::vector<SubmapId> near_submaps = CloseSubmaps(submap_entry.pose.position, parameters_.distance_threshold_for_adding);
SubmapId next_submap {submap_id.trajectory_id,submap_id.submap_index+1};
SubmapId last_submap {submap_id.trajectory_id,submap_id.submap_index+1};
near_submaps.push_back(std::move(next_submap));
near_submaps.push_back(std::move(last_submap));
for(auto& near_submap:near_submaps){
// Check near_submap exists and is not submap itself
if(submap_.count(near_submap)==0) continue;
if(near_submap==submap_id) continue;
// Connect two submpas
Path path = PlanPathRRT(submap_id,near_submap);
if(path.empty()){
std::cout<<"Warning!! Fail to connect "<<submap_id<<" , "<<near_submap<<std::endl;
continue;
}
// Add path into road_map
double path_length = LengthOfPath(path);
SubmapConnectState submap_connect_state (submap_id,
near_submap,
path_length);
SubmapConnectState other_submap_connect_state (near_submap,
submap_id,
path_length);
submap_connect_state.path = path;
std::reverse(path.begin(),path.end());
other_submap_connect_state.path = std::move(path);
road_map_[submap_id][near_submap] = std::move(submap_connect_state);
road_map_[near_submap][submap_id] = std::move(other_submap_connect_state);
}
}
// update the road map every time received submaplist
void PathPlannerNode::UpdateRoadMap(const cartographer_ros_msgs::SubmapList::ConstPtr& msg){
::cartographer::common::MutexLocker locker(&mutex_);
// check if submap has been changed
for(auto& submap_entry:msg->submap){
SubmapId submap_id {submap_entry.trajectory_id, submap_entry.submap_index};
if(submap_entry.submap_version < kFinishVersion) continue;
// add new finished submap into road_map_
if(submap_.find(submap_id)==submap_.end()){
submap_[submap_id] = submap_entry;
submap_kdtree_.AddPointToKdTree(submap_entry.pose.position, submap_id.trajectory_id, submap_id.submap_index);
AddSubmapGrid(submap_id);
AddRoadMapEntry(submap_id);
} else{
auto& old_submap_entry = submap_[submap_id];
double distance2 = Distance2BetweenPose(old_submap_entry.pose,submap_entry.pose);
double rotation = RotationBetweenPose(old_submap_entry.pose,submap_entry.pose);
if(rotation > parameters_.rotation_threshold_for_updating ||
distance2 > parameters_.distance2_threshold_for_updating){
submap_[submap_id] = submap_entry;
AddSubmapGrid(submap_id);
AddRoadMapEntry(submap_id);
}
}
}
}
bool PathPlannerNode::ReconnectSubmapService(::cartographer_ros_msgs::ReconnectSubmaps::Request &req,
::cartographer_ros_msgs::ReconnectSubmaps::Response &res){
SubmapId start_submap_id {req.start_trajectory_id, req.start_submap_index};
SubmapId end_submap_id {req.end_trajectory_id, req.end_submap_index};
ReconnectSubmaps(start_submap_id,end_submap_id);
return true;
}
bool PathPlannerNode::QueryRoadmap(::cartographer_ros_msgs::RoadmapQuery::Request &req,
::cartographer_ros_msgs::RoadmapQuery::Response &res){
SubmapId submap_id {req.trajectory_id, req.submap_index};
const auto& pair = road_map_.find(submap_id);
if(pair==road_map_.end()){
std::cout<<"Submap "<<submap_id<<" do not exist!"<<std::endl;
return true;
}
std::cout<<"Submap "<<submap_id<<" Connections: ";
for(const auto& connection_state:pair->second){
std::cout<<connection_state.first<<" ";
res.connections.push_back(connection_state.first.trajectory_id);
res.connections.push_back(connection_state.first.submap_index);
}
std::cout<<std::endl;
return true;
}
bool PathPlannerNode::QueryConnection(cartographer_ros_msgs::ConnectionQuery::Request &req,
cartographer_ros_msgs::ConnectionQuery::Response &res){
SubmapId start_submap_id {req.start_trajectory_id, req.start_submap_index};
SubmapId end_submap_id {req.end_trajectory_id, req.end_submap_index};
const auto& pair = road_map_.find(start_submap_id);
if(pair==road_map_.end()){
std::cout<<"Submap "<<start_submap_id<<" do not exist!"<<std::endl;
return true;
}
const auto& entry = pair->second.find(end_submap_id);
if(entry==pair->second.end()){
return true;
}
res.path = entry->second.path;
return true;
}
bool PathPlannerNode::PlanPath(cartographer_ros_msgs::PathPlan::Request &req,
cartographer_ros_msgs::PathPlan::Response &res) {
geometry_msgs::Point start_point = req.start_point;
geometry_msgs::Point end_point = req.end_point;
res.path = PlanPathRRT(start_point,end_point);
if(!res.path.empty()) AddDisplayPath(res.path);
return true;
}
void PathPlannerNode::PublishPath(const ::ros::WallTimerEvent& timer_event){
path_publisher_.publish(path_to_display_);
}
/*
Functions below are for test
*/
void PathPlannerNode::IsClickedPointFree(const geometry_msgs::PointStamped::ConstPtr& msg) const {
//std::cout<<msg->point.x<<","<<msg->point.y<<":";
std::cout<<IsFree(msg->point);
std::cout<<std::endl;
}
void PathPlannerNode::NavigateToClickedPoint(const geometry_msgs::PointStamped::ConstPtr& msg) {
std::cout<<"Received Goal:"<<msg->point.x<<","<<msg->point.y<<std::endl;
geometry_msgs::Point departure;
departure.x = 0.01;
departure.y = 0.01;
departure.z = 0.0;
Path path = PlanPathRRT(departure,msg->point);
if(path.empty()){
std::cout<<"Fail to find a valid path!"<<std::endl;
SubmapId submap_id = ClosestSubmap(msg->point);
std::cout<<departure<<" :: "<<submap_id<<", "<<GetPointIntensity(msg->point,submap_id)<<std::endl;
}
AddDisplayPath(path);
SubmapId submap_id = ClosestSubmap(msg->point);
std::cout<<departure<<" :: "<<submap_id<<", "<<GetPointIntensity(msg->point,submap_id)<<std::endl;
}
} // namespace cartographer_ros_path_planner
} // namespace cartographer_ros
<file_sep># Cartographer ROS Path Planner
This package provides online 2D path planning based on cartographer submaps and does not rely on the global occupied grid. Main idea is to build up a global road map for submaps and use RRT* as local planner.

## Getting Started
### Prerequisites
The package runs on Ubuntu 16.04 and ROS Kinetic.
### Installing
* Follow [cartographer_ros](https://github.com/googlecartographer/cartographer_ros) to download cartographer, cacartographer_ros and 2d demo.
* Move files in "src" to cartographer_ros/cartographer_ros/cartographer_ros
* Move files in "srv" to cartographer_ros/cartographer_ros_msgs/srv
* Move files in "launch" to cartographer_ros/cartographer_ros/launch
* Substitute cartographer_ros/cartographer_ros_msgs/CmakeLists.txt with the cmake file in srv
* Remake cartographer_ros
### Running the tests
* After launching 2d demo, open another terminal and launch the planner
```
roslaunch cartographer_ros cartographer_path_planner.launch
```
* Use the "clicked point" to play with it. The planner will plan a path between map origin to clicked point.
* In a few case, the path may go through the wall. This is mainly due to incorrect submaps created by cartographer.
## Methods
### Submap Road Map
Kd tree is used to store each submap's origin. For each submap, I try to connect it to nearby submaps in map, last submap and the next submap in time series. RRT* is used to do local planning and the result path is stored in a map with submap id as key.
### Global Path Plan
I decompose the global path plan into three parts: locally plan paths to connect start point and end point to nearest submaps. Use BFS to find the shortest path between these two submaps in road map. Finally combine the three paths.
## Parameters
### Hard Coded Parameters (const)
* kFinishVersion = 180. This is given by cartographer.
* kOccupyThreshold = 64. 0 is definitely free and 100 is definitely occupied.
* kOccupyGridResolution = 0.05 [m] Decided by cartographer configuration but hard coded here.
* kCloseSubmapRadius = 5.0 [m] Radius to find nearby submaps to given point
### ROS parameters in launch file
* max_rrt_node_num. Max num of node RRT will contain.
* step_to_check_reach_endpoint. Decide how often try to connect end point to RRT
* distance_threshold_for_adding. Distance threshold to decide whether try to connect two submaps
* distance_threshold_for_updating. If the position of the submap changes over this threshold, it will recalculate its road map
* rotation_threshold_for_updating. If the oretation (q.z) of the submap changes over this threshold, it will recalculate its road map
* probability_of_choose_endpoint. Probability to choose end point instead of random point as new point in RRT.
* rrt_grow_step and rrt_trim_radius. Parameters in RRT* algorithm.
## ROS API
* "/roadmap_query": Receive the SubmapId and return corresponding submaps connections
* "/connection_query": Receive two SubmapId and return the path in road map between them
* "/reconnect_submaps": Receive two SubmapId, discard existing path and try to reconnect them
* "/plan_path": Receive two geometry_msgs::Point and return a path connecting them
## C++ API
path_planner_node.h is well documented and provides useful information
## Future Work
### Improvement
* Add functions to smooth the path
* Add more RRT* tricks to accelerate convergence of RRT*
### Navigation
To work as navigation stack, continues real time localization and velocity controller are needed. Now cartographer supports pure localization as a new trajectory in map builder but has not provided ROS API.
Velocity controller transforms trajectory of way points to smooth velocity command which can be directly sent to robot's motion controller.
Since the submap are not perfect, dynamic navigation is desired. This however needs changes in cartographer and can not be implemented just in ROS.
<file_sep>/*
* Author: <NAME>
*/
#include <queue>
#include "common.h"
#include "kd_tree.h"
namespace cartographer_ros {
namespace cartographer_ros_path_planner{
// Constructor for KdTreeNode
KdTreeNode::KdTreeNode() : parent_node(nullptr), distance (0.0), left_node(nullptr), right_node(nullptr),
trajectory_id(0), submap_index(0){
point.x = 0.0;
point.y = 0.0;
point.z = 0.0;
}
KdTreeNode::KdTreeNode(geometry_msgs::Point p) : point(p), parent_node(nullptr), distance (0.0),
left_node(nullptr), right_node(nullptr), trajectory_id(0), submap_index(0){}
KdTreeNode::KdTreeNode(geometry_msgs::Point p, int trajectory_idx, int submap_idx) : point(p),
parent_node(nullptr), distance (0.0), left_node(nullptr), right_node(nullptr),
trajectory_id(trajectory_idx), submap_index(submap_idx){}
// Return nearest node to target point
KdTreeNode* KdTree::NearestKdTreeNode(const geometry_msgs::Point& target) const {
KdTreeNode* nearest_node = nullptr;
double closest_distance2 = DBL_MAX;
SearchKdTreeNode(target, root_, nearest_node, closest_distance2,0);
return nearest_node;
}
// Return near nodes around target within radius
std::vector<KdTreeNode*> KdTree::NearKdTreeNode(const geometry_msgs::Point& target,
double radius) const {
std::vector<KdTreeNode*> near_nodes;
SearchKdTreeNode(target,root_,near_nodes,radius * radius,0);
return near_nodes;
}
// Helper function to go through KdTree
void KdTree::SearchKdTreeNode(const geometry_msgs::Point& target,
KdTreeNode* current_node,
KdTreeNode*& current_nearest_node,
double& current_cloest_distance2,
int depth) const{
if(current_node==nullptr) return;
double distance2 = Distance2BetweenPoint(target, current_node->point);
bool go_to_left = depth%2==0 ? target.x <= current_node->point.x // Compare x
: target.y <= current_node->point.y; // Compare y
// Recursively visit children
go_to_left ?
SearchKdTreeNode(target, current_node->left_node,
current_nearest_node,current_cloest_distance2, depth+1) :
SearchKdTreeNode(target, current_node->right_node,
current_nearest_node,current_cloest_distance2, depth+1);
// Search current_node
if(distance2<current_cloest_distance2){
current_cloest_distance2 = distance2;
current_nearest_node = current_node;
}
// Judge whether search other side
double discard_threshold = depth%2==0
? (target.x - current_node->point.x) * (target.x - current_node->point.x)
: (target.y - current_node->point.y) * (target.y - current_node->point.y);
if(current_cloest_distance2 > discard_threshold){
go_to_left ? SearchKdTreeNode(target,current_node->right_node,
current_nearest_node,current_cloest_distance2,depth+1)
: SearchKdTreeNode(target,current_node->left_node,
current_nearest_node,current_cloest_distance2,depth+1);
}
}
// Helper function to go through KdTree
void KdTree::SearchKdTreeNode(const geometry_msgs::Point& target,
KdTreeNode* current_node,
std::vector<KdTreeNode*>& near_nodes,
double radius,
int depth) const{
if(current_node==nullptr) return;
double distance2 = Distance2BetweenPoint(target, current_node->point);
// Visit current node
if(distance2 < radius) near_nodes.push_back(current_node);
// Recursively visit children
bool go_to_left = depth%2==0 ? target.x <= current_node->point.x // Compare x
: target.y <= current_node->point.y; // Compare y
if(go_to_left){
SearchKdTreeNode(target, current_node->left_node, near_nodes,radius, depth+1);
} else{
SearchKdTreeNode(target, current_node->right_node, near_nodes,radius, depth+1);
}
// Visit the otherside
double discard_threshold = depth%2==0
? (target.x - current_node->point.x) * (target.x - current_node->point.x)
: (target.y - current_node->point.y) * (target.y - current_node->point.y);
if(radius > discard_threshold){
go_to_left ? SearchKdTreeNode(target, current_node->right_node, near_nodes, radius, depth+1)
: SearchKdTreeNode(target, current_node->left_node, near_nodes,radius, depth+1);
}
}
// Add a new point into RRT tree and return a pointer to it
KdTreeNode* KdTree::AddPointToKdTree(geometry_msgs::Point point){
return AddPointToKdTree(point, root_, 0);
}
KdTreeNode* KdTree::AddPointToKdTree(geometry_msgs::Point point, int trajectory_idx, int submap_idx){
auto added_node = AddPointToKdTree(point, root_, 0);
added_node->trajectory_id = trajectory_idx;
added_node->submap_index = submap_idx;
return added_node;
}
// Recursively add the point into kd tree
KdTreeNode* KdTree::AddPointToKdTree(geometry_msgs::Point point, KdTreeNode* parent, int depth){
bool go_to_left = depth%2==0 ? point.x <= parent->point.x // Compare x
: point.y <= parent->point.y; // Compare y
if(go_to_left){
if(parent->left_node==nullptr){
parent->left_node = new KdTreeNode(point);
return parent->left_node;
} else{
return AddPointToKdTree(point, parent->left_node, depth+1);
}
} else{
if(parent->right_node==nullptr){
parent->right_node = new KdTreeNode(point);
return parent->right_node;
} else{
return AddPointToKdTree(point, parent->right_node, depth+1);
}
}
}
// Constructor
KdTree::KdTree() : root_(new KdTreeNode ()){}
KdTree::KdTree(geometry_msgs::Point start_point) : root_(new KdTreeNode (start_point)){}
// Destroy RRT
void KdTree::DestroyRRT(KdTreeNode* root){
if(root!=nullptr){
DestroyRRT(root->left_node);
DestroyRRT(root->right_node);
delete(root);
}
}
// For test
KdTreeNode* KdTree::BruceNearestKdTreeNode(const geometry_msgs::Point& target){
KdTreeNode* nearest_node = nullptr;
double min_distance2 = DBL_MAX;
std::queue<KdTreeNode*> q;
q.push(root_);
while(!q.empty()){
double distance2 = Distance2BetweenPoint(target, q.front()->point);
if(distance2<min_distance2){
min_distance2 = distance2;
nearest_node = q.front();
}
if(q.front()->left_node) q.push(q.front()->left_node);
if(q.front()->right_node) q.push(q.front()->right_node);
q.pop();
}
return nearest_node;
}
std::vector<KdTreeNode*> KdTree::BruceNearKdTreeNode(const geometry_msgs::Point& target,
double radius){
std::vector<KdTreeNode*> bruce_near_nodes;
std::queue<KdTreeNode*> q;
q.push(root_);
while(!q.empty()){
double distance2 = Distance2BetweenPoint(target, q.front()->point);
if(distance2 < radius){
bruce_near_nodes.push_back(q.front());
}
if(q.front()->left_node) q.push(q.front()->left_node);
if(q.front()->right_node) q.push(q.front()->right_node);
q.pop();
}
return bruce_near_nodes;
}
} // namespace cartographer_ros_path_planner
} // namespace cartographer_ros
<file_sep>/*
* Author: <NAME>
*/
#include "ros/ros.h"
#include "path_planner_node.h"
int main(int argc, char** argv){
::ros::init(argc, argv, "cartographer_navigation_node");
::ros::start();
cartographer_ros::cartographer_ros_path_planner::PathPlannerNode node;
::ros::spin();
::ros::shutdown();
return 0;
}
<file_sep>/*
*
*
*
*/
#include "common.h"
namespace cartographer_ros {
namespace cartographer_ros_path_planner{
// Return distance2 in XY plane
double Distance2BetweenPoint(const geometry_msgs::Point& point1, const geometry_msgs::Point& point2){
return (point1.x-point2.x)*(point1.x-point2.x) + (point1.y-point2.y)*(point1.y-point2.y);
}
double Distance2BetweenPose(const geometry_msgs::Pose& pose1, const geometry_msgs::Pose& pose2){
return (pose1.position.x-pose2.position.x)*(pose1.position.x-pose2.position.x)+
(pose1.position.y-pose2.position.y)*(pose1.position.y-pose2.position.y)
+(pose1.position.z-pose2.position.z)*(pose1.position.z-pose2.position.z);
}
} // namespace cartographer_ros_path_planner
} // namespace cartographer_ros
|
f9bb4a300741f70689d36d60770b26532b1f0816
|
[
"Markdown",
"C++"
] | 8
|
C++
|
jeking1/cartographer_ros_path_planner
|
ef08f8f9b52a517a4e6a141d64fab99a1a5b1a9a
|
713215934629be9329e798595b91fc0654610215
|
refs/heads/master
|
<file_sep>create table property (
propid serial primary key,
propname varchar(40),
propdescription varchar(200),
address varchar(200),
city varchar(40),
state varchar(20),
zip varchar(40),
image varchar(200),
loanAmount decimal(20, 2),
monthlyMortgage decimal(20, 2),
desiredRent decimal(20, 2),
userid varchar(20)
)
<file_sep>module.exports = {
addProperty: (req, res) => {
const db = req.app.get('db');
console.log(req.body);
const { propName, propDescription, address, city,
listingState, zip, image, loanAmount, monthlyMortgage,
desiredRent, userid } = req.body;
db.add_property([propName, propDescription, address, city,
listingState, zip, image, loanAmount, monthlyMortgage,
desiredRent, userid]).then(props => {
res.status(200).send(props);
})
},
getProperties: (req, res) => {
console.log(req.query);
const db = req.app.get('db');
db.get_properties().then(props => {
if (req.query.rent) {
let filtered = props.filter((el) => Number(el.desiredrent) > Number(req.query.rent));
res.status(200).send(filtered)
} else {
res.status(200).send(props);
}
})
},
deleteProperty: (req, res) => {
console.log(req.params.id);
const db = req.app.get('db');
db.delete_property([req.params.id]).then(props => {
res.status(200).send(props);
})
}
}<file_sep>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { updateDesiredRent, resetState } from '../../ducks/reducer';
import axios from 'axios';
import { Redirect } from 'react-router';
import Header from '../Header/Header';
class Wizard5 extends Component {
constructor(props) {
super(props);
this.state = {
redirect: false
}
this.addToDatabase = this.addToDatabase.bind(this);
}
componentDidMount() {
if (!this.props.user.username) {
this.props.history.push('/');
}
}
addToDatabase() {
const { propName, propDescription, address,
city, listingState, zip, image, loanAmount,
desiredRent, monthlyMortgage, user } = this.props;
const userid = user.id;
axios.post('/api/properties', {
propName,
propDescription,
address,
city,
listingState,
zip,
image,
loanAmount,
desiredRent,
monthlyMortgage,
userid: String(userid)
}).then(res => {
this.setState({ redirect: true })
})
this.props.resetState(this.props.user);
}
render() {
const { propName, propDescription, address,
city, listingState, zip, image, loanAmount,
updateDesiredRent, resetState, desiredRent,
monthlyMortgage, user } = this.props;
console.log(this.props);
if (this.state.redirect) {
return <Redirect to="/dashboard" />
}
return (
<div>
<Header />
<div className="wizard">
<div className="wizard-top">
<h1>Add new listing</h1>
<Link to="/dashboard" className="cancel-button"><button onClick={() => resetState(user)}>Cancel</button></Link>
</div>
<div className="circle-div">
<div className="circle"><div className="circle-complete"></div></div>
<div className="circle"><div className="circle-complete"></div></div>
<div className="circle"><div className="circle-complete"></div></div>
<div className="circle"><div className="circle-complete"></div></div>
<div className="circle"><div className="circle-complete"></div></div>
</div>
<h3>Step 5</h3>
<h4>Recommended Rent: ${Number(monthlyMortgage) + Number((monthlyMortgage / 4))}</h4>
<div className="wizard-content">
<h2>Desired Rent</h2>
<input value={desiredRent} onChange={(e) => updateDesiredRent(e.target.value)} />
</div>
<div className="wizard-buttons">
<Link to="/wizard/4"><button>Previous Step</button></Link>
<button className="complete-button"onClick={this.addToDatabase}>Complete</button>
</div>
</div>
</div>
)
}
}
function mapStateToProps(state) {
const { propName, propDescription, address,
city, listingState, zip, image, loanAmount,
monthlyMortgage, desiredRent, user } = state;
return {
propName,
propDescription,
address,
city,
listingState,
zip,
image,
loanAmount,
monthlyMortgage,
desiredRent,
user
}
}
let actions = {
updateDesiredRent,
resetState
}
export default connect(mapStateToProps, actions)(Wizard5);<file_sep>import React, { Component } from 'react';
import Header from '../Header/Header';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { updateImage, resetState } from '../../ducks/reducer';
class Wizard3 extends Component {
componentDidMount() {
if (!this.props.user.username) {
this.props.history.push('/');
}
}
render() {
console.log(this.props);
const { updateImage, image, user } = this.props;
return (
<div>
<Header />
<div className="wizard">
<div className="wizard-top">
<h1>Add new listing</h1>
<Link to="/dashboard" className="cancel-button"><button onClick={() => resetState(user)}>Cancel</button></Link>
</div>
<h3>Step 3</h3>
<div className="circle-div">
<div className="circle"><div className="circle-complete"></div></div>
<div className="circle"><div className="circle-complete"></div></div>
<div className="circle"><div className="circle-complete"></div></div>
<div className="circle"></div>
<div className="circle"></div>
</div>
<div className="wizard-content">
<div className="wizard-image">
</div>
<h2>Image URL</h2>
<input value={image} onChange={(e) => updateImage(e.target.value)} />
</div>
<div className="wizard-buttons">
<Link to="/wizard/2"><button>Previous Step</button></Link>
<Link to="/wizard/4"><button>Next Step</button></Link>
</div>
</div>
</div>
)
}
}
function mapStateToProps(state) {
const { image, user } = state;
return {
image,
user
}
}
let actions = {
updateImage,
resetState
}
export default connect(mapStateToProps, actions)(Wizard3);<file_sep>module.exports = {
login: (req, res) => {
const db = req.app.get('db');
const { username, password } = req.body;
db.get_user([username, password]).then(user => {
if (user[0]) {
console.log(user[0])
req.session.user = { id: user[0].userid, username: user[0].username }
console.log(req.session.user);
res.status(200).send(req.session.user);
} else {
res.status(500).send('User is not registered');
}
})
},
register: (req, res) => {
const db = req.app.get('db');
const { username, password } = req.body;
console.log(username, password);
db.get_username([username, password]).then(result => {
if (!result[0]) {
db.add_user([username, password]).then((user) => {
req.session.user = { id: user[0].userid, username: user[0].username }
res.status(200).send(req.session.user);
})
} else {
res.status(500).send('User is already registered');
}
})
},
logout: (req, res) => {
const { session } = req;
session.destroy();
res.status(200).send(req.session);
}
}<file_sep>import React, { Component } from 'react';
import Header from '../Header/Header';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { connect } from 'react-redux';
import { resetState, logout } from '../../ducks/reducer';
import { Redirect } from 'react-router';
import "./Dashboard.css";
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
properties: [],
query: null,
logout: false
}
this.filterProperties = this.filterProperties.bind(this);
this.handleChange = this.handleChange.bind(this);
this.resetProperties = this.resetProperties.bind(this);
this.deleteProperty = this.deleteProperty.bind(this);
}
componentDidMount() {
if (this.props.user.username) {
axios.get('/api/properties').then(res => {
this.setState({ properties: res.data })
})
} else {
this.props.history.push('/')
}
}
filterProperties() {
axios.get(`/api/properties?rent=${Number(this.state.query)}`).then(res => {
this.setState({ properties: res.data })
})
}
resetProperties() {
axios.get('/api/properties').then(res => {
this.setState({ properties: res.data })
})
}
deleteProperty(val) {
axios.delete(`/api/properties/${val}`).then(res => {
this.setState({ properties: res.data })
})
}
handleChange(val) {
this.setState({ query: val })
}
render() {
if (this.state.logout) {
console.log(true);
return <Redirect to="/" />
}
// console.log(this.props.match);
// console.log(this.state.properties);
let properties = this.state.properties.filter((el) => el.userid == this.props.user.id)
properties = properties.map((el, idx) => {
const { propid, propname, propdescription, address, city, state, zip,
image, loanamount, monthlymortgage, desiredrent, userid } = el;
return (
<div className="property-div">
<img src={image} alt="" />
<div className="property-div-middle">
<h2>Name: {propname}</h2>
<p>{propdescription}</p>
</div>
<div className="property-div-right">
<div>
<button value={propid} onClick={(e) => this.deleteProperty(e.target.value)}>X</button>
<h2>Loan: {loanamount}</h2>
<h2>Monthly Mortgage: {monthlymortgage}</h2>
<h2>Recommended Rent: {Number(monthlymortgage) + Number(monthlymortgage / 4)}</h2>
<h2>Desired Rent: {desiredrent}</h2>
<h2>Address: {address}</h2>
<h2>City: {city}</h2>
</div>
</div>
</div>
)
})
return (
<div>
<Header />
<div className="dashboard">
<Link to="/wizard/1" ><button className="add-new">Add new property</button></Link>
<span className="filter-span">
<p>List properties with "desired rent" greater than: $
<span className="filter-span">
<input type="number" onChange={(e) => this.handleChange(e.target.value)} />
<button onClick={this.filterProperties}>Filter</button>
<button onClick={this.resetProperties}>Reset</button>
</span>
</p>
</span>
<hr />
{properties}
</div>
</div>
)
}
}
function mapStateToProps(state) {
const { user } = state;
return {
user
}
}
let actions = {
resetState,
logout
}
export default connect(mapStateToProps, actions)(Dashboard);<file_sep>create table users (
userid serial primary key,
username varchar(40),
password varchar(40)
)<file_sep>import React, { Component } from 'react';
import Header from '../Header/Header';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import './Wizard.css';
import { updatePropName, updatePropDescription, resetState } from '../../ducks/reducer'
class Wizard1 extends Component {
componentDidMount() {
if (!this.props.user.username) {
this.props.history.push('/');
}
}
render() {
console.log(this.props);
const { updatePropDescription, updatePropName, propName, propDescription, resetState, user } = this.props;
return (
<div>
<Header />
<div className="wizard">
<div className="wizard-top">
<h1>Add new listing</h1>
<Link className="cancel-button" to="/dashboard"><button onClick={() => resetState(user)}>Cancel</button></Link>
</div>
<h3>Step 1</h3>
<div className="circle-div">
<div className="circle"><div className="circle-complete"></div></div>
<div className="circle"></div>
<div className="circle"></div>
<div className="circle"></div>
<div className="circle"></div>
</div>
<div className="wizard-content">
<h2>Property Name</h2>
<input value={propName} onChange={(e) => updatePropName(e.target.value)} />
<h2>Property Description</h2>
<input className="wizard-prop-description" value={propDescription} onChange={(e) => updatePropDescription(e.target.value)} />
</div>
<div className="wizard-buttons" style={{justifyContent: "center"}}>
<Link to="/wizard/2"><button>Next Step</button></Link>
</div>
</div>
</div>
)
}
}
function mapStateToProps(state) {
const { propName, propDescription, user } = state;
return {
propName,
propDescription,
user
}
}
let actions = {
updatePropName,
updatePropDescription,
resetState
}
export default connect(mapStateToProps, actions)(Wizard1);<file_sep>require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const cors = require('cors');
const massive = require('massive');
const auth_controller = require('./controllers/auth_controller.js');
const prop_controller = require('./controllers/prop_controller.js');
const checkForSession = require('./middlewares/checkForSession');
const app = express();
app.use(bodyParser.json());
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true
}));
app.use(checkForSession);
//AUTH CONTROLLERS
app.post('/api/auth/login', auth_controller.login);
app.post('/api/auth/register', auth_controller.register);
app.post('/api/auth/logout', auth_controller.logout);
//PROPERTY CONTROLLERS
app.post('/api/properties', prop_controller.addProperty);
app.get('/api/properties', prop_controller.getProperties);
app.delete('/api/properties/:id', prop_controller.deleteProperty);
var port = process.env.PORT || 3005;
massive(process.env.CONNECTION_STRING).then(db => {
app.set('db', db);
app.listen(port, () => console.log(`Listening on port ${port}`))
})<file_sep>import React, { Component } from 'react';
import Header from '../Header/Header';
import { connect } from 'react-redux';
import { access } from 'fs';
import { Link } from 'react-router-dom';
import { updateAddress, updateCity, updateState, updateZip, user, resetState } from '../../ducks/reducer';
class Wizard2 extends Component {
componentDidMount() {
if (!this.props.user.username) {
this.props.history.push('/');
}
}
render() {
console.log(this.props);
const { updateAddress, updateCity, updateState, updateZip, resetState,
address, city, listingState, zip, user } = this.props;
return (
<div>
<Header />
<div className="wizard">
<div className="wizard-top">
<h1>Add new listing</h1>
<Link to="/dashboard" className="cancel-button"><button onClick={() => resetState(user)}>Cancel</button></Link>
</div>
<h3>Step 2</h3>
<div className="circle-div">
<div className="circle"><div className="circle-complete"></div></div>
<div className="circle"><div className="circle-complete"></div></div>
<div className="circle"></div>
<div className="circle"></div>
<div className="circle"></div>
</div>
<div className="wizard-content">
<h2>Address</h2>
<input value={address} onChange={(e) => updateAddress(e.target.value)} />
<span className="wizard-content-span">
<div className="wizard-city">
<h2>City</h2>
<input value={city} onChange={(e) => updateCity(e.target.value)} />
</div>
<div className="wizard-state">
<h2>State</h2>
<input value={listingState} onChange={(e) => updateState(e.target.value)} />
</div>
</span>
<div className="wizard-zip">
<h2>Zip</h2>
<input value={zip} onChange={(e) => updateZip(e.target.value)} />
</div>
</div>
<div className="wizard-buttons">
<Link to="/wizard/1"><button>Previous Step</button></Link>
<Link to="/wizard/3"><button>Next Step</button></Link>
</div>
</div>
</div>
)
}
}
function mapStateToProps(state) {
const { address, city, listingState, zip, user } = state;
return {
address,
city,
listingState,
zip,
user
}
}
let actions = {
updateAddress,
updateCity,
updateState,
updateZip,
resetState
}
export default connect(mapStateToProps, actions)(Wizard2);<file_sep>import React, { Component } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router';
import { connect } from 'react-redux';
import { logout } from '../../ducks/reducer';
import './Header.css';
class Header extends Component {
constructor() {
super();
this.state = {
redirect: false
}
this.handleLogout = this.handleLogout.bind(this);
}
handleLogout() {
axios.post('/api/auth/logout', {}).then(res => {
this.props.logout();
this.setState({ redirect: true })
})
}
render() {
if (this.state.redirect) {
return <Redirect to="/" />
}
return (
<div className="header">
<div className="header-content">
<div className="header-left">
<img src="https://raw.githubusercontent.com/DevMountain/simulation-2/master/assets/auth_logo.png" alt="house" />
<h1>Houser Dashboard</h1>
</div>
<button onClick={this.handleLogout}>Log Out</button>
</div>
</div>
)
}
}
function mapStateToProps(state) {
const { user } = state;
return {
user
}
}
let actions = {
logout
}
export default connect(mapStateToProps, actions)(Header);
|
8d4b579879e28883984d6fceac1a4627e4d6d21e
|
[
"JavaScript",
"SQL"
] | 11
|
SQL
|
haftav/simulation-2
|
efb8c66e5325fefd4a99e2126a29d0ad249a6913
|
49f468863c88567116f3a9d78af63cfbcdedf605
|
refs/heads/main
|
<repo_name>egdemems/Aurum<file_sep>/point/ExploreView.swift
//
// ExploreView.swift
// point
//
// Created by <NAME> on 7/13/21.
//
import SwiftUI
struct ExploreView: View {
@AppStorage("zipcode") var zipcode: String = UserDefaults.standard.string(forKey: "Zipcode") ?? ""
var categories = ["Appliances", "Apps & Games", "Arts, Crafts, & Sewing", "Automotive Parts & Accessories", "Beauty & Personal Care",
"Books", "CDs & Vinyl", "Cell Phones & Accesories", "Clothing", "Shoes", "Jewlery", "Collectibles & Fine Art", "Computers", "Electronics", "Garden & Outdoor", "Grocery & Gourmet Food", "Handmade", "Health & Household", "Home & Kitchen", "Industrial & Scientific", "Luggage & Travel", "Movies & TV", "Musical Instruments", "Office Products",
"Pet Supplies", "Sports & Outdoors", "Tools & Home Improvement", "Toys & Games", "Video Games"]
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
}
}
struct ExploreView_Previews: PreviewProvider {
static var previews: some View {
ExploreView()
}
}
<file_sep>/point/PostSubView.swift
//
// PostSubView.swift
// point
//
// Created by <NAME> on 7/9/21.
//
import SwiftUI
import FirebaseDatabase
import FirebaseStorage
import WKView
struct Onboard: Codable {
struct subHref: Codable {
var href: String
var rel: String
var method: String
var description: String
}
var links: [subHref]
}
struct Buyer: Codable {
struct subHref2: Codable {
var href: String
var rel: String
var method: String
}
var id: String
var status: String
var links: [subHref2]
}
struct accToke: Codable{
var access_token: String
}
struct PostSubView: View {
@State var showUrl = false
@State var OnboardSave = ""
@State var OnboardId = ""
@State var toke = ""
@State var address = ""
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@AppStorage("wallet") var wallet:String = ""
var ref = Database.database().reference()
var username: String
var firstPhoto: UIImage
var name: String
@State var postCount1 = true
@State var thumbnail1 = [UIImage]()
@State var title = ""
@State var description = ""
@State var category = ""
@State var price = 0
@State var zipcode = 0
@State private var image = UIImage(imageLiteralResourceName: "tab")
func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
func accessToken(){
guard let url = URL(string: "https://api-m.sandbox.paypal.com/v1/oauth2/token"),
let payload = "grant_type=client_credentials".data(using: .utf8) else
{
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("Basic QWFHUy1FMU1Nb0pBS0FaWXBETWI5aWxONGRlQktBcjFKRW8tMVdORElNeFVwbnFUd3BlSjFUb19nREozem54UVZVSDJFX3lBXzk0RDBsdDU6RUQzODV3Sm9adUNTcWoxMUhUX1Vac0Nvd0hmU0R1MG9TV2RrQVVRQU9vNUhFbFgzTktTb2lOZFRMRXhfeXF4Tmg4ZG1pVnM1NjdJVGVqU3k=", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = payload
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else { print(error!.localizedDescription); return }
guard let data = data else { print("Empty data"); return }
let decoder = JSONDecoder()
let token1 = try? decoder.decode(accToke.self, from: data)
self.toke = token1!.access_token
}.resume()
}
func loader() {
ref.child("\(name)/image_count").getData {
(error, snapshot) in
let pop = snapshot.value as? Int
if pop! != 0 {
if pop == 1 {
postCount1 = true
}
else {
postCount1 = false
for x in 2...pop! {
ref.child("\(name)/image_\(x)").observe(.value) {
(snapshot) in
let pop1 = snapshot.value as? String
if pop1 != nil {
Storage.storage().reference().child("\(pop1!)").getData(maxSize: 1 * 1024 * 1024) {
(imageData, err) in
if err != nil {
print("error downloading image")
} else {
if let imageData = imageData {
self.thumbnail1.append(UIImage(data: imageData)!)
} else {
print("couldn't unwrap")
}
}
}
}
}
}
}
}
}
ref.child("\(name)/title").getData {
(error, snapshot) in
let pop = snapshot.value as? String
self.title = pop ?? "No title"
}
ref.child("\(name)/description").getData {
(error, snapshot) in
let pop = snapshot.value as? String
self.description = pop ?? "No Description"
}
ref.child("\(name)/category").getData {
(error, snapshot) in
let pop = snapshot.value as? String
self.category = pop ?? ""
}
ref.child("\(name)/price").getData {
(error, snapshot) in
let pop = snapshot.value as? Int
self.price = pop ?? 0
}
ref.child("\(name)/zipcode").getData {
(error, snapshot) in
let pop = snapshot.value as? Int
self.zipcode = pop ?? 0
}
ref.child("\(username)/email").getData {
(error, snapshot) in
let pop = snapshot.value as? String
self.address = pop ?? ""
}
Storage.storage().reference().child("\(wallet)/pfp").getData(maxSize: 1 * 1024 * 1024) {
(imageData, err) in
if err != nil {
print("error downloading image")
} else {
if let imageData = imageData {
self.image = UIImage(data: imageData)!
} else {
print("couldn't unwrap")
}
}
}
}
var body: some View {
ZStack {
Text(OnboardSave)
.opacity(0)
Color(#colorLiteral(red: 0.992025435, green: 0.9831623435, blue: 0.8817279935, alpha: 1))
.frame(maxWidth: .infinity, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
ZStack(alignment: .topLeading){
ScrollView {
if postCount1 == true {
Image(uiImage: firstPhoto)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 390, height: 390, alignment: .center)
.clipped()
}
else {
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack {
Image(uiImage: firstPhoto)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 390, height: 390, alignment: .center)
.clipped()
if thumbnail1 != [UIImage]() {
ForEach(thumbnail1, id: \.self) { thing in
Image(uiImage: thing)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 390, height: 390, alignment: .center)
.clipped()
}
}
}
}
}
VStack{
HStack {
Text(title)
.bold()
.font(.system(size: 20))
.foregroundColor(.black)
Spacer()
Text("$\(self.price)")
.font(.system(size: 20))
.foregroundColor(.black)
.bold()
}
.frame(width: 350, alignment: .leading)
.padding()
Text("Description")
.bold()
.font(.system(size: 20))
.foregroundColor(.black)
.frame(width: 350, alignment: .leading)
Text(self.description)
.font(.system(size: 20))
.foregroundColor(.black)
.frame(width: 350, alignment: .leading)
Spacer()
.frame(height:40)
Text("Category")
.bold()
.font(.system(size: 20))
.foregroundColor(.black)
.frame(width: 350, alignment: .leading)
Text(self.category)
.font(.system(size: 20))
.foregroundColor(.black)
.frame(width: 350, alignment: .leading)
Spacer()
.frame(height:40)
HStack {
Text("Zipcode:")
.bold()
.font(.system(size: 20))
.foregroundColor(.black)
Text(String(self.zipcode))
.font(.system(size: 20))
.foregroundColor(.black)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
Spacer()
}
.padding(.top, 1)
VStack {
HStack {
Image(uiImage: self.image)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 50, height: 50)
.clipped()
.cornerRadius(50)
Text(username)
.bold()
.font(.system(size: 25))
.foregroundColor(.black)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
}
.padding(.top, 10)
}
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
ZStack {
Ellipse()
.fill(Color(red: 255 / 255, green: 211 / 255, blue: 138 / 255))
.frame(width: 50, height: 50)
Image(systemName: "chevron.left")
.foregroundColor(.black)
}
.padding(.leading, 20)
.padding(.top, 20)
}
HStack(alignment: .center) {
if username == wallet {
Button(action: {}, label: {
ZStack {
Ellipse()
.fill(Color(red: 255 / 255, green: 211 / 255, blue: 138 / 255))
.frame(width: 50, height: 50)
Image(systemName: "message")
.foregroundColor(.black)
}
.padding(.top, 20)
.padding(.trailing, 20)
})
}
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
//.navigationBarBackButtonHidden(true)
.navigationBarTitle("")
.navigationBarHidden(true)
//.navigationBarItems(leading: btnBack)
//.navigationBarTitle("", displayMode: .inline)
.onAppear{
loader()
accessToken()
}
VStack{
Spacer()
Button(action: {
accessToken()
if address == "" {
print("address = ''")
return
}
if price == 0 {
print("price = 0")
return
}
let fee = Double(price) / 20
guard let url = URL(string: "https://api-m.sandbox.paypal.com/v2/checkout/orders"),
let payload = """
{"intent": "CAPTURE",
"purchase_units": [{
"amount": {
"currency_code": "USD",
"value": "\(price)"
},
"payee": {
"email_address": "\(address)"
},
"payment_instruction": {
"disbursement_mode": "INSTANT",
"platform_fees": [{
"amount": {
"currency_code": "USD",
"value": "\(fee)"
},
"payee": {
"email_address": "<EMAIL>"
}
}]
}
}],
"application_context": {
"return_url": "https://google.com/",
"cancel_url": "https://github.com/"
}
}
""".data(using: .utf8) else
{
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("Bearer \(toke)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = payload
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else { print(error!.localizedDescription); return }
guard let data = data else { print("Empty data"); return }
if let str = String(data: data, encoding: .utf8) {
print(str)
}
let decoder = JSONDecoder()
let OnboardData = try? decoder.decode(Buyer.self, from: data)
OnboardId = OnboardData!.id
print(OnboardId)
OnboardSave = OnboardData!.links[1].href
print(OnboardSave)
DispatchQueue.main.async {
self.showUrl = true
}
}.resume()}, label: {
Text("Buy")
.foregroundColor(.black)
.font(.system(size: 30))
.frame(width: 300, height: 50)
.background(Color(red: 255 / 255, green: 211 / 255, blue: 138 / 255))
.cornerRadius(30)
})
}
.frame(maxHeight: .infinity)
.frame(maxWidth: .infinity)
}
.sheet(isPresented: $showUrl, onDismiss: {
guard let url = URL(string: "https://api-m.sandbox.paypal.com/v2/checkout/orders/\(self.OnboardId)/capture") else
{
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("Bearer \(toke)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else { print(error!.localizedDescription); return }
guard let data = data else { print("Empty data"); return }
if let str = String(data: data, encoding: .utf8) {
print(str)
}
}
.resume()
}) {
VStack {
NavigationView {
//WebView(url: OnboardSave)
WebView(url: OnboardSave//,
// allowedHosts: ["github", ".com"],
// forbiddenHosts: [".org", "google"],
// credential: URLCredential(user: "user", password: "<PASSWORD>", persistence: .none)
){ (onNavigationAction) in
switch onNavigationAction {
case .decidePolicy(let webView, let navigationAction, let policy):
print("WebView -> \(String(describing: webView.url)) -> decidePolicy navigationAction: \(navigationAction)")
switch policy {
case .cancel:
print("WebView -> \(String(describing: webView.url)) -> decidePolicy: .cancel")
showUrl = false
case .allow:
print("WebView -> \(String(describing: webView.url)) -> decidePolicy: .allow")
@unknown default:
print("WebView -> \(String(describing: webView.url)) -> decidePolicy: @unknown default")
}
case .didRecieveAuthChallenge(let webView, let challenge, let disposition, let credential):
print("WebView -> \(String(describing: webView.url)) -> didRecieveAuthChallange challenge: \(challenge.protectionSpace.host)")
print("WebView -> \(String(describing: webView.url)) -> didRecieveAuthChallange disposition: \(disposition.rawValue)")
if let credential = credential {
print("WebView -> \(String(describing: webView.url)) -> didRecieveAuthChallange credential: \(credential)")
}
case .didStartProvisionalNavigation(let webView, let navigation):
if String(describing: webView.url!.absoluteString).contains("github"){
print("WebView -> \(String(describing: webView.url!.absoluteString)) -> didReceiveServerRedirectForProvisionalNavigation: \(navigation)")
showUrl = false
}
case .didReceiveServerRedirectForProvisionalNavigation(let webView, let navigation):
if String(describing: webView.url!.absoluteString).contains("google"){
print("WebView -> \(String(describing: webView.url!.absoluteString)) -> didReceiveServerRedirectForProvisionalNavigation: \(navigation)")
showUrl = false
self.presentationMode.wrappedValue.dismiss()
}
case .didCommit(let webView, let navigation):
print("WebView -> \(String(describing: webView.url)) -> didCommit: \(navigation)")
case .didFinish(let webView, let navigation):
print("WebView -> \(String(describing: webView.url)) -> didFinish: \(navigation)")
case .didFailProvisionalNavigation(let webView, let navigation, let error):
print("WebView -> \(String(describing: webView.url)) -> didFailProvisionalNavigation: \(navigation)")
print("WebView -> \(String(describing: webView.url)) -> didFailProvisionalNavigation: \(error)")
case .didFail(let webView, let navigation, let error):
print("WebView -> \(String(describing: webView.url)) -> didFail: \(navigation)")
print("WebView -> \(String(describing: webView.url)) -> didFail: \(error)")
}
}
}
}
}
}
}
<file_sep>/point/TextBindingManager.swift
//
// TextBindingManager.swift
// point
//
// Created by <NAME> on 7/7/21.
//
import Foundation
class TextBindingManager: ObservableObject {
@Published var text = "" {
didSet {
if text.count > characterLimit && oldValue.count <= characterLimit {
text = oldValue
}
}
}
let characterLimit: Int
init(limit: Int = 1){
characterLimit = limit
}
}
<file_sep>/point/Send.swift
//
// Send.swift
// point
//
// Created by <NAME> on 7/3/21.
//
import SwiftUI
import FirebaseDatabase
struct Send: View {
//var wallet = "Harry"
@AppStorage("wallet") var wallet:String = ""
@AppStorage("showingSender") var showingSender: Bool = false
var ref = Database.database().reference()
@AppStorage("amount") var amount: Int = 0
@AppStorage("sending") var sending: Int = 0
@State var errYa = false
@State var notEnough = false
@State var digits = [Int]()
@State var address = ""
@State var badAddress = false
func load() {
ref.child("\(wallet)/points").observe(.value) {
(snapshot) in
let pop = snapshot.value as? Int
self.amount = pop ?? 0
}
}
var body: some View {
VStack {
if self.amount == 1 {
Text("1 point available")
.foregroundColor(Color.white)
.font(.system(size: 40, design: .rounded))
}
else {
Text("\(self.amount) points available")
.foregroundColor(Color.white)
.font(.system(size: 40, design: .rounded))
}
Spacer()
.frame(height: 20)
Text(String(digits.reduce(0, {$0*10 + $1})))
.foregroundColor(Color.white)
.padding()
.font(.system(size: 80, design: .rounded))
ForEach((0...2), id: \.self) { bruh in
HStack {
ForEach((1...3), id: \.self) { bruh2 in
Button(action: {
if digits.count < 7 {
digits.append((bruh * 3) + bruh2)
}
}, label: {
Text("\((bruh * 3) + bruh2)")
.foregroundColor(Color.white)
.padding(.leading, 40)
.padding(.trailing, 40)
.font(.system(size: 50, design: .rounded))
})
}
}
Spacer()
.frame(height: 30)
}
HStack {
Button(action: {
if digits.count > 0 {
if digits.count < 7 {
digits.append(0)
}
}
}, label: {
Text("0")
.foregroundColor(Color.white)
.padding(.leading, 40)
.padding(.trailing, 40)
.font(.system(size: 50, design: .rounded))
})
Button(action: {digits.popLast()}, label: {
Text("<")
.foregroundColor(Color.white)
.padding(.leading, 40)
.padding(.trailing, 40)
.font(.system(size: 50, design: .rounded))
})
}
Spacer()
.frame(height: 50)
Button (action: {
if digits.reduce(0, {$0*10 + $1}) != 0{
errYa = false
if (amount - digits.reduce(0, {$0*10 + $1})) >= 0 {
notEnough = false
sending = digits.reduce(0, {$0*10 + $1})
showingSender = true
} else {
print("not enough points")
notEnough = true
}
} else {
print("sending is 0")
errYa = true
}
}, label: {
Text("Confirm")
.bold()
.frame(width: 300 , height: 20, alignment: .center)
})
.padding()
.font(.system(size: 30, design: .rounded))
.background(Color(red: 255 / 255, green: 220 / 255, blue: 159 / 255))
.foregroundColor(.white)
.cornerRadius(30)
}
.onAppear{load()}
.sheet(isPresented: $showingSender) {
ZStack {
//Color(red: 255 / 255, green: 220 / 255, blue: 159 / 255)
Color(red: 255 / 255, green: 211 / 255, blue: 138 / 255)
VStack {
if sending == 1 {
Text("Sending 1 point")
.foregroundColor(Color.white)
.font(.system(size: 40, design: .rounded))
}
else {
Text("Sending \(sending) points")
.foregroundColor(Color.white)
.font(.system(size: 40, design: .rounded))
}
ZStack {
Rectangle()
.fill(Color.white)
.frame(width: 450, height: 50)
HStack{
Text("To")
.padding(.leading, 50)
.padding(.trailing, 10)
.font(.system(size: 20, design: .rounded))
TextField("username...", text: $address)
.padding()
.font(.system(size: 20, design: .rounded))
}
}
Button(action: {
if address != "" {
if address != wallet {
ref.child("\(address)/points").getData {
(error, snapshot) in
if let error = error {
print("Error getting data \(error)")
}
else if snapshot.exists() {
print("Got data \(snapshot.value!)")
}
else {
print("No data available")
}
let pop = snapshot.value as? Int
if pop != nil {
badAddress = false
ref.child("\(address)/points").setValue(pop! + self.sending)
ref.child("\(wallet)/points").setValue(self.amount - self.sending)
self.address = ""
self.digits = [Int]()
showingSender = false
}
else {
print("address does not exist")
badAddress = true
}
}
}
else {
print("address is your own")
}
} else {
print("address is nil")
//errYa = true
}
}, label: {
//Image(systemName: "paperplane")
Text("Send")
.bold()
.frame(width: 300 , height: 20, alignment: .center)
})
.padding()
.font(.system(size: 30, design: .rounded))
.background(Color(red: 255 / 255, green: 220 / 255, blue: 159 / 255))
.foregroundColor(.white)
.cornerRadius(30)
Spacer()
.frame(height: 450)
}
}.ignoresSafeArea()
}
}
}
struct Send_Previews: PreviewProvider {
static var previews: some View {
Send()
}
}
<file_sep>/point/Neumorphic.swift
//
// Neumorphic.swift
// point
//
// Created by <NAME> on 7/15/21.
//
import SwiftUI
struct Neumorphic: View {
var name: String
var width: CGFloat
var col = Color(red: 255 / 255, green: 211 / 255, blue: 138 / 255)
//Color(#colorLiteral(red: 0.7915348411, green: 0.8569207191, blue: 0.9852443337, alpha: 1))
var body: some View {
Text(self.name)
.foregroundColor(.black)
.font(.system(size:20, weight: .semibold, design: .rounded))
.frame(width: self.width, height: 60)
.background(
ZStack {
self.col
RoundedRectangle(cornerRadius: 16, style: .continuous)
.foregroundColor(.white)
.blur(radius: 4)
.offset(x:-8, y:-8)
RoundedRectangle(cornerRadius: 16, style: .continuous)
.fill(
LinearGradient(gradient: Gradient(colors: [self.col, Color.white]), startPoint: .topLeading, endPoint: .bottomTrailing)
)
.padding(2)
.blur(radius: 2)
}
)
.clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
.shadow(color: self.col, radius: 20, x: 20, y: 20)
.shadow(color: Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)), radius: 20, x: -20, y: -20)
}
}
<file_sep>/point/loginView.swift
//
// Login.swift
// point
//
// Created by <NAME> on 7/5/21.
//
import SwiftUI
import FirebaseDatabase
struct loginView: View {
var ref = Database.database().reference()
@AppStorage("wallet") var wallet:String = ""
@State var logUsername = ""
@State var logPassword = ""
var body: some View {
VStack {
Text("Log in")
.padding()
.font(.system(size: 50, design: .rounded))
TextField("Username", text: $logUsername)
.padding()
.font(.system(size: 20, design: .rounded))
SecureField("Password", text: $log<PASSWORD>)
.padding()
.font(.system(size: 20, design: .rounded))
Button(action: {
if logUsername != "" && logPassword != "" {
ref.child("\(logUsername)/password").getData {
(error, snapshot) in
if let error = error {
print("Error getting data \(error)")
}
else if snapshot.exists() {
print("Got data \(snapshot.value!)")
}
else {
print("No data available")
}
let pop = snapshot.value as? String
if pop == logPassword {
wallet = logUsername
UserDefaults.standard.set(self.wallet, forKey: "Wallet")
logUsername = ""
logPassword = ""
}
else {
print("\(logPassword) doesn't equal \(pop ?? "")")
}
}
}
}, label: {
Text("Continue")
.padding()
.font(.system(size: 20, design: .rounded))
.background(Color(red: 255 / 255, green: 158 / 255, blue: 0 / 255))
.foregroundColor(.white)
.cornerRadius(30)
})
Spacer()
}
}
}
<file_sep>/point/imagePicker.swift
//
// imagePicker.swift
// point
//
// Created by <NAME> on 7/13/21.
//
import SwiftUI
import PhotosUI
struct ImagePicker: UIViewControllerRepresentable {
@Binding var images: [UIImage]
@Binding var picker: Bool
func makeCoordinator() -> Coordinator {
return ImagePicker.Coordinator(imagePicker: self)
}
func makeUIViewController(context: Context) -> PHPickerViewController {
var config = PHPickerConfiguration()
// videos can be used too
config.filter = .images
// 0 = multiple selections
config.selectionLimit = 6
let picker = PHPickerViewController(configuration: config)
// assigning delegate
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {
}
class Coordinator: NSObject, PHPickerViewControllerDelegate {
var parent: ImagePicker
init(imagePicker: ImagePicker) {
parent = imagePicker
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
// closing picker
parent.picker.toggle()
for img in results {
if img.itemProvider.canLoadObject(ofClass: UIImage.self) {
img.itemProvider.loadObject(ofClass: UIImage.self) { image, err in
guard let image1 = image else {
print(err!)
return
}
// appending image
self.parent.images.append(image1 as! UIImage)
}
} else {
// cannot be loaded
print("Error: image cannot be loaded")
}
}
}
}
}
<file_sep>/point/Photo.swift
//
// Photo.swift
// point
//
// Created by <NAME> on 7/8/21.
//
//Copyright 2021
//
import SwiftUI
import PhotosUI
import FirebaseDatabase
import FirebaseStorage
struct Photo: View {
@AppStorage("zipcode") var zipcode: String = UserDefaults.standard.string(forKey: "Zipcode") ?? ""
@AppStorage("showingPhoto") var showingPhoto:Bool = false
@AppStorage("wallet") var wallet:String = ""
var ref = Database.database().reference()
@State var images: [UIImage] = []
@State var picker = false
@State var title = ""
@State var description = ""
var categories = ["Appliances", "Apps & Games", "Arts, Crafts, & Sewing", "Automotive Parts & Accessories", "Beauty & Personal Care",
"Books", "CDs & Vinyl", "Cell Phones & Accesories", "Clothing", "Shoes", "Jewlery", "Collectibles & Fine Art", "Computers", "Electronics", "Garden & Outdoor", "Grocery & Gourmet Food", "Handmade", "Health & Household", "Home & Kitchen", "Industrial & Scientific", "Luggage & Travel", "Movies & TV", "Musical Instruments", "Office Products",
"Pet Supplies", "Sports & Outdoors", "Tools & Home Improvement", "Toys & Games", "Video Games"]
@State var category = ""
@State var hashtags = ""
@State var price = ""
@State var count = 0
@AppStorage("showingCategory") var showingCategory = false
@State private var scrollViewContentOffset = CGFloat(0)
init() {
UITextView.appearance().backgroundColor = .clear
}
var body: some View {
ZStack {
Color(red: 255 / 255, green: 220 / 255, blue: 159 / 255)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
ScrollView {
VStack {
ZStack{
Rectangle()
.fill(Color(red: 255 / 255, green: 211 / 255, blue: 138 / 255))
.frame(maxWidth: .infinity, alignment: .center)
.frame(height: 100)
if !images.isEmpty {
ScrollView(.horizontal, showsIndicators: false, content: {
LazyHStack(spacing: 5) {
ForEach(images, id: \.self) { img in
Image(uiImage: img)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100)
.clipped()
.cornerRadius(10)
}
}
})
} else {
Image("pluscamera")
.resizable()
.scaledToFit()
.frame(width:25, height:25)
}
Button(action: {
images.removeAll()
picker.toggle()
}, label: {
Text("")
.frame(maxWidth: .infinity, alignment: .center)
.frame(height: 100)
})
}
//.padding(.top, 30)
VStack {
Text("Title")
.font(.system(size: 20))
.frame(maxWidth: .infinity, alignment: .leading)
.frame(height: 20)
.foregroundColor(.black)
TextField("", text: $title)
.font(.system(size: 20))
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(maxWidth: .infinity, alignment: .center)
}
.frame(maxWidth: .infinity, alignment: .center)
.padding()
VStack {
Text("Description")
.font(.system(size: 20))
.frame(maxWidth: .infinity, alignment: .leading)
.frame(height: 20)
.foregroundColor(.black)
ZStack(alignment: .topLeading) {
RoundedRectangle(cornerRadius: 8, style: .continuous)
.fill(Color.white)
if description.isEmpty {
Text("Add item color, style, condition, sizing, and any other important details.")
.foregroundColor(Color(UIColor.placeholderText))
.padding(.horizontal, 8)
.padding(.vertical, 12)
}
TextEditor(text: $description)
.padding(4)
}
.frame(maxWidth: .infinity, alignment: .center)
.frame(height: 300)
.font(.body)
}
.frame(maxWidth: .infinity, alignment: .center)
.padding()
//.cornerRadius(20)
VStack {
Text("Price")
.font(.system(size: 20))
.frame(maxWidth: .infinity, alignment: .leading)
.frame(height: 20)
.foregroundColor(.black)
HStack {
Text("$")
.font(.system(size: 20))
TextField("0", text: $price)
.font(.system(size: 20))
.keyboardType(.decimalPad)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(maxWidth: .infinity, alignment: .center)
}
}
.frame(maxWidth: .infinity, alignment: .center)
.padding()
//.cornerRadius(20)
VStack {
Button(action: {self.showingCategory.toggle()}, label: {
HStack {
Text("Category")
.font(.system(size: 20))
.foregroundColor(.black)
Spacer()
if category == "" {
Text("Choose")
.foregroundColor(Color.gray)
}
else {
Text(category)
.foregroundColor(Color.black)
}
}
.frame(maxWidth: .infinity, alignment: .center)
.frame(height: 20)
})
}
.frame(maxWidth: .infinity, alignment: .center)
.padding()
//.cornerRadius(20)
VStack {
Text("Zipcode")
.font(.system(size: 20))
.frame(maxWidth: .infinity, alignment: .leading)
.frame(height: 20)
.foregroundColor(.black)
TextField("0", text: $zipcode)
.font(.system(size: 20))
.keyboardType(.numberPad)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(maxWidth: .infinity, alignment: .center)
}
.frame(maxWidth: .infinity, alignment: .center)
.padding()
//.cornerRadius(20)
Spacer()
.frame(height: 10)
Button(action: {
if !images.isEmpty {
if description != "" {
if price != "" {
if category != "" {
if zipcode != "" {
if title != "" {
count = 1
let post1 = UUID()
let post2 = UUID()
for x in images {
if let imageData = x.jpegData(compressionQuality: 0.25) {
let storage = Storage.storage()
storage.reference().child("\(wallet)/\(post1)/\(count)").putData(imageData, metadata: nil) { (_, err) in
if err != nil {
print("an error occurred")
print(err ?? "")
} else {
print("image uploaded successfully")
}
}
} else {
print("couldnt unwrap image to data")
}
ref.child("\(wallet)/posts/\(post1)/title").setValue(title)
ref.child("\(wallet)/posts/\(post1)/price").setValue(Int(price))
ref.child("\(wallet)/posts/\(post1)/zipcode").setValue(Int(zipcode))
ref.child("\(wallet)/posts/\(post1)/description").setValue(description)
ref.child("\(wallet)/posts/\(post1)/image_\(count)").setValue("\(wallet)/\(post1)/\(count)")
ref.child("\(wallet)/posts/\(post1)/image_count").setValue(count)
ref.child("\(wallet)/posts/\(post1)/category").setValue(category)
count += 1
}
ref.child("\(category)/\(zipcode)/\(post2)").setValue("\(wallet)/posts/\(post1)")
images.removeAll()
description = ""
price = ""
category = ""
title = ""
self.showingPhoto = false
}
else {
print("title = ''")
}
}
else {
print("zipcode = ''")
}
}
else {
print("category = ''")
}
}
else {
print("price = nil")
}
}
else {
print("description = ''")
}
}
else {
print("images = empty")
}
}, label: {
Neumorphic(name: "Post", width: 300)
.padding()
})
//.cornerRadius(30)
}
.simultaneousGesture(
TapGesture()
.onEnded { _ in
UIApplication.shared.endEditing()
}
)
.sheet(isPresented: $picker) {
ImagePicker(images: $images, picker: $picker)
}
.sheet(isPresented: $showingCategory) {
ZStack {
Color(red: 255 / 255, green: 220 / 255, blue: 159 / 255)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
ScrollView{
Spacer()
.frame(height: 30)
ForEach(categories, id: \.self) { cat in
Button(action: {
category = cat
self.showingCategory.toggle()
}, label: {
Text(cat)
.font(.system(size: 20))
.frame(maxWidth: .infinity, alignment: .center)
.frame(height: 20)
.foregroundColor(.black)
})
.padding()
.font(.system(size: 20))
.background(Color(red: 255 / 255, green: 211 / 255, blue: 138 / 255))
.foregroundColor(.white)
//.cornerRadius(30)
}
}
}
}
}
}
}
}
extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
struct Photo_Previews: PreviewProvider {
static var previews: some View {
Photo()
}
}
<file_sep>/point/signupView.swift
//
// Signup.swift
// point
//
// Created by <NAME> on 7/5/21.
//
import SwiftUI
import FirebaseDatabase
struct signupView: View {
var ref = Database.database().reference()
@AppStorage("wallet") var wallet:String = ""
@State var fullName = ""
@State var email = ""
@State var username = ""
@State var password = ""
func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
public func isValidPassword(_ password: String) -> Bool {
let passwordRegex = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z!@#$%^&*()\\-_=+{}|?>.<,:;~`’]{8,}$"
return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: password)
}
func isValidInput(_ input:String) -> Bool {
let RegEx = "\\w{1,18}"
return NSPredicate(format:"SELF MATCHES %@", RegEx).evaluate(with: input)
}
var body: some View {
VStack {
Text("Sign up")
.padding()
.font(.system(size: 50, design: .rounded))
TextField("Full Name", text: $fullName)
.padding()
.font(.system(size: 20, design: .rounded))
TextField("Email", text: $email)
.padding()
.font(.system(size: 20, design: .rounded))
TextField("Username", text: $username)
.padding()
.font(.system(size: 20, design: .rounded))
SecureField("Password", text: $password)
.padding()
.font(.system(size: 20, design: .rounded))
Button(action: {
if fullName != "" && email != "" && username != "" && password != "" {
if isValidEmail(email) == true && isValidPassword(password) == true && isValidInput(username){
ref.child("\(username)/points").getData {
(error, snapshot) in
if let error = error {
print("Error getting data \(error)")
}
else if snapshot.exists() {
print("Got data \(snapshot.value!)")
}
else {
print("No data available")
}
let pop = snapshot.value as? Int
if pop != nil {
print("account already exists")
}
else {
ref.child("\(username)/points").setValue(0)
ref.child("\(username)/fullName").setValue(fullName)
ref.child("\(username)/email").setValue(email)
ref.child("\(username)/password").setValue(password)
wallet = username
UserDefaults.standard.set(self.wallet, forKey: "Wallet")
fullName = ""
email = ""
username = ""
password = ""
}
}
}
}
}, label: {
Text("Continue")
.padding()
.font(.system(size: 20, design: .rounded))
.background(Color(red: 255 / 255, green: 158 / 255, blue: 0 / 255))
.foregroundColor(.white)
.cornerRadius(30)
})
Spacer()
}
}
}
<file_sep>/point/PostView.swift
//
// PostView.swift
// point
//
// Created by <NAME> on 7/9/21.
//
import SwiftUI
import FirebaseStorage
import FirebaseDatabase
struct Post: Hashable {
var id = UUID()
var image: UIImage
var postNum: String
}
struct PostView: View {
var ref = Database.database().reference()
@AppStorage("showingPhoto") var showingPhoto = false
@AppStorage("wallet") var wallet:String = ""
@State var thumbnail = [Post]()
@State var adder = [String]()
@State var postsLen = 0
@State var firstLoad = true
//@State var firstLoad = true
var twoColumnGrid = [GridItem(.flexible()), GridItem(.flexible())]
func loader() {
ref.child("\(wallet)/posts").observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
if adder.contains("\(wallet)/posts/\(key)") {
print("already loaded")
}
else {
ref.child("\(wallet)/posts/\(key)/image_1").getData {
(err, snapshot) in
let pop = snapshot.value as? String
if pop != nil {
Storage.storage().reference().child("\(pop!)").getData(maxSize: 1 * 1024 * 1024) {
(imageData, err) in
if err != nil {
print("error downloading image")
} else {
if let imageData = imageData {
self.thumbnail.insert(Post(image: UIImage(data: imageData)!, postNum: "\(wallet)/posts/\(key)"), at: 0)
self.adder.append("\(wallet)/posts/\(key)")
} else {
print("couldn't unwrap")
}
}
}
}
}
}
}
})
}
var body: some View {
VStack{
Spacer()
.frame(height: 30)
Button(action: {self.showingPhoto = true}, label: {
Neumorphic(name: "List an item", width: 350)
.padding()
})
ScrollView {
Spacer()
.frame(height: 30)
Text("Your Listings")
.font(.system(size: 25))
.frame(width: 350 , height: 20, alignment: .leading)
.foregroundColor(.black)
Spacer()
.frame(height: 10)
if thumbnail == [Post]() {
Text("")
}
else {
LazyVGrid(columns: twoColumnGrid) {
ForEach(thumbnail, id: \.self) { thing in
NavigationLink(destination: PostSubView(username: wallet,firstPhoto: thing.image, name: thing.postNum)) {
Image(uiImage: thing.image)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 190, height: 190, alignment: .topLeading)
.clipped()
.cornerRadius(10)
}
}
}
}
}
.padding(.top, 1)
.sheet(isPresented: $showingPhoto, onDismiss: {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
loader()
}
}) {
Photo()
}
}
.onAppear{
if firstLoad == true {
loader()
firstLoad = false
}
}
}
}
struct PostView_Previews: PreviewProvider {
static var previews: some View {
PostView()
}
}
<file_sep>/point/ContentView.swift
//
// ContentView.swift
// point
//
// Created by <NAME> on 7/3/21.
//
import SwiftUI
import FirebaseDatabase
struct ContentView: View {
var ref = Database.database().reference()
@AppStorage("zipcode") var zipcode = UserDefaults.standard.string(forKey: "Zipcode") ?? ""
@AppStorage("wallet") var wallet = UserDefaults.standard.string(forKey: "Wallet") ?? ""
@AppStorage("showingSender") var showingSender = false
@AppStorage("sending") var sending = 0
@AppStorage("amount") var amount = 0
@State var tabSelection: Tabs = .tab1
@State var currentColor = Color.black
@State var currentTabBarColor = Color.black
var body: some View {
if wallet != "" {
NavigationView {
TabView(selection: $tabSelection) {
ZStack {
Color(#colorLiteral(red: 0.992025435, green: 0.9831623435, blue: 0.8817279935, alpha: 1))
ExploreView()
}
.ignoresSafeArea()
.tabItem {
Image(systemName: "safari")
}
.tag(Tabs.tab1)
ZStack {
Color(#colorLiteral(red: 0.992025435, green: 0.9831623435, blue: 0.8817279935, alpha: 1))
.frame(maxWidth: .infinity, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
PostView()
}
.navigationBarTitle("")
.navigationBarHidden(true)
.tabItem {
Image(systemName: "camera")
}
.tag(Tabs.tab2)
ZStack {
Color(red: 255 / 255, green: 211 / 255, blue: 138 / 255)
Send()
.accentColor(.black)
}
.ignoresSafeArea()
.navigationBarTitle("")
.navigationBarHidden(true)
.tabItem {
Image(systemName: "arrow.left.arrow.right")
}
.tag(Tabs.tab3)
ZStack {
Color(#colorLiteral(red: 0.992025435, green: 0.9831623435, blue: 0.8817279935, alpha: 1))
Text("messages")
}
.ignoresSafeArea()
.tabItem {
Image(systemName: "message")
}
.tag(Tabs.tab4)
accountView()
.tabItem {
Image(systemName: "gearshape")
}
.tag(Tabs.tab5)
}
.onAppear() {
UITabBar.appearance().barTintColor = UIColor(Color(red: 255 / 255, green: 220 / 255, blue: 159 / 255))
//let appearance = UITabBarAppearance()
UITabBar.appearance().layer.borderWidth = 0.0
UITabBar.appearance().clipsToBounds = true
//appearance.configureWithTransparentBackground()
//UITabBar.appearance().standardAppearance = appearance
}
.onChange(of: tabSelection) { newValue in
if tabSelection == .tab3 {
currentColor = Color.white
}
else {
currentColor = Color.black
}
}
.accentColor(currentColor)
//.navigationBarTitle(returnNaviBarTitle(tabSelection: self.tabSelection))
}
}
else {
NavigationView {
ZStack {
Image("clothes")
.resizable()
.scaledToFill()
.edgesIgnoringSafeArea(.all)
VStack {
Image("logo")
.resizable()
.scaledToFit()
.frame(width:160, height:150)
NavigationLink(destination: signupView(), label: {
Text("Sign up")
.frame(width: 300 , height: 20, alignment: .center)
})
.padding()
.font(.system(size: 20, design: .rounded))
.background(Color(red: 255 / 255, green: 211 / 255, blue: 138 / 255))
.foregroundColor(.white)
.cornerRadius(30)
NavigationLink(destination: loginView(), label: {
Text("Log in")
.frame(width: 300 , height: 20, alignment: .center)
})
.padding()
.font(.system(size: 20, design: .rounded))
.background(Color.gray)
.foregroundColor(.white)
.cornerRadius(30)
Spacer()
}
.padding(30)
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
}
enum Tabs{
case tab1, tab2, tab3, tab4, tab5
}
func returnNaviBarTitle(tabSelection: Tabs) -> String{//this function will return the correct NavigationBarTitle when different tab is selected.
switch tabSelection{
case .tab1: return "Explore"
case .tab2: return "Post"
case .tab3: return ""
case .tab4: return "Message"
case .tab5: return "Account"
}
}
}
struct ColorPreferenceKey: PreferenceKey {
static var defaultValue: Color = Color.clear
static func reduce(value: inout Color, nextValue: () -> Color) {
value = nextValue()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
<file_sep>/point/pointApp.swift
//
// pointApp.swift
// point
//
// Created by <NAME> on 7/3/21.
//
import SwiftUI
import Firebase
@main
struct pointApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
<file_sep>/point/accountView.swift
//
// accountView.swift
// point
//
// Created by <NAME> on 7/5/21.
//
import SwiftUI
import FirebaseDatabase
import FirebaseStorage
struct accountView: View {
var ref = Database.database().reference()
@AppStorage("wallet") var wallet:String = ""
@State private var isShowPhotoLibrary = false
@State private var image = UIImage(imageLiteralResourceName: "tab")
@State var check = true
func load() {
Storage.storage().reference().child("\(wallet)/pfp").getData(maxSize: 1 * 1024 * 1024) {
(imageData, err) in
if err != nil {
print("error downloading image")
} else {
if let imageData = imageData {
self.image = UIImage(data: imageData)!
} else {
print("couldn't unwrap")
}
}
}
}
var body: some View {
VStack(alignment: .center) {
HStack {
Button(action: {
self.isShowPhotoLibrary = true
}) {
Image(uiImage: self.image)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100)
.clipped()
.cornerRadius(50)
}
Text(wallet)
.font(.system(size: 40, design: .rounded))
}
Button(action: {
wallet = ""
}, label: {
Neumorphic(name: "Log out", width: 300)
.padding()
})
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color(#colorLiteral(red: 0.992025435, green: 0.9831623435, blue: 0.8817279935, alpha: 1)))
.edgesIgnoringSafeArea(.all)
.sheet(isPresented: $isShowPhotoLibrary) {
SingleImagePicker(sourceType: .photoLibrary, selectedImage: self.$image)
}
.onChange(of: image, perform: { value in
if check == false {
ref.child("\(wallet)/pfp").setValue(true)
if let imageData = image.jpegData(compressionQuality: 0.25) {
let storage = Storage.storage()
storage.reference().child("\(wallet)/pfp").putData(imageData, metadata: nil) { (_, err) in
if err != nil {
print("an error occurred")
print(err ?? "")
} else {
print("image uploaded successfully")
}
}
}
}
})
.onAppear{
if check == true {
load()
check = false
}
}
}
}
struct accountView_Previews: PreviewProvider {
static var previews: some View {
accountView()
}
}
|
c7f31eb35a67fd58d5b85d036d47af389324b3e6
|
[
"Swift"
] | 13
|
Swift
|
egdemems/Aurum
|
84210e85ad3994a9604c302599872d812ba634e3
|
10392f827476fafffd2ed0cd9318d0a921878c04
|
refs/heads/master
|
<repo_name>mohitss/Coding_Practice<file_sep>/test.c
#include<stdio.h>
int int main() {
printf("Hello World22\n");
return 0;
}
|
3065c0208938f28672cdf1abc548523fce3b30b8
|
[
"C"
] | 1
|
C
|
mohitss/Coding_Practice
|
4026c2a89f3a45ce41feb932d4eaaab15abd2a9f
|
18db028ab12a3228ae9887fb23f3f2a0cee099c7
|
refs/heads/master
|
<repo_name>AlexandrMardanov/react-calculator<file_sep>/src/react/commonConfig.js
export const commonConfig = {
currencySignes: {
GBP: '£',
AUD: 'A$',
EUR: '€',
USD: '$'
},
showFields: {
levels: true,
subjects: true,
currency: true,
promo: true,
discountText: true,
promoChecked: true,
numPagesWordsView: false
},
defaultDoctype: 0,
siteCurrency: 'USD', /* from site config */
labels: {
title: 'CALCULATE PRICE',
doctype: 'Type of document',
numPages: 'Number of ',
numPapers: 'Number of papers',
urgency: 'Urgency',
subject: 'Subject',
level: 'Level',
promoText: `I'm a new customer `,
total: 'Total price: ',
proceedText: 'Proceed',
discountText: 'discount applies to order over ',
currencyLabel: ''
},
discountFromUSDCents: 3000,
getDoctypeIdsWithoutDiscount: [1],
getDoctypeIdsWithoutCategory: [2],
getPageLabels: {
1: 'Slide',
2: 'Question'
},
getDoctypeIdsWithPapers: [2],
getSpecialPrices: {
2: { value: 10, type: 1 }
}
}
<file_sep>/src/react/components/DiscountText.js
import React from 'react'
import PropTypes from 'prop-types'
const DiscountText = props => {
const {
currencyRates,
currency,
currencySign,
discountText,
discountFromUSDCents
} = props
const currencyCorrelation = currencyRates[currency]
const discountTextPrice = `${currencySign}${(Math.round(discountFromUSDCents * currencyCorrelation) / 100).toFixed(2)}`
return (
<div className='Calculator__row Calculator__row--discount-text'>
{discountText} {discountTextPrice}
</div>
)
}
DiscountText.propTypes = {
currencyRates: PropTypes.object.isRequired,
currency: PropTypes.string.isRequired,
discountText: PropTypes.string.isRequired,
currencySign: PropTypes.string.isRequired,
discountFromUSDCents: PropTypes.number.isRequired
}
export default DiscountText
<file_sep>/webpack/webpack_modules/html.js
// ------------------------------------
// Подробнее: https://github.com/webpack-contrib/html-loader
// Подробнее: https://github.com/jantimon/html-webpack-plugin
// ------------------------------------
import { resolve } from 'path'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import HtmlWebpackInlineSourcePlugin from 'html-webpack-inline-source-plugin'
import fs from 'fs'
const path = resolve('src/templates')
const templates = fs.readdirSync(path)
const templatesConfig = templates.map(item => {
return new HtmlWebpackPlugin({
template: resolve(`src/templates/${item}`),
filename: resolve(`build/${item}`),
chunks: ['main', 'vendor', 'runtime'],
inject: true,
inlineSource: 'runtime'
})
})
export default () => ({
plugins: [...templatesConfig, new HtmlWebpackInlineSourcePlugin()]
})
<file_sep>/src/react/components/Levels.js
import React from 'react'
import PropTypes from 'prop-types'
import Select from 'react-select'
import '../react-select.scss'
const Level = props => {
const { doctype, levels, handleLevelChange, level, levelLabel } = props
return (
<div className='Calculator__row Calculator__row--level'>
<label className='Calculator__label'>{levelLabel}</label>
<Select
value={level}
clearable={false}
searchable
valueKey='id'
labelKey='name'
onChange={handleLevelChange}
options={levels[doctype]}
/>
</div>
)
}
Level.propTypes = {
levels: PropTypes.object.isRequired,
level: PropTypes.number.isRequired,
doctype: PropTypes.number.isRequired,
levelLabel: PropTypes.string.isRequired,
handleLevelChange: PropTypes.func.isRequired
}
export default Level
<file_sep>/src/react/components/Promo.js
import React from 'react'
import PropTypes from 'prop-types'
const Promo = props => {
const {
handlePromoChange,
promoCodes,
currencySign,
currencyRates,
currency,
promoChecked,
promoText
} = props
const discountValue = promoCodes[0].value
const discountType = +promoCodes[0].type
const discount = (discountType === 0)
? `${discountValue}% OFF`
: `${currencySign}${(discountValue * currencyRates[currency]).toFixed(2)} OFF`
return (
<div className='Calculator__row Calculator__row--promo'>
<input
type='checkbox'
checked={promoChecked}
id='Calculator__promo'
onChange={handlePromoChange} />
<label htmlFor='Calculator__promo'>
{promoText}
<span className='Calculator__discount-value'> ({discount})</span>
</label>
</div>
)
}
Promo.propTypes = {
promoCodes: PropTypes.array.isRequired,
currencySign: PropTypes.string.isRequired,
currency: PropTypes.string.isRequired,
promoText: PropTypes.string.isRequired,
currencyRates: PropTypes.object.isRequired,
handlePromoChange: PropTypes.func.isRequired,
promoChecked: PropTypes.bool.isRequired
}
export default Promo
<file_sep>/src/react/components/Doctypes.js
import React from 'react'
import PropTypes from 'prop-types'
import sortDoctypes from '../../utils/sortDoctypes'
import Select from 'react-select'
import '../react-select.scss'
const Doctype = props => {
const { doctypes, doctype, handleDoctypeChange, doctypeLabel } = props
return (
<div className='Calculator__row Calculator__row--doctype'>
<label className='Calculator__label'>{doctypeLabel}</label>
<Select
value={doctype}
clearable={false}
searchable
valueKey='id'
labelKey='name'
onChange={handleDoctypeChange}
options={sortDoctypes(doctypes)}
/>
</div>
)
}
Doctype.propTypes = {
doctypes: PropTypes.array.isRequired,
doctype: PropTypes.number.isRequired,
doctypeLabel: PropTypes.string.isRequired,
handleDoctypeChange: PropTypes.func.isRequired
}
export default Doctype
<file_sep>/src/react/components/NumPapers.js
import React from 'react'
import PropTypes from 'prop-types'
import Select from 'react-select'
import '../react-select.scss'
const numPapers = props => {
const { numPapers, handleNumPapersChange, numPapersLabel } = props
const numPapersOptions = []
for (let i = 1; i <= 20; i++) {
numPapersOptions.push(
{
value: i,
name: `${i} ${'paper'}${(i !== 1 ? 's' : '')}`
}
)
}
return (
<div className='Calculator__row Calculator__row--numPapers'>
<label className='Calculator__label'>{numPapersLabel}</label>
<Select
value={numPapers}
matchProp='value'
matchPos='start'
clearable={false}
searchable
valueKey='value'
labelKey='name'
onChange={handleNumPapersChange}
options={numPapersOptions}
/>
</div>
)
}
numPapers.propTypes = {
numPapers: PropTypes.number.isRequired,
numPapersLabel: PropTypes.string.isRequired,
handleNumPapersChange: PropTypes.func.isRequired
}
export default numPapers
<file_sep>/src/react/containers/Calculator.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Loader from '../components/Loader'
import Doctypes from '../components/Doctypes'
import NumPages from '../components/NumPages'
import NumPapers from '../components/NumPapers'
import Urgency from '../components/Urgency'
import Subjects from '../components/Subjects'
import Levels from '../components/Levels'
import Currency from '../components/Currency'
import Total from '../components/Total'
import Proceed from '../components/Proceed'
import Promo from '../components/Promo'
import DiscountText from '../components/DiscountText'
import getCookie from '../../utils/getCookie'
class Calculator extends Component {
static propTypes = {
config: PropTypes.shape({
currencySignes: PropTypes.object.isRequired,
showFields: PropTypes.object.isRequired,
defaultDoctype: PropTypes.number.isRequired,
siteCurrency: PropTypes.string.isRequired,
labels: PropTypes.object.isRequired,
getDoctypeIdsWithoutDiscount: PropTypes.array.isRequired,
getDoctypeIdsWithoutCategory: PropTypes.array.isRequired,
getDoctypeIdsWithPapers: PropTypes.array.isRequired,
getPageLabels: PropTypes.object.isRequired,
getSpecialPrices: PropTypes.object.isRequired
}),
api: PropTypes.array
}
state = {
loading: true,
doctype: 0,
numPagesLimit: 0,
urgency: 0,
subject: 0,
level: 0,
price: 0,
numPages: 1,
numPapers: 1,
currency: 'USD',
currencySign: this.props.config.currencySignes['USD'],
pagesType: 'page',
promoChecked: this.props.config.showFields.promoChecked,
discount: 1
}
componentDidMount = () => {
this.API = {
doctypes: this.props.api[0].result,
urgencies: this.props.api[1].result,
prices: this.props.api[2].result,
levels: this.props.api[3].result,
limits: this.props.api[4].result,
currencyRates: this.props.api[5].result,
subjects: this.props.api[6].result,
isAuthorized: this.props.api[7].result,
getDefaultValues: this.props.api[8].result,
getFirstTimePromoCodes: this.props.api[9].result
}
const promoDiscount = this.API.getFirstTimePromoCodes[0].value
const defaultCurrency = this.API.getDefaultValues.defaultCurrency
this.setState({
doctype: this.props.config.defaultDoctype,
currency: getCookie('currency') || defaultCurrency,
discount: (this.state.promoChecked && !this.API.isAuthorized)
? (100 - promoDiscount) / 100
: 1
}, () => {
const { doctype, currency } = this.state
this.setState({
urgency: +this.API.urgencies[doctype][0].id,
level: +this.API.levels[doctype][0].id,
currencySign: this.props.config.currencySignes[currency]
}, () => {
const { doctype, level, urgency } = this.state
this.setState({
price: +this.API.prices[doctype][level][urgency],
numPagesLimit: +this.API.limits[doctype][level][urgency]
}, () => {
this.setState({ loading: false })
})
})
})
}
handleDoctypeChange = (selectedOption) => {
this.setState({
doctype: +selectedOption.id,
numPages: 1,
numPapers: 1
}, () => {
const { doctype } = this.state
this.setState({
urgency: +this.API.urgencies[doctype][0].id,
level: +this.API.levels[doctype][0].id,
pagesType: (doctype in this.props.config.getPageLabels)
? this.props.config.getPageLabels[doctype]
: 'page'
}, () => {
const { level, urgency, doctype } = this.state
this.setState({
price: +this.API.prices[doctype][level][urgency],
numPagesLimit: +this.API.limits[doctype][level][urgency]
})
})
})
}
handleNumPagesChange = (selectedOption) => {
this.setState({
numPages: +selectedOption.value
})
}
handleUrgencyChange = (selectedOption) => {
this.setState({
urgency: +selectedOption.id
}, () => {
const { doctype, level, urgency } = this.state
this.setState({
numPagesLimit: +this.API.limits[doctype][level][urgency],
price: +this.API.prices[doctype][level][urgency]
}, () => {
const { numPages, numPagesLimit } = this.state
this.setState({
numPages: numPages > numPagesLimit
? numPagesLimit
: numPages
})
})
})
}
handleLevelChange = (selectedOption) => {
this.setState({
level: +selectedOption.id
}, () => {
const { doctype, level, urgency } = this.state
this.setState({
price: +this.API.prices[doctype][level][urgency],
numPagesLimit: +this.API.limits[doctype][level][urgency]
})
})
}
handleSubjectsChange = (selectedOption) => {
this.setState({
subject: selectedOption ? +selectedOption.value : 0
}, () => {
const { subject, doctype, level, urgency } = this.state
const originalPrice = +this.API.prices[doctype][level][urgency]
for (let key in this.props.config.getSpecialPrices) {
if (+key === subject) {
let value = this.props.config.getSpecialPrices[key].value
let type = this.props.config.getSpecialPrices[key].type
this.setState({
price: type === 1
? originalPrice + value
: originalPrice + Math.round(originalPrice * value) / 100
})
break
} else {
this.setState({
price: originalPrice
})
}
}
})
}
handleCurrencyChange = (e) => {
if (e.target.className === 'Calculator__currency-item') {
this.setState({
currency: e.target.innerText,
currencySign: this.props.config.currencySignes[e.target.innerText]
})
}
}
handlePromoChange = () => {
this.setState({
promoChecked: !this.state.promoChecked
}, () => {
const promoDiscount = this.API.getFirstTimePromoCodes[0].value
this.setState({
discount: (this.state.promoChecked && !this.API.isAuthorized)
? (100 - promoDiscount) / 100
: 1
})
})
}
handleNumPapersChange = (selectedOption) => {
this.setState({
numPapers: +selectedOption.value
})
}
render() {
const {
doctype,
numPagesLimit,
level,
urgency,
subject,
loading,
currency,
currencySign,
price,
numPages,
pagesType,
discount,
promoChecked,
numPapers
} = this.state
const {
config
} = this.props
if (loading) return <Loader />
return (
<div className='Calculator'>
<div className='Calculator__title'>{config.labels.title}</div>
<Doctypes
doctypes={this.API.doctypes}
doctype={doctype}
doctypeLabel={config.labels.doctype}
handleDoctypeChange={this.handleDoctypeChange}
/>
<NumPages
numPagesLimit={numPagesLimit}
numPages={numPages}
pagesType={pagesType}
numPagesWordsView={config.showFields.numPagesWordsView}
numPagesLabel={config.labels.numPages}
handleNumPagesChange={this.handleNumPagesChange}
/>
{
config.getDoctypeIdsWithPapers.includes(doctype) &&
<NumPapers
numPapers={numPapers}
numPapersLabel={config.labels.numPapers}
handleNumPapersChange={this.handleNumPapersChange}
/>
}
<Urgency
urgencies={this.API.urgencies}
doctype={doctype}
urgency={urgency}
urgencyLabel={config.labels.urgency}
handleUrgencyChange={this.handleUrgencyChange}
/>
{
config.showFields.subjects &&
!config.getDoctypeIdsWithoutCategory.includes(doctype) &&
<Subjects
subjects={this.API.subjects}
subject={subject}
subjectLabel={config.labels.subject}
handleSubjectsChange={this.handleSubjectsChange}
/>
}
{
config.showFields.levels &&
this.API.levels[doctype][0].name.length > 0 &&
<Levels
levels={this.API.levels}
level={level}
levelLabel={config.labels.level}
doctype={doctype}
handleLevelChange={this.handleLevelChange}
/>
}
{
!this.API.isAuthorized &&
config.showFields.promo &&
!config.getDoctypeIdsWithoutDiscount.includes(doctype) &&
<Promo
promoCodes={this.API.getFirstTimePromoCodes}
currencySign={currencySign}
currency={currency}
promoText={config.labels.promoText}
currencyRates={this.API.currencyRates}
handlePromoChange={this.handlePromoChange}
promoChecked={promoChecked}
/>
}
{
config.showFields.currency &&
<Currency
currency={currency}
currencySignes={config.currencySignes}
handleCurrencyChange={this.handleCurrencyChange}
currencyLabel={config.labels.currencyLabel}
/>
}
<div className='Calculator__row Calculator__row--bottom'>
<Total
currencyRates={this.API.currencyRates}
currency={currency}
currencySign={currencySign}
numPages={numPages}
numPapers={numPapers}
price={price}
siteCurrency={config.siteCurrency}
discount={discount}
totalLabel={config.labels.total}
doctype={doctype}
discountFromUSDCents={config.discountFromUSDCents}
getDoctypeIdsWithoutDiscount={config.getDoctypeIdsWithoutDiscount}
/>
<Proceed
doctype={doctype}
level={level}
urgency={urgency}
subject={subject}
numPages={numPages}
numPapers={numPapers}
levels={this.API.levels}
currency={currency}
promoChecked={promoChecked}
proceedText={config.labels.proceedText}
promoCodes={this.API.getFirstTimePromoCodes}
showFields={config.showFields}
getDoctypeIdsWithPapers={config.getDoctypeIdsWithPapers}
getDoctypeIdsWithoutCategory={config.getDoctypeIdsWithoutCategory}
getDoctypeIdsWithoutDiscount={config.getDoctypeIdsWithoutDiscount}
/>
</div>
{
config.showFields.discountText &&
!this.API.isAuthorized &&
config.showFields.promo &&
!config.getDoctypeIdsWithoutDiscount.includes(doctype) &&
<DiscountText
currencyRates={this.API.currencyRates}
currency={currency}
currencySign={currencySign}
discountText={config.labels.discountText}
discountFromUSDCents={config.discountFromUSDCents}
/>
}
</div >
)
}
}
export default Calculator
<file_sep>/src/main.js
import React from 'react'
import { render } from 'react-dom'
import { hot } from 'react-hot-loader'
import { api } from './api'
import Calculator from './react/containers/Calculator'
import { commonConfig } from './react/commonConfig'
import './react/styles.scss'
hot(module)(Calculator)
render(<Calculator config={commonConfig} api={api} />,
document.querySelector('#root'))
<file_sep>/src/utils/extend.js
const extend = (commonConfig, customConfig) => {
for (let key in customConfig) {
if (typeof customConfig[key] === 'object') {
for (let subkey in customConfig[key]) {
commonConfig[key][subkey] = customConfig[key][subkey]
}
} else {
commonConfig[key] = customConfig[key]
}
}
return commonConfig
}
export default extend
<file_sep>/src/react/components/Total.js
import React from 'react'
import PropTypes from 'prop-types'
const Total = props => {
const {
currencyRates,
price,
discount,
currency,
currencySign,
numPages,
siteCurrency,
totalLabel,
numPapers,
getDoctypeIdsWithoutDiscount,
doctype,
discountFromUSDCents
} = props
const priceUSDcents = Math.round(price * 100 / currencyRates[siteCurrency])
const discountValue = priceUSDcents * numPages * numPapers > discountFromUSDCents &&
!getDoctypeIdsWithoutDiscount.includes(doctype)
? discount
: 1
const priceValue = (
<span className='Calculator__total--value'>
{currencySign}
{(Math.round(priceUSDcents * currencyRates[currency]) * discountValue * numPages * numPapers / 100).toFixed(2)}
</span>
)
const oldPriceValue = (
<span className='Calculator__total--old-price'>
{currencySign}
{(Math.round(priceUSDcents * currencyRates[currency]) * numPages * numPapers / 100).toFixed(2)}
</span>
)
return (
<div className='Calculator__prices'>
<div className='Calculator__total'>
<span className='Calculator__total--label'>{totalLabel}</span>
<span className='Calculator__total--value'>
{
discountValue === 1
? priceValue
: <React.Fragment>
{oldPriceValue} {priceValue}
</React.Fragment>
}
</span>
</div>
</div>
)
}
Total.propTypes = {
price: PropTypes.number.isRequired,
currencyRates: PropTypes.object.isRequired,
currency: PropTypes.string.isRequired,
currencySign: PropTypes.string.isRequired,
siteCurrency: PropTypes.string.isRequired,
totalLabel: PropTypes.string.isRequired,
numPages: PropTypes.number.isRequired,
numPapers: PropTypes.number.isRequired,
discount: PropTypes.number.isRequired,
doctype: PropTypes.number.isRequired,
discountFromUSDCents: PropTypes.number.isRequired,
getDoctypeIdsWithoutDiscount: PropTypes.array.isRequired
}
export default Total
<file_sep>/src/react/components/Urgency.js
import React from 'react'
import PropTypes from 'prop-types'
import Select from 'react-select'
import '../react-select.scss'
const Urgency = props => {
const { urgencies, doctype, urgency, handleUrgencyChange, urgencyLabel } = props
return (
<div className='Calculator__row Calculator__row--urgency'>
<label className='Calculator__label'>{urgencyLabel}</label>
<Select
value={urgency}
clearable={false}
searchable
valueKey='id'
labelKey='name'
onChange={handleUrgencyChange}
options={urgencies[doctype]}
/>
</div>
)
}
Urgency.propTypes = {
urgencies: PropTypes.object.isRequired,
doctype: PropTypes.number.isRequired,
urgency: PropTypes.number.isRequired,
handleUrgencyChange: PropTypes.func.isRequired,
urgencyLabel: PropTypes.string.isRequired
}
export default Urgency
<file_sep>/README.md
# react-calculator
### Demo
https://alexandrmardanov.github.io/react-calculator/build/
<file_sep>/src/react/components/Currency.js
import React from 'react'
import PropTypes from 'prop-types'
const Currency = props => {
const { currency, handleCurrencyChange, currencySignes, currencyLabel } = props
const currencyNames = Object.keys(currencySignes)
return (
<div className='Calculator__row Calculator__row--currency'>
<label className='Calculator__label'>{currencyLabel}</label>
<div
className='Calculator__currency'
onClick={handleCurrencyChange}>
{currencyNames.map((item, index) => {
const activeClass = currency === item ? ' active' : ''
return <span
className={`Calculator__currency-item${activeClass}`}
key={index}>{item}</span>
})}
</div>
</div>
)
}
Currency.propTypes = {
currency: PropTypes.string.isRequired,
currencyLabel: PropTypes.string.isRequired,
handleCurrencyChange: PropTypes.func.isRequired,
currencySignes: PropTypes.object.isRequired
}
export default Currency
|
97dd84d1bc2e1a5daa9280b36ef7dac70075edaa
|
[
"JavaScript",
"Markdown"
] | 14
|
JavaScript
|
AlexandrMardanov/react-calculator
|
da7bd3b7fdfa201260e970c341680e273bc30981
|
29ce5a7ec38bd825c81328c024468d70e5eb2877
|
refs/heads/master
|
<repo_name>mazhurin/LifeExpectancy<file_sep>/README.md
# LifeExpectancy
Life Expectancy Calculator
## Description
Life expectancy is a statistical measure of how long an organism may live, based on the year of their birth, their current age and other demographic factors including sex.
This Life expectancy calculator is base on the data published by World Health Organization
## Dataset
You can find the dataset [here](http://apps.who.int/gho/data/node.main.688?lang=en)
## Online Calculator
You can test the calculator online [here](https://greymemory.shinyapps.io/LifeExpectancy/)
## Under the hood
The calcularor is building a linear model using year as a predictor and life expectancy as an outcome.
The data for the model is filtered by selected country and sex.
<file_sep>/server.R
library(shiny)
# Life expectancy calculator.
#http://apps.who.int/gho/data/node.main.688?lang=en
# load the data
x <- read.csv("data.csv", header = TRUE)
# factorize Country column
x$Country <- as.factor(x$Country)
calculate_expectancy <- function(country, year, sex)
{
if(! country %in% levels(x$Country))
return (0)
f <- x[x$Country == country,]
if(length(f) <= 0)
return (0.0)
if (sex == 1)
fit <- lm(Male~Year, data = f)
else
fit <- lm(Female~Year, data = f)
new <- data.frame(Year = year)
return (predict(fit, newdata = new))
}
shinyServer(function(input, output) {
expectancy <- reactive({
calculate_expectancy(input$country, as.numeric(input$year), as.numeric(input$sex))
})
output$result <- renderText({
paste(format(round(expectancy(), 1), nsmall = 1), " years." )
#expectancy
})
output$resultYear <- renderText({
paste(format(round(input$year + expectancy(),0), nsmall = 0))
})
output$resultLeft <- renderText({
paste(format(round(input$year + expectancy() - as.numeric(format(Sys.Date(), "%Y")), 1), nsmall = 1),
" years.")
})
})<file_sep>/ui.R
library(shiny)
# Life expectancy calculator.
#http://apps.who.int/gho/data/node.main.688?lang=en
# load the data
x <- read.csv("data.csv", header = TRUE)
# factorize Country column
x$Country <- as.factor(x$Country)
# Define UI for application that plots random distributions
shinyUI(pageWithSidebar(
# Application title
headerPanel("Life expectancy calculator."),
# Sidebar with a slider input for number of observations
sidebarPanel(
selectizeInput("country", label = h3("Select your country"),
choices = as.character(levels(x$Country)), selected = 33),
sliderInput("year",
"Your were born in :",
min = 1960,
max = 1999,
value = 1971),
radioButtons("sex", label = h3("Your sex is:"),
choices = list("Male" = 1,
"Female" = 2),selected = 2)
),
# Show a plot of the generated distribution
mainPanel(
h3("Life expectancy is a statistical measure of how long an organism may live, based on the year of their birth, their current age and other demographic factors including sex."),
h4("This Life expectancy calculator is base on the data published by World Health Organization"),
h4("You can find the dataset ", a("here.", href="http://apps.who.int/gho/data/node.main.688?lang=en")),
h4("The source code repository for this calculator is ", a("here.", href="https://github.com/mazhurin/LifeExpectancy")),
h2("Your life expectancy is : "),
div(h3(strong(textOutput("result"))), style = "color:red"),
h2(" "),
h2("The expected value of your last year is : "),
div(h3(textOutput("resultYear")), style = "color:red"),
h2(" "),
h2("The expected value of years left : "),
div(h3(textOutput("resultLeft")), style = "color:red")
)
))
|
f1490253e47cbc75002ed9a5ac1a777aab9c8c88
|
[
"Markdown",
"R"
] | 3
|
Markdown
|
mazhurin/LifeExpectancy
|
2ac0690afe2a59e70d2bdeaa8a4798fc2398bfd5
|
5fd36898f35fb0af33ab085142eb836bc653f7d3
|
refs/heads/master
|
<repo_name>ARAVINDDAYALAN/ecommerce<file_sep>/yankart_backend/databaseQueries.sql
CREATE TABLE category (
id IDENTITY,
name VARCHAR(50),
description VARCHAR(255),
image_url VARCHAR(50),
is_active BOOLEAN,
CONSTRAINT pk_category_id PRIMARY KEY (id)
);
INSERT INTO category (name,description,image_url,is_active) VALUES ('FLOWERING PLANTS','This is the description for FLOWERING PLANTS','fp.png',true);
INSERT INTO category (name,description,image_url,is_active) VALUES ('GARDEN PLANTS','This is the description for GARDEN PLANTS','gp.png',true);
INSERT INTO category (name,description,image_url,is_active) VALUES ('ORNAMENTAL PLANTS','This is the description for ORNAMENTAL PLANTS','op.png',true);
CREATE TABLE user_detail (
id IDENTITY,
first_name VARCHAR(50),
last_name VARCHAR(50),
role VARCHAR(50),
enabled BOOLEAN,
password VARCHAR(60),
email VARCHAR(100),
contact_number VARCHAR(15),
CONSTRAINT pk_user_id PRIMARY KEY(id)
);
INSERT INTO user_detail
(first_name, last_name, role, enabled, password, email, contact_number)
VALUES ('Aravind'', 'D', 'ADMIN', true, '$2y$10$Dv3b1VlDpQ3OnjtLCwwBiOHId4ECegiWDz.Jq8rkksysc9.DpbZ2K', '<EMAIL>', '234567891');
INSERT INTO user_detail
(first_name, last_name, role, enabled, password, email, contact_number)
VALUES ('Yan', 'Karto', 'SUPPLIER', true, '$2y$10$8Yvv5rlH0NvZGwKZyOm1Vu2DGemktNALcx94C0/m3.CbPYxIArvJ6', '<EMAIL>', '1239999899');
INSERT INTO user_detail
(first_name, last_name, role, enabled, password, email, contact_number)
VALUES ('Naruto', 'Uzumaki', 'SUPPLIER', true, '$2y$10$x2bEyO60xLBRXhJtrB3Qg.pR9MXrYMbKq9yEAqWmmhKRdnBvHC/L.', '<EMAIL>', '6279875757');
CREATE TABLE product (
id IDENTITY,
code VARCHAR(20),
name VARCHAR(50),
description VARCHAR(255),
unit_price DECIMAL(10,2),
quantity INT,
is_active BOOLEAN,
category_id INT,
supplier_id INT,
purchases INT DEFAULT 0,
views INT DEFAULT 0,
CONSTRAINT pk_product_id PRIMARY KEY (id),
CONSTRAINT fk_product_category_id FOREIGN KEY (category_id) REFERENCES category (id),
CONSTRAINT fk_product_supplier_id FOREIGN KEY (supplier_id) REFERENCES user_detail(id),
);
INSERT INTO product (code, name, description, unit_price, quantity, is_active, category_id, supplier_id, purchases, views)
VALUES ('YANABC123DEFY', 'Hybrid Tea Rose Plant','We are a top notch supplier of Hybrid Tea Rose Plant.', 200, 5, true, 1, 2, 0, 0 );
INSERT INTO product (code, name, description, unit_price, quantity, is_active, category_id, supplier_id, purchases, views)
VALUES ('YANABC456DEFY', 'Anthurium Flower Plant','Driven by a vision to achieve significant growth in this industry, we are providing a premium quality array of Anthurium Flower Plant.', 150, 5, true, 2, 3, 0, 0 );
INSERT INTO product (code, name, description, unit_price, quantity, is_active, category_id, supplier_id, purchases, views)
VALUES ('YANABC789DEFY', 'tinny oriantal plant','We are successfully meeting the varied requirements of our clients by providing the best quality range of Decorative Ornamental Plant.', 600, 5, true, 3, 2, 0, 0 );
INSERT INTO product (code, name, description, unit_price, quantity, is_active, category_id, supplier_id, purchases, views)
VALUES ('YANABC101112DEFY', 'Lantana Camara Depressa plant','We are leading and eminent industry which is offering a broad range of Lantana Camara Depressa. ', 300, 5, true, 2, 3, 0, 0 );
INSERT INTO product (code, name, description, unit_price, quantity, is_active, category_id, supplier_id, purchases, views)
VALUES ('YANABC131415DEFY', 'Ficus Panda Plant','We are remarkable entity, engaged in offering superior quality of Ficus Panda Plant.', 1500, 5, true, 3, 2, 0, 0 );
|
8939d3d7c81ae93c2eeefdfa1bd787e7a6b9fac9
|
[
"SQL"
] | 1
|
SQL
|
ARAVINDDAYALAN/ecommerce
|
8373adfae2d858d4e44e3afeb839d9c64a875183
|
91d06703d1d9a958bef7349fdf90a217dafcfdf6
|
refs/heads/master
|
<repo_name>snpusr/sigtool<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_fcmpes.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_fcmpes.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_fcmpes.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libasm.h"
int
asm_sparc_fcmpes(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_format3 opcode;
struct s_asm_proc_sparc *inter;
sparc_convert_format3(&opcode, buf);
inter = proc->internals;
ins->instr = inter->op2_table[opcode.op3];
ins->type = ASM_TYPE_COMPARISON | ASM_TYPE_WRITEFLAG;
ins->flagswritten = ASM_SP_FLAG_FCC0 << opcode.cc;
ins->instr = inter->fcmp_table[(opcode.opf & 0x1f) - 16];
ins->nb_op = 3;
ins->op[0].baser = opcode.rs2;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_FREGISTER, ins);
ins->op[1].baser = opcode.rs1;
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_FREGISTER, ins);
ins->op[2].baser = opcode.cc;
asm_sparc_op_fetch(&ins->op[2], buf, ASM_SP_OTYPE_CC, ins);
return 4;
}
<file_sep>/src/libasm/src/arch/ia32/operand_handlers/asm_operand_fetch_immediatebyte.c
/**
* @file libasm/src/arch/ia32/operand_handlers/asm_operand_fetch_immediatebyte.c
*
* @ingroup IA32_operands
* $Id: asm_operand_fetch_immediatebyte.c 1397 2009-09-13 02:19:08Z may $
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler to fetch ASM_OTYPE_IMMEDIATEBYTE operand.
*
* @ingroup IA32_operands
* @param operand Pointer to operand structure.
* @param opcode Pointer to data to disassemble.
* @param otype Operand type.
* @param proc Pointer to processor structure.
* @return Operand Length
*/
#if WIP
int asm_operand_fetch_immediatebyte(asm_operand *operand, u_char *opcode, int otype,
asm_instr *ins, int opt)
#else
int asm_operand_fetch_immediatebyte(asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins)
#endif
{
u_int len;
operand->type = ASM_OTYPE_IMMEDIATE;
operand->content = ASM_OP_VALUE;
operand->ptr = opcode;
operand->imm = 0;
operand->len = 1;
if (*opcode >= 0x80)
{
len = asm_proc_opsize(ins->proc) ? 2 : 4;
//memset(&operand->imm, 0xff, 4);
memset(&operand->imm, 0xff, len);
}
memcpy(&operand->imm, opcode, 1);
return (1);
}
<file_sep>/src/libaspect/types.c
/**
* @file libaspect/types.c
** @ingroup libaspect
** @brief The base of the unified type system.
**
** Started on Sun Jan 9 07:23:58 2007 jfv
** $Id: types.c 1397 2009-09-13 02:19:08Z may $
*/
#include "libaspect.h"
/**
* @brief Available types hash
*/
hash_t types_hash;
/* Base types numbers, strings, and infos */
/* Type Unknown is always at index 0 */
int aspect_type_nbr = ASPECT_TYPE_BASENUM;
typeinfo_t *aspect_typeinfo = NULL;
typeinfo_t aspect_typeinfo_base[ASPECT_TYPE_BASENUM] =
{
{ASPECT_TYPENAME_UNKNOW , 0 },
{ASPECT_TYPENAME_RAW , 0 },
{ASPECT_TYPENAME_BYTE , sizeof(u_char) },
{ASPECT_TYPENAME_STR , sizeof(u_long) },
{ASPECT_TYPENAME_SHORT , sizeof(u_short) },
{ASPECT_TYPENAME_INT , sizeof(u_int) },
{ASPECT_TYPENAME_LONG , sizeof(u_long) },
{ASPECT_TYPENAME_DADDR , sizeof(eresi_Addr) },
{ASPECT_TYPENAME_CADDR , sizeof(eresi_Addr) },
{ASPECT_TYPENAME_BIT , sizeof(u_char) },
{ASPECT_TYPENAME_OID , sizeof(u_int) },
{ASPECT_TYPENAME_VECT , sizeof(vector_t) },
{ASPECT_TYPENAME_HASH , sizeof(hash_t) },
{ASPECT_TYPENAME_LIST , sizeof(list_t) },
{ASPECT_TYPENAME_EXPR , 28 }, /* XXX: should be sizeof(revmexpr_t) */
{ASPECT_TYPENAME_BLOC , 13 }, /* XXX: should be sizeof(mjrblock_t) */
{ASPECT_TYPENAME_FUNC , 110 }, /* XXX: should be sizeof(mjrfunc_t) */
{ASPECT_TYPENAME_LINK , 6 }, /* XXX: should be sizeof(mjrlink_t) */
};
/**
* @brief Indicate if a type is simple (1) or not (0)
* @param typeid Type identifier to be checked
* @return 1 if type is simple, 0 if not
*/
int aspect_type_simple(int typeid)
{
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (typeid != ASPECT_TYPE_UNKNOW && typeid < ASPECT_TYPE_SIMPLENUM)
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 1);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Copy the structure representing a field data type for creating a new meta-type instance
* @param type Type structure for the field data type
* @param off Offset in parent data type
* @param isptr Indicate if field data type is a pointer
* @param elemnbr Element numbers (if typing an array)
* @param fieldname Name for typed field
* @param dims Dimension array for type
* @return Type structure derived from input information
*/
aspectype_t *aspect_type_copy(aspectype_t *type,
unsigned int off,
u_char isptr,
u_int elemnbr,
char *fieldname,
u_int *dims)
{
aspectype_t *newtype;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
XALLOC(__FILE__, __FUNCTION__, __LINE__,
newtype, sizeof(aspectype_t), NULL);
memcpy(newtype, type, sizeof(aspectype_t));
newtype->off = off;
newtype->isptr = isptr;
newtype->dimnbr = elemnbr;
newtype->fieldname = strdup(fieldname);
newtype->elemnbr = dims;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, newtype);
}
/**
* @brief Copy the structure representing a data type and change its name to create a new meta-type
* @param type Type structure to be copied
* @param name Type name to be copied
* @param fieldshash Hash table of fields for this type (if structure type)
* @param curdepth Number of pointer indirections since start of copy
* @param maxdepth Maximum number of pointer indirections for whole copy
* @return Copied meta-type structure
*/
aspectype_t *aspect_type_copy_by_name(aspectype_t *type,
char *name,
hash_t *fieldshash,
u_int curdepth,
u_int maxdepth)
{
aspectype_t *newtype;
aspectype_t *result;
aspectype_t *next;
aspectype_t *prev;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (curdepth > maxdepth)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid depth parameters", NULL);
/* Allocate and name the new type */
XALLOC(__FILE__, __FUNCTION__, __LINE__,
newtype, sizeof(aspectype_t), NULL);
memcpy(newtype, type, sizeof(aspectype_t));
if (name)
newtype->name = strdup(name);
if (fieldshash && newtype->fieldname)
hash_add(fieldshash, strdup(newtype->fieldname), (void *) 1);
prev = result = newtype;
/* Here check if newtype->childs is a pointer */
if (newtype->childs)
{
if (!newtype->isptr || curdepth != maxdepth || !maxdepth)
{
if (newtype->isptr)
curdepth++;
newtype->childs = aspect_type_copy_by_name(newtype->childs, NULL,
(!newtype->fieldname ? fieldshash : NULL),
curdepth, maxdepth);
if (newtype->isptr)
curdepth--;
}
else
newtype->childs = NULL;
}
/* Copy all the field types, if we are dealing with a record type */
for (next = newtype->next; next; next = next->next)
{
/* Copy the type structure */
XALLOC(__FILE__, __FUNCTION__, __LINE__,
newtype, sizeof(aspectype_t), NULL);
memcpy(newtype, next, sizeof(aspectype_t));
/* Set this field name as used to avoid doubles */
if (fieldshash)
hash_add(fieldshash, strdup(newtype->fieldname), (void *) 1);
/* Here check if next->childs is a pointer */
if (next->childs)
{
if (!next->childs->isptr || curdepth != maxdepth || !maxdepth)
{
if (next->childs->isptr)
curdepth++;
newtype->childs = aspect_type_copy_by_name(next->childs,
NULL, NULL,
curdepth, maxdepth);
if (next->childs->isptr)
curdepth--;
}
else
next->childs = NULL;
}
/* Now next type in structure */
prev->next = newtype;
prev = newtype;
}
/* Return copied root type as a result */
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, result);
}
/**
* @brief Add a field to a meta-type
* @param parent Parent data type
* @param field Field data type to add to parent
* @return 0 on succes and -1 on error
*/
int aspect_type_addfield(aspectype_t *parent,
aspectype_t *field)
{
volatile aspectype_t *next;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!parent || !field)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid NULL parameter", -1);
if (!parent->childs)
parent->childs = field;
else
{
for (next = parent->childs; next->next; next = next->next);
next->next = field;
}
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Find the number of dimensions for a field
* @param typename Complete type name string (can be array)
* @param dimnbr Pointer on dimension number integer to be filled
* @return NULL on error or dimension array on succesfull allocation
*/
static u_int *aspect_type_getdims(char *typename, int *dimnbr)
{
char *idxname;
char *idxend;
u_int *dims;
char *realtypename;
int idx;
int curidx;
u_int sz;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
/* First count the number of dimensions */
for (idx = 0, realtypename = typename; *typename;
typename = idxend + 1)
{
idxname = strchr(typename, '[');
if (idxname)
{
idxend = strchr(idxname + 1, ']');
if (!idxend)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid array dimensions", NULL);
idx++;
}
else
break;
}
*dimnbr = idx;
/* Then allocate the array */
XALLOC(__FILE__, __FUNCTION__, __LINE__,
dims, idx * sizeof(int), NULL);
/* Fill array with fetched indexes */
for (curidx = 0, typename = realtypename;
curidx < idx;
typename = idxend + 1, curidx++)
{
idxname = strchr(typename, '[');
*idxname = 0x00;
idxend = strchr(idxname + 1, ']');
sz = atoi(idxname + 1);
if (!sz)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid array element number", NULL);
dims[curidx] = sz;
}
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, dims);
}
/**
* @brief Find the size of an union type
* @param utype Union type whose size is to be infered
* @return Total size for union type
*/
int aspect_type_find_union_size(aspectype_t *utype)
{
int biggest = 0;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!utype)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid input type", 0);
if (!utype->next && utype->childs)
utype = utype->childs;
while (utype)
{
if (utype->size > biggest)
biggest = utype->size;
utype = utype->next;
}
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, biggest);
}
/**
* @brief Create a new (meta description) type
* @param isunion 1 if type to be created is a union
* @param label String name for new type
* @param fields List of fields for type
* @param fieldnbr Number of fields for type
* @return Created type structure
*/
aspectype_t *aspect_type_create(u_char isunion,
char *label,
char **fields,
u_int fieldnbr)
{
aspectype_t *newtype;
aspectype_t *childtype;
aspectype_t *copy;
aspectype_t *supertype;
int index;
char *fieldname;
char *typename;
char *fieldsz;
u_int curoff, off;
char isptr;
int dimnbr;
u_int *dims;
u_int idx;
u_int size;
hash_t fields_hash;
u_char updatetype;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
/* Preliminary checks */
if (!label || !fields || !fieldnbr)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid NULL parameter", NULL);
/* Subtyping was specified */
updatetype = 0;
supertype = NULL;
typename = strstr(label, "::");
if (typename)
{
*typename = 0x00;
typename += 2;
supertype = aspect_type_get_by_name(typename);
if (!supertype)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid record derivation", NULL);
}
/* Check that the created type name is not existing already */
/* It is authorized to update/change some specific types: bloc, func, vector, hash, list .. */
newtype = hash_get(&types_hash, label);
if (newtype && (newtype->type < ASPECT_TYPE_CORENUM || newtype->type >= ASPECT_TYPE_BASENUM))
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Cannot create type : name already exists", NULL);
/* Just remember the name of fields we have already created */
bzero(&fields_hash, sizeof(hash_t));
hash_init(&fields_hash, "localfields", 10, ASPECT_TYPE_UNKNOW);
/* Allocate the new type structure */
if (!supertype)
{
XALLOC(__FILE__, __FUNCTION__, __LINE__,
newtype, sizeof(aspectype_t), NULL);
XALLOC(__FILE__, __FUNCTION__, __LINE__,
newtype->childs, sizeof(hash_t), NULL);
newtype->childs = NULL;
newtype->name = strdup(label);
curoff = 0;
}
else
{
newtype = aspect_type_copy_by_name(supertype, label, &fields_hash, 0, ASPECT_TYPE_MAXPTRDEPTH);
curoff = newtype->size;
}
/* Add fields to types */
for (dims = NULL, off = dimnbr = isptr = index = 0;
index < fieldnbr;
index++, off = dimnbr = isptr = 0, dims = NULL)
{
/* Field name */
fieldname = fields[index];
/* Typename */
typename = strchr(fields[index], ':');
if (typename)
*typename++ = 0x00;
/* Size field */
fieldsz = strchr(fields[index], '%');
if (fieldsz)
*fieldsz++ = 0x00;
/* Either you provide the size or the typename */
if (!*fieldname || hash_get(&fields_hash, fieldname) ||
(!typename && !fieldsz) || (typename && fieldsz) ||
(typename && !*typename) || (fieldsz && (!*fieldsz || !atoi(fieldsz))))
{
hash_destroy(&fields_hash);
XFREE(__FILE__, __FUNCTION__, __LINE__, newtype->name);
XFREE(__FILE__, __FUNCTION__, __LINE__, newtype);
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid use of fieldname or typename", NULL);
}
hash_add(&fields_hash, strdup(fieldname), (void *) 1);
/* Support raw types determined by their size */
if (!typename)
{
off = atoi(fieldsz);
XALLOC(__FILE__, __FUNCTION__, __LINE__,
childtype, sizeof(aspectype_t), NULL);
childtype->type = ASPECT_TYPE_RAW;
childtype->size = off;
childtype->name = aspect_typeinfo[childtype->type].name;
}
/* Deals with incomplete types */
else
{
/* Pointer types */
isptr = 0;
while (typename[0] == '*')
{
isptr += 1;
typename++;
}
/* Array type */
dims = aspect_type_getdims(typename, &dimnbr);
if (dimnbr < 0)
{
hash_destroy(&fields_hash);
XFREE(__FILE__, __FUNCTION__, __LINE__,newtype->name);
XFREE(__FILE__, __FUNCTION__, __LINE__,newtype);
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid array dimensions", NULL);
}
/* Lookup field type */
childtype = hash_get(&types_hash, typename);
if (!childtype)
{
/* If we have a non-pointer recursive type,
make it a pointer */
if (!strcmp(label, typename))
{
isptr = 1;
childtype = newtype;
off = sizeof(u_long);
}
/* If we point on a unknown type, mark is as unknown */
else if (isptr)
{
XALLOC(__FILE__, __FUNCTION__, __LINE__,
childtype, sizeof(aspectype_t), NULL);
childtype->type = ASPECT_TYPE_UNKNOW;
childtype->name = strdup(typename);
}
else
{
hash_destroy(&fields_hash);
XFREE(__FILE__, __FUNCTION__, __LINE__, newtype->name);
XFREE(__FILE__, __FUNCTION__, __LINE__, newtype);
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid type structure", NULL);
}
}
else
off = (isptr ? sizeof(u_long) : childtype->size);
}
/* Copy an existing base type for this child and change type offset */
copy = aspect_type_copy(childtype, (isunion ? 0 : curoff), isptr,
dimnbr, fieldname, dims);
for (size = off, idx = 0; dims != NULL && idx < dimnbr; idx++)
size *= dims[idx];
/* Compute the correct size for bitfields */
if (childtype->type == ASPECT_TYPE_BIT)
{
size /= 8;
size++;
}
curoff += size;
aspect_type_addfield(newtype, copy);
}
/* Add type to global type hash table and return success */
newtype->size = (isunion ? aspect_type_find_union_size(newtype) : curoff);
hash_destroy(&fields_hash);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, newtype);
}
/**
* @brief The real type registering code
* @param label Name for type to be registered
* @param ntype Type structure to be registered
* @return 0 on success and -1 on error
*/
int aspect_type_register_real(char *label,
aspectype_t *ntype)
{
aspectype_t *update;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
/* We do a type update of one of the base type */
update = hash_get(&types_hash, label);
if (update)
{
ntype->type = update->type;
hash_set(&types_hash, label, ntype);
aspect_typeinfo[ntype->type].size = ntype->size;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/* A real new type incrementing the last type id */
hash_add(&types_hash, label, ntype);
aspect_type_nbr++;
XREALLOC(__FILE__, __FUNCTION__, __LINE__,
aspect_typeinfo, aspect_typeinfo,
sizeof(typeinfo_t) * aspect_type_nbr, -1);
aspect_typeinfo[aspect_type_nbr - 1].name = label;
aspect_typeinfo[aspect_type_nbr - 1].size = ntype->size;
ntype->type = aspect_type_nbr - 1;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Wrapper for easy type creation and registration
* @param isunion 1 if registered type is a union
* @param label Name of registered type
* @param fields Array of field names for registered type
* @param fieldnbr Number of fields for registered type
* @return 0 on success and -1 on error
*/
int aspect_type_register(u_char isunion,
char *label,
char **fields,
u_int fieldnbr)
{
aspectype_t *ret;
int iret;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
ret = aspect_type_create(isunion, label, fields, fieldnbr);
if (!ret)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid type declaration", -1);
iret = aspect_type_register_real(label, ret);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, iret);
}
/**
* @brief Create a new type with a single field (internal function)
* @param type Type identifier to be created
* @param info Internal typeinfo structure related to newly created type
* @return 0 on success and -1 on error
*/
static int aspect_basetype_create(u_int type, typeinfo_t *info)
{
aspectype_t *newtype;
char hashname[BUFSIZ];
hash_t *newhash;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
XALLOC(__FILE__, __FUNCTION__, __LINE__,
newtype, sizeof(aspectype_t), -1);
newtype->type = type;
newtype->size = info->size;
newtype->name = info->name;
hash_add(&types_hash, info->name, newtype);
/* Create the hash table for objects of that type */
snprintf(hashname, sizeof(hashname), "type_%s", info->name);
XALLOC(__FILE__, __FUNCTION__, __LINE__,
newhash, sizeof(hash_t), -1);
hash_init(newhash, strdup(hashname), 11, ASPECT_TYPE_UNKNOW);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Create all simple types
* @return 0 on success and -1 on error
*/
int aspect_basetypes_create()
{
int index;
u_int basesize;
static u_int done = 0;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (done)
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
done = 1;
basesize = ASPECT_TYPE_BASENUM * sizeof(typeinfo_t);
XALLOC(__FILE__, __FUNCTION__, __LINE__, aspect_typeinfo, basesize, -1);
memcpy(aspect_typeinfo, aspect_typeinfo_base, basesize);
for (index = 1; index < ASPECT_TYPE_BASENUM; index++)
aspect_basetype_create(index, aspect_typeinfo + index);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Get field type from field name and parent type
* @param parent Parent type structure
* @param name Field name to lookup
* @return Type for looked-up field
*/
aspectype_t *aspect_type_get_child(aspectype_t *parent, char *name)
{
aspectype_t *cur;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
for (cur = parent->childs; cur; cur = cur->next)
if (!strcmp(cur->fieldname, name))
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, cur);
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Unknown child name", NULL);
}
/**
* @brief Get a type by its type id
* @param id Type identifier to be found
* @return Structure for matching type
*/
aspectype_t *aspect_type_get_by_id(unsigned int id)
{
aspectype_t *type;
typeinfo_t info;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (id >= aspect_type_nbr)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid type ID", NULL);
info = aspect_typeinfo[id];
type = hash_get(&types_hash, info.name);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, type);
}
/**
* @brief Get a type by its type id
* @param name Type name to be found
* @return Structure for matching type
*/
aspectype_t *aspect_type_get_by_name(char *name)
{
aspectype_t *type;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
type = hash_get(&types_hash, name);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, type);
}
/**
* @brief Return the list of base types
* @param nbr Integer pointer that will be filled with the number of base types
* @return Pointer on array of internal Typeinfo structures
*/
typeinfo_t *aspect_basetype_get(unsigned int *nbr)
{
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (nbr)
*nbr = ASPECT_TYPE_BASENUM;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, aspect_typeinfo_base);
}
/**
* @brief Create and register a new simple type
* @param name Name for new base type
* @param size Total size for new base type
* @return -1 on error and 0 on success
*/
int aspect_basetype_register(char *name, u_int size)
{
typeinfo_t info;
aspectype_t *exist;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!name)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid parameters", -1);
exist = (aspectype_t *) hash_get(&types_hash, name);
if (exist)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Type destination already exist", -1);
info.name = name;
info.size = size;
aspect_basetype_create(aspect_type_nbr, &info);
/* The type ID is incremented here */
aspect_type_nbr++;
XREALLOC(__FILE__, __FUNCTION__, __LINE__,
aspect_typeinfo, aspect_typeinfo,
sizeof(typeinfo_t) * aspect_type_nbr, -1);
aspect_typeinfo[aspect_type_nbr - 1].name = name;
aspect_typeinfo[aspect_type_nbr - 1].size = size;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Retreive the ascii name of a type
* @param type Requested type identifier
* @return Name associated to type identifier
*/
char *aspect_typename_get(u_int type)
{
if (type >= aspect_type_nbr)
return (NULL);
return (aspect_typeinfo[type].name);
}
/**
* @brief Retreive the size (in bytes) of a type
* @param type Requested type identifier
* @return Size of requested type
*/
u_int aspect_typesize_get(u_int type)
{
if (type >= aspect_type_nbr)
return (0);
return (aspect_typeinfo[type].size);
}
<file_sep>/src/libaspect/libbtree.c
/**
**
* @file libaspect/libbtree.c
** @ingroup libaspect
**
** Author : <087432084750432042>
** Started : Fri Oct 17 14:29:24 2003
** Updated : Thu Nov 27 23:29:29 2003
**
** $Id: libbtree.c 1397 2009-09-13 02:19:08Z may $
**
*/
//#include <sys/types.h>
#include "libaspect.h"
/**
* @brief insert element in tree using id to sort it
*
*
*
*
*/
void btree_insert(btree_t **proot, /*!< ptr to btree root */
u_int id, /*!< element id */
void *elem) /*!< ptr to element */
{
btree_t *root;
void *ptr;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
root = *proot;
if (!root)
{
XALLOC(__FILE__, __FUNCTION__, __LINE__, ptr, sizeof (btree_t), );
root = (btree_t *) ptr;
root->id = id;
root->elem = elem;
*proot = root;
}
else
{
if (id < root->id)
btree_insert(&root->left, id, elem);
else
btree_insert(&root->right, id, elem);
}
PROFILER_OUT(__FILE__, __FUNCTION__, __LINE__);
}
/**
* @brief Insert element in tree using a function to sort it.
*
* depending on function return value, element is insert
* in left or right path:
* if return value is null, element is already present in
* tree and is discarded.
*
* if apply function return a positive value,
* element is inserted on right path
* if apply function return a negative value,
* element is inserted on left path
*
*/
void btree_insert_sort(btree_t **proot, /*!< ptr to root */
int (*apply)(void *, void *), /*!< cmp handler */
void *elem) /*!< element */
{
btree_t *root;
int ret;
root = *proot;
if (!root)
btree_insert(proot, (u_int) elem, elem);
else
{
if ((ret = apply(root->elem, elem)))
{
if (ret > 0)
btree_insert_sort(&root->right, apply, elem);
else
btree_insert_sort(&root->left, apply, elem);
}
}
}
/**
* @brief return an element by providing its id.
* id is id provided to insert element
* with btree_insert();
* do not use on trees built with btree_insert_sort
*/
void *btree_get_elem(btree_t *root, /* !< ptr to root */
u_int id) /* !< element id to fetch */
{
if (!root)
return (NULL);
/* elem found, return it */
if (root->id == id)
return (root->elem);
/* switch on path */
if (id < root->id)
return (btree_get_elem(root->left, id));
else if (root->id < id)
return (btree_get_elem(root->right, id));
return (NULL);
}
/**
* return an element by providing a matching function
* this matching function is used to follow path
* until it find element depending on its return value:
* if match function is null, element is current element
* and is returned.
* else
* if return value is negative, element is searched in right path
* if return value is positive, element is searched in left path
*
*/
void *btree_find_elem(btree_t *root,
int (*match)(void *, void *),
void *ptr)
{
int ret;
void *to_ret;
if (root)
{
ret = match(root->elem, ptr);
if (!ret)
to_ret = root->elem;
else
{
if (ret > 0)
to_ret = btree_find_elem(root->right, match, ptr);
else
to_ret = btree_find_elem(root->left, match, ptr);
}
}
else
to_ret = NULL;
return (to_ret);
}
/**
* @brief browse tree and call function apply on each element.
*
* @param ptr ptr is a pointer passed as second argument of apply
*
*/
void btree_browse_prefix(btree_t *root, int (*apply)(void *, void *), void *ptr)
{
if (root)
{
apply(root->elem, ptr);
if (root->left)
btree_browse_prefix(root->left, apply, ptr);
if (root->right)
btree_browse_prefix(root->right, apply, ptr);
}
}
void btree_browse_infix(btree_t *root, int (*apply)(void *, void *), void *ptr)
{
if (root)
{
if (root->left)
btree_browse_infix(root->left, apply, ptr);
apply(root->elem, ptr);
if (root->right)
btree_browse_infix(root->right, apply, ptr);
}
}
void btree_browse_suffix(btree_t *root, int (*apply)(void *, void *), void *ptr)
{
if (root)
{
if (root->left)
btree_browse_suffix(root->left, apply, ptr);
if (root->right)
btree_browse_suffix(root->right, apply, ptr);
apply(root->elem, ptr);
}
}
/**
* @brief free full tree.
* @param mode if mode is not null, tree elements are also freed
*/
void btree_free(btree_t *root, int mode)
{
if (root)
{
if (mode)
XFREE(__FILE__, __FUNCTION__, __LINE__, root->elem);
btree_free(root->left, mode);
btree_free(root->right, mode);
XFREE(__FILE__, __FUNCTION__, __LINE__, root);
}
}
#ifndef __KERNEL__
/**
*
*
*/
int btree_debug_node(void *elem, void *ptr, btree_t *root)
{
struct s_debug *opt;
opt = (struct s_debug *) ptr;
fprintf(opt->fp, BTREE_DEBUG_NODE, (int) root, (int) root,
(int) root->left, (int) root->right);
return (0);
}
int btree_debug_link(void *elem, void *ptr, btree_t *root)
{
struct s_debug *opt;
opt = (struct s_debug *) ptr;
if (root->left)
fprintf(opt->fp, BTREE_DEBUG_LINK, (int) root,
"L", (int) root->left, opt->link++);
if (root->right)
fprintf(opt->fp, BTREE_DEBUG_LINK, (int) root, "R",
(int) root->right, opt->link++);
return (0);
}
void btree_browse_prefix_debug(btree_t *root, int (*apply)(void *, void *, btree_t *),
void *ptr)
{
if (root)
{
apply(root->elem, ptr, root);
if (root->left)
btree_browse_prefix_debug(root->left, apply, ptr);
if (root->right)
btree_browse_prefix_debug(root->right, apply, ptr);
}
}
void btree_debug(btree_t *root, char *filename,
void (*apply)(void *, void *)) {
struct s_debug opt;
opt.fp = fopen(filename, "w");
if (opt.fp)
{
fprintf(opt.fp, "digraph g {\n"
"size=\"6,4\"; ratio = fill; graph [ rankdir = \"LR\" ] ;\n");
btree_browse_prefix_debug(root, btree_debug_node, &opt);
opt.link = 0;
btree_browse_prefix_debug(root, btree_debug_link, &opt);
fprintf(opt.fp, "};\n");
fclose(opt.fp);
}
}
#endif
<file_sep>/src/libasm/include/libasm-structs.h
/**
* @file libasm/include/libasm-structs.h
*
* Started on Tue Jun 14 05:00:05 2005 <NAME>
* $Id: libasm-structs.h 1440 2010-12-29 02:22:03Z may $
*/
/**
* Operand structure.
*/
struct s_asm_op
{
/** operand length. (usefull on ia32 only).
* operands expressed in R byte from ModRM byte have a null size. */
u_int len;
/* pointer to operand in buffer */
u_char *ptr;
/* operand type: contain operandb type flags */
u_int type;
/* a pointer to the operand name in string format */
char *name;
/* contain operand size flags */
u_int size;
/* Operand content flags */
u_int content;
/* register set: 8/16/32 bits general registers, segment registers .. (IA32 only) */
/* register set: usr, svc, abt, und, irq, fiq (arm) */
int regset;
/* operand prefix (ia32 only) */
int prefix;
/* immediate value extracted from operand */
int imm;
/* base register: primary register extracted */
int baser;
/* index register: auxiliary register */
int indexr;
/* String for base register */
char *sbaser;
/* String for index register */
char *sindex;
/* Determines if this register is source or destination */
int destination;
/* address space (sparc only)
*
* has to be different than ASM_SP_ASI_P for ASM_SP_OTYPE_IMM_ADDRESS
* operands on "alternate space" instructions so the output can be correct
*/
int address_space;
/* scale factor (ia32 only) */
unsigned int scale;
/* shift type (arm only) */
u_int shift_type;
/* indexing type (arm only) */
u_int indexing;
/* determines if offset is added or subtracted from the base (arm only) */
u_int offset_added;
};
/**
* Instruction structure.
*
* This contains all the fields related to an instruction: type, mnemonic,
* operand types, contents.
*/
struct s_asm_instr
{
/* pointer to instruction buffer -- please let this field in first if using containers */
u_char *ptr_instr;
/* internal processor structure */
asm_processor *proc;
/* instruction name */
char *name;
/* instruction id */
int instr;
/* instruction type */
int type;
/* instruction prefix (ia32 only) */
int prefix;
/* stack offset difference. push/pop/ret/call related */
int spdiff;
/* bitfield of flags which could have been modified */
int flagswritten;
/* bitfield of flags which were read */
int flagsread;
/* Pointer to instruction prefix (ia32 only) */
void *ptr_prefix;
/* annul bit (sparc only) */
int annul;
/* prediction bit (sparc only) */
int prediction;
/* number of operand */
int nb_op;
/* Array of operands */
asm_operand op[6];
/* instruction/operands full lengh */
u_int len;
/* If arithmetic, make explicit what kind of operation is done */
u_int arith;
};
/**
* Processor structure.
* Contains architecture dependant handler.
*
* This structure contains several functions pointers which are used
* to as handlers to manage each architecture.
*
* NOTE: A vector should be implemented to replace thoses handlers
* by provided functions.
*/
struct s_asm_processor
{
/* handler to resolving function */
void (*resolve_immediate)(void *, eresi_Addr, char *, u_int);
/* handler data pointer */
void *resolve_data;
/* processor type */
int type;
/* array to instruction memonic by instr field of asm_instr */
char **instr_table;
/* fetching instruction. points to processor fetching function. */
LIBASM_HANDLER_FETCH(fetch);
/* output handler. print instruction in a readable string */
char *(*display_handle)(asm_instr *instr, eresi_Addr addr);
/* pointer to an internal structure. */
void *internals;
/* Last operation error code */
int error_code;
};
<file_sep>/src/libasm/src/arch/ia32/handlers/op_opsize.c
/*
** $Id: op_opsize.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_opsize" opcode="0x66"/>
*/
int op_opsize(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
asm_i386_processor *i386p;
if (!new->ptr_prefix)
new->ptr_prefix = opcode;
i386p = (asm_i386_processor *) proc;
i386p->internals->opsize = !i386p->internals->opsize;
new->len += 1;
new->prefix |= ASM_PREFIX_OPSIZE;
len = proc->fetch(new, opcode + 1, len - 1, proc);
i386p->internals->opsize = !i386p->internals->opsize;
return (len);
}
<file_sep>/src/libasm/src/arch/mips/operand_handlers/asm_mips_operand_regbase.c
/**
* @file libasm/src/arch/mips/operand_handlers/asm_mips_operand_regbase.c
** @ingroup MIPS_operands
*/
/*
* - Adam 'pi3' Zabrocki
*
*/
#include <libasm.h>
void asm_mips_operand_regbase(asm_operand *op, u_char *opcode, int otype,
asm_instr *ins)
{
op->type = ASM_MIPS_OTYPE_REGBASE;
memcpy(&op->scale,opcode,4);
}
<file_sep>/src/fw.h
#ifndef FW_H
#define FW_H
#define FILE_TYPE_RAW 0
#define FILE_TYPE_COFF 1
#define FILE_TYPE_ELF 2
#define FILE_TYPE_PE 3
#define FILE_COMP_LZMA 0x10000000
#define FILE_COMP_GZIP 0x01000000
#define FILE_COMP_BZIP 0x00100000
#define FILE_COMP_ZLIB 0x00010000
#define FILE_ENC_IDEA 0x80000000
#define FILE_ENC_TEA 0x08000000
#define FILE_ENC_XTEA 0x00800000
#define FILE_ENC_DES 0x00080000
#define FILE_ENC_3DES 0x00008000
#define FILE_ENDIAN_LITTLE 0
#define FILE_ENDIAN_BIG 1
#define FILE_ENDIAN_DEFAULT FILE_ENDIAN_LITTLE
typedef struct data {
unsigned char *data; // view data
unsigned int size; // view size
unsigned int flags;
} data_t;
typedef struct file {
char *name; // file name
unsigned char * rdata; // file raw data
unsigned int rsize; // file raw data size
unsigned int flags; // file flags
unsigned int type; // file tyoe
} file_t;
typedef struct asmview {
unsigned char align; // view size (1, 2, 4, 8, 16, 32)
unsigned char ascii; // view ascii data
unsigned char *data; // view data aligned by valign;
unsigned int size; // view size (if vascii is true, vsize = vsize + valign)
unsigned int lines;
} asmview_t;
#define SYM_TYPE_LOCAL 0
#define SYM_TYPE_GLOBAL 1
#define SYM_TYPE_UNKNOWN 2
typedef struct sym {
unsigned char symid;
unsigned char *dptr;
unsigned char align;
char *name;
unsigned int paddr,
vaddr,
offset,
size;
} symbol_t;
#define VAR_TYPE_LOCAL 0
#define VAR_TYPE_GLOBAL 1
#define VAR_TYPE_UNKNOWN 2
typedef struct variable {
unsigned char varid; // variable unique id
unsigned char align; // alignement
unsigned char type; // variable type (int,char,long,double,float,etc)
unsigned int owner; // variable owner
char *name; // variable name
void *vptr; // variable data pointer into file binary image
} variable_t;
#endif
<file_sep>/src/libasm/include/libasm-sparc.h
/**
* @defgroup sparc Libasm SPARC support.
* @ingroup libasm
*/
/**
* @file libasm/include/libasm-sparc.h
** @ingroup sparc
**
** Started by sroy on Tue Dec 2 22:43:08 2003
** $Id: libasm-sparc.h 1397 2009-09-13 02:19:08Z may $
*/
#ifndef LIBASM_SPARC_H_
#define LIBASM_SPARC_H_
#include <libasm-sparc-decode.h>
#define MGETBIT(val, shift) (((val) >> shift) & 1)
#define ASM_FREG_FSR -1 /* Nasty little hack */
#define ASM_SP_ASI_P 0x80 /* Primary ASI */
#define ASM_SP_ASI_P_L 0x88 /* Primary ASI little-endian */
/* SPARC Instruction decoders */
int asm_sparc_add (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_addc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_addcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_addccc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_and (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_andcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_andn (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_andncc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_bicc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_bpcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_bpr (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_call (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_casa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_casxa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_done (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fbfcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fbpfcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fcmpd (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fcmped (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fcmpeq (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fcmpes (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fcmpq (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fcmps (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_flush (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_flushw (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fmovdcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fmovdr (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fmovqcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fmovqr (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fmovscc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fmovsr (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_fpop1 (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_hu (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_hu2 (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_illegal (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_illtrap (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_impdep1 (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_impdep2 (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_jmpl (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldd (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldda (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_lddf (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_lddfa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldf (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldfa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldfsr (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldqf (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldqfa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldsb (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldsba (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldsh (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldsha (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldstub (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldstuba (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldsw (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldswa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldub (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_lduba (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_lduh (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_lduha (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_lduw (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_lduwa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldx (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_ldxa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_movcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_movr (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_mulscc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_mulx (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_or (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_orcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_orn (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_orncc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_popc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_prefetch (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_prefetcha (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_rd (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_rdpr (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_restore (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_return (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_save (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_saved (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_sdiv (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_sdivcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_sdivx (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_sethi (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_sll (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_smul (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_smulcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_sra (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_srl (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stb (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stba (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_std (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stda (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stdf (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stdfa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stf (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stfa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stfsr (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_sth (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stha (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stqf (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stqfa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stw (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stwa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stx (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_stxa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_sub (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_subc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_subcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_subccc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_swap (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_swapa (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_taddcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_taddcctv (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_tcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_tsubcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_tsubcctv (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_udiv (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_udivcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_udivx (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_umul (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_umulcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_wr (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_wrpr (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_xnor (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_xnorcc (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_xor (asm_instr *, u_char *, u_int, asm_processor *);
int asm_sparc_xorcc (asm_instr *, u_char *, u_int, asm_processor *);
void sparc_convert_pbranch(struct s_decode_pbranch *, u_char *);
void sparc_convert_rbranch(struct s_decode_rbranch *, u_char *);
void sparc_convert_branch(struct s_decode_branch *, u_char *);
void sparc_convert_call(struct s_decode_call *, u_char *);
void sparc_convert_format3(struct s_decode_format3 *, u_char *);
void sparc_convert_format4(struct s_decode_format4 *, u_char *);
void asm_resolve_sparc(void *, eresi_Addr, char *, u_int);
/* Get operand name */
char *asm_sparc_get_op_name (asm_operand *op);
char *get_sparc_register(int reg);
char *get_sparc_sregister(int reg);
char *get_sparc_pregister(int reg);
char *get_sparc_fregister(int reg);
char *get_sparc_cc(int cc);
/* SPARC operand handlers (ie. fetchers) */
int asm_sparc_op_fetch (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
int asm_sparc_op_fetch_register (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
int asm_sparc_op_fetch_immediate (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
int asm_sparc_op_fetch_displacement (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
int asm_sparc_op_fetch_disp30 (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
int asm_sparc_op_fetch_sethi (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
int asm_sparc_op_fetch_fregister (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
int asm_sparc_op_fetch_sregister (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
int asm_sparc_op_fetch_pregister (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
int asm_sparc_op_fetch_cc (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
int asm_sparc_op_fetch_imm_address (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
int asm_sparc_op_fetch_reg_address (asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins);
/**
* Registration functions.
*
*/
int asm_register_sparc();
/*****
* sparc processor internals
*/
struct s_asm_ins_sparc {
int instr;
asm_operand op1;
asm_operand op2;
asm_operand op3;
};
/**
* SPARC "flags" (ie. condition codes)
*/
enum e_sparc_flags {
/* Flags inside the integer condition codes (icc, xcc) */
ASM_SP_FLAG_C = 1 << 0, // Carry
ASM_SP_FLAG_V = 1 << 1, // oVerflow
ASM_SP_FLAG_Z = 1 << 2, // Zero
ASM_SP_FLAG_N = 1 << 3, // Negative
/* Floating-point condition codes */
ASM_SP_FLAG_FCC0 = 1 << 4,
ASM_SP_FLAG_FCC1 = 1 << 5,
ASM_SP_FLAG_FCC2 = 1 << 6,
ASM_SP_FLAG_FCC3 = 1 << 7
};
struct s_asm_proc_sparc {
/* handlers for x86 instructions referenced by opcode */
int *bcc_table;
int *brcc_table;
int *fbcc_table;
int *shift_table;
int *movcc_table;
int *movfcc_table;
int *movr_table;
int *fpop1_table;
int *fmovcc_table;
int *fmovfcc_table;
int *fmovr_table;
int *fcmp_table;
int *tcc_table;
int *op2_table;
int *op3_table;
};
enum e_sparc_gregisters {
ASM_REG_R0,
ASM_REG_R1
} ;
enum e_sparc_sregisters {
ASM_REG_G0,
ASM_REG_G1,
ASM_REG_G2,
ASM_REG_G3,
ASM_REG_G4,
ASM_REG_G5,
ASM_REG_G6,
ASM_REG_G7,
ASM_REG_O0,
ASM_REG_O1,
ASM_REG_O2,
ASM_REG_O3,
ASM_REG_O4,
ASM_REG_O5,
ASM_REG_O6,
ASM_REG_O7,
ASM_REG_L0,
ASM_REG_L1,
ASM_REG_L2,
ASM_REG_L3,
ASM_REG_L4,
ASM_REG_L5,
ASM_REG_L6,
ASM_REG_L7,
ASM_REG_I0,
ASM_REG_I1,
ASM_REG_I2,
ASM_REG_I3,
ASM_REG_I4,
ASM_REG_I5,
ASM_REG_I6,
ASM_REG_I7
} ;
enum e_sparc_state_registers {
ASM_SREG_Y,
ASM_SREG_BAD,
ASM_SREG_CCR,
ASM_SREG_ASI,
ASM_SREG_TICK,
ASM_SREG_PC,
ASM_SREG_FPRS
/* Values from 7 to 31 are either unused or implementation-specific */
};
enum e_sparc_privileged_registers {
ASM_PREG_TPC,
ASM_PREG_TNPC,
ASM_PREG_TSTATE,
ASM_PREG_TT,
ASM_PREG_TICK,
ASM_PREG_TBA,
ASM_PREG_PSTATE,
ASM_PREG_TL,
ASM_PREG_PIL,
ASM_PREG_CWP,
ASM_PREG_CANSAVE,
ASM_PREG_CANRESTORE,
ASM_PREG_CLEANWIN,
ASM_PREG_OTHERWIN,
ASM_PREG_WSTATE,
ASM_PREG_FQ,
ASM_PREG_BAD16, /* Values from 16 to 30 are reserved */
ASM_PREG_BAD17,
ASM_PREG_BAD18,
ASM_PREG_BAD19,
ASM_PREG_BAD20,
ASM_PREG_BAD21,
ASM_PREG_BAD22,
ASM_PREG_BAD23,
ASM_PREG_BAD24,
ASM_PREG_BAD25,
ASM_PREG_BAD26,
ASM_PREG_BAD27,
ASM_PREG_BAD28,
ASM_PREG_BAD29,
ASM_PREG_BAD30,
ASM_PREG_VER
};
enum e_sparc_condition_codes {
ASM_SP_FCC0,
ASM_SP_FCC1,
ASM_SP_FCC2,
ASM_SP_FCC3,
ASM_SP_ICC,
ASM_SP_BADCC, /* 5 and 7 are reserved */
ASM_SP_XCC
};
/**
* Instruction family, depending on op field
*/
enum e_sparc_opcode {
ASM_SPARC_OP0_BRANCH,
ASM_SPARC_OP1_CALL,
ASM_SPARC_OP2_FORMAT3,
ASM_SPARC_OP3_FORMAT3
};
/* Possible values for SPARC operands' content attribute */
enum e_sparc_operand {
ASM_SP_OTYPE_REGISTER,
ASM_SP_OTYPE_IMMEDIATE,
ASM_SP_OTYPE_DISPLACEMENT,
ASM_SP_OTYPE_DISP30,
ASM_SP_OTYPE_SETHI,
ASM_SP_OTYPE_FREGISTER,
ASM_SP_OTYPE_SREGISTER,
ASM_SP_OTYPE_PREGISTER,
ASM_SP_OTYPE_CC,
ASM_SP_OTYPE_IMM_ADDRESS, /* [ r[rs1] + imm ] */
ASM_SP_OTYPE_REG_ADDRESS, /* [ r[rs1] + r[rs2] ] */
ASM_SP_OTYPE_NUM /* This element must be the last in the enum */
};
/***
* Instruction list
*
* Last instruction must be ASM_SP_BAD
*/
enum e_sparc_instr {
ASM_SP_,
ASM_SP_ADD, /* ADD */
ASM_SP_ADDCC, /* ADDcc */
ASM_SP_ADDC, /* ADDC */
ASM_SP_ADDCCC, /* ADDCcc */
ASM_SP_AND, /* AND */
ASM_SP_ANDCC, /* ANDcc */
ASM_SP_ANDN, /* ANDN */
ASM_SP_ANDNCC, /* ANDNcc */
ASM_SP_BA, /* BPcc, Bicc */
ASM_SP_BN,
ASM_SP_BNE,
ASM_SP_BE,
ASM_SP_BG,
ASM_SP_BLE,
ASM_SP_BGE,
ASM_SP_BL,
ASM_SP_BGU,
ASM_SP_BLEU,
ASM_SP_BCC,
ASM_SP_BCS,
ASM_SP_BPOS,
ASM_SP_BNEG,
ASM_SP_BVC,
ASM_SP_BVS,
ASM_SP_BRZ, /* BPr */
ASM_SP_BRLEZ,
ASM_SP_BRLZ,
ASM_SP_BRNZ,
ASM_SP_BRGZ,
ASM_SP_BRGEZ,
ASM_SP_CALL, /* CALL */
ASM_SP_CASA, /* CASA */
ASM_SP_CASXA, /* CASXA */
ASM_SP_DONE, /* DONE */
ASM_SP_FABSS, /* FABS(s,d,q) */
ASM_SP_FABSD,
ASM_SP_FABSQ,
ASM_SP_FADDS, /* FADD(s,d,q) */
ASM_SP_FADDD,
ASM_SP_FADDQ,
ASM_SP_FBA, /* FBfcc, FBPfcc */
ASM_SP_FBN,
ASM_SP_FBU,
ASM_SP_FBG,
ASM_SP_FBUG,
ASM_SP_FBL,
ASM_SP_FBUL,
ASM_SP_FBLG,
ASM_SP_FBNE,
ASM_SP_FBE,
ASM_SP_FBUE,
ASM_SP_FBGE,
ASM_SP_FBUGE,
ASM_SP_FBLE,
ASM_SP_FBULE,
ASM_SP_FBO,
ASM_SP_FCMPS, /* FCMP(s,d,q) */
ASM_SP_FCMPD,
ASM_SP_FCMPQ,
ASM_SP_FCMPES, /* FCMPE(s,d,q) */
ASM_SP_FCMPED,
ASM_SP_FCMPEQ,
ASM_SP_FDIVS, /* FDIV(s,d,q) */
ASM_SP_FDIVD,
ASM_SP_FDIVQ,
ASM_SP_FDMULQ, /* FdMULq */
ASM_SP_FITOS, /* FiTO(s,d,q) */
ASM_SP_FITOD,
ASM_SP_FITOQ,
ASM_SP_FLUSH, /* FLUSH */
ASM_SP_FLUSHW, /* FLUSHW */
ASM_SP_FMOVS, /* FMOV(s,d,q) */
ASM_SP_FMOVD,
ASM_SP_FMOVQ,
ASM_SP_FMOVSA, /* FMOV(s,d,q)cc */
ASM_SP_FMOVSN,
ASM_SP_FMOVSNE,
ASM_SP_FMOVSE,
ASM_SP_FMOVSG,
ASM_SP_FMOVSLE,
ASM_SP_FMOVSGE,
ASM_SP_FMOVSL,
ASM_SP_FMOVSGU,
ASM_SP_FMOVSLEU,
ASM_SP_FMOVSCC,
ASM_SP_FMOVSCS,
ASM_SP_FMOVSPOS,
ASM_SP_FMOVSNEG,
ASM_SP_FMOVSVC,
ASM_SP_FMOVSVS,
ASM_SP_FMOVSU,
ASM_SP_FMOVSUG,
ASM_SP_FMOVSUL,
ASM_SP_FMOVSLG,
ASM_SP_FMOVSUE,
ASM_SP_FMOVSUGE,
ASM_SP_FMOVSULE,
ASM_SP_FMOVSO,
ASM_SP_FMOVDA,
ASM_SP_FMOVDN,
ASM_SP_FMOVDNE,
ASM_SP_FMOVDE,
ASM_SP_FMOVDG,
ASM_SP_FMOVDLE,
ASM_SP_FMOVDGE,
ASM_SP_FMOVDL,
ASM_SP_FMOVDGU,
ASM_SP_FMOVDLEU,
ASM_SP_FMOVDCC,
ASM_SP_FMOVDCS,
ASM_SP_FMOVDPOS,
ASM_SP_FMOVDNEG,
ASM_SP_FMOVDVC,
ASM_SP_FMOVDVS,
ASM_SP_FMOVDU,
ASM_SP_FMOVDUG,
ASM_SP_FMOVDUL,
ASM_SP_FMOVDLG,
ASM_SP_FMOVDUE,
ASM_SP_FMOVDUGE,
ASM_SP_FMOVDULE,
ASM_SP_FMOVDO,
ASM_SP_FMOVQA,
ASM_SP_FMOVQN,
ASM_SP_FMOVQNE,
ASM_SP_FMOVQE,
ASM_SP_FMOVQG,
ASM_SP_FMOVQLE,
ASM_SP_FMOVQGE,
ASM_SP_FMOVQL,
ASM_SP_FMOVQGU,
ASM_SP_FMOVQLEU,
ASM_SP_FMOVQCC,
ASM_SP_FMOVQCS,
ASM_SP_FMOVQPOS,
ASM_SP_FMOVQNEG,
ASM_SP_FMOVQVC,
ASM_SP_FMOVQVS,
ASM_SP_FMOVQU,
ASM_SP_FMOVQUG,
ASM_SP_FMOVQUL,
ASM_SP_FMOVQLG,
ASM_SP_FMOVQUE,
ASM_SP_FMOVQUGE,
ASM_SP_FMOVQULE,
ASM_SP_FMOVQO,
ASM_SP_FMOVRSZ, /* FMOV(s,d,q)r */
ASM_SP_FMOVRSLEZ,
ASM_SP_FMOVRSLZ,
ASM_SP_FMOVRSNZ,
ASM_SP_FMOVRSGZ,
ASM_SP_FMOVRSGEZ,
ASM_SP_FMOVRDZ,
ASM_SP_FMOVRDLEZ,
ASM_SP_FMOVRDLZ,
ASM_SP_FMOVRDNZ,
ASM_SP_FMOVRDGZ,
ASM_SP_FMOVRDGEZ,
ASM_SP_FMOVRQZ,
ASM_SP_FMOVRQLEZ,
ASM_SP_FMOVRQLZ,
ASM_SP_FMOVRQNZ,
ASM_SP_FMOVRQGZ,
ASM_SP_FMOVRQGEZ,
ASM_SP_FMULS, /* FMUL(s,d,q) */
ASM_SP_FMULD,
ASM_SP_FMULQ,
ASM_SP_FNEGS, /* FNEG(s,d,q) */
ASM_SP_FNEGD,
ASM_SP_FNEGQ,
ASM_SP_FSMULD, /* FsMULd */
ASM_SP_FSQRTS, /* FSQRT(s,d,q) */
ASM_SP_FSQRTD,
ASM_SP_FSQRTQ,
ASM_SP_FSTOI, /* F(s,d,q)TOi */
ASM_SP_FDTOI,
ASM_SP_FQTOI,
ASM_SP_FSTOD, /* F(s,d,q)TO(s,d,q) */
ASM_SP_FSTOQ,
ASM_SP_FDTOS,
ASM_SP_FDTOQ,
ASM_SP_FQTOS,
ASM_SP_FQTOD,
ASM_SP_FSTOX, /* F(s,d,q)TOx */
ASM_SP_FDTOX,
ASM_SP_FQTOX,
ASM_SP_FSUBS, /* FSUB(s,d,q) */
ASM_SP_FSUBD,
ASM_SP_FSUBQ,
ASM_SP_FXTOS, /* FxTO(s,d,q) */
ASM_SP_FXTOD,
ASM_SP_FXTOQ,
ASM_SP_ILLTRAP, /* ILLTRAP */
ASM_SP_IMPDEP1, /* IMPDEP1 */
ASM_SP_IMPDEP2, /* IMPDEP2 */
ASM_SP_JMPL, /* JMPL, RET, RETL */
ASM_SP_LDD, /* LDD */
ASM_SP_LDDA, /* LDDA */
ASM_SP_LDDF, /* LDFF */
ASM_SP_LDDFA, /* LDDFA */
ASM_SP_LDF, /* LDF */
ASM_SP_LDFA, /* LDFA */
ASM_SP_LDFSR, /* LDFSR */
ASM_SP_LDQF, /* LDQF */
ASM_SP_LDQFA, /* LDQFA */
ASM_SP_LDSB, /* LDSB */
ASM_SP_LDSBA, /* LDSBA */
ASM_SP_LDSH, /* LDSH */
ASM_SP_LDSHA, /* LDSHA */
ASM_SP_LDSTUB, /* LDSTUB */
ASM_SP_LDSTUBA, /* LDSTUBA */
ASM_SP_LDSW, /* LDSW */
ASM_SP_LDSWA, /* LDSWA */
ASM_SP_LDUB, /* LDUB */
ASM_SP_LDUBA, /*LDUBA */
ASM_SP_LDUH, /* LDUH */
ASM_SP_LDUHA, /* LDUHA */
ASM_SP_LDUW, /* LDUW */
ASM_SP_LDUWA, /* LDUWA */
ASM_SP_LDX, /* LDX */
ASM_SP_LDXA, /* LDXA */
ASM_SP_LDXFSR, /* LDXFSR */
ASM_SP_MEMBAR, /* MEMBAR */
ASM_SP_MOVA, /* MOVcc */
ASM_SP_MOVN,
ASM_SP_MOVNE,
ASM_SP_MOVE,
ASM_SP_MOVG,
ASM_SP_MOVLE,
ASM_SP_MOVGE,
ASM_SP_MOVL,
ASM_SP_MOVGU,
ASM_SP_MOVLEU,
ASM_SP_MOVCC,
ASM_SP_MOVCS,
ASM_SP_MOVPOS,
ASM_SP_MOVNEG,
ASM_SP_MOVVC,
ASM_SP_MOVVS,
ASM_SP_MOVU,
ASM_SP_MOVUG,
ASM_SP_MOVUL,
ASM_SP_MOVLG,
ASM_SP_MOVUE,
ASM_SP_MOVUGE,
ASM_SP_MOVULE,
ASM_SP_MOVO,
ASM_SP_MOVRZ, /* MOVr */
ASM_SP_MOVRLEZ,
ASM_SP_MOVRLZ,
ASM_SP_MOVRNZ,
ASM_SP_MOVRGZ,
ASM_SP_MOVRGEZ,
ASM_SP_MULSCC, /* MULScc */
ASM_SP_MULX, /* MULX */
ASM_SP_NOP, /* NOP */
ASM_SP_OR, /* OR */
ASM_SP_ORCC, /* ORcc */
ASM_SP_ORN, /* ORC */
ASM_SP_ORNCC, /* ORNcc */
ASM_SP_POPC, /* POPC */
ASM_SP_PREFETCH, /* PREFETCH */
ASM_SP_PREFETCHA, /* PREFETCHA */
ASM_SP_RD, /* RDASI, RDASR, RDCCR, RDFPRS, RDPC, RDPR, RDTICK, RDY */
ASM_SP_RDPR, /* RDPR */
ASM_SP_RESTORE, /* RESTORE */
ASM_SP_RESTORED, /* RESTORED */
ASM_SP_RETRY, /* RETRY */
ASM_SP_RETURN, /* RETURN */
ASM_SP_SAVE, /* SAVE */
ASM_SP_SAVED, /* SAVED */
ASM_SP_SDIV, /* SDIV */
ASM_SP_SDIVCC, /* SDIVcc */
ASM_SP_SDIVX, /* SDIVX */
ASM_SP_SETHI, /* SETHI */
ASM_SP_SIR, /* SIR */
ASM_SP_SLL, /* SLL */
ASM_SP_SLLX, /* SLLX */
ASM_SP_SMUL, /* SMUL */
ASM_SP_SMULCC, /* SMULcc */
ASM_SP_SQRTS, /* SQRT(s,d,q) */
ASM_SP_SQRTD,
ASM_SP_SQRTQ,
ASM_SP_SRA, /* SRA */
ASM_SP_SRAX, /* SRAX */
ASM_SP_SRL, /* SRL */
ASM_SP_SRLX, /* SRLX */
ASM_SP_STB, /* STB */
ASM_SP_STBA, /* STBA */
ASM_SP_STBAR, /* STBAR */
ASM_SP_STD, /* STD */
ASM_SP_STDA, /* STDA */
ASM_SP_STDF, /* STDF */
ASM_SP_STDFA, /* STDFA */
ASM_SP_STF, /* STF */
ASM_SP_STFA, /* STFA */
ASM_SP_STFSR, /* STFSR */
ASM_SP_STH, /* STH */
ASM_SP_STHA, /* STHA */
ASM_SP_STQF, /* STQF */
ASM_SP_STQFA, /* STQFA */
ASM_SP_STW, /* STW */
ASM_SP_STWA, /* STWA */
ASM_SP_STX, /* STX */
ASM_SP_STXA, /* STXA */
ASM_SP_STXFSR, /* STXFSR */
ASM_SP_SUB, /* SUB */
ASM_SP_SUBCC, /* SUBcc */
ASM_SP_SUBC, /* SUBC */
ASM_SP_SUBCCC, /* SUBCcc */
ASM_SP_SWAP, /* SWAP */
ASM_SP_SWAPA, /* SWAPA */
ASM_SP_TADDCC, /* TADDcc */
ASM_SP_TADDCCTV, /* TADDccTV */
ASM_SP_TA, /* Tcc */
ASM_SP_TN,
ASM_SP_TNE,
ASM_SP_TE,
ASM_SP_TG,
ASM_SP_TLE,
ASM_SP_TGE,
ASM_SP_TL,
ASM_SP_TGU,
ASM_SP_TLEU,
ASM_SP_TCC,
ASM_SP_TCS,
ASM_SP_TPOS,
ASM_SP_TNEG,
ASM_SP_TVC,
ASM_SP_TVS,
ASM_SP_TSUBCC, /* TSUBcc */
ASM_SP_TSUBCCTV, /* TSUBccTV */
ASM_SP_UDIV, /* UDIV */
ASM_SP_UDIVCC, /* UDIVcc */
ASM_SP_UDIVX, /* UDIVX */
ASM_SP_UMUL, /* UMUL */
ASM_SP_UMULCC, /* UMULcc */
ASM_SP_WR, /* WRASI, WRASR, WRCCR, WRFPRS, WRY */
ASM_SP_WRPR, /* WRPR */
ASM_SP_XNOR, /* XNOR */
ASM_SP_XNORCC, /* XNORcc */
ASM_SP_XOR, /* XOR */
ASM_SP_XORCC, /* XORcc */
ASM_SP_CMP, /* Synthetics */
ASM_SP_JMP,
ASM_SP_IPREFETCH,
ASM_SP_TST,
ASM_SP_RET,
ASM_SP_RETL,
ASM_SP_SETUW,
ASM_SP_SET,
ASM_SP_SETSW,
ASM_SP_SETX,
ASM_SP_SIGNX,
ASM_SP_NOT,
ASM_SP_NEG,
ASM_SP_CAS,
ASM_SP_CASL,
ASM_SP_CASX,
ASM_SP_CASXL,
ASM_SP_INC,
ASM_SP_INCCC,
ASM_SP_DEC,
ASM_SP_DECCC,
ASM_SP_BTST,
ASM_SP_BSET,
ASM_SP_BCLR,
ASM_SP_BTOG,
ASM_SP_CLR,
ASM_SP_CLRB,
ASM_SP_CLRH,
ASM_SP_CLRX,
ASM_SP_CLRUW,
ASM_SP_MOV,
ASM_SP_BAD
};
extern char *sparc_instr_list[ASM_SP_BAD + 1];
extern int sparc_bcc_list[16];
extern int sparc_brcc_list[8];
extern int sparc_fbcc_list[16];
extern int sparc_shift_list[6];
extern int sparc_movcc_list[16];
extern int sparc_movfcc_list[16];
extern int sparc_movr_list[8];
extern int sparc_fpop1_list[256];
extern int sparc_fmovcc_list[48];
extern int sparc_fmovfcc_list[48];
extern int sparc_fmovr_list[24];
extern int sparc_fcmp_list[8];
extern int sparc_tcc_list[16];
extern int sparc_op2_table[64];
extern int sparc_op3_table[64];
#endif
<file_sep>/src/libasm/src/arch/ia32/handlers/op_incdec_rmb.c
/*
** $Id: op_incdec_rmb.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_incdec_rmb" opcode="0xfe"/>
*/
int op_incdec_rmb(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
new->ptr_instr = opcode;
modrm = (struct s_modrm *) opcode + 1;
new->len += 1;
new->type = ASM_TYPE_ARITH | ASM_TYPE_INCDEC | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_AF | ASM_FLAG_OF | ASM_FLAG_PF |
ASM_FLAG_SF | ASM_FLAG_ZF;
switch(modrm->r) {
case 0:
new->instr = ASM_INC;
break;
case 1:
new->instr = ASM_DEC;
break;
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
break;
default:
break;
}
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODEDBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODEDBYTE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_sahf.c
/**
* @file libasm/src/arch/ia32/handlers/op_sahf.c
*
* @ingroup IA32_instrs
** $Id: op_sahf.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction opcode="0x9e" func="op_sahf"/>
*/
int op_sahf(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->ptr_instr = opcode;
new->instr = ASM_SAHF;
new->type = ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_CF | ASM_FLAG_PF | ASM_FLAG_AF |
ASM_FLAG_SF | ASM_FLAG_ZF;
return (new->len);
}
<file_sep>/src/libasm/src/arch/sparc/tables_sparc.c
/**
* @file libasm/src/arch/sparc/tables_sparc.c
** @ingroup sparc
*/
/*
** tables_sparc.c for in /hate/home/hate/code/libasm_current
**
** Made by #!HATE#@!
** Login <<EMAIL>>
**
** Started on Tue Jun 14 05:23:16 2005 #!HATE#@!
** Last update Thu Jun 16 05:39:25 2005 #!HATE#@!
**
** $Id: tables_sparc.c 1439 2010-12-13 10:27:16Z may $
**
*/
#include <libasm.h>
int sparc_op2_table[64] = {
ASM_SP_ADD,
ASM_SP_AND,
ASM_SP_OR,
ASM_SP_XOR,
ASM_SP_SUB,
ASM_SP_ANDN,
ASM_SP_ORN,
ASM_SP_XNOR,
ASM_SP_ADDC,
ASM_SP_MULX,
ASM_SP_UMUL,
ASM_SP_SMUL,
ASM_SP_SUBC,
ASM_SP_UDIVX,
ASM_SP_UDIV,
ASM_SP_SDIV,
ASM_SP_ADDCC,
ASM_SP_ANDCC,
ASM_SP_ORCC,
ASM_SP_XORCC,
ASM_SP_SUBCC,
ASM_SP_ANDNCC,
ASM_SP_ORNCC,
ASM_SP_XNORCC,
ASM_SP_ADDCCC,
ASM_SP_,
ASM_SP_UMULCC,
ASM_SP_SMULCC,
ASM_SP_SUBCCC,
ASM_SP_,
ASM_SP_UDIVCC,
ASM_SP_SDIVCC,
ASM_SP_TADDCC,
ASM_SP_TSUBCC,
ASM_SP_TADDCCTV,
ASM_SP_TSUBCCTV,
ASM_SP_MULSCC,
ASM_SP_SLL, /* SLL, SLLX */
ASM_SP_SRL, /* SRL, SRLX */
ASM_SP_SRA, /* SRA, SRAX */
ASM_SP_RD, /* RD*(-PR), MEMBAR, STBAR */
ASM_SP_,
ASM_SP_RDPR,
ASM_SP_FLUSHW,
ASM_SP_MOVA, /* MOVcc */
ASM_SP_SDIVX,
ASM_SP_POPC,
ASM_SP_MOVRZ, /* MOVr */
ASM_SP_WR, /* WR*(-PR), SIR */
ASM_SP_SAVED, /* SAVED, RESTORED */
ASM_SP_WRPR,
ASM_SP_,
ASM_SP_FMOVS, /* FPop1 */
ASM_SP_FMOVS, /* FPop2 */
ASM_SP_IMPDEP1,
ASM_SP_IMPDEP2,
ASM_SP_JMPL,
ASM_SP_RETURN,
ASM_SP_TA,
ASM_SP_FLUSH,
ASM_SP_SAVE,
ASM_SP_RESTORE,
ASM_SP_DONE, /* DONE, RETRY */
ASM_SP_
};
int sparc_op3_table[64] = {
ASM_SP_LDUW,
ASM_SP_LDUB,
ASM_SP_LDUH,
ASM_SP_LDD,
ASM_SP_STW,
ASM_SP_STB,
ASM_SP_STH,
ASM_SP_STD,
ASM_SP_LDSW,
ASM_SP_LDSB,
ASM_SP_LDSH,
ASM_SP_LDX,
ASM_SP_,
ASM_SP_LDSTUB,
ASM_SP_STX,
ASM_SP_SWAP,
ASM_SP_LDUWA,
ASM_SP_LDUBA,
ASM_SP_LDUHA,
ASM_SP_LDDA,
ASM_SP_STWA,
ASM_SP_STBA,
ASM_SP_STHA,
ASM_SP_STDA,
ASM_SP_LDSWA,
ASM_SP_LDSBA,
ASM_SP_LDSHA,
ASM_SP_LDXA,
ASM_SP_,
ASM_SP_LDSTUBA,
ASM_SP_STXA,
ASM_SP_SWAPA,
ASM_SP_LDF,
ASM_SP_LDFSR, /* LDFSR, LDXFSR */
ASM_SP_LDQF,
ASM_SP_LDDF,
ASM_SP_STF,
ASM_SP_STFSR, /* STFSR, STXFSR */
ASM_SP_STQF,
ASM_SP_STDF,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_PREFETCH,
ASM_SP_,
ASM_SP_,
ASM_SP_LDFA,
ASM_SP_,
ASM_SP_LDQFA,
ASM_SP_LDDFA,
ASM_SP_STFA,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_CASA,
ASM_SP_PREFETCHA,
ASM_SP_CASXA,
ASM_SP_
};
int sparc_bcc_list[16] = {
ASM_SP_BN,
ASM_SP_BE,
ASM_SP_BLE,
ASM_SP_BL,
ASM_SP_BLEU,
ASM_SP_BCS,
ASM_SP_BNEG,
ASM_SP_BVS,
ASM_SP_BA,
ASM_SP_BNE,
ASM_SP_BG,
ASM_SP_BGE,
ASM_SP_BGU,
ASM_SP_BCC,
ASM_SP_BPOS,
ASM_SP_BVC
};
int sparc_tcc_list[16] = {
ASM_SP_TN,
ASM_SP_TE,
ASM_SP_TLE,
ASM_SP_TL,
ASM_SP_TLEU,
ASM_SP_TCS,
ASM_SP_TNEG,
ASM_SP_TVS,
ASM_SP_TA,
ASM_SP_TNE,
ASM_SP_TG,
ASM_SP_TGE,
ASM_SP_TGU,
ASM_SP_TCC,
ASM_SP_TPOS,
ASM_SP_TVC
};
int sparc_brcc_list[8] = {
ASM_SP_,
ASM_SP_BRZ,
ASM_SP_BRLEZ,
ASM_SP_BRLZ,
ASM_SP_,
ASM_SP_BRNZ,
ASM_SP_BRGZ,
ASM_SP_BRGEZ
};
int sparc_fbcc_list[16] = {
ASM_SP_FBN,
ASM_SP_FBNE,
ASM_SP_FBLG,
ASM_SP_FBUL,
ASM_SP_FBL,
ASM_SP_FBUG,
ASM_SP_FBG,
ASM_SP_FBU,
ASM_SP_FBA,
ASM_SP_FBE,
ASM_SP_FBUE,
ASM_SP_FBGE,
ASM_SP_FBUGE,
ASM_SP_FBLE,
ASM_SP_FBULE,
ASM_SP_FBO
};
int sparc_shift_list[6] = {
ASM_SP_SLL,
ASM_SP_SLLX,
ASM_SP_SRL,
ASM_SP_SRLX,
ASM_SP_SRA,
ASM_SP_SRAX,
};
int sparc_movcc_list[16] = {
ASM_SP_MOVN,
ASM_SP_MOVE,
ASM_SP_MOVLE,
ASM_SP_MOVL,
ASM_SP_MOVLEU,
ASM_SP_MOVCS,
ASM_SP_MOVNEG,
ASM_SP_MOVVS,
ASM_SP_MOVA,
ASM_SP_MOVNE,
ASM_SP_MOVG,
ASM_SP_MOVGE,
ASM_SP_MOVGU,
ASM_SP_MOVCC,
ASM_SP_MOVPOS,
ASM_SP_MOVVC
};
int sparc_movfcc_list[16] = {
ASM_SP_MOVN,
ASM_SP_MOVNE,
ASM_SP_MOVLG,
ASM_SP_MOVUL,
ASM_SP_MOVL,
ASM_SP_MOVUG,
ASM_SP_MOVG,
ASM_SP_MOVU,
ASM_SP_MOVA,
ASM_SP_MOVE,
ASM_SP_MOVUE,
ASM_SP_MOVGE,
ASM_SP_MOVUGE,
ASM_SP_MOVLE,
ASM_SP_MOVULE,
ASM_SP_MOVO
};
int sparc_movr_list[8] = {
ASM_SP_,
ASM_SP_MOVRZ,
ASM_SP_MOVRLEZ,
ASM_SP_MOVRLZ,
ASM_SP_,
ASM_SP_MOVRNZ,
ASM_SP_MOVRGZ,
ASM_SP_MOVRGEZ
};
int sparc_fpop1_list[256] = {
ASM_SP_, /* 0x00 */
ASM_SP_FMOVS,
ASM_SP_FMOVD,
ASM_SP_FMOVQ,
ASM_SP_,
ASM_SP_FNEGS,
ASM_SP_FNEGD,
ASM_SP_FNEGQ,
ASM_SP_,
ASM_SP_FABSS,
ASM_SP_FABSD,
ASM_SP_FABSQ,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0x10 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0x20 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_SQRTS,
ASM_SP_SQRTD,
ASM_SP_SQRTQ,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0x30 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0x40 */
ASM_SP_FADDS,
ASM_SP_FADDD,
ASM_SP_FADDQ,
ASM_SP_,
ASM_SP_FSUBS,
ASM_SP_FSUBD,
ASM_SP_FSUBQ,
ASM_SP_,
ASM_SP_FMULS,
ASM_SP_FMULD,
ASM_SP_FMULQ,
ASM_SP_,
ASM_SP_FDIVS,
ASM_SP_FDIVD,
ASM_SP_FDIVQ,
ASM_SP_, /* 0x50 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0x60 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_FSMULD,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_FDMULQ,
ASM_SP_,
ASM_SP_, /* 0x70 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0x80 */
ASM_SP_FSTOX,
ASM_SP_FDTOX,
ASM_SP_FQTOX,
ASM_SP_FXTOS,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_FXTOD,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_FXTOQ,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0x90 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0xA0 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0xB0 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0xC0 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_FITOS,
ASM_SP_,
ASM_SP_FDTOS,
ASM_SP_FQTOS,
ASM_SP_FITOD,
ASM_SP_FSTOD,
ASM_SP_,
ASM_SP_FQTOD,
ASM_SP_FITOQ,
ASM_SP_FSTOQ,
ASM_SP_FDTOQ,
ASM_SP_,
ASM_SP_, /* 0xD0 */
ASM_SP_FSTOI,
ASM_SP_FDTOI,
ASM_SP_FQTOI,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0xE0 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_, /* 0xF0 */
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_,
ASM_SP_
};
int sparc_fmovcc_list[48] = {
ASM_SP_FMOVSN,
ASM_SP_FMOVSE,
ASM_SP_FMOVSLE,
ASM_SP_FMOVSL,
ASM_SP_FMOVSLEU,
ASM_SP_FMOVSCS,
ASM_SP_FMOVSNEG,
ASM_SP_FMOVSVS,
ASM_SP_FMOVSA,
ASM_SP_FMOVSNE,
ASM_SP_FMOVSG,
ASM_SP_FMOVSGE,
ASM_SP_FMOVSGU,
ASM_SP_FMOVSCC,
ASM_SP_FMOVSPOS,
ASM_SP_FMOVSVC,
ASM_SP_FMOVDN,
ASM_SP_FMOVDE,
ASM_SP_FMOVDLE,
ASM_SP_FMOVDL,
ASM_SP_FMOVDLEU,
ASM_SP_FMOVDCS,
ASM_SP_FMOVDNEG,
ASM_SP_FMOVDVS,
ASM_SP_FMOVDA,
ASM_SP_FMOVDNE,
ASM_SP_FMOVDG,
ASM_SP_FMOVDGE,
ASM_SP_FMOVDGU,
ASM_SP_FMOVDCC,
ASM_SP_FMOVDPOS,
ASM_SP_FMOVDVC,
ASM_SP_FMOVQN,
ASM_SP_FMOVQE,
ASM_SP_FMOVQLE,
ASM_SP_FMOVQL,
ASM_SP_FMOVQLEU,
ASM_SP_FMOVQCS,
ASM_SP_FMOVQNEG,
ASM_SP_FMOVQVS,
ASM_SP_FMOVQA,
ASM_SP_FMOVQNE,
ASM_SP_FMOVQG,
ASM_SP_FMOVQGE,
ASM_SP_FMOVQGU,
ASM_SP_FMOVQCC,
ASM_SP_FMOVQPOS,
ASM_SP_FMOVQVC
};
int sparc_fmovfcc_list[48] = {
ASM_SP_FMOVSN,
ASM_SP_FMOVSNE,
ASM_SP_FMOVSLG,
ASM_SP_FMOVSUL,
ASM_SP_FMOVSL,
ASM_SP_FMOVSUG,
ASM_SP_FMOVSG,
ASM_SP_FMOVSU,
ASM_SP_FMOVSA,
ASM_SP_FMOVSE,
ASM_SP_FMOVSUE,
ASM_SP_FMOVSGE,
ASM_SP_FMOVSUGE,
ASM_SP_FMOVSLE,
ASM_SP_FMOVSULE,
ASM_SP_FMOVSO,
ASM_SP_FMOVDN,
ASM_SP_FMOVDNE,
ASM_SP_FMOVDLG,
ASM_SP_FMOVDUL,
ASM_SP_FMOVDL,
ASM_SP_FMOVDUG,
ASM_SP_FMOVDG,
ASM_SP_FMOVDU,
ASM_SP_FMOVDA,
ASM_SP_FMOVDE,
ASM_SP_FMOVDUE,
ASM_SP_FMOVDGE,
ASM_SP_FMOVDUGE,
ASM_SP_FMOVDLE,
ASM_SP_FMOVDULE,
ASM_SP_FMOVDO,
ASM_SP_FMOVQN,
ASM_SP_FMOVQNE,
ASM_SP_FMOVQLG,
ASM_SP_FMOVQUL,
ASM_SP_FMOVQL,
ASM_SP_FMOVQUG,
ASM_SP_FMOVQG,
ASM_SP_FMOVQU,
ASM_SP_FMOVQA,
ASM_SP_FMOVQE,
ASM_SP_FMOVQUE,
ASM_SP_FMOVQGE,
ASM_SP_FMOVQUGE,
ASM_SP_FMOVQLE,
ASM_SP_FMOVQULE,
ASM_SP_FMOVQO
};
int sparc_fmovr_list[24] = {
ASM_SP_,
ASM_SP_FMOVRSZ,
ASM_SP_FMOVRSLEZ,
ASM_SP_FMOVRSLZ,
ASM_SP_,
ASM_SP_FMOVRSNZ,
ASM_SP_FMOVRSGZ,
ASM_SP_FMOVRSGEZ,
ASM_SP_,
ASM_SP_FMOVRDZ,
ASM_SP_FMOVRDLEZ,
ASM_SP_FMOVRDLZ,
ASM_SP_,
ASM_SP_FMOVRDNZ,
ASM_SP_FMOVRDGZ,
ASM_SP_FMOVRDGEZ,
ASM_SP_,
ASM_SP_FMOVRQZ,
ASM_SP_FMOVRQLEZ,
ASM_SP_FMOVRQLZ,
ASM_SP_,
ASM_SP_FMOVRQNZ,
ASM_SP_FMOVRQGZ,
ASM_SP_FMOVRQGEZ
};
int sparc_fcmp_list[8] = {
ASM_SP_,
ASM_SP_FCMPS,
ASM_SP_FCMPD,
ASM_SP_FCMPQ,
ASM_SP_,
ASM_SP_FCMPES,
ASM_SP_FCMPED,
ASM_SP_FCMPEQ
};
char *sparc_instr_list[ASM_SP_BAD + 1] = {
"(unimpl)",
"add", /* ADD */
"addcc", /* ADDcc */
"addc", /* ADDC */
"addccc", /* ADDCcc */
"and", /* AND */
"andcc", /* ANDcc */
"andn", /* ANDN */
"andncc", /* ANDNcc */
"ba", /* BPcc, Bicc */
"bn",
"bne",
"be",
"bg",
"ble",
"bge",
"bl",
"bgu",
"bleu",
"bcc",
"bcs",
"bpos",
"bneg",
"bvc",
"bvs",
"brz", /* BPr */
"brlez",
"brlz",
"brnz",
"brgz",
"brgez",
"call", /* CALL */
"casa", /* CASA */
"casxa", /* CASXA */
"done", /* DONE */
"fabss", /* FABS(s,d,q) */
"fabsd",
"fabsq",
"fadds", /* FADD(s,d,q) */
"faddd",
"faddq",
"fba", /* FBfcc, FBPfcc */
"fbn",
"fbu",
"fbg",
"fbug",
"fbl",
"fbul",
"fblg",
"fbne",
"fbe",
"fbue",
"fbge",
"fbuge",
"fble",
"fbule",
"fbo",
"fcmps", /* FCMP(s,d,q) */
"fcmpd",
"fcmpq",
"fcmpes", /* FCMPE(s,d,q) */
"fcmped",
"fcmpeq",
"fdivs", /* FDIV(s,d,q) */
"fdivd",
"fdivq",
"fdmulq", /* FdMULq */
"fitos", /* FiTO(s,d,q) */
"fitod",
"fitoq",
"flush", /* FLUSH */
"flushw", /* FLUSHW */
"fmovs", /* FMOV(s,d,q) */
"fmovd",
"fmovq",
"fmovsa", /* FMOV(s,d,q)cc */
"fmovsn",
"fmovsne",
"fmovse",
"fmovsg",
"fmovsle",
"fmovsge",
"fmovsl",
"fmovsgu",
"fmovsleu",
"fmovscc",
"fmovscs",
"fmovspos",
"fmovsneg",
"fmovsvc",
"fmovsvs",
"fmovsu",
"fmovsug",
"fmovsul",
"fmovslg",
"fmovsue",
"fmovsuge",
"fmovsule",
"fmovso",
"fmovda",
"fmovdn",
"fmovdne",
"fmovde",
"fmovdg",
"fmovdle",
"fmovdge",
"fmovdl",
"fmovdgu",
"fmovdleu",
"fmovdcc",
"fmovdcs",
"fmovdpos",
"fmovdneg",
"fmovdvc",
"fmovdvs",
"fmovdu",
"fmovdug",
"fmovdul",
"fmovdlg",
"fmovdue",
"fmovduge",
"fmovdule",
"fmovdo",
"fmovqa",
"fmovqn",
"fmovqne",
"fmovqe",
"fmovqg",
"fmovqle",
"fmovqge",
"fmovql",
"fmovqgu",
"fmovqleu",
"fmovqcc",
"fmovqcs",
"fmovqpos",
"fmovqneg",
"fmovqvc",
"fmovqvs",
"fmovqu",
"fmovqug",
"fmovqul",
"fmovqlg",
"fmovque",
"fmovquge",
"fmovqule",
"fmovo",
"fmovrsz", /* FMOV(s,d,q)r */
"fmovrslez",
"fmovrslz",
"fmovrsnz",
"fmovrsgz",
"fmovrsgez",
"fmovrdz",
"fmovrdlez",
"fmovrdlz",
"fmovrdnz",
"fmovrdgz",
"fmovrdgez",
"fmovrqz",
"fmovrqlez",
"fmovrqlz",
"fmovrqnz",
"fmovrqgz",
"fmovrqgez",
"fmuls", /* FMUL(s,d,q) */
"fmuld",
"fmulq",
"fnegs", /* FNEG(s,d,q) */
"fnegd",
"fnegq",
"fsmuld", /* FsMULd */
"fsqrts", /* FSQRT(s,d,q) */
"fsqrtd",
"fsqrtq",
"fstoi", /* F(s,d,q)TOi */
"fdtoi",
"fqtoi",
"fstod", /* F(s,d,q)TO(s,d,q) */
"fstoq",
"fdtos",
"fdtoq",
"fqtos",
"fqtod",
"fstox", /* F(s,d,q)TOx */
"fdtox",
"fqtox",
"fsubs", /* FSUB(s,d,q) */
"fsubd",
"fsubq",
"fxtos", /* FxTO(s,d,q) */
"fxtod",
"fxtoq",
"illtrap", /* ILLTRAP */
"impdep1", /* IMPDEP1 and IMPDEP2 are not real names, these are
* implementation-specific instruction. Maybe we should let
* the user specify a name for these instructions?
*/
"impdep2",
"jmpl", /* JMPL, RET, RETL */
"ldd", /* LDD */
"ldda", /* LDDA */
"ldd", /* LDFF */
"ldda", /* LDDFA */
"ld", /* LDF */
"lda", /* LDFA */
"ld", /* LDFSR */
"ldq", /* LDQF */
"ldqa", /* LDQFA */
"ldsb", /* LDSB */
"ldsba", /* LDSBA */
"ldsh", /* LDSH */
"ldsha", /* LDSHA */
"ldstub", /* LDSTUB */
"ldstuba", /* LDSTUBA */
"ldsw", /* LDSW */
"ldswa", /* LDSWA */
"ldub", /* LDUB */
"lduba", /*LDUBA */
"lduh", /* LDUH */
"lduha", /* LDUHA */
"ld", /* LDUW */
"lduwa", /* LDUWA */
"ldx", /* LDX */
"ldxa", /* LDXA */
"ldx", /* LDXFSR */
"membar", /* MEMBAR */
"mova", /* MOVcc */
"movn",
"movne",
"move",
"movg",
"movle",
"movge",
"movl",
"movgu",
"movleu",
"movcc",
"movcs",
"movpos",
"movneg",
"movvc",
"movvs",
"movu",
"movug",
"movul",
"movlg",
"movue",
"movuge",
"movule",
"movo",
"movrz", /* MOVr */
"movrlez",
"movrlz",
"movrnz",
"movrgz",
"movrgez",
"mulscc", /* MULScc */
"mulx", /* MULX */
"nop", /* NOP */
"or", /* OR */
"orcc", /* ORcc */
"orn", /* ORC */
"orncc", /* ORNcc */
"popc", /* POPC */
"prefetch", /* PREFETCH */
"prefetcha", /* PREFETCHA */
"rd", /* RDASI, RDASR, RDCCR, RDFPRS, RDPC, RDTICK, RDY */
"rdpr", /* RDPR */
"restore", /* RESTORE */
"restored", /* RESTORED */
"retry", /* RETRY */
"return", /* RETURN */
"save", /* SAVE */
"saved", /* SAVED */
"sdiv", /* SDIV */
"sdivcc", /* SDIVcc */
"sdivx", /* SDIVX */
"sethi", /* SETHI */
"sir", /* SIR */
"sll", /* SLL */
"sllx", /* SLLX */
"smul", /* SMUL */
"smulcc", /* SMULcc */
"sqrts", /* SQRT(s,d,q) */
"sqrtd",
"sqrtq",
"sra", /* SRA */
"srax", /* SRAX */
"srl", /* SRL */
"srlx", /* SRLX */
"stb", /* STB */
"stba", /* STBA */
"stbar", /* STBAR */
"std", /* STD */
"stda", /* STDA */
"std", /* STDF */
"stda", /* STDFA */
"st", /* STF */
"sta", /* STFA */
"st", /* STFSR */
"sth", /* STH */
"stha", /* STHA */
"stq", /* STQF */
"stqa", /* STQFA */
"st", /* STW */
"stwa", /* STWA */
"stx", /* STX */
"stxa", /* STXA */
"stx", /* STXFSR */
"sub", /* SUB */
"subcc", /* SUBcc */
"subc", /* SUBC */
"subccc", /* SUBCcc */
"swap", /* SWAP */
"swapa", /* SWAPA */
"taddcc", /* TADDcc */
"taddcctv", /* TADDccTV */
"ta", /* Tcc */
"tn",
"tne",
"te",
"tg",
"tle",
"tge",
"tl",
"tgu",
"tleu",
"tcc",
"tcs",
"tpos",
"tneg",
"tvc",
"tvs",
"tsubcc", /* TSUBcc */
"tsubcctv", /* TSUBccTV */
"udiv", /* UDIV */
"udivcc", /* UDIVcc */
"udivx", /* UDIVX */
"umul", /* UMUL */
"umulcc", /* UMULcc */
"wr", /* WRASI, WRASR, WRCCR, WRFPRS, WRY */
"wrpr", /* WRPR */
"xnor", /* XNOR */
"xnorcc", /* XNORcc */
"xor", /* XOR */
"xorcc", /* XORcc */
"cmp", /* Synthetics */
"jmp",
"iprefetch",
"tst",
"ret",
"retl",
"setuw",
"set",
"setsw",
"setx",
"signx",
"not",
"neg",
"cas",
"casl",
"casx",
"casxl",
"inc", // inc is a add
"inccc", //inccc = addcc
"dec", // dec is a sub
"deccc", // deccc is a subcc
"btst",
"bset",
"bclr",
"btog", // btog is a xor
"clr",
"clrb",
"clrh",
"clrx",
"clruw",
"mov",
"(bad)"
};
<file_sep>/src/libasm/src/arch/ia32/handlers/op_prefix_ss.c
/*
** $Id: op_prefix_ss.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_prefix_ss" opcode="0x36"/>
*/
int op_prefix_ss(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->prefix |= ASM_PREFIX_SS;
if (!new->ptr_prefix)
new->ptr_prefix = opcode;
return (proc->fetch(new, opcode + 1, len - 1, proc));
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_popa.c
/*
** $Id: op_popa.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for the popa instruction. Opcode = 0x61
* @param new Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of buffer to disassemble.
* @param proc Pointer to processor structure.
*/
int op_popa(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->ptr_instr = opcode;
new->instr = ASM_POPA;
new->spdiff = 8 * 4;
new->type = ASM_TYPE_TOUCHSP | ASM_TYPE_LOAD;
return (new->len);
}
<file_sep>/src/libasm/src/arch/mips/operand_handlers/asm_mips_operand_fetch.c
/**
* @defgroup MIPS_operands MIPS operands API.
* @ingroup mips
*/
/**
* @file libasm/src/arch/mips/operand_handlers/asm_mips_operand_fetch.c
** @ingroup MIPS_operands
*/
/*
* Started by Adam 'pi3' Zabrocki
* $Id: asm_mips_operand_fetch.c 1397 2009-09-13 02:19:08Z may $
*/
#include <libasm.h>
int asm_mips_operand_fetch(asm_operand *op, u_char *opcode, int otype,
asm_instr *ins)
{
vector_t *vec;
u_int dim[1];
int ret;
int (*func_op)(asm_operand *op, u_char *opcode, int otype, asm_instr *ins);
vec = aspect_vector_get(LIBASM_VECTOR_OPERAND_MIPS);
dim[0] = otype;
func_op = aspect_vectors_select(vec, dim);
if ( (ret = func_op(op, opcode, otype, ins)) == -1) {
printf("%s:%i Unsupported operand content : %i\n", __FILE__, __LINE__,
otype);
}
return (ret);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_wr.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_wr.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_wr.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libasm.h"
int
asm_sparc_wr(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_format3 opcode;
struct s_asm_proc_sparc *inter;
sparc_convert_format3(&opcode, buf);
inter = proc->internals;
ins->instr = inter->op2_table[opcode.op3];
ins->type = ASM_TYPE_ASSIGN;
if (opcode.rd == 1)
ins->instr = ASM_SP_BAD;
else if (opcode.rd == 15) { /* SIR */
ins->instr = ASM_SP_SIR;
ins->type = ASM_TYPE_INT;
ins->nb_op = 1;
ins->op[0].imm = opcode.imm;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_IMMEDIATE, ins);
}
else { /* WR */
ins->nb_op = 3;
if (opcode.rd == 2) { /* WRCCR overwrites the condition codes */
ins->type |= ASM_TYPE_WRITEFLAG;
ins->flagswritten = ASM_SP_FLAG_C | ASM_SP_FLAG_V | ASM_SP_FLAG_Z | ASM_SP_FLAG_N;
}
if (opcode.rd == 4 || opcode.rd == 5) /* can't write PC or TICK */
ins->op[0].baser = ASM_SREG_BAD;
else
ins->op[0].baser = opcode.rd;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_SREGISTER, ins);
ins->op[2].baser = opcode.rs1;
asm_sparc_op_fetch(&ins->op[2], buf, ASM_SP_OTYPE_REGISTER, ins);
if (opcode.i == 0) {
ins->op[1].baser = opcode.rs2;
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_REGISTER, ins);
}
else {
ins->op[1].imm = opcode.imm;
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_IMMEDIATE, ins);
}
if (ins->op[0].baser == ASM_SREG_Y && ins->op[2].baser == ASM_REG_G0) {
ins->instr = ASM_SP_MOV;
ins->nb_op = 2;
}
}
return 4;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_retf_i2.c
/**
* @file libasm/src/arch/ia32/handlers/op_retf_i2.c
*
* @ingroup IA32_instrs
** $Id: op_retf_i2.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_retf_i2" opcode="0xca"/>
*/
int op_retf_i2(asm_instr *instr, u_char *opcode, u_int len,
asm_processor *proc)
{
instr->instr = ASM_RETF;
instr->ptr_instr = opcode;
instr->len += 1;
instr->type = ASM_TYPE_RETPROC | ASM_TYPE_TOUCHSP | ASM_TYPE_EPILOG;
#if WIP
instr->len += asm_operand_fetch(&instr->op[0], opcode + 1,
ASM_OTYPE_IMMEDIATEWORD, instr, 0);
#else
instr->len += asm_operand_fetch(&instr->op[0], opcode + 1,
ASM_OTYPE_IMMEDIATEWORD, instr);
#endif
return (instr->len);
}
<file_sep>/src/libasm/src/arch/ia32/operand_ia32.c
/**
* @file libasm/src/arch/ia32/operand_ia32.c
* @ingroup ia32
** $Id: operand_ia32.c 1397 2009-09-13 02:19:08Z may $
**
** Author : <sk at devhell dot org>
** Started : Tue May 28 13:06:39 2002
** Updated : Sun Mar 21 00:39:09 2004
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @brief Extracts operands from memory and stores them in instruction.
* @todo This function should not be called.
*/
int operand_rmb_ib(asm_instr *ins, u_char *opcode,
int len, asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode;
operand_rmb(&ins->op[0], opcode, len, proc);
ins->op[1].content = ASM_OP_VALUE;
ins->op[1].len = 1;
ins->op[1].ptr = opcode + (ins->op[0].len ? ins->op[0].len : 1);
// if (*(opcode + ins->op1.len) >= 0x80u)
// memcpy((char *) &ins->op2.imm + 1, "\xff\xff\xff", 3);
// else
ins->op[1].imm = 0;
memcpy(&ins->op[1].imm, opcode + (ins->op[0].len ? ins->op[0].len : 1), 1);
ins->len += (ins->op[0].len ? ins->op[0].len : 1) + ins->op[1].len;
return (1);
}
/**
* @brief Decode a modRM operand of size Byte.
*
* @param op Pointer to operand to fill.
* @param opcode Pointer to operand bytes.
* @param len Length of data.
* @param proc Pointer to processor structure
* @return Length of the operand.
*
*/
int operand_rmb(asm_operand *op, u_char *opcode, u_int len, asm_processor *proc)
{
struct s_modrm *modrm;
struct s_sidbyte *sidbyte;
u_char mode;
u_char pmode;
modrm = (struct s_modrm *) (opcode);
sidbyte = (struct s_sidbyte *) (opcode + 1);
mode = asm_ia32_get_mode(proc);
pmode = (mode == INTEL_PROT);
#if __DEBUG_MODRM__
fprintf(stderr, "[DEBUG_MODRM] IA32 processor in %c-mode (RMB) \n",
(pmode ? 'p' : (mode == INTEL_REAL ? 'r' : 'U')));
#endif
switch (modrm->mod)
{
/** mod == 00 : operand base */
case 0:
switch (modrm->m)
{
case ASM_REG_ESP:
if (sidbyte->base == ASM_REG_EBP)
{
op->content = ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_INDEX | ASM_OP_SCALE;
op->regset = ASM_REGSET_R32;
op->len = (pmode ? 6 : 4); //
op->ptr = opcode;
op->scale = asm_int_pow2(sidbyte->sid);
// erased by the following memcpy !?
//if (((unsigned char)*(opcode + 2)) >= 0x80)
//memcpy((char *) &op->imm + 2, "\xff\xff", 2);
//else
//op->imm = 0;
memcpy((char *) &op->imm, opcode + 2, (pmode ? 4 : 2)); //
op->indexr = sidbyte->index;
}
else
{
if ((op->indexr = sidbyte->index) != ASM_REG_ESP)
op->content = ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE;
else
op->content = ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_SCALE;
op->len = 2;
op->ptr = opcode;
op->regset = ASM_REGSET_R32;
op->baser = sidbyte->base;
op->scale = asm_int_pow2(sidbyte->sid);
}
break;
case ASM_REG_EBP:
op->content = ASM_OP_REFERENCE | ASM_OP_VALUE;
op->ptr = opcode;
op->len = (pmode ? 5 : 3); //
memcpy(&op->imm, opcode + 1, (pmode ? 4 : 2)); //
break;
default:
op->ptr = opcode;
op->len = 1;
op->content = ASM_OP_REFERENCE | ASM_OP_BASE;
op->baser = modrm->m;
op->regset = pmode ? ASM_REGSET_R32 : ASM_REGSET_R16;
break;
}
break;
/** mod == 01 : operand : base + sbyte */
case 1:
if (modrm->m == ASM_REG_ESP)
{
if ((op->indexr = sidbyte->index) != ASM_REG_ESP)
op->content = ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE;
else
op->content = ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_BASE | ASM_OP_SCALE;
op->ptr = opcode;
op->len = (pmode ? 3 : 1); //
op->regset = ASM_REGSET_R32;
op->baser = sidbyte->base;
op->indexr = sidbyte->index;
op->scale = asm_int_pow2(sidbyte->sid);
if (*(opcode + 2) >= 0x80u)
memset((char *) &op->imm + 1, '\xff', (pmode ? 3 : 1)); //
else
op->imm = 0;
memcpy(&op->imm, opcode + 2, 1);
}
else
{
op->content = ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_VALUE;
op->len = 2; // ?????
op->baser = modrm->m;
op->regset = ASM_REGSET_R32;
if (*(opcode + 1) >= 0x80u)
memset((char *) &op->imm + 1, '\xff', (pmode ? 3 : 1)); //
else
op->imm = 0;
memcpy(&op->imm, opcode + 1, 1);
}
break;
/** mod == 10 : operand base + sdword */
case 2:
op->ptr = opcode;
if (modrm->m == ASM_REG_ESP)
{
if (sidbyte->base == ASM_REG_ESP)
op->content = ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE;
else
op->content = ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE;
op->regset = ASM_REGSET_R32;
op->baser = sidbyte->base;
op->indexr = sidbyte->index;
op->scale = asm_int_pow2(sidbyte->sid);
op->len = (pmode ? 6 : 4); //
memcpy(&op->imm, opcode + 2, (pmode ? 4 : 2)); //
}
else
{
op->content = ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_VALUE;
op->len = (pmode ? 5 : 3); //
op->regset = ASM_REGSET_R32;
op->baser = modrm->m;
op->imm = 0;
memcpy(&op->imm, opcode + 1, (pmode ? 4 : 2)); //
}
break;
/*
if (modrm->m == ASM_REG_ESP)
op->content = ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_VALUE;
op->len = 5;
op->baser = modrm->m;
op->regset = ASM_REGSET_R32;
memcpy(&op->imm, opcode + 1, 4);
op->baser;
op->imm;
break;
*/
/* mod == 3 */
case 3:
op->content = ASM_OP_BASE;
op->regset = ASM_REGSET_R8;
op->len = 1;
op->ptr = opcode;
op->baser = modrm->m;
break;
}
return (op->len);
}
/***
*
*
*
*/
int operand_rmv(asm_operand *op, u_char *opcode, u_int len, asm_processor *proc)
{
struct s_modrm *modrm;
struct s_sidbyte *sidbyte;
u_char mode;
u_char pmode;
mode = asm_ia32_get_mode(proc);
pmode = (mode == INTEL_PROT);
#if __DEBUG_MODRM__
fprintf(stderr, "[DEBUG_MODRM] IA32 processor in %c-mode (RMV) \n",
(pmode ? 'p' : (mode == INTEL_REAL ? 'r' : 'U')));
#endif
modrm = (struct s_modrm *) (opcode);
sidbyte = (struct s_sidbyte *) (opcode + 1);
op->regset = pmode ? ASM_REGSET_R32 : ASM_REGSET_R16;
switch (modrm->mod)
{
/* modrm->mod = 0 */
case 0:
switch (modrm->m)
{
/* modrm == ESP */
case ASM_REG_ESP:
switch (sidbyte->base)
{
case ASM_REG_EBP:
/* pushl 0x8050fe0(,%eax,4) ; opcode = 'ff 34 85 e0 0f 05 08' */
op->content = ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_INDEX | ASM_OP_SCALE;
op->regset = ASM_REGSET_R32;
op->len = (pmode ? 6 : 4); //
op->ptr = opcode;
op->scale = asm_int_pow2(sidbyte->sid);
memcpy((char *) &op->imm, opcode + 2, (pmode ? 4 : 2)); //
op->baser = -1;
op->indexr = sidbyte->index;
break;
case ASM_REG_ESP:
op->content = ASM_OP_REFERENCE | ASM_OP_SCALE | ASM_OP_BASE;
op->len = 2;
op->baser = sidbyte->base;
op->scale = asm_int_pow2(sidbyte->sid);
break;
default:
op->content = ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE;
// op->content = ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE;
op->len = 2;
op->ptr = opcode;
op->regset = ASM_REGSET_R32;
op->baser = sidbyte->base;
op->scale = asm_int_pow2(sidbyte->sid);
op->indexr = sidbyte->index;
break;
}
break;
/* modrm == EBP */
case ASM_REG_EBP:
op->content = ASM_OP_REFERENCE | ASM_OP_VALUE;
op->ptr = opcode;
op->len = (pmode ? 5 : 3); //
memcpy(&op->imm, opcode + 1, (pmode ? 4 : 2)); //
break;
/* modrm != EBP and modrm != ESP */
default:
op->ptr = opcode;
op->len = 1;
op->content = ASM_OP_REFERENCE | ASM_OP_BASE;
op->baser = modrm->m;
break;
}
break;
/* modrm->mod = 1 */
case 1:
if (modrm->m == ASM_REG_ESP)
{
if (sidbyte->base == ASM_REG_ESP)
op->content = ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_BASE | ASM_OP_SCALE;
else
op->content = ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE;
op->ptr = opcode;
op->len = 3; // ????
op->regset = ASM_REGSET_R32;
op->baser = sidbyte->base;
op->indexr = sidbyte->index;
op->scale = asm_int_pow2(sidbyte->sid);
if (*(opcode + 2) >= 0x80u)
memset((char *) &op->imm + 1, '\xff', (pmode ? 3 : 1)); //
else
op->imm = 0;
memcpy(&op->imm, opcode + 2, 1);
}
else
{
op->content = ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_VALUE;
op->len = 2; // ?????
op->regset = ASM_REGSET_R32;
op->baser = modrm->m;
if (*(opcode + 1) >= 0x80u)
memset((char *) &op->imm + 1, '\xff', (pmode ? 3 : 1)); //
else
op->imm = 0;
memcpy(&op->imm, opcode + 1, 1);
}
break;
/* modrm->mod = 2 */
case 2:
if (modrm->m == ASM_REG_ESP)
{
if (sidbyte->base == ASM_REG_ESP)
op->content = ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_BASE | ASM_OP_SCALE;
else
op->content = ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE;
op->len = (pmode ? 6 : 4); //
op->ptr = opcode;
op->baser = sidbyte->base;
op->regset = ASM_REGSET_R32;
op->indexr = sidbyte->index;
op->scale = asm_int_pow2(sidbyte->sid);
memcpy(&op->imm, opcode + 2, (pmode ? 4 : 2)); //
}
else
{
op->content = ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_VALUE;
op->len = (pmode ? 5 : 3); //
op->ptr = opcode;
op->regset = ASM_REGSET_R32;
op->baser = modrm->m;
memcpy(&op->imm, opcode + 1, (pmode ? 4 : 2)); //
}
break;
/* modrm->mod = 3 */
case 3:
op->content = ASM_OP_BASE;
op->len = 1;
op->ptr = opcode;
op->regset = asm_proc_opsize(proc) ? ASM_REGSET_R16 : ASM_REGSET_R32;
op->baser = modrm->m;
break;
}
return (op->len);
}
/**
* Note about operand content field.
* This field contain two packed value
* one for the content of the operand, which is a bitfield,
* and an otype value which is the type of the operand.
* This type is related to the sandpile.org reference and
* to the enum ASM_OTYPE_* (!!add link to enum!!)
*/
/**
* Pack content and otype values of the content field.
* @param content
* @param otype
*/
int asm_content_pack(asm_operand *op, int content, int otype)
{
return (0);
}
/**
* Return content part of the content field
*/
int asm_content_extract_otype(asm_operand *op)
{
return (0);
}
/**
* Return otype part of the content field
* param asm_op_content Content field of an operand.
*/
int asm_content_extract_content(asm_operand *op)
{
return (0);
}
/**
* Return a packed value for asm_operand_fetch_fixed optional parameters.
* @todo Implement this correctly.
* opt may be a regset or nothing
* value may be a register, or a fixed value
* otype is an
*/
int asm_fixed_pack(int otype, int content, int value, int opt)
{
return (otype | content | value | opt);
}
<file_sep>/src/libasm/src/arch/sparc/output_sparc.c
/**
* @file libasm/src/arch/sparc/output_sparc.c
** @ingroup sparc
*/
/*
** output_sparc.c for in /hate/home/hate/code/libasm_current
**
** Made by #!HATE#@!
** Login <<EMAIL>>
**
** Started on Fri Jun 10 14:06:47 2005 #!HATE#@!
** Last update Thu Jun 16 05:41:18 2005 #!HATE#@!
**
** $Id: output_sparc.c 1439 2010-12-13 10:27:16Z may $
**
*/
#include <libasm.h>
#include <libasm-sparc.h>
void asm_resolve_sparc(void *d, eresi_Addr val, char *buf, u_int len)
{
uint32_t addr;
/* Address are always 32bits long on sparc, even for the ultra-64 architecture */
addr = (uint32_t) val;
sprintf(buf, "0x%X", addr);
}
char *get_sparc_register(int reg)
{
switch(reg) {
case ASM_REG_G0: return "%g0";
case ASM_REG_G1: return "%g1";
case ASM_REG_G2: return "%g2";
case ASM_REG_G3: return "%g3";
case ASM_REG_G4: return "%g4";
case ASM_REG_G5: return "%g5";
case ASM_REG_G6: return "%g6";
case ASM_REG_G7: return "%g7";
case ASM_REG_O0: return "%o0";
case ASM_REG_O1: return "%o1";
case ASM_REG_O2: return "%o2";
case ASM_REG_O3: return "%o3";
case ASM_REG_O4: return "%o4";
case ASM_REG_O5: return "%o5";
case ASM_REG_O6: return "%sp";
case ASM_REG_O7: return "%o7";
case ASM_REG_L0: return "%l0";
case ASM_REG_L1: return "%l1";
case ASM_REG_L2: return "%l2";
case ASM_REG_L3: return "%l3";
case ASM_REG_L4: return "%l4";
case ASM_REG_L5: return "%l5";
case ASM_REG_L6: return "%l6";
case ASM_REG_L7: return "%l7";
case ASM_REG_I0: return "%i0";
case ASM_REG_I1: return "%i1";
case ASM_REG_I2: return "%i2";
case ASM_REG_I3: return "%i3";
case ASM_REG_I4: return "%i4";
case ASM_REG_I5: return "%i5";
case ASM_REG_I6: return "%fp";
case ASM_REG_I7: return "%i7";
default: return "bad";
}
}
/* Get SPARC state register */
char *get_sparc_sregister(int reg)
{
switch(reg) {
case ASM_SREG_Y: return "%y";
case ASM_SREG_CCR: return "%ccr";
case ASM_SREG_ASI: return "%asi";
case ASM_SREG_TICK: return "%tick";
case ASM_SREG_PC: return "%pc";
case ASM_SREG_FPRS: return "%fprs";
default: return "bad";
}
}
/* Get SPARC privileged register */
char *get_sparc_pregister(int reg)
{
switch(reg) {
case ASM_PREG_TPC: return "%tpc";
case ASM_PREG_TNPC: return "%tnpc";
case ASM_PREG_TSTATE: return "%tstate";
case ASM_PREG_TT: return "%tt";
case ASM_PREG_TICK: return "%tick";
case ASM_PREG_TBA: return "%tba";
case ASM_PREG_PSTATE: return "%pstate";
case ASM_PREG_TL: return "%tl";
case ASM_PREG_PIL: return "%pil";
case ASM_PREG_CWP: return "%cwp";
case ASM_PREG_CANSAVE: return "%cansave";
case ASM_PREG_CANRESTORE: return "%canrestore";
case ASM_PREG_CLEANWIN: return "%cleanwin";
case ASM_PREG_OTHERWIN: return "%otherwin";
case ASM_PREG_WSTATE: return "%wstate";
case ASM_PREG_FQ: return "%fq";
case ASM_PREG_VER: return "%ver";
default: return "bad";
}
}
/* Get SPARC floating-point register */
char *get_sparc_fregister(int reg)
{
switch(reg) {
case ASM_FREG_FSR: return "%fsr";
case 0: return "%f0";
case 1: return "%f1";
case 2: return "%f2";
case 3: return "%f3";
case 4: return "%f4";
case 5: return "%f5";
case 6: return "%f6";
case 7: return "%f7";
case 8: return "%f8";
case 9: return "%f9";
case 10: return "%f10";
case 11: return "%f11";
case 12: return "%f12";
case 13: return "%f13";
case 14: return "%f14";
case 15: return "%f15";
case 16: return "%f16";
case 17: return "%f17";
case 18: return "%f18";
case 19: return "%f19";
case 20: return "%f20";
case 21: return "%f21";
case 22: return "%f22";
case 23: return "%f23";
case 24: return "%f24";
case 25: return "%f25";
case 26: return "%f26";
case 27: return "%f27";
case 28: return "%f28";
case 29: return "%f29";
case 30: return "%f30";
case 31: return "%f31";
case 32: return "%f32";
case 34: return "%f34";
case 36: return "%f36";
case 38: return "%f38";
case 40: return "%f40";
case 42: return "%f42";
case 44: return "%f44";
case 46: return "%f46";
case 48: return "%f48";
case 50: return "%f50";
case 52: return "%f52";
case 54: return "%f54";
case 56: return "%f56";
case 58: return "%f58";
case 60: return "%f60";
case 62: return "%f62";
default: return "bad";
}
}
/* Get SPARC condition code */
char *get_sparc_cc(int cc)
{
switch(cc) {
case ASM_SP_FCC0: return "%fcc0";
case ASM_SP_FCC1: return "%fcc1";
case ASM_SP_FCC2: return "%fcc2";
case ASM_SP_FCC3: return "%fcc3";
case ASM_SP_ICC: return "%icc";
case ASM_SP_XCC: return "%xcc";
default: return "bad";
}
}
/**
* Dump a sparc operand to a buffer.
* @param ins Pointer to instruction structure.
* @param num Number of the operand to dump
* @param addr Address of the instruction
* @param buf Buffer to store operand ascii representation.
*/
void asm_sparc_dump_operand(asm_instr *ins, int num,
eresi_Addr addr, char *buf)
{
asm_operand *op;
eresi_Addr address;
switch (num)
{
case 1: op = &ins->op[0]; break;
case 2: op = &ins->op[1]; break;
case 3: op = &ins->op[2]; break;
default: return;
}
switch (op->content)
{
case ASM_SP_OTYPE_REGISTER:
sprintf(buf, "%s", get_sparc_register(op->baser));
break;
case ASM_SP_OTYPE_SREGISTER:
sprintf(buf, "%s", get_sparc_sregister(op->baser));
break;
case ASM_SP_OTYPE_PREGISTER:
sprintf(buf, "%s", get_sparc_pregister(op->baser));
break;
case ASM_SP_OTYPE_FREGISTER:
sprintf(buf, "%s", get_sparc_fregister(op->baser));
break;
case ASM_SP_OTYPE_CC:
sprintf(buf, "%s", get_sparc_cc(op->baser));
break;
case ASM_SP_OTYPE_IMMEDIATE:
if (op->imm < 10)
sprintf(buf, "%i", op->imm);
else
sprintf(buf, "0x%x", op->imm);
break;
case ASM_SP_OTYPE_SETHI:
if (op->imm)
sprintf(buf, "%%hi(0x%x)", op->imm << 10);
else
sprintf(buf, "%%hi(%x)", op->imm << 10);
break;
case ASM_SP_OTYPE_DISPLACEMENT:
address = addr + (op->imm << 2);
ins->proc->resolve_immediate(ins->proc->resolve_data, address, buf, 42);
break;
case ASM_SP_OTYPE_DISP30:
address = addr + (op->imm << 2);
ins->proc->resolve_immediate(ins->proc->resolve_data, address, buf, 42);
break;
case ASM_SP_OTYPE_IMM_ADDRESS:
sprintf(buf, "[%s", get_sparc_register(op->baser));
if (op->imm)
sprintf(buf + strlen(buf), " + 0x%x", op->imm);
sprintf(buf + strlen(buf), "]");
if (op->address_space != ASM_SP_ASI_P)
sprintf(buf + strlen(buf), " %%asi");
break;
case ASM_SP_OTYPE_REG_ADDRESS:
if (op->indexr > 0)
sprintf(buf, "[%s + %s]",
get_sparc_register(op->baser),
get_sparc_register(op->indexr));
else
sprintf(buf, "[%s]", get_sparc_register(op->baser));
if (op->address_space != ASM_SP_ASI_P)
sprintf(buf + strlen(buf), " 0x%x", op->address_space);
break;
default:
sprintf(buf, "err");
}
}
/**
* Return a pointer to a static buffer containing
*
*
*/
char *asm_sparc_display_instr(asm_instr *instr, eresi_Addr addr)
{
static char buffer[1024];
memset(buffer, 0, 1024);
sprintf(buffer, "%s", instr->proc->instr_table[instr->instr]);
// just debugging to be able to break
if (!strcmp(instr->proc->instr_table[instr->instr], "btog"))
{
*buffer = *buffer;
}
if ((instr->type & ASM_TYPE_BRANCH) && (instr->type & ASM_TYPE_CONDCONTROL))
{
if (instr->annul)
strcat(buffer, ",a");
if (!instr->prediction)
strcat(buffer, ",pn");
}
if (instr->nb_op > 0)
{
strcat(buffer, " ");
if (instr->nb_op == 3)
{
asm_sparc_dump_operand(instr, 3, addr, buffer + strlen(buffer));
strcat(buffer, ", ");
}
if (instr->nb_op >= 2)
{
asm_sparc_dump_operand(instr, 2, addr, buffer + strlen(buffer));
strcat(buffer, ", ");
}
asm_sparc_dump_operand(instr, 1, addr, buffer + strlen(buffer));
}
return (buffer);
}
<file_sep>/src/libasm/include/libasm.h
/**
* @defgroup libasm libasm: the disassembling library.
*/
/**
* @file libasm/include/libasm.h
* @ingroup libasm
*
* Author : <sk at devhell dot org>
* Started : Sat Oct 26 01:18:46 2002
*
* This is the main definition file for libasm.h
* Definitions, enums, prototypes or anything related
* to a specific architecture MUST be stored in that specific
* architecture include files.
*
* $Id: libasm.h 1311 2009-01-14 20:36:48Z may
*/
/**
* @brief It contains the main define types and prototypes.
* @todo Reorganize include files content.
*/
#ifndef LIBASM_H_
#define LIBASM_H_
#ifndef __KERNEL__
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#if defined(__OpenBSD__) ||defined(__FreeBSD__) || defined(sgi) || defined(__NetBSD__)
//#include <sys/endian.h>
#include <machine/endian.h>
#elif defined(__MacOSX__)
#include <machine/endian.h>
#elif !defined(sun)
#include <endian.h>
#else
#include <db.h>
#endif
#endif
#include <libaspect.h>
#define LIBASM_SUPPORT_SPARC 1
#define LIBASM_SUPPORT_IA32 1
#define LIBASM_SUPPORT_MIPS 0 /*<! XXX: Work in progress */
#define LIBASM_SUPPORT_POWERPC 0 /*<! XXX: Wanted */
#define LIBASM_SUPPORT_ARM 0 /*<! XXX: Work in progress */
#define LIBASM_VECTOR_OPCODE_IA32 "opcode-ia32"
#define LIBASM_VECTOR_OPCODE_SPARC "opcode-sparc"
#define LIBASM_VECTOR_OPCODE_MIPS "opcode-mips"
#define LIBASM_VECTOR_OPCODE_ARM "opcode-arm"
#define LIBASM_VECTOR_OPERAND_IA32 "operand-ia32"
#define LIBASM_VECTOR_OPERAND_SPARC "operand-sparc"
#define LIBASM_VECTOR_OPERAND_MIPS "operand-mips"
#define LIBASM_VECTOR_OPERAND_ARM "operand-arm"
/**
* Set to 1 to use libasm vector.
* @obselete
*/
#define LIBASM_USE_VECTOR 1
/**
* Set to 1 to use libasm operand vector.
* @obselete
*/
#define LIBASM_USE_OPERAND_VECTOR 1
/**
* Set to 1 to use profiling.
* @todo Profiling - Work in progress
*/
#define LIBASM_USE_PROFILE 0
#if LIBASM_USE_PROFILE
#define LIBASM_PROFILE_FIN() \
fprintf(stderr, " ENTER %s\n", __FUNCTION__);
#define LIBASM_PROFILE_IN() \
fprintf(stderr, " ENTER %s\n", __FUNCTION__);
#define LIBASM_PROFILE_FOUT(val) \
fprintf(stderr, " LEAVE %s\n", __FUNCTION__); \
return (val);
#define LIBASM_PROFILE_VOUT() \
fprintf(stderr, " LEAVE %s\n", __FUNCTION__); \
return;
#define LIBASM_PROFILE_ROUT(val) \
fprintf(stderr, " LEAVE %s\n", __FUNCTION__); \
return (val);
#else
//
// Profile disabled.
//
#define LIBASM_PROFILE_FIN()
#define LIBASM_PROFILE_IN()
#define LIBASM_PROFILE_FOUT(val) return (val);
#define LIBASM_PROFILE_VOUT() return;
#define LIBASM_PROFILE_ROUT(val) return (val);
#endif
/**
* Architecture-independant instruction types
*
*/
enum e_instr_types
{
ASM_TYPE_NONE = 0x0, //!< Undefined instruction type.
ASM_TYPE_BRANCH = 0x1, //!< Branching instruction.
ASM_TYPE_CALLPROC = 0x2, //!< Sub Procedure calling instruction.
ASM_TYPE_RETPROC = 0x4, //!< Return instruction
ASM_TYPE_ARITH = 0x8, //!< Arithmetic (or logic) instruction.
ASM_TYPE_LOAD = 0x10, //!< Instruction that reads from memory.
ASM_TYPE_STORE = 0x20, //!< Instruction that writes in memory.
ASM_TYPE_ARCH = 0x40, //!< Architecture dependent instruction.
ASM_TYPE_WRITEFLAG = 0x80, //!< Flag-modifier instruction.
ASM_TYPE_READFLAG = 0x100, //!< Flag-reader instruction.
ASM_TYPE_INT = 0x200, //!< Interrupt/call-gate instruction.
ASM_TYPE_ASSIGN = 0x400, //!< Assignment instruction.
ASM_TYPE_COMPARISON = 0x800, //!< Instruction that performs comparison or test.
ASM_TYPE_CONTROL = 0x1000, //!< Instruction modifies control registers.
ASM_TYPE_NOP = 0x2000, //!< Instruction that does nothing.
ASM_TYPE_TOUCHSP = 0x4000, //!< Instruction modifies stack pointer.
ASM_TYPE_BITTEST = 0x8000, //!< Instruction investigates values of bits in the operands.
ASM_TYPE_BITSET = 0x10000, //!< Instruction modifies values of bits in the operands.
ASM_TYPE_INCDEC = 0x20000, //!< Instruction does an increment or decrement
ASM_TYPE_PROLOG = 0x40000, //!< Instruction creates a new function prolog
ASM_TYPE_EPILOG = 0x80000, //!< Instruction creates a new function epilog
ASM_TYPE_STOP = 0x100000, //!< Instruction stops the program
ASM_TYPE_IO = 0x200000, //!< Instruction accesses I/O locations (e.g. ports).
ASM_TYPE_CONDCONTROL = 0x400000, //!< Instruction executes conditionally.
ASM_TYPE_INDCONTROL = 0x800000, //!< Instruction changes control indirectly.
ASM_TYPE_OTHER = 0x1000000, //!< Type that doesn't fit the ones above.
};
/* Indicate arithmetic operation for ASM_TYPE_ARITH instructions */
enum e_arith_types
{
ASM_ARITH_ADD = 0x1,
ASM_ARITH_SUB = 0x2,
ASM_ARITH_MUL = 0x4,
ASM_ARITH_DIV = 0x8,
ASM_ARITH_OR = 0x10,
ASM_ARITH_XOR = 0x20,
ASM_ARITH_AND = 0x40,
ASM_ARITH_SL = 0x80,
ASM_ARITH_SR = 0x100,
ASM_ARITH_NOT = 0x200,
};
/**
* Architecture-independant operand types
*
*/
enum e_op_types
{
ASM_OPTYPE_NONE = 0x0, //!< Undefined operand type
ASM_OPTYPE_IMM = 0x1, //!< Immediate operand type
ASM_OPTYPE_REG = 0x2, //!< Register operand type
ASM_OPTYPE_MEM = 0x4 //!< Memory access operand type
};
#define LIBASM_HANDLER_FETCH(fcn) int (*fcn)(asm_instr *, u_char *, u_int, asm_processor *)
#define LIBASM_HANDLER_DISPLAY(fcn) char *(*fcn)(asm_instr *, int)
/*
typedef's
*/
typedef struct s_asm_processor asm_processor;
typedef struct s_asm_instr asm_instr;
typedef struct s_asm_op asm_operand;
enum e_vector_arch
{
LIBASM_VECTOR_IA32,
LIBASM_VECTOR_SPARC,
LIBASM_VECTOR_MIPS,
LIBASM_VECTOR_ARM,
LIBASM_VECTOR_ARCHNUM
};
/**
* List of architecture.
*/
enum e_proc_type
{
ASM_PROC_IA32, //!< Architecture IA32
ASM_PROC_SPARC, //!< Architecture SPARC
ASM_PROC_MIPS, //!< Architecture MIPS
ASM_PROC_ARM //!< Architecture ARM
};
/*
prototypes.
*/
/**
* Initialize an asm_processor structure to disassemble
*/
int asm_init_ia32(asm_processor *proc);
int asm_init_i386(asm_processor *proc); /*!< XXX:Obsolete */
int asm_init_sparc(asm_processor *proc);
int asm_init_mips(asm_processor *proc);
int asm_init_arm(asm_processor *proc);
/**
* Intialize an asm_processor structure.
*
* Architectures currently availables are ASM_PROC_IA32, ASM_PROC_SPARC and ASM_PROC_MIPS
* @param proc Pointer to asm_processor structure.
* @param arch Architecture to initialize (ASM_PROC_<arch>)
* @return 1 on success, 0 on error.
*/
int asm_init_arch(asm_processor *proc, int arch);
/**
* Return endianess
*/
int asm_config_get_endian();
void asm_config_set_endian(int mode);
/**
* Return synthetic instructions enabled flag
*/
int asm_config_get_synthinstr();
/**
* return build date.
*/
char *asm_get_build(void);
/**
* Initialize an asm_processor structure to disassemble
* sparc instructions.
*\param proc Pointer to an asm_processor structure
*/
/**
* Disassemble instruction
*/
int asm_read_instr(asm_instr *instr, u_char *buffer, u_int len, asm_processor *proc);
/**
* Return instruction length.
*
*/
int asm_instr_len(asm_instr *);
/**
* Return instruction length.
*
*/
int asm_instruction_get_len(asm_instr *, int, void *);
/**
* Return instruction mnemonic.
*/
char *asm_instr_get_memonic(asm_instr *, asm_processor *);
/**
* Return a pointer
*/
char *asm_display_instr_att(asm_instr *, eresi_Addr);
void asm_clear_instr(asm_instr *);
/**
* Set libasm error
*/
void asm_set_error(asm_instr *, int errorcode, char *error_msg);
int asm_get_error_code();
char* asm_get_error_message();
/**
* operand field access methods.
* use this to keep compatibility.
**/
/**
* Return instruction number of operands.
*
*/
int asm_operand_get_count(asm_instr *instr, int num, int, void *);
/**
* Return operand content.
*/
int asm_operand_get_content(asm_instr *, int, int, void *);
/******************
*
*/
void *asm_opcode_fetch(const char *vector_name, int opcode);
/**
* Return operand type.
*/
int asm_operand_get_type(asm_instr *, int, int, void *);
/**
* Return operand size
*/
int asm_operand_get_size(asm_instr *, int, int, void *);
int asm_operand_get_len(asm_instr *, int, int, void *);
int asm_operand_set_value(asm_instr *, int, int, void *);
int asm_operand_get_value(asm_instr *, int, int, void *);
#ifndef __KERNEL__
/**
* immediate field may be a 1,2,4,8 ... byte long value
* to set it,
*/
int asm_operand_debug(asm_instr *, int, int, void *);
/**
* Dump content of instruction
*
*/
void asm_instruction_debug(asm_instr *ins, FILE *out);
#endif
/**
* Free asm processor internal structures
*/
void asm_free_i386(asm_processor *proc);
/**
* Get immediate value stored in operand.
*/
int asm_operand_get_immediate(asm_instr *, int, int, void *);
/**
* Set immediate value stored in operand.
*/
int asm_operand_set_immediate(asm_instr *, int, int, void *);
/**
* Get base register stored in operand.
*/
int asm_operand_get_basereg(asm_instr *, int, int, void *);
int asm_operand_set_basereg(asm_instr *, int, int, void *);
/**
* Get index register stored in operand (IA32 only).
*/
int asm_operand_get_indexreg(asm_instr *, int, int, void *);
/**
* Set index register stored in operand (IA32 only).
*/
int asm_operand_set_indexreg(asm_instr *, int, int, void *);
/**
* Get index scale stored in operand (IA32 only).
*/
int asm_operand_get_scale(asm_instr *, int num, int opt, void *);
/**
* Set index scale stored in operand (IA32 only).
*/
int asm_operand_set_scale(asm_instr *, int num, int opt, void *);
/**
*
*/
int asm_operand_is_reference(asm_operand *op);
int asm_instruction_is_prefixed(asm_instr *ins, int prefix);
/**
* Set resolve handler used by asm_display_instr() to resolve immediate value.
*/
void asm_set_resolve_handler(asm_processor *,
void (*)(void *, eresi_Addr, char *, u_int),
void *);
/**
*
*/
char *asm_operand_type_string(int type);
/**
* IA32 related : should be moved in libasm-ia32.h
*/
int asm_register_ia32_opcode(int opcode, unsigned long fcn);
int asm_register_sparc_opcode(int opcode, int opcode2, int fpop,
unsigned long fcn);
/**
* XXX: This is obsolete.
*/
int asm_arch_register(asm_processor *proc, int machine);
int asm_operand_register(asm_processor *proc);
int asm_init_vectors(asm_processor *proc);
/**
* One dimension vector facilities.
*/
int asm_register_opcode_create(const char *name, int num);
int asm_register_operand_create(const char *name, int num);
int asm_register_opcode(const char *, int, unsigned long fcn);
int asm_register_operand(const char *, int, unsigned long fcn);
/**
* Default handlers.
*
*/
int asm_fetch_default(asm_instr *, u_char *opcode, u_int len, asm_processor *proc);
/**
* Return an ascii static string corresponding to a register.
* @param reg Register
* @param regset Register set (ie: ASM_REGSET_R32)
* @return An ascii string.
*/
char *get_reg_intel(int reg, int regset);
/**
* @brief enum of the error codes available in asm_processor->error_code.
* XXX: Being implemented. Currently not accurate.
*/
enum e_libasm_errorcode
{
#define LIBASM_MSG_ERRORNOTIMPLEMENTED "error message not implemented"
LIBASM_ERROR_SUCCESS,
#define LIBASM_MSG_SUCCESS "success"
LIBASM_ERROR_NSUCH_CONTENT,
#define LIBASM_MSG_NSUCH_CONTENT "no such content"
LIBASM_ERROR_ILLEGAL,
#define LIBASM_MSG_ILLEGAL "illegal instruction"
LIBASM_ERROR_TOOSHORT,
#define LIBASM_MSG_TOOSHORT "data length too short"
};
#include <libasm-structs.h>
#include <libasm-i386.h>
#include <libasm-sparc.h>
#include <libasm-mips.h>
#include <libasm-arm.h>
#endif
<file_sep>/src/libasm/src/arch/ia32/handlers/op_cmp_al_ib.c
/*
** $Id: op_cmp_al_ib.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_cmp_al_ib" opcode="0x3c"/>
*/
int op_cmp_al_ib(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->instr = ASM_CMP;
new->len += 1;
new->type = ASM_TYPE_COMPARISON | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_CF | ASM_FLAG_PF | ASM_FLAG_AF |
ASM_FLAG_SF | ASM_FLAG_OF | ASM_FLAG_ZF;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new);
#endif
new->op[0].content = ASM_OP_BASE | ASM_OP_FIXED;
new->op[0].regset = ASM_REGSET_R8;
new->op[0].ptr = opcode;
new->op[0].len = 0;
new->op[0].baser = ASM_REG_AL;
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_group14.c
/*
** $Id: i386_group14.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<i386 func="i386_group14" opcode="0x73"/>
*/
int i386_group14(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
int olen;
struct s_modrm *modrm = (struct s_modrm *) opcode + 1;
new->ptr_instr = opcode;
new->len += 1;
switch (modrm->r)
{
case 2:
new->instr = ASM_PSRLQ;
break;
case 6:
new->instr = ASM_PSLLQ;
new->op[0].type = ASM_OTYPE_PMMX;
new->op[0].size = ASM_OSIZE_QWORD;
new->op[1].type = ASM_OTYPE_IMMEDIATE;
new->op[1].size = ASM_OSIZE_BYTE;
operand_rmb_ib(new, opcode + 1, len - 1, proc);
new->op[0].regset = ASM_REGSET_MM;
break;
default:
new->instr = ASM_BAD;
return (new->len = 0);
break;
}
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_PMMX, new, 0));
#else
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_PMMX, new));
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen, ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen, ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
#else
new->op[0].type = ASM_OTYPE_PMMX;
new->op[0].size = ASM_OSIZE_QWORD;
new->op[1].type = ASM_OTYPE_IMMEDIATE;
new->op[1].size = ASM_OSIZE_BYTE;
operand_rmb_ib(new, opcode + 1, len - 1, proc);
new->op[0].regset = ASM_REGSET_MM;
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_bpcc.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_bpcc.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_bpcc.c 1413 2010-05-21 03:41:25Z figueredo $
**
*/
#include "libasm.h"
int
asm_sparc_bpcc(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_pbranch opcodep;
struct s_asm_proc_sparc *inter;
sparc_convert_pbranch(&opcodep, buf);
inter = proc->internals;
ins->instr = inter->bcc_table[opcodep.cond];
if (ins->instr == ASM_SP_BA)
ins->type = ASM_TYPE_BRANCH;
else if (ins->instr == ASM_SP_BN)
ins->type = ASM_TYPE_NOP;
else
ins->type = ASM_TYPE_BRANCH | ASM_TYPE_CONDCONTROL;
ins->nb_op = 2;
ins->op[0].imm = opcodep.imm;
ins->op[1].baser = opcodep.cc + 4;
ins->annul = opcodep.a;
ins->prediction = opcodep.p;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_DISPLACEMENT, ins);
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_CC, ins);
if (ins->instr == ASM_SP_BN &&
ins->annul && ins->prediction && ins->op[1].baser == ASM_SP_XCC) {
ins->instr = ASM_SP_IPREFETCH;
ins->nb_op = 1;
ins->type = ASM_TYPE_NONE;
}
return 4;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_jmp_iv.c
/*
** $Id: op_jmp_iv.c 1413 2010-05-21 03:41:25Z figueredo $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_jmp_iv" opcode="0xe9"/>
*/
int op_jmp_iv(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->instr = ASM_BRANCH;
new->type = ASM_TYPE_BRANCH;
new->ptr_instr = opcode;
new->len += 1;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_JUMP, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_JUMP, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_indir_rmv.c
/*
** $Id: op_indir_rmv.c 1413 2010-05-21 03:41:25Z figueredo $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_indir_rmv" opcode="0xff"/>
*/
int op_indir_rmv(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
new->ptr_instr = opcode;
modrm = (struct s_modrm *) (opcode + 1);
new->len += 1;
switch(modrm->r) {
case 0:
new->instr = ASM_INC;
new->type = ASM_TYPE_INCDEC | ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_AF | ASM_FLAG_OF | ASM_FLAG_PF |
ASM_FLAG_SF | ASM_FLAG_ZF;
new->op[0].type = ASM_OTYPE_ENCODED;
new->op[0].size = ASM_OSIZE_VECTOR;
break;
case 1:
new->instr = ASM_DEC;
new->type = ASM_TYPE_INCDEC | ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_AF | ASM_FLAG_OF | ASM_FLAG_PF |
ASM_FLAG_SF | ASM_FLAG_ZF;
new->op[0].type = ASM_OTYPE_ENCODED;
new->op[0].size = ASM_OSIZE_VECTOR;
break;
case 2:
new->type = ASM_TYPE_CALLPROC | ASM_TYPE_TOUCHSP;
new->spdiff = -4;
new->instr = ASM_CALL;
new->op[0].type = ASM_OTYPE_MEMORY;
break;
case 3:
new->type = ASM_TYPE_CALLPROC | ASM_TYPE_TOUCHSP;
new->instr = ASM_CALL;
new->op[0].type = ASM_OTYPE_MEMORY;
break;
case 4:
new->type = ASM_TYPE_BRANCH;
new->instr = ASM_BRANCH;
new->op[0].type = ASM_OTYPE_MEMORY;
break;
case 5:
new->type = ASM_TYPE_BRANCH;
new->instr = ASM_BRANCH;
new->op[0].type = ASM_OTYPE_MEMORY;
break;
case 6:
new->instr = ASM_PUSH;
new->type = ASM_TYPE_TOUCHSP | ASM_TYPE_STORE;
new->op[0].type = ASM_OTYPE_ENCODED;
new->op[0].size = ASM_OSIZE_VECTOR;
break;
case 7:
new->instr = ASM_BAD;
new->op[0].type = ASM_OTYPE_ENCODED;
new->op[0].size = ASM_OSIZE_VECTOR;
break;
default:
break;
} /* switch */
if ((new->op[0].type == ASM_OTYPE_ENCODED) ||
(new->op[0].type == ASM_OTYPE_MEMORY)) {
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
if (new->op[0].type == ASM_OTYPE_MEMORY)
new->op[0].content |= ASM_OP_ADDRESS;
}
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_push_iv.c
/**
* @file libasm/src/arch/ia32/handlers/op_push_iv.c
*
* @ingroup IA32_instrs
* $Id: op_push_iv.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
*
* Handler for opcode 0x68 , instruction push_iv
<instruction func="op_push_iv" opcode="0x68"/>
*/
int op_push_iv(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->instr = ASM_PUSH;
new->len += 1;
new->ptr_instr = opcode;
new->type = ASM_TYPE_TOUCHSP | ASM_TYPE_STORE;
new->spdiff = -4;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_IMMEDIATE,
new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_IMMEDIATE,
new);
#endif
return (new->len);
}
<file_sep>/src/disasm.c
/*
** Author : <sk at devhell dot org>
** Started : Mon Jun 10 01:49:20 2002
** Updated : Thu Dec 4 02:46:23 2003
**
** $Id: mydisasm.c 1311 2009-01-14 20:36:48Z may $
**
*/
/*
* this tool is designed to disassemble binary with the same output as
* objdump (except symbols.)
*
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <libasm.h>
int usage(char *p)
{
printf("Usage: %s <binary> <sym/vaddr> <[len]>\n",
p);
return (-1);
}
void dump_opcodes(char *why, u_char *ptr, u_int curr, u_int vaddr)
{
printf("0x%08x (%s): .byte 0x%02x\n", (int) vaddr + curr, why, *(ptr + curr));
printf(";; error reading instruction at %p\n", ptr + curr);
printf(";; dumping opcodes: %02x %02x %02x %02x\n",
*(ptr + curr), *(ptr + curr + 1),
*(ptr + curr + 2), *(ptr + curr + 3));
}
int main(int ac, char **argv) {
u_char *ptr;
unsigned long start;
unsigned long end;
unsigned long len;
u_int curr;
unsigned long vaddr;
char *att_dump;
int i;
asm_instr instr;
asm_processor proc;
u_int arch;
FILE *fp;
printf("opening %s\n", argv[1]);
fp = fopen(argv[1], "rb");
fseek(fp, 0L, SEEK_END);
len = ftell(fp);
fseek(fp, 0L, SEEK_SET);
start = strtoul(argv[2], NULL, 16);
vaddr = 0;
fseek(fp, start, SEEK_SET);
printf("offset: %x\n", start);
len = atoi(argv[3]);
ptr = malloc(len + 1);
memset(ptr, 0, len + 1);
start = 0;
curr = fread(ptr, 1, len, fp);
if (curr != len)
{
printf("error reading %li bytes at %li -> read %i bytes\n", len, start, curr);
return (-1);
}
/* disassembling loop */
curr = 0;
unsigned char ch = 0;
asm_init_mips(&proc);
asm_config_set_endian(CONFIG_ASM_BIG_ENDIAN);
while(curr < len) {
if (asm_read_instr(&instr, ptr + curr, len - curr, &proc) > 0) {
att_dump = asm_display_instr_att(&instr, (int) vaddr + curr);
if (att_dump && (strcmp(att_dump,"int_err")))
{
printf("0x%08x:\t", (int) vaddr + curr);
for (i = instr.len-1; i >= 0; i--)
printf("%02x", *(ptr + curr + i));
printf(" ");
for (i = instr.len-1; i >= 0; i--) {
ch = *(ptr + curr + i);
if(ch > 0x20 && ch < 0x7f)
printf("%c", ch);
else printf(".");
}
printf("\t");
printf("%-30s", att_dump);
puts("");
//asm_instruction_debug(&instr, stdout);
curr += asm_instr_len(&instr);
}
else
{
dump_opcodes("int_err", ptr, curr, vaddr);
curr++;
}
} else {
dump_opcodes("asm_read_instr",ptr,curr,vaddr);
curr++;
}
}
fclose(fp);
free(ptr);
return (0);
}
<file_sep>/src/libasm/src/arch/mips/output_mips.c
/**
* @file libasm/src/arch/mips/output_mips.c
** @ingroup mips
*/
/**
* @file libasm/src/arch/mips/output_mips.c
* @brief This file implements the MIPS ASCII output engine
*
* Made by <NAME> and <NAME>
* $Id: output_mips.c 1397 2009-09-13 02:19:08Z may $
*/
#include <libasm.h>
/**
* @fn char *asm_mips_display_operand(asm_instr *ins, int num, unsigned int addr)
* @brief Return ASCII representation of a mips operand
*
* @param ins Pointer to asm_instr structure.
* @param num Now it unused.
* @parram addr Virtual Address of instruction.
* @return A pointer to a static buffer or NULL on error.
*/
char *asm_mips_display_operand(asm_instr *ins, int num, eresi_Addr addr)
{
unsigned int i;
static char bufer[80];
char temp[4][20];
asm_operand *op;
unsigned int converted;
memset(bufer, 0x0, sizeof(bufer));
for (i = 0; i < 4; i++)
{
op = &ins->op[i];
memset(&temp[i][0], 0x0, sizeof(temp[i]));
switch(op->type)
{
case ASM_MIPS_OTYPE_REGISTER:
memcpy((char *)&converted, ins->ptr_instr, ins->len);
if((((converted >> 26)) == MIPS_OPCODE_COP0) && (i == 1) && op->baser < 32) {
op->baser += 32;
}
snprintf(temp[i],sizeof(temp[i]),(i) ? ", %s" : "%s",
(op->regset) ? e_mips_registers[op->baser].fpu_mnemonic : e_mips_registers[op->baser].ext_mnemonic);
break;
case ASM_MIPS_OTYPE_IMMEDIATE:
memcpy((char *)&converted, ins->ptr_instr, ins->len);
switch((converted >> 0)) {
case MIPS_OPCODE_ADDIU:
case MIPS_OPCODE_ADDU:
case MIPS_OPCODE_SUBU:
case MIPS_OPCODE_SUB:
snprintf(temp[i],sizeof(temp[i]),(i) ? ", %d" : "%d\t# 0x%x",(unsigned short)op->imm, (unsigned short)op->imm);
break;
default:
snprintf(temp[i],sizeof(temp[i]),(i) ? ", 0x%x" : "0x%x",(unsigned short)op->imm);
break;
}
//snprintf(temp[i],sizeof(temp[i]),(i) ? ", %d" : "%d",(short)op->imm);
break;
case ASM_MIPS_OTYPE_JUMP:
//snprintf(temp[i], sizeof(temp[i]), (i ? ", "XFMT : XFMT), (op->imm << 2) | ((((addr + 8) >> 28) & 0xF) << 28));
snprintf(temp[i], sizeof(temp[i]), (i ? ", 0x%x": "0x%x"), (op->imm << 2) | ((((addr + 8) >> 28) & 0xF) << 28));
break;
case ASM_MIPS_OTYPE_NONE:
case ASM_MIPS_OTYPE_NOOP:
// snprintf(bufer,sizeof(bufer)," ");
break;
case ASM_MIPS_OTYPE_BRANCH:
snprintf(temp[i], sizeof(temp[i]) , (i) ? ", 0x%x" : "0x%x", (addr + (((short) op->imm + 1) * 4)));
break;
case ASM_MIPS_OTYPE_REGBASE:
snprintf(temp[i], sizeof(temp[i]), "(%s)",
(op->regset) ?
e_mips_registers[op->baser].fpu_mnemonic :
e_mips_registers[op->baser].ext_mnemonic);
break;
}
}
for (i = 0; i < 4; i++)
if (temp[i][0])
strcat(bufer,temp[i]);
return (bufer[0]) ? bufer : NULL;
}
/**
* @fn char *asm_mips_display_instr(asm_instr *ins,int addr)
* @brief Return ASCII representation of a mips instruction with operand.
*
* @param ins Pointer to instruction structure.
* @param addr Virtual Address of instruction.
* @return Pointer to a static buffer or NULL on error.
*/
char *asm_mips_display_instr(asm_instr *ins, eresi_Addr addr)
{
static char buf[120];
char *tmp = NULL;
tmp = asm_mips_display_operand(ins, 0, addr);
bzero(buf, sizeof(buf));
if (tmp)
snprintf(buf, sizeof(buf), "%-8s %s",
e_mips_instrs[ins->instr].mnemonic,
asm_mips_display_operand(ins, 0, addr));
else
snprintf(buf, sizeof(buf), "%-8s", e_mips_instrs[ins->instr].mnemonic);
return buf;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_repnz.c
/**
* @file libasm/src/arch/ia32/handlers/op_repnz.c
*
* @ingroup IA32_instrs
** $Id: op_repnz.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_repnz" opcode="0xf2"/>
*/
int op_repnz(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
if (!new->ptr_prefix)
new->ptr_prefix = opcode;
new->len += 1;
new->prefix = ASM_PREFIX_REPNE;
return (proc->fetch(new, opcode + 1, len - 1, proc));
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_sti.c
/**
* @file libasm/src/arch/ia32/handlers/op_sti.c
*
* @ingroup IA32_instrs
*
** $Id: op_sti.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @todo: Set flags field.
*
*
<instruction func="op_sti" opcode="0xfb"/>
*/
int op_sti(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->ptr_instr = opcode;
new->instr = ASM_STI;
new->type = ASM_TYPE_WRITEFLAG;
/* Should be VIF for CPL = 3 and IOPL < CPL */
new->flagswritten = ASM_FLAG_IF;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_leave.c
/**
* @file libasm/src/arch/ia32/handlers/op_leave.c
*
* @ingroup IA32_instrs
* $Id: op_leave.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for the leave instruction opcode 0xc9
* @param new Pointer to the instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
*/
int op_leave(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->ptr_instr = opcode;
new->type = ASM_TYPE_TOUCHSP;
new->spdiff = 4;
new->instr = ASM_LEAVE;
return (new->len);
}
<file_sep>/src/libasm/tools/mydisasm.c
/*
** Author : <sk at devhell dot org>
** Started : Mon Jun 10 01:49:20 2002
** Updated : Thu Dec 4 02:46:23 2003
**
** $Id: mydisasm.c 1311 2009-01-14 20:36:48Z may $
**
*/
/*
* this tool is designed to disassemble binary with the same output as
* objdump (except symbols.)
*
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <libelfsh.h>
#include <libasm.h>
int usage(char *p)
{
printf("Usage: %s <binary> <sym/vaddr> <[len]>\n",
p);
return (-1);
}
void dump_opcodes(char *why, u_char *ptr, u_int curr, u_int vaddr)
{
printf("0x%08x (%s): .byte 0x%02x\n", (int) vaddr + curr, why, *(ptr + curr));
printf(";; error reading instruction at %p\n", ptr + curr);
printf(";; dumping opcodes: %02x %02x %02x %02x\n",
*(ptr + curr), *(ptr + curr + 1),
*(ptr + curr + 2), *(ptr + curr + 3));
}
int main(int ac, char **av) {
u_char *ptr;
unsigned long start;
unsigned long end;
unsigned long len;
u_int curr;
unsigned long vaddr;
char *att_dump;
int i;
Elf32_Sym *sym;
elfshobj_t *obj;
asm_instr instr;
asm_processor proc;
u_int arch;
if (ac < 3)
return (usage(av[0]));
obj = elfsh_load_obj(av[1]);
if (!obj)
{
printf("failed opening %s\n", av[1]);
return (-1);
}
/* fetching 2nd argument <start> : symbol or vaddr */
arch = elfsh_get_arch(obj->hdr);
vaddr = 0;
if (!(sym = elfsh_get_metasym_by_name(obj, av[2])))
vaddr = strtoul(av[2], 0, 16);
else
vaddr = sym->st_value;
/*
if (!vaddr)
{
printf("invalid start %s: null or cannot find symbol\n", av[2]);
elfsh_unload_obj(obj);
return (-1);
}
*/
/* fetching third argument if present L: <len> */
if (av[3])
len = atol(av[3]);
else
{
if (!sym)
{
printf("len required with no symbol information\n");
elfsh_unload_obj(obj);
return (-1);
}
else
len = sym->st_size;
}
end = vaddr + len;
/* select arch */
switch(arch)
{
case EM_SPARC32PLUS:
case EM_SPARC:
case EM_SPARCV9:
asm_init_sparc(&proc);
break;
case EM_386:
asm_init_ia32(&proc);
break;
case EM_MIPS:
asm_init_mips(&proc);
break;
default:
printf("unsupported architecture : %i\n", arch);
elfsh_unload_obj(obj);
return (-1);
}
/*
filling buffer
*/
ptr = malloc(len + 1);
memset(ptr, 0, len + 1);
start = elfsh_get_foffset_from_vaddr(obj, vaddr);
if (!start)
printf("Converted vaddr %08x to file offset : %i\n", vaddr, start);
curr = elfsh_readmemf(obj, start, ptr, len);
if (curr != len)
{
printf("error reading %li bytes at %li -> read %i bytes\n", len, start, curr);
elfsh_error();
elfsh_unload_obj(obj);
return (-1);
}
/* disassembling loop */
curr = 0;
while(curr < len) {
if (asm_read_instr(&instr, ptr + curr, len - curr, &proc) > 0) {
att_dump = asm_display_instr_att(&instr, (int) vaddr + curr);
if (att_dump && (strcmp(att_dump,"int_err")))
{
printf("0x%08x:\t", (int) vaddr + curr);
printf("%30s\t", att_dump);
for (i = 0; i < instr.len; i++)
printf("%02x ", *(ptr + curr + i));
puts("");
//asm_instruction_debug(&instr, stdout);
curr += asm_instr_len(&instr);
}
else
{
dump_opcodes("int_err", ptr, curr, vaddr);
curr++;
}
} else {
dump_opcodes("asm_read_instr",ptr,curr,vaddr);
curr++;
}
}
if (arch == EM_386)
asm_free_i386(&proc);
free(ptr);
elfsh_unload_obj(obj);
return (0);
}
<file_sep>/src/libasm/src/output.c
/**
* @file libasm/src/output.c
* @ingroup libasm
* $Id: output.c 1397 2009-09-13 02:19:08Z may $
*
* Author : <sk at devhell dot org>
* Started : Xxx Xxx xx xx:xx:xx 2002
* Updated : Thu Mar 11 00:40:31 2004
* @brief ASCII Output wrappers.
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @brief Wrapper to internal resolving handler for immediate values.
* @param proc Pointer to processor structure
* @param val Value to resolve
* @param buf Pointer to store string
* @param len Length of string
*/
void asm_resolve_immediate(asm_processor *proc, eresi_Addr val,
char *buf, u_int len)
{
LIBASM_PROFILE_FIN();
proc->resolve_immediate(proc->resolve_data, val, buf, len);
LIBASM_PROFILE_VOUT();
}
/**
* @brief Wrapper to internal Ascii output handler.
* @param instr Pointer to instruction structure
* @param addr Virtual address of instruction
* @return Pointer to a static buffer containing current instruction string
*/
char *asm_display_instr_att(asm_instr *instr, eresi_Addr addr)
{
char *to_ret;
LIBASM_PROFILE_FIN();
to_ret = instr->proc->display_handle(instr, addr);
LIBASM_PROFILE_ROUT(to_ret);
}
/**
* merged from mjollnir
* @brief Debug dump to stderr of an operand
* @param op Pointer to operand structure.
* @return Always returns 0.
*/
int asm_debug_operand(asm_operand * op)
{
fprintf(stderr, "[*] Operand Dump\n[*] len: %d type: %d size: %d content: %d\n",
op->len, op->type, op->size, op->content);
fprintf(stderr, "[*] Content: %s %s %s %s %s %s %s\n",
(op->content & ASM_OP_VALUE) ? "ASM_OP_VALUE" : ".",
(op->content & ASM_OP_BASE) ? "ASM_OP_BASE" : ".",
(op->content & ASM_OP_INDEX) ? "ASM_OP_INDEX" : ".",
(op->content & ASM_OP_SCALE) ? "ASM_OP_SCALE" : ".",
(op->content & ASM_OP_FIXED) ? "ASM_OP_FIXED" : ".",
(op->content & ASM_OP_REFERENCE) ? "ASM_OP_REFERENCE" : ".",
(op->content & ASM_OP_ADDRESS) ? "ASM_OP_ADDRESS" : ".");
return 0;
}
/**
* @brief Return a string describing otype
* @param type Instruction type
* @return A pointer to a static string
*/
char *asm_operand_type_string(int type)
{
switch (type)
{
case ASM_OTYPE_FIXED: return ("fixed");
case ASM_OTYPE_OPMOD: return ("opmod");
case ASM_OTYPE_ADDRESS: return ("address");
case ASM_OTYPE_CONTROL: return ("control");
case ASM_OTYPE_DEBUG: return ("debug");
case ASM_OTYPE_ENCODED: return ("encoded");
case ASM_OTYPE_ENCODEDBYTE: return ("encodedbyte");
case ASM_OTYPE_FLAGS: return ("flags");
case ASM_OTYPE_GENERAL: return ("general");
case ASM_OTYPE_GENERALBYTE: return ("generalbyte");
case ASM_OTYPE_IMMEDIATE: return ("immediate");
case ASM_OTYPE_IMMEDIATEWORD: return ("immediateword");
case ASM_OTYPE_IMMEDIATEBYTE: return ("immediatebyte");
case ASM_OTYPE_SHORTJUMP: return ("shortjump");
case ASM_OTYPE_JUMP: return ("jump");
case ASM_OTYPE_MEMORY: return ("memory");
case ASM_OTYPE_OFFSET: return ("offset");
case ASM_OTYPE_PMMX: return ("pmmx");
case ASM_OTYPE_QMMX: return ("qmmx");
case ASM_OTYPE_REGISTER: return ("register");
case ASM_OTYPE_SEGMENT: return ("segment");
case ASM_OTYPE_TEST: return ("test");
case ASM_OTYPE_VSFP: return ("vsfp");
case ASM_OTYPE_WSFP: return ("wsfp");
case ASM_OTYPE_XSRC: return ("xsrc");
case ASM_OTYPE_YDEST: return ("ydest");
}
return ("undocumented type");
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_sethi.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_sethi.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_sethi.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libasm.h"
int
asm_sparc_sethi(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_branch opcode;
sparc_convert_branch(&opcode, buf);
ins->type = ASM_TYPE_ASSIGN;
if (!opcode.rd && !opcode.imm) {
ins->instr = ASM_SP_NOP;
ins->type = ASM_TYPE_NOP;
ins->nb_op = 0;
}
else {
ins->instr = ASM_SP_SETHI;
ins->nb_op = 2;
ins->op[0].baser = opcode.rd;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_REGISTER, ins);
ins->op[1].imm = opcode.imm;
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_SETHI, ins);
}
return 4;
}
<file_sep>/src/libaspect/include/libaspect-btree.h
/*
**
* @file libaspect/include/libaspect-btree.h
**
** Author : <IDSAFQREOFASOCASDCAADS>
** Started : Fri Oct 17 14:30:27 2003
** Updated : Thu Nov 27 23:27:49 2003
**
** $Id: libaspect-btree.h 1397 2009-09-13 02:19:08Z may $
**
*/
#ifndef __KERNEL__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#endif
/**
* @brief Graphviz node pattern for debugging purpose
*/
#define BTREE_DEBUG_NODE "\"btree_%08x\" [\n"\
"label = \"<ptr> %8x| <L> %8x|<R> %8x\n"\
"shape = \"record\"\n"\
"];\n"
/**
* @brief Graphviz link pattern for debugging purpose
*/
#define BTREE_DEBUG_LINK "\"btree_%08x\":%s -> \"btree_%08x\":ptr [\n"\
"id = %i\n"\
"];\n"
#ifndef __KERNEL__
/**
*
*/
struct s_debug
{
FILE *fp;
int link;
};
#endif
/**
* @brief Binary tree structure.
*/
typedef struct s_btree
{
unsigned int id; /*!< Id of the node */
void *elem; /*!< Pointer to element of the node */
struct s_btree *left; /*!< Left link of the tree */
struct s_btree *right; /*!< Right link of the tree */
} btree_t;
#define BTREE_FREE_ELEM 1
#define BTREE_FREE_TREE 0
void btree_insert(btree_t **, u_int, void *);
void btree_insert_sort(btree_t **, int (*)(void *, void *), void *);
void *btree_get_elem(btree_t *, u_int);
void *btree_find_elem(btree_t *, int (*)(void *, void *), void *);
void btree_browse_prefix(btree_t *, int (*)(void *, void *), void *);
void btree_browse_infix(btree_t *, int (*)(void *, void *), void *);
void btree_browse_suffix(btree_t *, int (*)(void *, void *), void *);
void btree_free(btree_t *, int);
void btree_browse_prefix_debug(btree_t *, int (*)(void *, void *, btree_t *), void *);
void btree_debug(btree_t *, char *, void (*)(void *, void *));
<file_sep>/src/libasm/src/arch/ia32/handlers/op_shr_rmv_ib.c
/**
* @file libasm/src/arch/ia32/handlers/op_shr_rmv_ib.c
*
* @ingroup IA32_instrs
** $Id: op_shr_rmv_ib.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_shr_rmv_ib" opcode="0xc1"/>
*/
int op_shr_rmv_ib(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc) {
struct s_modrm *modrm;
int olen;
modrm = (struct s_modrm *) opcode + 1;
new->ptr_instr = opcode;
new->len += 1;
new->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_OF | ASM_FLAG_CF;
if (modrm->r == ASM_REG_EAX)
new->instr = ASM_ROL;
if (modrm->r == ASM_REG_EBP) {
new->instr = ASM_SHR;
new->flagswritten |= ASM_FLAG_PF | ASM_FLAG_ZF | ASM_FLAG_SF;
}
else if (modrm->r == ASM_REG_EDI) {
new->instr = ASM_SAR;
new->flagswritten |= ASM_FLAG_PF | ASM_FLAG_ZF | ASM_FLAG_SF;
}
else if (modrm->r == ASM_REG_ECX)
new->instr = ASM_ROR;
else if (modrm->r == ASM_REG_EAX)
new->instr = ASM_ROL;
else {
new->instr = ASM_SHL;
new->flagswritten |= ASM_FLAG_PF | ASM_FLAG_ZF | ASM_FLAG_SF;
}
#if WIP
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1,
ASM_OTYPE_ENCODED, new, 0));
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen,
ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1,
ASM_OTYPE_ENCODED, new));
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen,
ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
return (new->len);
}
<file_sep>/src/libaspect/config.c
/*
* @file libaspect/config.c
** @ingroup libaspect
**
** Started on Sat Jun 2 15:20:18 2005 jfv
** $Id: config.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libaspect.h"
aspectworld_t aspectworld;
/**
* @brief Wrapper for updating value depending on data type
* @param item Configuration item structure
* @param data Configuration item value
*/
static void __config_update_item(configitem_t *item, void *data)
{
switch(item->type)
{
case CONFIG_TYPE_INT:
item->val = (int)data;
break;
case CONFIG_TYPE_STR:
item->data = strdup(data);
break;
default:
break;
}
}
/**
* @brief Add a configure item to the configuration items hash table
* @param name Configuration item string name
* @param type Configuration item type identifier
* @param mode Configuration mode (RW or RO)
* @param data Configuration item value
*/
void config_add_item(char *name,
u_int type, /* int, string ... */
u_int mode, /* RW, RO */
void *data)
{
configitem_t *tmp;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
XALLOC(__FILE__, __FUNCTION__, __LINE__, tmp, sizeof(configitem_t), );
tmp->name = strdup(name);
tmp->type = type;
tmp->mode = mode;
tmp->val = -1;
tmp->data = NULL;
__config_update_item(tmp,data);
if (hash_get(&aspectworld.config_hash,tmp->name) == NULL)
hash_add(&aspectworld.config_hash,tmp->name,tmp);
PROFILER_OUT(__FILE__,__FUNCTION__,__LINE__);
}
/**
* @brief Update value of an existing configuration item
* @param name Configuration item string name
* @param data Configuration item value
*/
void config_update_key(char *name,void *data)
{
configitem_t *tmp;
tmp = (configitem_t *) hash_get(&aspectworld.config_hash,name);
if (tmp == NULL)
return;
__config_update_item(tmp,data);
hash_del(&aspectworld.config_hash, name);
hash_add(&aspectworld.config_hash, tmp->name, tmp);
}
/**
* @brief Retreive the value of a configuration item
* @param name Requested configuration item name
* @return A pointer on the configuration item value
*/
void *config_get_data(char *name)
{
configitem_t *item;
item = (configitem_t *) hash_get(&aspectworld.config_hash,name);
if (item == NULL)
return NULL;
switch (item->type)
{
case CONFIG_TYPE_INT:
return (int *)item->val;
case CONFIG_TYPE_STR:
return (char *)item->data;
default:
return NULL;
}
}
/**
* @brief Function to turn on safemode
*/
void config_safemode_set()
{
config_update_key(CONFIG_NAME_SAFEMODE,
(void *) CONFIG_SAFEMODE_ON);
}
/**
* @brief Functions to turn off safemode
*/
void config_safemode_reset()
{
config_update_key(CONFIG_NAME_SAFEMODE,
(void *) CONFIG_SAFEMODE_OFF);
}
/**
* @brief Indicate safemode state
* @return Current safemode state
*/
int config_safemode()
{
return (int) config_get_data(CONFIG_NAME_SAFEMODE);
}
/**
* @brief Enable profile verbose printing for internal ERESI warnings
* @return Always 0
*/
int profiler_enable_err()
{
aspectworld.proflevel |= PROFILE_WARN;
return (0);
}
/**
* @brief Enable profile verbose printing for internal ERESI functions tracing
* @return Always 0
*/
int profiler_enable_out()
{
aspectworld.proflevel |= PROFILE_FUNCS;
return (0);
}
/**
* @brief Enable profile verbose printing for internal memory allocations
* @return Always 0
*/
int profiler_enable_alloc()
{
aspectworld.proflevel |= PROFILE_ALLOC;
return (0);
}
/**
* @brief Enable profile verbose printing for internal debugging informations
* @return Always 0
*/
int profiler_enable_debug()
{
aspectworld.proflevel |= PROFILE_DEBUG;
return (0);
}
/**
* @brief Disable profile verbose printing for internal warnings
* @return Always 0
*/
int profiler_disable_err()
{
aspectworld.proflevel &= (~PROFILE_WARN);
return (0);
}
/**
* @brief Disable profile verbose printing for internal ERESI functions tracing
* @return Always 0
*/
int profiler_disable_out()
{
aspectworld.proflevel &= (~PROFILE_FUNCS);
return (0);
}
/**
* @brief Disable profile verbose printing for internal memory allocations
* @return Always 0
*/
int profiler_disable_alloc()
{
aspectworld.proflevel &= (~PROFILE_ALLOC);
return (0);
}
/**
* @brief Disable profile verbose printing for internal debugging informations
* @return Always 0
*/
int profiler_disable_debug()
{
aspectworld.proflevel &= (~PROFILE_DEBUG);
return (0);
}
/**
* @brief Disable all profiling printing
* @return Always 0
*/
int profiler_disable_all()
{
aspectworld.proflevel = PROFILE_NONE;
return 0;
}
/**
* @brief Enable all profiling printing
* @return Always 0
*/
int profiler_enable_all()
{
profiler_enable_err();
profiler_enable_out();
profiler_enable_alloc();
return 0;
}
/**
* @brief Test if profiling is enabled
* @return Integer value of the profiling level
*/
int profiler_enabled()
{
return (aspectworld.proflevel);
}
/**
* @brief Test if profiler is enabled under certain flags
* @param mask Bitmask of bits to be tested
* @return A Bitmask of enabled profiling flags
*/
int profiler_is_enabled(u_char mask)
{
return (aspectworld.proflevel & mask);
}
/**
* @brief Change the profiling output function (default: revm_output in librevm)
* @param profile Function pointer of type int fct(char*) to be registered for standard profiling
* @param profile_err Function pointer of type int fct(char*) to be registered for error profiling
*/
void profiler_install(int (*profile)(char *),
int (*profile_err)(char *))
{
aspectworld.profile = profile;
aspectworld.profile_err = profile_err;
}
/* We setup two functions for colors because we have too many functions */
/**
* @brief Change simple color functions handlers
* @param endline Function pointer of type void fct() handling ends of line (default: revm_endline)
* @param colorinstr Function pointer of type char *fct(char *str) handling instruction printing
* @param colorstr Function pointer of type char *fct(char *str) handling string printing
* @param colorfieldstr Function pointer of type char *fct(char *str) handling field printing
* @param colortypestr Function pointer of type char *fct(char *str) handling type printing
* @param colorend Function pointer of type char *fct(char *str) handling ending lines printing
* @param colorwarn Function pointer of type char *fct(char *str) handling priting of warnings
* @param colorfunction Function pointer of type char *fct(char *str) handling function name printing
* @param colorfilename Function pointer of type char *fct(char *str) handling file name printing
*/
void profiler_setcolor(void (*endline)(),
char *(*colorinstr)(char *text),
char *(*colorstr)(char *t),
char *(*colorfieldstr)(char *t),
char *(*colortypestr)(char *t),
char *(*colorend)(char *text),
char *(*colorwarn)(char *text),
char *(*colorfunction)(char *text),
char *(*colorfilename)(char *text))
{
aspectworld.endline = endline;
aspectworld.colorinstr = colorinstr;
aspectworld.colorstr = colorstr;
aspectworld.colorfieldstr = colorfieldstr;
aspectworld.colortypestr = colortypestr;
aspectworld.colorend = colorend;
aspectworld.colorwarn = colorwarn;
aspectworld.colorfunction = colorfunction;
aspectworld.colorfilename = colorfilename;
}
/**
* @brief Change advanced color functions
* @param coloradv Function pointer of type char *fct(char*, char*, char*) formatting end lines
* @param colorinstr_fmt Function pointer of type char *fct(char *, char *) formatting instructions
* @param coloraddress Function pointer of type char *fct(char *, u_long) formatting addresses
* @param colornumber Function pointer of type char *fct(char *, u_int) formatting decimal numbers
* @param colorstr_fmt Function pointer of type char *fct(char *, char *) formatting strings
* @param colorfieldstr_fmt Function pointer of type char *fct(char *, char *) formatting field strings
* @param colortypestr_fmt Function pointer of type char *fct(char *, char *) formatting type names
* @param colorwarn_fmt Function pointer of type char *fct(char *, char *) formatting warnings
*/
void profiler_setmorecolor(char *(*coloradv)(char *ty, char *p, char *te),
char *(*colorinstr_fmt)(char* p, char *t),
char *(*coloraddress)(char *p, eresi_Addr a),
char *(*colornumber)(char *p, eresi_Off n),
char *(*colorstr_fmt)(char *p, char *t),
char *(*colorfieldstr_fmt)(char *p, char *t),
char *(*colortypestr_fmt)(char *p, char *t),
char *(*colorwarn_fmt)(char *pattern, char *text))
{
aspectworld.coloradv = coloradv;
aspectworld.colorinstr_fmt = colorinstr_fmt;
aspectworld.coloraddress = coloraddress;
aspectworld.colornumber = colornumber;
aspectworld.colorstr_fmt = colorstr_fmt;
aspectworld.colorfieldstr_fmt = colorfieldstr_fmt;
aspectworld.colortypestr_fmt = colortypestr_fmt;
aspectworld.colorwarn_fmt = colorwarn_fmt;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_sub_al_ib.c
/**
* @file libasm/src/arch/ia32/handlers/op_sub_al_ib.c
*
* @ingroup IA32_instrs
** $Id: op_sub_al_ib.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_sub_al_ib" opcode="0x2c"/>
*/
int op_sub_al_ib(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->len += 1;
new->instr = ASM_SUB;
new->ptr_instr = opcode;
new->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_AF | ASM_FLAG_CF | ASM_FLAG_PF |
ASM_FLAG_OF | ASM_FLAG_SF | ASM_FLAG_ZF;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_AL,
ASM_REGSET_R8));
new->len += asm_operand_fetch(&new->op[1], opcode + 1,
ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new);
new->op[0].content = ASM_OP_BASE | ASM_OP_FIXED;
new->op[0].ptr = opcode;
new->op[0].len = 0;
new->op[0].regset = ASM_REGSET_R8;
new->op[0].baser = ASM_REG_AL;
new->len += asm_operand_fetch(&new->op[1], opcode + 1,
ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_ldqf.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_ldqf.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_ldqf.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libasm.h"
int
asm_sparc_ldqf(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_format3 opcode;
struct s_asm_proc_sparc *inter;
sparc_convert_format3(&opcode, buf);
inter = proc->internals;
ins->instr = inter->op3_table[opcode.op3];
ins->type = ASM_TYPE_LOAD | ASM_TYPE_ASSIGN;
ins->nb_op = 2;
ins->op[0].baser = ((opcode.rd & 1) << 5) | (opcode.rd & 0x1E);
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_FREGISTER, ins);
if (opcode.i) {
ins->op[1].baser = opcode.rs1;
ins->op[1].imm = opcode.imm;
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_IMM_ADDRESS, ins);
}
else {
ins->op[1].baser = opcode.rs1;
ins->op[1].indexr = opcode.rs2;
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_REG_ADDRESS, ins);
}
return 4;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_prefix_es.c
/*
** $Id: op_prefix_es.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_prefix_es" opcode="0x26"/>
*/
int op_prefix_es(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->prefix |= ASM_PREFIX_ES;
if (!new->ptr_prefix)
new->ptr_prefix = opcode;
new->len += 1;
return (proc->fetch(new, opcode + 1, len - 1, proc));
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_shrd_rmv_rv_ib.c
/**
* @file libasm/src/arch/ia32/handlers/i386_shrd_rmv_rv_ib.c
*
* @ingroup IA32_instrs
* $Id: i386_shrd_rmv_rv_ib.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for instruction shrd, opcode 0x0f 0xac
* @param new Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Length of instruction.
*/
int i386_shrd_rmv_rv_ib(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
int olen;
new->instr = ASM_SHRD;
new->len += 1;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0));
#else
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new));
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_GENERAL, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_GENERAL, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[2], opcode + 1 + olen, ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[2], opcode + 1 + olen, ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
#else
new->op[0].type = ASM_OTYPE_ENCODED;
new->op[0].size = ASM_OSIZE_VECTOR;
new->op[1].type = ASM_OTYPE_GENERAL;
new->op[1].size = ASM_OSIZE_VECTOR;
new->op[2].type = ASM_OTYPE_IMMEDIATE;
new->op[2].size = ASM_OSIZE_BYTE;
operand_rmv_rv(new, opcode + 1, len - 1, proc);
new->op[2].type = ASM_OTYPE_IMMEDIATE;
new->op[2].content = ASM_OP_VALUE;
new->op[2].ptr = opcode + 2;
new->op[2].len = 1;
new->op[2].imm = 0;
memcpy(&new->op[2].imm, opcode + 2, 1);
#endif
return (new->len);
}
<file_sep>/src/libaspect/liblist.c
/**
* @file libaspect/liblist.c
* @ingroup libaspect
*
* @brief Contain ELFsh internal lists related API.
*
* Started on Fri Jul 13 20:26:18 2007 jfv
* $Id: liblist.c 1444 2011-01-31 07:41:29Z may $
*/
#include "libaspect.h"
/* Hash tables of hash tables */
hash_t *hash_lists = NULL;
/**
* @brief Initialize the hash table
*/
int elist_init(list_t *h, char *name, u_int type)
{
list_t *exist;
NOPROFILER_IN();
if (type >= aspect_type_nbr)
{
fprintf(stderr, "Unable to initialize list %s \n", name);
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Unable to initialize list", -1);
}
exist = elist_find(name);
if (exist)
{
#if 1 //__LIST_DEBUG__
fprintf(stderr, "DEBUG: List %s (%p) already exists in hash with addr %p : NOT CREATING \n",
name, h, exist);
#endif
NOPROFILER_ROUT(1);
}
#if __LIST_DEBUG__
else
fprintf(stderr, "DEBUG: List %s allocated at %p does not exists in hash : CREATING \n", name, h);
#endif
bzero(h, sizeof(list_t));
h->type = type;
h->name = name;
hash_add(hash_lists, name, h);
NOPROFILER_ROUT(0);
}
/**
* @brief Return a list by its name
*/
list_t *elist_find(char *name)
{
return ((list_t *) hash_get(hash_lists, name));
}
/**
* @brief Set a list by its name (overwrite if existing )
*/
int elist_register(list_t *list, char *name)
{
list_t *h;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
h = hash_get(hash_lists, name);
if (h)
{
if (h->type == ASPECT_TYPE_UNKNOW)
h->type = list->type;
if (h->type != list->type)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Incompatible lists", -1);
if (h->elmnbr)
h = elist_empty(name);
elist_merge(h, list);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
XALLOC(__FILE__, __FUNCTION__, __LINE__, h, sizeof(list_t), -1);
elist_init(h, name, h->type);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Empty a list
*/
list_t *elist_empty(char *name)
{
list_t *list;
char *newname;
char type;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
list = elist_find(name);
if (!list)
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, NULL);
type = list->type;
hash_del(hash_lists, name);
elist_destroy(list);
XALLOC(__FILE__, __FUNCTION__, __LINE__,
newname, strlen(name) + 1, NULL);
strncpy(newname, name, strlen(name));
XALLOC(__FILE__, __FUNCTION__, __LINE__,
list, sizeof(list_t), NULL);
elist_init(list, newname, type);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, list);
}
/* Reverse a list */
list_t *elist_reverse(list_t *l)
{
list_t *newlist;
listent_t *nextent;
listent_t *curent;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
hash_del(hash_lists, l->name);
XALLOC(__FILE__, __FUNCTION__, __LINE__, newlist, sizeof(list_t), NULL);
elist_init(newlist, l->name, l->type);
/* Copy the list inserting at the beginning all the time */
for (curent = l->head; curent; curent = nextent)
{
elist_add(newlist, curent->key, curent->data);
nextent = curent->next;
XFREE(__FILE__, __FUNCTION__, __LINE__, curent);
}
XFREE(__FILE__, __FUNCTION__, __LINE__, l);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, newlist);
}
/* Destroy a list */
void elist_destroy(list_t *h)
{
char **keys;
int idx;
int keynbr;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
//fprintf(stderr, "DEBUG: Destroying list %s at addr %p \n", h->name, h);
/* We should not destroy the elements as they might be in other hashes */
keys = elist_get_keys(h, &keynbr);
for (idx = 0; idx < keynbr; idx++)
XFREE(__FILE__, __FUNCTION__, __LINE__, keys[idx]);
if (keys)
elist_free_keys(keys);
hash_del(hash_lists, h->name);
XFREE(__FILE__, __FUNCTION__, __LINE__, h);
PROFILER_OUT(__FILE__, __FUNCTION__, __LINE__);
}
/* Copy a list */
list_t *elist_copy(list_t *h)
{
list_t *newlist;
listent_t *newent;
listent_t *prevent;
listent_t *curent;
void *newelem;
int size;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
XALLOC(__FILE__, __FUNCTION__, __LINE__, newlist, sizeof(list_t), NULL);
*newlist = *h;
prevent = NULL;
size = aspect_typesize_get(h->type);
/* Copy the list */
for (curent = h->head; curent; curent = curent->next)
{
XALLOC(__FILE__, __FUNCTION__, __LINE__, newent, sizeof(listent_t), NULL);
*newent = *curent;
XALLOC(__FILE__, __FUNCTION__, __LINE__, newelem, size, NULL);
memcpy(newelem, curent->data, size);
newent->data = newelem;
newent->key = strdup(curent->key);
newent->next = NULL;
if (prevent)
prevent->next = newent;
else
newlist->head = newent;
prevent = newent;
}
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, newlist);
}
/**
* @brief Add an element at the head of the list
*/
int elist_add(list_t *h, char *key, void *data)
{
listent_t *cur;
listent_t *next;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!h || !key || !data)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid NULL parameters", -1);
XALLOC(__FILE__, __FUNCTION__, __LINE__, cur, sizeof(listent_t), -1);
next = h->head;
cur->key = key;
cur->data = data;
cur->next = next;
h->head = cur;
h->elmnbr++;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Add an element at the head of the list
*/
int elist_append(list_t *h, char *key, void *data)
{
listent_t *cur;
listent_t *next;
int ret;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!h || !key || !data)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid NULL parameters", -1);
if (!h->head)
{
ret = elist_add(h, key, data);
if (ret < 0)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Unable to append list element", -1);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
XALLOC(__FILE__, __FUNCTION__, __LINE__, cur, sizeof(listent_t), -1);
cur->key = key;
cur->data = data;
cur->next = NULL;
next = h->head;
while (next->next)
next = next->next;
next->next = cur;
h->elmnbr++;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/*
* @brief Push an element on the list (used as a stack)
*/
int elist_push(list_t *h, void *data)
{
char key[BUFSIZ];
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!h || !data)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid NULL parameters", -1);
snprintf(key, sizeof(key), "%s_%u", h->name, h->elmnbr);
elist_add(h, strdup(key), data);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/*
* @brief Pop an element off the list (used as a stack)
*/
void *elist_pop(list_t *h)
{
listent_t *next;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!h || !h->head)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid input list", NULL);
next = h->head;
h->head = h->head->next;
h->elmnbr--;
XFREE(__FILE__, __FUNCTION__, __LINE__, next);
if (!h->head)
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, h->head);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, h->head->data);
}
/**
* @brief Delete an element from a list
*/
int elist_del(list_t *h, char *key)
{
listent_t *curelem;
listent_t *prevelem;
listent_t *todel;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!h || !key)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid NULL parameters", -1);
curelem = h->head;
prevelem = NULL;
for (curelem = h->head; curelem && strcmp(curelem->key, key);
curelem = curelem->next)
prevelem = curelem;
if (!curelem)
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
if (!prevelem)
{
todel = h->head;
h->head = h->head->next;
}
else
{
todel = prevelem->next;
prevelem->next = prevelem->next->next;
}
h->elmnbr--;
if (!h->elmnbr)
h->head = NULL;
XFREE(__FILE__, __FUNCTION__, __LINE__, todel);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Get the list element giving the key
*/
void *elist_get(list_t *h, char *key)
{
listent_t *cur;
if (!h || !key)
return (NULL);
for (cur = h->head; cur; cur = cur->next)
if (!strcmp(cur->key, key))
return (cur->data);
return (NULL);
}
/**
* @brief Get the list data giving the key
*/
void *elist_select(list_t *h, char *key)
{
listent_t *cur;
if (!h || !key)
return (NULL);
for (cur = h->head; cur; cur = cur->next)
if (!strcmp(cur->key, key))
return (cur->data);
return (NULL);
}
/* Get the list head */
listent_t *elist_get_head(list_t *h)
{
if (!h)
return (NULL);
return (h->head);
}
/* Get the list head data */
void *elist_get_headptr(list_t *h)
{
if (!h || !h->head)
return (NULL);
return (h->head->data);
}
/* Change the metadata for an existing entry, giving its key */
int elist_set(list_t *h, char *key, void *data)
{
listent_t *cur;
if (!h || !key)
return (-1);
for (cur = h->head; cur; cur = cur->next)
if (!strcmp(cur->key, key))
{
cur->data = data;
return (0);
}
return (-1);
}
/**
* @brief Replace a single element by a list of elements
*/
int elist_replace(list_t *h, char *key, list_t *newlist)
{
listent_t *cur;
listent_t *lastent;
listent_t *prev;
/* Preliminary checks */
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!h || !key || !newlist || !newlist->head)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid NULL parameters", 0);
/* Just find the latest entry */
for (lastent = newlist->head; lastent && lastent->next; lastent = lastent->next);
/* Now find the original element to replace by the new list */
for (prev = NULL, cur = h->head; cur; prev = cur, cur = cur->next)
if (!strcmp(cur->key, key))
{
if (!prev)
h->head = newlist->head;
else
prev->next = newlist->head;
lastent->next = cur->next;
h->elmnbr += newlist->elmnbr - 1;
//XFREE(__FILE__, __FUNCTION__, __LINE__, cur->data);
XFREE(__FILE__, __FUNCTION__, __LINE__, cur);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/* Could not find the element to swap */
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Cannot find element to be swapped", -1);
}
/* Return the array of keys */
char** elist_get_keys(list_t *h, int* n)
{
char **keys;
listent_t *curelem;
int idx;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!h || !h->elmnbr)
{
if (n)
*n = 0;
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid NULL parameters", NULL);
}
XALLOC(__FILE__, __FUNCTION__, __LINE__, keys,
sizeof(char *) * (h->elmnbr + 1), NULL);
for (idx = 0, curelem = h->head; curelem; curelem = curelem->next, idx++)
keys[idx] = curelem->key;
if (n)
*n = h->elmnbr;
keys[idx] = NULL;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, keys);
}
/* Free the keys array */
void elist_free_keys(char **keys)
{
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
XFREE(__FILE__, __FUNCTION__, __LINE__, keys);
PROFILER_OUT(__FILE__, __FUNCTION__, __LINE__);
}
/* Get -the list entry- for a given key */
listent_t *elist_get_ent(list_t *h, char *key)
{
listent_t *cur;
if (!h || !key)
return (NULL);
for (cur = h->head; cur; cur = cur->next)
if (!strcmp(cur->key, key))
return (cur);
return (NULL);
}
/* Print list content */
void elist_print(list_t *h)
{
listent_t *actual;
int index;
if (!h)
return;
puts(".::. Printing list .::. ");
for (index = 0, actual = h->head; index < h->elmnbr; index++, actual = actual->next)
printf(" ENT [%u] key = %s ; data = %p ; next = %p\n",
index, actual->key, actual->data, actual->next);
}
/* Apply a function on all elements of the list */
int elist_apply(list_t *h, void *ptr,
int (*func)(listent_t *e, void *p))
{
int index;
int ret = 0;
listent_t *cur;
if (!h || !func)
return (-1);
for (cur = h->head, index = 0; index < h->elmnbr; index++, cur = cur->next)
ret |= func (cur, ptr);
return ret;
}
/* Merge two list */
int elist_merge(list_t *dst, list_t *src)
{
int index;
listent_t *cur;
if (!dst || !src)
return (-1);
for (cur = src->head, index = 0; index < src->elmnbr; index++, cur = cur->next)
elist_add(dst, cur->key, cur->data);
return 0;
}
/* Unmerge two lists */
int elist_unmerge(list_t *dst, list_t *src)
{
listent_t *cur;
if (!dst || !src)
return (-1);
for (cur = src->head; cur; cur = cur->next)
elist_del(dst, cur->key);
return 0;
}
/* Return the size of a list */
int elist_size(list_t *h)
{
if (!h)
return (0);
return (h->elmnbr);
}
/* Compare two lists */
/* Unimplemented */
int elist_compare(list_t *first, list_t *two)
{
return (-1);
}
/* Linear typing of list API */
u_char elist_linearity_get(list_t *l)
{
if (!l)
return (0);
return (l->linearity);
}
/* Linear typing of list API */
void elist_linearity_set(list_t *l, u_char val)
{
if (!l)
return;
l->linearity = val;
}
<file_sep>/src/list.c
/*
* alihack - signature creating/searching tool
* copyright (c) 2011, snape
* basicblock linked list
*
*/
#include "list.h"
bb_list_node_t *bb_list_node_alloc(void *dptr)
{
bb_list_node_t *node;
if((node = (bb_list_node_t *)malloc(sizeof(bb_list_node_t))) == NULL)
return (NULL);
node->dptr = dptr;
node->next = node->prev = NULL;
return (node);
}
void bb_list_add(bb_list_t **list, bb_list_node_t *new)
{
if((*list) == NULL) {
*list = (bb_list_t *)malloc(sizeof(bb_list_t));
(*list)->head = (*list)->tail = NULL;
}
if((*list)->head == NULL) {
(*list)->head = new;
new->prev = NULL;
} else {
(*list)->tail->next = new;
new->prev = (*list)->tail;
}
(*list)->tail = new;
new->next = NULL;
}
void bb_list_insert(bb_list_t **list, bb_list_node_t *new, bb_list_node_t *after)
{
new->next = after->next;
new->prev = after;
if(after->next != NULL) {
after->next->prev = new;
} else {
(*list)->tail = new;
}
after->next = new;
}
void bb_list_del(bb_list_t **list, bb_list_node_t *del)
{
if(del->prev == NULL) {
(*list)->head = del->next;
} else {
del->prev->next = del->next;
}
if(del->next == NULL) {
(*list)->tail = del->prev;
} else {
del->next->prev = del->prev;
}
free(del);
}
bb_list_node_t *bb_list_find_next(bb_list_t **list, void *dptr)
{
bb_list_node_t *next;
for(next = (*list)->head; next; next = next->next) {
if(next->dptr == dptr)
return (next);
}
return (NULL);
}
bb_list_node_t *bb_list_find_prev(bb_list_t **list, void *dptr)
{
bb_list_node_t *prev;
for(prev = (*list)->tail; prev; prev = prev->prev) {
if(prev->dptr == dptr)
return (prev);;
}
return (NULL);
}
#ifdef DEBUG_LIST
void bb_list_print(bb_list_t **list, unsigned char dir)
{
bb_list_node_t *p;
for(p = (!dir ? (*list)->head : (*list)->tail); p; p = (!dir ? p->next : p->prev))
printf("%d\n", *(int *)p->dptr);
}
int main(int argc, char **arv)
{
int one, *on[23];
bb_list_t *global;
bb_list_node_t *p;
for(one = 0; one < 10; one++) {
on[one] = malloc(sizeof(int));
memcpy(on[one], &one, 4);
bb_list_add(&global, bb_list_node_alloc(on[one]));
}
p = bb_list_find_next(&global, on[5]);
printf("===========================================\n");
bb_list_print(&global, 1);
printf("===========================================\n");
p = bb_list_find_next(&global, on[7]);
bb_list_insert(&global, bb_list_node_alloc(on[5]), p);
bb_list_print(&global, 1);
exit(0);
}
#endif
<file_sep>/src/libasm/src/arch/ia32/handlers/op_lodsb.c
/**
* @file libasm/src/arch/ia32/handlers/op_lodsb.c
*
* @ingroup IA32_instrs
* $Id: op_lodsb.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
*
* <instruction func="op_lodsb" opcode="0xac"/>
*/
int op_lodsb(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->instr = ASM_LODSB;
new->len += 1;
new->ptr_instr = opcode;
new->type = ASM_TYPE_LOAD;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_YDEST, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_YDEST, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_FIXED, new);
#endif
new->op[1].content = ASM_OP_BASE | ASM_OP_FIXED;
new->op[1].regset = asm_proc_opsize(proc) ?
ASM_REGSET_R16 : ASM_REGSET_R32;
new->op[1].baser = ASM_REG_EAX;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/operand_handlers/asm_operand_fetch.c
/**
* @file libasm/src/arch/ia32/operand_handlers/asm_operand_fetch.c
*
* @ingroup IA32_operands
* @brief Implements top-level fetching handler for IA32 operands.
*
* $Id: asm_operand_fetch.c 1397 2009-09-13 02:19:08Z may $
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @brief Main function, dispatch processing to handler.
*
* @ingroup IA32_operands
* @param op Pointer to operand to fill
* @param opcode Pointer to operand data.
* @param otype Type of operand to fetch : ASM_OTYPE_*
* @param proc Pointer to processor structure.
* @return Operand length or -1 on error (should currently never occur)
*/
#if WIP
int asm_operand_fetch(asm_operand *operand, u_char *opcode, int otype,
asm_instr *ins, int opt)
#else
int asm_operand_fetch(asm_operand *operand, u_char *opcode, int otype,
asm_instr *ins)
#endif
{
vector_t *vec;
u_int dim[1];
int to_ret;
#if WIP
int (*fetch)(asm_operand *, u_char *, int, asm_instr *, int);
#else
int (*fetch)(asm_operand *, u_char *, int, asm_instr *);
#endif
vec = aspect_vector_get(LIBASM_VECTOR_OPERAND_IA32);
dim[0] = otype;
fetch = aspect_vectors_select(vec, dim);
#if WIP
to_ret = fetch(operand, opcode, otype, ins, opt);
#else
to_ret = fetch(operand, opcode, otype, ins);
#endif
if (to_ret == -1)
{
printf("%s:%i Unsupported operand type : %i\n", __FILE__, __LINE__,
otype);
}
else
{
operand->sbaser = ((operand->content & ASM_OP_BASE) ?
get_reg_intel(operand->baser, operand->regset) : "");
operand->sindex = ((operand->content & ASM_OP_BASE) ?
get_reg_intel(operand->indexr, operand->regset) : "");
}
return (to_ret);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_lock.c
/*
** $Id: op_lock.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_lock" opcode="0xf0"/>
*/
int op_lock(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
if (!new->ptr_prefix)
new->ptr_prefix = opcode;
new->len += 1;
new->prefix = ASM_PREFIX_LOCK;
return (proc->fetch(new, opcode + 1, len - 1, proc));
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_ud2a.c
/**
* @file libasm/src/arch/ia32/handlers/op_ud2a.c
*
* @ingroup IA32_instrs
* @brief Handler for instruction ud2a opcode 0x??
* $Id: op_ud2a.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @brief Handler for instruction ud2a opcode 0x??
* @param instr Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Length of instruction.
*/
int op_ud2a(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->instr = ASM_UD2A;
return (new->len);
}
<file_sep>/src/libasm/Makefile
##
## $Id: Makefile 1331 2009-02-17 05:02:42Z figueredo $
## Author : <<EMAIL>>
## Started : Xxx Xxx xx xx:xx:xx 2002
## Updated : Sun Mar 21 00:03:07 2004
##
include ../config.h
#
# Architecture source files
#
#CFLAGS += -ggdb
CFLAGS += $(CFLAGS_libasm) $(EXTRACFLAGS) -D__MacOSX__
RANLIB=ranlib
SRCS_libasm = \
src/generic.c \
src/output.c \
src/error.c \
src/operand.c \
src/instruction.c \
src/register.c \
src/build.c \
src/vectors.c
#
# IA32 Support
#
ifeq ($(LIBASM_ENABLE_IA32), 1)
SRCS_libasm += src/arch/ia32/init_i386.c \
src/arch/ia32/register.c \
src/arch/ia32/tables_i386.c \
src/arch/ia32/output_ia32.c \
src/arch/ia32/operand_ia32.c
ifeq ($(LIBASM_PACKED_HANDLERS), 1)
$(info [IA32] PACKED)
PACKED_ARCH += packed_ia32
SRCS_libasm += src/arch/ia32/packed_handlers.c
else
$(info [IA32] UNPACKED)
SRCS_libasm += $(foreach dir,src/arch/ia32/handlers/,\
$(wildcard $(dir)/*.c))
SRCS_libasm += $(foreach dir,src/arch/ia32/operand_handlers/,\
$(wildcard $(dir)/*.c))
endif
CFLAGS += -DLIBASM_ENABLE_IA32
endif
#
# Sparc Support
#
ifeq ($(LIBASM_ENABLE_SPARC), 1)
PACKED_ARCH += packed_sparc
SRCS_libasm += src/arch/sparc/init_sparc.c \
src/arch/sparc/register.c \
src/arch/sparc/tables_sparc.c \
src/arch/sparc/output_sparc.c \
src/arch/sparc/sparc_convert.c
ifeq ($(LIBASM_PACKED_HANDLERS),1)
$(info [SPARC] PACKED)
PACKED_ARCH += packed_sparc
SRCS_libasm += src/arch/sparc/packed_handlers.c
else
$(info [SPARC] UNPACKED)
SRCS_libasm += $(foreach dir,src/arch/sparc/handlers/,\
$(wildcard $(dir)/*.c))
SRCS_libasm += $(foreach dir,src/arch/sparc/operand_handlers/,\
$(wildcard $(dir)/*.c))
endif
CFLAGS += -DLIBASM_ENABLE_SPARC
endif
#
# Mips Support
#
ifeq ($(LIBASM_ENABLE_MIPS), 1)
PACKED_ARCH += packed_mips
SRCS_libasm += src/arch/mips/init_mips.c \
src/arch/mips/output_mips.c \
src/arch/mips/tables_mips.c \
src/arch/mips/mips_convert.c \
src/arch/mips/register_mips.c
ifeq ($(LIBASM_PACKED_HANDLERS), 1)
$(info [MIPS] PACKED)
PACKED_ARCH += packed_mips
SRCS_libasm += src/arch/mips/packed_handlers.c
else
$(info [MIPS] UNPACKED)
SRCS_libasm += $(foreach dir,src/arch/mips/handlers/,\
$(wildcard $(dir)/*.c))
SRCS_libasm += $(foreach dir,src/arch/mips/operand_handlers/,\
$(wildcard $(dir)/*.c))
endif
CFLAGS += -DLIBASM_ENABLE_MIPS
endif
#
# ARM Support
#
ifeq ($(LIBASM_ENABLE_ARM), 1)
PACKED_ARCH += packed_arm
SRCS_libasm += src/arch/arm/init_arm.c \
src/arch/arm/register_arm.c \
src/arch/arm/tables_arm.c \
src/arch/arm/output_arm.c \
src/arch/arm/decode_arm.c \
src/arch/arm/arm_convert.c
ifeq ($(LIBASM_PACKED_HANDLERS),1)
$(info [ARM] PACKED)
PACKED_ARCH += packed_arm
SRCS_libasm += src/arch/arm/packed_handlers.c
else
$(info [ARM] UNPACKED)
SRCS_libasm += $(foreach dir,src/arch/arm/handlers/,\
$(wildcard $(dir)/*.c))
SRCS_libasm += $(foreach dir,src/arch/arm/operand_handlers/,\
$(wildcard $(dir)/*.c))
endif
CFLAGS += -DLIBASM_ENABLE_ARM
endif
OBJS32_libasm = ${SRCS_libasm:.c=.32.o}
OBJS32_libasm += ${SRCS_hdl:.c=.32.o}
OBJS64_libasm = ${SRCS_libasm:.c=.64.o}
OBJS64_libasm += ${SRCS_hdl:.c=.64.o}
NAME32_libasm = libasm32.a
NAME32_libasm_o = libasm32.o
NAME64_libasm = libasm64.a
NAME64_libasm_o = libasm64.o
SRCS_sparc = tools/sparc_mydisasm.c
OBJS_sparc = ${SRCS_sparc:.c=.o}
NAME_sparc = test_sparc
#CFLAGS32 = $(CFLAGS) -Iinclude -Isrc/include -Wall -g3 -fPIC -I../libaspect/include -DERESI32
CFLAGS32 = $(CFLAGS) -m32 -DERESI32 -Iinclude -fPIC -Isrc/include -Wall -I../libaspect/include
CFLAGS64 = $(CFLAGS) -Iinclude -Isrc/include -Wall -g3 -I../libaspect/include -DERESI64
RM = rm -f
ETAGS = etags
CC ?= gcc -E
LD ?= ld
CP = cp
RANLIB = ranlib
all: all32
all32: libasm32.so
all64: libasm64.so
#src/arch/ia32/packed_handlers.c:
# cat ${SRCS_IA32} > src/arch/ia32/packed_handlers.c
install:
${CP} ${NAME_libasm} /usr/lib
${CP} include/libasm.h /usr/include
${CP} include/libasm-i386.h /usr/include
${CP} include/libasm-sparc.h /usr/include
libasm32.so: $(PACKED_ARCH) $(OBJS32_libasm)
@echo "[AR] ${NAME32_libasm}"
@ar rcs ${NAME32_libasm} ${OBJS32_libasm}
@echo "[RANLIB] libasm32.a"
@${RANLIB} ${NAME32_libasm}
@$(LD) -r -arch i386 $(OBJS32_libasm) -o ${NAME32_libasm_o}
@echo "[LD] libasm32.so"
@$(CC) -m32 -L../libaspect/ -laspect32 ${OBJS32_libasm} -o libasm32.so -shared
libasm64.so: $(PACKED_ARCH) $(OBJS64_libasm)
ar rcs ${NAME64_libasm} ${OBJS64_libasm}
#echo "[AR] ${NAME64_libasm}"
${RANLIB} ${NAME64_libasm}
#echo "[RANLIB] ${NAME64_libasm}"
$(LD) -r $(OBJS64_libasm) -o ${NAME64_libasm_o}
#echo "[CC -shared] libasm64.so"
ifeq ($(IRIX),1)
$(LD) -L../libaspect/ -laspect64 ${OBJS64_libasm} -o libasm64.so -shared
else
$(CC) -L../libaspect/ -laspect64 ${OBJS64_libasm} -o libasm64.so -shared
endif
clean: fclean
$(RM) ${OBJS32_libasm} ${OBJ64_libasm}
find . -name '*~' -exec rm -f {} \;
find src -name '*.o' -exec rm -rf {} \;
find src -name 'packed_handlers.c' -exec rm -rf {} \;
fclean:
$(RM) ${NAME32_libasm} ${NAME64_libasm}
$(RM) *.so *.o *.a
packed_ia32:
@#echo "packed ia32 ..."
@cat src/arch/ia32/handlers/*.c src/arch/ia32/operand_handlers/*.c > src/arch/ia32/packed_handlers.c
packed_sparc:
@#echo "packed sparc ..."
@cat src/arch/sparc/handlers/*.c src/arch/sparc/operand_handlers/*.c > src/arch/sparc/packed_handlers.c
packed_mips:
@#echo "packed mips ..."
@cat src/arch/mips/handlers/*.c src/arch/mips/operand_handlers/*.c > src/arch/mips/packed_handlers.c
packed_arm:
@#echo "packed arm ..."
@cat src/arch/arm/handlers/*.c src/arch/arm/operand_handlers/*.c > src/arch/arm/packed_handlers.c
%.32.o : %.c
@echo "[CC] $< ..."
@$(CC) $(CFLAGS32) -c -o $@ $<
%.64.o : %.c
$(CC) $(CFLAGS64) -c -o $@ $<
<file_sep>/src/libasm/src/arch/ia32/handlers/op_mov_rmv_iv.c
/**
* @file libasm/src/arch/ia32/handlers/op_mov_rmv_iv.c
*
* @ingroup IA32_instrs
* $Id: op_mov_rmv_iv.c 1397 2009-09-13 02:19:08Z may $
* ChangeLog:
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for opcode 0xc7
* @param new
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Length of instruction.
*/
int op_mov_rmv_iv(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
int olen;
new->len += 1;
new->type = ASM_TYPE_ASSIGN;
new->ptr_instr = opcode;
new->instr = ASM_MOV;
#if WIP
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0));
#else
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new));
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen, ASM_OTYPE_IMMEDIATE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen, ASM_OTYPE_IMMEDIATE, new);
#endif
if (asm_instruction_is_prefixed(new, ASM_PREFIX_OPSIZE))
{
if (asm_operand_is_reference(&new->op[0]))
{
new->instr = ASM_MOVW;
}
}
else
new->instr = ASM_MOV;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_group6.c
/*
** $Id: op_group6.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
int op_group6(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
new->len += 1;
modrm = (struct s_modrm *) opcode + 1;
switch(modrm->r) {
case 0:
new->instr = ASM_SLDT;
break;
case 1:
new->instr = ASM_STR;
break;
case 2:
new->instr = ASM_LLDT;
break;
case 3:
new->instr = ASM_LTR;
break;
case 4:
case 5:
case 6:
case 7:
break;
}
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
new->op[0].regset = ASM_REGSET_R16;
#else
new->op[0].type = ASM_OTYPE_ENCODED;
new->op[0].size = ASM_OSIZE_VECTOR;
operand_rmv(&new->op[0], opcode + 1, len - 1, proc);
new->len += new->op[0].len;
new->op[0].regset = ASM_REGSET_R16;
#endif
return (new->len);
}
<file_sep>/src/libasm/include/libasm-mips-structs.h
/**
* @defgroup MIPS_instrs MIPS instructions disassembler.
* @ingroup mips
*/
/**
* @file libasm/include/libasm-mips-structs.h
* @ingroup mips
* fix and fill
* - Adam 'pi3' Zabrocki
*
* $Id: libasm-mips-structs.h 1397 2009-09-13 02:19:08Z may $
*/
#ifndef LIBASM_MIPS_STRUCTS_H
#define LIBASM_MIPS_STRUCTS_H
/**
* Structure used to decode format reg instructions
*/
struct s_mips_decode_reg
{
u_int32_t op:6; /*! opcode field */
u_int32_t rs:5; /*! 1st source register */
u_int32_t rt:5; /*! 2nd source register */
u_int32_t rd:5; /*! destination register */
u_int32_t sa:5; /*! shift amount (shift instr) */
u_int32_t fn:6; /*! function to perform */
};
struct s_mips_decode_cop0
{
u_int32_t op:6; /*! opcode field */
u_int32_t rs:5; /*! 1st source register */
u_int32_t rt:5; /*! 2nd source register */
u_int32_t rd:5; /*! destination register */
u_int32_t sa:5; /*! shift amount (shift instr) */
u_int32_t fn:6; /*! function to perform */
};
/**
* Structure used to decode format immediate instructions
*/
struct s_mips_decode_imm
{
u_int32_t op:6;
u_int32_t rs:5;
u_int32_t rt:5;
u_int32_t im:16;
};
/**
* Structure used to decode format jump instructions
*/
struct s_mips_decode_jump
{
u_int32_t op:6; /*! opcode field */
u_int32_t ta:26; /*! target to jump to */
};
/**
* Structure used to decode format trap instructions
*/
struct s_mips_decode_trap
{
u_int32_t op:6;
u_int32_t rs:5;
u_int32_t rt:5;
u_int32_t code:10;
u_int32_t fn:6;
};
/**
* Structure used to decode format mov* instructions
*/
struct s_mips_decode_mov
{
u_int32_t op:6;
u_int32_t rs:5;
u_int32_t cc:3;
u_int32_t b1:1;
u_int32_t tf:1;
u_int32_t rd:5;
u_int32_t b2:5;
u_int32_t fn:6;
};
/**
* Structure used to decode some coprocesor2 instructions
*/
struct s_mips_decode_cop2
{
u_int32_t op:6;
u_int32_t rs:5;
u_int32_t rt:5;
u_int32_t rd:5;
u_int32_t fn:8;
u_int32_t sl:3;
};
#define s_mips_decode_priv s_mips_decode_cop2
/**
* Structure used to decode COP1X format instructions
*/
struct s_mips_decode_cop1x
{
u_int32_t op:6;
u_int32_t bs:5;
u_int32_t in:5;
u_int32_t f1:5;
u_int32_t f2:5;
u_int32_t fn:3;
u_int32_t fmt:3;
};
#endif
<file_sep>/src/libasm/include/libasm-i386.h
/**
* @defgroup ia32 Libasm IA32 support
* @ingroup libasm
*/
/**
* @file libasm/include/libasm-i386.h
* @ingroup ia32
* @brief Contains structures,prototypes and defines/enum related to ia32.
* $Id: libasm-i386.h 1403 2010-03-30 20:26:42Z thorkill $
*/
#ifndef LIBASM_I386_H_
#define LIBASM_I386_H_
#include <libasm-ia32-hdl.h>
typedef struct s_asm_i386_processor asm_i386_processor;
typedef struct s_asm_i386_table asm_i386_table;
/* Prototypes for IA32 specific API */
void asm_resolve_ia32(void *d, eresi_Addr, char *, u_int);
int asm_ia32_get_mode(asm_processor *proc);
eresi_Addr asm_dest_resolve(asm_processor *proc, eresi_Addr, u_int shift);
int asm_ia32_switch_mode(asm_processor *proc, int mode);
/** Are we in protected mode or real mode ? */
enum e_asm_proc_mode
{
INTEL_REAL,
INTEL_PROT
};
/** IA32 related functions */
int asm_content_pack(asm_operand *, int, int);
int asm_fixed_pack(int, int, int, int);
/**
* this structure is internal and may not be accessed by user
* directly. it contains reference to each table describing i386 opcodes
* refer to sandpile.org
*/
struct s_asm_proc_i386
{
int mode; /*!< processor state: opsize actived or not */
int vect_size;
int addsize; /*!< WIPcurrent state of the processor addsize prefix */
int opsize; /*!< WIPcurrent state of the processor addsize prefix */
int type; /*!< WIPcurrent state of the processor addsize prefix */
//int (*get_vect_size)(asm_processor *); /*!< Internal handler unused */
};
/**
* Content of the operand.
* Those flags are stored in asm_operand.content field.
*
* FIXME: MUST BE UNIFIED WITH libasm.h:156 e_op_types
* WARNING: used for pretty printing in libasm/ia32/
* Never used on others.
*/
#define ASM_OP_VALUE 1 /*!< immediate value present */
#define ASM_OP_BASE 2 /*!< base register present */
#define ASM_OP_INDEX 4 /*!< index register present */
#define ASM_OP_SCALE 8 /*!< scale factor present */
#define ASM_OP_FIXED 16
#define ASM_OP_REFERENCE 32 /*!< reference */
#define ASM_OP_ADDRESS 64 /*!< reference to a reference */
#define ASM_OP_FPU 128 /*!< operand is a FPU reference */
/**
* prefix
* |F|E|D|C|B|A|9|8|7|6|5|4|3|2|1|0|
*
* 0: rep
* 1: repne
* 2345:
* 0001: DS
* 0010: ES
* 0011: SS
* 0100: CS
* 0101: FS
* 0110: GS
* 6: lock
* 7: opsize
* 8: addsize
*/
/**
* Enum of the intel available prefixes.
*/
enum e_ia32_prefix
{
ASM_PREFIX_REP = 1, /*!< rep prefix */
ASM_PREFIX_REPNE = 2, /*!< repne prefix */
ASM_PREFIX_SEG = 60, /*!< Segment prefix mask */
ASM_PREFIX_DS = 4, /*!< ds prefix */
ASM_PREFIX_ES = 8, /*!< es prefix */
ASM_PREFIX_SS = 12, /*!< ss prefix */
ASM_PREFIX_CS = 16, /*!< cs prefix */
ASM_PREFIX_FS = 20, /*!< fs prefix */
ASM_PREFIX_GS = 24,
ASM_PREFIX_MASK = 60,
ASM_PREFIX_LOCK = 64,
ASM_PREFIX_OPSIZE = 128,
ASM_PREFIX_ADDSIZE = 256,
ASM_PREFIX_FWAIT = 512,
};
/**
* Control register bit flags
*
*/
enum e_ia32_flags
{
ASM_FLAG_CF = 1 << 0, /*!< carry flag */
ASM_FLAG_PF = 1 << 2, /*!< parity flag */
ASM_FLAG_AF = 1 << 4, /*!< ?? flag */
ASM_FLAG_ZF = 1 << 6, /*!< zero flag */
ASM_FLAG_SF = 1 << 7, /*!< signed flag */
ASM_FLAG_TF = 1 << 8, /*!< ?? flag */
ASM_FLAG_IF = 1 << 9, /*!< interrupt flag */
ASM_FLAG_DF = 1 << 10, /*!< debug flag ? */
ASM_FLAG_OF = 1 << 11,
ASM_FLAG_IOPL = 1 << 12,
ASM_FLAG_NT = 1 << 14,
ASM_FLAG_RF = 1 << 16,
ASM_FLAG_VM = 1 << 17,
ASM_FLAG_AC = 1 << 18,
ASM_FLAG_VIF = 1 << 19,
ASM_FLAG_VIP = 1 << 20,
ASM_FLAG_ID = 1 << 21
};
/**
* Content of the struct s_operand type field
*/
enum e_asm_operand_type {
/* no operand
*/
ASM_OTYPE_NONE,
/* operand is fixed in instruction coded by this opcode;
*/
ASM_OTYPE_FIXED,
/* register is coded in mod field of instruction opcode.
*/
ASM_OTYPE_OPMOD,
/* direct address; no mod R/M byte;
* address of operand is encoded in instruction;
* no base register, index register, or scaling factor can be applied
*/
ASM_OTYPE_ADDRESS,
/* reg field of mod R/M byte selects a control register
*/
ASM_OTYPE_CONTROL,
/* reg field of mod R/M byte selects a debug register
*/
ASM_OTYPE_DEBUG,
/* mod R/M byte follows opcode and specifies operand;
* operand is either a general register or a memory address;
* if it is a memory address, the address is computed from
* a segment register and any of the following values:
* a base register, an index register, a scaling factor, a displacement
*/
ASM_OTYPE_ENCODED,
ASM_OTYPE_ENCODEDBYTE,
/* flags registers
*/
ASM_OTYPE_FLAGS,
/* reg field of mod R/M byte selelcts a general register.
*/
ASM_OTYPE_GENERAL,
ASM_OTYPE_GENERALBYTE,
/* immediate data; value of operand is encoded in subsequent bytes
* of instruction
*/
ASM_OTYPE_IMMEDIATE,
ASM_OTYPE_IMMEDIATEWORD,
/* immediate data; value of operand is encoded in subsequent bytes
* of instruction
*/
ASM_OTYPE_IMMEDIATEBYTE,
/* instruction contains a relative offset to be added
* to the instruction pointer register
*/
ASM_OTYPE_SHORTJUMP,
/* instruction contains a relative one byte offset to be added
* to the instruction pointer register
*/
ASM_OTYPE_JUMP,
/* mod R/M only refer to memory
*/
ASM_OTYPE_MEMORY,
/* instruction has no mod R/M byte; |
* offset of operand is coded as a word or double word (depending on
* address size attribute) in instruction; |
* no base register, index register, or scaling factor can be applied;
* eg. MOV (A0..A3h)
*/
ASM_OTYPE_OFFSET,
/* reg field of mod R/M byte selects a packed quadword MMX register
*/
ASM_OTYPE_PMMX,
/* mod R/M byte follows opcode and specifies operand; operand is
* either an MMX register or a memory address;
* if it is a memory address, the address is computed
* from a segment register and any of the following values:
* |a base register, an index register, a scaling factor, a displacement
*/
ASM_OTYPE_QMMX,
/*
* mod field of mod R/M byte may refer only to a general register
*/
ASM_OTYPE_REGISTER,
/* reg field of mod R/M byte selects a segment register
*/
ASM_OTYPE_SEGMENT,
/* no operand
*/
ASM_OTYPE_TEST,
/* no operand
*/
ASM_OTYPE_VSFP,
/* no operand
*/
ASM_OTYPE_WSFP,
/* memory addressed by ds:si
*/
ASM_OTYPE_XSRC,
/* memory addressed by es:di
*/
ASM_OTYPE_YDEST,
/* immediate value encoded in instruction
*/
ASM_OTYPE_VALUE,
ASM_OTYPE_REG0,
ASM_OTYPE_REG1,
ASM_OTYPE_REG2,
ASM_OTYPE_REG3,
ASM_OTYPE_REG4,
ASM_OTYPE_REG5,
ASM_OTYPE_REG6,
ASM_OTYPE_REG7,
ASM_OTYPE_ST,
ASM_OTYPE_ST_0,
ASM_OTYPE_ST_1,
ASM_OTYPE_ST_2,
ASM_OTYPE_ST_3,
ASM_OTYPE_ST_4,
ASM_OTYPE_ST_5,
ASM_OTYPE_ST_6,
ASM_OTYPE_ST_7,
ASM_OTYPE_NUM
};
/**
* Content of the struct s_operand size field
*
*/
enum e_asm_operand_size {
ASM_OSIZE_NONE,
ASM_OSIZE_BYTE,
ASM_OSIZE_WORD,
ASM_OSIZE_DWORD,
ASM_OSIZE_QWORD,
ASM_OSIZE_OWORD,
ASM_OSIZE_CHAR,
ASM_OSIZE_VECTOR,
ASM_OSIZE_POINTER,
ASM_OSIZE_ADDRESS,
ASM_OSIZE_6BYTES
};
/**
* Currently unsupported.
*/
enum e_asm_enc {
ASM_ENC_NONE,
ASM_ENC_ADDRESS,
ASM_ENC_CONTROL,
ASM_ENC_DEBUG,
ASM_ENC_ENCODED,
ASM_ENC_FLAGS,
ASM_ENC_GENERAL,
ASM_ENC_IMMEDIATE,
ASM_ENC_JUMP,
ASM_ENC_MEMORY,
ASM_ENC_OFFSET,
ASM_ENC_P,
ASM_ENC_Q,
ASM_ENC_R,
ASM_ENC_SEGREG,
ASM_ENC_TEST,
ASM_ENC_VREGPACKEDFP,
ASM_ENC_WMOD,
ASM_ENC_SRC,
ASM_ENC_DST,
/* */
ASM_ENC_REG0,
ASM_ENC_REG1,
ASM_ENC_REG2,
ASM_ENC_REG3,
ASM_ENC_REG4,
ASM_ENC_REG5,
ASM_ENC_REG6,
ASM_ENC_REG7
};
#define ASM_ENC_ANY ( ASM_ENC_ADDRESS | ASM_ENC_CONTROL | ASM_ENC_DEBUG | \
ASM_ENC_ENCODED | ASM_ENC_FLAGS | ASM_ENC_GENERAL | ASM_ENC_IMMEDIATE | \
ASM_ENC_JUMP | ASM_ENC_MEMORY | ASM_ENC_OFFSET | ASM_ENC_P | ASM_ENC_Q | \
ASM_ENC_R | ASM_ENC_SEGREG | ASM_ENC_TEST | ASM_ENC_VREGPACKEDFP | ASM_ENC_WMOD | \
ASM_ENC_SRC | ASM_ENC_DST | \
ASM_ENC_REG0 | ASM_ENC_REG1 | ASM_ENC_REG2 | ASM_ENC_REG3 | ASM_ENC_REG4 | \
ASM_ENC_REG5 | ASM_ENC_REG6 | ASM_ENC_REG7)
enum e_asm_size {
ASM_SIZE_BYTE,
ASM_SIZE_WORD,
ASM_SIZE_DWORD,
ASM_SIZE_QWORD,
ASM_SIZE_OWORD,
ASM_SIZE_CWORD,
ASM_SIZE_VECTOR,
ASM_SIZE_30BITS
};
#define ASM_SIZE_ANY (ASM_SIZE_BYTE | ASM_SIZE_WORD | ASM_SIZE_DWORD |\
ASM_SIZE_QWORD | ASM_SIZE_CWORD | ASM_SIZE_VECTOR)
/**
* regset
*
*/
#define ASM_REGSET_R8 256 /* al,cl,dl... */
#define ASM_REGSET_R16 512 /* ax,cx,dx... */
#define ASM_REGSET_R32 1024 /* eax,ecx,edx... */
#define ASM_REGSET_MM 2048 /* mm0, mm1, mm2 */
#define ASM_REGSET_XMM 4096 /* xmm0, xmm1... */
#define ASM_REGSET_SREG 8192 /* es, cs, ss ... */
#define ASM_REGSET_CREG 16384 /* cr0, cr1 ... */
#define ASM_REGSET_DREG 32768 /* dr0, dr1, ... */
/**
* enum
*
* here follows enums for each regsets.
*
**/
/**
* 8 bits registers set.
*/
enum e_asm_reg8 {
ASM_REG_AL, /* 000 */
ASM_REG_CL, /* 001 */
ASM_REG_DL, /* 010 */
ASM_REG_BL, /* 011 */
ASM_REG_AH, /* 100 */
ASM_REG_CH, /* 101 */
ASM_REG_DH, /* 110 */
ASM_REG_BH /* 111 */
};
/**
* 16 bits registers set.
*/
enum e_asm_reg16 {
ASM_REG_AX, /* 000 */
ASM_REG_CX, /* 001 */
ASM_REG_DX, /* 010 */
ASM_REG_BX, /* 011 */
ASM_REG_SP, /* 100 */
ASM_REG_BP, /* 101 */
ASM_REG_SI, /* 110 */
ASM_REG_DI /* 111 */
};
/**
* @brief 32 bits registers set.
*/
enum e_regset_r32 {
ASM_REG_EAX, /* 000 */
ASM_REG_ECX, /* 001 */
ASM_REG_EDX, /* 010 */
ASM_REG_EBX, /* 011 */
ASM_REG_ESP, /* 100 */
ASM_REG_EBP, /* 101 */
ASM_REG_ESI, /* 110 */
ASM_REG_EDI /* 111 */
};
/**
* @brief MM registers set.
*/
enum e_asm_regmm {
ASM_REG_MM0, /* 110 */
ASM_REG_MM1, /* 110 */
ASM_REG_MM2, /* 110 */
ASM_REG_MM3, /* 110 */
ASM_REG_MM4, /* 110 */
ASM_REG_MM6, /* 110 */
ASM_REG_MM7 /* 110 */
};
/**
* @brief XMMS registers set.
*/
enum e_asm_regxmm {
ASM_REG_XMM0, /* 110 */
ASM_REG_XMM1, /* 110 */
ASM_REG_XMM2, /* 110 */
ASM_REG_XMM3, /* 110 */
ASM_REG_XMM4, /* 110 */
ASM_REG_XMM5, /* 110 */
ASM_REG_XMM6, /* 110 */
ASM_REG_XMM7 /* 110 */
};
/**
* @brief Segment registers set.
*/
enum e_asm_sreg {
ASM_REG_ES, /* 000 */
ASM_REG_CS, /* 001 */
ASM_REG_SS, /* 010 */
ASM_REG_DS, /* 011 */
ASM_REG_FS, /* 100 */
ASM_REG_GS, /* 101 */
ASM_REG_SREGRES1,
ASM_REG_SREGRES2
};
/**
* @brief Control registers set.
*/
enum e_asm_creg {
ASM_REG_CR0, /* 000 */
ASM_REG_CR1, /* 001 */
ASM_REG_CR2, /* 010 */
ASM_REG_CR3, /* 011 */
ASM_REG_CR4, /* 100 */
ASM_REG_CR5, /* 101 */
ASM_REG_CR6, /* 110 */
ASM_REG_CR7 /* 111 */
};
/**
* @brief Debug registers set
*/
enum e_asm_dreg {
ASM_REG_DR0, /* 000 */
ASM_REG_DR1, /* 001 */
ASM_REG_DR2, /* 010 */
ASM_REG_DR3, /* 011 */
ASM_REG_DR4, /* 100 */
ASM_REG_DR5, /* 101 */
ASM_REG_DR6, /* 110 */
ASM_REG_DR7 /* 111 */
};
/**
* @brief Instruction list.
* Last instruction must be ASM_BAD
* If NOT, this may produce allocation error as ASM_BAD is used to allocate
* size of the instruction label array.
* Refer to init_instr_table in tables_i386.c
*/
enum e_asm_instr {
ASM_NONE,
/* special instr id */
ASM_IPREFIX_MIN,
ASM_IPREFIX_CS,
ASM_IPREFIX_DS,
ASM_IPREFIX_ES,
ASM_IPREFIX_FS,
ASM_IPREFIX_GS,
ASM_IPREFIX_SS,
ASM_IPREFIX_OPSIZE,
ASM_IPREFIX_ADSIZE,
ASM_IPREFIX_MAX,
ASM_GROUP_MIN,
ASM_GROUP1,
ASM_GROUP2,
ASM_GROUP3,
ASM_GROUP4,
ASM_GROUP5,
ASM_GROUP6,
ASM_GROUP7,
ASM_GROUP8,
ASM_GROUP9,
ASM_GROUP10,
ASM_GROUP11,
ASM_GROUP12,
ASM_GROUP13,
ASM_GROUP14,
ASM_GROUP15,
ASM_GROUP16,
ASM_GROUP17,
ASM_ESC0,
ASM_ESC1,
ASM_ESC2,
ASM_ESC3,
ASM_ESC4,
ASM_ESC5,
ASM_ESC6,
ASM_ESC7,
ASM_GROUP_MAX,
ASM_2BYTES,
/* instructions */
ASM_CALL,
ASM_BRANCH,
ASM_BRANCH_U_LESS,
ASM_BRANCH_U_LESS_EQUAL,
ASM_BRANCH_S_LESS,
ASM_BRANCH_S_LESS_EQUAL,
ASM_BRANCH_U_GREATER,
ASM_BRANCH_U_GREATER_EQUAL,
ASM_BRANCH_S_GREATER,
ASM_BRANCH_S_GREATER_EQUAL,
/* 10 */
ASM_BRANCH_EQUAL,
ASM_BRANCH_NOT_EQUAL,
/* x86 specific */
ASM_BRANCH_PARITY,
ASM_BRANCH_NOT_PARITY,
ASM_BRANCH_OVERFLOW,
/* 15 */
ASM_BRANCH_NOT_OVERFLOW,
ASM_BRANCH_SIGNED,
ASM_BRANCH_NOT_SIGNED,
ASM_BRANCH_CXZ,
/* */
ASM_JO,
ASM_JNO,
ASM_JB,
ASM_JNB,
ASM_JZ,
ASM_JNZ,
ASM_JBE,
ASM_JNBE,
ASM_JS,
ASM_JNS,
ASM_JP,
ASM_JNP,
ASM_JL,
ASM_JNL,
ASM_JLE,
ASM_JNLE,
/* generic instruction */
ASM_ADD,
ASM_CBW,
ASM_CWD,
/* 20 */
ASM_LEA,
ASM_OR,
ASM_ADC,
ASM_SBB,
ASM_AND,
/* 25 */
ASM_SUB,
ASM_XOR,
ASM_XADD,
ASM_CLFLUSH,
ASM_CMP,
ASM_IN,
ASM_INC,
/* 30 */
ASM_DEC,
ASM_PUSH,
ASM_PUSHF,
ASM_CWTD,
ASM_CBTW,
ASM_POP,
ASM_POPF,
/* 35 */
ASM_TEST,
ASM_NOP,
ASM_LOAD,
ASM_STORE,
ASM_MOV,
ASM_MOVW,
/* 40 */
ASM_INT,
ASM_RET,
ASM_XCHG,
ASM_INSB,
ASM_INSW,
ASM_INSD,
ASM_PUSHA,
ASM_POPA,
/* 45 */
ASM_AAM,
ASM_AAD,
ASM_LOCK,
ASM_LOOP,
ASM_LOOPE,
/* 50 */
ASM_LOOPNE,
ASM_JECX,
ASM_SALC,
ASM_LEAVE,
ASM_HLT,
ASM_SHR,
ASM_DIV,
/* 55 */
ASM_IDIV,
ASM_MUL,
ASM_IMUL,
ASM_NOT,
ASM_NEG,
/* 60 */
ASM_SAHF,
ASM_LAHF,
ASM_MOVSB,
ASM_MOVSBW,
ASM_MOVSD,
ASM_CMPSB,
ASM_CMPSW,
/* 65 */
ASM_CMPSD,
ASM_STOSB,
ASM_STOSW,
ASM_STOSD,
ASM_LODSB,
ASM_LODSD,
/* 70 */
ASM_SCASB,
ASM_SCASD,
ASM_INTO,
ASM_IRET,
ASM_SHIFT,
/* 75 */
ASM_XLATB,
ASM_XLAT,
ASM_ORB,
/* 80 */
ASM_MOVZWL,
ASM_CLD,
ASM_SMSW,
ASM_LMSW,
/* 85 */
ASM_STD,
ASM_OUT,
ASM_SHL,
ASM_RETF,
/* 90 */
ASM_ENTER,
ASM_MOVZBL,
ASM_REPNZ,
ASM_REPZ,
ASM_SET_OVERFLOW,
/* 95 */
ASM_SET_NOT_OVERFLOW,
ASM_SET_PARITY,
ASM_SET_NOT_PARITY,
ASM_SET_SIGNED,
ASM_SET_NOT_SIGNED,
ASM_SET_EQUAL,
ASM_SET_NOT_EQUAL,
ASM_SET_U_LESS,
ASM_SET_U_LESS_EQUAL,
ASM_SET_S_LESS,
ASM_SET_S_LESS_EQUAL,
ASM_SET_U_GREATER,
ASM_SET_U_GREATER_EQUAL,
ASM_SET_S_GREATER,
ASM_SET_S_GREATER_EQUAL,
ASM_CPUID,
ASM_SHRD,
ASM_SHLD,
ASM_CLTD,
ASM_SAR,
ASM_ROR,
ASM_BT,
ASM_BTS,
ASM_INT3,
ASM_CMC,
ASM_RCL,
ASM_SAL,
ASM_ROL,
ASM_SCASW,
ASM_WAIT,
ASM_FWAIT,
ASM_BSR,
ASM_BSF,
ASM_RCR,
ASM_CLI,
ASM_CWTL,
ASM_OUTSB,
ASM_OUTSW,
ASM_OUTSD,
ASM_STI,
ASM_CMOVNE,
ASM_LSS,
ASM_MOVSW,
ASM_MOVZBW,
ASM_BOUND,
ASM_LES,
ASM_LDS,
ASM_AAA,
ASM_DAA,
ASM_ARPL,
ASM_CLC,
ASM_STC,
ASM_INT1,
ASM_VERR,
ASM_VERW,
ASM_BRANCHE,
ASM_AAS,
ASM_DAS,
ASM_UD2A,
ASM_UD2,
ASM_BTC,
ASM_CMPXCHG,
ASM_LIDT,
ASM_LGDT,
ASM_FXSAVE,
ASM_FXRSTOR,
ASM_LDMXCSR,
ASM_STMXCSR,
ASM_LFENCE,
ASM_MLENCE,
ASM_SLENCE,
ASM_WBINVD,
ASM_RDMSR,
ASM_XSTORERNG,
ASM_XCRYPTCBC,
ASM_XCRYPTCFB,
ASM_XCRYPTOFB,
ASM_BTRL,
ASM_PREFETCH_NTA,
ASM_PREFETCH_T0,
ASM_PREFETCH_T1,
ASM_PREFETCH_T2,
ASM_HINT_NOP,
ASM_SGDT,
ASM_SIDT,
ASM_STR,
ASM_BTR,
ASM_LTR,
ASM_SLDT,
ASM_INVLPG,
/* 150 */
ASM_RDTSC,
ASM_LLDT,
ASM_LBRANCH,
ASM_CMOVA,
ASM_CMOVE,
ASM_CMOVAE,
ASM_CMOVO,
ASM_CMOVNO,
ASM_CMOVB,
ASM_CMOVBE,
ASM_CMOVS,
ASM_CMOVNS,
ASM_CMOVP,
ASM_CMOVNP,
ASM_CMOVL,
ASM_CMOVNL,
ASM_CMOVLE,
ASM_CMOVNLE,
ASM_MOVSBL,
ASM_MOVSWL,
ASM_MOVD,
ASM_MOVQ,
ASM_BSWAP,
ASM_PAND,
ASM_POR,
ASM_PXOR,
ASM_PSLLQ,
ASM_PSRLQ,
ASM_PSRLW,
ASM_PSRAW,
ASM_PSLLW,
ASM_PMULLW,
ASM_PADDUSW,
ASM_PADDUSB,
ASM_PUNPCKLBW,
ASM_PUNPCKHBW,
ASM_PACKUSWB,
ASM_EMMS,
/*
*
*/
ASM_FXRSTORE,
ASM_MFENCE,
ASM_SFENCE,
/*
* FPU INSTRUCTIONS
*/
ASM_F2XM1, /* Function 2^X Minus 1 */
ASM_FABS, /* Function ABSolute value */
ASM_FADD, /* Function ADD */
ASM_FADDP, /* Function ADD and Pop */
ASM_FBLD, /* Function BCD LoaD */
ASM_FBSTP, /* Function BCD STore and Pop */
ASM_FCHS, /* Function CHange Sign */
ASM_FCLEX, /* Function CLear EXceptions with wait */
ASM_FCMOVB,
ASM_FCMOVU,
ASM_FCOM, /* Functioon COMpare real */
ASM_FCOMP, /* Function COMpare reald and Pop */
ASM_FCOMPP, /* Function COMpare reald and PoP twice */
ASM_FCOMPS, /* */
ASM_FDECSTP, /* Function DECrement STack Pointer */
ASM_FDISI, /* Function DISable Interrupts with wait */
ASM_FDIV, /* Function real DIVide */
ASM_FDIVP, /* Function real DIVide and Pop */
ASM_FDIVR, /* Function real DIVide Reversed */
ASM_DIVRP, /* Function real DIVide Reversed and Pop */
ASM_FENI, /* Function ENable Interrupts with wait */
ASM_FFREE, /* Function FREE register */
ASM_FIADD, /* Function Integer ADD */
ASM_FICOM, /* Function Integer COMpare */
ASM_FICOMP, /* Function Integer COMpare and Pop */
ASM_FIDIV, /* Function Integer DIVide */
ASM_FIDIVR, /* Function Integer DIVide Reversed */
ASM_FILD, /* Function Integer LoaD */
ASM_FIMUL, /* Function Integer Multiply */
ASM_FINCSTP, /* Function INCrement STac Pointer */
ASM_FINIT, /* Function INITialize coprocessor with wait */
ASM_FIST, /* Function Integer STore */
ASM_FISTP, /* Function Integer STore and Pop */
ASM_FISUB, /* */
ASM_FISUBR, /* */
ASM_FUCOM, /* */
ASM_FUCOMP, /* */
ASM_FUCOMPP, /* */
ASM_FLDLN2,
ASM_FTST,
ASM_FPREM,
ASM_FRNDINT,
ASM_FNOP,
ASM_FCMOVNE,
ASM_FSTP1,
ASM_FSCALE,
ASM_FSQRT,
ASM_FSIN,
ASM_FCOS,
ASM_FISTTP,
ASM_FDIVRP, /* */
ASM_FREEP,
ASM_FSUBP, /* */
ASM_FSUBRP, /* */
ASM_FCMOVBE,
ASM_FMUL, /* */
ASM_FMULP, /* */
ASM_FRSTOR, /* */
ASM_FSAVE, /* */
ASM_FNSAVE, /* */
ASM_FSTP, /* Function STore real and Pop - 8087 */
ASM_FSUB, /* */
ASM_FSUBR, /* */
ASM_FPATAN,
ASM_FST, /* */
ASM_FXAM,
ASM_FCMOVNBE,
ASM_FCMOVNU,
ASM_FXCH,
ASM_FSINCOS,
ASM_FYL2X,
ASM_FSTENV,
ASM_FLDL2T,
ASM_FLDL2E,
ASM_FLDPI,
ASM_FPTAN,
ASM_FXTRACT,
ASM_FYL2XP1,
ASM_FLD, /* Function LoaD real - 8087 */
ASM_FLDZ, /* */
ASM_FLD1,
ASM_FSTSW, /* */
ASM_FNSTSW, /* */
AM_FNSTSW, /* Function (No wait) STore Status Word - 8087 */
ASM_FCMOVE,
ASM_FCMOVNB,
ASM_FLDLG2,
ASM_FSORT,
ASM_FXCH4,
ASM_FTSTP,
ASM_FPEM1,
ASM_FLDCW, /* */
ASM_FNSTENV,
ASM_FSTCW,
ASM_FNSTCW,
ASM_FLDENV,
ASM_FSETPM,
ASM_FRSTPM,
ASM_FUCOMI,
ASM_FRICHOP,
ASM_FCOMI,
ASM_FCOMP5,
ASM_FRINT2,
ASM_FCOM2,
ASM_FCOMP3,
ASM_FXCH7,
ASM_FSTP8,
ASM_FSTP9,
ASM_FSTDW,
ASM_FSTSG,
ASM_FUCOMIP,
ASM_FRINEAR,
ASM_FCOMIP,
/**
* keep this in last position unless
* you know what you are doing
**/
ASM_BAD
};
/*
* specialisation asm_processor for i386
*/
struct s_asm_i386_processor {
/* handler to resolving function */
void (*resolve_immediate)(void *, u_int, char *, u_int);
/* handler data pointer */
void *resolve_data;
/* processor type . I386 supports only */
int type;
/* */
char **instr_table;
int (*fetch)(asm_instr *, u_char *, u_int,
asm_processor *);
/* output handler. print instruction in a readable string */
char *(*display_handle)(asm_instr *instr, int addr);
/* pointer to an internal structure. */
struct s_asm_proc_i386 *internals;
};
#endif
<file_sep>/src/libasm/src/arch/ia32/handlers/op_pusha.c
/*
** $Id: op_pusha.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_pusha" opcode="0x60"/>
*/
int op_pusha(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->ptr_instr = opcode;
new->instr = ASM_PUSHA;
new->type = ASM_TYPE_TOUCHSP | ASM_TYPE_STORE;
new->spdiff = -4 * 8;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_insw.c
/*
** $Id: op_insw.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_insw" opcode="0x6d"/>
<instruction func="op_insd" opcode="0x6d"/>
*/
int op_insw(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->len += 1;
new->ptr_instr = opcode;
if (!asm_proc_opsize(proc))
new->instr = ASM_INSW;
else
new->instr = ASM_INSD;
new->ptr_instr = opcode;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_YDEST, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_YDEST, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE | ASM_OP_REFERENCE, ASM_REG_DX,
ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_FIXED, new);
#endif
new->op[1].content = ASM_OP_BASE | ASM_OP_REFERENCE;
new->op[1].regset = ASM_REGSET_R16;
new->op[1].baser = ASM_REG_DX;
#else
new->op[0].type = ASM_OTYPE_YDEST;
new->op[0].content = ASM_OP_BASE | ASM_OP_REFERENCE;
new->op[0].baser = ASM_REG_EDI;
new->op[0].prefix = ASM_PREFIX_DS;
new->op[0].regset = asm_proc_addsize(proc) ? ASM_REGSET_R16 :
ASM_REGSET_R32;
new->op[1].type = ASM_OTYPE_FIXED;
new->op[1].content = ASM_OP_BASE | ASM_OP_REFERENCE;
new->op[1].regset = ASM_REGSET_R16;
new->op[1].baser = ASM_REG_DX;
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_unary_rmv.c
/**
* @file libasm/src/arch/ia32/handlers/op_unary_rmv.c
*
* @ingroup IA32_instrs
* @brief Handler for instruction unary rmv opcode 0xf7
* $Id: op_unary_rmv.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @brief Handler for instruction unary rmv opcode 0xf7
* @param instr Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Length of instruction.
*/
int op_unary_rmv(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
int olen;
modrm = (struct s_modrm *) (opcode + 1);
new->ptr_instr = opcode;
new->len += 1;
new->type = ASM_TYPE_ARITH;
switch (modrm->r) {
case 0:
new->instr = ASM_TEST;
new->type = ASM_TYPE_COMPARISON | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_OF | ASM_FLAG_CF | ASM_FLAG_PF |
ASM_FLAG_SF | ASM_FLAG_ZF;
break;
case 1:
return (0);
case 2:
new->instr = ASM_NOT;
break;
case 3:
new->instr = ASM_NEG;
new->type |= ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_CF;
break;
case 4:
new->instr = ASM_MUL;
new->type |= ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_OF | ASM_FLAG_CF;
break;
case 5:
new->instr = ASM_IMUL;
new->type |= ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_OF | ASM_FLAG_CF;
break;
case 6:
new->instr = ASM_DIV;
break;
case 7:
new->instr = ASM_IDIV;
break;
} /* switch */
#if WIP
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1,
ASM_OTYPE_ENCODED, new, 0));
if (new->instr == ASM_TEST) {
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen,
ASM_OTYPE_IMMEDIATE, new, 0);
}
#else
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1,
ASM_OTYPE_ENCODED, new));
if (new->instr == ASM_TEST) {
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen,
ASM_OTYPE_IMMEDIATE, new);
}
#endif
return (new->len);
}
<file_sep>/src/libaspect/vectors.c
/**
* @defgroup libaspect libaspect: The ERESI aspect library.
* @ingroup ERESI
*/
/**
* @file libaspect/vectors.c
** @ingroup libaspect
** @brief Implement the modularity for the framework.
**
** Started Dec 22 2006 02:57:03 jfv
** $Id: vectors.c 1440 2010-12-29 02:22:03Z may $
*/
#include "libaspect.h"
hash_t *vector_hash = NULL;
/**
* @brief Retreive a vector from the hash table giving its name
* @param name Vector name
* @return Found vector, or NULL if unfound
*/
vector_t* aspect_vector_get(char *name)
{
vector_t *vect;
if (!vector_hash)
{
printf("Tried to get a vector when hash table = NULL \n");
// sleep(30);
return (NULL);
}
vect = (vector_t *) hash_get(vector_hash, name);
return (vect);
}
/**
* @brief Retreive the hash table : useful when iterating over it
* @return Return a pointer to the global hash table
*/
hash_t* aspect_vecthash_get()
{
return (vector_hash);
}
/**
* @brief Project each dimension and write the desired function pointer
* @param vect Vector in which handlers are to be inserted
* @param dim Dimension arrays where handler is to be inserted
* @param fct Handler to be inserted (casted to unsigned long)
*/
void aspect_vectors_insert(vector_t *vect,
unsigned int *dim,
unsigned long fct)
{
unsigned long *tmp;
unsigned int idx;
unsigned int dimsz;
dimsz = vect->arraysz;
tmp = (unsigned long *) vect->hook;
for (idx = 0; idx < dimsz; idx++)
{
tmp += dim[idx];
if (idx + 1 < dimsz)
tmp = (unsigned long *) *tmp;
}
*tmp = (unsigned long) fct;
}
/**
* @brief Project each dimension and get the requested function pointer
* @param vect Vector to be looked up
* @param dim DImension arrays where handler is to be selected
* @return Return Function pointer for selected handler
*/
void* aspect_vectors_select(vector_t *vect, unsigned int *dim)
{
unsigned long *tmp;
unsigned int idx;
unsigned int dimsz;
tmp = (unsigned long *) vect->hook;
dimsz = vect->arraysz;
for (idx = 0; idx < dimsz; idx++)
{
tmp += dim[idx];
tmp = (unsigned long *) *tmp;
}
return (tmp);
}
/**
* @brief Project each dimension and get the requested vector element pointer
* @param vect Vector to be looked up
* @param dim Dimension arrays for vector element
* @return The element of the vector containing the requested handler
*/
void *aspect_vectors_selectptr(vector_t * vect,
unsigned int *dim)
{
unsigned long *tmp;
unsigned int idx;
unsigned int dimsz;
tmp = (unsigned long *) vect->hook;
dimsz = vect->arraysz;
for (idx = 0; idx < dimsz; idx++)
{
tmp += dim[idx];
if (idx + 1 < dimsz)
tmp = (unsigned long *) *tmp;
}
return (tmp);
}
/**
* @brief Allocate recursively the hook array for a vector (internal function)
* @param tab Vector hook array to be allocated
* @param dims Vector dimensions array
* @param depth Vector depth remaining to be allocated
* @param dimsz Number of dimensions in vector
* return 0 in success or -1 if error
*/
static int aspect_vectors_recalloc(unsigned long *tab,
unsigned int *dims,
unsigned int depth,
unsigned int dimsz)
{
unsigned int idx;
void *ptr;
//PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
//printf("Calling recalloc with depth = %u and dimsz = %u\n",
//depth, dimsz);
if (depth == dimsz)
return (0);
//PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
for (idx = 0; idx < dims[depth - 1]; idx++)
{
//XALLOC(__FILE__, __FUNCTION__, __LINE__,
//ptr, dims[depth] * sizeof(unsigned long), -1);
ptr = calloc(dims[depth] * sizeof(unsigned long), 1);
if (!ptr)
return (-1);
tab[idx] = (unsigned long) ptr;
aspect_vectors_recalloc((unsigned long *) tab[idx],
dims, depth + 1, dimsz);
}
//printf("GETTING OUT OF recalloc with depth = %u and dimentnbr = %u\n",
// depth, dimsz);
return (0);
//PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Initialize recursively the hook array in a vector (internal function)
* @param tab Vector hopl array to be initialized
* @param dims Dimension array for vector
* @param depth Vector depth remaining to be initialized
* @param dimsz Number of dimensions for vector
* @param defaultelem Default element for vector
* @return Always 0
*/
static int aspect_vectors_recinit(unsigned long *tab,
unsigned int *dims,
unsigned int depth,
unsigned int dimsz,
void *defaultelem)
{
unsigned int idx;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
/* Check if we reached a leaf, otherwise recurse more */
if (depth == dimsz)
{
for (idx = 0; idx < dims[depth - 1]; idx++)
tab[idx] = (unsigned long) defaultelem;
}
else
for (idx = 0; idx < dims[depth - 1]; idx++)
aspect_vectors_recinit((unsigned long *) tab[idx], dims,
depth + 1, dimsz, defaultelem);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Register a new vector. A vector is an multidimentional array of hooks
* @param name Vector name to be registered
* @param defaultfunc Default handler for initializing all vector elements
* @param dimensions Dimension arrays for the vector
* @param strdims Dimension arrays for dimension description (to be printed)
* @param dimsz Number of dimensions
* @param vectype Type of elements inside this new vector
* @return 0 on success and -1 on error
*/
int aspect_register_vector(char *name,
void *defaultfunc,
unsigned int *dimensions,
char **strdims,
unsigned int dimsz,
unsigned int vectype)
{
vector_t *vector;
unsigned long *ptr;
void *mem;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!defaultfunc || !dimsz || !dimensions)
{
(void) write(1, "Invalid NULL parameters\n", 24);
return (-1);
}
if (vectype >= aspect_type_nbr)
{
(void) write(1, "Invalid vector element type\n", 28);
return (-1);
}
XALLOC(__FILE__, __FUNCTION__, __LINE__, mem, sizeof(vector_t), -1);
vector = (vector_t *) mem;
XALLOC(__FILE__, __FUNCTION__, __LINE__, mem,
dimensions[0] * sizeof(unsigned long), -1);
ptr = (unsigned long *) mem;
vector->hook = ptr;
if (dimsz > 1)
aspect_vectors_recalloc((unsigned long *) vector->hook,
dimensions, 1, dimsz);
vector->arraysz = dimsz;
vector->arraydims = dimensions;
vector->strdims = strdims;
vector->default_func = defaultfunc;
hash_add(vector_hash, name, vector);
/* Initialize vectored elements */
aspect_vectors_recinit((unsigned long *) vector->hook,
dimensions, 1, dimsz, defaultfunc);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, (0));
}
<file_sep>/src/libaspect/include/libaspect.h
/**
* @file libaspect/include/libaspect.h
**
** @brief The header file for modular objects in the framework
**
** Started Dec 22 2006 02:57:03 jfv
**
**
** $Id: libaspect.h 1443 2011-01-14 06:37:39Z may $
**
*/
#if !defined(__ASPECT_H__)
#define __ASPECT_H__ 1
#ifndef __KERNEL__
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <strings.h>
#include <stdint.h>
#include <assert.h>
/* Debug flags */
#define __DEBUG_LIST__ 1
#ifdef __BEOS__
#include <image.h>
#include <bsd_mem.h>
#else
#if !defined(__USE_GNU)
#define __USE_GNU
#endif
#include <dlfcn.h>
#endif
#endif /* __KERNEL__ */
/* Endianess definitions */
#if defined(__linux__) || defined (__BEOS__)
#ifndef __KERNEL__
#include <endian.h>
#else
#define __LITTLE_ENDIAN 1234
#define __BIG_ENDIAN 4321
#define __PDP_ENDIAN 3412
#endif
#elif defined(__FreeBSD__) || defined (__OpenBSD__) || defined(__NetBSD__)
#include <machine/endian.h>
#define __LITTLE_ENDIAN _LITTLE_ENDIAN
#define __BIG_ENDIAN _BIG_ENDIAN
#if defined(__FreeBSD__)
#include <elf.h>
#include <sys/elf_common.h>
#define __WORDSIZE __ELF_WORD_SIZE
#endif
#if __FreeBSD__ < 5
#define __BYTE_ORDER __LITTLE_ENDIAN
#else
#define __BYTE_ORDER BYTE_ORDER
#endif
#elif defined(sun)
#define __LITTLE_ENDIAN 1234
#define __BIG_ENDIAN 4321
#if !defined(__i386)
#define __BYTE_ORDER __BIG_ENDIAN
#else
#define __BYTE_ORDER __LITTLE_ENDIAN
#endif
#elif defined(HPUX)
#include <arpa/nameser_compat.h>
#undef ADD
#define __LITTLE_ENDIAN LITTLE_ENDIAN
#define __BIG_ENDIAN BIG_ENDIAN
#define __BYTE_ORDER BYTE_ORDER
#elif defined(IRIX)
#include <standards.h>
#include <sys/endian.h>
#define __LITTLE_ENDIAN LITTLE_ENDIAN
#define __BIG_ENDIAN BIG_ENDIAN
#define __BYTE_ORDER BIG_ENDIAN
#endif
#ifndef __RELEASE__
#define ASSERT(_x) assert(_x)
#define NOT_REACHED() ASSERT(FALSE)
#else
#define ASSERT(_x)
#define NOT_REACHED()
#endif
#define NOT_USED(_x) _x = _x
#ifndef swap32
#define swap32(x) \
((uint32_t)( \
(((uint32_t)(x) & (uint32_t) 0x000000ffU) << 24) | \
(((uint32_t)(x) & (uint32_t) 0x0000ff00U) << 8) | \
(((uint32_t)(x) & (uint32_t) 0x00ff0000U) >> 8) | \
(((uint32_t)(x) & (uint32_t) 0xff000000U) >> 24) ))
#endif
#ifndef swap16
#define swap16(x) \
((unsigned short)( \
(((unsigned short)(x) & (unsigned short) 0x00ffU) << 8) | \
(((unsigned short)(x) & (unsigned short) 0xff00U) >> 8) ))
#endif
#ifndef swap64
#define swap64(x) \
((uint64_t)( \
((uint64_t)(((uint64_t)x) & (uint64_t) 0x00000000000000ffULL) << 56) | \
((uint64_t)(((uint64_t)x) & (uint64_t) 0x000000000000ff00ULL) << 40) | \
((uint64_t)(((uint64_t)x) & (uint64_t) 0x0000000000ff0000ULL) << 24) | \
((uint64_t)(((uint64_t)x) & (uint64_t) 0x00000000ff000000ULL) << 8) | \
((uint64_t)(((uint64_t)x) & (uint64_t) 0x000000ff00000000ULL) >> 8) | \
((uint64_t)(((uint64_t)x) & (uint64_t) 0x0000ff0000000000ULL) >> 24) | \
((uint64_t)(((uint64_t)x) & (uint64_t) 0x00ff000000000000ULL) >> 40) | \
((uint64_t)(((uint64_t)x) & (uint64_t) 0xff00000000000000ULL) >> 56)))
#endif
/* The size of an address depends on if we analyse 32bits or 64bits objects */
#if defined(ERESI32)
typedef uint32_t eresi_Addr;
typedef uint32_t eresi_Off;
#define XFMT "0x%08X"
#define AFMT "%08X"
#define UFMT "%08u"
#define DFMT "%08d"
#define RDFMT "%d"
#define RXFMT "0x%X"
#elif defined(ERESI64)
typedef uint64_t eresi_Addr;
typedef uint64_t eresi_Off;
#if __WORDSIZE == 32
#define XFMT "0x%016llX"
#define AFMT "%016llX"
#define UFMT "%016llu"
#define DFMT "%016lld"
#define RDFMT "%lld"
#define RXFMT "0x%llX"
#elif __WORDSIZE == 64
#define XFMT "0x%016lX"
#define AFMT "%016lX"
#define UFMT "%016lu"
#define DFMT "%016ld"
#define RDFMT "%ld"
#define RXFMT "0x%lX"
#else
#error "__WORDSIZE not defined"
#endif
#else
#error "You must define either ERESI32 or ERESI64 built"
#endif
/* Define Boolean types */
typedef uint8_t Bool;
#define TRUE 1
#define FALSE 0
/* Typedef the registers, linear addresses, virtual, etc for better
understanding. */
typedef uint32_t ureg32;
typedef uint64_t ureg64;
typedef uint32_t la32;
typedef uint64_t la64;
typedef uint32_t va32;
typedef uint64_t va64;
/* Include this here since it contains an allocation too */
#ifndef __KERNEL__
#include "aproxy.h"
#endif
#include "libaspect-hash.h"
#include "libaspect-list.h"
#include "libaspect-btree.h"
#include "libaspect-profiler.h"
/* Those types are built-in */
#define ASPECT_TYPE_UNKNOW 0 /*!< Unknown */
#define ASPECT_TYPE_RAW 1 /*!< Raw */
#define ASPECT_TYPE_BYTE 2 /*!< Byte */
#define ASPECT_TYPE_STR 3 /*!< String */
#define ASPECT_TYPE_SHORT 4 /*!< 2 bytes */
#define ASPECT_TYPE_INT 5 /*!< 4 bytes */
#define ASPECT_TYPE_LONG 6 /*!< 4 or 8 bytes */
#define ASPECT_TYPE_DADDR 7 /*!< 4 or 8 bytes */
#define ASPECT_TYPE_CADDR 8 /*!< 4 or 8 bytes */
#define ASPECT_TYPE_BIT 9 /*!< just 1 bit */
#define ASPECT_TYPE_OID 10 /*!< object identifier */
#define ASPECT_TYPE_CORENUM 11 /*!< Core types number */
/* Vectors, tables and hash are parts of "simple types"
Note: you cannot copy them or look inside them without foreach */
#define ASPECT_TYPE_VECT ASPECT_TYPE_CORENUM /*!< Vector type */
#define ASPECT_TYPE_HASH (ASPECT_TYPE_CORENUM + 1) /*!< Hash table type */
#define ASPECT_TYPE_LIST (ASPECT_TYPE_CORENUM + 2) /*!< List type */
#define ASPECT_TYPE_SIMPLENUM (ASPECT_TYPE_CORENUM + 3) /*!< SIMPLE TYPES NUMBER */
/* Now come complex types which are part of the base types */
#define ASPECT_TYPE_EXPR ASPECT_TYPE_SIMPLENUM /*!< Expression type */
#define ASPECT_TYPE_BLOC (ASPECT_TYPE_SIMPLENUM + 1) /*!< Block type */
#define ASPECT_TYPE_FUNC (ASPECT_TYPE_SIMPLENUM + 2) /*!< Function type */
#define ASPECT_TYPE_LINK (ASPECT_TYPE_SIMPLENUM + 3)
#define ASPECT_TYPE_BASENUM (ASPECT_TYPE_SIMPLENUM + 4) /*!< BASE TYPES NUMBER */
/* Type names */
#define ASPECT_TYPENAME_UNKNOW "unknown"
#define ASPECT_TYPENAME_RAW "raw"
#define ASPECT_TYPENAME_BYTE "byte"
#define ASPECT_TYPENAME_BIT "bit"
#define ASPECT_TYPENAME_STR "string"
#define ASPECT_TYPENAME_SHORT "short"
#define ASPECT_TYPENAME_INT "int"
#define ASPECT_TYPENAME_LONG "long"
#define ASPECT_TYPENAME_DADDR "daddr"
#define ASPECT_TYPENAME_CADDR "caddr"
#define ASPECT_TYPENAME_OID "oid"
#define ASPECT_TYPENAME_VECT "vector"
#define ASPECT_TYPENAME_HASH "hash"
#define ASPECT_TYPENAME_LIST "list"
#define ASPECT_TYPENAME_EXPR "expr"
#define ASPECT_TYPENAME_BLOC "bloc"
#define ASPECT_TYPENAME_FUNC "func"
#define ASPECT_TYPENAME_LINK "link"
/* Max pointer depth for a compound type */
#define ASPECT_TYPE_MAXPTRDEPTH 1
/* Some general purpose macros */
#define IS_VADDR(s) (s[0] == '0' && (s[1] == 'X' || s[1] == 'x'))
#define PRINTABLE(c) (c >= 32 && c <= 126)
#define LOWORD(_dw) ((_dw) & 0xffff)
#define HIWORD(_dw) (((_dw) >> 16) & 0xffff)
#define LOBYTE(_w) ((_w) & 0xff)
#define HIBYTE(_w) (((_w) >> 8) & 0xff)
#define HIDWORD(_qw) ((uint32)((_qw) >> 32))
#define LODWORD(_qw) ((uint32)(_qw))
#define QWORD(_hi, _lo) ((((uint64)(_hi)) << 32) | ((uint32)(_lo)))
#define BYTE_IN_CHAR 2
#define WORD_IN_BYTE 2
#define DWORD_IN_BYTE 4
#define QWORD_IN_BYTE 8
#define BYTE_IN_BIT 8
#define WORD_IN_BIT 16
#define DWORD_IN_BIT 32
#define QWORD_IN_BIT 64
#define NEXT_CHAR(_x) _x + 1
/* A structure for the type information */
typedef struct s_info
{
char *name;
u_int size;
} typeinfo_t;
/**
* @brief Structure for type
*/
typedef struct s_type
{
u_int type; /*!< @brief Plain or pointed type */
u_char isptr; /*!< @brief the type is a pointer */
u_int size; /*!< @brief Type full memsize */
u_int off; /*!< @brief Offset inside parent */
u_int dimnbr; /*!< @brief Nbr of array dimensions */
u_int *elemnbr; /*!< @brief Nbr of elements per dim */
char *name; /*!< @brief Type name */
char *fieldname; /*!< @brief Field name */
/* We have a list of child, and a list
** of nexts in case we are ourselves
** a child of a structure object */
struct s_type *childs; /*!< @brief Curobj fields if any */
struct s_type *next; /*!< @brief Next parent field */
} aspectype_t;
/**
* @brief The structure of multidimensional vectors
*/
typedef struct s_vector
{
void *hook; /*!< @brief The vector data */
void *register_func; /*!< @brief Registration function */
void *default_func; /*!< @brief Default registered function */
u_int *arraydims; /*!< @brief Size of each dimension */
char **strdims; /*!< @brief Label for each dimension */
u_int arraysz; /*!< @brief Number of dimensions */
u_int type; /*!< @brief Elements type in this vector */
} vector_t;
/**
* @brief Structure to define a generic container
*/
typedef struct s_container
{
unsigned int id; /* !< @brief unique id of this container */
u_int type; /* !< @brief Contained object type */
u_int nbrinlinks; /* !< @brief Number of -ondisk- input links */
u_int nbroutlinks; /* !< @brief Number of -ondisk- output links */
list_t *inlinks; /* !< @brief Input links for this container */
list_t *outlinks; /* !< @brief Output links for this container */
void *data; /* !< @brief Pointer to the contained object */
} container_t;
/**
* @brief Input and Output links for containers
*/
#define CONTAINER_LINK_IN 0
#define CONTAINER_LINK_OUT 1
/**
* @brief Config related data types
*/
#define CONFIG_HASH_SIZE 256
/**
* @brief Default names for config names
*/
#define CONFIG_NAME_SAFEMODE "safemode"
#define CONFIG_USE_ASMDEBUG "asm.debug"
#define CONFIG_CFGDEPTH "mjr.cfg_depth"
/**
* @brief Config flags
*/
#define CONFIG_SAFEMODE_OFF 0
#define CONFIG_SAFEMODE_ON 1
#define CONFIG_CFGDEPTH_DEFAULT 1
/**
* @brief libasm related config
*/
#define CONFIG_ASM_ENDIAN_FLAG "libasm.endian.flag"
#define CONFIG_ASM_LITTLE_ENDIAN 0
#define CONFIG_ASM_BIG_ENDIAN 1
#define CONFIG_ASM_ATT_MARGIN_DEFAULT 14
#define CONFIG_ASM_ATT_MARGIN_FLAG "libasm.output.att.margin"
#define CONFIG_ASM_SYNTHINSTRS_DEFAULT 1
#define CONFIG_ASM_SYNTHINSTRS "libasm.output.synth.instrs"
/* A configuration item */
typedef struct s_config_item
{
char *name;
#define CONFIG_TYPE_INT 0
#define CONFIG_TYPE_STR 1
u_int type; /*!< int will use val, str *data */
/* RO/RW - it's relevant to higher api
like revm_ allows direct updates to those values
when RW is set and enforces usage of revm_api
when RO is set (see profile) */
u_int val; /*!< For int values 0-off/1-on ... */
#define CONFIG_MODE_RW 0
#define CONFIG_MODE_RO 1
u_int mode;
void *data;
} configitem_t;
/**
* The library has its world itself
* There stands all the flags that are used by libelfsh
*/
typedef struct s_aspectworld
{
hash_t config_hash; /*!< Configuration */
u_char kernel_mode; /*!< Kernel residence */
#define PROFILE_NONE 0
#define PROFILE_WARN (1 << 0)
#define PROFILE_FUNCS (1 << 1)
#define PROFILE_ALLOC (1 << 2)
#define PROFILE_DEBUG (1 << 3)
u_char proflevel; /*!< Profiling switch */
u_char profstarted; /*!< Profiling started ? */
int (*profile)(char *); /*!< Profiling output func */
int (*profile_err)(char *); /*!< Profiling error func */
/* Libui pointers */
void (*endline)();
/* Simple */
char *(*colorinstr)(char *text);
char *(*colorstr)(char *t);
char *(*colorfieldstr)(char *t);
char *(*colortypestr)(char *t);
char *(*colorend)(char *text);
char *(*colorwarn)(char *text);
char *(*colorfunction)(char *text);
char *(*colorfilename)(char *text);
/* Advanced */
char *(*coloradv)(char *ty, char *p, char *te);
char *(*colorinstr_fmt)(char* p, char *t);
char *(*coloraddress)(char *p, eresi_Addr a);
char *(*colornumber)(char *p, eresi_Off n);
char *(*colorstr_fmt)(char *p, char *t);
char *(*colorfieldstr_fmt)(char *p, char *t);
char *(*colortypestr_fmt)(char *p, char *t);
char *(*colorwarn_fmt)(char *pattern, char *text);
} aspectworld_t;
/* Make it accessible from all files */
extern aspectworld_t aspectworld;
/* Low-level constructor-time related functions */
int aspect_init();
void aspect_called_ctors_inc();
int aspect_called_ctors_finished();
int kernsh_is_present();
void kernsh_present_set();
void kedbg_present_set();
int kedbg_is_present();
void e2dbg_presence_set();
void e2dbg_presence_reset();
u_char e2dbg_presence_get();
u_char e2dbg_kpresence_get();
void e2dbg_kpresence_set(u_char pres);
/* Retreive pointer on the vector hash table */
hash_t* aspect_vecthash_get();
/* Retreive a vector from the vectors hash table */
vector_t* aspect_vector_get(char *name);
/* Add the function pointer to the hook at requested coordonates */
void aspect_vectors_insert(vector_t *vect,
unsigned int *dim,
unsigned long fct);
/* Get the hook from the dimension array */
void* aspect_vectors_select(vector_t *vect,
unsigned int *dim);
/* Project each dimension and get the requested data pointer */
void *aspect_vectors_selectptr(vector_t *vect,
unsigned int *dim);
/* Add a new vector */
int aspect_register_vector(char *, void*,
unsigned int*,
char **, unsigned int,
unsigned int);
/* Container related functions */
container_t *container_create(u_int type,
void *data,
list_t *in,
list_t *out,
u_int uniqid);
int container_linklists_create(container_t *container,
u_int linktype,
u_int uniqid);
/* Type related functions */
int aspect_type_simple(int typeid);
char *aspect_type_get(u_int type);
u_int aspect_typesize_get(u_int type);
int aspect_basetypes_create();
int aspect_type_find_union_size(aspectype_t *type);
int aspect_type_register_real(char *label,
aspectype_t *ntype);
aspectype_t *aspect_type_create(u_char isunion,
char *label,
char **fields,
u_int fieldnbr);
int aspect_type_register(u_char isunion,
char *label,
char **fields,
u_int fieldnbr);
aspectype_t *aspect_type_copy(aspectype_t *type,
unsigned int off,
u_char isptr,
u_int elemnbr,
char *fieldname,
u_int *dims);
aspectype_t *aspect_type_copy_by_name(aspectype_t *type, char *name, hash_t *fields, u_int, u_int);
int aspect_basetype_register(char *name, u_int size);
typeinfo_t *aspect_basetype_get(unsigned int *nbr);
aspectype_t *aspect_type_get_by_name(char *name);
aspectype_t *aspect_type_get_by_id(unsigned int id);
aspectype_t *aspect_type_get_child(aspectype_t *parent, char *name);
char *aspect_typename_get(u_int typeid);
/* profile.c : Profiler related functions */
void profiler_reset(u_int sel);
int profiler_print(char *file, char *func,
u_int line, char *msg);
void profiler_err(char *file, char *func,
u_int line, char *msg);
void profiler_out(char *file, char *func, u_int line);
void profiler_error();
void profiler_incdepth();
void profiler_decdepth();
void profiler_updir();
int profiler_enabled();
int profiler_is_enabled(u_char mask);
u_char profiler_started();
void profiler_error_reset();
int profiler_enable_err();
int profiler_enable_out();
int profiler_enable_alloc();
int profiler_enable_debug();
int profiler_disable_err();
int profiler_disable_out();
int profiler_disable_alloc();
int profiler_disable_debug();
int profiler_disable_all();
int profiler_enable_all();
void profiler_install(int (*profile)(char *),
int (*profile_err)(char *));
/* The allocation profiler */
void profiler_alloc_warnprint(char *s, int fat, int i);
void profiler_alloc_warning(u_char warntype);
void profile_alloc_shift();
int profiler_alloc_update(char *file, char *func,
u_int line, u_long addr,
u_char atype, u_char otype);
profallocentry_t *profiler_alloc_find(u_char direction,
u_long addr,
u_char optype);
/* Color related handlers for the profiler */
void profiler_setcolor(void (*endline)(),
char *(*colorinstr)(char *text),
char *(*colorstr)(char *t),
char *(*colorfieldstr)(char *t),
char *(*colortypestr)(char *t),
char *(*colorend)(char *text),
char *(*colorwarn)(char *text),
char *(*colorfunction)(char *text),
char *(*colorfilename)(char *text));
void profiler_setmorecolor(char *(*coloradv)(char *ty,
char *p,
char *te),
char *(*colorinstr_fmt)(char* p,
char *t),
char *(*coloraddress)(char *p,
eresi_Addr a),
char *(*colornumber)(char *p,
eresi_Off n),
char *(*colorstr_fmt)(char *p,
char *t),
char *(*colorfieldstr_fmt)(char *p,
char *t),
char *(*colortypestr_fmt)(char *p,
char *t),
char *(*colorwarn_fmt)(char *pat,
char *text));
/* config.c : Configuration related fonctions */
void config_init();
void config_add_item(char *name, u_int type,
u_int mode, void *dat);
void config_update_key(char *name, void *data);
void *config_get_data(char *name);
void config_safemode_set();
void config_safemode_reset();
int config_safemode();
#endif
<file_sep>/src/libasm/src/arch/ia32/handlers/op_mov_ref_iv_al.c
/**
* @file libasm/src/arch/ia32/handlers/op_mov_ref_iv_al.c
*
* @ingroup IA32_instrs
* $Id: op_mov_ref_iv_al.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
*
* <instruction func="op_mov_ref_iv_al" opcode="0xa2"/>
*/
int op_mov_ref_iv_al(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->instr = ASM_MOV;
new->type = ASM_TYPE_ASSIGN;
new->ptr_instr = opcode;
new->len += 1;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_OFFSET, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_OFFSET, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_AL,
ASM_REGSET_R8));
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_FIXED, new);
#endif
new->op[1].type = ASM_OTYPE_FIXED;
new->op[1].regset = ASM_REGSET_R8;
new->op[1].content = ASM_OP_BASE;
new->op[1].baser = ASM_REG_AL;
return (new->len);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_fbfcc.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_fbfcc.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_fbfcc.c 1413 2010-05-21 03:41:25Z figueredo $
**
*/
#include "libasm.h"
int
asm_sparc_fbfcc(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_branch opcode;
struct s_asm_proc_sparc *inter;
sparc_convert_branch(&opcode, buf);
inter = proc->internals;
ins->instr = inter->fbcc_table[opcode.cond];
if (ins->instr == ASM_SP_FBA)
ins->type = ASM_TYPE_BRANCH;
else if (ins->instr == ASM_SP_FBN)
ins->type = ASM_TYPE_NOP;
else
ins->type = ASM_TYPE_BRANCH | ASM_TYPE_CONDCONTROL;
ins->nb_op = 1;
ins->op[0].imm = opcode.imm;
ins->annul = opcode.a;
ins->prediction = 1;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_DISPLACEMENT, ins);
return 4;
}
<file_sep>/src/libasm/src/error.c
/**
* @file libasm/src/error.c
* @ingroup libasm
**
** $Id: error.c 1397 2009-09-13 02:19:08Z may $
**
** Author : <<EMAIL>>
** Started : Sun Nov 30 19:58:38 2003
** Updated : Thu Dec 4 01:18:48 2003
*/
#include <libasm.h>
/**
* Set error
* @param ins Pointer to instruction structure.
* @param err Error number
* @param msg Error message
*/
void asm_set_error(asm_instr *ins, int err, char *msg)
{
if (ins && ins->proc)
ins->proc->error_code = err;
}
/**
* Set error message.
* This is currently not implemented.
* @param ins Pointer to instruction structure
* @param msg Error message
*/
void asm_set_errormsg(asm_instr *ins, char *msg)
{
}
/**
* Return error code.
* @param ins Pointer to instruction structure.
* @return Return error code.
*/
int asm_get_error(asm_instr *ins)
{
return (0);
}
/**
* Return error message.
* @param ins Pointer to instruction structure.
* @return Return a pointer to a static string containing error message.
*/
const char *asm_get_errormsg(asm_processor *proc)
{
if (proc)
{
switch(proc->error_code)
{
case LIBASM_ERROR_SUCCESS: return (LIBASM_MSG_SUCCESS);
case LIBASM_ERROR_NSUCH_CONTENT: return (LIBASM_MSG_SUCCESS);
case LIBASM_ERROR_ILLEGAL: return (LIBASM_MSG_SUCCESS);
case LIBASM_ERROR_TOOSHORT: return (LIBASM_MSG_TOOSHORT);
}
return (LIBASM_MSG_ERRORNOTIMPLEMENTED);
}
else
return ("asm_get_errormsg: proc is NULL");
}
<file_sep>/src/libaspect/libhash.c
/**
* @file libaspect/libhash.c
* @ingroup libaspect
*
* @brief Contain ELFsh internal hashtables library calls.
*
* Started on Fri Jan 24 20:26:18 2003 jfv
* $Id: libhash.c 1443 2011-01-14 06:37:39Z may $
*/
#include "libaspect.h"
/* Hash tables of hash tables */
hash_t *hash_hash = NULL;
/**
* @brief Initialize the hash table
* @param h Pointer to the hash to initialize
* @param name Name of the hash.
* @param size Size to document
* @param type Type to document
* @param Returns 0 on success, -1 on error or 1 if hash already exists.
*/
int hash_init(hash_t *h, char *name, int size, u_int type)
{
NOPROFILER_IN();
/* First checks */
/* Initialize the global hash table of lists and
the global hash table of hash tables */
if (!hash_hash)
{
hash_hash = (hash_t *) calloc(sizeof(hash_t), 1);
hash_init(hash_hash, "hashes", 51, ASPECT_TYPE_UNKNOW);
}
if (type >= aspect_type_nbr)
{
fprintf(stderr, "Unable to initialize hash table %s \n", name);
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Unable to initialize hash table", -1);
}
if (h != hash_hash && hash_find(name) && h->ent)
{
//#if __DEBUG__
fprintf(stderr, "Hash table already exists and initialized\n");
//#endif
NOPROFILER_ROUT(1);
}
/* Add a new element */
XALLOC(__FILE__, __FUNCTION__, __LINE__,
h->ent, size * sizeof(listent_t), -1);
h->size = size;
h->type = type;
h->elmnbr = 0;
h->linearity = 0;
h->name = name;
hash_add(hash_hash, name, h);
if (!hash_lists)
{
hash_lists = (hash_t *) calloc(sizeof(hash_t), 1);
hash_init(hash_lists, "lists", 51, ASPECT_TYPE_UNKNOW);
}
NOPROFILER_ROUT(0);
}
/**
* @brief Return a hash table by its name
* @param name Name of the hash to retrieve.
* @return A pointer to a hash_t structure or NULL on error.
*/
hash_t *hash_find(char *name)
{
if (!name)
return (NULL);
return ((hash_t *) hash_get(hash_hash, name));
}
/**
* Return a hash table pointer by its name.
* Overwrite existing table if there was one sharing that name, only
* if both tables have the same elements type
* @param table
* @param name
* @return
*/
int hash_register(hash_t *table, char *name)
{
hash_t *h;
int sz;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
h = hash_get(hash_hash, name);
if (h)
{
if (h->type == ASPECT_TYPE_UNKNOW)
h->type = table->type;
if (h->type != table->type)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Incompatible hash tables", -1);
if (h->elmnbr)
h = hash_empty(name);
hash_merge(h, table);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
XALLOC(__FILE__, __FUNCTION__, __LINE__, h, sizeof(hash_t), -1);
sz = (table->size > table->elmnbr ? table->size : table->elmnbr);
hash_init(h, name, sz, table->type);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Empty a hash table
* @param name Name of the ash table to empty.
* @param returrn a pointer to the hash table or NULL on error.
*/
hash_t *hash_empty(char *name)
{
hash_t *hash;
char *newname;
int size;
char type;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
hash = hash_find(name);
if (!hash)
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, NULL);
//printf("EMPTY HASH %s \n", name);
size = hash->size;
type = hash->type;
hash_del(hash_hash, name);
hash_destroy(hash);
XALLOC(__FILE__, __FUNCTION__, __LINE__,
newname, strlen(name) + 1, NULL);
strncpy(newname, name, strlen(name));
hash_init(hash, newname, size, type);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, hash);
}
/**
* Destroy a hash table.
* @param hash Pointer to the hash to destroy
*/
void hash_destroy(hash_t *hash)
{
char **keys;
int idx;
int keynbr;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
//printf("DESTROY HASH %s \n", hash->name);
/* We should not destroy the elements as they might be in other hashes */
keys = hash_get_keys(hash, &keynbr);
for (idx = 0; idx < keynbr; idx++)
if (keys[idx])
XFREE(__FILE__, __FUNCTION__, __LINE__, keys[idx]);
if (keys)
hash_free_keys(keys);
hash_del(hash_hash, hash->name);
XFREE(__FILE__, __FUNCTION__, __LINE__, hash->ent);
PROFILER_OUT(__FILE__, __FUNCTION__, __LINE__);
}
/**
* @brief Add an entry to the hash table.
* @param h Hash table.
* @param key Key of the new entry.
* @param data Value associated with the key.
* @return Returns an index (to document)
*/
int hash_add(hash_t *h, char *key, void *data)
{
listent_t *actual;
listent_t *newent;
char *backup;
u_int index;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
//Weaken the check : do not hash_get(h, key) check and do not check !data
if (!h || !key) {
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid NULL parameters", -1);
}
/* If the element already exist, make sure we erase the existing one */
actual = hash_get(h, key);
if (actual)
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__,
hash_set(h, key, data));
newent = NULL;
for (index = 0, backup = key; *backup; backup++)
index += *backup;
index %= h->size;
if (h->ent[index].key == NULL)
{
h->ent[index].key = key;
h->ent[index].data = data;
}
else
{
XALLOC(__FILE__, __FUNCTION__, __LINE__,
newent, sizeof(listent_t), -1);
newent->key = key;
newent->data = data;
actual = h->ent + index;
while (actual->next)
actual = actual->next;
actual->next = newent;
}
h->elmnbr++;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, index);
}
/**
* @brief Delete an entry from the hash table.
* @param
*/
int hash_del(hash_t *h, char *key)
{
listent_t *actual;
listent_t *todel;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
/* Check the first entry for this hash */
actual = hash_get_head(h, key);
if (actual->key != NULL && !strcmp(actual->key, key))
{
if (actual->next)
{
todel = actual->next;
*actual = *actual->next;
XFREE(__FILE__, __FUNCTION__, __LINE__, todel);
}
else
bzero(actual, sizeof (listent_t));
h->elmnbr--;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/* Looking for the good entry in the list for this hash value */
while (actual->next != NULL &&
actual->next->key != NULL &&
strcmp(actual->next->key,
key))
actual = actual->next;
/* Not found */
if (!actual->next)
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, -1);
/* Found */
todel = actual->next;
actual->next = actual->next->next;
XFREE(__FILE__, __FUNCTION__, __LINE__, todel);
h->elmnbr--;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Retrieve the metadata for a given key
*
* @param h
* @param key
*/
void *hash_get(hash_t *h, char *key)
{
listent_t *actual;
actual = hash_get_head(h, key);
while (actual != NULL &&
actual->key != NULL &&
strcmp(actual->key,
key))
actual = actual->next;
return (actual != NULL ? actual->data : NULL);
}
/**
* Retrieve the data pointer for a given key
*
* @param h
* @param key
*/
void *hash_select(hash_t *h, char *key)
{
listent_t *actual;
actual = hash_get_head(h, key);
while (actual != NULL &&
actual->key != NULL &&
strcmp(actual->key, key))
actual = actual->next;
return (actual != NULL ? &actual->data : NULL);
}
/**
* Change the metadata for an existing entry, giving its key
* @param h
* @param key
* @param data
* @return
*/
int hash_set(hash_t *h, char *key, void *data)
{
listent_t *ent;
ent = hash_get_ent(h, key);
if (!ent || (!ent->key && !ent->data))
return (hash_add(h, key, data));
ent->data = data;
return (0);
}
/**
* @brief Retrieve the -entry- for a given key
* @param h
* @param key
* @return
*/
listent_t *hash_get_ent(hash_t *h, char *key)
{
listent_t *actual;
actual = hash_get_head(h, key);
while (actual != NULL &&
actual->key != NULL &&
strcmp(actual->key, key))
actual = actual->next;
return (actual);
}
/**
* Retreive a Hash entry head giving the key *
* @param h
* @param backup
* @return
*/
listent_t *hash_get_head(hash_t *h, char *backup)
{
u_int index;
for (index = 0; *backup; backup++)
index += *backup;
return (&h->ent[index % h->size]);
}
/**
* @brief Used to create arrays of keys for completion
* @param h
* @param n
* @return
*/
char **hash_get_keys(hash_t *h, int *n)
{
char **keys;
listent_t *curelem;
int idx;
int last;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (!h || !h->elmnbr)
{
if (n)
*n = 0;
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Invalid NULL parameters", NULL);
}
XALLOC(__FILE__, __FUNCTION__, __LINE__, keys,
sizeof(char *) * (h->elmnbr + 1), NULL);
for (last = idx = 0; idx < h->size; idx++)
{
curelem = h->ent + idx;
while (curelem && curelem->key)
{
keys[last] = curelem->key;
curelem = curelem->next;
last++;
}
}
if (n)
*n = h->elmnbr;
keys[last] = NULL;
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, keys);
}
/**
* @brief Free the keys returned by hash_get_keys()
*/
void hash_free_keys(char **keys)
{
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
if (keys)
XFREE(__FILE__, __FUNCTION__, __LINE__, keys);
PROFILER_OUT(__FILE__, __FUNCTION__, __LINE__);
}
/**
* Print the hash table (DEBUG PURPOSE)
* @param h Hash table.
*/
void hash_print(hash_t *h)
{
listent_t *actual;
int index;
if (!h)
return;
puts(".::. Printing hash .::. ");
for (index = 0; index < h->size; index++)
{
for (actual = &h->ent[index];
actual != NULL && actual->key != NULL;
actual = actual->next)
printf(" ENT [%u] key = %s ; data = %p ; next = %p\n",
index, actual->key, actual->data, actual->next);
}
}
/**
* @brief Apply func all entries .
* @param h
* @param ptr
* @param func
* @return
*/
int hash_apply(hash_t *h,
void *ptr,
int (*func)(listent_t *ph, void *pptr))
{
listent_t *actual;
int index;
int ret = 0;
for (index = 0; index < h->size; index++)
{
for (actual = &h->ent[index];
actual != NULL && actual->key != NULL;
actual = actual->next)
ret |= func (actual, ptr);
}
return ret;
}
/* Compare 2 hash tables */
/* Contributed by zorgon */
/* Can be used to compare ELF in memory and ELF in file */
int hash_compare(hash_t *first, hash_t *two)
{
int index;
int m;
listent_t *actual;
listent_t *bis;
if (first->size != two->size)
return (-1);
for (m = index = 0; index < first->size; index++)
{
for (actual = first->ent + index;
actual != NULL && actual->key != NULL;
actual = actual->next)
{
bis = hash_get_ent(two, actual->key);
if (actual->data != bis->data)
{
printf("FIRST key = %s ; data = %p",
actual->key, actual->data);
printf("SECOND key = %s ; data = %p",
bis->key, bis->data);
m++;
}
}
}
if (m)
return (-1);
return (0);
}
/* Merge hash tables in the first one */
/* We cannot use hash_get_keys() because we dont know the type of hashed objects */
int hash_merge(hash_t *dst, hash_t *src)
{
listent_t *actual;
int index;
int ret;
/* Make sure we dont inject element already presents */
if (!src || !dst || src->elmnbr == 0)
return (0);
for (ret = index = 0; index < src->size; index++)
for (actual = &src->ent[index];
actual != NULL && actual->key != NULL;
actual = actual->next)
if (!hash_get(dst, actual->key))
ret += hash_add(dst, actual->key, actual->data);
return ret;
}
/* Intersect hash tables in the first one */
int hash_inter(hash_t *dst, hash_t *src)
{
char **keys;
int keynbr;
int idx;
char *curkey;
int ret;
if (!src || !dst || src->elmnbr == 0 || dst->elmnbr == 0)
return (0);
keys = hash_get_keys(dst, &keynbr);
for (ret = idx = 0; idx < keynbr; idx++)
{
curkey = keys[idx];
if (!hash_get(src, curkey))
ret += hash_del(dst, curkey);
}
return ret;
}
/* Delete all elements of source hash in destination hash */
/* We cannot use hash_get_keys() because we dont know the type of hashed objects */
int hash_unmerge(hash_t *dst, hash_t *src)
{
listent_t *actual;
int index;
int ret;
/* Make sure we dont inject element already presents */
if (!src || !dst || src->elmnbr == 0)
return (0);
for (ret = index = 0; index < src->size; index++)
for (actual = &src->ent[index];
actual != NULL && actual->key != NULL;
actual = actual->next)
if (hash_get(dst, actual->key))
ret += hash_del(dst, actual->key);
return ret;
}
/* Return the hash size */
int hash_size(hash_t *hash)
{
return (hash ? hash->elmnbr : 0);
}
/**
* @brief Return the only element of this hash .
* @param hash Hash table.
* @return NULL on error.
*/
void *hash_get_single(hash_t *hash)
{
char **keys;
int idx;
if (!hash || hash_size(hash) != 1)
return (NULL);
keys = hash_get_keys(hash, &idx);
return (hash_get(hash, keys[0]));
}
/**
* Return an element of this hash
* The choice is non-deterministic.
*
* @param hash
* @return
*/
void* hash_get_one(hash_t *hash)
{
char **keys;
int index;
if (!hash || !hash_size(hash))
return (NULL);
keys = hash_get_keys(hash, &index);
return (hash_get(hash, keys[0]));
}
/**
* Linear typing of list API.
* @param h Hash table.
*/
u_char hash_linearity_get(hash_t *h)
{
if (!h)
return (0);
return (h->linearity);
}
/**
* Linear typing of list API .
* @param h
* @param val
*/
void hash_linearity_set(hash_t *h, u_char val)
{
if (!h)
return;
h->linearity = val;
}
<file_sep>/src/libasm/src/arch/ia32/output_ia32.c
/**
* @file libasm/src/arch/ia32/output_ia32.c
* @ingroup ia32
** $Id: output_ia32.c 1397 2009-09-13 02:19:08Z may $
**
** Author : <sk at devhell dot org>
** Started : Xxx Xxx xx xx:xx:xx 2002
** Updated : Thu Mar 11 00:40:31 2004
*/
/*
Sat Jul 13 00:15:51 2002
removed a bug in scalar output.
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Default resolving handler for virtual address
*
*/
void asm_resolve_ia32(void *d, eresi_Addr val, char *buf, u_int len)
{
snprintf(buf, len, XFMT, val);
}
/**
* Instruction label handler.
* Return ia32 instruction label
*
*
*/
char *asm_get_instr_name(asm_instr *i)
{
return (i->proc->instr_table[i->instr]);
}
void output_instr(asm_instr *instr)
{
printf("%10s ", instr->proc->instr_table[instr->instr]);
if (instr->op[0].type)
{
switch(instr->op[0].content)
{
}
} /* !instr->op1 */
else
{
}
/*
printf("\t;; len: %5u ", instr->len);
if (instr->type & IS_MEM_WRITE)
printf("MW : Y ");
else
printf("MW : N ");
if (instr->type & IS_MEM_READ)
printf("MR : Y ");
else
printf("MR : N ");
if (instr->type & IS_CALL)
printf("CALL : Y ");
else
printf("CALL : N ");
if (instr->type & IS_JMP)
printf("JMP : Y ");
else
printf("JMP : N ");
if (instr->type & IS_COND_BRANCH)
printf("CONDBR : Y ");
else
printf("CONDBR : N ");
*/
puts("");
}
/**
* Return register ascii string
* @param r Register
* @param regset Register Set (32 bits registers, 16 bits, control ...)
*/
char *get_reg_intel(int r, int regset)
{
char *rsub[8] ={ "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh" };
char *r16[8] = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di" };
char *r32[8] = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi" };
char *rseg[8] = { "es", "cs", "ss", "ds", "fs", "gs", "#@!", "#@!" };
char *rmm[8] = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7"};
char *rxmm[8] = {"xmm0", "xmm1", "xmm2","xmm3", "xmm4", "xmm5","xmm6", "xmm7"};
char *rcr[8] = { "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7"};
char *rdr[8] = { "db0", "db1", "db2", "db3", "db4", "db5", "db6", "db7"};
char *rdefault[8] = {"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7"};
if (r >= 0 && r < 8)
switch(regset) {
case ASM_REGSET_R8:
return (rsub[r]);
case ASM_REGSET_R16:
return (r16[r]);
case ASM_REGSET_R32:
return (r32[r]);
case ASM_REGSET_XMM:
return (rxmm[r]);
case ASM_REGSET_CREG:
return (rcr[r]);
case ASM_REGSET_DREG:
return (rdr[r]);
case ASM_REGSET_MM:
return (rmm[r]);
case ASM_REGSET_SREG:
return (rseg[r]);
default:
return (rdefault[r]);
}
return ("\?\?\?");
}
/**
* Dump an operand output in att syntax to a buffer.
* @param instr Pointer to instruction structure
* @param num Number of operand to dump
* @param addr Virtual address of instruction
* @param bufptr Buffer to dump operand to
* @bug 2007-06-16 : Raise a segfault when used lonely
*/
void att_dump_operand(asm_instr *ins, int num, eresi_Addr addr, void *bufptr)
{
char resolved[256];
eresi_Addr addr_mask;
int baser;
int indexr;
int scale;
int imm;
asm_operand *op;
char *buffer;
/* Fetch some necessary info */
addr_mask = asm_proc_opsize(ins->proc) ? 0x000fffff : 0xffffffff;
op = 0;
buffer = bufptr;
baser = indexr = scale = imm = 0;
switch (num)
{
case 1:
op = &ins->op[0];
break;
case 2:
op = &ins->op[1];
break;
case 3:
op = &ins->op[2];
break;
}
asm_operand_get_immediate(ins, num, addr, &imm);
asm_operand_get_basereg(ins, num, addr, &baser);
asm_operand_get_indexreg(ins, num, addr, &indexr);
asm_operand_get_scale(ins, num, addr, &scale);
/* Resolve target addresses if any, dealing with real/protected mode addressing */
if (op->content & ASM_OP_ADDRESS)
{
if (op->content & ASM_OP_REFERENCE)
ins->proc->resolve_immediate(ins->proc->resolve_data, imm & addr_mask, resolved, 256);
else
{
addr = asm_dest_resolve(ins->proc, addr, imm + ins->len);
ins->proc->resolve_immediate(ins->proc->resolve_data, addr, resolved, 256);
}
}
else if (op->len == 1)
snprintf(resolved, sizeof(resolved), "0x%02X", (u_char) imm);
else
ins->proc->resolve_immediate(ins->proc->resolve_data, imm, resolved, 256);
/* Resolve any potential encoded information */
switch (op->content & ~ASM_OP_FIXED)
{
case ASM_OP_BASE|ASM_OP_ADDRESS:
sprintf(buffer, "*%%%s",
get_reg_intel(baser, op->regset));
break;
case ASM_OP_BASE:
sprintf(buffer, "%%%s",
get_reg_intel(baser, op->regset));
break;
case ASM_OP_VALUE:
sprintf(buffer, "$%s",
resolved);
break;
case ASM_OP_VALUE | ASM_OP_ADDRESS:
sprintf(buffer, "%s",
resolved);
break;
case ASM_OP_REFERENCE | ASM_OP_VALUE:
sprintf(buffer, "%s",
resolved);
break;
case ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_ADDRESS:
sprintf(buffer, "*%s",
resolved);
break;
case ASM_OP_REFERENCE | ASM_OP_BASE:
sprintf(buffer, "(%%%s)",
get_reg_intel(baser, op->regset));
break;
case ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_ADDRESS:
sprintf(buffer, "*(%%%s)",
get_reg_intel(baser, op->regset));
break;
case ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_BASE:
sprintf(buffer, "%s(%%%s)", resolved,
get_reg_intel(baser, op->regset));
break;
case ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_BASE | ASM_OP_ADDRESS:
sprintf(buffer, "*%s(%%%s)", resolved,
get_reg_intel(baser, op->regset));
break;
case
ASM_OP_REFERENCE | ASM_OP_ADDRESS | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE:
sprintf(buffer, "*(%%%s,%%%s,%d)",
get_reg_intel(baser, op->regset),
get_reg_intel(indexr, op->regset),
scale);
break;
case ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_SCALE:
sprintf(buffer, "(%%%s,%d)",
get_reg_intel(baser, op->regset),
scale);
break;
case ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE:
sprintf(buffer, "(%%%s,%%%s,%d)",
get_reg_intel(baser, op->regset),
get_reg_intel(indexr, op->regset),
scale);
break;
case ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_BASE | ASM_OP_SCALE:
sprintf(buffer, "%s(%%%s,%d)",
resolved,
get_reg_intel(baser, op->regset),
scale);
break;
case ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE | ASM_OP_VALUE:
sprintf(buffer, "%s(%%%s,%%%s,%d)",
resolved,
get_reg_intel(baser, op->regset),
get_reg_intel(indexr, op->regset),
scale);
break;
case ASM_OP_REFERENCE | ASM_OP_BASE | ASM_OP_INDEX | ASM_OP_SCALE |
ASM_OP_VALUE | ASM_OP_ADDRESS:
sprintf(buffer, "*%s(%%%s,%%%s,%d)",
resolved,
get_reg_intel(baser, op->regset),
get_reg_intel(indexr, op->regset),
scale);
break;
case ASM_OP_REFERENCE | ASM_OP_INDEX | ASM_OP_VALUE | ASM_OP_SCALE |ASM_OP_ADDRESS:
sprintf(buffer, "*%s(,%%%s,%d)",
resolved,
get_reg_intel(indexr, op->regset),
scale);
break;
case ASM_OP_REFERENCE | ASM_OP_VALUE | ASM_OP_INDEX | ASM_OP_SCALE:
sprintf(buffer, "%s(,%%%s,%d)",
resolved,
get_reg_intel(indexr, op->regset),
scale);
break;
case ASM_OP_REFERENCE | ASM_OP_INDEX | ASM_OP_SCALE:
sprintf(buffer, "(,%%%s,%d)",
get_reg_intel(indexr, op->regset),
scale);
break;
case ASM_OP_FPU | ASM_OP_BASE:
strcat(buffer, "%st");
break;
case ASM_OP_FPU | ASM_OP_BASE | ASM_OP_SCALE:
sprintf(buffer, "%%st(%d)", scale);
break;
case 0:
break;
default:
sprintf(buffer, "(...)");
}
}
/**
*
*
*
*/
int asm_operand_get_att(asm_instr *ins, int num, int opt, void *valptr)
{
att_dump_operand(ins, num, opt, valptr);
return (1);
}
/**
* @brief Return at&t ascii representation of an instruction
* @param instr Pointer to an instruction structure.
* @param addr Address of the instruction. May be used to compute offset of branch.
* @return A Pointer to a static buffer containing ascii instruction
*/
char *asm_ia32_display_instr_att(asm_instr *instr,
eresi_Addr addr)
{
static char buffer[1024];
int len;
int margin;
if (!instr)
return (0);
memset(buffer, 0, 1024);
if (instr->prefix & ASM_PREFIX_LOCK)
strcat(buffer, "lock ");
if (instr->prefix & ASM_PREFIX_REP)
strcat(buffer, "repz ");
if (instr->prefix & ASM_PREFIX_REPNE)
strcat(buffer, "repnz ");
if (instr->instr >= 0 && instr->instr <= ASM_BAD)
{
if (instr->proc->instr_table[instr->instr] != NULL)
sprintf(buffer + strlen(buffer), "%s", instr->proc->instr_table[instr->instr]);
else
sprintf(buffer + strlen(buffer), "missing");
}
else
{
sprintf(buffer + strlen(buffer), "out_of_range");
return (buffer);
}
/* Add spaces */
if (instr->op[0].type)
{
len = strlen(buffer);
margin = (int) config_get_data(CONFIG_ASM_ATT_MARGIN_FLAG);
while (len++ < margin)
strcat(buffer, " ");
if (instr->op[2].type)
{
asm_operand_get_att(instr, 3, addr, buffer + strlen(buffer));
strcat(buffer, ",");
}
if (instr->op[1].type)
{
switch(instr->op[1].prefix & ASM_PREFIX_SEG)
{
case ASM_PREFIX_ES:
strcat(buffer, "%es:");
break;
case ASM_PREFIX_DS:
strcat(buffer, "%ds:");
break;
}
asm_operand_get_att(instr, 2, addr, buffer + strlen(buffer));
strcat(buffer, ",");
}
switch (instr->op[0].prefix & ASM_PREFIX_SEG)
{
case ASM_PREFIX_ES:
strcat(buffer, "%es:");
break;
case ASM_PREFIX_DS:
strcat(buffer, "%ds:");
break;
}
switch (instr->prefix & ASM_PREFIX_MASK)
{
case ASM_PREFIX_CS:
strcat(buffer, "%cs:");
break;
case ASM_PREFIX_ES:
strcat(buffer, "%es:");
break;
case ASM_PREFIX_DS:
strcat(buffer, "%ds:");
break;
case ASM_PREFIX_GS:
strcat(buffer, "%gs:");
break;
case ASM_PREFIX_FS:
strcat(buffer, "%fs:");
break;
case ASM_PREFIX_SS:
strcat(buffer, "%ss:");
break;
}
asm_operand_get_att(instr, 1, addr, buffer + strlen(buffer));
}
return(buffer);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_tcc.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_tcc.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_tcc.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libasm.h"
int
asm_sparc_tcc(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_format3 opcode;
struct s_decode_format4 opcode4;
struct s_asm_proc_sparc *inter;
sparc_convert_format3(&opcode, buf);
sparc_convert_format4(&opcode4, buf);
inter = proc->internals;
ins->type = ASM_TYPE_INT | ASM_TYPE_READFLAG;
ins->flagsread = ASM_SP_FLAG_C | ASM_SP_FLAG_V | ASM_SP_FLAG_N | ASM_SP_FLAG_Z;
ins->instr = inter->tcc_table[opcode4.cond];
ins->nb_op = 2;
if (opcode4.i) {
ins->op[0].baser = opcode4.rs1;
ins->op[0].imm = opcode4.sw_trap;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_IMM_ADDRESS, ins);
}
else {
ins->op[0].baser = opcode4.rs1;
ins->op[0].indexr = opcode4.rs2;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_REG_ADDRESS, ins);
}
ins->op[1].baser = (opcode4.cc & 0x3) + 4;
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_CC, ins);
return 4;
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_fbpfcc.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_fbpfcc.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_fbpfcc.c 1413 2010-05-21 03:41:25Z figueredo $
**
*/
#include "libasm.h"
int
asm_sparc_fbpfcc(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_pbranch opcodep;
struct s_asm_proc_sparc *inter;
sparc_convert_pbranch(&opcodep, buf);
inter = proc->internals;
ins->instr = inter->fbcc_table[opcodep.cond];
if (ins->instr == ASM_SP_FBA)
ins->type = ASM_TYPE_BRANCH;
else if (ins->instr == ASM_SP_FBN)
ins->type = ASM_TYPE_NOP;
else
ins->type = ASM_TYPE_BRANCH | ASM_TYPE_CONDCONTROL;
/* Removed during flags cleanup. */
/* ins->type = ASM_TYPE_BRANCH | ASM_TYPE_CONDCONTROL; */
ins->nb_op = 2;
ins->op[0].imm = opcodep.imm;
ins->op[1].baser = opcodep.cc;
ins->annul = opcodep.a;
ins->prediction = opcodep.p;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_DISPLACEMENT, ins);
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_CC, ins);
return 4;
}
<file_sep>/src/fastcrc.c
/***FastCRC.c*/
/***Fast CRC code/decode functions*/
/***<NAME>*/
/***2000.7.13*/
/***NOTE: The type of int must be 32bits weight. ***/
#include "fastcrc.h"
#ifdef MG_CRC_32_ARITHMETIC_CCITT
#define MG_CRC_32_BIT
#endif
#ifdef MG_CRC_32_ARITHMETIC
#define MG_CRC_32_BIT
#endif
#ifdef MG_CRC_24_ARITHMETIC_CCITT
#define MG_CRC_24_BIT
#endif
#ifdef MG_CRC_24_ARITHMETIC
#define MG_CRC_24_BIT
#endif
/* 0xbba1b5 = 1'1011'1011'1010'0001'1011'0101b
= x24+x23+x21+x20+x19+x17+x16+x15+x13+x8+x7+x5+x4+x2+1 */
#define MG_CRC_24_CCITT (0x00ddd0da)
#define MG_CRC_24 (0x00ad85dd)
/* 0x04c11db7 = 1'0000'0100'1100'0001'0001'1101'1011'0111b
= x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1 */
#define MG_CRC_32_CCITT (0x04c11db7)
#define MG_CRC_32 (0xedb88320)
/************************************ Var define ************************************/
unsigned int MG_CRC_Table[256];
/********************************** Function define *********************************/
#define _bswap_32(x) ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \
(((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))
void MG_Print_Table(void)
{
int i;
unsigned int bend;
printf("LITTLE ENDIAN | BIG ENDIAN\n");
for(i = 0; i < 256; i++) {
bend = _bswap_32(MG_CRC_Table[i]);
printf("[%03d]: 0x%08x | 0x%08x\n", i, MG_CRC_Table[i], bend);
}
}
unsigned int MG_Compute_CRC24_CCITT(unsigned int crc, unsigned char *bufptr, int len)
{
register int i;
while(len--) /*Length limited*/
{
crc ^= ((unsigned int)(*bufptr) << 16);
bufptr++;
for(i = 0; i < 8; i++)
{
if(crc & 0x00800000) /*Highest bit procedure*/
crc = (crc << 1) ^ MG_CRC_24_CCITT;
else
crc <<= 1;
}
}
return(crc & 0x00ffffff); /*Get lower 24 bits FCS*/
}
unsigned int MG_Compute_CRC24(unsigned int crc, unsigned char *bufptr, int len)
{
register int i;
while(len--) /*Length limited*/
{
crc ^= (unsigned int)*bufptr;
bufptr++;
for(i = 0; i < 8; i++)
{
if(crc & 1) /*Lowest bit procedure*/
crc = (crc >> 1) ^ MG_CRC_24;
else
crc >>= 1;
}
}
return(crc & 0x00ffffff); /*Get lower 24 bits FCS*/
}
unsigned int MG_Compute_CRC32_CCITT(unsigned int crc, unsigned char *bufptr, int len)
{
register int i;
while(len--) /*Length limited*/
{
crc ^= (unsigned int)(*bufptr) << 24;
bufptr++;
for(i = 0; i < 8; i++)
{
if(crc & 0x80000000) /*Highest bit procedure*/
crc = (crc << 1) ^ MG_CRC_32_CCITT;
else
crc <<= 1;
}
}
return(crc & 0xffffffff); /*Get lower 32 bits FCS*/
}
unsigned int MG_Compute_CRC32(unsigned int crc, unsigned char *bufptr, int len)
{
register int i;
while(len--) /*Length limited*/
{
crc ^= (unsigned int)*bufptr;
bufptr++;
for(i = 0; i < 8; i++)
{
if(crc & 1) /*Lowest bit procedure*/
crc = (crc >> 1) ^ MG_CRC_32;
else
crc >>= 1;
}
}
return(crc & 0xffffffff); /*Get lower 32 bits FCS*/
}
/*Setup fast CRC compute table*/
void MG_Setup_CRC_Table(unsigned char type)
{
register int count;
unsigned char zero=0;
for(count = 0; count <= 255; count++) {
switch(type) {
case MG_CRC_24_ARITHMETIC_CCITT:
MG_CRC_Table[count] = (MG_Compute_CRC24_CCITT(count << 16,&zero,1));
break;
case MG_CRC_24_ARITHMETIC:
MG_CRC_Table[count] = (MG_Compute_CRC24(count,&zero,1));
break;
case MG_CRC_32_ARITHMETIC_CCITT:
MG_CRC_Table[count] = (MG_Compute_CRC32_CCITT(count << 24,&zero,1));
break;
case MG_CRC_32_ARITHMETIC:
MG_CRC_Table[count] = (MG_Compute_CRC32(count,&zero,1));
break;
}
}
}
/*Fast CRC compute*/
unsigned int MG_Table_Driven_CRC(unsigned int crc, unsigned char *bufptr, int len, unsigned char type)
{
register int i;
for(i = 0; i < len; i++) {
switch(type) {
case MG_CRC_24_ARITHMETIC_CCITT:
crc=(MG_CRC_Table[((crc >> 16) & 0xff) ^ bufptr[i]] ^ (crc << 8)) & 0x00ffffff;
break;
case MG_CRC_24_ARITHMETIC:
crc=(MG_CRC_Table[(crc & 0xff) ^ bufptr[i]] ^ (crc >> 8)) & 0x00ffffff;
break;
case MG_CRC_32_ARITHMETIC_CCITT:
crc=(MG_CRC_Table[((crc >> 24) & 0xff) ^ bufptr[i]] ^ (crc << 8)) & 0xffffffff;
break;
case MG_CRC_32_ARITHMETIC:
crc=(MG_CRC_Table[(crc & 0xff) ^ bufptr[i]] ^ (crc >> 8)) & 0xffffffff;
break;
}
}
return(crc);
}
void MG_FCS_Coder(unsigned char *pucInData,int len, unsigned char type)
{
unsigned int iFCS;
switch(type) {
case MG_CRC_24_ARITHMETIC_CCITT:
iFCS = ~MG_Table_Driven_CRC(0x00ffffff,pucInData,len,type);
pucInData[len + 2] = (unsigned char)iFCS&0xff;
pucInData[len + 1] = (unsigned char)(iFCS >> 8) & 0xff;
pucInData[len] = (unsigned char)(iFCS >> 16) & 0xff;
break;
case MG_CRC_24_ARITHMETIC:
iFCS = ~MG_Table_Driven_CRC(0x00ffffff,pucInData,len,type);
pucInData[len] = (unsigned char)iFCS&0xff;
pucInData[len + 1] = (unsigned char)(iFCS >> 8) & 0xff;
pucInData[len + 2] = (unsigned char)(iFCS >> 16) & 0xff;
break;
case MG_CRC_32_ARITHMETIC_CCITT:
iFCS = MG_Table_Driven_CRC(0xffffffff,pucInData,len,type);
pucInData[len + 3] = (unsigned char)iFCS & 0xff;
pucInData[len + 2] = (unsigned char)(iFCS >> 8) & 0xff;
pucInData[len + 1] = (unsigned char)(iFCS >> 16) & 0xff;
pucInData[len] = (unsigned char)(iFCS >> 24) & 0xff;
break;
case MG_CRC_32_ARITHMETIC:
iFCS = ~MG_Table_Driven_CRC(0xffffffff,pucInData,len,type);
pucInData[len] = (unsigned char)iFCS & 0xff;
pucInData[len + 1] = (unsigned char)(iFCS >> 8) & 0xff;
pucInData[len + 2] = (unsigned char)(iFCS >> 16) & 0xff;
pucInData[len + 3] = (unsigned char)(iFCS >> 24) & 0xff;
break;
}
}
int MG_FCS_Decoder(unsigned char *pucInData,int len, unsigned char type)
{
unsigned int iFCS;
switch(type) {
case MG_CRC_24_ARITHMETIC_CCITT:
pucInData[len - 1] = ~pucInData[len - 1];
pucInData[len - 2] = ~pucInData[len - 2];
pucInData[len - 3] = ~pucInData[len - 3];
if ((iFCS = MG_Table_Driven_CRC(0x00ffffff,pucInData,len,type)) != 0)/*Compute FCS*/
{
return(-1); /* CRC check error */
}
pucInData[len-1]='\0';
pucInData[len-2]='\0';
pucInData[len-3]='\0';
break;
case MG_CRC_24_ARITHMETIC:
pucInData[len - 1] = ~pucInData[len - 1];
pucInData[len - 2] = ~pucInData[len - 2];
pucInData[len - 3] = ~pucInData[len - 3];
if ((iFCS = MG_Table_Driven_CRC(0x00ffffff,pucInData,len,type)) != 0)/*Compute FCS*/
{
return(-1); /* CRC check error */
}
pucInData[len-1]='\0';
pucInData[len-2]='\0';
pucInData[len-3]='\0';
break;
case MG_CRC_32_ARITHMETIC_CCITT:
//pucInData[len - 1] = ~pucInData[len - 1];
//pucInData[len - 2] = ~pucInData[len - 2];
//pucInData[len - 3] = ~pucInData[len - 3];
//pucInData[len - 4] = ~pucInData[len - 4];
if ((iFCS = MG_Table_Driven_CRC(0xffffffff,pucInData,len,type)) != 0)/*Compute FCS*/
{
return(-1); /* CRC check error */
}
//pucInData[len - 1] = '\0';
//pucInData[len - 2] = '\0';
//pucInData[len - 3] = '\0';
//pucInData[len - 4] = '\0';
break;
case MG_CRC_32_ARITHMETIC:
pucInData[len - 1] = ~pucInData[len - 1];
pucInData[len - 2] = ~pucInData[len - 2];
pucInData[len - 3] = ~pucInData[len - 3];
pucInData[len - 4] = ~pucInData[len - 4];
if ((iFCS = MG_Table_Driven_CRC(0xffffffff,pucInData,len,type)) != 0)/*Compute FCS*/
{
return(-1); /* CRC check error */
}
pucInData[len - 1] = '\0';
pucInData[len - 2] = '\0';
pucInData[len - 3] = '\0';
pucInData[len - 4] = '\0';
break;
}
return(0); /* CRC check OK */
}
/***************************************** END ***************************************/
<file_sep>/src/libasm/src/arch/ia32/handlers/op_nop.c
/**
* @file libasm/src/arch/ia32/handlers/op_nop.c
*
* @ingroup IA32_instrs
* $Id: op_nop.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for the nop instruction, opcode 0x90
* @param new Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Length of the instruction.
*/
int op_nop(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->ptr_instr = opcode;
new->len += 1;
new->instr = ASM_NOP;
new->type = ASM_TYPE_NOP;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_pop_rmv.c
/*
** $Id: op_pop_rmv.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for the pop [rmv] instruction opcode = 0x8f
* @param new Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Lenght of buffer to disassemble.
* @param proc Pointer to processor structure.
*
*/
int op_pop_rmv(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->instr = ASM_POP;
new->ptr_instr = opcode;
new->type = ASM_TYPE_TOUCHSP | ASM_TYPE_ASSIGN | ASM_TYPE_LOAD;
new->spdiff = 4;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED,
new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED,
new);
#endif
return (new->len);
}
<file_sep>/src/libasm/include/libasm-sparc-decode.h
/**
* @defgroup SPARC_instrs SPARC instructions API.
* @ingroup sparc
*/
/**
* @file libasm/include/libasm-sparc-decode.h
** @ingroup sparc
**
** Started by sroy on Tue Jun 14 05:02:37 2005
** $Id: libasm-sparc-decode.h 1397 2009-09-13 02:19:08Z may $
*/
#ifndef LIBASM_SPARC_DECODE_H_
#define LIBASM_SPARC_DECODE_H_
/*
* sparc instruction formats
*/
struct s_decode_pbranch {
u_int32_t op:2;
u_int32_t a:1;
u_int32_t cond:4; /* TODO: fix the branches decode to use cc's */
u_int32_t op2:3;
u_int32_t cc1:1;
u_int32_t cc0:1;
u_int32_t p:1;
u_int32_t immediate:19;
u_int32_t imm;
u_int32_t cc;
};
struct s_decode_rbranch {
u_int32_t op:2;
u_int32_t a:1;
u_int32_t zero:1;
u_int32_t rcond:3;
u_int32_t op2:3;
u_int32_t d16hi:2;
u_int32_t p:1;
u_int32_t rs1:5;
u_int32_t d16lo:14;
u_int32_t d16;
};
struct s_decode_branch {
u_int32_t op:2;
u_int32_t a:1;
u_int32_t cond:4;
u_int32_t op2:3;
u_int32_t immediate:22;
u_int32_t imm;
u_int32_t rd;
};
struct s_decode_call {
u_int32_t op:2;
u_int32_t disp30:30;
u_int32_t displacement;
};
struct s_decode_format3 {
u_int32_t op:2;
u_int32_t rd:5;
u_int32_t op3:6;
u_int32_t rs1:5;
u_int32_t i:1;
u_int32_t none:8;
u_int32_t rs2:5;
u_int32_t imm;
u_int32_t imm10;
u_int32_t rcond;
u_int32_t shcnt;
u_int32_t opf;
u_int32_t cc; // as used by FCMP*
u_int32_t opf_cc; // as used by FMOV(s,d,q)cc
u_int32_t cond; // as used by FMOV(s,d,q)cc
};
struct s_decode_format4 {
u_int32_t op:2;
u_int32_t rd:5;
u_int32_t op3:6;
u_int32_t rs1:5;
u_int32_t i:1;
u_int32_t cc1:1;
u_int32_t cc0:1;
u_int32_t none:6;
u_int32_t rs2:5;
u_int32_t cond;
u_int32_t cc2;
u_int32_t cc;
u_int32_t imm;
u_int32_t sw_trap;
};
#endif
<file_sep>/src/libaspect/include/libaspect-profiler.h
/*
* @file libaspect/include/libaspect-profiler.h
**
** Started on Wed Jan 1 07:51:24 2003 jfv
** Last update Thu Mar 20 06:19:53 2003 jfv
**
** $Id: libaspect-profiler.h 1440 2010-12-29 02:22:03Z may $
**
*/
#ifndef __LIBASPECT_INTERN_
#define __LIBASPECT_INTERN_
#if defined(sun) || defined(__linux__) || defined(__BEOS__) || defined(HPUX) || defined(__FreeBSD__)
#define PROFILER_ERRORS_ARRAY strerror(errno)
#else
#define PROFILER_ERRORS_ARRAY sys_errlist[sys_nerr]
#endif
/* Extern variables */
extern int profiler_depth;
extern char* profiler_error_str;
extern int aspect_type_nbr;
extern hash_t *vector_hash;
extern hash_t types_hash;
/**
* Type of warnings that emit the allocation profiler
*/
#define PROFILER_WARNING_UNKNOW 0
#define PROFILER_WARNING_LAST 1
#define PROFILER_WARNING_FIRST 2
/**
* The structure for an allocation entry
*/
typedef struct s_allocentry
{
#define PROFILER_ALLOC_UNKNOW 0
#define PROFILER_ALLOC_LEGIT 1
#define PROFILER_ALLOC_PROXY 2
u_char alloctype; /*!< Inform about the allocator */
#define PROFILER_OP_UNKNOW 0
#define PROFILER_OP_ALLOC 1
#define PROFILER_OP_REALLOC 2
#define PROFILER_OP_FREE 3
u_char optype; /*!< Inform about alloc/free/etc */
char *filename; /*!< Inform about file location */
char *funcname; /*!< Inform about func location */
u_int linenbr; /*!< Inform about line number */
u_long addr; /*!< Address of allocation */
} profallocentry_t;
/**
* Maximum function calls patterns depth
*/
#define PROFILER_MAX_PATTERN 10
#define PROFILER_MAX_ALLOC 2000
/**
* Safe calloc()
*/
#define XALLOC(f, fc, l, a, b, c) \
do \
{ \
if ((a = (void *) calloc(b, 1)) == NULL) \
{ \
int wret = write(1, "Out of memory\n", 14); \
exit(wret); \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
(char *)"Out of memory .", c); \
} \
if (profiler_started()) \
profiler_alloc_update(f, (char *) fc, l, (u_long) a, \
PROFILER_ALLOC_PROXY, \
PROFILER_OP_ALLOC); \
} \
while (0)
/**
* Safe realloc()
*/
#define XREALLOC(f, fc, l, a, b, c, d) \
do \
{ \
if ((a = (void *) realloc(b, c)) == NULL) \
{ \
int wret = write(1, "Out of memory\n", 14); \
exit(wret); \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
"Out of memory .", d); \
} \
if (profiler_started()) \
profiler_alloc_update(f, (char *) fc, l, (u_long) a, \
PROFILER_ALLOC_PROXY, \
PROFILER_OP_REALLOC); \
} \
while (0)
/**
* Our free()
*/
#define XFREE(f, fc, l, a) \
do \
{ \
if (profiler_started()) \
profiler_alloc_update(f, (char *) fc, l, (u_long) a, \
PROFILER_ALLOC_PROXY, \
PROFILER_OP_FREE); \
free(a); \
a = 0; \
} \
while (0)
/**
* Our strdup()
*/
#define XSTRDUP(f, fc, l, a, b) \
do \
{ \
if (profiler_started()) \
profiler_alloc_update(f, (char *) fc, l, (u_long) a, \
PROFILER_ALLOC_PROXY, \
PROFILER_OP_ALLOC); \
a = strdup(b); \
} \
while (0)
/**
* Safe open()
*/
#define XOPEN(a, b, c, d, e) \
do \
{ \
if ((a = open(b, c, d)) < 0) \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
"Cannot open file", e); \
} \
while (0)
/**
* Safe read()
*/
#define XREAD(a, b, c, d) \
do \
{ \
if (read(a, b, c) != c) \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
(char *) PROFILER_ERRORS_ARRAY, d); \
} \
while (0)
/**
* Safe lseek()
*/
#define XSEEK(a, b, c, d) \
do \
{ \
if (lseek(a, b, c) == (off_t) -1) \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
(char *) PROFILER_ERRORS_ARRAY, d); \
} \
while (0)
/**
* Safe write
*/
#define XWRITE(a, b, c, d) \
do \
{ \
if (write(a, b, c) != c) \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
(char *) PROFILER_ERRORS_ARRAY, d); \
if (fsync(a)) \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
(char *) PROFILER_ERRORS_ARRAY, d); \
} \
while (0)
/**
* Safe close
*/
#define XCLOSE(a, b) \
do \
{ \
if (close(a)) \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
(char *)PROFILER_ERRORS_ARRAY, b); \
} \
while (0)
/**
* @brief Safe mmap
*/
#define XMMAP(a, b, c, d, e, f, g, h) \
do \
{ \
if ((a = mmap(b, c, d, e, f, g)) == MAP_FAILED) \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
(char *)PROFILER_ERRORS_ARRAY, h); \
} \
while (0)
/**
* @brief Safe munmap
*/
#define XMUNMAP(a, b, c) \
do \
{ \
if (munmap(a, b) == -1) \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
(char *)PROFILER_ERRORS_ARRAY, c); \
} \
while(0)
/**
* @brief Safe msync
*/
#define XMSYNC(a, b, c, d) \
do \
{ \
if (msync(a, b, c) == -1) \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
(char *)PROFILER_ERRORS_ARRAY, d); \
} \
while(0)
/**
* @brief Safe lseek64
*/
#define XLSEEK64(a, b, c, d) \
do \
{ \
if (lseek64(a, (off64_t)b, c) == -1) \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, \
(char *)PROFILER_ERRORS_ARRAY, d); \
} \
while(0)
/**
* Simple useful macro
*/
#define INTERVAL(a, b, c) (a <= b && b < c)
/**
* Profiling macros
*/
#define NOPROFILER_IN() int profileme = 0
#define NOPROFILER_OUT() \
do \
{ \
profileme = 0; \
return; \
} \
while (0)
#define NOPROFILER_ROUT(r) \
do \
{ \
profileme = 0; \
return (r); \
} \
while (0)
#define PROFILER_INQ() \
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__)
#define PROFILER_IN(file, fun, lin) \
int profileme = profiler_depth; \
do { \
if (profiler_started()) { \
profiler_updir(); \
profiler_out(file, (char*) fun, lin); \
profiler_incdepth(); } \
} while (0)
#define PROFILER_OUTQ() \
PROFILER_OUT(__FILE__, __FUNCTION__, __LINE__)
#define PROFILER_OUT(file, func, line) \
do { \
if (profiler_started()) { \
profiler_decdepth(); \
if (profileme != profiler_depth) \
{ \
printf(" [!] A function called by current" \
"forgot to decrement profiler_depth" \
"(%d %d)\n", \
profileme, profiler_depth); \
printf(" Current FUNCTION %s@%s:%d\n", \
func, file, line); \
profiler_depth = profileme; \
} \
profiler_out(file, (char*) func, line); } \
return; \
} while (0)
#define PROFILER_ROUTQ(ret) \
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, ret)
#define PROFILER_ROUT(file, f, l, ret) \
do { \
if (profiler_started()) { \
profiler_decdepth(); \
if (profileme != profiler_depth) \
{ \
printf(" [!] A function called by current " \
"forgot to decrement profiler_depth" \
"(%d %d)\n", profileme, \
profiler_depth); \
printf(" Current FUNCTION %s@%s:%d\n", \
f, file, l); \
profiler_depth = profileme; \
} \
profiler_out(file, (char*) f, l); } \
return ret; \
} while (0)
#define PROFILER_ERRQ(msg, ret) \
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, msg, ret);
#define PROFILER_ERR(file, f, l, m, r) \
do { \
if (profiler_started()) { \
profiler_decdepth(); \
if (profileme != profiler_depth) \
{ \
printf(" [!] A function called by current " \
"one forgot to decrement " \
"profiler_depth\n"); \
printf(" Current FUNCTION %s@%s:%d\n", \
f, file, l); \
profiler_depth = profileme; \
} \
profiler_error_str = m; \
profiler_err(file, (char*) f, l, m); } \
return r; \
} while (0)
#define PROFILER_RERR(file, f, l, m) \
do { \
if (profiler_started()) { \
profiler_decdepth(); \
if (profileme != profiler_depth) \
{ \
printf("a function called by the current " \
"one forgot to decrement " \
"profiler_depth\n"); \
printf("current FUNCTION %s@%s:%d\n", \
f, file, l); \
profiler_depth = profileme; \
} \
profiler_error_str = m; \
profiler_err(file, (char*) f, l, m); } \
} while (0)
/**
* Debugging macro
*/
#ifdef ELFSH_DEBUG
#define PROFILER_DEBUG(fi, f, l, fm, a...) do \
{ \
if (profiler_started() && dbgworld.proflevel >= PROFILE_DEBUG) \
{ \
char dbg[BUFSIZ]; \
snprintf(dbg, BUFSIZ, " [D]<%s@%s:%d> ", f, fi, l); \
dbgworld.profile(dbg); \
snprintf(dbg, BUFSIZ, fm, ##a); \
dbgworld.profile(dbg); \
dbgworld.profile("\n"); \
} \
while (0)
#endif
#endif
<file_sep>/src/libaspect/containers.c
/*
* @file libaspect/containers.c
** @ingroup libaspect
**
** @brief Implement generic routines for containers.
**
** Started on Sat Jun 2 15:20:18 2005 jfv
** $Id: containers.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libaspect.h"
/**
* @brief Create container lists
* @param container Container holding the lists
* @param linktype CONTAINER_LINK_IN or CONTAINER_LINK_OUT for input or output links list
* @param uniqid Unique ID to be put into name
* @return -1 on error and 0 on success
*/
int container_linklists_create(container_t *container,
u_int linktype,
u_int uniqid)
{
aspectype_t *type;
char bufname[BUFSIZ];
char *prefix;
list_t *newlist;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
/* Check for prefix (XXX: change to lookup user-configured prefixes ?) */
switch (container->type)
{
case ASPECT_TYPE_BLOC:
prefix = "bloc";
break;
case ASPECT_TYPE_FUNC:
prefix = "func";
break;
default:
type = aspect_type_get_by_id(container->type);
if (!type)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Unable to find type of container", -1);
prefix = type->name;
}
/* Now really allocate the list */
switch (linktype)
{
case CONTAINER_LINK_IN:
snprintf(bufname, BUFSIZ, "%d_%s_"AFMT"_%s",
uniqid, prefix, *(eresi_Addr *) container->data, "inputs");
newlist = elist_find(bufname);
if (newlist)
container->inlinks = newlist;
else
{
XALLOC(__FILE__, __FUNCTION__, __LINE__, container->inlinks, sizeof(list_t), -1);
elist_init(container->inlinks, strdup(bufname), ASPECT_TYPE_LINK);
}
break;
case CONTAINER_LINK_OUT:
snprintf(bufname, BUFSIZ, "%d_%s_"AFMT"_%s",
uniqid, prefix, *(eresi_Addr *) container->data, "outputs");
newlist = elist_find(bufname);
if (newlist)
container->outlinks = newlist;
else
{
XALLOC(__FILE__, __FUNCTION__, __LINE__, container->outlinks, sizeof(list_t), -1);
elist_init(container->outlinks, strdup(bufname), ASPECT_TYPE_LINK);
}
break;
default:
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Unknown link type", -1);
}
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, 0);
}
/**
* @brief Create a new container
* @param type Type of element inside container
* @param data Data pointer for contained element
* @param inlist Input links list if any (else it will be created empty)
* @param outlist Output links list if any (else it will be created empty)
* @param uniqid Unique ID to be put into name
* @return Container newly created
*/
container_t *container_create(u_int type, void *data, list_t *inlist, list_t *outlist, u_int uniqid)
{
container_t *newcntnr;
aspectype_t *rtype;
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
rtype = aspect_type_get_by_id(type);
if (!rtype)
PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__,
"Unknown container element type", NULL);
/* Make sure meta-data is initialized and contiguous with pointed data */
#if defined(DEBUG_LIBASPECT)
fprintf(stderr, "Allocating sizeof(container) + (%s type->size = %u) \n",
rtype->name, rtype->size);
#endif
XALLOC(__FILE__, __FUNCTION__, __LINE__, newcntnr, sizeof(container_t) + rtype->size, NULL);
newcntnr->data = (char *) newcntnr + sizeof(container_t);
newcntnr->type = type;
memcpy((char *) newcntnr->data, (char *) data, rtype->size);
/* Create lists if not specified */
if (inlist)
newcntnr->inlinks = elist_copy(inlist);
else
container_linklists_create(newcntnr, CONTAINER_LINK_IN, uniqid);
if (outlist)
newcntnr->outlinks = elist_copy(outlist);
else
container_linklists_create(newcntnr, CONTAINER_LINK_OUT, uniqid);
/* Make sure the container and contained data are contiguous */
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, newcntnr);
}
<file_sep>/src/libaspect/include/libaspect-list.h
/*
* @file libaspect/include/libaspect-list.h
**
** @brief Prototypes of API for ERESI lists
**
** Started on Fri Jul 13 20:25:42 2007 jfv
** $Id: libaspect-list.h 1444 2011-01-31 07:41:29Z may $
*/
#ifndef _LIBLIST_H_
#define _LIBLIST_H_ 1
/**
* @brief List entry data structure
*/
typedef struct s_listent
{
char *key;
void *data;
struct s_listent *next;
} listent_t;
/**
* @brief List data structure
*/
typedef struct s_aspect_list
{
listent_t *head;
int elmnbr;
u_int type;
u_char linearity;
char *name;
} list_t;
/* list.c */
int elist_init(list_t *, char*, u_int); /* Allocate the list */
list_t *elist_find(char *name); /* Find a list */
int elist_register(list_t *h, char *name); /* Register a list */
list_t *elist_empty(char *name); /* Empty the list */
list_t *elist_reverse(list_t *l); /* Reverse the list */
void elist_destroy(list_t *h); /* Free the list */
list_t *elist_copy(list_t *h); /* Copy a list */
int elist_add(list_t *h, char *k, void *d); /* Add an entry */
int elist_append(list_t *h, char *key, void *data); /* Append element to list */
int elist_del(list_t *h, char *key); /* Delete an entry */
void *elist_get(list_t *h, char *key); /* Get data from key */
void *elist_select(list_t *h, char *key); /* Get an entry pointer */
listent_t *elist_get_head(list_t *h); /* Get a list head */
listent_t *elist_get_ent(list_t *h, char *key); /* Get an entry metadata */
void elist_print(list_t *h); /* Print the list */
char** elist_get_keys(list_t *h, int* n); /* Create array of keys */
void elist_free_keys(char **keys); /* Free keys */
int elist_apply(list_t *h, void *ptr,
int (*f)(listent_t *e, void *p)); /* Apply function */
int elist_merge(list_t *dst, list_t *src); /* Fuse lists */
int elist_unmerge(list_t *dst, list_t *src); /* Quotient lists */
int elist_size(list_t *hash); /* Return the elm nbr */
int elist_set(list_t *h, char *key, void *data); /* Change meta data for a key */
int elist_replace(list_t *h, char *k, list_t *nl); /* Replace one elem by a list */
int elist_compare(list_t *first, list_t *two); /* Compare the content of 2 lists */
u_char elist_linearity_get(list_t *l); /* Get linearity of a list */
void elist_linearity_set(list_t *l, u_char val); /* Set linearity of a list */
void *elist_pop(list_t *h); /* Remove the head of the list */
int elist_push(list_t *h, void *data); /* Add an element in first of the list */
void *elist_get_headptr(list_t *h); /* Get list head data without popping */
#endif /* _LIBLIST_H_ */
<file_sep>/src/libasm/src/arch/ia32/handlers/op_enter.c
/*
** $Id: op_enter.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for the enter instruction, opcode 0xc8
* @param new Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
*/
int op_enter(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->instr = ASM_ENTER;
new->len += 1;
new->ptr_instr = opcode;
new->type = ASM_TYPE_TOUCHSP;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_IMMEDIATEWORD, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_IMMEDIATEWORD, new);
#endif
#else
new->op[0].type = ASM_OTYPE_IMMEDIATE;
new->op[0].content = ASM_OP_VALUE;
new->op[0].len = 2;
new->op[0].ptr = opcode + 1;
new->op[0].imm = 0;
memcpy(&new->op[0].imm, opcode + 1, 2);
new->len += 2;
#endif
new->spdiff = -new->op[0].imm;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_adc_eax_iv.c
/*
** $Id: op_adc_eax_iv.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_adc_eax_iv" opcode="0x15"/>
*/
int op_adc_eax_iv(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->instr = ASM_ADC;
new->ptr_instr = opcode;
new->len += 1;
new->type = ASM_TYPE_ARITH | ASM_TYPE_READFLAG | ASM_TYPE_WRITEFLAG;
new->flagsread = ASM_FLAG_CF;
new->flagswritten = ASM_FLAG_OF | ASM_FLAG_SF | ASM_FLAG_ZF |
ASM_FLAG_AF | ASM_FLAG_CF | ASM_FLAG_PF;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new);
#endif
new->op[0].type = ASM_OTYPE_FIXED;
new->op[0].size = new->op[1].size = asm_proc_vector_size(proc);
new->op[0].content = ASM_OP_FIXED | ASM_OP_BASE;
new->op[0].baser = ASM_REG_EAX;
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_imul_gv_ev_ib.c
/*
** $Id: op_imul_gv_ev_ib.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_imul_gv_ev_ib" opcode="0x6b"/>
*/
int op_imul_gv_ev_ib(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
int olen;
new->len += 1;
new->ptr_instr = opcode;
new->instr = ASM_IMUL;
new->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_OF | ASM_FLAG_CF;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_GENERAL, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_GENERAL, new);
#endif
#if WIP
new->len += (olen = asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_ENCODED, new, 0));
#else
new->len += (olen = asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_ENCODED, new));
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[2], opcode + 1 + olen, ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[2], opcode + 1 + olen, ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/include/libasm-int.h
/**
* @file libasm/include/libasm-int.h
* $Id: libasm-int.h 1397 2009-09-13 02:19:08Z may $
*
* This file contains the forward declarations of i386 instruction
* handlers and some internal functions prototypes.
*/
#ifndef LIBASM_INT_H
#define LIBASM_INT_H
/* Debug flags */
#define __DEBUG_MODRM__ 0
/**
* Structure describing the modrm byte.
*/
typedef struct s_modrm
{
u_char m:3;
u_char r:3;
u_char mod:2;
} asm_modrm;
/**
* Structure describing the sid byte.
*/
typedef struct s_sidbyte
{
u_char base:3;
u_char index:3;
u_char sid:2;
} asm_sidbyte;
int asm_int_pow2(int);
int fetch_i386(asm_instr *, u_char *, u_int, asm_processor *);
void asm_resolve_immediate(asm_processor *proc, eresi_Addr val, char *buffer, u_int len);
char *asm_ia32_display_instr_att(asm_instr *ins, eresi_Addr addr);
char *asm_sparc_display_instr(asm_instr *, eresi_Addr addr);
int asm_ia32_switch_mode(asm_processor *proc, int mode);
int asm_proc_opsize(asm_processor *proc);
int asm_proc_addsize(asm_processor *proc);
int asm_proc_vector_size(asm_processor *proc);
int asm_proc_vector_len(asm_processor *);
int asm_proc_is_protected(asm_processor *);
/**
* Internal functions to extract operands.
*/
int operand_rmb_rb(asm_instr *, u_char *, int, asm_processor *);
int operand_rmv_rv(asm_instr *, u_char *, int, asm_processor *);
int operand_rb_rmb(asm_instr *, u_char *, int, asm_processor *);
int operand_rv_rmv(asm_instr *, u_char *, int, asm_processor *);
int operand_rv_rmb(asm_instr *, u_char *, int, asm_processor *);
int operand_rmb_ib(asm_instr *, u_char *, int, asm_processor *);
int operand_rmv_iv(asm_instr *, u_char *, int, asm_processor *);
int operand_rmv_ib(asm_instr *, u_char *, int, asm_processor *);
int operand_rv_rm2(asm_instr *, u_char *, int, asm_processor *);
int operand_rv_m(asm_instr *, u_char *, int, asm_processor *);
int operand_rmv(asm_operand *, u_char *, u_int, asm_processor *);
int operand_rmb(asm_operand *, u_char *, u_int, asm_processor *);
/**
* Handler for the i386 instructions.
*/
int op_add_rmb_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_add_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int op_add_rb_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_add_rv_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_add_al_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_add_eax_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_es(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_es(asm_instr *, u_char *, u_int, asm_processor *);
int op_or_rmb_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_or_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int op_or_rb_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_or_rv_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_or_al_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_or_eax_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_cs(asm_instr *, u_char *, u_int, asm_processor *);
int op_386sp(asm_instr *, u_char *, u_int, asm_processor *);
int op_adc_rmb_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_adc_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int op_adc_rb_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_adc_rv_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_adc_al_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_adc_eax_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_ss(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_es(asm_instr *, u_char *, u_int, asm_processor *);
int op_sbb_rmb_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_sbb_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int op_sbb_rb_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_sbb_rv_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_sbb_al_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_sbb_eax_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_ds(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_ds(asm_instr *, u_char *, u_int, asm_processor *);
int op_and_rmb_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_and_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int op_and_rb_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_and_rv_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_and_al_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_and_eax_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_prefix_es(asm_instr *, u_char *, u_int, asm_processor *);
int op_daa(asm_instr *, u_char *, u_int, asm_processor *);
int op_sub_rmb_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_sub_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int op_sub_rb_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_sub_rv_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_sub_al_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_sub_eax_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_prefix_cs(asm_instr *, u_char *, u_int, asm_processor *);
int op_das(asm_instr *, u_char *, u_int, asm_processor *);
int op_xor_rmb_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_xor_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int op_xor_rb_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_xor_rv_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_xor_al_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_xor_eax_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_prefix_ss(asm_instr *, u_char *, u_int, asm_processor *);
int op_aaa(asm_instr *, u_char *, u_int, asm_processor *);
int op_cmp_rmb_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_cmp_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int op_cmp_rb_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_cmp_rv_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_cmp_al_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_cmp_eax_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_cmp_xchg(asm_instr *, u_char *, u_int, asm_processor *);
int op_prefix_ds(asm_instr *, u_char *, u_int, asm_processor *);
int op_aas(asm_instr *, u_char *, u_int, asm_processor *);
int op_inc_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_inc_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_inc_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_inc_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_inc_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_inc_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_inc_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_inc_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_dec_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_dec_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_dec_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_dec_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_dec_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_dec_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_dec_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_dec_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_pusha(asm_instr *, u_char *, u_int, asm_processor *);
int op_popa(asm_instr *, u_char *, u_int, asm_processor *);
int op_bound_gv_ma(asm_instr *, u_char *, u_int, asm_processor *);
int op_arpl_ew_rw(asm_instr *, u_char *, u_int, asm_processor *);
int op_prefix_fs(asm_instr *, u_char *, u_int, asm_processor *);
int op_prefix_gs(asm_instr *, u_char *, u_int, asm_processor *);
int op_opsize(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_imul_rv_rmv_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_push_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_imul_gv_ev_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_insb(asm_instr *, u_char *, u_int, asm_processor *);
int op_insw(asm_instr *, u_char *, u_int, asm_processor *);
int op_outsb(asm_instr *, u_char *, u_int, asm_processor *);
int op_outsw(asm_instr *, u_char *, u_int, asm_processor *);
int op_jo(asm_instr *, u_char *, u_int, asm_processor *);
int op_jno(asm_instr *, u_char *, u_int, asm_processor *);
int op_jb(asm_instr *, u_char *, u_int, asm_processor *);
int op_jae(asm_instr *, u_char *, u_int, asm_processor *);
int op_je(asm_instr *, u_char *, u_int, asm_processor *);
int op_jne(asm_instr *, u_char *, u_int, asm_processor *);
int op_jbe(asm_instr *, u_char *, u_int, asm_processor *);
int op_ja(asm_instr *, u_char *, u_int, asm_processor *);
int op_js(asm_instr *, u_char *, u_int, asm_processor *);
int op_jns(asm_instr *, u_char *, u_int, asm_processor *);
int op_jp(asm_instr *, u_char *, u_int, asm_processor *);
int op_jnp(asm_instr *, u_char *, u_int, asm_processor *);
int op_jl(asm_instr *, u_char *, u_int, asm_processor *);
int op_jge(asm_instr *, u_char *, u_int, asm_processor *);
int op_jle(asm_instr *, u_char *, u_int, asm_processor *);
int op_jg(asm_instr *, u_char *, u_int, asm_processor *);
int op_immed_rmb_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_immed_rmb_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_immed_rmv_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_immed_rmv_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_test_rmb_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_test_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int op_xchg_rmb_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_xchg_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_rmb_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_rb_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_rv_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_rm_segr(asm_instr *, u_char *, u_int, asm_processor *);
int op_lea_rv_m(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_segr_rm(asm_instr *, u_char *, u_int, asm_processor *);
int op_pop_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_nop(asm_instr *, u_char *, u_int, asm_processor *);
int op_xchg_eax_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_xchg_eax_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_xchg_eax_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_xchg_eax_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_xchg_eax_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_xchg_eax_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_xchg_eax_reg(asm_instr *, u_char *, u_int, asm_processor *);
int op_cwtl(asm_instr *, u_char *, u_int, asm_processor *);
int op_cltd(asm_instr *, u_char *, u_int, asm_processor *);
int op_fwait(asm_instr *, u_char *, u_int, asm_processor *);
int op_pushf(asm_instr *, u_char *, u_int, asm_processor *);
int op_popf(asm_instr *, u_char *, u_int, asm_processor *);
int op_sahf(asm_instr *, u_char *, u_int, asm_processor *);
int op_lahf(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_al_ref_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_eax_ref_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_ref_iv_al(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_ref_iv_eax(asm_instr *, u_char *, u_int, asm_processor *);
int op_movsb(asm_instr *, u_char *, u_int, asm_processor *);
int op_movsd(asm_instr *, u_char *, u_int, asm_processor *);
int op_cmpsb(asm_instr *, u_char *, u_int, asm_processor *);
int op_cmpsd(asm_instr *, u_char *, u_int, asm_processor *);
int op_test_al_rb(asm_instr *, u_char *, u_int, asm_processor *);
int op_test_eax_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_stosb(asm_instr *, u_char *, u_int, asm_processor *);
int op_stosd(asm_instr *, u_char *, u_int, asm_processor *);
int op_lodsb(asm_instr *, u_char *, u_int, asm_processor *);
int op_lodsd(asm_instr *, u_char *, u_int, asm_processor *);
int op_scasb(asm_instr *, u_char *, u_int, asm_processor *);
int op_scasd(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_subreg_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_subreg_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_subreg_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_subreg_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_subreg_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_subreg_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_subreg_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_subreg_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_reg_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_reg_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_reg_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_reg_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_reg_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_reg_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_reg_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_reg_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_shr_rmb_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_shr_rmv_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_ret_i2(asm_instr *, u_char *, u_int, asm_processor *);
int op_ret(asm_instr *, u_char *, u_int, asm_processor *);
int op_les_rm_rmp(asm_instr *, u_char *, u_int, asm_processor *);
int op_lds_rm_rmp(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_rmb_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_mov_rmv_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_enter(asm_instr *, u_char *, u_int, asm_processor *);
int op_leave(asm_instr *, u_char *, u_int, asm_processor *);
int op_retf_i2(asm_instr *, u_char *, u_int, asm_processor *);
int op_retf(asm_instr *, u_char *, u_int, asm_processor *);
int op_int_3(asm_instr *, u_char *, u_int, asm_processor *);
int op_int_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_into(asm_instr *, u_char *, u_int, asm_processor *);
int op_iret(asm_instr *, u_char *, u_int, asm_processor *);
int op_shift_rmb_1(asm_instr *, u_char *, u_int, asm_processor *);
int op_shift_rmv_1(asm_instr *, u_char *, u_int, asm_processor *);
int op_shift_rmb_cl(asm_instr *, u_char *, u_int, asm_processor *);
int op_shift_rmv_cl(asm_instr *, u_char *, u_int, asm_processor *);
int op_aam(asm_instr *, u_char *, u_int, asm_processor *);
int op_aad(asm_instr *, u_char *, u_int, asm_processor *);
int op_xlatb(asm_instr *, u_char *, u_int, asm_processor *);
int op_esc0(asm_instr *, u_char *, u_int, asm_processor *);
int op_esc1(asm_instr *, u_char *, u_int, asm_processor *);
int op_esc2(asm_instr *, u_char *, u_int, asm_processor *);
int op_esc3(asm_instr *, u_char *, u_int, asm_processor *);
int op_esc4(asm_instr *, u_char *, u_int, asm_processor *);
int op_esc5(asm_instr *, u_char *, u_int, asm_processor *);
int op_esc6(asm_instr *, u_char *, u_int, asm_processor *);
int op_esc7(asm_instr *, u_char *, u_int, asm_processor *);
int op_loopne(asm_instr *, u_char *, u_int, asm_processor *);
int op_loope(asm_instr *, u_char *, u_int, asm_processor *);
int op_loop(asm_instr *, u_char *, u_int, asm_processor *);
int op_je_cxz(asm_instr *, u_char *, u_int, asm_processor *);
int op_in_al_ref_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_in_eax_ref_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_out_ref_ib_al(asm_instr *, u_char *, u_int, asm_processor *);
int op_out_ref_ib_eax(asm_instr *, u_char *, u_int, asm_processor *);
int op_call_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_jmp_iv(asm_instr *, u_char *, u_int, asm_processor *);
int op_jmp_ap(asm_instr *, u_char *, u_int, asm_processor *);
int op_jmp_ib(asm_instr *, u_char *, u_int, asm_processor *);
int op_in_al_dx(asm_instr *, u_char *, u_int, asm_processor *);
int op_in_eax_dx(asm_instr *, u_char *, u_int, asm_processor *);
int op_out_dx_al(asm_instr *, u_char *, u_int, asm_processor *);
int op_out_dx_eax(asm_instr *, u_char *, u_int, asm_processor *);
int op_lock(asm_instr *, u_char *, u_int, asm_processor *);
int op_lock(asm_instr *, u_char *, u_int, asm_processor *);
int op_repnz(asm_instr *, u_char *, u_int, asm_processor *);
int op_repz(asm_instr *, u_char *, u_int, asm_processor *);
int op_hlt(asm_instr *, u_char *, u_int, asm_processor *);
int op_cmc(asm_instr *, u_char *, u_int, asm_processor *);
int op_unary_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_unary_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_clc(asm_instr *, u_char *, u_int, asm_processor *);
int op_stc(asm_instr *, u_char *, u_int, asm_processor *);
int op_cli(asm_instr *, u_char *, u_int, asm_processor *);
int op_sti(asm_instr *, u_char *, u_int, asm_processor *);
int op_cld(asm_instr *, u_char *, u_int, asm_processor *);
int op_std(asm_instr *, u_char *, u_int, asm_processor *);
int op_incdec_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_indir_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_group6(asm_instr *, u_char *, u_int, asm_processor *);
int op_group7(asm_instr *, u_char *, u_int, asm_processor *);
int op_ud2a(asm_instr *, u_char *, u_int, asm_processor *);
int i386_rdtsc(asm_instr *, u_char *, u_int, asm_processor *);
int i386_mov_rm_cr(asm_instr *, u_char *, u_int, asm_processor *);
int i386_mov_cr_rm(asm_instr *, u_char *, u_int, asm_processor *);
int i386_mov_dr_rm(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovae(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmove(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovne(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovno(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovbe(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovb(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovo(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmova(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovs(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovns(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovp(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovnp(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovl(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovnl(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovle(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cmovnle(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jb(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jae(asm_instr *, u_char *, u_int, asm_processor *);
int i386_je(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jne(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jbe(asm_instr *, u_char *, u_int, asm_processor *);
int i386_ja(asm_instr *, u_char *, u_int, asm_processor *);
int i386_js(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jp(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jnp(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jns(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jl(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jge(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jle(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jg(asm_instr *, u_char *, u_int, asm_processor *);
int i386_jg(asm_instr *, u_char *, u_int, asm_processor *);
int op_setno_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_setb_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_setae_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_sete_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_setne_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_setbe_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_seta_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_sets_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_setns_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_setp_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_setnp_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_setl_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_setge_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_setle_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int op_setg_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int i386_push_fs(asm_instr *, u_char *, u_int, asm_processor *);
int i386_pop_fs(asm_instr *, u_char *, u_int, asm_processor *);
int i386_cpuid(asm_instr *, u_char *, u_int, asm_processor *);
int i386_bt_rm_r(asm_instr *, u_char *, u_int, asm_processor *);
int i386_xadd(asm_instr *, u_char *, u_int, asm_processor *);
int i386_group12(asm_instr *, u_char *, u_int, asm_processor *);
int i386_group14(asm_instr *, u_char *, u_int, asm_processor *);
int i386_group15(asm_instr *, u_char *, u_int, asm_processor *);
int i386_group16(asm_instr *, u_char *, u_int, asm_processor *);
int i386_bswap(asm_instr *, u_char *, u_int, asm_processor *);
int i386_shld(asm_instr *, u_char *, u_int, asm_processor *);
int i386_shld_rmv_rv_cl(asm_instr *, u_char *, u_int, asm_processor *);
int i386_bts(asm_instr *, u_char *, u_int, asm_processor *);
int i386_shrd_rmv_rv_ib(asm_instr *, u_char *, u_int, asm_processor *);
int i386_shrd_rmv_rv_cl(asm_instr *, u_char *, u_int, asm_processor *);
int i386_imul_rv_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_lss_rv_rmv(asm_instr *, u_char *, u_int, asm_processor *);
int op_btr_rmv_rv(asm_instr *, u_char *, u_int, asm_processor *);
int i386_movzbl_rv_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int i386_movzwl_rv_rm2(asm_instr *, u_char *, u_int, asm_processor *);
int i386_bsf(asm_instr *, u_char *, u_int, asm_processor *);
int i386_bsr_rv_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int i386_movsbl_rv_rmb(asm_instr *, u_char *, u_int, asm_processor *);
int i386_movswl_rv_rm2(asm_instr *, u_char *, u_int, asm_processor *);
int i386_movd_pd_qd(asm_instr *, u_char *, u_int, asm_processor *);
int i386_movq_pq_qq(asm_instr *, u_char *, u_int, asm_processor *);
int i386_movq_qq_pq(asm_instr *, u_char *, u_int, asm_processor *);
int i386_pand_pq_qq(asm_instr *, u_char *, u_int, asm_processor *);
int i386_por_pq_qq(asm_instr *, u_char *, u_int, asm_processor *);
int i386_pxor_pq_qq(asm_instr *, u_char *, u_int, asm_processor *);
int i386_pmullw_pq_qq(asm_instr *, u_char *, u_int, asm_processor *);
int i386_paddusw_pq_qq(asm_instr *, u_char *, u_int, asm_processor *);
int i386_paddusb_pq_qq(asm_instr *, u_char *, u_int, asm_processor *);
int i386_punpcklbw_pq_qd(asm_instr *, u_char *, u_int, asm_processor *);
int i386_punpckhbw_pq_qq(asm_instr *, u_char *, u_int, asm_processor *);
int i386_packuswb_pq_qq(asm_instr *, u_char *, u_int, asm_processor *);
int i386_emms(asm_instr *, u_char *, u_int, asm_processor *);
int op_addsize(asm_instr *, u_char *, u_int, asm_processor *);
int i386_wbinvd(asm_instr *, u_char *, u_int, asm_processor *);
int i386_rdmsr(asm_instr *, u_char *, u_int, asm_processor *);
int i386_btrl(asm_instr *, u_char *, u_int, asm_processor *);
int i386_xstorenrg(asm_instr *, u_char *, u_int, asm_processor *);
#endif
<file_sep>/src/libasm/src/arch/ia32/handlers/op_fwait.c
/**
* $Id: op_fwait.c 1397 2009-09-13 02:19:08Z may $
* @file libasm/src/arch/ia32/handlers/op_fwait.c
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Instruction handler for opcode 0x9b.
* This opcode is the for fwait prefix opcode.
* Disassembling is forwarded on next byte after execution of this
* handler.
*
* @param new Pointer to instruction structure.
* @param opcode Pointer to buffer to disassemble.
* @param len Length of buffer to disassemble.
* @param proc Pointer to processor structure.
* @return Length of disassembled instruction.
*/
int op_fwait(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
if (!new->ptr_prefix)
new->ptr_instr = opcode;
new->prefix |= ASM_PREFIX_FWAIT;
return (proc->fetch(new, opcode + 1, len - 1, proc));
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_xor_rmv_rv.c
/**
* @file libasm/src/arch/ia32/handlers/op_xor_rmv_rv.c
*
* @ingroup IA32_instrs
* @brief Handler for instruction xor rmv,rv opcode 0x31
* $Id: op_xor_rmv_rv.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @brief Handler for instruction xor rmv,rv opcode 0x31
* @param instr Pointer to instruction structure.
* @param opcode Pointer to data to disassemble
* @param len Length of data to disassemble
* @param proc Pointer to processor structure
* @return Insruction length
<instruction func="op_xor_rmv_rv" opcode="0x31"/>
*/
int op_xor_rmv_rv(asm_instr *instr, u_char *opcode, u_int len,
asm_processor *proc)
{
instr->len += 1;
instr->ptr_instr = opcode;
instr->instr = ASM_XOR;
instr->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
instr->flagswritten = ASM_FLAG_CF | ASM_FLAG_OF | ASM_FLAG_PF |
ASM_FLAG_ZF | ASM_FLAG_SF;
#if WIP
instr->len += asm_operand_fetch(&instr->op[0], opcode + 1, ASM_OTYPE_ENCODED, instr, 0);
instr->len += asm_operand_fetch(&instr->op[1], opcode + 1, ASM_OTYPE_GENERAL, instr, 0);
#else
instr->len += asm_operand_fetch(&instr->op[0], opcode + 1, ASM_OTYPE_ENCODED, instr);
instr->len += asm_operand_fetch(&instr->op[1], opcode + 1, ASM_OTYPE_GENERAL, instr);
#endif
return (instr->len);
}
<file_sep>/src/db.h
#ifndef DB_H
#define DB_H
#ifndef LIST_H
#include "list.h"
#endif
#define DB_MAGIC 0xdeadbeef
#define DB_ITEM 0xc00ffee
#define DB_OPEN 0
#define DB_NEW 1
#define DB_OVERWRITE 2
#define DB_TYPE_FLAT 0
#define DB_TYPE_CRYPTO 2
#define DB_TYPE_COMPRESS 4
enum {
DB_ERROR_OPEN,
DB_ERROR_HEADER,
DB_ERROR_MAGIC,
DB_ERROR_ITEM_MAGIC,
DB_ERROR_ITEM_HEADER,
DB_ERROR_ITEM_DATA,
DB_ERROR_MALLOC,
DB_ERROR_NONE
};
typedef struct db {
unsigned int magic;
unsigned int type;
int nitems;
int nroot;
bb_list_t *items;
int fd;
unsigned char error;
} db_t;
typedef struct db_item {
int id;
int root;
char name[64];
unsigned int size;
int child;
unsigned char *data;
} db_item_t;
int db_open(db_t *db, const char *filename, int mode);
int db_close(db_t *db, int save);
void db_item_add(db_t *db, char *name, int root, void *data, int size);
db_item_t *db_item_get(db_t *, char *, int);
char *db_strerror(db_t *db);
#endif
<file_sep>/src/list.h
/*
* beardbastards source code
*/
#ifndef BB_LIST_H
#define BB_LIST_H
#include <stdio.h>
#include <stdlib.h>
typedef struct bb_list bb_list_t;
typedef struct bb_list_node bb_list_node_t;
struct bb_list {
bb_list_node_t *head, *tail;
};
struct bb_list_node {
void *dptr;
bb_list_node_t *next, *prev;
};
bb_list_node_t *bb_list_node_alloc(void *);
void bb_list_add(bb_list_t **, bb_list_node_t *);
void bb_list_insert(bb_list_t **, bb_list_node_t *, bb_list_node_t *);
void bb_list_del(bb_list_t **, bb_list_node_t *);
bb_list_node_t *bb_list_find_next(bb_list_t **, void *);
bb_list_node_t *bb_list_find_prev(bb_list_t **, void *);
void bb_list_print(bb_list_t **, unsigned char);
#endif
<file_sep>/src/libasm/src/arch/mips/init_mips.c
/**
* @file libasm/src/arch/mips/init_mips.c
** @ingroup mips
*/
/**
* @file libasm/src/arch/mips/init_mips.c
* @brief This file have function for initializing and fetch code for MIPS architecture.
*
* fix and fill
* - Adam 'pi3' Zabrocki
*
* <NAME> - 2007
*/
#include <libasm.h>
/**
* @fn int asm_fetch_mips(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc)
* @brief MIPS main fetching handler.
*
* This function is called by asm_read_instr.
* Function pointer is stored in asm_processor structure.
*
* @param ins Pointer to instruction structure to fill.
* @param buf Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Lengh of instruction or 0 on error.
*/
int asm_fetch_mips(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc)
{
vector_t *vec = 0;
u_int i = 0, converted = 0;
u_int dim[3];
u_char *for_help;
LIBASM_HANDLER_FETCH(fetch);
if (asm_config_get_endian() == CONFIG_ASM_BIG_ENDIAN) {
memcpy((char *)&converted,buf,sizeof(converted));
} else if (asm_config_get_endian() == CONFIG_ASM_LITTLE_ENDIAN) {
for_help = (u_char*)&converted;
for(i=0;i<4;i++)
*(for_help + i) = *(buf + 3 - i);
} else {
printf("[INIT] Where am I ?!?!?!\n");
exit(-1);
}
ins->proc = proc;
ins->len = 4;
ins->ptr_instr = buf;
ins->nb_op = 0;
ins->type = ASM_TYPE_NONE;
vec = aspect_vector_get(LIBASM_VECTOR_OPCODE_MIPS);
/*
* Instruction hierarchy, lacks COP0 COP1 COP2 and COP1X
* subclasses wich are fpu/privileged/coprocessor 2 stuff
*
* dim[0] = 0-63 = base class : 64 combinations
* dim[1] = 0-63 = SPECIAL subclass : 64 combinations
* dim[2] = 0-1 = MOVCI subclass
* dim[2] = 2-3 = SRL subclass
* dim[2] = 4-5 = SRLV subclass
* dim[1] = 64-95 = REGIMM subclass : 32 combinations
* dim[1] = 96-159 = SPECIAL2 subclass : 64 combinations
* dim[1] = 160-223 = SPECIAL3 subclass : 64 combinations
* dim[2] = 6-37 = BSHFL subclass : 32 combinations
*/
dim[0] = converted >> 26;
dim[1] = 0; //(converted >> 21) & 0x1F;
dim[2] = 0;
switch(dim[0])
{
case MIPS_OPCODE_SPECIAL:
{
dim[1] = converted & 0x3f;
switch(dim[1])
{
case MIPS_OPCODE_MOVCI:
dim[2] = (converted & 0x10000 ) >> 16;
break;
case MIPS_OPCODE_SRL:
// dim[2] = ((converted & 0x200000 ) >> 21) + 2;
dim[2] = ((converted >> 21) & 0x1F);
break;
case MIPS_OPCODE_SRLV:
// dim[2] = ((converted & 0x40) >> 6) + 4;
dim[2] = ((converted >> 6) & 0x1F);
break;
}
break;
}
case MIPS_OPCODE_REGIMM:
dim[1] = ((converted >> 16) & 0x1F);
break;
case MIPS_OPCODE_SPECIAL2:
dim[1] = converted & 0x3F;
break;
case MIPS_OPCODE_SPECIAL3:
dim[1] = converted & 0x3F;
switch(dim[1])
{
case MIPS_OPCODE_BSHFL:
dim[2] = ((converted & 0x7c0) >> 6) + 6;
}
break;
case MIPS_OPCODE_COP0:
do {
u_int tmp = (converted >> 21) & 0x1F;
if (!tmp)
dim[1] = tmp;
else
dim[1] = (converted >> 21) & 0x1F;
dim[1] = tmp;
//printf("OPCODE: %02x %02x, %02x %02x\n", dim[0], dim[1], MIPS_OPCODE_COP0, MIPS_OPCODE_MTC0);
} while(0);
break;
case MIPS_OPCODE_COP1:
do {
u_int tmp = (converted >> 0) & 0x3F;
u_int fmt = (converted >> 21) & 0x1F;
u_int jajo = (converted >> 4) & 0xF;
u_int kupa = (converted >> 0) & 0xF;
if (fmt == MIPS_OPCODE_BCC2) {
dim[1] = fmt;
dim[2] = (converted >> 16) & 0x3;
} else if (fmt == MIPS_OPCODE_F_CFC1 || fmt == MIPS_OPCODE_F_CTC1
|| fmt == MIPS_OPCODE_F_MFC1 || fmt == MIPS_OPCODE_F_MTC1
|| fmt == MIPS_OPCODE_DMFC2 || fmt == MIPS_OPCODE_DMTC2) {
dim[1] = fmt;
} else if (jajo == 0x3) {
dim[1] = kupa;
dim[2] = fmt;
} else {
dim[1] = tmp;
dim[2] = fmt;
}
} while(0);
break;
case MIPS_OPCODE_COP2:
do {
u_int tmp = (converted >> 25) & 0x1;
if (tmp)
dim[1] = tmp;
else {
dim[1] = (converted >> 21) & 0x1F;
if (dim[1] == MIPS_OPCODE_BCC2)
dim[2] = (converted >> 16) & 0x3;
}
} while(0);
break;
case MIPS_OPCODE_COP1X:
dim[1] = converted & 0x3F;
break;
}
fetch = aspect_vectors_select(vec,dim);
return (fetch(ins,(u_char *)&converted,len,proc));
}
/**
* @fn int asm_init_mips(asm_processor *proc)
* @brief MIPS initialization function to disassemble.
*
* This function fill asm_processor structure and call
* for register vectors.
*
* @param proc Pointer to a asm_processor structure.
* @return Always 1
*/
int asm_init_mips(asm_processor *proc)
{
proc->fetch = asm_fetch_mips;
proc->display_handle = asm_mips_display_instr;
proc->internals = 0;
proc->type = ASM_PROC_MIPS;
proc->instr_table = (char **)e_mips_instrs;
aspect_init();
asm_arch_register(proc, 0);
return (1);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_sbb_al_ib.c
/**
* @file libasm/src/arch/ia32/handlers/op_sbb_al_ib.c
*
* @ingroup IA32_instrs
** $Id: op_sbb_al_ib.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_sbb_al_ib" opcode="0x1c"/>
*/
int op_sbb_al_ib(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->instr = ASM_SBB;
new->len += 1;
new->ptr_instr = opcode;
new->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG | ASM_TYPE_READFLAG;
new->flagsread = ASM_FLAG_CF;
new->flagswritten = ASM_FLAG_AF | ASM_FLAG_CF | ASM_FLAG_PF |
ASM_FLAG_OF | ASM_FLAG_SF | ASM_FLAG_ZF;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_AL,
ASM_REGSET_R8));
new->len += asm_operand_fetch(&new->op[1], opcode + 1,
ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new);
new->op[0].size = new->op[1].size = ASM_OSIZE_BYTE;
new->op[0].content = ASM_OP_BASE | ASM_OP_FIXED;
new->op[0].ptr = opcode;
new->op[0].len = 0;
new->op[0].baser = ASM_REG_AL;
new->op[0].regset = ASM_REGSET_R8;
new->len += asm_operand_fetch(&new->op[1], opcode + 1,
ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_esc6.c
/*
** $Id: op_esc6.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_esc6" opcode="0xde"/>
*/
int op_esc6(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
struct s_modrm *modrm;
new->ptr_instr = opcode;
modrm = (struct s_modrm *) opcode + 1;
new->len += 1;
if (modrm->mod <= 2) {
switch(modrm->r) {
case 0:
new->instr = ASM_FIADD;
break;
case 1:
new->instr = ASM_FIMUL;
break;
case 2:
new->instr = ASM_FICOM;
break;
case 3:
new->instr = ASM_FICOMP;
break;
case 4:
new->instr = ASM_FISUB;
break;
case 5:
new->instr = ASM_FISUBR;
break;
case 6:
new->instr = ASM_FIDIV;
break;
case 7:
new->instr = ASM_FIDIVR;
break;
}
} else {
switch(modrm->r) {
case 0: new->instr = ASM_FADDP; break;
case 1:
new->instr = ASM_FMULP;
break;
case 2:
new->instr = ASM_FCOMPS;
break;
case 3: new->instr = ASM_FCOMPP;
break;
case 4: new->instr = ASM_FSUBP;
break;
case 5: new->instr = ASM_FSUBRP;
break;
case 6:
switch(modrm->m) {
case 3: case 5: case 2: case 4: case 6: case 1:
new->instr = ASM_FDIVP; break;
default: case 0: new->instr = ASM_FDIVP; break;
}
break;
case 7:
switch(modrm->m) {
case 3: new->instr = ASM_FDIVR; break;
default: new->instr = ASM_FDIV; break;
}
break;
}
}
if (!(*(opcode + 1) == 0xd9)) {
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_FPU | ASM_OP_BASE | ASM_OP_SCALE,
modrm->m,
0));
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new);
#endif
new->op[0].content = ASM_OP_FPU | ASM_OP_BASE | ASM_OP_SCALE;
new->op[0].len = 1;
new->op[0].scale = modrm->m;
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_FIXED, new);
#endif
new->op[1].content = ASM_OP_FPU | ASM_OP_BASE;
new->op[1].len = 0;
#else
new->op[0].type = ASM_OTYPE_FIXED;
new->op[0].content = ASM_OP_FPU | ASM_OP_BASE | ASM_OP_SCALE;
new->op[0].len = 1;
new->op[0].scale = modrm->m;
new->op[1].type = ASM_OTYPE_FIXED;
new->op[1].content = ASM_OP_FPU | ASM_OP_BASE;
new->op[1].len = 0;
#endif
} else
new->len++;
#if LIBASM_USE_OPERAND
#else
if (new->op[0].type)
new->len += new->op[0].len;
#endif
return (new->len);
}
<file_sep>/src/libasm/src/build.c
/**
* @file libasm/src/build.c
* @ingroup libasm
* @brief Contains latest build date.
* $Id: build.c 1397 2009-09-13 02:19:08Z may $
*/
/**
* State of the project.
*
* Libasm developpement is not regular. Some time is spent on documenting it.
* Some time to fix bugs. Some time to implement.
*
* Currently, there are two architectures supported :
* -
*
*
*
*/
#include <libasm.h>
/**
* @brief Return build date.
* @return build date.
*/
char *asm_get_build(void)
{
return (__DATE__);
}
/**
*
*/
char *g_asm_features [] =
{
0
};
/**
*
*/
char **asm_get_features()
{
return g_asm_features;
}
<file_sep>/src/libasm/src/operand.c
/**
* @file libasm/src/operand.c
* @ingroup libasm
* @brief Contains arch-independent generic operand manipulation functions.
*
* Author : <<EMAIL>>
* $Id: operand.c 1397 2009-09-13 02:19:08Z may $
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Return immediate part of the operand
* @param ins Pointer to instruction
* @param num Number of the operand. (SOURCE/DEST/OPT)
* @param opt Optionnal. May be the virtual address of instruction
* @param valptr Reference to store immediate content
*/
int asm_operand_get_immediate(asm_instr *ins, int num, int opt, void *valptr)
{
asm_operand *op;
char *c;
short *s;
int *i;
switch(num)
{
case 1: op = &ins->op[0]; break;
case 2: op = &ins->op[1]; break;
case 3: op = &ins->op[2]; break;
default:
return (-1);
}
memset(valptr, 0, 4);
//if(asm_config_get_endian() == CONFIG_ASM_BIG_ENDIAN) {
// imm = swap32(op->imm);
// memcpy(valptr, &imm, 4);
//} else {
// memcpy(valptr, &op->imm, 4);
//}
/**
* This is pseudo dead code
* it was about
*
*/
switch(op->type)
{
case ASM_OTYPE_VALUE:
switch(op->size)
{
case ASM_OSIZE_BYTE: memcpy(valptr, &op->imm, 1); break;
case ASM_OSIZE_WORD: memcpy(valptr, &op->imm, 2); break;
case ASM_OSIZE_DWORD: memcpy(valptr, &op->imm, 4); break;
case ASM_OSIZE_VECTOR: memcpy(valptr, &op->imm, 4); break;
default: return (-1);
}
break;
case ASM_OTYPE_JUMP:
switch(op->size)
{
case ASM_OSIZE_BYTE: c = (char *)op->ptr; opt = opt + *c; break;
case ASM_OSIZE_WORD: s = (short *)op->ptr; opt += *s; break;
case ASM_OSIZE_DWORD: i = (int *) op->ptr; opt += *i; break;
case ASM_OSIZE_VECTOR: i = (int *) op->ptr; opt += *i; break;
}
memcpy(valptr, &opt, 4);
break;
}
return (1);
}
/**
* Get base register of operand
* asm_operand must have ASM_OP_BASE defined
* @param ins Pointer to instruction
* @param num Number of the operand
* @param opt Optionnal parameter, may be virtual address
* @param valptr Reference to store the content of the register
* @return -1 on error,
*/
int asm_operand_get_basereg(asm_instr *ins, int num, int opt, void *valptr)
{
int *val;
val = (int *) valptr;
switch(num)
{
case 1:
if (ins->op[0].type && (ins->op[0].content & ASM_OP_BASE))
*val = ins->op[0].baser;
else
return (-1);
break;
case 2:
if (ins->op[1].type && (ins->op[1].content & ASM_OP_BASE))
*val = ins->op[1].baser;
else
return (-1);
break;
case 3:
if (ins->op[2].type && (ins->op[2].content & ASM_OP_BASE))
*val = ins->op[2].baser;
else
return (-1);
break;
default:
return (-1);
}
return (1);
}
/**
* Get index register field of operand
* asm_operand must have ASM_OP_INDEX
* @return -1 on errorreturn -1 on error
*/
int asm_operand_get_indexreg(asm_instr *ins, int num, int opt, void *valptr)
{
int *val;
val = (int *) valptr;
switch(num)
{
case 1:
if (ins->op[0].type && (ins->op[0].content & ASM_OP_INDEX))
*val = ins->op[0].indexr;
else
return (-1);
break;
case 2:
if (ins->op[1].type && (ins->op[1].content & ASM_OP_INDEX))
*val = ins->op[1].indexr;
else
return (-1);
break;
case 3:
if (ins->op[2].type && (ins->op[2].content & ASM_OP_INDEX))
*val = ins->op[2].indexr;
else
return (-1);
break;
default:
return (-1);
}
return (1);
}
/**
* Get scale field of operand
* asn_operand must have ASM_OP_SCALE type set
* @return -1 on error, 1 on success
*/
int asm_operand_get_scale(asm_instr *ins, int num, int opt, void *valptr)
{
int *val;
val = (int *) valptr;
switch(num)
{
case 1:
if (ins->op[0].type && (ins->op[0].content & ASM_OP_SCALE))
*val = ins->op[0].scale;
else
return (-1);
break;
case 2:
if (ins->op[1].type && (ins->op[1].content & ASM_OP_SCALE))
*val = ins->op[1].scale;
else
return (-1);
break;
case 3:
if (ins->op[2].type && (ins->op[2].content & ASM_OP_SCALE))
*val = ins->op[2].scale;
else
return (-1);
break;
default:
return (-1);
}
return (1);
}
/**
* Set base register of operand
* @param ins
* @param num
* @param opt
* @param valptr
* @return -1 on error, 1 on success
*/
int asm_operand_set_basereg(asm_instr *ins, int num, int opt, void *valptr)
{
asm_modrm *modrm;
asm_operand *op;
int *val;
return (-1);
if (!op->ptr) {
fprintf(stderr, "no pointer available");
}
else
{
val = (int *) valptr;
modrm = (asm_modrm *) op->ptr;
switch(op->type)
{
case ASM_OTYPE_OPMOD:
modrm->m = *val;
break;
case ASM_OTYPE_CONTROL:
modrm->m = *val;
break;
case ASM_OTYPE_DEBUG:
modrm->m = *val;
break;
case ASM_OTYPE_ENCODED:
modrm->r = *val;
break;
case ASM_OTYPE_GENERAL:
modrm->r = *val;
break;
case ASM_OTYPE_REGISTER:
modrm->m = *val;
break;
default:
return (0);
}
/*
if ((op->type & ASM_OP_BASE) &&
((ASM_OP_INDEX & op->type) || (ASM_OP_SCALE))) {
*/
}
return (1);
}
/**
* Set index register of operand
* @param ins
* @param num
* @param opt
* @param valptr
* @return -1 on error, 1 on success
*/
int asm_operand_set_indexreg(asm_instr *ins, int num, int opt, void *valptr)
{
int *val;
struct s_sidbyte *sidbyte;
asm_operand *op=NULL;
//return (-1);
if (op->content & ASM_OP_INDEX) {
sidbyte = (struct s_sidbyte *) (op->ptr + 1);
val = (int *) valptr;
switch(op->type) {
case ASM_OTYPE_ENCODED:
case ASM_OTYPE_MEMORY:
if (!op->ptr)
fprintf(stderr, "ptr field NULL, cannot set index reg\n");
else
sidbyte->index = *val;
break;
default:
fprintf(stderr, "unsupported operand type to set index register\n");
}
}
return (-1);
}
/**
* Set scale field of operand
* @param ins
* @param num
* @param opt
* @param valptr
* @return -1 on error, 1 on success
*/
int asm_operand_set_scale(asm_instr *ins, int num,
int opt, void *valptr) {
int *val;
struct s_sidbyte *sidbyte;
asm_operand *op;
return (-1);
op = &ins->op[0];
val = (int *) valptr;
if (op && op->type & ASM_OP_SCALE) {
if (op->type & ASM_OP_FPU)
sidbyte->sid = *val;
else
switch(*val) {
case 1:
sidbyte->sid = 0; break;
case 2:
sidbyte->sid = 1; break;
case 4:
sidbyte->sid = 2; break;
case 8:
sidbyte->sid = 3; break;
default:
return (0);
}
}
return (1);
}
/**
*
*
*
*/
int asm_operand_get_type(asm_instr *ins, int num, int opt, void *valptr) {
int *val;
if ((val = valptr))
switch(num)
{
case 1:
return (*val = ins->op[0].type);
case 2:
return (*val = ins->op[1].type);
case 3:
return (*val = ins->op[2].type);
}
return (-1);
}
int asm_operand_get_size(asm_instr *ins, int num, int opt, void *valptr) {
int *val, to_ret;
val = (int *) valptr;
switch(num)
{
case 1:
*val = ins->op[0].size;
to_ret = 1;
break;
case 2:
*val = ins->op[1].size;
to_ret = 1;
break;
case 3:
*val = ins->op[2].size;
to_ret = 1;
break;
default:
to_ret = -1;
}
return (to_ret);
}
int asm_operand_get_len(asm_instr *ins, int num, int opt, void *valptr) {
switch(num)
{
case 1:
return (ins->op[0].len);
case 2:
return (ins->op[1].len);
case 3:
return (ins->op[2].len);
default:
return (0);
}
}
/**
* Return number of operands
* @param ins Pointer to instruction *
*/
int asm_operand_get_count(asm_instr *ins, int num, int opt, void *valptr)
{
if (!ins)
return (-1);
num = 0;
if (ins->op[0].content)
num++;
if (ins->op[1].content)
num++;
if (ins->op[2].content)
num++;
return (num);
}
/**
* Return wether operand if a reference or not.
* @param op Pointer to operand structure.
* @return True if operand is a reference, or False.
*/
int asm_operand_is_reference(asm_operand *op)
{
return(op->content & ASM_OP_REFERENCE);
}
<file_sep>/src/libasm/src/arch/ia32/operand_handlers/asm_operand_fetch_fixed.c
/**
* @file libasm/src/arch/ia32/operand_handlers/asm_operand_fetch_fixed.c
*
* @ingroup IA32_operands
* $Id: asm_operand_fetch_fixed.c 1397 2009-09-13 02:19:08Z may $
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @todo
* Implement optional parameter for fixed operand fetching.
*/
/**
*
* @ingroup IA32_operands
* Decode data for operand type ASM_OTYPE_YDEST
* @param operand Pointer to operand structure to fill.
* @param opcode Pointer to operand data
* @param otype
* @param ins Pointer to instruction structure.
* @return Operand length
*/
#if WIP
int asm_operand_fetch_fixed(asm_operand *operand, u_char *opcode, int otype,
asm_instr *ins, int opt)
#else
int asm_operand_fetch_fixed(asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins)
#endif
{
operand->type = ASM_OTYPE_FIXED;
#if WIP
/**
* @todo extract fields.
operand->content = asm_fixed_unpack_content();
operand->regset = asm_fixed_unpack_regset();
operand->
*/
#endif
return (0);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_pop_reg.c
/*
** $Id: op_pop_reg.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_pop_reg" opcode="0x58"/>
<instruction func="op_pop_reg" opcode="0x59"/>
<instruction func="op_pop_reg" opcode="0x5a"/>
<instruction func="op_pop_reg" opcode="0x5b"/>
<instruction func="op_pop_reg" opcode="0x5c"/>
<instruction func="op_pop_reg" opcode="0x5d"/>
<instruction func="op_pop_reg" opcode="0x5e"/>
<instruction func="op_pop_reg" opcode="0x5f"/>
*/
int op_pop_reg(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->ptr_instr = opcode;
new->len += 1;
new->instr = ASM_POP;
new->type = ASM_TYPE_TOUCHSP | ASM_TYPE_ASSIGN | ASM_TYPE_LOAD;
new->spdiff = 4;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_OPMOD, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_OPMOD, new);
#endif
if (new->op[0].baser == ASM_REG_EBP)
new->type |= ASM_TYPE_EPILOG;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_group7.c
/*
** $Id: op_group7.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
int op_group7(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
new->len += 1;
modrm = (struct s_modrm *) opcode + 1;
switch(modrm->r)
{
case 0:
new->instr = ASM_SGDT;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#else
new->op[0].type = ASM_OTYPE_ENCODED;
operand_rmv(&new->op[0], opcode + 1, len - 1, proc);
new->len += new->op[0].len;
#endif
break;
case 1:
new->instr = ASM_SIDT;
break;
case 2:
new->instr = ASM_LGDT;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#else
new->op[0].type = ASM_OTYPE_ENCODED;
operand_rmv(&new->op[0], opcode + 1, len - 1, proc);
new->len += new->op[0].len;
#endif
break;
case 3:
new->instr = ASM_LIDT;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#else
new->op[0].type = ASM_OTYPE_ENCODED;
operand_rmv(&new->op[0], opcode + 1, len - 1, proc);
new->len += new->op[0].len;
#endif
break;
case 4:
break;
case 5:
new->instr = ASM_BAD;
break;
case 6:
break;
case 7:
break;
}
return (new->len);
}
<file_sep>/src/libasm/src/arch/mips/handlers/asm_mips_mfc0.c
/**
* @file libasm/src/arch/mips/handlers/asm_mips_mfc0.c
** @ingroup MIPS_instrs
*/
/* Adam 'pi3' Zabrocki */
/* <NAME> - 2007 */
#include <libasm.h>
/* MFC0 rt, rd */
int asm_mips_mfc0(asm_instr *ins, u_char *buf, u_int len,
asm_processor *proc)
{
struct s_mips_decode_priv temp;
ins->instr = ASM_MIPS_MFC0;
ins->type = ASM_TYPE_ARCH | ASM_TYPE_ASSIGN;
mips_convert_format_priv(&temp, buf);
ins->op[0].baser = temp.rt;
asm_mips_operand_fetch(&ins->op[0], buf, ASM_MIPS_OTYPE_REGISTER, ins);
ins->op[1].baser = temp.rd;
asm_mips_operand_fetch(&ins->op[1], buf, ASM_MIPS_OTYPE_REGISTER, ins);
/* Exceptions: Coprocessor Unusable, Reserved Instruction */
return 4;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_esc4.c
/**
* $Id: op_esc4.c 1397 2009-09-13 02:19:08Z may $
* @file libasm/src/arch/ia32/handlers/op_esc4.c
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler of FPU instruction group esc4 opcode 0xdc
<instruction func="op_esc4" opcode="0xdc"/>
*/
int op_esc4(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
struct s_modrm *modrm;
new->ptr_instr = opcode;
modrm = (struct s_modrm *) opcode + 1;
new->len += 1;
switch(modrm->r)
{
case 0:
new->instr = ASM_FADD;
break;
case 1:
new->instr = ASM_FMUL;
break;
case 2:
new->instr= ASM_FCOM;
break;
case 3:
new->instr = ASM_FCOMP;
break;
case 4:
new->instr = ASM_FSUB;
break;
case 5:
new->instr = ASM_FSUBR;
break;
case 6:
new->instr = ASM_FDIV;
break;
case 7:
new->instr = ASM_FDIVR;
break;
}
if (modrm->mod == 3)
{
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_FPU | ASM_OP_BASE | ASM_OP_SCALE,
modrm->m, 0));
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new);
#endif
new->op[0].type = ASM_OTYPE_FIXED;
new->op[0].content = ASM_OP_FPU | ASM_OP_BASE | ASM_OP_SCALE;
new->op[0].len = 1;
new->op[0].scale = modrm->m;
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_FIXED, 0,
asm_fixed_pack(0, ASM_OP_FPU | ASM_OP_BASE, 0,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_FIXED, new);
#endif
new->op[1].type = ASM_OTYPE_FIXED;
new->op[1].content = ASM_OP_FPU | ASM_OP_BASE;
new->len += 1;
#else
new->op[0].type = ASM_OTYPE_FIXED;
new->op[0].content = ASM_OP_FPU | ASM_OP_BASE | ASM_OP_SCALE;
new->op[0].len = 1;
new->op[0].scale = modrm->m;
new->op[1].type = ASM_OTYPE_FIXED;
new->op[1].content = ASM_OP_FPU | ASM_OP_BASE;
#endif
}
else
{
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#else
new->op[0].type = ASM_OTYPE_FIXED;
operand_rmv(&new->op[0], opcode + 1, len - 1, proc);
#endif
}
#if LIBASM_USE_OPERAND_VECTOR
#else
if (new->op[0].type)
new->len += new->op[0].len;
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_xstorenrg.c
/*
** $Id: i386_xstorenrg.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<i386 func="i386_shld_rmv_rv_cl" opcode="0xa7"/>
*/
int i386_xstorenrg(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
switch(*(opcode + 1))
{
case 0xc0: new->instr = ASM_XSTORERNG; break;
case 0xd0: new->instr = ASM_XCRYPTCBC; break;
case 0xe0: new->instr = ASM_XCRYPTCFB; break;
case 0xe8: new->instr = ASM_XCRYPTOFB; break;
default: new->instr = ASM_NONE;
}
new->len += 2;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_esc1.c
/**
* @file libasm/src/arch/ia32/handlers/op_esc1.c
*
* @ingroup IA32_instrs
* $Id: op_esc1.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for fpu instruction group 1, opcode 0xd9
* @param new Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Length of instruction.
*/
int op_esc1(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode + 1;
new->ptr_instr = opcode;
new->len += 1;
if (modrm->mod == 3)
{
switch(modrm->r)
{
case 0:
new->instr = ASM_FLD;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new);
#endif
new->len += 1;
new->op[0].content = ASM_OP_FPU | ASM_OP_SCALE | ASM_OP_BASE;
new->op[0].len = 1;
new->op[0].scale = modrm->m;
#else
new->op[0].type = ASM_OTYPE_FIXED;
new->op[0].content = ASM_OP_FPU | ASM_OP_SCALE | ASM_OP_BASE;
new->op[0].len = 1;
new->op[0].scale = modrm->m;
#endif
break;
case 1:
new->instr = ASM_FXCH;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new);
#endif
new->len += 1;
new->op[0].type = ASM_OTYPE_FIXED;
new->op[0].len = 1;
new->op[0].content = ASM_OP_FPU | ASM_OP_SCALE | ASM_OP_BASE;
new->op[0].scale = modrm->m;
#else
new->op[0].type = ASM_OTYPE_FIXED;
new->op[0].len = 1;
new->op[0].content = ASM_OP_FPU | ASM_OP_SCALE | ASM_OP_BASE;
new->op[0].scale = modrm->m;
#endif
break;
case 2:
new->instr = ASM_FNOP; break;
case 4:
new->len += 1;
switch(modrm->m) {
case 0: new->instr = ASM_FCHS; break;
case 1: new->instr = ASM_FABS; break;
case 4: new->instr = ASM_FTST; break;
case 5: new->instr = ASM_FXAM; break;
default: new->instr = ASM_BAD; break;
}
break;
case 5:
new->len += 1;
switch(modrm->m) {
case 0: new->instr = ASM_FLD1; break;
case 1: new->instr = ASM_FLDL2T; break;
case 2: new->instr = ASM_FLDL2E; break;
case 3: new->instr = ASM_FLDPI; break;
case 4: new->instr = ASM_FLDLG2; break;
case 5: new->instr = ASM_FLDLN2; break;
case 6: new->instr = ASM_FLDZ; break;
}
break;
case 6:
new->len += 1;
switch(modrm->m) {
case 0: new->instr = ASM_F2XM1; break;
case 1: new->instr = ASM_FYL2X; break;
case 2: new->instr = ASM_FPTAN; break;
case 3: new->instr = ASM_FPATAN; break;
case 4: new->instr = ASM_FXTRACT; break;
//case 5: new->instr = ASM_FPREM1; break;
case 6: new->instr = ASM_FDECSTP; break;
case 7: new->instr = ASM_FINCSTP; break;
}
break;
case 7:
new->len += 1;
switch(modrm->m) {
case 0: new->instr = ASM_FPREM; break;
case 1: new->instr = ASM_FYL2XP1; break;
case 2: new->instr = ASM_FSQRT; break;
case 3: new->instr = ASM_FSINCOS; break;
case 4: new->instr = ASM_FRNDINT; break;
case 5: new->instr = ASM_FSCALE; break;
//case 6: new->instr = ASM_SIN; break;
//case 7: new->instr = ASM_COS; break;
}
break;
}
}
else /* modrm != 3 */
{
switch(modrm->r)
{
case 0:
new->instr = ASM_FLD;
break;
case 1:
new->instr = ASM_BAD;
break;
case 2:
new->instr = ASM_FST;
break;
case 3:
new->instr = ASM_FSTP;
break;
case 4:
new->instr = ASM_FLDENV;
break;
case 5:
new->instr = ASM_FLDCW;
break;
case 6:
if (!(new->prefix & ASM_PREFIX_FWAIT))
new->instr = ASM_FNSTENV;
else
new->instr = ASM_FSTENV;
break;
case 7:
if (!(new->prefix & ASM_PREFIX_FWAIT))
new->instr = ASM_FNSTCW;
else
new->instr = ASM_FSTCW;
break;
}
}
if (modrm->mod < 3)
{
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#else
new->op[0].type = ASM_OTYPE_ENCODED;
operand_rmv(&new->op[0], opcode + 1, len - 1, proc);
#endif
}
#if LIBASM_USE_OPERAND_VECTOR
#else
if (new->op[0].type)
new->len += new->op[0].len;
else
new->len += 1;
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_cpuid.c
/*
** $Id: i386_cpuid.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
Opcode : 0x0f 0xa2
Instruction : CPUID
*/
int i386_cpuid(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->instr = ASM_CPUID;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_cmova.c
/*
** $Id: i386_cmova.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<i386 func="i386_cmova" opcode="0x47"/>
*/
int i386_cmova(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->len += 1;
new->instr = ASM_CMOVA;
new->type = ASM_TYPE_ASSIGN | ASM_TYPE_COMPARISON;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_GENERAL, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_GENERAL, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
return (new->len);
}
<file_sep>/src/fastcrc.h
#ifndef _MG_CRC_H
#define _MG_CRC_H
#include <stdio.h>
#define MG_CRC_24_ARITHMETIC_CCITT 1
#define MG_CRC_24_ARITHMETIC 2
#define MG_CRC_32_ARITHMETIC_CCITT 3
#define MG_CRC_32_ARITHMETIC 4
/* 0xbba1b5 = 1'1011'1011'1010'0001'1011'0101b
= x24+x23+x21+x20+x19+x17+x16+x15+x13+x8+x7+x5+x4+x2+1 */
#define MG_CRC_24_CCITT (0x00ddd0da)
#define MG_CRC_24 (0x00ad85dd)
/* 0x04c11db7 = 1'0000'0100'1100'0001'0001'1101'1011'0111b
= x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1 */
#define MG_CRC_32_CCITT (0x04c11db7)
#define MG_CRC_32 (0xedb88320)
#define bswap_16(x) (((x) & 0x00ff) << 8 | ((x) & 0xff00) >> 8)
#define bswap_32(x) ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \
(((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))
extern unsigned int MG_CRC_Table[256];
unsigned int MG_Compute_CRC24(unsigned int crc,unsigned char *bufptr,int len);
unsigned int MG_Compute_CRC24_CCITT(unsigned int crc,unsigned char *bufptr,int len);
unsigned int MG_Compute_CRC32(unsigned int crc,unsigned char *bufptr,int len);
unsigned int MG_Compute_CRC32_CCITT(unsigned int crc,unsigned char *bufptr,int len);
void MG_Setup_CRC_Table(unsigned char type);
unsigned int MG_Table_Driven_CRC(register unsigned int crc,register unsigned char *bufptr,register int len, unsigned char type);
void MG_FCS_Coder(unsigned char *pucInData,int len,unsigned char type);
int MG_FCS_Decoder(unsigned char *pucInData,int len, unsigned char type);
#endif
<file_sep>/src/libasm/src/vectors.c
/**
* $Id: vectors.c 1409 2010-05-11 14:03:41Z figueredo $
* @file libasm/src/vectors.c
* @ingroup libasm
* @brief Initialization the instruction and opcode vectors.
*/
#include <libasm.h>
/**
* @brief Default handler for the disasm vector.
* @ingroup libasm
*
* This handler does nothing, simply returning -1.
* @param ins Pointer to instruction structure to fill
* @param opcode Pointer to buffer to disassemble
* @param len Length of the buffer to disassemble
* @param proc Pointer to the processor structure
* @return -1
*/
#if 0 && WIP
int asm_fetch_default(asm_instr *ins, u_char *opcode, u_int len,
asm_processor *proc, int opt)
{
int to_ret;
LIBASM_PROFILE_FIN();
#if LIBASM_ENABLE_SPARC
if (proc->type == ASM_PROC_SPARC)
to_ret = asm_sparc_illegal(ins, opcode, len, proc);
else
#endif
to_ret = -1;
LIBASM_PROFILE_FOUT(to_ret);
}
#else
int asm_fetch_default(asm_instr *ins, u_char *opcode, u_int len,
asm_processor *proc)
{
int to_ret;
LIBASM_PROFILE_FIN();
switch (proc->type)
{
#if LIBASM_ENABLE_SPARC
case ASM_PROC_SPARC:
to_ret = asm_sparc_illegal(ins, opcode, len, proc);
break;
#endif
#if LIBASM_ENABLE_ARM
case ASM_PROC_ARM:
to_ret = asm_arm_illegal(ins, opcode, len, proc);
break;
#endif
default:
to_ret = -1;
}
LIBASM_PROFILE_FOUT(to_ret);
}
#endif
/**
* @brief Default handler for the operand vector
* This handler does nothing, simply returning -1
* @param ins Pointer to instruction structure to fill
* @param opcode Pointer to buffer to disassemble
* @param len Length of the buffer to disassemble
* @param proc Pointer to the processor structure
* @return -1
*
*/
#if WIP
int asm_operand_fetch_default(asm_operand *op, u_char *opcode, int otype,
asm_instr *ins, int opt)
{
LIBASM_PROFILE_FIN();
LIBASM_PROFILE_FOUT(-1);
}
#else
int asm_operand_fetch_default(asm_operand *op, u_char *opcode, int otype,
asm_instr *ins)
{
LIBASM_PROFILE_FIN();
LIBASM_PROFILE_FOUT(-1);
}
#endif
/**
* @brief Return handler associated with an opcode
* @param vector_name Name of the vector.
* @param opcode
*
*/
void *asm_opcode_fetch(const char *vector_name, int opcode)
{
vector_t *vec;
u_int dim[1];
void *fcn_ptr;
vec = aspect_vector_get((char *) vector_name);
dim[0] = opcode;
fcn_ptr = aspect_vectors_select(vec, dim);
return (fcn_ptr);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_bpr.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_bpr.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_bpr.c 1413 2010-05-21 03:41:25Z figueredo $
**
*/
#include "libasm.h"
int
asm_sparc_bpr(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_rbranch opcoder;
struct s_asm_proc_sparc *inter;
sparc_convert_rbranch(&opcoder, buf);
inter = proc->internals;
ins->instr = inter->brcc_table[opcoder.rcond];
ins->type = ASM_TYPE_BRANCH | ASM_TYPE_CONDCONTROL;
ins->nb_op = 2;
ins->op[0].imm = opcoder.d16;
ins->op[1].baser = opcoder.rs1;
ins->annul = opcoder.a;
ins->prediction = opcoder.p;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_DISPLACEMENT, ins);
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_REGISTER, ins);
return 4;
}
<file_sep>/src/libasm/src/register.c
/**
* $Id: register.c 1397 2009-09-13 02:19:08Z may $
* @file libasm/src/register.c
* @ingroup libasm
* @brief Registration of instruction and operand handlers.
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Wrapper for Architecture initialization.
*
* This function create an abstraction to enable partial building
* of libasm depending on needs.
* @param proc Pointer to asm_processor structure.
* @param arch Architecture: ASM_PROC_IA32
*/
int asm_init_arch(asm_processor *proc, int arch)
{
switch(arch)
{
#if LIBASM_ENABLE_IA32
//#warning Enabling IA32 support
case ASM_PROC_IA32:
return asm_init_ia32(proc);
break;
#endif
#if LIBASM_ENABLE_SPARC
//#warning Enabling SPARC support
case ASM_PROC_SPARC:
return asm_init_sparc(proc);
break;
#endif
#if LIBASM_ENABLE_MIPS
//#warning Enabling MIPS support
case ASM_PROC_MIPS:
return asm_init_mips(proc);
break;
#endif
#if LIBASM_ENABLE_ARM
//#warning Enabling ARM support
case ASM_PROC_ARM:
return asm_init_arm(proc);
break;
#endif
default:
return (0);
}
return (0);
}
/**
* Initialize instruction level vector.
* @param proc Pointer to processor structure
* @param machine Currently not used.
* @return 1 on success, 0 on error
*/
int asm_arch_register(asm_processor *proc, int machine)
{
int to_ret;
LIBASM_PROFILE_FIN();
to_ret = 0;
#if LIBASM_ENABLE_IA32
if (proc->type == ASM_PROC_IA32)
{
asm_register_ia32(proc);
to_ret = 1;
}
#endif
#if LIBASM_ENABLE_SPARC
if (proc->type == ASM_PROC_SPARC)
{
asm_register_sparc();
to_ret = 1;
}
#endif
#if LIBASM_ENABLE_MIPS
if (proc->type == ASM_PROC_MIPS)
{
asm_register_mips();
to_ret = 1;
}
#endif
#if LIBASM_ENABLE_ARM
if (proc->type == ASM_PROC_ARM)
{
asm_register_arm();
to_ret = 1;
}
#endif
//
// Add your architecture handler here.
//
LIBASM_PROFILE_FOUT(to_ret);
}
/**
* @brief Create a new operand vector of dimension 1 and size <size>
* @param vector_name Name of the vector
* @param size Size of the vector
* @return 1 on success, or 0 on error.
*/
int asm_register_operand_create(const char *vector_name, int size)
{
u_int *dims;
char **dimstr;
dims = malloc(1 * sizeof (u_int));
if (!dims)
{
return 0;
}
dimstr = malloc(1 * sizeof (char *));
if (!dimstr)
{
return 0;
}
dims[0] = size;
dimstr[0] = "operand";
aspect_register_vector((char *)vector_name, asm_operand_fetch_default,
dims, dimstr, 1, ASPECT_TYPE_CADDR);
return (1);
}
/**
* Generic function to register operand handlers.
* @param vector_name name of the vector to store the handlers (arch specific)
* @param operand_type Type of the operand to register
* @param fcn Function pointer.
* @return 1 on success, 0 on error.
*/
int asm_register_operand(const char *vector_name, int operand_type,
unsigned long fcn)
{
vector_t *vec;
u_int dim[1];
LIBASM_PROFILE_FIN();
vec = aspect_vector_get((char *)vector_name);
dim[0] = operand_type;
aspect_vectors_insert(vec, dim, fcn);
LIBASM_PROFILE_FOUT(1);
}
/**
*
*
*
*/
int asm_register_opcode_create(const char *vector_name, int size)
{
u_int *dims;
char **dimstr;
dims = malloc(1 * sizeof (u_int));
if (!dims)
{
return 0;
}
dimstr = malloc(1 * sizeof (char *));
if (!dimstr)
{
return 0;
}
dims[0] = size;
dimstr[0] = "opcode";
aspect_register_vector((char *) vector_name, asm_operand_fetch_default,
dims, dimstr, 1, ASPECT_TYPE_CADDR);
return (1);
}
/**
*
*
*
*
*
*/
int asm_register_opcode(const char *vector_name, int opcode, unsigned long fcn)
{
vector_t *vec;
u_int dim[1];
int to_ret;
LIBASM_PROFILE_FIN();
to_ret = 0;
if ((vec = aspect_vector_get((char *)vector_name)) != NULL)
{
dim[0] = opcode;
aspect_vectors_insert(vec, dim, fcn);
to_ret = 1;
}
LIBASM_PROFILE_FOUT(to_ret);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_shift_rmv_cl.c
/**
* @file libasm/src/arch/ia32/handlers/op_shift_rmv_cl.c
*
* @ingroup IA32_instrs
** $Id: op_shift_rmv_cl.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_shift_rmv_cl" opcode="0xd3"/>
*/
int op_shift_rmv_cl(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
new->ptr_instr = opcode;
modrm = (struct s_modrm *) opcode + 1;
new->len += 1;
new->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_CF | ASM_FLAG_OF;
switch(modrm->r) {
case 0:
new->instr = ASM_ROL;
break;
case 5:
new->instr = ASM_SHR;
new->flagswritten |= ASM_FLAG_PF | ASM_FLAG_ZF | ASM_FLAG_SF;
break;
case 4:
new->instr = ASM_SHL;
new->flagswritten |= ASM_FLAG_PF | ASM_FLAG_ZF | ASM_FLAG_SF;
break;
case 7:
new->instr = ASM_SAR;
new->flagswritten |= ASM_FLAG_PF | ASM_FLAG_ZF | ASM_FLAG_SF;
break;
default:
new->instr = ASM_BAD;
}
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1,
ASM_OTYPE_ENCODED, new, 0);
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_CL,
ASM_REGSET_R8));
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1,
ASM_OTYPE_ENCODED, new);
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_FIXED, new);
new->op[1].content = ASM_OP_BASE | ASM_OP_FIXED;
new->op[1].regset = ASM_REGSET_R8;
new->op[1].baser = ASM_REG_CL;
new->op[1].len = 0;
new->op[1].ptr = 0;
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_iret.c
/**
* @file libasm/src/arch/ia32/handlers/op_iret.c
*
* @ingroup IA32_instrs
* $Id: op_iret.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
*
* <instruction opcode="0xcf" func="op_iret"/>
*/
int op_iret(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->ptr_instr = opcode;
new->len += 1;
new->instr = ASM_IRET;
new->type = ASM_TYPE_INT | ASM_TYPE_TOUCHSP | ASM_TYPE_RETPROC |
ASM_TYPE_READFLAG;
new->flagsread = ASM_FLAG_NT | ASM_FLAG_VM;
return (new->len);
}
<file_sep>/src/libasm/src/arch/sparc/sparc_convert.c
/**
* @file libasm/src/arch/sparc/sparc_convert.c
** @ingroup sparc
*/
/*
** sparc_convert.c for in /hate/home/hate/code/libasm
**
** Made by #!HATE#@!
** Login <<EMAIL>>
**
** Started on Mon Apr 25 01:01:26 2005 #!HATE#@!
** Last update Tue Jun 14 09:18:36 2005 #!HATE#@!
**
** $Id: sparc_convert.c 1397 2009-09-13 02:19:08Z may $
**
*/
/*
* Note: during the development on this code, I got kinda
* confused about the efficiency of this endian-specific-code
* approach. I'm not sure if this is doing what it's supposed
* to, but I'm too stupid to draw a conclusion. So, please,
* someone take a look at the code, fix whatever needs to
* be fixed and remove this note. kthx.
*
* Strauss
*/
#include <libasm.h>
void sparc_convert_pbranch(struct s_decode_pbranch *opcode, u_char *buf)
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
int converted;
memcpy(&converted, buf, 4);
opcode->op = (converted >> 30) & 0x3;
opcode->a = (converted >> 29) & 0x1;
opcode->cond = (converted >> 25) & 0xf;
opcode->op2 = (converted >> 22) & 0x7;
opcode->cc1 = (converted >> 21) & 0x1;
opcode->cc0 = (converted >> 20) & 0x1;
opcode->p = (converted >> 19) & 0x1;
opcode->immediate = converted & 0x7FFFF;
#else
memcpy(opcode, buf, 4);
#endif
opcode->cc = (opcode->cc1 << 1) | opcode->cc0;
if (opcode->immediate & 0x40000)
opcode->imm = opcode->immediate | 0xFFFC0000;
else
opcode->imm = opcode->immediate;
}
void sparc_convert_rbranch(struct s_decode_rbranch *opcode, u_char *buf)
{
int d16;
#if __BYTE_ORDER == __LITTLE_ENDIAN
int converted;
memcpy(&converted, buf, 4);
opcode->op = (converted >> 30) & 0x3;
opcode->a = (converted >> 29) & 0x1;
opcode->zero = (converted >> 28) & 0x1;
opcode->rcond = (converted >> 25) & 0x7;
opcode->op2 = (converted >> 22) & 0x7;
opcode->d16hi = (converted >> 20) & 0x3;
opcode->p = (converted >> 19) & 0x1;
opcode->rs1 = (converted >> 14) & 0x1f;
opcode->d16lo = converted & 0x3FFF;
#else
memcpy(opcode, buf, 4);
#endif
d16 = (opcode->d16hi << 14) | (opcode->d16lo);
if (d16 & 0x8000)
opcode->d16 = d16 | 0xFFFF0000;
else
opcode->d16 = d16;
}
void sparc_convert_branch(struct s_decode_branch *opcode, u_char *buf)
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
int converted;
memcpy(&converted, buf, 4);
opcode->op = (converted >> 30) & 0x3;
opcode->a = (converted >> 29) & 0x1;
opcode->cond = (converted >> 25) & 0xf;
opcode->op2 = (converted >> 22) & 0x7;
opcode->immediate = converted & 0x3FFFFF;
#else
memcpy(opcode, buf, 4);
#endif
opcode->rd = (opcode->a << 4) | opcode->cond;
if (opcode->immediate & 0x200000)
opcode->imm = opcode->immediate | 0xFFE00000;
else
opcode->imm = opcode->immediate;
}
void sparc_convert_call(struct s_decode_call *opcode, u_char *buf)
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
int converted;
memcpy(&converted, buf, 4);
opcode->op = (converted >> 30) & 0x3;
opcode->disp30 = (converted & 0x3FFFFFFF);
#else
memcpy(opcode, buf, 4);
#endif
if (opcode->disp30 & 0x20000000)
opcode->displacement = opcode->disp30 | 0xC0000000;
else
opcode->displacement = opcode->disp30;
}
void sparc_convert_format3(struct s_decode_format3 *opcode, u_char *buf)
{
int shcnt, immediate10;
int immediate;
#if __BYTE_ORDER == __LITTLE_ENDIAN
int converted;
memcpy(&converted, buf, 4);
opcode->op = (converted >> 30) & 0x3;
opcode->rd = (converted >> 25) & 0x1f;
opcode->op3 = (converted >> 19) & 0x3f;
opcode->rs1 = (converted >> 14) & 0x1f;
opcode->i = (converted >> 13) & 0x1;
opcode->none = (converted >> 5) & 0xff;
opcode->rs2 = converted & 0x1f;
#else
memcpy(opcode, buf, 4);
#endif
/* The following code sets the immediate and the shcnt values
* (abstracting whether the shcnt value is for 32 or 64 bits)
*/
immediate = (opcode->none << 5) | (opcode->rs2);
if (immediate & 0x1000)
opcode->imm = 0xFFFFF000 | immediate;
else
opcode->imm = immediate;
immediate10 = immediate & 0x3ff;
if (immediate10 & 0x200)
opcode->imm10 = 0xFFFFFC00 | immediate10;
else
opcode->imm10 = immediate10;
shcnt = immediate & 0x3f;
/* (immediate & 0x1fff == the 'x' bit */
if ((immediate & 0x1fff) == 0)
shcnt &= 0x1f;
opcode->shcnt = shcnt;
opcode->rcond = (opcode->imm & 0x1c00) >> 10;
opcode->opf = (opcode->i << 8) | opcode->none;
opcode->opf_cc = (opcode->opf & 0x1c0) >> 6;
opcode->cc = opcode->rd & 0x3;
opcode->cond = opcode->rs1 & 0xf;
}
void sparc_convert_format4(struct s_decode_format4 *opcode, u_char *buf)
{
int immediate;
#if __BYTE_ORDER == __LITTLE_ENDIAN
int converted;
memcpy(&converted, buf, 4);
opcode->op = (converted >> 30) & 0x3;
opcode->rd = (converted >> 25) & 0x1f;
opcode->op3 = (converted >> 19) & 0x3f;
opcode->rs1 = (converted >> 14) & 0x1f;
opcode->i = (converted >> 13) & 0x1;
opcode->cc1 = (converted >> 12) & 0x1;
opcode->cc0 = (converted >>11) & 0x1;
opcode->none = (converted >> 5) & 0x3f;
opcode->rs2 = converted & 0x1f;
#else
memcpy(opcode, buf, 4);
#endif
opcode->cond = opcode->rs1 & 0xf;
opcode->cc2 = opcode->rs1 & 0x10;
opcode->cc = (opcode->cc2 << 2) | (opcode->cc1 << 1) | opcode->cc0;
opcode->sw_trap = ((opcode->none & 0x3) << 5) | opcode->rs2;
immediate = (opcode->none << 5) | (opcode->rs2);
if (immediate & 0x400)
opcode->imm = 0xFFFFF800 | immediate;
else
opcode->imm = immediate;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_push_reg.c
/*
** $Id: op_push_reg.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_push_reg" opcode="0x50"/>
<instruction func="op_push_reg" opcode="0x51"/>
<instruction func="op_push_reg" opcode="0x52"/>
<instruction func="op_push_reg" opcode="0x53"/>
<instruction func="op_push_reg" opcode="0x54"/>
<instruction func="op_push_reg" opcode="0x55"/>
<instruction func="op_push_reg" opcode="0x56"/>
<instruction func="op_push_reg" opcode="0x57"/>
*/
int op_push_reg(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode;
new->len += 1;
new->ptr_instr = opcode;
new->instr = ASM_PUSH;
new->type = ASM_TYPE_TOUCHSP | ASM_TYPE_STORE;
new->spdiff = -4;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_OPMOD, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_OPMOD, new);
#endif
if (new->op[0].baser == ASM_REG_EBP)
new->type |= ASM_TYPE_PROLOG;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_386sp.c
/**
* @file libasm/src/arch/ia32/handlers/op_386sp.c
*
* @ingroup IA32_instrs
* $Id: op_386sp.c 1397 2009-09-13 02:19:08Z may $
* ChangeLog:
* 2007-05-30 Fixed a bug in fetching. The vector used was the previously defined.
* strauss set up a new disasm vector and didn't know about it which
* was called here.
* Filled instruction opcode pointer.
* Removed the old unused handler.
* Added minimal error management.
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* This is the handler for 2 bytes instruction, opcode 0x0f
* The second byte is used to fetch a new handler in the vector
* starting at offset 0x100.
* @param ins Pointer to instruction structure.
* @param buf Pointer to data to disassemble.
* @param len Length of dat to disassemble.
* @param proc Pointer to processor structure.
* @return Length of instruction or -1 error.
*/
int op_386sp(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc)
{
int opcode;
int (*fetch)(asm_instr *, u_char *, u_int, asm_processor *);
// XXX: Use asm_set_error to set error code to LIBASM_ERROR_TOOSHORT
if (len < 2)
return (-1);
opcode = *(buf + 1);
opcode += 0x100;
fetch = asm_opcode_fetch(LIBASM_VECTOR_OPCODE_IA32, opcode);
if (!fetch)
return (-1);
if (!ins->ptr_instr)
ins->ptr_instr = buf;
ins->len += 1;
return (fetch(ins, buf + 1, len - 1, proc));
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_prefix_ds.c
/**
* @file libasm/src/arch/ia32/handlers/op_prefix_ds.c
*
* @ingroup IA32_instrs
* $Id: op_prefix_ds.c 1397 2009-09-13 02:19:08Z may $
*
* Changelog
* 200-07-29 : instruction length was not incremented. fixed.
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_prefix_ds" opcode="0x3e"/>
*/
int op_prefix_ds(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
if (!new->ptr_prefix)
new->ptr_prefix = opcode;
new->len += 1;
new->prefix |= ASM_PREFIX_DS;
return (proc->fetch(new, opcode + 1, len - 1, proc));
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_esc7.c
/**
* $Id: op_esc7.c 1311 2009-01-14 20:36:48Z may $
* @param
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for fpu instruction for opcode 0xdf
*
* @param instr Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
*
<instruction func="op_esc7" opcode="0xdf"/>
*/
int op_esc7(asm_instr *instr, u_char *opcode, u_int len, asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode + 1;
instr->ptr_instr = opcode;
instr->len += 1;
if (*(opcode + 1) == 0xe0)
{
if (!(instr->prefix & ASM_PREFIX_FWAIT))
instr->instr = ASM_FNSTSW;
else
instr->instr = ASM_FSTSW;
instr->op[0].type = ASM_OTYPE_FIXED;
instr->op[0].content = ASM_OP_BASE;
instr->op[0].regset = ASM_REGSET_R16;
instr->op[0].baser = ASM_REG_EAX;
}
else
switch (modrm->r)
{
case 0:
instr->instr = ASM_FILD;
break;
case 1:
// bad instr->instr = ASM_;
break;
case 2:
instr->instr = ASM_FIST;
break;
case 3:
instr->instr = ASM_FISTP;
break;
case 4:
instr->instr = ASM_FBLD;
break;
case 5:
instr->instr = ASM_FILD;
break;
case 6:
instr->instr = ASM_FBSTP;
break;
case 7:
instr->instr = ASM_FISTP;
break;
}
if (*(opcode + 1) != 0xe0) {
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
instr->len += asm_operand_fetch(&instr->op[0], opcode + 1, ASM_OTYPE_ENCODED,
instr, 0);
#else
instr->len += asm_operand_fetch(&instr->op[0], opcode + 1, ASM_OTYPE_ENCODED,
instr);
#endif
#else
instr->op[0].type = ASM_OTYPE_ENCODED;
operand_rmv(&instr->op[0], opcode + 1, len - 1, proc);
instr->len += instr->op[0].len;
#endif
} else
instr->len++;
return (instr->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_outsw.c
/*
** $Id: op_outsw.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_outsw" opcode="0x6f"/>
<instruction func="op_outsd" opcode="0x6f"/>
*/
int op_outsw(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->ptr_instr = opcode;
new->len += 1;
if (!asm_proc_opsize(proc))
new->instr = ASM_OUTSW;
else
new->instr = ASM_OUTSD;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_DX,
ASM_REGSET_R16));
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_XSRC, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new);
new->op[0].content = ASM_OP_BASE | ASM_OP_REFERENCE;
new->op[0].regset = ASM_REGSET_R16;
new->op[0].baser = ASM_REG_DX;
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_XSRC, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_lds_rm_rmp.c
/*
** $Id: op_lds_rm_rmp.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for instruction lds opcode 0xc5
*
<instruction func="op_lds_rm_rmp" opcode="0xc5"/>
*/
int op_lds_rm_rmp(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->ptr_instr = opcode;
new->instr = ASM_LDS;
new->len += 1;
new->type = ASM_TYPE_LOAD;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_shrd_rmv_rv_cl.c
/*
** $Id: i386_shrd_rmv_rv_cl.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<i386 func="i386_shrd_rmv_rv_cl" opcode="0xad"/>
*/
int i386_shrd_rmv_rv_cl(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->instr = ASM_SHRD;
new->len += 1;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_GENERAL, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_GENERAL, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new);
#endif
new->op[2].content = ASM_OP_BASE;
new->op[2].regset = ASM_REGSET_R8;
new->op[2].ptr = opcode;
new->op[2].len = 0;
new->op[2].baser = ASM_REG_CL;
#else
new->op[0].type = ASM_OTYPE_ENCODED;
new->op[0].size = ASM_OSIZE_VECTOR;
new->op[1].type = ASM_OTYPE_GENERAL;
new->op[1].size = ASM_OSIZE_VECTOR;
operand_rmv_rv(new, opcode + 1, len - 1, proc);
new->op[2].type = ASM_OTYPE_FIXED;
new->op[2].content = ASM_OP_BASE;
new->op[2].regset = ASM_REGSET_R8;
new->op[2].ptr = opcode;
new->op[2].len = 0;
new->op[2].baser = ASM_REG_CL;
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_in_al_ref_ib.c
/**
* @file libasm/src/arch/ia32/handlers/op_in_al_ref_ib.c
*
* @ingroup IA32_instrs
* @brief Handler for instruction in al,ib opcode 0xe4
* $Id: op_in_al_ref_ib.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @brief Handler for instruction in al,ib opcode 0xe4
*
<instruction func="op_in_al_ref_ib" opcode="0xe4"/>
*/
int op_in_al_ref_ib(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->instr = ASM_IN;
new->ptr_instr = opcode;
new->len += 1;
new->type = ASM_TYPE_LOAD | ASM_TYPE_IO;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_AL,
ASM_REGSET_R8));
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new);
#endif
new->op[0].content = ASM_OP_BASE;
new->op[0].regset = ASM_REGSET_R8;
new->op[0].baser = ASM_REG_AL;
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
new->op[0].type = ASM_OTYPE_FIXED;
new->op[0].content = ASM_OP_BASE;
new->op[0].regset = ASM_REGSET_R8;
new->op[0].baser = ASM_REG_AL;
new->op[1].type = ASM_OTYPE_IMMEDIATE;
new->op[1].content = ASM_OP_VALUE;
new->len += 1;
new->op[1].imm = 0;
memcpy(&new->op[1].imm, opcode + 1, 1);
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_je.c
/*
** $Id: i386_je.c 1413 2010-05-21 03:41:25Z figueredo $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<i386 func="i386_je" opcode="0x84"/>
*/
int i386_je(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->type = ASM_TYPE_BRANCH | ASM_TYPE_CONDCONTROL;
new->instr = ASM_BRANCH_EQUAL;
new->len += 1;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_JUMP, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_JUMP, new);
#endif
#else
new->op[0].type = ASM_OTYPE_JUMP;
new->op[0].content = ASM_OP_VALUE | ASM_OP_ADDRESS;
new->op[0].ptr = opcode + 1;
new->op[0].len = 4;
memcpy(&new->op[0].imm, opcode + 1, 4);
new->len += 4;
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_shld_rmv_rv_cl.c
/*
** $Id: i386_shld_rmv_rv_cl.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<i386 func="i386_shld_rmv_rv_cl" opcode="0xa5"/>
*/
int i386_shld_rmv_rv_cl(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->instr = ASM_SHRD;
new->len += 1;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_GENERAL, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_GENERAL, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[2], opcode + 1, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[2], opcode + 1, ASM_OTYPE_FIXED, new);
#endif
new->op[2].content = ASM_OP_BASE;
new->op[2].regset = ASM_REGSET_R8;
new->op[2].ptr = opcode;
new->op[2].len = 0;
new->op[2].baser = ASM_REG_CL;
#else
new->op[0].type = ASM_OTYPE_ENCODED;
new->op[0].size = ASM_OSIZE_VECTOR;
new->op[1].type = ASM_OTYPE_GENERAL;
new->op[1].size = ASM_OSIZE_VECTOR;
operand_rmv_rv(new, opcode + 1, len - 1, proc);
new->op[2].type = ASM_OTYPE_FIXED;
new->op[2].content = ASM_OP_BASE;
new->op[2].regset = ASM_REGSET_R8;
new->op[2].ptr = opcode;
new->op[2].len = 0;
new->op[2].baser = ASM_REG_CL;
#endif
return (new->len);
}
<file_sep>/README.md
# sigtool-0.1
elf objects signature tool
signatures are created based on bit entropy and opcode checksum of basic blocks
<file_sep>/src/libasm/src/generic.c
/**
* @file libasm/src/generic.c
* @ingroup libasm
* Latest edition Author : $Author: may $
* $Id: generic.c 1439 2010-12-13 10:27:16Z may $
* Started : Wed Jul 24 18:45:15 2002
* Updated : Sat Mar 20 05:26:26 2004
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Fetch instruction using asm_processor handler
* func asm_read_instr
* fetch instruction stored in buffer of max length len
* according to specified processor.
* @param instr instruction to fill.
* @param buf pointer to opcode to disassemble
* @param len maximum length of opcode to disassemble
* @return -1 on error or instruction fetched length
*/
int asm_read_instr(asm_instr *instr, u_char *buf, u_int len, asm_processor *proc)
{
int to_ret;
LIBASM_PROFILE_FIN();
memset(instr, 0, sizeof (asm_instr));
instr->proc = proc;
to_ret = proc->fetch(instr, buf, len, proc);
instr->name = instr->proc->instr_table[instr->instr];
/* Print debug information if requested */
if ((int) config_get_data(CONFIG_USE_ASMDEBUG))
asm_instruction_debug(instr, stdout);
LIBASM_PROFILE_FOUT(to_ret);
}
/**
* @brief Reassemble instruction operands. WORK IN PROGRESS
*
* @param instr Pointer to instruction structure.
* @param buf Pointer to instruction buffer
* @param len Length of buffer.
* @return Length of written instruction or -1 on error.
*/
int asm_write_instr(asm_instr *instr, u_char *buf, u_int len) {
/*
if (instr->op1)
asm_write_operand(instr->op1);
if (instr->op2)
asm_write_operand(instr->op1);
if (instr->op3)
asm_write_operand(instr->op1)
fprintf(stderr, "asm_write unimplemented\n");
*/
return (-1);
}
/**
* @brief Return instruction length
* @param ins Pointer to instruction structure.
* @return
*/
int asm_instr_len(asm_instr *ins)
{
return (asm_instruction_get_len(ins, 0, 0));
}
/**
* Return 2 power val
* @param val The level of power to raise 2.
* @return Return the computed value.
*/
int asm_int_pow2(int val) {
return (val ? (2 * asm_int_pow2(val - 1)) : 1);
}
/**
* @brief Set the resolving handler to display addresses.
* @param proc Pointer to processor structure.
* @param fcn The resolving handler to use
*/
void asm_set_resolve_handler(asm_processor *proc,
void (*fcn)(void *, eresi_Addr, char *, u_int), void *d)
{
proc->resolve_immediate = fcn;
proc->resolve_data = d;
}
/**
* @brief returns 1 if OPLEN is not activated
* This is related only to ia32 architecture.
* @param proc The pointer to the processor structure.
* @return 1 if OPLEN is activated, 0 if not.
*/
int asm_proc_is_protected(asm_processor *proc) {
asm_i386_processor *i386p;
i386p = (asm_i386_processor *) proc;
if (i386p->internals->mode == INTEL_PROT)
return (1);
return (0);
}
/**
* @brief returns the value of the processor's current operand length
* This is related only to ia32 architecture.
* @param proc Pointer to the processor structure.
* @return 1 if opsize is set, 0 if not.
*/
int asm_proc_opsize(asm_processor *proc) {
asm_i386_processor *i386p;
i386p = (asm_i386_processor *) proc;
if (i386p->internals->opsize)
return (1);
return (0);
}
/**
* @brief Returns the value of the processor's current address size
* @param proc Pointer to the processor structure
* @return 1 if addsize is set, 0 if not
*/
int asm_proc_addsize(asm_processor *proc)
{
asm_i386_processor *i386p;
i386p = (asm_i386_processor *) proc;
if (i386p->internals->addsize)
return (1);
return (0);
}
/**
* @brief Returns vector current size depending on oplen prefix
* This is related to ia32 architecture only
* @param proc Pointer to the processor structure.
* @return 4 or 2 depending on
*/
int asm_proc_vector_len(asm_processor *proc)
{
if (asm_proc_opsize(proc))
return (2);
else
return (4);
}
/**
* @brief Return vector size depending on prefix
* This is ia32 related.
* @param proc Pointer to the processor structure
* @return Return vector size.
*/
int asm_proc_vector_size(asm_processor *proc)
{
if (asm_proc_opsize(proc))
return (2);
else
return (4);
}
/**
* Set the immediate part of the operand if present
* @param ins Pointer to instruction
* @param num Number of the operand to set.
* @param opt Optionnal. may be used to specify current virtual address.
* @param valptr Pointer to the new value
* @return number of bytes written
*/
int asm_operand_set_immediate(asm_instr *ins, int num,
int opt, void *valptr)
{
int *value;
int off;
int len;
asm_operand *op;
op = 0;
off = len = 0;
value = (int *) valptr;
switch(num)
{
case 1:
op = &ins->op[0];
break;
case 2:
op = &ins->op[1];
break;
case 3:
op = &ins->op[2];
break;
default:
op = 0;
return (-1);
break;
}
if (op->ptr && (op->content & ASM_OP_VALUE)) {
switch (op->len) {
case 0:
break;
case 1:
if ((op->type & ASM_OP_BASE) || (op->type & ASM_OP_INDEX)) {
if ((op->type & ASM_OP_SCALE) || (op->type & ASM_OP_INDEX)) {
off = 2;
len = 1;
} else {
off = 1;
len = 1;
} } else {
off = 0;
len = 1;
}
break;
case 2:
if ((op->type & ASM_OP_BASE) || (op->type & ASM_OP_INDEX)) {
off = 1;
len = 1;
} else {
off = 0;
len = 2;
}
break;
case 3:
off = 2;
len = 1;
break;
case 4:
off = 0;
len = 4;
break;
case 5:
off = 1;
len = 4;
break;
case 6:
off = 2;
len = 4;
break;
} /* !switch */ } /* !if */
else {
off = 0;
len = 0;
}
memcpy(op->ptr + off, value, len);
memset(&op->imm, 0, 4);
memcpy(&op->imm, value, len);
return (len);
}
/**
* returns a pointer to a static buffer containing instruction memonic
*/
/**
* returns a pointer to a static buffer containing instruction memonic
* @param ins Pointer to the instruction structure
* @param proc Pointer to the processor structure
* return Return the mnemonic.
*/
char *asm_instr_get_memonic(asm_instr *ins, asm_processor *proc)
{
return (proc->instr_table[ins->instr]);
}
/**
* @brief Return content field of an operand.
* @param ins Pointer to an instruction structure.
* @param num Number of the operand to get content from.
* @param opt Currently not used.
* @param valptr Currently not used.
* @return Return operand content field.
*/
int asm_operand_get_content(asm_instr *ins, int num, int opt, void *valptr)
{
switch(num)
{
case 1:
return (ins->op[0].content);
case 2:
return (ins->op[1].content);
case 3:
return (ins->op[2].content);
default:
return (0);
}
}
/**
* @brief Dump debug output of operand to a file stream.
* @param ins Pointer to the instruction structure
* @param num Number of the operand to dump
* @param opt optional parameter. Currently not used.
* @param valptr is a filestream : FILE *
* @return 1 on success, 0 on error.
*/
int asm_operand_debug(asm_instr *ins, int num, int opt, void *valptr)
{
asm_operand *op;
FILE *fp;
switch(num)
{
case 1: op = &ins->op[0]; break;
case 2: op = &ins->op[1]; break;
case 3: op = &ins->op[2]; break;
default: return (-1);
}
if (op->type)
{
fp = (FILE *) valptr;
fprintf(fp, "o%i type=[%s] content=[%c%c%c%c]\n",
num,
asm_operand_type_string(op->type),
op->content & ASM_OP_BASE ? 'B' : ' ',
op->content & ASM_OP_INDEX ? 'I' : ' ',
op->content & ASM_OP_SCALE ? 'S' : ' ',
op->content & ASM_OP_VALUE ? 'V' : ' ');
/*
fprintf(fp, "o%i len = %i\n", num, op->len);
fprintf(fp, "o%i ptr = %8p\n", num, op->ptr);
fprintf(fp, "o%i type = %08x\n", num, op->type);
fprintf(fp, "o%i size = %i\n", num, op->size);
fprintf(fp, "o%i content = [%i]\n", num, op->content);
fprintf(fp, "o%i immediate = %08X\n", num, op->imm);
fprintf(fp, "o%i basereg = %i\n", num, op->baser);
fprintf(fp, "o%i indexreg = %i\n", num, op->indexr);
fprintf(fp, "o%i scale = %i\n", num, op->scale);
*/
}
return (1);
}
/**
* Dump debugging information for an instruction.
* @param ins Pointer to instruction to debug.
* @param out Output FILE* stream.
*/
void asm_instruction_debug(asm_instr *ins, FILE *out)
{
int i;
fprintf(out, "ins=[%s] len=[%i] types=[%c|%c%c%c]\n",
asm_instr_get_memonic(ins, ins->proc),
asm_instr_len(ins),
(ins->type & ASM_TYPE_BRANCH) && !(ins->type & ASM_TYPE_CONDCONTROL) ? 'I' :
ins->type & ASM_TYPE_CALLPROC ? 'C' :
(ins->type & ASM_TYPE_BRANCH) && (ins->type & ASM_TYPE_CONDCONTROL) ? 'J' :
ins->type & ASM_TYPE_RETPROC ? 'R' : ' ',
ins->type & ASM_TYPE_ARITH ? 'c' : ' ',
ins->type & ASM_TYPE_CONTROL ? 'f' : ' ',
ins->type & ASM_TYPE_ASSIGN ? 'a' : ' ');
for (i = 0; i < 3; i++)
{
asm_operand_debug(ins, i, 0, out);
}
}
/**
* set config flag to specified endian
* @param mode endian (big/little)
*/
void asm_config_set_endian(int mode)
{
config_update_key(CONFIG_ASM_ENDIAN_FLAG,(void *) mode);
}
/**
* get the endian flag
*/
int asm_config_get_endian()
{
return (int) config_get_data(CONFIG_ASM_ENDIAN_FLAG);
}
/**
* get the synthetic instruction enabled flag
*/
int asm_config_get_synthinstr()
{
return (int) config_get_data(CONFIG_ASM_SYNTHINSTRS);
}
/**
*
*
*/
int asm_instruction_is_prefixed(asm_instr *ins, int prefix)
{
return (ins->prefix & prefix);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_mov_dr_rm.c
/*
** $Id: i386_mov_dr_rm.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
int i386_mov_dr_rm(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) (opcode + 1);
new->len += 1;
new->instr = ASM_MOV;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_DEBUG, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_DEBUG, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_REGISTER, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_REGISTER, new);
#endif
#else
new->op[0].type = ASM_OTYPE_DEBUG;
new->op[0].content = ASM_OP_BASE;
new->op[0].regset = ASM_REGSET_DREG;
new->op[0].baser = modrm->r;
new->op[1].type = ASM_OTYPE_REGISTER;
new->op[1].content = ASM_OP_BASE;
new->op[1].regset = ASM_REGSET_R32;
new->op[1].baser = modrm->m;
#endif
return (new->len);
}
<file_sep>/src/libaspect/profiler.c
/**
* @file libaspect/profiler.c
** @ingroup libaspect
**
** Started on Thu Nov 08 02:08:28 2001 mm
** $Id: profiler.c 1397 2009-09-13 02:19:08Z may $
*/
#include "libaspect.h"
/* Patterns memory */
static char mem[2][PROFILER_MAX_PATTERN][80] = {{{0,0,0}}};
/* Patterns hit counters */
static u_int hit[2][PROFILER_MAX_PATTERN] = {{0,0}};
/* Selection of memory */
static u_int sel;
/* The last error message */
char *profiler_error_str = NULL;
/* Last function depth */
int profiler_depth = 0;
/* Last function direction */
static char profiler_direction = '+';
/* Allocation cache */
static profallocentry_t allocentries[PROFILER_MAX_ALLOC];
/* Current allocation depth */
static u_int profiler_adepth = 0;
/***************** Now the allocator profiler *********************/
/**
* @brief Find an entry in the allocation profiler cache
* @param direction Either PROFILER_WARNING_LAST, PROFILER_WARNING_FIRST, or PROFILER_WARNING_UNKNOW
* @param addr Allocated address to be found in profiling cache
* @param optype Type of operation to be found
* @return Allocation profiler entry corresponding to input criterions
*/
profallocentry_t *profiler_alloc_find(u_char direction,
u_long addr,
u_char optype)
{
u_int index;
switch (direction)
{
case PROFILER_WARNING_LAST:
for (index = profiler_adepth - 1; index; index--)
if (allocentries[index].addr == addr &&
allocentries[index].optype == optype)
return (allocentries + index);
return (NULL);
case PROFILER_WARNING_FIRST:
for (index = 1; index < profiler_adepth; index++)
if (allocentries[index].addr == addr &&
allocentries[index].optype == optype)
return (allocentries + index);
return (NULL);
case PROFILER_WARNING_UNKNOW:
default:
if (aspectworld.profile)
aspectworld.profile(" [E] Unknown alloc optype requested to the "
"allocator profiler\n");
return (NULL);
}
}
/**
* @brief Print the warning string
* @param str Header string to be printed
* @param fatal 1 if error is fatal (exit afterwards)
* @param idx Index corresponding to allocation entry to print
*/
void profiler_alloc_warnprint(char *str, int fatal, int idx)
{
char buf[BUFSIZ];
snprintf(buf, sizeof(buf),
"%s\n (%s-[%s of addr: 0x%08lX at %s@%s:%u) \n\n", str,
(allocentries[idx].alloctype ==
PROFILER_ALLOC_LEGIT ? "LEGIT " :
PROFILER_ALLOC_PROXY ? "PROXY " : "UNKNOW "),
(allocentries[idx].optype ==
PROFILER_OP_ALLOC ? "ALLOC " :
PROFILER_OP_REALLOC ? "REALLOC" :
PROFILER_OP_FREE ? "FREE " : "UNKNOW "),
allocentries[idx].addr,
allocentries[idx].filename,
allocentries[idx].funcname,
allocentries[idx].linenbr);
if (aspectworld.profile)
aspectworld.profile(buf);
if (fatal)
exit(-1);
}
/**
* @brief Warn if anything bad is happening. Good when we cannot use valgrind.
* @param warntype Either PROFILER_WARNING_LAST, PROFILER_WARNING_FIRST or PROFILER_WARNING_UNKNOW
*/
void profiler_alloc_warning(u_char warntype)
{
profallocentry_t *ent;
profallocentry_t *ent2;
profallocentry_t *ent3;
/* Do not emit warning if not asked to */
if (!(aspectworld.proflevel & PROFILE_ALLOC))
return;
switch (warntype)
{
/* There are many checks for the last entry */
case PROFILER_WARNING_LAST:
ent2 = profiler_alloc_find(PROFILER_WARNING_LAST,
allocentries[profiler_adepth].addr,
PROFILER_OP_FREE);
ent = profiler_alloc_find(PROFILER_WARNING_LAST,
allocentries[profiler_adepth].addr,
PROFILER_OP_ALLOC);
ent3 = profiler_alloc_find(PROFILER_WARNING_LAST,
allocentries[profiler_adepth].addr,
PROFILER_OP_REALLOC);
/* We do emit a warning if we encountered a double free */
if (allocentries[profiler_adepth].optype == PROFILER_OP_FREE &&
ent2 && ent2 > ent)
profiler_alloc_warnprint(" [A] A pointer was freed"
" but it is already free ",
1, profiler_adepth);
/* We emit a warning when a free happens in the wrong allocator */
if ((allocentries[profiler_adepth].optype == PROFILER_OP_FREE ||
allocentries[profiler_adepth].optype == PROFILER_OP_REALLOC)
&& ent
&& ent->alloctype != allocentries[profiler_adepth].alloctype)
profiler_alloc_warnprint(" [A] A pointer was freed"
" but it is was belonging "
" to another allocator ",
1, profiler_adepth);
/* We emit a warning when we free without remembering the alloc */
if (allocentries[profiler_adepth].optype == PROFILER_OP_REALLOC
&& !ent)
profiler_alloc_warnprint(" [A] A pointer was reallocated but its"
" allocation was not found in history",
0, profiler_adepth);
/* We emit a warning when we realloc without remembering alloc */
if (allocentries[profiler_adepth].optype == PROFILER_OP_REALLOC
&& !ent && !ent2)
profiler_alloc_warnprint(" [A] A pointer was reallocated but its"
" allocation was not found in history",
0, profiler_adepth);
/* We emit a warning when we realloc something freed */
if (allocentries[profiler_adepth].optype == PROFILER_OP_REALLOC
&& ent2 && (ent2 > ent))
profiler_alloc_warnprint(" [A] A pointer was reallocated but it"
" was in a freed state",
1, profiler_adepth);
/* We do emit a warning if the last entry is an allocation
and this pointer was already allocated after beeing freed */
if (allocentries[profiler_adepth].optype == PROFILER_OP_ALLOC &&
ent && ((ent > ent2) || (ent > ent3)))
profiler_alloc_warnprint(" [A] A pointer was reallocated"
" without beeing freed ",
1, profiler_adepth);
break;
/* We do emit a warning if the first entry is a malloc
and it has not been freed before it was removed from
the cache, which mean its a potential memory leak */
case PROFILER_WARNING_FIRST:
if (allocentries[0].optype == PROFILER_OP_FREE)
return;
ent = profiler_alloc_find(PROFILER_WARNING_FIRST,
allocentries[0].addr,
PROFILER_OP_FREE);
if (!ent)
profiler_alloc_warnprint(" [A] An allocation was removed"
" from the history without beeing free",
0, 0);
break;
/* Just an error detection message */
default:
case PROFILER_WARNING_UNKNOW:
if (aspectworld.profile)
aspectworld.profile(" [A] Unknown warning type requested to the "
"allocator profiler\n");
exit(-1);
break;
}
}
/**
* @brief Shift the allocation history
*/
void profiler_alloc_shift()
{
int index;
for (index = 1; index < PROFILER_MAX_ALLOC; index++)
allocentries[index - 1] = allocentries[index];
profiler_adepth--;
}
/**
* @brief Add an entry in the allocation cache
* @param file Generally called with __FILE__ (gcc), contains the file name where allocation is done
* @param func Generally called with __FUNCTION__ (gcc), contains the function name where allocation is done
* @param line Generally called with __LINE__ (gcc), contains the line number in related file
* @param addr Newly allocated address
* @param atype Type of allocation
* @param otype Type of allocation operation
*/
static void profiler_alloc_add(char *file, char *func,
u_int line, u_long addr,
u_char atype, u_char otype)
{
allocentries[profiler_adepth].alloctype = atype;
allocentries[profiler_adepth].optype = otype;
allocentries[profiler_adepth].filename = file;
allocentries[profiler_adepth].funcname = func;
allocentries[profiler_adepth].linenbr = line;
allocentries[profiler_adepth].addr = addr;
profiler_adepth++;
}
/**
* @brief Update allocation cache with a new entry
* @param file Generally called with __FILE__ (gcc), contains the file name where allocation is done
* @param func Generally called with __FUNCTION__ (gcc), contains the function name where allocation is done
* @param line Generally called with __LINE__ (gcc), contains the line number in related file
* @param addr Newly allocated address
* @param atype Type of allocation
* @param otype Type of allocation operation
* @return 0 if we are filling the last cache entry, 0 if not
*/
int profiler_alloc_update(char *file, char *func,
u_int line, u_long addr,
u_char atype, u_char otype)
{
if (aspectworld.proflevel & PROFILE_ALLOC)
printf(" [A] %s@%s:%u %s ADDR %lX \n", func, file, line,
(atype == PROFILER_OP_FREE ? "FREE" : "(RE)ALLOC"), addr);
/* Just happens an entry at the end. Check the last entry. */
if (profiler_adepth + 1 != PROFILER_MAX_ALLOC)
{
profiler_alloc_add(file, func, line, addr, atype, otype);
profiler_alloc_warning(PROFILER_WARNING_LAST);
return (0);
}
/* In that case we have to shift all entries. Check the removed entry */
profiler_alloc_warning(PROFILER_WARNING_FIRST);
profiler_alloc_shift();
profiler_alloc_add(file, func, line, addr, atype, otype);
profiler_alloc_warning(PROFILER_WARNING_LAST);
return (1);
}
/***************** Now the profiler for function calls ***************/
/**
* @brief Reset profiler memory
* @param lsel Identifiant for profiler cache bank to be used
*/
void profiler_reset(u_int lsel)
{
u_int idx;
for (idx = 0; idx < PROFILER_MAX_PATTERN; idx++)
{
mem[lsel][idx][0] = 0x00;
hit[lsel][idx] = 0;
}
}
/**
* @brief Generic routine for profiler output
* @param file Generally called with __FILE__ (gcc), contains the file name where allocation is done
* @param func Generally called with __FUNCTION__ (gcc), contains the function name where allocation is done
* @param line Generally called with __LINE__ (gcc), contains the line number in related file
* @param msg Profiling message suffix to be printed
* @return 1 if message is already present in bank, 0 if not
*/
int profiler_print(char *file, char *func,
u_int line, char *msg)
{
char buff[80];
char buf[BUFSIZ];
// char mesg[100];
volatile int idx;
// volatile int idx2;
char flag;
char *fill;
sel = (msg ? 0 : 1);
/* Compute location string */
snprintf(buf, sizeof(buf), "<%s@%s:%u>", func, file, line);
snprintf(buff, sizeof(buff), "%-50s %s", buf, (msg ? msg : ""));
flag = 0;
for (idx = 0; idx < PROFILER_MAX_PATTERN; idx++)
if (!strcmp(buff, mem[sel][idx]))
{
hit[sel][idx]++;
flag = 1;
}
if (flag)
return (1);
fill = alloca(profiler_depth + 1);
memset(fill, ' ', profiler_depth);
fill[profiler_depth] = 0x00;
/* Print memory when pattern matched */
for (idx = PROFILER_MAX_PATTERN - 1; idx >= 0; idx--)
if (hit[sel][idx])
{
aspectworld.profile("\n");
/*
for (idx2 = idx; idx2 >= 0; idx2--)
{
snprintf(buf, BUFSIZ, " %s [%c] --[ (%u hit%s) %-50s \n",
fill,
(sel ? 'P' : 'W'),
hit[sel][idx],
(hit[sel][idx] > 1 ? "s" : ""),
mem[sel][idx2]);
aspectworld.profile(buf);
}
snprintf(mesg, sizeof(mesg), " %s [%c] --- Last %u %s %u time(s) ---\n\n",
fill,
(sel ? 'P' : 'W'), idx + 1,
(sel ? "function(s) called/returned again" : "warning(s) repeated"),
hit[sel][idx]);
aspectworld.profile(mesg);
*/
for (idx = 0; idx < PROFILER_MAX_PATTERN; idx++)
hit[sel][idx] = 0;
break;
}
/* shifting of memories */
for (idx = PROFILER_MAX_PATTERN - 1; idx > 0; idx--)
strncpy(mem[sel][idx], mem[sel][idx - 1], 80);
strncpy(mem[sel][0], buff, 80);
return (0);
}
/**
* @brief Generic routine for profiler error output
* @param file Generally called with __FILE__ (gcc), contains the file name where allocation is done
* @param func Generally called with __FUNCTION__ (gcc), contains the function name where allocation is done
* @param line Generally called with __LINE__ (gcc), contains the line number in related file
* @param msg Profiling message suffix to be printed
*/
void profiler_err(char *file, char *func,
u_int line, char *msg)
{
char buff[80];
char buf[BUFSIZ];
char *fill;
if (!(aspectworld.proflevel & PROFILE_WARN))
return;
/* Stock a pattern without printing */
if (profiler_print(file, func, line, msg))
return;
fill = (profiler_depth - 6 > 0 ? alloca(profiler_depth + 1) : "");
if (profiler_depth - 6 > 0)
{
memset(fill, ' ', profiler_depth);
fill[profiler_depth] = 0x00;
}
if (aspectworld.endline != NULL)
{
snprintf(buff, sizeof(buff), " <%s@%s:%s>",
aspectworld.colorfunction(func),
aspectworld.colorfilename(file),
aspectworld.colornumber("%u", line));
snprintf(buf, BUFSIZ, " %s %s %-70s %s \n",
aspectworld.colorwarn("[W]"),
fill, buff, aspectworld.colorwarn(msg));
}
else
{
snprintf(buff, sizeof(buff), " <%s@%s:%u>",
func, file, line);
snprintf(buf, BUFSIZ, " [W] %s %-70s %s \n",
fill, buff, msg);
}
if (aspectworld.profile_err != NULL)
aspectworld.profile_err(buf);
else
fprintf(stderr, "No profiling function specified.\n");
if (aspectworld.endline != NULL)
aspectworld.endline();
profiler_reset(0);
}
/**
* @brief Write the last profiling information
* @param file Generally called with __FILE__ (gcc), contains the file name where allocation is done
* @param func Generally called with __FUNCTION__ (gcc), contains the function name where allocation is done
* @param line Generally called with __LINE__ (gcc), contains the line number in related file
*/
void profiler_out(char *file, char *func, u_int line)
{
char buff[160];
char *space;
char b_dir[2];
if (!(aspectworld.proflevel & PROFILE_FUNCS))
return;
/* Stock a pattern, without printing */
if (profiler_print(file, func, line, NULL))
return;
if (profiler_depth > 80)
profiler_depth = 1;
space = alloca(profiler_depth + 1);
memset(space, 0x00, profiler_depth);
memset(space, ' ', profiler_depth);
space[profiler_depth] = 0x00;
if (aspectworld.endline != NULL)
{
b_dir[0] = profiler_direction;
b_dir[1] = '\0';
snprintf(buff, sizeof(buff), "%s %s %s <%s@%s:%s>\n",
space,
aspectworld.colornumber("%u", profiler_depth),
aspectworld.colorfieldstr(b_dir),
aspectworld.colorfunction(func),
aspectworld.colorfilename(file),
aspectworld.colornumber("%u", line));
}
else
{
snprintf(buff, sizeof(buff), "%s %u %c <%s@%s:%u>\n",
space, profiler_depth, profiler_direction,
func, file,line);
}
if (aspectworld.profile)
aspectworld.profile(buff);
if (aspectworld.endline != NULL)
aspectworld.endline();
}
/**
* @brief Profiler is started ?
*/
u_char profiler_started()
{
return (aspectworld.profstarted);
}
/**
* @brief Set the current function depth and direction
*/
void profiler_incdepth()
{
profiler_depth++;
}
/**
* @brief Set current function direction to be UP (function entering)
*/
void profiler_updir()
{
profiler_direction = '+';
}
/**
* @brief Set current function direction to be DOWN (function exiting)
*/
void profiler_decdepth()
{
if (profiler_depth > 0)
profiler_depth--;
profiler_direction = '-';
}
/**
* @brief Remove lastly generated error (nulify error string)
*/
void profiler_error_reset()
{
profiler_error_str = NULL;
}
/**
* @brief Display last error message
*/
void profiler_error()
{
char buf[BUFSIZ];
if (profiler_error_str)
{
snprintf(buf, BUFSIZ, " [E] %s\n\n", profiler_error_str);
if (aspectworld.profile_err)
aspectworld.profile_err(buf);
else
printf("[WARNING] : profile_err() is NULL . Reverting to prinf.\n%s\n", buf);
}
profiler_error_reset();
}
<file_sep>/src/libasm/src/arch/mips/mips_convert.c
/**
* @file libasm/src/arch/mips/mips_convert.c
** @ingroup mips
*/
/**
* @file libasm/src/arch/mips/mips_convert.c
* @brief Convert MIPS instruction to definied types and fill suitable structures.
*
* $Id: mips_convert.c 1397 2009-09-13 02:19:08Z may $
*
* Integrated to vectors
* - Adam 'pi3' Zabrocki
*
*/
#include <libasm.h>
/**
* @fn void mips_convert_format_r(struct s_mips_decode_reg *opcode, u_char *buf)
* @brief Convert 'type r' instruction.
*
* Fill structure for 'type r' MIPS instruction.
*
* @param opcode Pointer to structure which will be fill.
* @param buf Pointer to data -> instruction.
*/
void mips_convert_format_r(struct s_mips_decode_reg *opcode, u_char *buf)
{
u_int32_t converted;
if (asm_config_get_endian() == CONFIG_ASM_LITTLE_ENDIAN) {
memcpy(opcode, buf, 4);
} else if (asm_config_get_endian() == CONFIG_ASM_BIG_ENDIAN) {
memcpy(&converted, buf, 4);
opcode->op = (converted >> 26) & 0x3F;
opcode->rs = (converted >> 21) & 0x1F;
opcode->rt = (converted >> 16) & 0x1F;
opcode->rd = (converted >> 11) & 0x1F;
opcode->sa = (converted >> 6) & 0x1F;
opcode->fn = (converted >> 0) & 0x3F;
} else {
printf("[CONV_R] Where am I ?!?!?!\n");
exit(-1);
}
}
/**
* @fn void mips_convert_format_i(struct s_mips_decode_imm *opcode, u_char *buf)
* @brief Convert 'type i' instruction.
*
* Fill structure for 'type i' MIPS instruction.
*
* @param opcode Pointer to structure which will be fill.
* @param buf Pointer to data -> instruction.
*/
void mips_convert_format_i(struct s_mips_decode_imm *opcode, u_char *buf)
{
u_int32_t converted;
if (asm_config_get_endian() == CONFIG_ASM_LITTLE_ENDIAN) {
//memcpy(opcode, buf, 4);
memcpy(&converted, buf, 4);
opcode->op = (converted >> 26) & 0x3F;
opcode->rs = (converted >> 21) & 0x1F;
opcode->rt = (converted >> 16) & 0x1F;
opcode->im = (converted >> 0) & 0xFFFF;
} else if (asm_config_get_endian() == CONFIG_ASM_BIG_ENDIAN) {
memcpy(&converted, buf, 4);
opcode->op = (converted >> 26) & 0x3F;
opcode->rs = (converted >> 21) & 0x1F;
opcode->rt = (converted >> 16) & 0x1F;
opcode->im = (converted >> 0) & 0xFFFF;
} else {
printf("[CONV_I] Where am I ?!?!?!\n");
exit(-1);
}
}
/**
* @fn void mips_convert_format_j(struct s_mips_decode_jump *opcode, u_char *buf)
* @brief Convert 'type j' instruction.
*
* Fill structure for 'type j' MIPS instruction.
*
* @param opcode Pointer to structure which will be fill.
* @param buf Pointer to data -> instruction.
*/
void mips_convert_format_j(struct s_mips_decode_jump *opcode,
u_char *buf)
{
u_int32_t converted;
if (asm_config_get_endian() == CONFIG_ASM_LITTLE_ENDIAN) {
//memcpy(opcode, buf, 4);
memcpy(&converted, buf, 4);
opcode->op = (converted >> 26) & 0x3F;
opcode->ta = (converted >> 0) & 0x3FFFFFF;
} else if (asm_config_get_endian() == CONFIG_ASM_BIG_ENDIAN) {
memcpy(&converted, buf, 4);
opcode->op = (converted >> 26) & 0x3F;
opcode->ta = (converted >> 0) & 0x3FFFFFF;
} else {
printf("[CONV_J] Where am I ?!?!?!\n");
exit(-1);
}
}
/**
* @fn void mips_convert_format_t(struct s_mips_decode_trap *opcode, u_char *buf)
* @brief Convert 'trap' instruction.
*
* Fill structure for 'trap' MIPS instruction.
*
* @param opcode Pointer to structure which will be fill.
* @param buf Pointer to data -> instruction.
*/
void mips_convert_format_t(struct s_mips_decode_trap *opcode,
u_char *buf)
{
u_int32_t converted;
if (asm_config_get_endian() == CONFIG_ASM_LITTLE_ENDIAN) {
memcpy(opcode, buf, 4);
} else if (asm_config_get_endian() == CONFIG_ASM_BIG_ENDIAN) {
memcpy(&converted, buf, 4);
opcode->op = (converted >> 26) & 0x3F;
opcode->rs = (converted >> 21) & 0x1F;
opcode->rt = (converted >> 16) & 0x1F;
opcode->code = (converted >> 6) & 0x3FF;
opcode->fn = (converted >> 0) & 0x3F;
} else {
printf("[CONV_T] Where am I ?!?!?!\n");
exit(-1);
}
}
/**
* @fn void mips_convert_format_cop2(struct s_mips_decode_cop2 *opcode, u_char *buf)
* @brief Convert instrction from second coprocesor
*
* Fill structure for 'second coprocesor' MIPS instruction.
*
* @param opcode Pointer to structure which will be fill.
* @param buf Pointer to data -> instruction.
*/
void mips_convert_format_cop2(struct s_mips_decode_cop2 *opcode,
u_char *buf)
{
u_int32_t converted;
if (asm_config_get_endian() == CONFIG_ASM_LITTLE_ENDIAN) {
memcpy(opcode, buf, 4);
} else if (asm_config_get_endian() == CONFIG_ASM_BIG_ENDIAN) {
memcpy(&converted, buf, 4);
opcode->op = (converted >> 26) & 0x3F;
opcode->rs = (converted >> 21) & 0x1F;
opcode->rt = (converted >> 16) & 0x1F;
opcode->rd = (converted >> 11) & 0x1F;
opcode->fn = (converted >> 3) & 0xFF;
opcode->sl = (converted >> 0) & 0x7;
} else {
printf("[CONV_COP2] Where am I ?!?!?!\n");
exit(-1);
}
}
void mips_convert_format_cop0(struct s_mips_decode_cop0 *opcode, u_char *buf)
{
u_int32_t converted;
if (asm_config_get_endian() == CONFIG_ASM_LITTLE_ENDIAN) {
memcpy(opcode, buf, 4);
} else if (asm_config_get_endian() == CONFIG_ASM_BIG_ENDIAN) {
memcpy(&converted, buf, 4);
opcode->op = (converted >> 26) & 0x3F;
opcode->rs = (converted >> 21) & 0x1F;
opcode->rt = (converted >> 16) & 0x1F;
opcode->rd = (converted >> 11) & 0x1F;
opcode->sa = (converted >> 3) & 0xFF;
opcode->fn = (converted >> 0) & 0x7;
} else {
printf("[CONV_COP2] Where am I ?!?!?!\n");
exit(-1);
}
}
/**
* @fn void mips_convert_format_mov(struct s_mips_decode_mov *opcode, u_char *buf)
* @brief Convert *mov* instruction.
*
* Fill structure for 'mov' MIPS instruction.
*
* @param opcode Pointer to structure which will be fill.
* @param buf Pointer to data -> instruction.
*/
void mips_convert_format_mov(struct s_mips_decode_mov *opcode,
u_char *buf)
{
u_int32_t converted;
if (asm_config_get_endian() == CONFIG_ASM_LITTLE_ENDIAN) {
memcpy(opcode, buf, 4);
} else if (asm_config_get_endian() == CONFIG_ASM_BIG_ENDIAN) {
memcpy(&converted, buf, 4);
opcode->op = (converted >> 26) & 0x3F;
opcode->rs = (converted >> 21) & 0x1F;
opcode->cc = (converted >> 18) & 0x7;
opcode->b1 = (converted >> 17) & 0x1;
opcode->tf = (converted >> 16) & 0x1;
opcode->rd = (converted >> 11) & 0x1F;
opcode->b2 = (converted >> 6) & 0x1F;
opcode->fn = (converted >> 0) & 0x3F;
} else {
printf("[CONV_MOV] Where am I ?!?!?!\n");
exit(-1);
}
}
/**
* @fn void mips_convert_format_cop1x(struct s_mips_decode_mov *opcode, u_char *buf)
* @brief Convert COP1X instruction.
*
* Fill structure for MIPS COP1X instruction.
*
* @param opcode Pointer to structure which will be fill.
* @param buf Pointer to data -> instruction.
*/
void mips_convert_format_cop1x(struct s_mips_decode_cop1x *opcode,
u_char *buf)
{
u_int32_t converted;
if (asm_config_get_endian() == CONFIG_ASM_LITTLE_ENDIAN) {
memcpy(opcode, buf, 4);
} else if (asm_config_get_endian() == CONFIG_ASM_BIG_ENDIAN) {
memcpy(&converted, buf, 4);
opcode->op = (converted >> 26) & 0x3F;
opcode->bs = (converted >> 21) & 0x1F;
opcode->in = (converted >> 16) & 0x1F;
opcode->f1 = (converted >> 11) & 0x1F;
opcode->f2 = (converted >> 6) & 0x1F;
opcode->fn = (converted >> 3) & 0x3;
opcode->fmt = (converted >> 0) & 0x3;
} else {
printf("[CONV_MOV] Where am I ?!?!?!\n");
exit(-1);
}
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_bicc.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_bicc.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_bicc.c 1413 2010-05-21 03:41:25Z figueredo $
**
*/
#include "libasm.h"
int
asm_sparc_bicc(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_branch opcode;
struct s_asm_proc_sparc *inter;
sparc_convert_branch(&opcode, buf);
inter = proc->internals;
ins->instr = inter->bcc_table[opcode.cond];
if (ins->instr == ASM_SP_BA)
ins->type = ASM_TYPE_BRANCH;
else if (ins->instr == ASM_SP_BN)
ins->type = ASM_TYPE_NOP;
else
ins->type = ASM_TYPE_BRANCH | ASM_TYPE_CONDCONTROL;
ins->nb_op = 1;
ins->op[0].imm = opcode.imm;
ins->annul = opcode.a;
ins->prediction = 1;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_DISPLACEMENT, ins);
return 4;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_bts.c
/**
* @file libasm/src/arch/ia32/handlers/i386_bts.c
*
* @ingroup IA32_instrs
* $Id: i386_bts.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<i386 func="i386_bts" opcode="0xab"/>
*/
int i386_bts(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc) {
new->len += 1;
new->instr = ASM_BTS;
new->type = ASM_TYPE_BITTEST | ASM_TYPE_BITSET | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_CF;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_GENERAL, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_GENERAL, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_illegal.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_illegal.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_illegal.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libasm.h"
int
asm_sparc_illegal(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
ins->instr = ASM_SP_BAD;
ins->type = ASM_TYPE_STOP;
return 4;
}
<file_sep>/src/libasm/src/arch/mips/register_mips.c
/**
* @file libasm/src/arch/mips/register_mips.c
** @ingroup mips
*/
/**
* @file libasm/src/arch/mips/register_mips.c
* @brief Registration of the MIPS disassembling vectors.
* $Id: register_mips.c 1397 2009-09-13 02:19:08Z may $
*
* fix and fill
* - Adam 'pi3' Zabrocki
*
* <NAME> - 2007
* This file contains mips architecture registration code.
*/
#include <libasm.h>
/**
* @fn int asm_register_mips_opcode(int op1,int op2,int op3, unsigned long fcn)
* @brief Register MIPS opcode handler.
*
* This function is called by asm_register_mips_opcodes()
*
* @param op1 First argument of instruction type.
* @param op2 Second argument of instruction type.
* @param op3 Third argument of instruction type.
* @param fcn Address for registered function.
* @return Always 1
*/
int asm_register_mips_opcode(int op1,int op2,int op3, unsigned long fcn)
{
vector_t *vec;
u_int dim[3];
LIBASM_PROFILE_FIN();
vec = aspect_vector_get(LIBASM_VECTOR_OPCODE_MIPS);
dim[0] = op1;
dim[1] = op2;
dim[2] = op3;
aspect_vectors_insert(vec,dim,fcn);
LIBASM_PROFILE_FOUT(1);
}
/**
* @fn int asm_register_mips_opcodes()
* @brief Register MIPS opcode handlers.
*
* @return 1 on success
*/
int asm_register_mips_opcodes()
{
int i = 0;
struct e_mips_instr *insns;
insns = e_mips_instrs;
for(i=0;insns[i].code != ASM_MIPS_TABLE_END;i++)
{
asm_register_mips_opcode(insns[i].index1,insns[i].index2,insns[i].index3, (unsigned long) insns[i].func_op);
}
return (1);
}
/**
* @fn int asm_register_mips()
* @brief Initialize the disassembling vector for MIPS.
*
* @return Always 1.
*/
int asm_register_mips()
{
u_int *dims;
char **dimstr;
/*hash_opcode = (hash_t *)malloc(sizeof(hash_t));
hash_operand = (hash_t *)malloc(sizeof(hash_t));
hash_vector = (hash_t *)malloc(sizeof(hash_t));*/
//asm_register_operand_create(LIBASM_VECTOR_OPERAND_MIPS, 64);
//asm_register_opcode_create(LIBASM_VECTOR_OPCODE_MIPS, 64);
dims = malloc(3 * sizeof (u_int));
if (!dims)
{
goto out;
}
dimstr = malloc(3 * sizeof (char *));
if (!dimstr)
{
goto out;
}
/* TODO: These sizes _HAVE_ to be reviewed */
dims[0] = 64;
dims[1] = 64;
dims[2] = 64;
dimstr[0] = "OPCODES";
dimstr[1] = "SECONDARY OPCODES"; /* Should be 0 when unused */
dimstr[2] = "TERTIARY OPCODES"; /* Should be 0 when unused */
aspect_register_vector(LIBASM_VECTOR_OPCODE_MIPS, asm_fetch_default, dims, dimstr, 3, ASPECT_TYPE_CADDR);
/* Initializing MIPS operand handler vector */
/* This section is just a stub for when the operand vector is actually
* implemented. */
dims = malloc(1 * sizeof (u_int));
if (!dims)
{
goto out;
}
dimstr = malloc(1 * sizeof (char *));
if (!dimstr)
{
goto out;
}
dims[0] = ASM_MIPS_OTYPE_LAST;
dimstr[0] = "OPERAND";
aspect_register_vector(LIBASM_VECTOR_OPERAND_MIPS, asm_operand_fetch_default, dims, dimstr, 1, ASPECT_TYPE_CADDR);
asm_register_mips_opcodes();
asm_register_mips_operands();
out:
return (1);
}
/**
* @fn int asm_register_mips()
* @brief Register MIPS operand handlers.
*
* @return Always 1.
*/
int asm_register_mips_operands()
{
asm_register_mips_operand(ASM_MIPS_OTYPE_NONE, (unsigned long) asm_mips_operand_none);
asm_register_mips_operand(ASM_MIPS_OTYPE_REGISTER, (unsigned long) asm_mips_operand_r);
asm_register_mips_operand(ASM_MIPS_OTYPE_IMMEDIATE, (unsigned long) asm_mips_operand_i);
asm_register_mips_operand(ASM_MIPS_OTYPE_JUMP, (unsigned long) asm_mips_operand_j);
asm_register_mips_operand(ASM_MIPS_OTYPE_NOOP, (unsigned long) asm_mips_operand_noop);
asm_register_mips_operand(ASM_MIPS_OTYPE_BRANCH, (unsigned long) asm_mips_operand_branch);
asm_register_mips_operand(ASM_MIPS_OTYPE_REGBASE, (unsigned long) asm_mips_operand_regbase);
return 1;
}
/**
* @fn int asm_register_mips_operand(unsigned int type, unsigned long func)
* @brief Register MIPS operand handler.
*
* This function is called by asm_register_mips_operands()
*
* @param type Type of the operand to register.
* @param func Function pointer.
* @return 1 on success, 0 on error.
*/
int asm_register_mips_operand(unsigned int type, unsigned long func)
{
LIBASM_PROFILE_FIN();
asm_register_operand(LIBASM_VECTOR_OPERAND_MIPS, type, func);
LIBASM_PROFILE_FOUT(1);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_xchg_eax_reg.c
/**
* @file libasm/src/arch/ia32/handlers/op_xchg_eax_reg.c
*
* @ingroup IA32_instrs
* @brief Handler for instruction xchg eax,reg opcode 0x91 to 0x97
** $Id: op_xchg_eax_reg.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @brief Handler for instruction xchg eax,reg opcode 0x91 to 0x97
* @param instr Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Length of instruction.
*/
int op_xchg_eax_reg(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->instr = ASM_XCHG;
new->ptr_instr = opcode;
new->len += 1;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED,
new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_OPMOD, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED,
new);
new->op[0].content = ASM_OP_BASE | ASM_OP_FIXED;
new->op[0].len = 0;
new->op[0].baser = ASM_REG_EAX;
new->op[0].regset = asm_proc_opsize(proc) ?
ASM_REGSET_R16 : ASM_REGSET_R32;
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_OPMOD, new);
#endif
return (new->len);
}
<file_sep>/src/db.c
/*
* alihack - lazy db api
* support fast encryption/compression
* copyright (c) 2011, beardbastard.
* 10/08/2011
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <assert.h>
#include "db.h"
int debug_flag = 0;
void debug(const char *fmt, ...)
{
va_list ap;
char buffer[1024];
va_start(ap, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, ap);
va_end(ap);
if(debug_flag)
fprintf(stderr, "%s", buffer);
}
char *db_strerror(db_t *db)
{
switch(db->error) {
case DB_ERROR_OPEN:
return ("DB_ERROR_HEADER");
case DB_ERROR_MAGIC:
return ("DB_ERROR_MAGIC");
case DB_ERROR_ITEM_MAGIC:
return ("DB_ERROR_ITEM_MAGIC");
case DB_ERROR_ITEM_HEADER:
return ("DB_ERROR_ITEM_HEADER");
case DB_ERROR_ITEM_DATA:
return ("DB_ERROR_ITEM_DATA");
case DB_ERROR_MALLOC:
return ("DB_ERROR_MALLOC");
case DB_ERROR_NONE:
return ("DB_ERROR_NONE");
}
return ("DB_ERROR_UNKNOWN");
}
int db_open(db_t *db, const char *filename, int mode)
{
int c, i, icount = -1;
unsigned int magic;
db_item_t *item = NULL;
struct stat st;
db->nitems = -1;
db->fd = 0;
db->items = NULL;
db->nroot = 0;
if(mode == DB_OPEN) {
if((db->fd = open(filename, O_RDONLY)) < 0) {
db->error = DB_ERROR_OPEN;
return (-1);
}
debug("checking magic: ");
if(read(db->fd, (char *)&magic, 4) != 4) {
db->error = DB_ERROR_MAGIC;
debug("failed!\n");
goto rdout;
}
if(magic != DB_MAGIC) {
db->error = DB_ERROR_HEADER;
debug("failed!\n");
goto rdout;
}
debug("ok!\nchecking items: ");
if(read(db->fd, (char *)&db->nitems, 4) != 4) {
db->error = DB_ERROR_HEADER;
debug("failed\n");
goto rdout;
}
if(read(db->fd, (char *)&db->nroot, 4) != 4) {
db->error = DB_ERROR_HEADER;
debug("failed\n");
goto rdout;
}
if(db->nitems < 0 || db->nroot < 0) {
db->error = DB_ERROR_HEADER;
debug("failed\n");
goto rdout;
}
for(icount = i = 0; i < db->nitems; icount++, i++) {
debug("\rparsing item %-10d/%-10d", icount, db->nitems);
if((item = (db_item_t *)malloc(sizeof(db_item_t))) == NULL) {
db->error = DB_ERROR_MALLOC;
break;
}
if(read(db->fd, (char *)&magic, 4) != 4) {
db->error = DB_ERROR_ITEM_HEADER;
break;
}
if(magic != DB_ITEM) {
db->error = DB_ERROR_ITEM_MAGIC;
break;
}
if((item = (db_item_t *)malloc(sizeof(db_item_t))) == NULL) {
db->error = DB_ERROR_MALLOC;
break;
}
if(((c = read(db->fd, (char *)item, sizeof(db_item_t) - 8)) != (sizeof(db_item_t) - 8)) || c < 0) {
db->error = DB_ERROR_ITEM_HEADER;
break;
}
if((item->data = (unsigned char *)malloc(item->size + 1)) == NULL) {
db->error = DB_ERROR_MALLOC;
break;
}
if((c = read(db->fd, item->data, item->size)) != item->size) {
db->error = DB_ERROR_ITEM_DATA;
break;
}
bb_list_add(&db->items, bb_list_node_alloc((void *)item));
}
rdout:
if(icount != db->nitems) {
close(db->fd);
icount = -1;
}
return (icount);
} else if(mode == DB_NEW || mode == DB_OVERWRITE) {
if(mode == DB_NEW)
if(stat(filename, &st) >= 0)
return (DB_ERROR_OPEN);
if((db->fd = open(filename, O_CREAT | O_RDWR)) < 0)
return (-1);
fchmod(db->fd, 0644);
db->nitems = 0;
db->items = NULL;
db->error = DB_ERROR_NONE;
return (1);
}
return (-1);
}
void db_item_add(db_t *db, char *name, int root, void *data, int size)
{
db_item_t *item = (db_item_t *)malloc(sizeof(db_item_t));
assert((item != NULL));
if(name == NULL)
name = "null";
memset(item->name, 0x00, sizeof(item->name));
sprintf(item->name, "%s", name);
item->size = size;
item->data = data;
item->root = root;
item->child = 0;
db->nitems++;
if(!root)
db->nroot++;
bb_list_add(&db->items, bb_list_node_alloc((void *)item));
db->error = DB_ERROR_NONE;
}
int db_item_set_data(db_item_t *item, void *data, int size)
{
if(item->data && item->size)
free(item->data);
else if(item->size <= 0)
return (0);
item->data = data;
item->size = size;
return (1);
}
db_item_t *db_item_get(db_t *db, char *name, int start)
{
bb_list_node_t *node;
db_item_t *item = NULL;
static db_item_t *last = NULL;
int noname = 0;
if(start)
last = NULL;
if(name == NULL)
noname = 1;
for(node = db->items->head; node; node = node->next) {
if((item = (db_item_t *)node->dptr) == NULL)
continue;
if(noname) {
if(last == NULL) {
last = item;
return (item);
}
if(last == item) {
if(node->next == NULL)
return (NULL);
item = (db_item_t *)node->next->dptr;
last = item;
return (item);
} else
continue;
}
if(!strcmp(item->name, name)) {
if(last == NULL) {
last = item;
return (item);
}
if(last == item) {
if(node->next == NULL) {
return (NULL);
}
item = (db_item_t *)node->next->dptr;
if(!strcmp(item->name, name)) {
last = item;
return (item);
} else continue;
}
}
}
last = NULL;
return (NULL);
}
int db_close(db_t *db, int save)
{
int i;
int magic = DB_ITEM;
bb_list_node_t *node;
db_item_t *item;
if(save) {
db->magic = DB_MAGIC;
write(db->fd, (char *)&db->magic, 4);
write(db->fd, (char *)&db->nitems, 4);
write(db->fd, (char *)&db->nroot, 4);
for(i = 0, node = db->items->head; i < db->nitems; node = node->next, i++) {
if((item = (db_item_t *)node->dptr) != NULL) {
write(db->fd, (char *)&magic, 4);
write(db->fd, (char *)&i, 4);
write(db->fd, (char *)&item->root, 4);
write(db->fd, (char *)item->name, sizeof(item->name));
write(db->fd, (char *)&item->size, sizeof(int));
write(db->fd, (char *)item->data, item->size);
free(item);
}
}
}
close(db->fd);
return (0);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_cli.c
/*
** $Id: op_cli.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_cli" opcode="0xfa"/>
*/
int op_cli(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->ptr_instr = opcode;
new->instr = ASM_CLI;
new->type = ASM_TYPE_WRITEFLAG;
/* Should be VIF for CPL = 3 and IOPL < CPL */
new->flagswritten = ASM_FLAG_IF;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_esc2.c
/*
** $Id: op_esc2.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_esc2" opcode="0xda"/>
*/
int op_esc2(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode + 1;
new->ptr_instr = opcode;
new->len += 1;
if (modrm->mod == 3)
switch (modrm->r) {
case 5: new->instr = ASM_FUCOMPP; break;
default: new->instr = ASM_BAD; break;
}
else
switch(modrm->r) {
case 0:
new->instr = ASM_FIADD;
break;
case 1:
new->instr = ASM_FIMUL;
break;
case 2:
new->instr = ASM_FICOM;
break;
case 3:
new->instr = ASM_FICOMP;
break;
case 4:
new->instr = ASM_FISUB;
break;
case 5:
new->instr = ASM_FISUBR;
break;
case 6:
new->instr = ASM_FIDIV;
break;
case 7:
new->instr = ASM_FIDIVR;
break;
}
if (!(*(opcode + 1) == 0xe9)) {
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#else
new->op[0].type = ASM_OTYPE_ENCODED;
operand_rmv(&new->op[0], opcode + 1, len - 1, proc);
new->len += new->op[0].len;
#endif
} else
new->len += 1;
return (new->len);
}
<file_sep>/src/libasm/src/arch/sparc/init_sparc.c
/**
* @file libasm/src/arch/sparc/init_sparc.c
** @ingroup sparc
*/
/*
**
** init_sparc.c in
**
** Author : <sk at devhell dot org>
** Started : Sun Nov 30 20:13:12 2003
** Updated : Thu Dec 4 03:01:07 2003
**
** $Id: init_sparc.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Fetching handler of the sparc architecture.
* @param ins
* @param buf
* @param len
* @param proc
*/
int fetch_sparc(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc)
{
vector_t *vec;
u_int dim[3];
int (*fetch)(asm_instr *, u_char *, u_int, asm_processor *);
int converted;
#if __BYTE_ORDER == __LITTLE_ENDIAN
u_char *ptr;
int i;
ptr = (u_char*) &converted;
for (i = 0; i < 4; i++)
*(ptr + i) = *(buf + 3 - i);
#if DEBUG_SPARC
printf("[DIS_SPARC] big endian -> little endian : 0x%08x - ", converted);
for (i = 31; i >= 0; i--){
printf("%i", MGETBIT(converted, i));
if (!(i % 8))
printf(" ");
}
puts("");
#endif
#else
memcpy(&converted, buf, 4);
#endif
ins->proc = proc;
ins->len = 4;
ins->ptr_instr = buf;
ins->nb_op = 0;
ins->type = ASM_TYPE_NONE;
/* Primary (implicit) address space */
ins->op[0].address_space = 0x80;
ins->op[1].address_space = 0x80;
ins->op[2].address_space = 0x80;
vec = aspect_vector_get(LIBASM_VECTOR_OPCODE_SPARC);
dim[0] = (converted & 0xC0000000) >> 30;
dim[1] = 0;
dim[2] = 0;
if (MGETBIT(converted, 31)) {
if (MGETBIT(converted, 30)) {
dim[1] = (converted >> 19) & 0x3f;
dim[2] = 0;
}
else {
dim[1] = (converted >> 19) & 0x3f;
if (dim[1] == 0x35) /* FPop2 */
dim[2] = (converted & 0x3E0) >> 5;
else
dim[2] = 0;
}
}
else {
if (MGETBIT(converted, 30)) {
dim[1] = 0;
dim[2] = 0;
}
else {
dim[1] = (converted >> 22) & 0x7;
dim[2] = 0;
}
}
fetch = aspect_vectors_select(vec, dim);
return (fetch(ins, (u_char*) &converted, len, proc));
printf("[DEBUG_SPARC] fetch_sparc:impossible execution path\n");
return (-1);
}
/**
* Initialize the sparc processor.
*
*/
int asm_init_sparc(asm_processor *proc)
{
struct s_asm_proc_sparc *inter;
proc->instr_table = sparc_instr_list;
proc->resolve_immediate = asm_resolve_sparc;
proc->resolve_data = 0;
proc->fetch = fetch_sparc;
proc->display_handle = asm_sparc_display_instr;
proc->type = ASM_PROC_SPARC;
proc->internals = inter = malloc(sizeof (struct s_asm_proc_sparc));
inter->bcc_table = sparc_bcc_list;
inter->brcc_table = sparc_brcc_list;
inter->fbcc_table = sparc_fbcc_list;
inter->shift_table = sparc_shift_list;
inter->movcc_table = sparc_movcc_list;
inter->movfcc_table = sparc_movfcc_list;
inter->movr_table = sparc_movr_list;
inter->fpop1_table = sparc_fpop1_list;
inter->fmovcc_table = sparc_fmovcc_list;
inter->fmovfcc_table = sparc_fmovfcc_list;
inter->fmovr_table = sparc_fmovr_list;
inter->fcmp_table = sparc_fcmp_list;
inter->tcc_table = sparc_tcc_list;
inter->op2_table = sparc_op2_table;
inter->op3_table = sparc_op3_table;
/**
* XXX: Check this code and update if necessary to follow line developpement.
*/
asm_arch_register(proc, 0);
return (1);
}
<file_sep>/src/libasm/src/arch/mips/tables_mips.c
/**
* @file libasm/src/arch/mips/tables_mips.c
** @ingroup mips
*/
/**
* @file libasm/src/arch/mips/tables_mips.c
* @brief MIPS processor mnemonic table.
* $Id: tables_mips.c 1397 2009-09-13 02:19:08Z may $
*
* fix and fill
* - Adam 'pi3' Zabrocki
*
*
* <NAME> - 2007
*/
#include <libasm.h>
#define ASM_OPCODE_MATH_START 0
#define ASM_OPCODE_BRANCH_START 35
#define ASM_OPCODE_BRANCH_SIZE 16
/**
* @struct e_mips_instrs
* @brief Fill in "struct e_mips_instr"
*
* This structure have filled "struct e_mips_instr"
* and it is used in register vectors for opcodes.
*
* First field have name for instruction.
* Second field have something like unique ID (ASM_MIPS_xxx)
* Third, Fourth and Fifth field have unequivocal identify instruction (0x0 when unused)
* Sixth field have pointer to handler.
*/
struct e_mips_instr e_mips_instrs [] = {
/* CPU: Arithmetic Instructions => ALL from MIPS Vol. 2 + Extra 2 */
{"add" ,ASM_MIPS_ADD ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_ADD ,0x0 ,asm_mips_add},
{"addi" ,ASM_MIPS_ADDI ,MIPS_OPCODE_ADDI ,0x0 ,0x0 ,asm_mips_addi},
{"addiu" ,ASM_MIPS_ADDIU ,MIPS_OPCODE_ADDIU ,0x0 ,0x0 ,asm_mips_addiu},
{"addu" ,ASM_MIPS_ADDU ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_ADDU ,0x0 ,asm_mips_addu},
{"clo" ,ASM_MIPS_CLO ,MIPS_OPCODE_SPECIAL2 ,MIPS_OPCODE_CLO ,0x0 ,asm_mips_clo},
{"clz" ,ASM_MIPS_CLZ ,MIPS_OPCODE_SPECIAL2 ,MIPS_OPCODE_CLZ ,0x0 ,asm_mips_clz},
//
{"dadd" ,ASM_MIPS_DADD ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DADD ,0x0 ,asm_mips_dadd},
{"daddi" ,ASM_MIPS_DADDI ,MIPS_OPCODE_DADDI ,0x0 ,0x0 ,asm_mips_daddi},
{"daddiu" ,ASM_MIPS_DADDIU ,MIPS_OPCODE_DADDIU ,0x0 ,0x0 ,asm_mips_daddiu},
{"daddu" ,ASM_MIPS_DADDU ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DADDU ,0x0 ,asm_mips_daddu},
{"dclo" ,ASM_MIPS_DCLO ,MIPS_OPCODE_SPECIAL2 ,MIPS_OPCODE_DCLO ,0x0 ,asm_mips_dclo},
{"dclz" ,ASM_MIPS_DCLZ ,MIPS_OPCODE_SPECIAL2 ,MIPS_OPCODE_DCLZ ,0x0 ,asm_mips_dclz},
{"ddiv" ,ASM_MIPS_DDIV ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DDIV ,0x0 ,asm_mips_ddiv},
{"ddivu" ,ASM_MIPS_DDIVU ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DDIVU ,0x0 ,asm_mips_ddivu},
//
{"div" ,ASM_MIPS_DIV ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DIV ,0x0 ,asm_mips_div},
{"divu" ,ASM_MIPS_DIVU ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DIVU ,0x0 ,asm_mips_divu},
//
{"dmult" ,ASM_MIPS_DMULT ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DMULT ,0x0 ,asm_mips_dmult},
{"dmultu" ,ASM_MIPS_DMULTU ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DMULTU ,0x0 ,asm_mips_dmultu},
{"dsub" ,ASM_MIPS_DSUB ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DSUB ,0x0 ,asm_mips_dsub},
{"dsubu" ,ASM_MIPS_DSUBU ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DSUBU ,0x0 ,asm_mips_dsubu},
//
{"madd" ,ASM_MIPS_MADD ,MIPS_OPCODE_SPECIAL2 ,MIPS_OPCODE_MADD ,0x0 ,asm_mips_madd},
{"maddu" ,ASM_MIPS_MADDU ,MIPS_OPCODE_SPECIAL2 ,MIPS_OPCODE_MADDU ,0x0 ,asm_mips_maddu},
{"msub" ,ASM_MIPS_MSUB ,MIPS_OPCODE_SPECIAL2 ,MIPS_OPCODE_MSUB ,0x0 ,asm_mips_msub},
{"msubu" ,ASM_MIPS_MSUBU ,MIPS_OPCODE_SPECIAL2 ,MIPS_OPCODE_MSUBU ,0x0 ,asm_mips_msubu},
{"mul" ,ASM_MIPS_MUL ,MIPS_OPCODE_SPECIAL2 ,MIPS_OPCODE_MUL ,0x0 ,asm_mips_mul},
{"mult" ,ASM_MIPS_MULT ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_MULT ,0x0 ,asm_mips_mult},
{"multu" ,ASM_MIPS_MULTU ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_MULTU ,0x0 ,asm_mips_multu},
{"slt" ,ASM_MIPS_SLT ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SLT ,0x0 ,asm_mips_slt},
{"slti" ,ASM_MIPS_SLTI ,MIPS_OPCODE_SLTI ,0x0 ,0x0 ,asm_mips_slti},
{"sltiu" ,ASM_MIPS_SLTIU ,MIPS_OPCODE_SLTIU ,0x0 ,0x0 ,asm_mips_sltiu},
{"sltu" ,ASM_MIPS_SLTU ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SLTU ,0x0 ,asm_mips_sltu},
{"sub" ,ASM_MIPS_SUB ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SUB ,0x0 ,asm_mips_sub},
{"subu" ,ASM_MIPS_SUBU ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SUBU ,0x0 ,asm_mips_subu},
/* Extra 2: */
{"seb" ,ASM_MIPS_SEB ,MIPS_OPCODE_SPECIAL3 ,MIPS_OPCODE_BSHFL ,MIPS_OPCODE_SEB ,asm_mips_seb},
{"seh" ,ASM_MIPS_SEH ,MIPS_OPCODE_SPECIAL3 ,MIPS_OPCODE_BSHFL ,MIPS_OPCODE_SEH ,asm_mips_seh},
/* CPU: Branch and Jump Instructions => ALL from MIPS Vol. 2 + Extra 2 */
{"b" ,ASM_MIPS_B ,MIPS_OPCODE_BEQ ,0x0 ,0x0 ,asm_mips_b},
{"bal" ,ASM_MIPS_BAL ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_BGEZAL ,0x0 ,asm_mips_bal},
{"beq" ,ASM_MIPS_BEQ ,MIPS_OPCODE_BEQ ,0x0 ,0x0 ,asm_mips_beq},
{"bgez" ,ASM_MIPS_BGEZ ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_BGEZ ,0x0 ,asm_mips_bgez},
{"bgezal" ,ASM_MIPS_BGEZAL ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_BGEZAL ,0x0 ,asm_mips_bgezal},
{"bgtz" ,ASM_MIPS_BGTZ ,MIPS_OPCODE_BGTZ ,0x0 ,0x0 ,asm_mips_bgtz},
{"blez" ,ASM_MIPS_BLEZ ,MIPS_OPCODE_BLEZ ,0x0 ,0x0 ,asm_mips_blez},
{"bltz" ,ASM_MIPS_BLTZ ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_BLTZ ,0x0 ,asm_mips_bltz},
{"bltzal" ,ASM_MIPS_BLTZAL ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_BLTZAL ,0x0 ,asm_mips_bltzal},
{"bne" ,ASM_MIPS_BNE ,MIPS_OPCODE_BNE ,0x0 ,0x0 ,asm_mips_bne},
{"j" ,ASM_MIPS_J ,MIPS_OPCODE_J ,0x0 ,0x0 ,asm_mips_j},
{"jal" ,ASM_MIPS_JAL ,MIPS_OPCODE_JAL ,0x0 ,0x0 ,asm_mips_jal},
{"jalr" ,ASM_MIPS_JALR ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_JALR ,0x0 ,asm_mips_jalr},
{"jr" ,ASM_MIPS_JR ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_JR ,0x0 ,asm_mips_jr},
/* Extra 2: */
{"jalr.hb" ,ASM_MIPS_JALR_HB ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_JALR ,0x0 ,asm_mips_jalr_hb},
{"jr.hb" ,ASM_MIPS_JR_HB ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_JR ,0x0 ,asm_mips_jr_hb},
/* CPU: Instruction Control Instructions => ALL from MIPS Vol. 2 + Extra 1 */
{"nop" ,ASM_MIPS_NOP ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SLL ,MIPS_OPCODE_NOP ,asm_mips_nop},
{"ssnop" ,ASM_MIPS_SSNOP ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SLL ,MIPS_OPCODE_SSNOP ,asm_mips_ssnop},
/* Extra 1: */
// {"ehb" ,ASM_MIPS_EHB ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SLL ,MIPS_OPCODE_EHB, asm_mips_ehb},
/* CPU: Load, Store, and Memory Control Instructions => ALL from MIPS Vol. 2 + Extra 1 */
{"lb" ,ASM_MIPS_LB ,MIPS_OPCODE_LB ,0x0 ,0x0 ,asm_mips_lb},
{"lbu" ,ASM_MIPS_LBU ,MIPS_OPCODE_LBU ,0x0 ,0x0 ,asm_mips_lbu},
//
{"ld" ,ASM_MIPS_LD ,MIPS_OPCODE_LD ,0x0 ,0x0 ,asm_mips_ld},
{"ldl" ,ASM_MIPS_LDL ,MIPS_OPCODE_LDL ,0x0 ,0x0 ,asm_mips_ldl},
{"ldr" ,ASM_MIPS_LDR ,MIPS_OPCODE_LDR ,0x0 ,0x0 ,asm_mips_ldr},
//
{"lh" ,ASM_MIPS_LH ,MIPS_OPCODE_LH ,0x0 ,0x0 ,asm_mips_lh},
{"lhu" ,ASM_MIPS_LHU ,MIPS_OPCODE_LHU ,0x0 ,0x0 ,asm_mips_lhu},
{"ll" ,ASM_MIPS_LL ,MIPS_OPCODE_LL ,0x0 ,0x0 ,asm_mips_ll},
//
{"lld" ,ASM_MIPS_LLD ,MIPS_OPCODE_LLD ,0x0 ,0x0 ,asm_mips_lld},
//
{"lw" ,ASM_MIPS_LW ,MIPS_OPCODE_LW ,0x0 ,0x0 ,asm_mips_lw},
{"lwl" ,ASM_MIPS_LWL ,MIPS_OPCODE_LWL ,0x0 ,0x0 ,asm_mips_lwl},
{"lwr" ,ASM_MIPS_LWR ,MIPS_OPCODE_LWR ,0x0 ,0x0 ,asm_mips_lwr},
//
{"lwu" ,ASM_MIPS_LWU ,MIPS_OPCODE_LWU ,0x0 ,0x0 ,asm_mips_lwu},
//
{"pref" ,ASM_MIPS_PREF ,MIPS_OPCODE_PREF ,0x0 ,0x0 ,asm_mips_pref},
{"sb" ,ASM_MIPS_SB ,MIPS_OPCODE_SB ,0x0 ,0x0 ,asm_mips_sb},
{"sc" ,ASM_MIPS_SC ,MIPS_OPCODE_SC ,0x0 ,0x0 ,asm_mips_sc},
//
{"scd" ,ASM_MIPS_SCD ,MIPS_OPCODE_SCD ,0x0 ,0x0 ,asm_mips_scd},
{"sd" ,ASM_MIPS_SD ,MIPS_OPCODE_SD ,0x0 ,0x0 ,asm_mips_sd},
{"sdl" ,ASM_MIPS_SDL ,MIPS_OPCODE_SDL ,0x0 ,0x0 ,asm_mips_sdl},
{"sdr" ,ASM_MIPS_SDR ,MIPS_OPCODE_SDR ,0x0 ,0x0 ,asm_mips_sdr},
//
{"sh" ,ASM_MIPS_SH ,MIPS_OPCODE_SH ,0x0 ,0x0 ,asm_mips_sh},
{"sw" ,ASM_MIPS_SW ,MIPS_OPCODE_SW ,0x0 ,0x0 ,asm_mips_sw},
{"swl" ,ASM_MIPS_SWL ,MIPS_OPCODE_SWL ,0x0 ,0x0 ,asm_mips_swl},
{"swr" ,ASM_MIPS_SWR ,MIPS_OPCODE_SWR ,0x0 ,0x0 ,asm_mips_swr},
{"sync" ,ASM_MIPS_SYNC ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SYNC ,0x0 ,asm_mips_sync},
/* Extra: 1 */
{"synci" ,ASM_MIPS_SYNCI ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_SYNCI ,0x0 ,asm_mips_synci},
/* CPU: Logical Instructions => ALL from MIPS Vol. 2 + Extra 3 */
{"and" ,ASM_MIPS_AND ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_AND ,0x0 ,asm_mips_and},
{"andi" ,ASM_MIPS_ANDI ,MIPS_OPCODE_ANDI ,0x0 ,0x0 ,asm_mips_andi},
{"lui" ,ASM_MIPS_LUI ,MIPS_OPCODE_LUI ,0x0 ,0x0 ,asm_mips_lui},
{"nor" ,ASM_MIPS_NOR ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_NOR ,0x0 ,asm_mips_nor},
{"or" ,ASM_MIPS_OR ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_OR ,0x0 ,asm_mips_or},
{"ori" ,ASM_MIPS_ORI ,MIPS_OPCODE_ORI ,0x0 ,0x0 ,asm_mips_ori},
{"xor" ,ASM_MIPS_XOR ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_XOR ,0x0 ,asm_mips_xor},
{"xori" ,ASM_MIPS_XORI ,MIPS_OPCODE_XORI ,0x0 ,0x0 ,asm_mips_xori},
/* Extra: 3 */
{"ext" ,ASM_MIPS_EXT ,MIPS_OPCODE_SPECIAL3 ,MIPS_OPCODE_EXT ,0x0 ,asm_mips_ext},
{"ins" ,ASM_MIPS_INS ,MIPS_OPCODE_SPECIAL3 ,MIPS_OPCODE_INS ,0x0 ,asm_mips_ins},
{"wsbh" ,ASM_MIPS_WSBH ,MIPS_OPCODE_SPECIAL3 ,MIPS_OPCODE_BSHFL ,MIPS_OPCODE_WSBH ,asm_mips_wsbh},
/* CPU: Move Instructions => ALL from MIPS Vol. 2 */
{"mfhi" ,ASM_MIPS_MFHI ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_MFHI ,0x0 ,asm_mips_mfhi},
{"mflo" ,ASM_MIPS_MFLO ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_MFLO ,0x0 ,asm_mips_mflo},
{"movf" ,ASM_MIPS_MOVF ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_MOVCI ,MIPS_OPCODE_MOVF ,asm_mips_movf},
{"movn" ,ASM_MIPS_MOVN ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_MOVN ,0x0 ,asm_mips_movn},
{"movt" ,ASM_MIPS_MOVT ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_MOVCI ,MIPS_OPCODE_MOVT ,asm_mips_movt},
{"movz" ,ASM_MIPS_MOVZ ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_MOVZ ,0x0 ,asm_mips_movz},
{"mthi" ,ASM_MIPS_MTHI ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_MTHI ,0x0 ,asm_mips_mthi},
{"mtlo" ,ASM_MIPS_MTLO ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_MTLO ,0x0 ,asm_mips_mtlo},
/* CPU: Shift Instructions => ALL from MIPS Vol. 2 + Extra 3 */
//
{"dsll" ,ASM_MIPS_DSLL ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DSLL ,0x0 ,asm_mips_dsll},
{"dsll32" ,ASM_MIPS_DSLL32 ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DSLL32 ,0x0 ,asm_mips_dsll32},
{"dsllv" ,ASM_MIPS_DSLLV ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DSLLV ,0x0 ,asm_mips_dsllv},
{"dsra" ,ASM_MIPS_DSRA ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DSRA ,0x0 ,asm_mips_dsra},
{"dsra32" ,ASM_MIPS_DSRA32 ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DSRA32 ,0x0 ,asm_mips_dsra32},
{"dsrav" ,ASM_MIPS_DSRAV ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DSRAV ,0x0 ,asm_mips_dsrav},
{"dsrl" ,ASM_MIPS_DSRL ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DSRL ,0x0 ,asm_mips_dsrl},
{"dsrl32" ,ASM_MIPS_DSRL32 ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DSRL32 ,0x0 ,asm_mips_dsrl32},
{"dsrlv" ,ASM_MIPS_DSRLV ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_DSRLV ,0x0 ,asm_mips_dsrlv},
//
{"sll" ,ASM_MIPS_SLL ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SLL ,0x0 ,asm_mips_sll},
{"sllv" ,ASM_MIPS_SLLV ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SLLV ,0x0 ,asm_mips_sllv},
{"sra" ,ASM_MIPS_SRA ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SRA ,0x0 ,asm_mips_sra},
{"srav" ,ASM_MIPS_SRAV ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SRAV ,0x0 ,asm_mips_srav},
{"srl" ,ASM_MIPS_SRL ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SRL ,0x0 ,asm_mips_srl},
{"srlv" ,ASM_MIPS_SRLV ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SRLV ,0x0 ,asm_mips_srlv},
/* Extra: 3 */
{"rdhwr" ,ASM_MIPS_RDHWR ,MIPS_OPCODE_SPECIAL3 ,MIPS_OPCODE_RDHWR ,0x0 ,asm_mips_rdhwr},
{"rotr" ,ASM_MIPS_ROTR ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SRL ,MIPS_OPCODE_ROTR ,asm_mips_rotr},
{"rotrv" ,ASM_MIPS_ROTRV ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SRLV ,MIPS_OPCODE_ROTRV ,asm_mips_rotrv},
/* CPU: Trap Instructions => ALL from MIPS Vol. 2 */
{"break" ,ASM_MIPS_BREAK ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_BREAK ,0x0 ,asm_mips_break},
{"syscall" ,ASM_MIPS_SYSCALL ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_SYSCALL ,0x0 ,asm_mips_syscall},
{"teq" ,ASM_MIPS_TEQ ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_TEQ ,0x0 ,asm_mips_teq},
{"teqi" ,ASM_MIPS_TEQI ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_TEQI ,0x0 ,asm_mips_teqi},
{"tge" ,ASM_MIPS_TGE ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_TGE ,0x0 ,asm_mips_tge},
{"tgei" ,ASM_MIPS_TGEI ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_TGEI ,0x0 ,asm_mips_tgei},
{"tgeiu" ,ASM_MIPS_TGEIU ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_TGEIU ,0x0 ,asm_mips_tgeiu},
{"tgeu" ,ASM_MIPS_TGEU ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_TGEU ,0x0 ,asm_mips_tgeu},
{"tlt" ,ASM_MIPS_TLT ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_TLT ,0x0 ,asm_mips_tlt},
{"tlti" ,ASM_MIPS_TLTI ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_TLTI ,0x0 ,asm_mips_tlti},
{"tltiu" ,ASM_MIPS_TLTIU ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_TLTIU ,0x0 ,asm_mips_tltiu},
{"tltu" ,ASM_MIPS_TLTU ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_TLTU ,0x0 ,asm_mips_tltu},
{"tne" ,ASM_MIPS_TNE ,MIPS_OPCODE_SPECIAL ,MIPS_OPCODE_TNE ,0x0 ,asm_mips_tne},
{"tnei" ,ASM_MIPS_TNEI ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_TNEI ,0x0 ,asm_mips_tnei},
/* CPU: Obsolete CPU Branch Instructions => ALL from MIPS Vol. 2 */
{"beql" ,ASM_MIPS_BEQL ,MIPS_OPCODE_BEQL ,0x0 ,0x0 ,asm_mips_beql},
{"bgezall" ,ASM_MIPS_BGEZALL ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_BGEZALL ,0x0 ,asm_mips_bgezall},
{"bgezl" ,ASM_MIPS_BGEZL ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_BGEZL ,0x0 ,asm_mips_bgezl},
{"bgtzl" ,ASM_MIPS_BGTZL ,MIPS_OPCODE_BGTZL ,0x0 ,0x0 ,asm_mips_bgtzl},
{"blezl" ,ASM_MIPS_BLEZL ,MIPS_OPCODE_BLEZL ,0x0 ,0x0 ,asm_mips_blezl},
{"bltzall" ,ASM_MIPS_BLTZALL ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_BLTZALL ,0x0 ,asm_mips_bltzall},
{"bltzl" ,ASM_MIPS_BLTZL ,MIPS_OPCODE_REGIMM ,MIPS_OPCODE_BLTZL ,0x0 ,asm_mips_bltzl},
{"bnel" ,ASM_MIPS_BNEL ,MIPS_OPCODE_BNEL ,0x0 ,0x0 ,asm_mips_bnel},
/* Coprocessor Branch Instructions - COP2 */
{"bc2f" ,ASM_MIPS_BC2F ,MIPS_OPCODE_COP2 ,MIPS_OPCODE_BCC2 ,0x0 ,asm_mips_bc2f},
{"bc2t" ,ASM_MIPS_BC2T ,MIPS_OPCODE_COP2 ,MIPS_OPCODE_BCC2 ,0x1 ,asm_mips_bc2t},
/* Coprocessor Execute Instruction - COP2 */
{"cop2" ,ASM_MIPS_COP2 ,MIPS_OPCODE_COP2 ,0x1 ,0x0 ,asm_mips_cop2},
/* Coprocessor Load and Store Instructions - COP2 */
{"ldc2" ,ASM_MIPS_LDC2 ,MIPS_OPCODE_LDC2 ,0x0 ,0x0 ,asm_mips_ldc2},
{"lwc2" ,ASM_MIPS_LWC2 ,MIPS_OPCODE_LWC2 ,0x0 ,0x0 ,asm_mips_lwc2},
{"sdc2" ,ASM_MIPS_SDC2 ,MIPS_OPCODE_SDC2 ,0x0 ,0x0 ,asm_mips_sdc2},
{"swc2" ,ASM_MIPS_SWC2 ,MIPS_OPCODE_SWC2 ,0x0 ,0x0 ,asm_mips_swc2},
/* Coprocessor Move Instructions - COP2 */
{"cfc2" ,ASM_MIPS_CFC2 ,MIPS_OPCODE_COP2 ,MIPS_OPCODE_CFC2 ,0x0 ,asm_mips_cfc2},
{"ctc2" ,ASM_MIPS_CTC2 ,MIPS_OPCODE_COP2 ,MIPS_OPCODE_CTC2 ,0x0 ,asm_mips_ctc2},
{"dmfc2" ,ASM_MIPS_DMFC2 ,MIPS_OPCODE_COP2 ,MIPS_OPCODE_DMFC2 ,0x0 ,asm_mips_dmfc2},
{"dmtc2" ,ASM_MIPS_DMTC2 ,MIPS_OPCODE_COP2 ,MIPS_OPCODE_DMTC2 ,0x0 ,asm_mips_dmtc2},
{"mfc2" ,ASM_MIPS_MFC2 ,MIPS_OPCODE_COP2 ,MIPS_OPCODE_MFC2 ,0x0 ,asm_mips_mfc2},
{"mtc2" ,ASM_MIPS_MTC2 ,MIPS_OPCODE_COP2 ,MIPS_OPCODE_MTC2 ,0x0 ,asm_mips_mtc2},
/* Obsolute Coprocessor Branch Instructions - COP2 */
{"bc2fl" ,ASM_MIPS_BC2FL ,MIPS_OPCODE_COP2 ,MIPS_OPCODE_BCC2 ,0x2 ,asm_mips_bc2fl},
{"bc2tl" ,ASM_MIPS_BC2TL ,MIPS_OPCODE_COP2 ,MIPS_OPCODE_BCC2 ,0x3 ,asm_mips_bc2tl},
/* COP1X Instructions */
{"lwxc1" ,ASM_MIPS_LWXC1 ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_LWXC1 ,0x0 ,asm_mips_lwxc1},
{"ldxc1" ,ASM_MIPS_LDXC1 ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_LDXC1 ,0x0 ,asm_mips_ldxc1},
{"luxc1" ,ASM_MIPS_LUXC1 ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_LUXC1 ,0x0 ,asm_mips_luxc1},
{"swxc1" ,ASM_MIPS_SWXC1 ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_SWXC1 ,0x0 ,asm_mips_swxc1},
{"sdxc1" ,ASM_MIPS_SDXC1 ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_SDXC1 ,0x0 ,asm_mips_sdxc1},
{"suxc1" ,ASM_MIPS_SUXC1 ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_SUXC1 ,0x0 ,asm_mips_suxc1},
{"prefx" ,ASM_MIPS_PREFX ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_PREFX ,0x0 ,asm_mips_prefx},
{"alnv.ps" ,ASM_MIPS_ALNV_PS ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_ALNV_PS ,0x0 ,asm_mips_alnv_ps},
{"madd.s" ,ASM_MIPS_MADD_S ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_MADD_S ,0x0 ,asm_mips_madd_s},
{"madd.d" ,ASM_MIPS_MADD_D ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_MADD_D ,0x0 ,asm_mips_madd_d},
{"madd.ps" ,ASM_MIPS_MADD_PS ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_MADD_PS ,0x0 ,asm_mips_madd_ps},
{"msub.s" ,ASM_MIPS_MSUB_S ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_MSUB_S ,0x0 ,asm_mips_msub_s},
{"msub.d" ,ASM_MIPS_MSUB_D ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_MSUB_D ,0x0 ,asm_mips_msub_d},
{"msub.ps" ,ASM_MIPS_MSUB_PS ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_MSUB_PS ,0x0 ,asm_mips_msub_ps},
{"nmadd.s" ,ASM_MIPS_NMADD_S ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_NMADD_S ,0x0 ,asm_mips_nmadd_s},
{"nmadd.d" ,ASM_MIPS_NMADD_D ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_NMADD_D ,0x0 ,asm_mips_nmadd_d},
{"nmadd.ps" ,ASM_MIPS_NMADD_PS ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_NMADD_PS ,0x0 ,asm_mips_nmadd_ps},
{"nmsub.s" ,ASM_MIPS_NMSUB_S ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_NMSUB_S ,0x0 ,asm_mips_nmsub_s},
{"nmsub.d" ,ASM_MIPS_NMSUB_D ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_NMSUB_D ,0x0 ,asm_mips_nmsub_d},
{"nmsub.ps" ,ASM_MIPS_NMSUB_PS ,MIPS_OPCODE_COP1X ,MIPS_OPCODE_NMSUB_PS ,0x0 ,asm_mips_nmsub_ps},
/* Privileged Instructions - COP0 */
{"mfc0" ,ASM_MIPS_MFC0 ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_MFC0 ,0x0 ,asm_mips_mfc0}, // !
{"dmfc0" ,ASM_MIPS_DMFC0 ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_DMFC0 ,0x0 ,asm_mips_dmfc0}, // !
{"dmtc0" ,ASM_MIPS_DMTC0 ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_DMTC0 ,0x0 ,asm_mips_dmtc0}, // !
{"mtc0" ,ASM_MIPS_MTC0 ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_MTC0 ,0x0 ,asm_mips_mtc0}, // !
{"tlbwi" ,ASM_MIPS_TLBWI ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_TLBWI ,0x0 ,asm_mips_tlbwi},
{"tlbwr" ,ASM_MIPS_TLBWR ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_TLBWR ,0x0 ,asm_mips_tlbwr},
{"eret" ,ASM_MIPS_ERET ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_ERET ,0x0 ,asm_mips_eret},
{"tlbp" ,ASM_MIPS_TLBP ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_TLBP ,0x0 ,asm_mips_tlbp},
{"tlbr" ,ASM_MIPS_TLBR ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_TLBR ,0x0 ,asm_mips_tlbr},
{"wait" ,ASM_MIPS_WAIT ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_WAIT ,0x0 ,asm_mips_wait},
/* EJTAG Instruction... */
{"deret" ,ASM_MIPS_DERET ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_DERET ,0x0 ,asm_mips_deret},
{"sdbbp" ,ASM_MIPS_SDBBP ,MIPS_OPCODE_COP0 ,MIPS_OPCODE_SDBBP ,0x0 ,asm_mips_sdbbp},
/*TODO
* - FPU insns
*/
/* FPU arithmetics */
{"abs.s" ,ASM_MIPS_ABS_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_ABS ,MIPS_OPCODE_FMT_S ,asm_mips_abs_s}, // !
{"abs.d" ,ASM_MIPS_ABS_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_ABS ,MIPS_OPCODE_FMT_D ,asm_mips_abs_d}, // !
{"abs.ps" ,ASM_MIPS_ABS_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_ABS ,MIPS_OPCODE_FMT_PS ,asm_mips_abs_ps},
{"add.s" ,ASM_MIPS_ADD_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_ADD ,MIPS_OPCODE_FMT_S ,asm_mips_add_s}, // !
{"add.d" ,ASM_MIPS_ADD_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_ADD ,MIPS_OPCODE_FMT_D ,asm_mips_add_d}, // !
{"add.ps" ,ASM_MIPS_ADD_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_ADD ,MIPS_OPCODE_FMT_PS ,asm_mips_add_ps},
// <--- START --->
{"div.s" ,ASM_MIPS_DIV_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_DIV ,MIPS_OPCODE_FMT_S ,asm_mips_div_s},
{"div.d" ,ASM_MIPS_DIV_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_DIV ,MIPS_OPCODE_FMT_D ,asm_mips_div_d},
{"mul.s" ,ASM_MIPS_MUL_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MUL ,MIPS_OPCODE_FMT_S ,asm_mips_mul_s}, // !
{"mul.d" ,ASM_MIPS_MUL_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MUL ,MIPS_OPCODE_FMT_D ,asm_mips_mul_d}, // !
{"mul.ps" ,ASM_MIPS_MUL_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MUL ,MIPS_OPCODE_FMT_PS ,asm_mips_mul_ps},
{"neg.s" ,ASM_MIPS_NEG_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_NEG ,MIPS_OPCODE_FMT_S ,asm_mips_neg_s}, // !
{"neg.d" ,ASM_MIPS_NEG_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_NEG ,MIPS_OPCODE_FMT_D ,asm_mips_neg_d}, // !
{"neg.ps" ,ASM_MIPS_NEG_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_NEG ,MIPS_OPCODE_FMT_PS ,asm_mips_neg_ps},
{"recip.s" ,ASM_MIPS_RECIP_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_RECIP ,MIPS_OPCODE_FMT_S ,asm_mips_recip_s},
{"recip.d" ,ASM_MIPS_RECIP_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_RECIP ,MIPS_OPCODE_FMT_D ,asm_mips_recip_d},
{"rsqrt.s" ,ASM_MIPS_RSQRT_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_RSQRT ,MIPS_OPCODE_FMT_S ,asm_mips_rsqrt_s},
{"rsqrt.d" ,ASM_MIPS_RSQRT_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_RSQRT ,MIPS_OPCODE_FMT_D ,asm_mips_rsqrt_d},
{"sqrt.s" ,ASM_MIPS_SQRT_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_SQRT ,MIPS_OPCODE_FMT_S ,asm_mips_sqrt_s},
{"sqrt.d" ,ASM_MIPS_SQRT_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_SQRT ,MIPS_OPCODE_FMT_D ,asm_mips_sqrt_d},
{"sub.s" ,ASM_MIPS_SUB_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_SUB ,MIPS_OPCODE_FMT_S ,asm_mips_sub_s}, // !
{"sub.d" ,ASM_MIPS_SUB_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_SUB ,MIPS_OPCODE_FMT_D ,asm_mips_sub_d}, // !
{"sub.ps" ,ASM_MIPS_SUB_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_SUB ,MIPS_OPCODE_FMT_PS ,asm_mips_sub_ps},
/* FPU Branch Instructions */
{"bc1f" ,ASM_MIPS_BC1F ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_BCC2 ,0x0 ,asm_mips_bc1f},
{"bc1t" ,ASM_MIPS_BC1T ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_BCC2 ,0x1 ,asm_mips_bc1t},
/* FPU Convert Instructions */
{"ceil.l.s" ,ASM_MIPS_CEIL_L_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CEIL_L ,MIPS_OPCODE_FMT_S ,asm_mips_ceil_l_s},
{"ceil.l.d" ,ASM_MIPS_CEIL_L_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CEIL_L ,MIPS_OPCODE_FMT_D ,asm_mips_ceil_l_d},
{"ceil.w.s" ,ASM_MIPS_CEIL_W_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CEIL_W ,MIPS_OPCODE_FMT_S ,asm_mips_ceil_w_s},
{"ceil.w.d" ,ASM_MIPS_CEIL_W_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CEIL_W ,MIPS_OPCODE_FMT_D ,asm_mips_ceil_w_d},
{"cvt.d.s" ,ASM_MIPS_CVT_D_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_D ,MIPS_OPCODE_FMT_S ,asm_mips_cvt_d_s},
{"cvt.d.w" ,ASM_MIPS_CVT_D_W ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_D ,MIPS_OPCODE_FMT_W ,asm_mips_cvt_d_w},
{"cvt.d.l" ,ASM_MIPS_CVT_D_L ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_D ,MIPS_OPCODE_FMT_L ,asm_mips_cvt_d_l},
{"cvt.l.s" ,ASM_MIPS_CVT_L_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_L ,MIPS_OPCODE_FMT_S ,asm_mips_cvt_l_s},
{"cvt.l.d" ,ASM_MIPS_CVT_L_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_L ,MIPS_OPCODE_FMT_D ,asm_mips_cvt_l_d},
{"cvt.ps.s" ,ASM_MIPS_CVT_PS_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_PS_S ,MIPS_OPCODE_FMT_S ,asm_mips_cvt_ps_s},
{"cvt.s.d" ,ASM_MIPS_CVT_S_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_S ,MIPS_OPCODE_FMT_D ,asm_mips_cvt_s_d},
{"cvt.s.w" ,ASM_MIPS_CVT_S_W ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_S ,MIPS_OPCODE_FMT_W ,asm_mips_cvt_s_w},
{"cvt.s.l" ,ASM_MIPS_CVT_S_L ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_S ,MIPS_OPCODE_FMT_L ,asm_mips_cvt_s_l},
{"cvt.s.pl" ,ASM_MIPS_CVT_S_PL ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_S_PL ,MIPS_OPCODE_FMT_PS ,asm_mips_cvt_s_pl},
{"cvt.s.pu" ,ASM_MIPS_CVT_S_PU ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_S ,MIPS_OPCODE_FMT_PS ,asm_mips_cvt_s_pu},
{"cvt.w.s" ,ASM_MIPS_CVT_W_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_W ,MIPS_OPCODE_FMT_S ,asm_mips_cvt_w_s},
{"cvt.w.d" ,ASM_MIPS_CVT_W_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CVT_W ,MIPS_OPCODE_FMT_D ,asm_mips_cvt_w_d},
{"floor.l.s",ASM_MIPS_FLOOR_L_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_FLOOR_L,MIPS_OPCODE_FMT_S ,asm_mips_floor_l_s},
{"floor.l.d",ASM_MIPS_FLOOR_L_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_FLOOR_L,MIPS_OPCODE_FMT_D ,asm_mips_floor_l_d},
{"floor.w.s",ASM_MIPS_FLOOR_W_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_FLOOR_W,MIPS_OPCODE_FMT_S ,asm_mips_floor_w_s},
{"floor.w.d",ASM_MIPS_FLOOR_W_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_FLOOR_W,MIPS_OPCODE_FMT_D ,asm_mips_floor_w_d},
{"round.l.s",ASM_MIPS_ROUND_L_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_ROUND_L,MIPS_OPCODE_FMT_S ,asm_mips_round_l_s},
{"round.l.d",ASM_MIPS_ROUND_L_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_ROUND_L,MIPS_OPCODE_FMT_D ,asm_mips_round_l_d},
{"round.w.s",ASM_MIPS_ROUND_W_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_ROUND_W,MIPS_OPCODE_FMT_S ,asm_mips_round_w_s},
{"round.w.d",ASM_MIPS_ROUND_W_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_ROUND_W,MIPS_OPCODE_FMT_D ,asm_mips_round_w_d},
{"trunc.l.s",ASM_MIPS_TRUNC_L_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_TRUNC_L,MIPS_OPCODE_FMT_S ,asm_mips_trunc_l_s},
{"trunc.l.d",ASM_MIPS_TRUNC_L_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_TRUNC_L,MIPS_OPCODE_FMT_D ,asm_mips_trunc_l_d},
{"trunc.w.s",ASM_MIPS_TRUNC_W_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_TRUNC_W,MIPS_OPCODE_FMT_S ,asm_mips_trunc_w_s},
{"trunc.w.d",ASM_MIPS_TRUNC_W_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_TRUNC_W,MIPS_OPCODE_FMT_D ,asm_mips_trunc_w_d},
/* FPU Load, Store and Memory Control Instructions */
{"ldc1" ,ASM_MIPS_LDC1 ,MIPS_OPCODE_LDC1 ,0x0 ,0x0 ,asm_mips_ldc1},
{"lwc1" ,ASM_MIPS_LWC1 ,MIPS_OPCODE_LWC1 ,0x0 ,0x0 ,asm_mips_lwc1},
{"sdc1" ,ASM_MIPS_SDC1 ,MIPS_OPCODE_SDC1 ,0x0 ,0x0 ,asm_mips_sdc1},
{"swc1" ,ASM_MIPS_SWC1 ,MIPS_OPCODE_SWC1 ,0x0 ,0x0 ,asm_mips_swc1},
/* FPU Move Instructions */
{"cfc1" ,ASM_MIPS_CFC1 ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CFC1 ,0x0 ,asm_mips_cfc1},
{"ctc1" ,ASM_MIPS_CTC1 ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_CTC1 ,0x0 ,asm_mips_ctc1},
{"mfc1" ,ASM_MIPS_MFC1 ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MFC1 ,0x0 ,asm_mips_mfc1},
{"mtc1" ,ASM_MIPS_MTC1 ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MTC1 ,0x0 ,asm_mips_mtc1},
{"mov.s" ,ASM_MIPS_MOV_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOV ,MIPS_OPCODE_FMT_S ,asm_mips_mov_s},
{"mov.d" ,ASM_MIPS_MOV_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOV ,MIPS_OPCODE_FMT_D ,asm_mips_mov_d},
{"mov.ps" ,ASM_MIPS_MOV_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOV ,MIPS_OPCODE_FMT_PS ,asm_mips_mov_ps},
{"movf.s" ,ASM_MIPS_MOVF_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVCF ,MIPS_OPCODE_FMT_S ,asm_mips_movcf_s},
{"movf.d" ,ASM_MIPS_MOVF_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVCF ,MIPS_OPCODE_FMT_D ,asm_mips_movcf_d},
{"movf.ps" ,ASM_MIPS_MOVF_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVCF ,MIPS_OPCODE_FMT_PS ,asm_mips_movcf_ps},
{"movt.s" ,ASM_MIPS_MOVT_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVCF ,MIPS_OPCODE_FMT_S ,asm_mips_movcf_s},
{"movt.d" ,ASM_MIPS_MOVT_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVCF ,MIPS_OPCODE_FMT_D ,asm_mips_movcf_d},
{"movt.ps" ,ASM_MIPS_MOVT_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVCF ,MIPS_OPCODE_FMT_PS ,asm_mips_movcf_ps},
{"movn.s" ,ASM_MIPS_MOVN_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVN ,MIPS_OPCODE_FMT_S ,asm_mips_movn_s},
{"movn.d" ,ASM_MIPS_MOVN_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVN ,MIPS_OPCODE_FMT_D ,asm_mips_movn_d},
{"movn.ps" ,ASM_MIPS_MOVN_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVN ,MIPS_OPCODE_FMT_PS ,asm_mips_movn_ps},
{"movz.s" ,ASM_MIPS_MOVZ_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVZ ,MIPS_OPCODE_FMT_S ,asm_mips_movz_s},
{"movz.d" ,ASM_MIPS_MOVZ_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVZ ,MIPS_OPCODE_FMT_D ,asm_mips_movz_d},
{"movz.ps" ,ASM_MIPS_MOVZ_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_F_MOVZ ,MIPS_OPCODE_FMT_PS ,asm_mips_movz_ps},
/* FPU Absolute Branch Instructions */
{"bc1fl" ,ASM_MIPS_BC1FL ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_BCC2 ,0x2 ,asm_mips_bc1fl},
{"bc1tl" ,ASM_MIPS_BC1TL ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_BCC2 ,0x3 ,asm_mips_bc1tl},
/* BUGFIX */
{"dmtc1" ,ASM_MIPS_DMTC1 ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_DMTC2 ,0x0 ,asm_mips_dmtc1},
{"dmfc1" ,ASM_MIPS_DMFC1 ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_DMFC2 ,0x0 ,asm_mips_dmfc1},
/* C.cond.fmt glupie instrukcje :) */
{"c.f.s" ,ASM_MIPS_C_F_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_F ,MIPS_OPCODE_FMT_S ,asm_mips_c_f_s},
{"c.f.d" ,ASM_MIPS_C_F_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_F ,MIPS_OPCODE_FMT_D ,asm_mips_c_f_d},
{"c.f.ps" ,ASM_MIPS_C_F_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_F ,MIPS_OPCODE_FMT_PS ,asm_mips_c_f_ps},
{"c.un.s" ,ASM_MIPS_C_UN_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_UN ,MIPS_OPCODE_FMT_S ,asm_mips_c_un_s},
{"c.un.d" ,ASM_MIPS_C_UN_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_UN ,MIPS_OPCODE_FMT_D ,asm_mips_c_un_d},
{"c.un.ps" ,ASM_MIPS_C_UN_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_UN ,MIPS_OPCODE_FMT_PS ,asm_mips_c_un_ps},
{"c.eq.s" ,ASM_MIPS_C_EQ_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_EQ ,MIPS_OPCODE_FMT_S ,asm_mips_c_eq_s},
{"c.eq.d" ,ASM_MIPS_C_EQ_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_EQ ,MIPS_OPCODE_FMT_D ,asm_mips_c_eq_d},
{"c.eq.ps" ,ASM_MIPS_C_EQ_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_EQ ,MIPS_OPCODE_FMT_PS ,asm_mips_c_eq_ps},
{"c.ueq.s" ,ASM_MIPS_C_UEQ_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_UEQ ,MIPS_OPCODE_FMT_S ,asm_mips_c_ueq_s},
{"c.ueq.d" ,ASM_MIPS_C_UEQ_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_UEQ ,MIPS_OPCODE_FMT_D ,asm_mips_c_ueq_d},
{"c.ueq.ps" ,ASM_MIPS_C_UEQ_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_UEQ ,MIPS_OPCODE_FMT_PS ,asm_mips_c_ueq_ps},
{"c.olt.s" ,ASM_MIPS_C_OLT_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_OLT ,MIPS_OPCODE_FMT_S ,asm_mips_c_olt_s},
{"c.olt.d" ,ASM_MIPS_C_OLT_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_OLT ,MIPS_OPCODE_FMT_D ,asm_mips_c_olt_d},
{"c.olt.ps" ,ASM_MIPS_C_OLT_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_OLT ,MIPS_OPCODE_FMT_PS ,asm_mips_c_olt_ps},
{"c.ult.s" ,ASM_MIPS_C_ULT_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_ULT ,MIPS_OPCODE_FMT_S ,asm_mips_c_ult_s},
{"c.ult.d" ,ASM_MIPS_C_ULT_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_ULT ,MIPS_OPCODE_FMT_D ,asm_mips_c_ult_d},
{"c.ult.ps" ,ASM_MIPS_C_ULT_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_ULT ,MIPS_OPCODE_FMT_PS ,asm_mips_c_ult_ps},
{"c.ole.s" ,ASM_MIPS_C_OLE_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_OLE ,MIPS_OPCODE_FMT_S ,asm_mips_c_ole_s},
{"c.ole.d" ,ASM_MIPS_C_OLE_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_OLE ,MIPS_OPCODE_FMT_D ,asm_mips_c_ole_d},
{"c.ole.ps" ,ASM_MIPS_C_OLE_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_OLE ,MIPS_OPCODE_FMT_PS ,asm_mips_c_ole_ps},
{"c.ule.s" ,ASM_MIPS_C_ULE_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_ULE ,MIPS_OPCODE_FMT_S ,asm_mips_c_ule_s},
{"c.ule.d" ,ASM_MIPS_C_ULE_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_ULE ,MIPS_OPCODE_FMT_D ,asm_mips_c_ule_d},
{"c.ule.ps" ,ASM_MIPS_C_ULE_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_ULE ,MIPS_OPCODE_FMT_PS ,asm_mips_c_ule_ps},
{"c.sf.s" ,ASM_MIPS_C_SF_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_SF ,MIPS_OPCODE_FMT_S ,asm_mips_c_sf_s},
{"c.sf.d" ,ASM_MIPS_C_SF_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_SF ,MIPS_OPCODE_FMT_D ,asm_mips_c_sf_d},
{"c.sf.ps" ,ASM_MIPS_C_SF_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_SF ,MIPS_OPCODE_FMT_PS ,asm_mips_c_sf_ps},
{"c.ngle.s" ,ASM_MIPS_C_NGLE_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGLE ,MIPS_OPCODE_FMT_S ,asm_mips_c_ngle_s},
{"c.ngle.d" ,ASM_MIPS_C_NGLE_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGLE ,MIPS_OPCODE_FMT_D ,asm_mips_c_ngle_d},
{"c.ngle.ps",ASM_MIPS_C_NGLE_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGLE ,MIPS_OPCODE_FMT_PS ,asm_mips_c_ngle_ps},
{"c.seq.s" ,ASM_MIPS_C_SEQ_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_SEQ ,MIPS_OPCODE_FMT_S ,asm_mips_c_seq_s},
{"c.seq.d" ,ASM_MIPS_C_SEQ_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_SEQ ,MIPS_OPCODE_FMT_D ,asm_mips_c_seq_d},
{"c.seq.ps" ,ASM_MIPS_C_SEQ_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_SEQ ,MIPS_OPCODE_FMT_PS ,asm_mips_c_seq_ps},
{"c.ngl.s" ,ASM_MIPS_C_NGL_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGL ,MIPS_OPCODE_FMT_S ,asm_mips_c_ngl_s},
{"c.ngl.d" ,ASM_MIPS_C_NGL_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGL ,MIPS_OPCODE_FMT_D ,asm_mips_c_ngl_d},
{"c.ngl.ps" ,ASM_MIPS_C_NGL_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGL ,MIPS_OPCODE_FMT_PS ,asm_mips_c_ngl_ps},
{"c.lt.s" ,ASM_MIPS_C_LT_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_LT ,MIPS_OPCODE_FMT_S ,asm_mips_c_lt_s},
{"c.lt.d" ,ASM_MIPS_C_LT_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_LT ,MIPS_OPCODE_FMT_D ,asm_mips_c_lt_d},
{"c.lt.ps" ,ASM_MIPS_C_LT_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_LT ,MIPS_OPCODE_FMT_PS ,asm_mips_c_lt_ps},
{"c.nge.s" ,ASM_MIPS_C_NGE_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGE ,MIPS_OPCODE_FMT_S ,asm_mips_c_nge_s},
{"c.nge.d" ,ASM_MIPS_C_NGE_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGE ,MIPS_OPCODE_FMT_D ,asm_mips_c_nge_d},
{"c.nge.ps" ,ASM_MIPS_C_NGE_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGE ,MIPS_OPCODE_FMT_PS ,asm_mips_c_nge_ps},
{"c.le.s" ,ASM_MIPS_C_LE_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_LE ,MIPS_OPCODE_FMT_S ,asm_mips_c_le_s},
{"c.le.d" ,ASM_MIPS_C_LE_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_LE ,MIPS_OPCODE_FMT_D ,asm_mips_c_le_d},
{"c.le.ps" ,ASM_MIPS_C_LE_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_LE ,MIPS_OPCODE_FMT_PS ,asm_mips_c_le_ps},
{"c.ngt.s" ,ASM_MIPS_C_NGT_S ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGT ,MIPS_OPCODE_FMT_S ,asm_mips_c_ngt_s},
{"c.ngt.d" ,ASM_MIPS_C_NGT_D ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGT ,MIPS_OPCODE_FMT_D ,asm_mips_c_ngt_d},
{"c.ngt.ps" ,ASM_MIPS_C_NGT_PS ,MIPS_OPCODE_COP1 ,MIPS_OPCODE_COND_NGT ,MIPS_OPCODE_FMT_PS ,asm_mips_c_ngt_ps},
/* mnemonic code index1 index 2 index 3 func pointer */
{ (const char *) -1, (int) -1, (int) -1, (int) -1, (int) -1, NULL }
};
/**
* @struct e_mips_registers
* @brief Fill in "struct e_mips_register"
*
* This structure have filled "struct e_mips_instr"
*
* First field have name for register.
* Second field have alternative name for register.
* Third field have unique ID (ASM_MIPS_REG_xxx)
*/
struct e_mips_register e_mips_registers [] = {
{"zero","r0","f0",ASM_MIPS_REG_ZERO},
{"at","r1","f1",ASM_MIPS_REG_AT},
{"v0","r2","f2",ASM_MIPS_REG_V0},
{"v1","r3","f3",ASM_MIPS_REG_V1},
{"a0","r4","f4",ASM_MIPS_REG_A0},
{"a1","r5","f5",ASM_MIPS_REG_A1},
{"a2","r6","f6",ASM_MIPS_REG_A2},
{"a3","r7","f7",ASM_MIPS_REG_A3},
{"t0","r8","f8",ASM_MIPS_REG_T0},
{"t1","r9","f9",ASM_MIPS_REG_T1},
{"t2","r10","f10",ASM_MIPS_REG_T2},
{"t3","r11","f11",ASM_MIPS_REG_T3},
{"t4","r12","f12",ASM_MIPS_REG_T4},
{"t5","r13","f13",ASM_MIPS_REG_T5},
{"t6","r14","f14",ASM_MIPS_REG_T6},
{"t7","r15","f15",ASM_MIPS_REG_T7},
{"s0","r16","f16",ASM_MIPS_REG_S0},
{"s1","r17","f17",ASM_MIPS_REG_S1},
{"s2","r18","f18",ASM_MIPS_REG_S2},
{"s3","r19","f19",ASM_MIPS_REG_S3},
{"s4","r20","f20",ASM_MIPS_REG_S4},
{"s5","r21","f21",ASM_MIPS_REG_S5},
{"s6","r22","f22",ASM_MIPS_REG_S6},
{"s7","r23","f23",ASM_MIPS_REG_S7},
{"t8","r24","f24",ASM_MIPS_REG_T8},
{"t9","r25","f25",ASM_MIPS_REG_T9},
{"k0","r26","f26",ASM_MIPS_REG_K0},
{"k1","r27","f27",ASM_MIPS_REG_K1},
{"gp","r28","f28",ASM_MIPS_REG_GP},
{"sp","r29","f29",ASM_MIPS_REG_SP},
{"fp","r30","f30",ASM_MIPS_REG_FP},
{"ra","r31","f31",ASM_MIPS_REG_RA},
{"INDEX","r0","f0",ASM_MIPS_REG_ZERO},
{"RANDOM","r1","f1",ASM_MIPS_REG_AT},
{"ENTRYLO0","r2","f2",ASM_MIPS_REG_V0},
{"ENTRYLO1","r3","f3",ASM_MIPS_REG_V1},
{"CONTEXT","r4","f4",ASM_MIPS_REG_A0},
{"PAGEMASK","r5","f5",ASM_MIPS_REG_A1},
{"WIRED","r6","f6",ASM_MIPS_REG_A2},
{"INFO","r7","f7",ASM_MIPS_REG_A3},
{"BADVADDR","r8","f8",ASM_MIPS_REG_T0},
{"COUNT","r9","f9",ASM_MIPS_REG_T1},
{"ENTRYHI","r10","f10",ASM_MIPS_REG_T2},
{"COMPARE","r11","f11",ASM_MIPS_REG_T3},
{"STATUS","r12","f12",ASM_MIPS_REG_T4},
{"CAUSE","r13","f13",ASM_MIPS_REG_T5},
{"EPC","r14","f14",ASM_MIPS_REG_T6},
{"PRID","r15","f15",ASM_MIPS_REG_T7},
{"CONFIG","r16","f16",ASM_MIPS_REG_S0},
{"LLADDR","r17","f17",ASM_MIPS_REG_S1},
{"WATCHLO","r18","f18",ASM_MIPS_REG_S2},
{"WATCHHI","r19","f19",ASM_MIPS_REG_S3},
{"XCONTEXT","r20","f20",ASM_MIPS_REG_S4},
{"FRAMEMASK","r21","f21",ASM_MIPS_REG_S5},
{"DIAGNOSTIC","r22","f22",ASM_MIPS_REG_S6},
{"DEBUG","r23","f23",ASM_MIPS_REG_S7},
{"DEPC","r24","f24",ASM_MIPS_REG_T8},
{"PERFORMANCE","r25","f25",ASM_MIPS_REG_T9},
{"ECC","r26","f26",ASM_MIPS_REG_K0},
{"CACHEERR","r27","f27",ASM_MIPS_REG_K1},
{"TAGLO","r28","f28",ASM_MIPS_REG_GP},
{"TAGHI","r29","f29",ASM_MIPS_REG_SP},
{"ERROREPC","r30","f30",ASM_MIPS_REG_FP},
{"DESAVE","r31","f31",ASM_MIPS_REG_RA},
/* ext_mnemonic mnemonic fpu_mnemonic code */
{ (const char *) -1, (const char *) -1, (const char *) -1, (int) -1 }
};
<file_sep>/src/libaspect/init.c
/**
* @file libaspect/init.c
** @ingroup libaspect
**
** @brief Implement the modularity for the framework.
**
** Started Dec 22 2006 02:57:03 jfv
**
**
** $Id: init.c 1439 2010-12-13 10:27:16Z may $
**
*/
#include "libaspect.h"
static u_char aspect_initialized = 0;
/***************** ERESI Constructors help functions **********************/
static u_char called_ctors = 0;
static u_char dbgpresent = 0;
static u_char kshpresent = 0;
static u_char kdbgpresent = 0;
/**
* @brief Count the number of constructors already called in the framework (update internal variable)
*/
void aspect_called_ctors_inc()
{
if (!called_ctors)
e2dbg_presence_set();
called_ctors++;
}
/**
* @brief Test if we called all constructors or not (currently we have 3)
*/
int aspect_called_ctors_finished()
{
return (called_ctors == 3);
}
/*************** E2DBG presence help functions *******************/
/**
* @brief Set debugger presence
*/
void e2dbg_presence_set()
{
dbgpresent = 1;
#if 1 //__DEBUG_E2DBG__
//write(2, " [*] Enabled debugger presence\n", 31);
#endif
}
/** @brief Reset debugger presence */
void e2dbg_presence_reset()
{
dbgpresent = 0;
#if 1 //__DEBUG_E2DBG__
//write(2, " [*] Disabled debugger presence\n", 32);
#endif
}
/* Get the Debugger presence information */
u_char e2dbg_presence_get()
{
#if 1 //__DEBUG_E2DBG__
//write(2, " [*] Probbing debugger presence\n", 32);
#endif
return (dbgpresent);
}
/**
* @brief Set kernsh presence flag
*/
void kernsh_present_set()
{
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
kshpresent = 1;
PROFILER_OUT(__FILE__, __FUNCTION__, __LINE__);
}
/**
* @brief Get presence of kernsh
* @return 1 on success, 0 on error
*/
int kernsh_is_present()
{
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, kshpresent);
}
/**
* @brief Set presence of kedbg
*/
void kedbg_present_set()
{
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
kdbgpresent = 1;
PROFILER_OUT(__FILE__, __FUNCTION__, __LINE__);
}
/**
* @brief Get presence of kedbg
* @return 1 on success, 0 on error
*/
int kedbg_is_present()
{
PROFILER_IN(__FILE__, __FUNCTION__, __LINE__);
PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, kdbgpresent);
}
/** Are we in kernel mode */
u_char e2dbg_kpresence_get()
{
return (aspectworld.kernel_mode);
}
/** Enable or disable kernel mode */
void e2dbg_kpresence_set(u_char pres)
{
aspectworld.kernel_mode = pres;
}
/**************** LIBASPECT initiazation ******************/
/** @brief Initialize the vector hash table */
static void aspect_vectors_init()
{
vector_hash = (hash_t *) hash_find("type_vector");
}
/** @brief Initialize base types : each type has a hash table of typed objects */
static void aspect_types_init()
{
hash_init(&types_hash, "types", 11, ASPECT_TYPE_UNKNOW);
aspect_basetypes_create();
}
/** @brief Configuration initialization in libaspect */
static void aspect_config_init()
{
memset(&aspectworld, 0x00, sizeof(aspectworld_t));
// Just for debugging
//aspectworld.profile = (void *) puts;
hash_init(&aspectworld.config_hash, "configuration",
CONFIG_HASH_SIZE, ASPECT_TYPE_UNKNOW);
aspectworld.proflevel = PROFILE_NONE;
/* XXX: should go in their respective library */
config_add_item(CONFIG_CFGDEPTH,
CONFIG_TYPE_INT,
CONFIG_MODE_RW,
(void *) CONFIG_CFGDEPTH_DEFAULT);
config_add_item(CONFIG_NAME_SAFEMODE,
CONFIG_TYPE_INT,
CONFIG_MODE_RW,
CONFIG_SAFEMODE_OFF);
config_add_item(CONFIG_ASM_ENDIAN_FLAG,
CONFIG_TYPE_INT,
CONFIG_MODE_RW,
(void *) CONFIG_ASM_LITTLE_ENDIAN);
config_add_item(CONFIG_ASM_ATT_MARGIN_FLAG,
CONFIG_TYPE_INT,
CONFIG_MODE_RW,
(void *) CONFIG_ASM_ATT_MARGIN_DEFAULT);
config_add_item(CONFIG_ASM_SYNTHINSTRS,
CONFIG_TYPE_INT,
CONFIG_MODE_RW,
(void *) CONFIG_ASM_SYNTHINSTRS_DEFAULT);
}
/** @brief Initialize everything Libaspect */
int aspect_init()
{
if (!aspect_initialized)
{
aspect_initialized = 1;
aspect_config_init();
aspect_types_init();
aspect_vectors_init();
aspectworld.profstarted = 1;
}
return (0);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_rd.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_rd.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_rd.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libasm.h"
int
asm_sparc_rd(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_format3 opcode;
struct s_asm_proc_sparc *inter;
sparc_convert_format3(&opcode, buf);
inter = proc->internals;
ins->instr = inter->op2_table[opcode.op3];
ins->type = ASM_TYPE_ASSIGN;
if (opcode.rs1 != 15) { /* RD*(-PR) */
ins->nb_op = 2;
ins->op[0].baser = opcode.rd;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_REGISTER, ins);
ins->op[1].baser = opcode.rs1;
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_SREGISTER, ins);
if (ins->op[0].baser == ASM_SREG_Y) {
ins->instr = ASM_SP_MOV;
}
}
else {
if (opcode.rd != 0)
ins->instr = ASM_SP_BAD;
else if (opcode.i == 0) { /* STBAR */
ins->type = ASM_TYPE_OTHER;
ins->instr = ASM_SP_STBAR;
}
else if (opcode.i == 1) { /* MEMBAR */
ins->instr = ASM_SP_MEMBAR;
ins->type = ASM_TYPE_OTHER;
ins->nb_op = 1;
/* operand = cmask OR mmask */
ins->op[0].imm = ((opcode.imm & 0x70) >> 4) | (opcode.imm & 0xf);
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_IMMEDIATE, ins);
}
}
return 4;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_bound_gv_ma.c
/*
** $Id: op_bound_gv_ma.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_bound_gv_ma" opcode="0x62"/>
*/
int op_bound_gv_ma(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
#if !LIBASM_USE_OPERAND_VECTOR
struct s_modrm *modrm;
#endif
new->instr = ASM_BOUND;
new->len += 1;
new->ptr_instr = opcode;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_MEMORY, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_MEMORY, new);
#endif
#else
modrm = (struct s_modrm *) (opcode + 1);
new->op[0].type = ASM_OTYPE_GENERAL;
new->op[1].type = ASM_OTYPE_MEMORY;
operand_rmv(&new->op[0], opcode + 1, len - 1, proc);
new->op[1].content = ASM_OP_BASE;
new->op[1].regset = ASM_REGSET_R32;
new->op[1].baser = modrm->r;
new->len += new->op[0].len;
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_cwtl.c
/*
** $Id: op_cwtl.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_cwtl" opcode="0x98"/>
*/
int op_cwtl(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc) {
new->len += 1;
new->ptr_instr = opcode;
new->type = ASM_TYPE_ARITH;
if (asm_proc_opsize(proc))
new->instr = ASM_CBTW;
else
new->instr = ASM_CWTL;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_popf.c
/*
** $Id: op_popf.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction name="popf" func="op_popf" opcode="0x9d"/>
*/
int op_popf(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->ptr_instr = opcode;
new->len += 1;
new->instr = ASM_POPF;
new->type = ASM_TYPE_TOUCHSP | ASM_TYPE_LOAD | ASM_TYPE_WRITEFLAG;
new->spdiff = 4;
new->flagswritten = ASM_FLAG_CF | ASM_FLAG_PF | ASM_FLAG_AF |
ASM_FLAG_ZF | ASM_FLAG_SF | ASM_FLAG_TF |
ASM_FLAG_IF | ASM_FLAG_DF | ASM_FLAG_OF |
ASM_FLAG_IOPL | ASM_FLAG_NT | ASM_FLAG_RF |
ASM_FLAG_AC | ASM_FLAG_VIF | ASM_FLAG_VIP |
ASM_FLAG_ID;
return (new->len);
}
<file_sep>/src/libaspect/Makefile
##
## Makefile.am for libaspect in elfsh
##
## Started on Fri Dec 22 16:32:29 2006 jfv
##
include ../config.h
BASEDIR = $(shell pwd)
CC ?= gcc
LD = ld
RM = rm -f
AR = ar rcs
RANLIB = ranlib
CFLAGS32 += -Iinclude -fPIC -m32 -g3 -O2 -DERESI32 $(EXTRACFLAGS)
CFLAGS64 += -Iinclude -fPIC -g3 -O2 -DERESI64 $(EXTRACFLAGS)
SRC = vectors.c libhash.c libbtree.c types.c init.c \
config.c profiler.c liblist.c containers.c
OBJ32 = $(SRC:.c=.32.o)
OBJ64 = $(SRC:.c=.64.o)
NAME = libaspect
NAME32 = libaspect32
NAME64 = libaspect64
all : all32
#all64
libaspect32.so : $(OBJ32)
@#@$(CC) -m32 -L../liballocproxy/ -lallocproxy $(DLOPT) -shared $(OBJ32) -o $(NAME32).so
@$(CC) -arch i386 -m32 $(DLOPT) -shared $(OBJ32) -o $(NAME32).so
@echo "[LD] $(NAME32).so"
@$(AR) $(NAME32).a $(OBJ32)
@echo "[AR] $(NAME32).a"
@$(RANLIB) $(NAME32).a
@$(LD) -arch i386 -r $(OBJ32) -o $(NAME32).o
all32: libaspect32.so
libaspect64.so : $(OBJ64)
#$(LD) -L../liballocproxy/ -lallocproxy $(DLOPT) $(OBJ64) -o $(NAME64).so
$(CC) -L../liballocproxy/ -lallocproxy $(DLOPT) -shared $(OBJ64) -o $(NAME64).so
$(AR) $(NAME64).a $(OBJ64)
$(RANLIB) $(NAME64).a
$(LD) -r $(OBJ64) -o $(NAME64).o
all64: libaspect64.so
clean :
$(RM) $(OBJ) $(OBJ32) $(NAME32).o
fclean : clean
$(RM) *.so *.a
%.32.o : %.c
@echo "[CC] $< ..."
@$(CC) $(CFLAGS32) -c -o $@ $<
%.64.o : %.c
$(CC) $(CFLAGS64) -c -o $@ $<
docs:
doxygen doc/doxygen.conf
<file_sep>/src/libasm/src/arch/ia32/handlers/op_dec_reg.c
/*
** $Id: op_dec_reg.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_dec_reg" opcode="0x48"/>
<instruction func="op_dec_reg" opcode="0x49"/>
<instruction func="op_dec_reg" opcode="0x4a"/>
<instruction func="op_dec_reg" opcode="0x4b"/>
<instruction func="op_dec_reg" opcode="0x4c"/>
<instruction func="op_dec_reg" opcode="0x4d"/>
<instruction func="op_dec_reg" opcode="0x4e"/>
<instruction func="op_dec_reg" opcode="0x4f"/>
*/
int op_dec_reg(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode;
new->ptr_instr = opcode;
new->instr = ASM_DEC;
new->len += 1;
new->type = ASM_TYPE_ARITH | ASM_TYPE_INCDEC | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_AF | ASM_FLAG_OF | ASM_FLAG_PF |
ASM_FLAG_SF | ASM_FLAG_ZF;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_OPMOD, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_OPMOD, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/tables_i386.c
/**
* @file libasm/src/arch/ia32/tables_i386.c
* @ingroup ia32
* @brief Initialization of ia32 processor mnemonic table.
* $Id: tables_i386.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
/**
* @brief Initialize ia32 mnemonic table.
* @param proc Pointer to processor structure.
* @return Returns 1
*/
int init_instr_table(asm_processor *proc)
{
/**
* XXX: should be replaced by a static array ?
*/
proc->instr_table = malloc(sizeof(char *) * (ASM_BAD + 1));
memset(proc->instr_table, 0, sizeof(char *) * (ASM_BAD + 1));
proc->instr_table[ASM_ADC] = "adc";
proc->instr_table[ASM_ADD] = "add";
proc->instr_table[ASM_AND] = "and";
proc->instr_table[ASM_AAM] = "aam";
proc->instr_table[ASM_AAD] = "aad";
proc->instr_table[ASM_AAA] = "aaa";
proc->instr_table[ASM_AAS] = "aas";
proc->instr_table[ASM_ARPL] = "arpl";
proc->instr_table[ASM_BOUND] = "bound";
proc->instr_table[ASM_BSWAP] = "bswap";
proc->instr_table[ASM_BTRL] = "btrl";
proc->instr_table[ASM_CMPSB] = "cmpsb";
proc->instr_table[ASM_CMPSD] = "cmpsd";
proc->instr_table[ASM_CALL] = "call";
proc->instr_table[ASM_CMP] = "cmp";
proc->instr_table[ASM_CWTL] = "cwtl";
proc->instr_table[ASM_CWTD] = "cwtd";
proc->instr_table[ASM_CBTW] = "cbtw";
proc->instr_table[ASM_CLTD] = "cltd";
proc->instr_table[ASM_CPUID] = "cpuid";
proc->instr_table[ASM_CLD] = "cld";
proc->instr_table[ASM_CLI] = "cli";
proc->instr_table[ASM_CLC] = "clc";
proc->instr_table[ASM_DAA] = "daa";
proc->instr_table[ASM_DAS] = "das";
proc->instr_table[ASM_DIV] = "div";
proc->instr_table[ASM_DEC] = "dec";
proc->instr_table[ASM_EMMS] = "emms";
proc->instr_table[ASM_ENTER] = "enter";
proc->instr_table[ASM_FWAIT] = "fwait";
proc->instr_table[ASM_HLT] = "hlt";
proc->instr_table[ASM_INTO] = "into";
proc->instr_table[ASM_IRET] = "iret";
proc->instr_table[ASM_INT] = "int";
proc->instr_table[ASM_INT3] = "int3";
proc->instr_table[ASM_INT1] = "int1";
proc->instr_table[ASM_IN] = "in";
proc->instr_table[ASM_INSB] = "insb";
proc->instr_table[ASM_INSW] = "insw";
proc->instr_table[ASM_INSD] = "insd";
proc->instr_table[ASM_INC] = "inc";
proc->instr_table[ASM_IMUL] = "imul";
proc->instr_table[ASM_IDIV] = "idiv";
proc->instr_table[ASM_BRANCH] = "jmp";
proc->instr_table[ASM_BRANCH_U_LESS] = "jb";
proc->instr_table[ASM_BRANCH_U_LESS_EQUAL] = "jbe";
proc->instr_table[ASM_BRANCH_S_LESS] = "jl";
proc->instr_table[ASM_BRANCH_S_LESS_EQUAL] = "jle";
proc->instr_table[ASM_BRANCH_U_GREATER] = "ja";
proc->instr_table[ASM_BRANCH_U_GREATER_EQUAL] = "jae";
proc->instr_table[ASM_BRANCH_S_GREATER] = "jg";
proc->instr_table[ASM_BRANCH_S_GREATER_EQUAL] = "jge";
proc->instr_table[ASM_BRANCH_EQUAL] = "je";
proc->instr_table[ASM_BRANCH_NOT_EQUAL] = "jne";
proc->instr_table[ASM_BRANCH_PARITY] = "jp";
proc->instr_table[ASM_BRANCH_NOT_PARITY] = "jnp";
proc->instr_table[ASM_BRANCH_OVERFLOW] = "jo";
proc->instr_table[ASM_BRANCH_NOT_OVERFLOW] = "jno";
proc->instr_table[ASM_BRANCH_SIGNED] = "js";
proc->instr_table[ASM_BRANCH_NOT_SIGNED] = "jns";
proc->instr_table[ASM_BRANCH_CXZ] = "jecxz";
proc->instr_table[ASM_LEA] = "lea";
proc->instr_table[ASM_LOAD] = "ld";
proc->instr_table[ASM_LOCK] = "lock";
proc->instr_table[ASM_LOOP] = "loop";
proc->instr_table[ASM_LOOPE] = "loope";
proc->instr_table[ASM_LOOPNE] = "loopne";
proc->instr_table[ASM_LEAVE] = "leave";
proc->instr_table[ASM_LAHF] = "lahf";
proc->instr_table[ASM_LODSB] = "lodsb";
proc->instr_table[ASM_LODSD] = "lodsd";
proc->instr_table[ASM_LES] = "les";
proc->instr_table[ASM_LDS] = "lds";
proc->instr_table[ASM_LBRANCH] = "ljmp";
proc->instr_table[ASM_MOVSB] = "movsb";
proc->instr_table[ASM_MOVSW] = "movsw";
proc->instr_table[ASM_MOVSD] = "movsl";
proc->instr_table[ASM_MOVSBL] = "movsbl";
proc->instr_table[ASM_MOVSBW] = "movsbw";
proc->instr_table[ASM_MOVSWL] = "movswl";
proc->instr_table[ASM_MOVZWL] = "movzwl";
proc->instr_table[ASM_MOVZBW] = "movzbw";
proc->instr_table[ASM_MOVZBL] = "movzbl";
proc->instr_table[ASM_MUL] = "mull";
proc->instr_table[ASM_MOV] = "mov";
proc->instr_table[ASM_MOVW] = "movw";
proc->instr_table[ASM_MOVD] = "movd";
proc->instr_table[ASM_MOVQ] = "movq";
proc->instr_table[ASM_NEG] = "neg";
proc->instr_table[ASM_NOT] = "not";
proc->instr_table[ASM_NOP] = "nop";
proc->instr_table[ASM_OR] = "or";
proc->instr_table[ASM_ORB] = "orb";
proc->instr_table[ASM_OUT] = "out";
proc->instr_table[ASM_OUTSB] = "outsb";
proc->instr_table[ASM_OUTSW] = "outsw";
proc->instr_table[ASM_PUSH] = "push";
proc->instr_table[ASM_POP] = "pop";
proc->instr_table[ASM_PUSHF] = "pushf";
proc->instr_table[ASM_POPF] = "popf";
proc->instr_table[ASM_PUSHA] = "pusha";
proc->instr_table[ASM_POPA] = "popa";
proc->instr_table[ASM_PAND] = "pand";
proc->instr_table[ASM_POR] = "por";
proc->instr_table[ASM_PXOR] = "pxor";
proc->instr_table[ASM_PUNPCKLBW] = "punpcklbw";
proc->instr_table[ASM_PUNPCKHBW] = "punpckhbw";
proc->instr_table[ASM_PACKUSWB] = "packuswb";
proc->instr_table[ASM_PSLLQ] = "psllq";
proc->instr_table[ASM_PSRLQ] = "psrlq";
proc->instr_table[ASM_PSRLW] = "psrlw";
proc->instr_table[ASM_PSRAW] = "psraw";
proc->instr_table[ASM_PSLLW] = "psllw";
proc->instr_table[ASM_PMULLW] = "pmullw";
proc->instr_table[ASM_PADDUSW] = "paddusw";
proc->instr_table[ASM_PADDUSB] = "paddusb";
proc->instr_table[ASM_RET] = "ret";
proc->instr_table[ASM_REPNZ] = "repnz";
proc->instr_table[ASM_REPZ] = "repz";
proc->instr_table[ASM_RCL] = "rcl";
proc->instr_table[ASM_ROL] = "rol";
proc->instr_table[ASM_ROR] = "ror";
proc->instr_table[ASM_RCR] = "rcr";
proc->instr_table[ASM_RETF] = "retf";
proc->instr_table[ASM_RDMSR] = "rdmsr";
proc->instr_table[ASM_STORE] = "st";
proc->instr_table[ASM_STI] = "sti";
proc->instr_table[ASM_SUB] = "sub";
proc->instr_table[ASM_SBB] = "sbb";
proc->instr_table[ASM_SCASB] = "scas";
proc->instr_table[ASM_SCASD] = "scasd";
proc->instr_table[ASM_STOSB] = "stosb";
proc->instr_table[ASM_STOSD] = "stos";
proc->instr_table[ASM_SHR] = "shr";
proc->instr_table[ASM_SAHF] = "sahf";
proc->instr_table[ASM_SHIFT] = "shift";
proc->instr_table[ASM_SAR] = "sar";
proc->instr_table[ASM_STD] = "std";
proc->instr_table[ASM_SHL] = "shl";
proc->instr_table[ASM_SHRD] = "shrd";
proc->instr_table[ASM_STC] = "stc";
proc->instr_table[ASM_TEST] = "test";
proc->instr_table[ASM_XADD] = "xadd";
proc->instr_table[ASM_XOR] = "xor";
proc->instr_table[ASM_XCHG] = "xchg";
proc->instr_table[ASM_XLATB] = "xlatb";
proc->instr_table[ASM_XSTORERNG] = "xstore-rng";
proc->instr_table[ASM_XCRYPTCBC] = "xcrypt-cbc";
proc->instr_table[ASM_XCRYPTCFB] = "xcrypt-cfb";
proc->instr_table[ASM_XCRYPTOFB] = "xcrypt-ofb";
proc->instr_table[ASM_WBINVD] = "wbinvd";
/* i386 */
proc->instr_table[ASM_SET_U_LESS] = "setb";
proc->instr_table[ASM_CMPXCHG] = "cmpxchg";
proc->instr_table[ASM_RDTSC] = "rdtsc";
proc->instr_table[ASM_BTR] = "btr";
proc->instr_table[ASM_SET_U_LESS_EQUAL] = "setbe";
proc->instr_table[ASM_SET_S_LESS] = "setl";
proc->instr_table[ASM_SET_S_LESS_EQUAL] = "setle";
proc->instr_table[ASM_SET_U_GREATER] = "seta";
proc->instr_table[ASM_SET_U_GREATER_EQUAL] = "setae";
proc->instr_table[ASM_SET_S_GREATER] = "setg";
proc->instr_table[ASM_SET_S_GREATER_EQUAL] = "setge";
proc->instr_table[ASM_SET_SIGNED] = "sets";
proc->instr_table[ASM_SET_NOT_SIGNED] = "setns";
proc->instr_table[ASM_SET_PARITY] = "setp";
proc->instr_table[ASM_SET_NOT_PARITY] = "setnp";
proc->instr_table[ASM_SET_OVERFLOW] = "seto";
proc->instr_table[ASM_SET_NOT_OVERFLOW] = "setno";
proc->instr_table[ASM_SET_EQUAL] = "sete";
proc->instr_table[ASM_SET_NOT_EQUAL] = "setne";
proc->instr_table[ASM_BT] = "bt";
proc->instr_table[ASM_BTS] = "bts";
proc->instr_table[ASM_SHLD] = "shld";
proc->instr_table[ASM_CMC] = "cmc";
proc->instr_table[ASM_BSR] = "bsr";
proc->instr_table[ASM_CMOVNE] = "cmovne";
proc->instr_table[ASM_CMOVA] = "cmova";
proc->instr_table[ASM_CMOVAE] = "cmovae";
proc->instr_table[ASM_CMOVE] = "cmove";
proc->instr_table[ASM_CMOVO] = "cmovo";
proc->instr_table[ASM_CMOVNO] = "cmovno";
proc->instr_table[ASM_CMOVB] = "cmovb";
proc->instr_table[ASM_CMOVBE] = "cmovbe";
proc->instr_table[ASM_CMOVS] = "cmovs";
proc->instr_table[ASM_CMOVNS] = "cmovns";
proc->instr_table[ASM_CMOVP] = "cmovp";
proc->instr_table[ASM_CMOVNP] = "cmovnp";
proc->instr_table[ASM_CMOVL] = "cmovl";
proc->instr_table[ASM_CMOVNL] = "cmovnl";
proc->instr_table[ASM_CMOVLE] = "cmovle";
proc->instr_table[ASM_CMOVNLE] = "cmovnle";
proc->instr_table[ASM_LSS] = "lss";
proc->instr_table[ASM_UD2A] = "ud2a";
proc->instr_table[ASM_LGDT] = "lgdt";
proc->instr_table[ASM_LIDT] = "lidt";
proc->instr_table[ASM_SGDT] = "sgdtl";
proc->instr_table[ASM_SIDT] = "sidt";
proc->instr_table[ASM_STR] = "str";
proc->instr_table[ASM_LTR] = "ltr";
proc->instr_table[ASM_LLDT] = "lldt";
proc->instr_table[ASM_STMXCSR] = "stmxcsr";
proc->instr_table[ASM_LDMXCSR] = "ldmxcsr";
proc->instr_table[ASM_BSF] = "bsf";
proc->instr_table[ASM_LFENCE] = "lfence";
proc->instr_table[ASM_MFENCE] = "mfence";
proc->instr_table[ASM_SFENCE] = "sfence";
proc->instr_table[ASM_FXSAVE] = "fxsave";
proc->instr_table[ASM_FXRSTORE] = "fxrstore";
proc->instr_table[ASM_LDMXCSR] = "ldmxcsr";
proc->instr_table[ASM_STMXCSR] = "stmxcsr";
/* FPU */
proc->instr_table[ASM_FILD] = "fild";
proc->instr_table[ASM_FIMUL] = "fimul";
proc->instr_table[ASM_FSTP] = "fstp";
proc->instr_table[ASM_FSAVE] = "fsave";
proc->instr_table[ASM_FNSAVE] = "fnsave";
proc->instr_table[ASM_FCOM] = "fcom";
proc->instr_table[ASM_FCOMP] = "fcomp";
proc->instr_table[ASM_FCOMPP] = "fcompp";
proc->instr_table[ASM_FLD] = "fldt";
proc->instr_table[ASM_FLDZ] = "fldz";
proc->instr_table[ASM_FADD] = "fadd";
proc->instr_table[ASM_FIADD] = "fiadd";
proc->instr_table[ASM_FABS] = "fabs";
proc->instr_table[ASM_FADDP] = "faddp";
proc->instr_table[ASM_FLD] = "fld";
proc->instr_table[ASM_FCOM] = "fcom";
proc->instr_table[ASM_FDIV] = "fdiv";
proc->instr_table[ASM_FDIVR] = "fdivr";
proc->instr_table[ASM_FDIVP] = "fdivp";
proc->instr_table[ASM_FDIVRP] = "fdivrp";
proc->instr_table[ASM_FXCH] = "fxch";
proc->instr_table[ASM_FINIT] = "finit";
proc->instr_table[ASM_FICOMP] = "ficomp";
proc->instr_table[ASM_FIDIV] = "fidiv";
proc->instr_table[ASM_FIDIVR] = "fidivr";
proc->instr_table[ASM_FLD1] = "fld1";
proc->instr_table[ASM_FLDCW] = "fldcw";
proc->instr_table[ASM_FCHS] = "fchs";
proc->instr_table[ASM_FST] = "fst";
proc->instr_table[ASM_FISUB] = "fisub";
proc->instr_table[ASM_FISUBR] = "fisubr";
proc->instr_table[ASM_FIST] = "fist";
proc->instr_table[ASM_FISTP] = "fistp";
proc->instr_table[ASM_FMUL] = "fmul";
proc->instr_table[ASM_FMULP] = "fmulp";
proc->instr_table[ASM_FSUB] = "fsub";
proc->instr_table[ASM_FSUBR] = "fsubr";
proc->instr_table[ASM_FSUBP] = "fsubp";
proc->instr_table[ASM_FSUBRP] = "fsubrp";
proc->instr_table[ASM_FUCOM] = "fucom";
proc->instr_table[ASM_FUCOMP] = "fucomp";
proc->instr_table[ASM_FUCOMPP] = "fucompp";
proc->instr_table[ASM_FSTSW] = "fstsw";
proc->instr_table[ASM_FNSTSW] = "fnstsw";
proc->instr_table[ASM_FPREM] = "fprem";
proc->instr_table[ASM_FSCALE] = "fscale";
proc->instr_table[ASM_FSQRT] = "fsqrt";
proc->instr_table[ASM_FNSTCW] = "fnstcw";
proc->instr_table[ASM_FSTCW] = "fstcw";
proc->instr_table[ASM_FRNDINT] = "frndint";
proc->instr_table[ASM_FPATAN] = "fpatan";
proc->instr_table[ASM_BAD] = "(bad)";
return (1);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_les_rm_rmp.c
/*
** $Id: op_les_rm_rmp.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_les_rm_rmp" opcode="0xc4"/>
*/
int op_les_rm_rmp(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->ptr_instr = opcode;
new->instr = ASM_LES;
new->len += 1;
new->type = ASM_TYPE_LOAD;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/init_i386.c
/**
* @file libasm/src/arch/ia32/init_i386.c
* @ingroup ia32
* $Id: init_i386.c 1397 2009-09-13 02:19:08Z may $
*
*/
#ifndef I386_H_
#define I386_H_
#include <libasm.h>
#include <libasm-int.h>
void init_instr_table(asm_processor *);
/**
* Handler to fetch i386 bytecode.
* This handler is called throught a function pointer stored in
* the asm_processor structure.
*
* @param instr Pointer to instruction structure to fill.
* @param buf Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Length of instruction or -1 on error.
*/
int fetch_i386(asm_instr *instr, u_char *buf, u_int len,
asm_processor *proc)
{
u_char opcode;
int (*fetch)(asm_instr *, u_char *, u_int, asm_processor *);
int to_ret;
opcode = *buf;
fetch = asm_opcode_fetch(LIBASM_VECTOR_OPCODE_IA32, opcode);
to_ret = fetch(instr, buf, len, proc);
if (to_ret > 0)
instr->name = proc->instr_table[instr->instr];
return (to_ret);
}
int asm_init_i386(asm_processor *proc)
{
fprintf(stderr, "you should not use asm_init_i386 anymore."
" Use asm_init_ia32 instead\n");
aspect_init();
return (asm_init_ia32(proc));
}
/**
* Intialize the processor and vector structures to disassemble i386 bytecode.
* @param Pointer to a asm_processor structure.
* @return Always 1.
*/
int asm_init_ia32(asm_processor *proc)
{
struct s_asm_proc_i386 *inter;
init_instr_table(proc);
proc->type = ASM_PROC_IA32;
asm_register_ia32();
proc->resolve_immediate = asm_resolve_ia32;
proc->resolve_data = 0;
proc->fetch = fetch_i386;
proc->display_handle = asm_ia32_display_instr_att;
inter = proc->internals = malloc(sizeof (struct s_asm_proc_i386));
inter->opsize = inter->addsize = 0;
inter->mode = INTEL_PROT;
return (1);
}
void asm_free_i386(asm_processor *proc)
{
free(proc->internals);
free(proc->instr_table);
}
/* Resolve destinations of control flow instruction depending on real or protected mode */
eresi_Addr asm_dest_resolve(asm_processor *proc, eresi_Addr addr, u_int shift)
{
int mode;
u_short off;
mode = asm_ia32_get_mode(proc);
if (mode == INTEL_REAL)
{
off = (addr & 0xFFFF) + shift;
addr = (addr & 0xFFFF0000) + off;
}
else
addr += shift;
return (addr);
}
/** Get mode of IA32 processor */
int asm_ia32_get_mode(asm_processor *proc)
{
struct s_asm_proc_i386 *inter;
inter = proc->internals;
return (inter->mode);
}
/**
* Switch
* @param proc Pointer to asm processor structure.
* @param mode INTEL_PROT or INTEL_REAL
*/
int asm_ia32_switch_mode(asm_processor *proc, int mode)
{
struct s_asm_proc_i386 *inter;
inter = proc->internals;
inter->mode = mode;
if (mode == INTEL_PROT)
inter->opsize = inter->addsize = 0;
else
{
/**
* inter->opsize and inter->addsize values are perhaps not accurate.
* Must add testcode for this feature.
*/
inter->opsize = inter->addsize = 1;
}
return (1);
}
#endif
<file_sep>/src/libasm/src/arch/ia32/handlers/op_esc3.c
/*
** $Id: op_esc3.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_esc3" opcode="0xdb"/>
*/
int op_esc3(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
struct s_modrm *modrm;
new->ptr_instr = opcode;
modrm = (struct s_modrm *) opcode + 1;
new->len += 1;
switch(modrm->r)
{
case 0:
new->instr = ASM_FILD;
break;
case 1:
new->instr = ASM_BAD;
break;
case 2:
new->instr = ASM_FIST;
break;
case 3:
new->instr = ASM_FISTP;
break;
case 4:
// bad
break;
case 5:
new->instr = ASM_FLD;
break;
case 6:
case 7:
new->instr = ASM_FSTP;
break;
}
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#else
new->op[0].type = ASM_OTYPE_ENCODED;
operand_rmv(&new->op[0], opcode + 1, len - 1, proc);
new->len += new->op[0].len;
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_immed_rmv_ib.c
/*
** $Id: op_immed_rmv_ib.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_immed_rmv_ib" opcode="0x83"/>
*/
int op_immed_rmv_ib(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
int olen;
struct s_modrm *modrm;
modrm = (struct s_modrm *) (opcode + 1);
new->ptr_instr = opcode;
new->len += 1;
new->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_AF | ASM_FLAG_CF | ASM_FLAG_OF |
ASM_FLAG_PF | ASM_FLAG_SF | ASM_FLAG_ZF;
switch(modrm->r) {
case 0:
new->instr = ASM_ADD;
break;
case 1:
new->instr = ASM_OR;
new->flagswritten ^= ASM_FLAG_AF;
break;
case 2:
new->instr = ASM_ADC;
new->type |= ASM_TYPE_READFLAG;
new->flagsread = ASM_FLAG_CF;
break;
case 3:
new->instr = ASM_SBB;
new->type |= ASM_TYPE_READFLAG;
new->flagsread = ASM_FLAG_CF;
break;
case 4:
new->instr = ASM_AND;
new->flagswritten ^= ASM_FLAG_AF;
break;
case 5:
new->instr = ASM_SUB;
if (new->op[0].content == ASM_OP_BASE &&
new->op[0].baser == ASM_REG_ESP)
new->type |= ASM_TYPE_EPILOG;
break;
case 6:
new->instr = ASM_XOR;
new->flagswritten ^= ASM_FLAG_AF;
break;
case 7:
new->instr = ASM_CMP;
new->type = ASM_TYPE_COMPARISON | ASM_TYPE_WRITEFLAG;
break;
}
#if WIP
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0));
#else
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new));
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen, ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen, ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_shift_rmv_1.c
/**
* @file libasm/src/arch/ia32/handlers/op_shift_rmv_1.c
*
* @ingroup IA32_instrs
** $Id: op_shift_rmv_1.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_shift_rmv_1" opcode="0xd1"/>
*/
int op_shift_rmv_1(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode + 1;
new->ptr_instr = opcode;
new->len += 1;
new->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_PF | ASM_FLAG_ZF | ASM_FLAG_SF |
ASM_FLAG_CF | ASM_FLAG_OF;
switch(modrm->r) {
case ASM_REG_EDI:
new->instr = ASM_SAR;
break;
case ASM_REG_ESP:
new->instr = ASM_SHL;
break;
default:
new->instr = ASM_SHR;
break;
}
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED,
new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED,
new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_fpop1.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_fpop1.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_fpop1.c 1440 2010-12-29 02:22:03Z may $
**
*/
#include "libasm.h"
int
asm_sparc_fpop1(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_format3 opcode;
struct s_asm_proc_sparc *inter;
sparc_convert_format3(&opcode, buf);
inter = proc->internals;
ins->instr = inter->fpop1_table[opcode.opf];
if (opcode.opf < 0x40 || opcode.opf >= 0x70) {
ins->type = ASM_TYPE_ASSIGN;
ins->nb_op = 2;
}
else { /* 0x40 < opf < 0x69 - add, sub, mul, div */
ins->type = ASM_TYPE_ARITH;
/* FIXME: what is the value to switch on here ? */
/*
switch ()
{
case:
ins->arith = ASM_ARITH_ADD;
break;
case:
ins->arith = ASM_ARITH_SUB;
break;
case:
ins->arith = ASM_ARITH_MUL;
break;
case:
ins->arith = ASM_ARITH_DIV;
break;
}
*/
ins->nb_op = 3;
ins->op[2].baser = opcode.rs1;
asm_sparc_op_fetch(&ins->op[2], buf, ASM_SP_OTYPE_FREGISTER, ins);
}
ins->op[0].baser = opcode.rd;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_FREGISTER, ins);
ins->op[1].baser = opcode.rs2;
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_FREGISTER, ins);
return 4;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_imul_rv_rmv_iv.c
/**
* @file libasm/src/arch/ia32/handlers/op_imul_rv_rmv_iv.c
* @brief Handler for instruction op_imul_rv_rmv_iv opcode 0x69
*
* @ingroup IA32_instrs
** $Id: op_imul_rv_rmv_iv.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @brief Handler for instruction op_imul_rv_rmv_iv opcode 0x69
*
*
*/
int op_imul_rv_rmv_iv(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
int olen;
new->instr = ASM_IMUL;
new->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
new->ptr_instr = opcode;
new->len += 1;
new->flagswritten = ASM_FLAG_OF | ASM_FLAG_CF;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_GENERAL, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_GENERAL, new);
#endif
#if WIP
new->len += (olen = asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_ENCODED, new, 0));
#else
new->len += (olen = asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_ENCODED, new));
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[2], opcode + 1 + olen, ASM_OTYPE_IMMEDIATE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[2], opcode + 1 + olen, ASM_OTYPE_IMMEDIATE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_lodsd.c
/*
** $Id: op_lodsd.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_lodsd" opcode="0xad"/>
*/
int op_lodsd(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->instr = ASM_LODSD;
new->ptr_instr = opcode;
new->type = ASM_TYPE_LOAD;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_YDEST, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_YDEST, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_XSRC, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_XSRC, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/operand_handlers/asm_operand_fetch_encodedbyte.c
/**
* @file libasm/src/arch/ia32/operand_handlers/asm_operand_fetch_encodedbyte.c
*
* @ingroup IA32_operands
* $Id: asm_operand_fetch_encodedbyte.c 1397 2009-09-13 02:19:08Z may $
*/
#include <libasm.h>
#include <libasm-int.h>
/**
*
* @ingroup IA32_operands
* Decode data for operand type ASM_OTYPE_ENCODEDBYTE
* @param operand Pointer to operand structure to fill.
* @param opcode Pointer to operand data
* @param otype
* @param ins Pointer to instruction structure.
* @return Operand length
*/
#if WIP
int asm_operand_fetch_encodedbyte(asm_operand *operand, u_char *opcode, int otype,
asm_instr *ins, int opt)
#else
int asm_operand_fetch_encodedbyte(asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins)
#endif
{
int len;
operand->type = ASM_OTYPE_ENCODED;
len = operand_rmb(operand, opcode, 5, ins->proc);
operand->sbaser = get_reg_intel(operand->baser, operand->regset);
operand->sindex = get_reg_intel(operand->indexr, operand->regset);
return (len);
}
<file_sep>/src/image.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <math.h>
#include "fastcrc.h"
#include "libasm.h"
#include "elf.h"
#include "list.h"
#include "db.h"
#define ELF_MAGIC "\x7f\x45\x4c\x46"
#define SIG_MAGIC 0xdeadbeef
#define BB_THRESHOLD 2
asm_processor proc;
asm_instr instr;
typedef struct basic_block basic_block_t;
typedef struct basic_block {
char fname[64];
unsigned int addr, vaddr;
unsigned int size, off;
unsigned int icnt, ilen;
unsigned int nopcnt;
unsigned char *data;
} bb_t;
typedef struct bin_image {
char *name;
unsigned int size;
unsigned char *data;
unsigned int crc;
unsigned int hashl,
hashb;
} bin_image_t;
typedef struct elf_symbol {
char name[64]; // symbol name
unsigned int addr; // symbol address
unsigned int size; // symbol size
unsigned short index; // symbol index into strtable
unsigned char type; // symbol type
unsigned char binding; // symbol binding
unsigned int crc; // symbol data checksum
unsigned int code; // mimimi
double entropy, // symbol bit entropy
probability;// symbol probability value when searching similar symbols
bb_list_t *blist; // basic block list
struct elf_symbol *next,
*prev;
} elf_sym_t;
typedef struct elf_image {
char *name; // image filename
unsigned int size;
unsigned char *data;
Elf32_Ehdr *ehdr; // pointer to image elf header
unsigned int nsections; // total number of elf sections
Elf32_Shdr *shstrtabhdr; // pointer to section string table section
unsigned char *shstrtab; // pointer to section string table data
unsigned int shstrtablen; // length of section string table data
Elf32_Shdr *strtabhdr; // pointer to string table header
unsigned char *strtab; // pointer to string table data
unsigned int strtablen; // length of string table data
Elf32_Shdr *symtabhdr; // pointer to section symbol table header
unsigned char *symtab; // pointer to section symbol table data
unsigned int symtablen; // length of section symbol table data
Elf32_Shdr *dyntabhdr; // pointer to section dynamic symbol table header
unsigned char *dyntab; // pointer to section dynamic symbol table data
unsigned int dyntablen; // lenght of section dynamic symbol table data
Elf32_Sym *lastsym;
elf_sym_t *symlist;
unsigned int crc;
} elf_image_t;
static int ELF32_ENDIAN = 0;
void elf_disassemble_symbol(elf_image_t *, elf_sym_t *);
unsigned char h_table[256];
void hexdump(unsigned int start_addr, unsigned char *data, unsigned int dlen)
{
int i, c;
char asc[18];
memset(asc, 0x00, sizeof(asc)-1);
printf("%08X: ", start_addr);
for(c = i = 0; i < dlen; i++) {
if(i && !(i % 16)) {
printf("| %s\n%08X: ", asc, start_addr);
c = 0;
}
if((data[i] > 0x20 && data[i] <= 0x7F))
asc[c++] = data[i];
else asc[c++] = '.';
printf("%02x ", data[i]);
}
for(asc[c] = 0, c = 0; (i%16) && c < ((16 - (i%16))); c++)
printf(" ");
if(c) printf("| %-16s\n", asc);
putc(0x0A, stdout);
}
/* 8 bit */
double bit_entropy(unsigned char *data, unsigned int len, double *prb)
{
int i;
int total = 0;
double prob, entropy = 0, p = 0;
memset(h_table, 0x00, sizeof(h_table));
/* build histogram table */
for(i = 0; i < len; h_table[data[i++] & 0xFF]++);
for(i = 0; i < 256; i++)
if(h_table[i])
total += h_table[i];
/* calculate byte probability
* and entropy */
for(i = 0; i < 256; i++) {
if(h_table[i]) {
prob = 1.0 * h_table[i] / total;
p += prob;
entropy += (prob * log2(1.0 / prob));
}
}
p /= (1.0 * total);
*prb = p;
return (entropy);
}
void elf_print_ehdr(elf_image_t *image)
{
int i;
printf("MAGIC: ");
for(i = 0; i < 16; i++)
printf("%02x ", image->ehdr->e_ident[i]);
printf("\n");
printf("e_type:\t%08x\n", image->ehdr->e_type);
printf("byte order:\t%s\n", image->ehdr->e_ident[EI_DATA] == ELFDATA2MSB ? "BIG ENDIAN" : "LITTLE ENDIAN");
printf("e_machine:\t%08x\n", image->ehdr->e_machine);
printf("e_version:\t%08x\n", image->ehdr->e_version);
printf("e_entry:\t %08x\n", image->ehdr->e_entry);
printf("e_phoff:\t %08x (%d)\n", image->ehdr->e_phoff, image->ehdr->e_phoff);
printf("e_shoff:\t %08x (%d)\n", (image->ehdr->e_shoff), (image->ehdr->e_shoff));
printf("e_flags:\t %08x\n", image->ehdr->e_flags);
printf("e_shnum:\t %08x\n", image->ehdr->e_shnum);
printf("e_phnum:\t %08x\n", image->ehdr->e_phnum);
}
char *elf_section_name(unsigned char *data, unsigned int datalen, unsigned int sh_name)
{
if(sh_name == 0)
return ("NULL");
if(sh_name > datalen)
return ("NULL");
//printf("%p %x\n", data, sh_name);
return ((char *)(data + sh_name));
}
unsigned int elf_byteswap(int bits, unsigned int value)
{
if(!ELF32_ENDIAN)
return (value);
switch(bits) {
case 16:
return (bswap_16(value));
case 32:
return (bswap_32(value));
default:
return (0);
}
}
int elf_load_strtab(elf_image_t *image)
{
Elf32_Shdr *shdr;
char *section_name;
unsigned char *data;
long datalen = 0;
int i, loaded = 0;
for(i = 0; i < image->nsections; i++) {
shdr = (Elf32_Shdr *)(image->data + image->ehdr->e_shoff + (i * image->ehdr->e_shentsize));
shdr->sh_type = elf_byteswap(32, shdr->sh_type);
shdr->sh_addralign = elf_byteswap(32, shdr->sh_addralign);
shdr->sh_link = elf_byteswap(32, shdr->sh_link);
shdr->sh_addr = elf_byteswap(32, shdr->sh_addr);
shdr->sh_size = elf_byteswap(32, shdr->sh_size);
shdr->sh_offset = elf_byteswap(32, shdr->sh_offset);
shdr->sh_name = elf_byteswap(32, shdr->sh_name);
shdr->sh_entsize = elf_byteswap(32, shdr->sh_entsize);
shdr->sh_flags = elf_byteswap(32, shdr->sh_flags);
if(shdr->sh_type != SHT_STRTAB && shdr->sh_type != SHT_PROGBITS)
continue;
data = (image->data + shdr->sh_offset);
datalen = shdr->sh_size * (shdr->sh_entsize ? shdr->sh_entsize : 1);
if(datalen < 0)
continue;
section_name = elf_section_name(image->shstrtab ? image->shstrtab : data, datalen, shdr->sh_name);
if(!strcmp(section_name, ".strtab")) {
image->strtab = (data);
image->strtablen = datalen;
image->strtabhdr = shdr;
loaded++;
printf("[+] loaded '%s' @ %08x (%ld bytes/%d entities)\n", section_name, shdr->sh_offset, datalen, shdr->sh_entsize);
} else if(!strcmp(section_name, ".shstrtab")) {
image->shstrtab = (data);
image->shstrtablen = datalen;
image->shstrtabhdr = shdr;
section_name = elf_section_name(data, datalen, shdr->sh_name);
loaded++;
printf("[+] loaded '%s' @ %08x (%ld bytes/%d entities)\n", section_name, shdr->sh_offset, datalen, shdr->sh_entsize);
}
}
return (loaded);
}
int elf_load_symtab(elf_image_t *image)
{
Elf32_Shdr *shdr;
int i;
for(i = 0; i < image->nsections; i++) {
shdr = (Elf32_Shdr *)(image->data + image->ehdr->e_shoff + (i * image->ehdr->e_shentsize));
if(shdr->sh_size > 0x80000000) {
shdr->sh_type = elf_byteswap(32, shdr->sh_type);
shdr->sh_type = elf_byteswap(32, shdr->sh_type);
shdr->sh_addralign = elf_byteswap(32, shdr->sh_addralign);
shdr->sh_link = elf_byteswap(32, shdr->sh_link);
shdr->sh_addr = elf_byteswap(32, shdr->sh_addr);
shdr->sh_size = elf_byteswap(32, shdr->sh_size);
shdr->sh_offset = elf_byteswap(32, shdr->sh_offset);
shdr->sh_name = elf_byteswap(32, shdr->sh_name);
shdr->sh_entsize = elf_byteswap(32, shdr->sh_entsize);
shdr->sh_flags = elf_byteswap(32, shdr->sh_flags);
}
if(shdr->sh_type != SHT_SYMTAB)
continue;
image->symtab = (image->data + shdr->sh_offset);
image->symtablen = shdr->sh_size;
image->symtabhdr = shdr;
printf("[+] loaded '%s' @ %08x (%d bytes/%d entities)\n", elf_section_name(image->shstrtab, image->shstrtablen, shdr->sh_name), shdr->sh_offset, image->symtablen, shdr->sh_entsize);
return (1);
}
return (0);
}
char *elf_symbol_name(unsigned char *data, unsigned int datalen, unsigned int st_name)
{
if(st_name == 0)
return ("NULL");
if(st_name > datalen)
return ("NULL");
return ((char *)data + st_name);
}
char *elf_type_str(elf_sym_t *sym)
{
int type = sym->type;
int bind = sym->binding;
switch(type) {
case STT_FUNC:
if(bind == STB_LOCAL)
return ("FUNCTION LOCAL");
else return ("FUNCTION GLOBAL");
break;
case STT_OBJECT:
if(bind == STB_LOCAL)
return ("OBJECT LOCAL");
else
return ("OBJECT GLOBAL");
break;
case STT_NOTYPE:
if(bind == STB_LOCAL)
return ("NOTYPE LOCAL");
else
return ("NOTYPE GLOBAL");
break;
case STT_SECTION:
if(bind == STB_LOCAL)
return ("SECTION LOCAL");
else
return ("SECTION GLOBAL");
break;
case STT_FILE:
if(bind == STB_LOCAL)
return ("FILE LOCAL");
else
return ("FILE GLOBAL");
break;
default:
break;
}
return ("NULL");
}
char *instr_type(int type)
{
switch(type) {
case ASM_TYPE_BRANCH:
case ASM_TYPE_CALLPROC:
case ASM_TYPE_CONDCONTROL:
case ASM_TYPE_INDCONTROL:
return ("flow change");
case ASM_TYPE_RETPROC:
return ("ret");
case ASM_TYPE_INT:
return ("int");
default:
return ("");
}
return ("NULL");
}
/* tosco crc */
unsigned int elf_symbol_opcode_crc(elf_image_t *image, elf_sym_t *sym)
{
int i;
unsigned int crc = 0, opcode, offset;
unsigned char *ptr;
Elf32_Shdr *shdr;
if((shdr = (Elf32_Shdr *)(image->data + (image->ehdr->e_shoff + (image->ehdr->e_shentsize * sym->index)))) != NULL) {
offset = (shdr->sh_offset + sym->addr);
ptr = (image->data + offset);
}
for(i = 0; i < sym->size; i++) {
opcode = *(unsigned int *)(ptr + i);
crc += ((opcode >> 16) & 0xFFFF);
}
return (crc);
}
int basic_block_count(bb_list_t **blist)
{
bb_list_node_t *p;
int count = 0;
if((*blist) == NULL)
return (0);
for(count = 0, p = (*blist)->head; p; p = p->next, count++);
return (count);
}
#define ASM_BLOCK_STOP(x) \
((x & ASM_TYPE_BRANCH) || (x & ASM_TYPE_CALLPROC) || (x & ASM_TYPE_CONDCONTROL) || \
(x & ASM_TYPE_INT) || (x & ASM_TYPE_RETPROC) || (x & ASM_TYPE_COMPARISON) || (x & ASM_TYPE_INDCONTROL))
/* build basic block list from elf image */
int elf_build_basicblock_list(bb_list_t **bblist, elf_image_t *image, int sig, char *sigfile)
{
unsigned int curr, len, vaddr = 0;
char *att_dump;
unsigned char *ptr, *bdata;
unsigned int offset;
elf_sym_t *sym;
Elf32_Shdr *shdr;
basic_block_t *bb;
bb_list_node_t *bnode;
int bstart, bstop, bsize, binst, binstlen = 0, nopcnt = 0;
db_t db;
int bcount = 0;
for(sym = image->symlist; sym; sym = sym->next) {
sym->blist = NULL;
shdr = (Elf32_Shdr *)(image->data + image->ehdr->e_shoff + (image->ehdr->e_shentsize * sym->index));
offset = (shdr->sh_offset + sym->addr);
if(offset > image->size)
break;
ptr = (image->data + offset);
vaddr = sym->addr;
len = (sym->size == 0) ? 65535 : sym->size;
curr = 0;
bstart = bstop = bsize = binst = 0;
bdata = NULL;
bcount = 0;
while(curr < len) {
if (asm_read_instr(&instr, ptr + curr, len - curr, &proc) > 0) {
if(ASM_BLOCK_STOP(instr.type)) {
bstop = 1;
//printf("STOPING %s at %d\n", sym->name, curr);
} else bstart=1;
att_dump = asm_display_instr_att(&instr, (int)vaddr + curr);
//if(bstop) printf("%s\n", att_dump);
if (att_dump && (strcmp(att_dump,"int_err"))) {
if(!strncmp(att_dump, "nop", 3))
nopcnt++;
curr += asm_instr_len(&instr);
binst++;
binstlen += asm_instr_len(&instr);
if(bstop) {
bdata = (unsigned char *)realloc(bdata, bsize + strlen(att_dump) + 2);
sprintf((char *)(bdata + bsize), "%s\n", att_dump);
bsize += strlen(att_dump) + 1;
if((bb = (basic_block_t *)malloc(sizeof(basic_block_t))) == NULL)
exit(0);
bb->addr = (int)(vaddr + curr);
bb->vaddr = (int)(vaddr + offset + curr) - binstlen;
bb->data = (unsigned char *)strdup((char *)bdata);
bb->size = curr; //sym->size;
bb->icnt = binst;
bb->nopcnt = nopcnt;
bb->ilen = binstlen;
bb->off = offset + curr;
snprintf(bb->fname, sizeof(bb->fname), "%s", sym->name);
// printf("adding %s...\n", sym->name);
bcount++;
bb_list_add(&sym->blist, bb_list_node_alloc(bb));
free(bdata);
bstop = 0;
bstart = 1;
bsize = 0;
nopcnt = binstlen = binst = 0;
bdata = NULL;
continue;
}
if(bstart) {
if(bdata == NULL) {
if((bdata = (unsigned char *)malloc(strlen(att_dump) + 2)) == NULL)
exit(0);
memset(bdata, 0x00, strlen(att_dump));
} else if((bdata = (unsigned char *)realloc(bdata, bsize + strlen(att_dump) + 2)) == NULL)
exit(0);
sprintf((char *)(bdata + bsize), "%s\n", att_dump);
bsize += strlen((char *)att_dump) + 1;
}
}
else
{
//dump_opcodes("int_err", ptr, curr, vaddr);
curr++;
}
} else {
//dump_opcodes("asm_read_instr",ptr,curr,vaddr);
curr+=4;
}
}
if(bcount == 0) {
bdata = (unsigned char *)realloc(bdata, bsize + strlen(att_dump) + 2);
sprintf((char *)(bdata + bsize), "%s\n", att_dump);
bsize += strlen(att_dump) + 1;
bb = (basic_block_t *)malloc(sizeof(basic_block_t));
bb->addr = (int)vaddr;// + curr;
bb->vaddr = (int)(vaddr + offset + curr) - binstlen;
bb->data = bdata; //(unsigned char *)strdup((char *)bdata);
bb->size = curr;
bb->icnt = binst;
bb->nopcnt = nopcnt;
bb->ilen = binstlen;
snprintf(bb->fname, sizeof(bb->fname), "%s", sym->name);
bb_list_add(&sym->blist, bb_list_node_alloc(bb));
//free(bdata);
}
}
if(sig) {
if(db_open(&db, sigfile, DB_OVERWRITE) < 0) {
perror("db_open");
exit(-1);
}
int root = 0;
for(sym = image->symlist; sym; sym = sym->next) {
printf("[ ROUTINE INFORMATION sym=%s ]\n", sym->name);
//db_item_add(&db, sym->name, (void *)sym, sizeof(sym_t) + (sizeof(basic_block_t) + bb->size + strlen(bb->fname)) - 4);
if((bcount = basic_block_count(&sym->blist))) {
root = 0;
//printf("%s %d\n", sym->name, bcount);
for(vaddr = 0, bnode = sym->blist->head; bnode; bnode = bnode->next, vaddr++) {
bb = (basic_block_t *)bnode->dptr;
//printf("\tblock (id=%03d, size=%08d, ncnt=%03d, icnt=%03d, ilen=%05d)\n",
// vaddr, bb->size, bb->nopcnt, bb->icnt, bb->ilen);
db_item_add(&db, sym->name, root++, (void *)bb, (sizeof(basic_block_t) + strlen(bb->fname)) - 8);
}
} else {
}
printf("\n");
}
db_close(&db, 1);
}
return (1);
}
/*
* build basic block list from binary files */
int bin_build_basicblock_list(bb_list_t **bblist, bin_image_t *image, unsigned int offset, int size, char *sigfile)
{
unsigned int curr, len, vaddr = 0;
char *att_dump;
unsigned char *ptr, *bdata;
basic_block_t *bb;
//bb_list_node_t *bnode;
int bstart, bstop, bsize, binst, binstlen = 0, nopcnt = 0;
//db_t db;
int bcount = 0;
len = size;
curr = 0;
bstart = bstop = bsize = binst = 0;
bdata = NULL;
bcount = 0;
vaddr = offset;
ptr = (image->data + offset);
while(curr < len) {
if (asm_read_instr(&instr, ptr + curr, len - curr, &proc) > 0) {
if(ASM_BLOCK_STOP(instr.type)) {
bstop = 1;
} else bstart=1;
att_dump = asm_display_instr_att(&instr, (int)vaddr + curr);
if (att_dump && (strcmp(att_dump,"int_err"))) {
if(!strncmp(att_dump, "nop", 3))
nopcnt++;
curr += asm_instr_len(&instr);
binst++;
binstlen += asm_instr_len(&instr);
if(bstop) {
bdata = (unsigned char *)realloc(bdata, bsize + strlen(att_dump) + 2);
sprintf((char *)(bdata + bsize), "%s\n", att_dump);
bsize += strlen(att_dump) + 2;
if((bb = (basic_block_t *)malloc(sizeof(basic_block_t))) == NULL)
exit(0);
bb->addr = (int)(vaddr + curr);
bb->vaddr = (int)(vaddr + offset + curr) - binstlen;
bb->data = (unsigned char *)strdup((char *)bdata);
bb->size = curr;
bb->icnt = binst;
bb->nopcnt = nopcnt;
bb->ilen = binstlen;
snprintf(bb->fname, sizeof(bb->fname), "block %d", bcount);
bcount++;
bb_list_add(bblist, bb_list_node_alloc(bb));
free(bdata);
bstop = 0;
bstart = 1;
bsize = 0;
nopcnt = binstlen = binst = 0;
bdata = NULL;
continue;
}
if(bstart) {
if(bdata == NULL) {
if((bdata = (unsigned char *)malloc(strlen(att_dump) + 2)) == NULL)
exit(0);
memset(bdata, 0x00, strlen(att_dump));
} else if((bdata = (unsigned char *)realloc(bdata, bsize + strlen(att_dump) + 2)) == NULL)
exit(0);
sprintf((char *)(bdata + bsize), "%s\n", att_dump);
bsize += strlen((char *)att_dump) + 1;
}
}
else
{
//dump_opcodes("int_err", ptr, curr, vaddr);
curr++;
}
} else {
//dump_opcodes("asm_read_instr",ptr,curr,vaddr);
curr+=4;
}
}
if(bcount == 0) {
bdata = (unsigned char *)realloc(bdata, bsize + strlen(att_dump) + 2);
sprintf((char *)(bdata + bsize), "%s\n", att_dump);
bsize += strlen(att_dump) + 1;
bb = (basic_block_t *)malloc(sizeof(basic_block_t));
bb->addr = (int)vaddr;// + curr;
bb->vaddr = (int)(vaddr + offset + curr) - binstlen;
bb->data = (unsigned char *)strdup((char *)bdata);
bb->size = curr;
bb->icnt = binst;
bb->nopcnt = nopcnt;
bb->ilen = binstlen;
snprintf(bb->fname, sizeof(bb->fname), "block 0");
bb_list_add(bblist, bb_list_node_alloc(bb));
free(bdata);
}
return (bcount ? bcount : 0);
}
int elf_add_sym2list(elf_image_t *image, Elf32_Sym *sym)
{
unsigned int offset =0;
unsigned char *p;
Elf32_Shdr *shdr;
elf_sym_t *esym;
elf_sym_t **list = &image->symlist;
if(elf_byteswap(16, sym->st_shndx) > image->ehdr->e_shnum)
return (-1);
if((esym = (elf_sym_t *)malloc(sizeof(elf_sym_t))) == NULL)
return (-1);
esym->addr = elf_byteswap(32, sym->st_value);
snprintf(esym->name, sizeof(esym->name), "%s",elf_symbol_name(image->strtab, image->strtablen, elf_byteswap(32, sym->st_name)));
//printf("adding %s\n", esym->name);
esym->size = elf_byteswap(32, sym->st_size);
esym->type = ELF32_ST_TYPE(sym->st_info);
esym->binding = ELF32_ST_BIND(sym->st_info);
esym->index = elf_byteswap(16, sym->st_shndx);
esym->next = NULL;
esym->prev = NULL;
esym->code = 0;
shdr = (Elf32_Shdr *)(image->data + image->ehdr->e_shoff + (image->ehdr->e_shentsize * esym->index));
offset = (shdr->sh_offset + esym->addr);
p = (unsigned char *)(image->data + offset);
esym->crc = MG_Table_Driven_CRC(0xFFFFFFFF, p, esym->size, MG_CRC_32_ARITHMETIC_CCITT);
esym->entropy = bit_entropy(p, esym->size, &esym->probability);
esym->code = elf_symbol_opcode_crc(image, esym);
if((*list) == NULL) {
(*list) = esym;
} else {
esym->next = (*list);
(*list) = esym;
}
//printf("%-32s | %08x | %08d | %08x | %-12s (0x%08X) (%.4f bits per symbol, probability=%.4f)\n", esym->name, esym->addr, esym->size, 0, elf_type_str(esym), esym->crc, esym->entropy, esym->probability);
return (1);
}
elf_sym_t *elf_add_sym(elf_sym_t **list, elf_sym_t *sym)
{
elf_sym_t *n = malloc(sizeof(elf_sym_t));
snprintf(n->name, 64, "%s",sym->name);
n->addr = sym->addr;
n->size = sym->size ? sym->size : 32;
n->type = sym->type;
n->index = sym->index;
n->binding = sym->binding;
n->next = NULL;
if((*list) == NULL)
*list = n;
else {
n->next = (*list);
(*list)=n;
}
return (NULL);
}
void elf_print_symbols(elf_image_t *image)
{
elf_sym_t *p, *symlist = image->symlist;
Elf32_Shdr *shdr;
char *section_name;
unsigned int crc = 0;
unsigned int offset;
unsigned char *ptr;
printf("%-32s | %-8s | %-8s | %-8s | %-10s\n", "NAME", "ADDR", "SIZE", "SECTION", "TYPE");
for(p = symlist; p != NULL; p = p->next) {
if((image->ehdr->e_shoff + (image->ehdr->e_shentsize * p->index)) > image->size)
continue;
//if(p->type != STT_FUNC)
// continue;
if(p->index > image->ehdr->e_shnum)
continue;
shdr = (Elf32_Shdr *)(image->data + (image->ehdr->e_shoff + (image->ehdr->e_shentsize * p->index)));
offset = (shdr->sh_offset + p->addr);
ptr = (image->data + offset);
if(p->size <= 0) {
crc = 0xFFFFFFFF;
} else {
crc = MG_Table_Driven_CRC(0xFFFFFFFF, ptr, p->size, MG_CRC_32_ARITHMETIC_CCITT);
}
if((section_name = elf_section_name(image->shstrtab, image->shstrtablen, shdr->sh_name)) == NULL)
section_name = "NULL";
if(strcmp(section_name, ".text") && strcmp(section_name, ".data") && strcmp(section_name, ".sbss"))
continue;
//printf("%-32s | %08x | %08d | %-12s (0x%08X) (%.4f bits per symbol, probability=%.4f, %04x, %x)\n", p->name, p->addr, p->size, elf_type_str(p), p->crc, p->entropy, p->probability, code, opcode);
printf("%-32s | %08x | %08d | %08X | %.4f | %.4f | %08x\n", p->name, p->addr, p->size, p->crc, p->entropy, p->probability, p->code);
//elf_disassemble_symbol(image, p);
}
}
int elf_load_symbols(elf_image_t *image)
{
Elf32_Sym *esym = NULL;
char *name;
image->lastsym = (Elf32_Sym *)(image->symtab + image->symtablen);
for(esym = (Elf32_Sym *)(image->symtab); esym && esym < image->lastsym; esym++) {
name = elf_symbol_name(image->strtab, image->strtablen, elf_byteswap(32, esym->st_name));
if(!strcmp(name, "NULL")) continue;
//printf("esym: %d, %d, %d, %s\n", ELF32_ST_BIND(esym->st_info), ELF32_ST_TYPE(esym->st_info), esym->st_size, name);
/* will parse only local/global functions and objects */
if(ELF32_ST_BIND(esym->st_info) != STB_LOCAL && ELF32_ST_BIND(esym->st_info) != STB_GLOBAL)
continue;
if(ELF32_ST_TYPE(esym->st_info) != STT_OBJECT && ELF32_ST_TYPE(esym->st_info) != STT_FUNC)
continue;
/* discard unintialized data */
if(ELF32_ST_TYPE(esym->st_info) != STT_FUNC && esym->st_size == 0)
continue;
elf_add_sym2list(image, esym);
}
return (0);
}
elf_image_t *elf_load_image(const char *filename)
{
FILE *fp;
elf_image_t *image;
struct stat st;
if((image = (elf_image_t *)malloc(sizeof(elf_image_t))) == NULL)
return ((elf_image_t *)NULL);
if(stat(filename, &st) < 0)
return ((elf_image_t *)NULL);
if((fp = fopen(filename, "rb")) == NULL) {
free(image);
return ((elf_image_t *)NULL);
}
image->size = st.st_size;
if((image->data = (unsigned char *)malloc(image->size + 1)) == NULL) {
free(image);
return ((elf_image_t *)NULL);
}
image->name = strdup(filename);
image->strtab = NULL;
image->strtablen = 0;
image->symtab = NULL;
image->symtablen = 0;
image->shstrtab = NULL;
image->shstrtablen = 0;
fseek(fp, 0L, SEEK_SET);
if(fread(image->data, 1, image->size, fp) != image->size) {
perror("fread");
free(image);
fclose(fp);
return ((elf_image_t *)NULL);
}
fclose(fp);
image->ehdr = (Elf32_Ehdr *)image->data;
if(image->ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
ELF32_ENDIAN = 1;
image->ehdr->e_type = elf_byteswap(16, image->ehdr->e_type);
image->ehdr->e_machine = elf_byteswap(16, image->ehdr->e_machine);
image->ehdr->e_entry = elf_byteswap(32, image->ehdr->e_entry);
image->ehdr->e_shoff = elf_byteswap(32, image->ehdr->e_shoff);
image->ehdr->e_phoff = elf_byteswap(32, image->ehdr->e_phoff);
image->ehdr->e_flags = elf_byteswap(32, image->ehdr->e_flags);
image->ehdr->e_shnum = elf_byteswap(16, image->ehdr->e_shnum);
image->ehdr->e_phnum = elf_byteswap(16, image->ehdr->e_phnum);
image->ehdr->e_ehsize = elf_byteswap(16, image->ehdr->e_ehsize);
image->ehdr->e_shentsize = elf_byteswap(16, image->ehdr->e_shentsize);
image->ehdr->e_phentsize = elf_byteswap(16, image->ehdr->e_phentsize);
image->ehdr->e_shstrndx = elf_byteswap(16, image->ehdr->e_shstrndx);
image->symlist = NULL;
if(memcmp(image->ehdr->e_ident, ELF_MAGIC, 4) != 0) {
fprintf(stderr, "load ehdr");
free(image);
return ((elf_image_t *)NULL);
}
image->nsections = image->ehdr->e_shnum;
return (image);
}
elf_sym_t *elf_get_symbol_with_name(elf_image_t *image, const char *name)
{
elf_sym_t *p;
for(p = image->symlist; p; p = p->next) {
if(!strcmp(name, p->name))
return (p);
}
return ((elf_sym_t *)NULL);
}
elf_sym_t *elf_get_symbol_with_addr(elf_image_t *image, unsigned int addr)
{
elf_sym_t *p;
for(p = image->symlist; p; p = p->next) {
if(addr == p->addr)
return (p);
}
return ((elf_sym_t *)NULL);
}
void elf_disassemble_symbol(elf_image_t *image, elf_sym_t *sym)
{
unsigned int curr, len, vaddr = 0;
unsigned char *att_dump;
unsigned char *ptr, ch;
unsigned int offset;
Elf32_Shdr *shdr;
int i;
printf("<%s>:\n", sym->name);
shdr = (Elf32_Shdr *)(image->data + image->ehdr->e_shoff + (image->ehdr->e_shentsize * sym->index));
offset = (shdr->sh_offset + sym->addr);
if(offset > image->size)
return;
ptr = (image->data + offset);
vaddr = sym->addr;
len = sym->size;
curr = 0;
while(curr < len) {
if (asm_read_instr(&instr, ptr + curr, len - curr, &proc) > 0) {
att_dump = (unsigned char *)asm_display_instr_att(&instr, (int)(vaddr + curr));
if (att_dump && (strcmp((char *)att_dump,"int_err"))) {
//printf("0x%08x:\t", (int) vaddr + curr);
printf("%08x : \t",instr.nb_op);
for (i = instr.len-1; i >= 0; i--)
printf("%02x", *(ptr + curr + i));
printf(" ");
for (i = instr.len-1; i >= 0; i--) {
ch = *(ptr + curr + i);
if(ch > 0x20 && ch < 0x7f)
printf("%c", ch);
else printf(".");
}
printf("\t");
printf("%-30s", att_dump);
puts("");
curr += asm_instr_len(&instr);
}
else
{
curr++;
}
} else {
curr+=4;
}
}
/*crc = MG_Table_Driven_CRC(0xFFFFFFFF, ptr, len, MG_CRC_32_ARITHMETIC_CCITT);
double entropy;
entropy = bit_entropy(ptr, len);
printf("CRC32=%08x ENTROPY=%f bits per symbol\n", crc, entropy);*/
}
void bin_disassemble_addr(bin_image_t *image, unsigned int addr, unsigned int len)
{
unsigned int curr, vaddr = 0;
unsigned char *att_dump;
unsigned char *ptr, ch;
//unsigned int offset;
int i;
vaddr = addr;
curr = 0;
ptr = image->data + addr;
while(curr < len) {
if (asm_read_instr(&instr, ptr + curr, len - curr, &proc) > 0) {
att_dump = (unsigned char *)asm_display_instr_att(&instr, (int)(vaddr + curr));
if (att_dump && (strcmp((char *)att_dump,"int_err"))) {
//printf("0x%08x:\t", (int) vaddr + curr);
printf("%08x : \t", vaddr + curr);
for (i = instr.len-1; i >= 0; i--)
printf("%02x", *(ptr + curr + i));
printf(" ");
for (i = instr.len-1; i >= 0; i--) {
ch = *(ptr + curr + i);
if(ch > 0x20 && ch < 0x7f)
printf("%c", ch);
else printf(".");
}
printf("\t");
printf("%-30s", att_dump);
puts("");
curr += asm_instr_len(&instr);
}
else
{
curr++;
}
} else {
curr+=4;
}
}
/*crc = MG_Table_Driven_CRC(0xFFFFFFFF, ptr, len, MG_CRC_32_ARITHMETIC_CCITT);
double entropy;
entropy = bit_entropy(ptr, len);
printf("CRC32=%08x ENTROPY=%f bits per symbol\n", crc, entropy);*/
}
bin_image_t *bin_load_image(const char *filename)
{
FILE *fp;
struct stat st;
bin_image_t *image = (bin_image_t *)malloc(sizeof(bin_image_t));
if(image == NULL)
return (image);
if(stat(filename, &st) < 0)
return (NULL);
if((image->size = st.st_size) <= 0)
return (NULL);
if((fp = fopen(filename, "rb")) == NULL)
return (NULL);
if((image->data = malloc(st.st_size + 1)) == NULL) {
fclose(fp);
free(image);
return (NULL);
}
if(fread((char *)image->data, 1, st.st_size, fp) != (int)st.st_size) {
fclose(fp);
free(image->data);
free(image);
return (NULL);
}
image->crc = MG_Table_Driven_CRC(0xFFFFFFFF, image->data, image->size, MG_CRC_32_ARITHMETIC_CCITT);
//image->hashl = hashlittle(image->data, image->size, image->crc);
return (image);
}
int search_symbol(bin_image_t *bimage, elf_sym_t *sym)
{
int cur;
unsigned char *ptr = (unsigned char *)bimage->data;
if(sym == NULL)
return (0);
for(cur = 0; cur < bimage->size;) {
if(asm_read_instr(&instr, (ptr + cur), sym->size, &proc) > 0) {
cur += instr.len;
} else {
cur += 4;
}
}
return (0);
}
#define MODE_INFO 0x00
#define MODE_SEARCH 0x01
#define MODE_DISASM 0x02
#define MODE_ANALISYS 0x03
#define MODE_CREATE_SIG 0x04
#define MODE_SIGINFO 0x05
#define MODE_BINASM 0x06
void sig_open(db_t *db, const char *filename)
{
//basic_block_t *bb;
db_item_t *item;
unsigned int icount = 0, ilen = 0, bsize = 0, bcount = 0;
if(db_open(db, filename, DB_OPEN) < 0) {
perror("db_open");
exit(-1);
}
printf("signature file '%s' loaded with %d block signatures and %d functions\n\n", filename, db->nitems, db->nroot);
}
void sig_info(const char *filename)
{
basic_block_t *bb;
db_item_t *item, *lastitem;
db_t db;
unsigned int icount = 0, ilen = 0, bsize = 0, bcount = 0;
double pr, entropy = 0;
if(db_open(&db, filename, DB_OPEN) < 0) {
perror("db_open");
exit(-1);
}
printf("block signatures: %d\n", db.nitems);
printf("function count: %d\n", db.nroot);
while((item = db_item_get(&db, NULL, 0)) != NULL) {
bb = (basic_block_t *)item->data;
if(!item->root && bcount) {
lastitem->child = bcount;
printf(" => icount=%d, bcount=%d, ilen=%d, entropy=%f, prob=%f\n", icount, bcount, ilen, entropy, pr);
}
if(!item->root) {
printf("[ FUNCTION %-32s ]", item->name);
icount = ilen = bsize = bcount = 0;
fflush(stdout);
}
icount += bb->icnt;
bsize += bb->size;
ilen += bb->ilen;
bcount += 1;
lastitem = item;
//fflush(stdout);
//entropy += bit_entropy(bb->data, bb->size, &pr);
//printf("bb->size: %d\n%x\n", bsize, bb->data);
}
printf(" => icount=%d, bcount=%d, ilen=%d\n", icount, bcount, ilen);
db_close(&db, 0);
}
int main(int argc, char **argv)
{
elf_sym_t *sym = NULL;
bin_image_t *bimage = NULL;
elf_image_t *eimage = NULL;
char output[65535];
int outsize = 0;
int mode = 0;
char *sigfile;
db_t sigdb;
bb_list_node_t *node;
MG_Setup_CRC_Table(MG_CRC_32_ARITHMETIC_CCITT);
if(argc < 4) {
printf("sigtool - 0.1");
printf("copyright (c) 2011, snape\n\n");
printf("options:\n");
printf("\t-createsig <elf file> <signature file>:\t create signatures for routines found on <elf file>\n");
printf("\t-search\n");
printf("\t-info\n");
printf("\t-disasm\n");
printf("\t-anal\n");
printf("\t-siginfo\n");
printf("\t-binasm\n");
printf("\tread source for info\n");
exit(0);
}
asm_init_mips(&proc);
//asm_init_i386(&proc);
asm_config_set_endian(!ELF32_ENDIAN);
if(!strcmp(argv[1], "-search") && argv[2] != NULL && argv[3] != NULL && argv[4] != NULL) {
mode = MODE_SEARCH;
bimage = bin_load_image(argv[2]);
if((eimage = elf_load_image(argv[3])) == NULL)
exit(0);
} else if(!strcmp(argv[1], "-info") && argv[2] != NULL) {
mode = MODE_INFO;
if((eimage = elf_load_image(argv[2])) == NULL)
exit(0);
} else if(!strcmp(argv[1], "-disasm") && argv[2] != NULL && argv[3] != NULL) {
mode = MODE_DISASM;
if((eimage = elf_load_image(argv[2])) == NULL)
exit(0);
} else if(!strcmp(argv[1], "-anal") && argv[2] != NULL && argv[3] != NULL) {
mode = MODE_ANALISYS;
if((eimage = elf_load_image(argv[2])) == NULL)
exit(0);
} else if(!strcmp(argv[1], "-createsig") && argv[2] != NULL) {
mode = MODE_CREATE_SIG;
if((eimage = elf_load_image(argv[2])) == NULL)
exit(0);
sigfile = argv[3] ? argv[3] : "sigs.db";
} else if(!strcmp(argv[1], "-siginfo") && argv[2] != NULL) {
mode = MODE_SIGINFO;
sigfile = argv[2];
} else if(!strcmp(argv[1], "-binasm") && argv[2] != NULL) {
mode = MODE_BINASM;
}
bb_list_t *blist = NULL;
db_item_t *item;
if(mode != MODE_SIGINFO && mode != MODE_BINASM) {
if(eimage == NULL)
exit(0);
elf_load_strtab(eimage);
elf_load_symtab(eimage);
elf_load_symbols(eimage);
}
switch(mode) {
case MODE_SEARCH:
if((sym = elf_get_symbol_with_name(eimage, argv[4])) != NULL) {
elf_disassemble_symbol(eimage, sym);
} else {
printf("%s symbol not found\n", argv[4]);
}
break;
case MODE_INFO:
elf_print_symbols(eimage);
break;
case MODE_DISASM:
if((sym = elf_get_symbol_with_name(eimage, argv[3])) != NULL) {
elf_disassemble_symbol(eimage, sym);
} else {
printf("%s symbol not found\n", argv[3]);
}
break;
case MODE_ANALISYS:
elf_build_basicblock_list(&blist, eimage, 0, NULL);
break;
case MODE_CREATE_SIG:
elf_build_basicblock_list(&blist, eimage, 1, sigfile);
break;
case MODE_SIGINFO:
sig_info(argv[2]);
break;
case MODE_BINASM:
sigfile = argv[3];
printf("loading binary image: %s\n", argv[2]);
bimage = bin_load_image(argv[2]);
bb_list_t *blist = NULL;
basic_block_t *b, *bb;
printf("loading signature file: %s\n", argv[3]);
sig_open(&sigdb, argv[3]);
printf("OK!\n");
int start = 1, found = 0;
int ilenok = 0, icntok = 0;
int check = 0, bcount = 0;
int startaddr = 0, ll = 0;
int probability = 0;
int bbbsize = 0;
int lastaddr = 0;
unsigned char ch[] = "-/|\\";
double pr = 0;
char tmpout[1024];
memset(output, 0x00, sizeof(output));
for(found = 0; startaddr < (bimage->size);) {
if(blist != NULL) {
for(node = blist->head; node; node = node->next) {
if((bb = (basic_block_t *)(node->dptr)) == NULL)
continue;
free(bb->data);
free(bb);
free(node);
}
blist = NULL;
}
start = 1;
bcount = 0;
probability = 0;
if(++found == 4)
found = 0;
printf("\rsearching for item %s, %-3d%% ( %c )", argv[4], ((startaddr * 100) / bimage->size), ch[found]);
fflush(stdout);
while ((item = db_item_get(&sigdb, argv[4], start)) != NULL) {
b = (basic_block_t *)(item->data);
if(start) {
//printf("loading basic blocks (address=0x%x, size=%d, file=%s)\n", startaddr, b->size, sigfile);
ll = bin_build_basicblock_list(&blist, bimage, startaddr, b->size, sigfile);
//printf("loaded %d blocks\n", ll);
node = blist->head;
bbbsize = b->size;
//bin_disassemble_addr(bimage, 0, b->size);
//node = blist->head;
}
if((bb = (basic_block_t *)(node->dptr)) == NULL) {
printf("exiting, db corrupted\n");
break;
}
ilenok = icntok = 0;
/* dumb probability calculation */
if(bb->ilen == b->ilen) {
ilenok = 1;
probability+=3;
} else
if(bb->ilen < b->ilen) {
if((b->ilen - bb->ilen) < BB_THRESHOLD) {
ilenok = 1;
probability+=1;
}
} else
if(bb->ilen > b->ilen){
if((bb->ilen - b->ilen) < BB_THRESHOLD) {
ilenok = 1;
probability+=1;
}
}
if(bb->icnt == b->icnt) {
icntok = 1;
probability+=3;
} else
if(bb->icnt < b->icnt) {
if((b->icnt - bb->icnt) < BB_THRESHOLD) {
icntok = 1;
probability+=1;
}
} else
if(bb->icnt > b->icnt) {
if((b->icnt - bb->icnt) < BB_THRESHOLD) {
icntok = 1;
probability+=1;
}
}
if(icntok && ilenok) check++;
bcount++;
ilenok = icntok = 0;
start = 0;
node=node->next;
if(node == NULL)
break;
}
icntok = 0;
if(check > bcount)
if((check - bcount) <= BB_THRESHOLD)
icntok = 1;
if(check < bcount)
if((bcount - check) <= BB_THRESHOLD)
icntok = 1;
if(icntok) {
if((startaddr - lastaddr) > 16) {
outsize = strlen(output);
memset(tmpout, 0x00, sizeof(tmpout));
snprintf(tmpout, sizeof(tmpout),
"sig(fname=%s, probability=%d, foff=0x%x, [check=%d, bcount=%d, startaddr=%d, threshold=%d])\n",
b->fname, probability,
startaddr, check, bcount, startaddr, BB_THRESHOLD);
//printf("size: %d\n", printf(output));
strcat(output + outsize, tmpout);
//outsize += strlen(tmpout);
}
lastaddr = startaddr;
if(probability == 36)
bin_disassemble_addr(bimage, startaddr, bbbsize);
check = 0; bcount = 0;
//printf("\n\n\n");
//found = 1;
//break;
}
startaddr += 4;
}
printf("\n%s\n", output);
break;
default:
break;
}
free(eimage);
printf("\nexiting.\n");
exit(0);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_movcc.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_movcc.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_movcc.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libasm.h"
int
asm_sparc_movcc(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_format3 opcode;
struct s_decode_format4 opcode4;
struct s_asm_proc_sparc *inter;
sparc_convert_format3(&opcode, buf);
sparc_convert_format4(&opcode4, buf);
inter = proc->internals;
ins->type = ASM_TYPE_ASSIGN | ASM_TYPE_READFLAG;
if (opcode4.cc2 == 0) { /* fcc{0,1,2,3,4} */
ins->instr = inter->movcc_table[opcode4.cond];
ins->flagsread = ASM_SP_FLAG_FCC0 << opcode4.cc;
}
else if (opcode4.cc0 == 0) { /* icc or xcc */
ins->instr = inter->movfcc_table[opcode4.cond];
ins->flagsread = ASM_SP_FLAG_C | ASM_SP_FLAG_V | ASM_SP_FLAG_N | ASM_SP_FLAG_Z;
}
else {
ins->instr = ASM_SP_BAD;
return 4;
}
ins->nb_op = 3;
ins->op[0].baser = opcode4.rd;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_REGISTER, ins);
ins->op[2].baser = opcode4.cc;
asm_sparc_op_fetch(&ins->op[2], buf, ASM_SP_OTYPE_CC, ins);
if (opcode.i == 0) {
ins->op[1].baser = opcode.rs2;
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_REGISTER, ins);
}
else {
ins->op[1].imm = opcode.imm;
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_IMMEDIATE, ins);
}
return 4;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_test_al_rb.c
/**
* @file libasm/src/arch/ia32/handlers/op_test_al_rb.c
*
* @ingroup IA32_instrs
** $Id: op_test_al_rb.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @brief Handler for instruction test al,rb opcode 0xa8
* @param instr Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Length of instruction.
*/
int op_test_al_rb(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->instr = ASM_TEST;
new->len += 1;
new->type = ASM_TYPE_COMPARISON | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_OF | ASM_FLAG_CF | ASM_FLAG_PF |
ASM_FLAG_SF | ASM_FLAG_ZF;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_AL,
ASM_REGSET_R8));
new->len += asm_operand_fetch(&new->op[1], opcode + 1,
ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new);
new->op[0].content = ASM_OP_BASE;
new->op[0].baser = ASM_REG_AL;
new->op[0].regset = ASM_REGSET_R8;
new->len += asm_operand_fetch(&new->op[1], opcode + 1,
ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_shift_rmb_cl.c
/**
* @file libasm/src/arch/ia32/handlers/op_shift_rmb_cl.c
*
* @ingroup IA32_instrs
* $Id: op_shift_rmb_cl.c 1397 2009-09-13 02:19:08Z may $
*
* Changelog
* 2007-05-29 : instruction set was not complete.
* operand type for operand 1 was incorrect.
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for instruction shit rmb,cl opcode 0xd2
* <instruction func="op_shift_rmb_cl" opcode="0xd2"/>
*/
int op_shift_rmb_cl(asm_instr *instr, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode + 1;
instr->ptr_instr = opcode;
instr->len += 1;
instr->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
instr->flagswritten = ASM_FLAG_CF | ASM_FLAG_OF;
switch(modrm->r)
{
case 0: instr->instr = ASM_ROL; break;
case 1: instr->instr = ASM_ROR; break;
case 2: instr->instr = ASM_RCL; break;
case 3: instr->instr = ASM_RCR; break;
case 4:
instr->instr = ASM_SHL;
instr->flagswritten |= ASM_FLAG_PF | ASM_FLAG_ZF | ASM_FLAG_SF;
break;
case 5:
instr->instr = ASM_SHR;
instr->flagswritten |= ASM_FLAG_PF | ASM_FLAG_ZF | ASM_FLAG_SF;
break;
case 6:
instr->instr = ASM_SAL;
instr->flagswritten |= ASM_FLAG_PF | ASM_FLAG_ZF | ASM_FLAG_SF;
break;
case 7:
instr->instr = ASM_SAR;
instr->flagswritten |= ASM_FLAG_PF | ASM_FLAG_ZF | ASM_FLAG_SF;
break;
}
#if WIP
instr->len += asm_operand_fetch(&instr->op[0], opcode + 1, ASM_OTYPE_ENCODEDBYTE,
instr, 0);
instr->len += asm_operand_fetch(&instr->op[1], opcode + 1, ASM_OTYPE_FIXED, instr,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_CL,
ASM_REGSET_R8));
#else
instr->len += asm_operand_fetch(&instr->op[0], opcode + 1, ASM_OTYPE_ENCODEDBYTE,
instr);
instr->len += asm_operand_fetch(&instr->op[1], opcode + 1, ASM_OTYPE_FIXED, instr);
instr->op[1].content = ASM_OP_BASE;
instr->op[1].regset = ASM_REGSET_R8;
instr->op[1].baser = ASM_REG_CL;
#endif
return (instr->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_group12.c
/*
** $Id: i386_group12.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<i386 func="i386_group12" opcode="0x71"/>
*/
int i386_group12(asm_instr *new, u_char *opcode,
u_int len, asm_processor *proc)
{
int olen;
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode + 1;
new->ptr_instr = opcode;
new->len += 1;
switch (modrm->r)
{
case 2:
new->instr = ASM_PSRLW;
break;
case 4:
new->instr = ASM_PSRAW;
break;
case 6:
new->instr = ASM_PSLLW;
break;
default:
new->instr = ASM_BAD;
return (new->len = 0);
break;
}
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_PMMX, new, 0));
#else
new->len += (olen = asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_PMMX, new));
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen, ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1 + olen, ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
#else
new->op[0].type = ASM_OTYPE_PMMX;
new->op[0].size = ASM_OSIZE_QWORD;
new->op[1].type = ASM_OTYPE_IMMEDIATE;
new->op[1].size = ASM_OSIZE_BYTE;
operand_rmb_ib(new, opcode + 1, len - 1, proc);
new->op[0].regset = ASM_REGSET_MM;
#endif
return (new->len);
}
<file_sep>/src/libasm/tools/modrm.c
/**
* @file libasm/tools/modrm.c
* $Id: modrm.c 1397 2009-09-13 02:19:08Z may $
* @brief Little utility to display modrm byte to debug ia32.
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct s_modrm
{
u_char m:3;
u_char r:3;
u_char mod:2;
} asm_modrm;
/**
* Will display content of 0xe0 for the modrm byte:
* Main usage : modrm 0xe2
* $ ./modrm e2
* op = 3 r = 4, m = 2
*
*/
int main(int ac, char **av)
{
struct s_modrm val;
char hex;
if (ac < 2)
{
printf("Usage: %s [hex modrmbyte]\n", av[0]);
exit(-1);
}
hex = strtoul(av[1], 0, 16);
memcpy(&val, &hex, 1);
printf("op = %i r = %i, m = %i\n",
val.mod,
val.r,
val.m);
return (0);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_fmovdcc.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_fmovdcc.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_fmovdcc.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libasm.h"
int
asm_sparc_fmovdcc(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_format3 opcode;
struct s_asm_proc_sparc *inter;
sparc_convert_format3(&opcode, buf);
inter = proc->internals;
ins->type = ASM_TYPE_ASSIGN | ASM_TYPE_READFLAG;
if (opcode.opf_cc < 4) {
ins->instr = inter->fmovfcc_table[(((opcode.opf & 0x1f) - 1) * 8)
+ opcode.cond];
ins->flagsread = ASM_SP_FLAG_FCC0 << opcode.opf_cc;
}
else if (opcode.opf_cc == 4 || opcode.opf_cc == 6) {
ins->instr = inter->fmovcc_table[(((opcode.opf & 0x1f) - 1) * 8)
+ opcode.cond];
ins->flagsread = ASM_SP_FLAG_C | ASM_SP_FLAG_V | ASM_SP_FLAG_N | ASM_SP_FLAG_Z;
}
else {
ins->instr = ASM_SP_BAD;
return 4;
}
ins->nb_op = 3;
ins->op[0].baser = ((opcode.rd & 1) << 5) | (opcode.rd & 0x1E);
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_FREGISTER, ins);
ins->op[1].baser = ((opcode.rs2 & 1) << 5) | (opcode.rs2 & 0x1E);
asm_sparc_op_fetch(&ins->op[1], buf, ASM_SP_OTYPE_FREGISTER, ins);
ins->op[2].baser = opcode.opf_cc;
asm_sparc_op_fetch(&ins->op[2], buf, ASM_SP_OTYPE_CC, ins);
return 4;
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_group15.c
/*
** $Id: i386_group15.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="i386_group15" opcode="0xae"/>
*/
int i386_group15(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode + 1;
new->len += 1;
switch(modrm->r)
{
case 2:
new->instr = ASM_LDMXCSR;
new->op[0].type = ASM_OTYPE_ENCODED;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#else
operand_rmv(&new->op[0], opcode + 1, len - 1, proc);
new->len += new->op[0].len;
#endif
break;
case 3:
new->instr = ASM_STMXCSR;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#else
new->op[0].type = ASM_OTYPE_ENCODED;
operand_rmv(&new->op[0], opcode + 1, len - 1, proc);
new->len += new->op[0].len;
#endif
break;
case 7:
new->instr = ASM_CLFLUSH;
new->op[0].type = ASM_OTYPE_GENERAL;
break;
default:
new->len = 0;
break;
}
return (new->len);
}
<file_sep>/Makefile
CC = gcc
DFLAGS = -m32 -ggdb -g3 -DERESI32 -fPIC -I./include/ -I./src/libasm/include -I./src/libaspect/include
CFLAGS = -Wall -Wno-unused -m32 -DERESI32 -fPIC -funroll-all-loops -fomit-frame-pointer -I./include/ -I./src/libasm/include -I./src/libaspect/include $(DFLAGS)
SRCS = src/image.c src/fastcrc.c src/list.c src/db.c
OBJECTS = $(SRCS:.c=.o)
TARGET = sigtool
LIBS = src/libasm/libasm32.a src/libaspect/libaspect32.a
all: libasm32 $(OBJECTS)
@$(CC) $(DFLAGS) $(LIBS) $(OBJECTS) -o $(TARGET)
libasm32:
@echo "BUILDING LIBASPECT..."
@make -C src/libaspect all
@echo ""
@echo "BUILDING LIBASM..."
@make -C src/libasm all
debug:
@$(CC) $(DFLAGS) $(LIBS) $(OBJECTS) -o $(TARGET)
dis:
@$(CC) $(CFLAGS) $(LIBS) disasm.c -o $(TARGET)
clean:
rm -rf $(OBJECTS) $(TARGET)
make -C src/libasm clean
make -C src/libaspect clean
.SUFFIXES: .c .o
.c.o:
@echo "[CC SIGTOOL] $< ..."
@$(CC) $(DFLAGS) -c -o $@ $<
<file_sep>/src/libasm/src/arch/ia32/handlers/op_outsb.c
/*
** $Id: op_outsb.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_outsb" opcode="0x6e"/>
*/
int op_outsb(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->instr = ASM_OUTSB;
new->ptr_instr = opcode;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_DX,
ASM_REGSET_R16));
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_XSRC, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new);
new->op[0].content = ASM_OP_BASE | ASM_OP_REFERENCE;
new->op[0].regset = ASM_REGSET_R16;
new->op[0].baser = ASM_REG_EDX;
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_XSRC, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_sbb_eax_iv.c
/**
* @file libasm/src/arch/ia32/handlers/op_sbb_eax_iv.c
*
* @ingroup IA32_instrs
** $Id: op_sbb_eax_iv.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_sbb_eax_iv" opcode="0x1d"/>
*/
int op_sbb_eax_iv(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->len += 1;
new->ptr_instr = opcode;
new->instr = ASM_SBB;
new->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG | ASM_TYPE_READFLAG;
new->flagsread = ASM_FLAG_CF;
new->flagswritten = ASM_FLAG_AF | ASM_FLAG_CF | ASM_FLAG_PF |
ASM_FLAG_OF | ASM_FLAG_SF | ASM_FLAG_ZF;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
new->len += asm_operand_fetch(&new->op[1], opcode + 1,
ASM_OTYPE_IMMEDIATE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new);
new->op[0].size = new->op[1].size = ASM_OSIZE_VECTOR;
new->op[0].content = ASM_OP_FIXED | ASM_OP_BASE;
new->op[0].baser = ASM_REG_EAX;
new->op[0].regset = asm_proc_opsize(proc) ? ASM_REGSET_R32 :
ASM_REGSET_R16;
new->len += asm_operand_fetch(&new->op[1], opcode + 1,
ASM_OTYPE_IMMEDIATE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_call.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_call.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_call.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libasm.h"
int
asm_sparc_call(asm_instr *ins, u_char *buf, u_int len,
asm_processor *proc)
{
struct s_decode_call opcode;
sparc_convert_call(&opcode, buf);
ins->ptr_instr = buf;
ins->instr = ASM_SP_CALL;
ins->type = ASM_TYPE_CALLPROC;
ins->nb_op = 1;
ins->op[0].imm = opcode.displacement;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_DISP30, ins);
return 4;
}
<file_sep>/src/libasm/src/instruction.c
/**
*
* @file libasm/src/instruction.c
* @ingroup libasm
* Author : <<EMAIL>>
* Started : Mon Mar 15 13:58:52 2004
* Updated : Mon Mar 22 01:35:03 2004
*
* $Id: instruction.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
/**
* Return instruction length.
* @param ins Pointer to instruction structure.
* @param opt Optional parameter, not used.
* @param valptr Optional parameter, not used.
* @return Instruction length
*/
int asm_instruction_get_len(asm_instr *ins, int opt, void *valptr) {
int *val;
val = (int *) valptr;
if (ins && val)
*val = ins->len;
return (ins->len);
}
/**
* @param
* @param opt Optional parameter. Not used.
* @param valptr
* @return Returns 0.
*/
int asm_instruction_get_mnemonic(asm_instr *ins, int opt, void *valptr)
{
char **ptr;
if (valptr)
{
ptr = valptr;
*ptr = ins->proc->instr_table[ins->instr];
}
return (0);
}
/**
* @brief Get instruction type.
* @return Returns 1 on success, 0 on error.
*/
int asm_instruction_get_type(asm_instr *ins, int opt, void *valptr)
{
int *val;
if (valptr)
{
val = valptr;
*val = ins->type;
}
return (1);
}
/**
* @brief Get instruction prefixes
* @param ins Pointer to instruction.
* @param opt Optional parameter.
* @param valptr Pointer to store prefix (bitflag stored on an integer)
* @return Returns 1.
*/
int asm_instruction_get_prefix(asm_instr *ins, int opt, void *valptr)
{
int *val;
if (valptr)
{
val = valptr;
*val = ins->prefix;
}
return (1);
}
/**
* get number of operand of instruction
*
*/
int asm_instruction_get_nbop(asm_instr *ins, int opt, void *valptr)
{
int *val;
if (valptr)
{
val = valptr;
*val = 0;
if (ins->op[0].type)
(*val)++;
if (ins->op[1].type)
(*val)++;
if (ins->op[2].type)
(*val)++;
}
return (1);
}
/**
* @brief Return instruction length
* @param instr Pointer to instruction.
*/
int asm_instruction_get_length(asm_instr *instr)
{
if (instr)
return (instr->len);
else
return (-1);
}
<file_sep>/src/libasm/src/arch/ia32/operand_handlers/asm_operand_fetch_general.c
/**
* @file libasm/src/arch/ia32/operand_handlers/asm_operand_fetch_general.c
*
* @ingroup IA32_operands
* $Id: asm_operand_fetch_general.c 1397 2009-09-13 02:19:08Z may $
* @brief Operand Handler to decode data for operand type ASM_OTYPE_GENERAL
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* @brief Decode data for operand type ASM_OTYPE_GENERAL
*
* @ingroup IA32_operands
* @param operand Pointer to operand structure to fill.
* @param opcode Pointer to operand data
* @param type Not used.
* @param ins Pointer to instruction structure.
* @return Operand length
*/
#if WIP
int asm_operand_fetch_general(asm_operand *operand, u_char *opcode,
int type, asm_instr *ins, int opt)
#else
int asm_operand_fetch_general(asm_operand *operand, u_char *opcode,
int type, asm_instr *ins)
#endif
{
struct s_modrm *modrm;
operand->type = ASM_OTYPE_GENERAL;
operand->content = ASM_OP_BASE;
operand->regset = asm_proc_is_protected(ins->proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16;
modrm = (struct s_modrm *) opcode;
operand->baser = modrm->r;
operand->sbaser = get_reg_intel(operand->baser, operand->regset);
operand->len = 0;
return (0);
}
<file_sep>/src/libasm/src/arch/ia32/operand_handlers/asm_operand_fetch_pmmx.c
/**
* @file libasm/src/arch/ia32/operand_handlers/asm_operand_fetch_pmmx.c
* $Id: asm_operand_fetch_pmmx.c 1397 2009-09-13 02:19:08Z may $
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Fetch ASM_OTYPE_PMMX operand
*
*
*/
/**
* Decode data for operand type ASM_OTYPE_PMMX
*
* @ingroup IA32_operands
* @param operand Pointer to operand structure to fill.
* @param opcode Pointer to operand data
* @param otype
* @param ins Pointer to instruction structure.
* @return Operand length
*/
#if WIP
int asm_operand_fetch_pmmx(asm_operand *operand, u_char *opcode, int otype,
asm_instr *ins, int opt)
#else
int asm_operand_fetch_pmmx(asm_operand *operand, u_char *opcode,
int otype, asm_instr *ins)
#endif
{
int len;
operand->type = ASM_OTYPE_PMMX;
len = operand_rmv(operand, opcode, 4, ins->proc);
asm_content_pack(operand, operand->content, operand->type);
operand->regset = ASM_REGSET_MM;
operand->sbaser = get_reg_intel(operand->baser, operand->regset);
return (len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_in_eax_ref_ib.c
/*
** $Id: op_in_eax_ref_ib.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_in_eax_ref_ib" opcode="0xe5"/>
*/
int op_in_eax_ref_ib(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->instr = ASM_IN;
new->ptr_instr = opcode;
new->len += 1;
new->type = ASM_TYPE_LOAD | ASM_TYPE_IO;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_FIXED, new);
#endif
new->op[0].content = ASM_OP_BASE | ASM_OP_FIXED;
new->op[0].baser = ASM_REG_EAX;
new->op[0].regset = asm_proc_opsize(proc) ?
ASM_REGSET_R16 : ASM_REGSET_R32;
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
new->op[1].content = ASM_OP_REFERENCE | ASM_OP_VALUE;
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_shld.c
/**
* @file libasm/src/arch/ia32/handlers/i386_shld.c
*
* @ingroup IA32_instrs
* $Id: i386_shld.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for instruction shld, opcode 0x0f 0xa4
* @param new Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Length of instruction.
*/
int i386_shld(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
new->len += 1;
modrm = (struct s_modrm *) opcode + 1;
new->instr = ASM_SHLD;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_REGISTER, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_REGISTER, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_GENERAL, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_GENERAL, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[2], opcode + 2, ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[2], opcode + 2, ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
new->len += 1;
#else
new->op[0].type = ASM_OTYPE_REGISTER;
new->op[0].regset = ASM_REGSET_R32;
new->op[0].content = ASM_OP_BASE;
new->op[0].ptr = opcode + 1;
new->op[0].len = 0;
new->op[0].baser = modrm->m;
new->op[1].type = ASM_OTYPE_GENERAL;
new->op[1].regset = ASM_REGSET_R32;
new->op[1].content = ASM_OP_BASE;
new->op[1].ptr = opcode + 1;
new->op[1].len = 1;
new->op[1].baser = modrm->r;
new->op[2].type = ASM_OTYPE_IMMEDIATE;
new->op[2].content = ASM_OP_VALUE;
new->op[2].ptr = opcode + 2;
new->op[2].len = 1;
new->op[2].imm = 0;
memcpy(&new->op[2].imm, opcode + 2, 1);
new->len += new->op[0].len + new->op[1].len + new->op[2].len;
#endif
return (new->len);
}
<file_sep>/src/libasm/include/libasm-mips.h
/**
* @defgroup mips Libasm MIPS support
* @ingroup libasm
*/
/**
* @file libasm/include/libasm-mips.h
* @ingroup mips
*
* - <NAME> - 2006
* - <NAME> - 2007
* - <NAME> - 2008
* $Id: libasm-mips.h 1397 2009-09-13 02:19:08Z may $
*/
#ifndef LIBASM_MIPS_H_
#define LIBASM_MIPS_H_
#include <libasm.h>
#include <libasm-mips-structs.h>
//LIBASM_HANDLER_DISPLAY(asm_mips_display_instr);
//LIBASM_HANDLER_FETCH(fetch_mips);
#define ASM_CONFIG_MIPS_REGISTER_FLAVOUR "libasm.mips.output.registers"
#define ASM_CONFIG_MIPS_STANDARD_REGISTERS 0
#define ASM_CONFIG_MIPS_EXTENDED_REGISTERS 1
#define ASM_MIPS_REG_FPU ASM_CONFIG_MIPS_EXTENDED_REGISTERS
char *asm_mips_display_instr(asm_instr *, eresi_Addr a);
void mips_convert_format_r(struct s_mips_decode_reg *opcode, u_char *buf);
void mips_convert_format_i(struct s_mips_decode_imm *opcode, u_char *buf);
void mips_convert_format_j(struct s_mips_decode_jump *opcode, u_char *buf);
void mips_convert_format_t(struct s_mips_decode_trap *opcode, u_char *buf);
void mips_convert_format_cop2(struct s_mips_decode_cop2 *opcode, u_char *buf);
void mips_convert_format_cop0(struct s_mips_decode_cop0 *opcode, u_char *buf);
void mips_convert_format_mov(struct s_mips_decode_mov *opcode, u_char *buf);
void mips_convert_format_cop1x(struct s_mips_decode_cop1x *opcode, u_char *buf);
//#define mips_convert_format_priv mips_convert_format_cop2 snape
#define mips_convert_format_priv mips_convert_format_cop2
int asm_fetch_mips(asm_instr *, u_char *, u_int, asm_processor *);
int asm_register_mips();
int asm_register_mips_opcodes();
int asm_register_mips_operands();
int asm_register_mips_operand(unsigned int type, unsigned long func);
#define Ob(x) ((unsigned)Ob_(0 ## x ## uL))
#define Ob_(x) ((x & 1) | ((x >> 2) & 2) | ((x >> 4) & 4) | ((x >> 6) & 8) | \
((x >> 8) & 16) | ((x >> 10) & 32) | ((x >> 12) & 64) | ((x >> 14) & 128))
/*
* funciones
* TODO
*/
/**
* @page mips.html
*
* <pre>
*
* Instruction field meanings, from the
* mips32 architecture manual
*
* opcode 6-bit primary operation code
* rd 5-bit specier for the destination register
* rs 5-bit spec for the source register
* rt 5-bit specr for the target (source/destination)
* register or used to specify functions within the primary
* opcode REGIMM
* immediate 16-bit signed immediate used for logical operands,
* arithmetic signed operands, load/store address
* byte offsets, and PC-relative branch signed
* instruction displacement
* instr_index 26-bit index shifted left two bits to supply the
* low-order 28 bits of the jump target address
* sa 5-bit shift amount
* function 6-bit function ld used to specify functions
* within the primary opcode SPECIAL
* </pre>
*/
/* Immediate/(I-type) instruction
* used to work with immediate values (up to 16 bits) */
//struct s_mips_insn_imm
//{
// u_int32_t opcode:6;
// u_int32_t rs:5;
// u_int32_t rt:5; /* operation (sometimes) */
// u_int32_t immediate:16;
//};
/* This is a subtype of the type inmmediate, it's used
* in some branch-conditional instructions*/
//struct s_mips_insn_imm_bc
//{
// u_int32_t opcode:6;
// u_int32_t rs:5; /* operation */
// u_int32_t cc:3; /* condition code*/
// u_int32_t nd:1; /* nullify delay slot*/
// u_int32_t tf:1; /* true/false*/
// u_int32_t offset:16;
//};
/* Jump/(J-type) instruction
* used for jumps/branches */
//struct s_mips_insn_jump
//{
// u_int32_t opcode:6;
// u_int32_t instr_index:26;
//};
/* Register/(R-type) instruction
* used to transfer data between registers */
//struct s_mips_insn_reg
//{
// u_int32_t opcode:6;
// u_int32_t rs:5;
// u_int32_t rt:5;
// u_int32_t rd:5;
// u_int32_t sa:5;
// u_int32_t function:6;
//};
/* This is a subtype of the register type, it's
* used only for the BREAK and SYSCALL instructions */
//struct s_mips_insn_reg_break_syscall
//{
// u_int32_t opcode:6;
// u_int32_t code:20;
// u_int32_t function:6;
//};
/* This is a subtype of the register type, it's
* used only for the DERET insn*/
//struct s_mips_insn_reg_deret
//{
// u_int32_t opcode:6;
// u_int32_t co:1;
// u_int32_t zero:19;
// u_int32_t function:6;
//};
#define MIPS_SPECIAL_FUNCTION_NUM 64
#define MIPS_REGIMM_FUNCTION_NUM 32
#define MIPS_SPECIAL2_FUNCTION_NUM 64
#define MIPS_SPECIAL3_FUNCTION_NUM 64
#define MIPS_LEVEL0_OPCODES_NUM 64
#define MIPS_LEVEL1_OPCODES_NUM 224
#define MIPS_LEVEL2_OPCODES_NUM 38
#define ASM_MIPS_TABLE_END -1
enum opcode_field_encoding {
MIPS_OPCODE_SPECIAL, /* class */
MIPS_OPCODE_REGIMM, /* class */
MIPS_OPCODE_J,
MIPS_OPCODE_JAL,
MIPS_OPCODE_BEQ,
MIPS_OPCODE_BNE,
MIPS_OPCODE_BLEZ,
MIPS_OPCODE_BGTZ,
MIPS_OPCODE_ADDI,
MIPS_OPCODE_ADDIU,
MIPS_OPCODE_SLTI,
MIPS_OPCODE_SLTIU,
MIPS_OPCODE_ANDI,
MIPS_OPCODE_ORI,
MIPS_OPCODE_XORI,
MIPS_OPCODE_LUI,
MIPS_OPCODE_COP0, /* class */
MIPS_OPCODE_COP1, /* class */
MIPS_OPCODE_COP2, /* class */
MIPS_OPCODE_COP1X, /* class */
MIPS_OPCODE_BEQL, /* obsolete */
MIPS_OPCODE_BNEL, /* obsolete */
MIPS_OPCODE_BLEZL, /* obsolete*/
MIPS_OPCODE_BGTZL, /* obsolete */
MIPS_OPCODE_SPECIAL2 = (Ob(011100)), /* class */
MIPS_OPCODE_JALX, /* reserved for ASE? */
MIPS_OPCODE_SPECIAL3 = Ob(011111), /* class / release2 */
MIPS_OPCODE_LB,
MIPS_OPCODE_LH,
MIPS_OPCODE_LWL,
MIPS_OPCODE_LW,
MIPS_OPCODE_LBU,
MIPS_OPCODE_LHU,
MIPS_OPCODE_LWR,
MIPS_OPCODE_SB = Ob(101000),
MIPS_OPCODE_SH,
MIPS_OPCODE_SWL,
MIPS_OPCODE_SW,
MIPS_OPCODE_SWR = Ob(101110),
MIPS_OPCODE_CACHE,
MIPS_OPCODE_LL,
MIPS_OPCODE_LWC1,
MIPS_OPCODE_LWC2, /* 3rd party */
MIPS_OPCODE_PREF,
MIPS_OPCODE_LDC1 = Ob(110101),
MIPS_OPCODE_LDC2, /* 3rd party */
MIPS_OPCODE_SC = Ob(111000),
MIPS_OPCODE_SWC1,
MIPS_OPCODE_SWC2, /* 3rd party */
MIPS_OPCODE_SDC1 = Ob(111101),
MIPS_OPCODE_SDC2, /* 3rd party */
MIPS_OPCODE_DADDI = Ob(011000),
MIPS_OPCODE_DADDIU,
MIPS_OPCODE_LDL,// 011010
MIPS_OPCODE_LDR,
MIPS_OPCODE_LLD = Ob(110100),
MIPS_OPCODE_LD = Ob(110111),
MIPS_OPCODE_LWU = Ob(100111),
MIPS_OPCODE_SCD = Ob(111100),
MIPS_OPCODE_SD = Ob(111111),
MIPS_OPCODE_SDL = Ob(101100),
MIPS_OPCODE_SDR
};
enum SPECIAL_function_field_encoding {
MIPS_OPCODE_SLL,
MIPS_OPCODE_MOVCI, /* class */
MIPS_OPCODE_SRL, /* class */
MIPS_OPCODE_SRA,
MIPS_OPCODE_SLLV,
MIPS_OPCODE_SRLV = Ob(000110), /* class */
MIPS_OPCODE_SRAV,
MIPS_OPCODE_JR,
MIPS_OPCODE_JALR,
MIPS_OPCODE_MOVZ,
MIPS_OPCODE_MOVN,
MIPS_OPCODE_SYSCALL,
MIPS_OPCODE_BREAK,
MIPS_OPCODE_SYNC = Ob(001111),
MIPS_OPCODE_MFHI,
MIPS_OPCODE_MTHI,
MIPS_OPCODE_MFLO,
MIPS_OPCODE_MTLO,
MIPS_OPCODE_MULT = Ob(011000),
MIPS_OPCODE_MULTU,
MIPS_OPCODE_DIV,
MIPS_OPCODE_DIVU,
MIPS_OPCODE_ADD = Ob(100000),
MIPS_OPCODE_ADDU,
MIPS_OPCODE_SUB,
MIPS_OPCODE_SUBU,
MIPS_OPCODE_AND,
MIPS_OPCODE_OR,
MIPS_OPCODE_XOR,
MIPS_OPCODE_NOR,
MIPS_OPCODE_SLT = Ob(101010),
MIPS_OPCODE_SLTU,
MIPS_OPCODE_TGE = Ob(110000),
MIPS_OPCODE_TGEU,
MIPS_OPCODE_TLT,
MIPS_OPCODE_TLTU,
MIPS_OPCODE_TEQ,
MIPS_OPCODE_TNE = Ob(110110),
MIPS_OPCODE_DADD = Ob(101100),
MIPS_OPCODE_DADDU,
MIPS_OPCODE_DSUB,
MIPS_OPCODE_DSUBU,
MIPS_OPCODE_DMULT = Ob(011100),
MIPS_OPCODE_DMULTU,
MIPS_OPCODE_DDIV,
MIPS_OPCODE_DDIVU,
MIPS_OPCODE_DSLL = Ob(111000),
MIPS_OPCODE_DSLL32 = Ob(111100),
MIPS_OPCODE_DSLLV = Ob(010100),
MIPS_OPCODE_DSRL = Ob(111010),
MIPS_OPCODE_DSRA,
MIPS_OPCODE_DSRL32 = Ob(111110),
MIPS_OPCODE_DSRA32,
MIPS_OPCODE_DSRLV = Ob(010110),
MIPS_OPCODE_DSRAV
};
enum REGIMM_rt_field_encoding {
MIPS_OPCODE_BLTZ,
MIPS_OPCODE_BGEZ,
MIPS_OPCODE_BLTZL, /* obsolete */
MIPS_OPCODE_BGEZL, /* obsolete */
MIPS_OPCODE_TGEI = Ob(01000),
MIPS_OPCODE_TGEIU,
MIPS_OPCODE_TLTI,
MIPS_OPCODE_TLTIU,
MIPS_OPCODE_TEQI,
MIPS_OPCODE_TNEI = Ob(01110),
MIPS_OPCODE_BLTZAL = Ob(10000),
MIPS_OPCODE_BGEZAL,
MIPS_OPCODE_BLTZALL, /* obsolete */
MIPS_OPCODE_BGEZALL, /* obsolete */
MIPS_OPCODE_SYNCI = Ob(11111) /* release 2 */
};
enum SPECIAL2_function_field_encoding {
MIPS_OPCODE_MADD,
MIPS_OPCODE_MADDU,
MIPS_OPCODE_MUL,
MIPS_OPCODE_MSUB = Ob(000100),
MIPS_OPCODE_MSUBU,
MIPS_OPCODE_CLZ = Ob(100000),
MIPS_OPCODE_CLO,
MIPS_OPCODE_SDBBP = Ob(111111), /* EJTAG */
MIPS_OPCODE_DCLZ = Ob(100100),
MIPS_OPCODE_DCLO
};
/* only for release 2*/
enum SPECIAL3_function_field_encoding {
MIPS_OPCODE_EXT,
MIPS_OPCODE_INS = Ob(000100),
MIPS_OPCODE_BSHFL = Ob(100000), /* class */
MIPS_OPCODE_RDHWR = Ob(111011),
};
enum MOVCI_tf_field_encoding {
MIPS_OPCODE_MOVF,
MIPS_OPCODE_MOVT
};
enum SRL_shiftrotate_field_encoding {
// XXX: _42 was added to allow compiling because MIPS_OPCODE_SRL is already in an other enum.
MIPS_OPCODE_SRL_42,
MIPS_OPCODE_ROTR
};
enum SRLV_shiftrotate_field_ecoding {
// XXX: _42 was added to allow compiling because MIPS_OPCODE_SRL is already in an other enum.
MIPS_OPCODE_SRLV_42,
MIPS_OPCODE_ROTRV
};
enum BSHFL_sa_field_encoding {
MIPS_OPCODE_WSBH = Ob(00010),
MIPS_OPCODE_SEB = Ob(10000),
MIPS_OPCODE_SEH = Ob(11000)
};
enum COP2_func {
MIPS_OPCODE_MFC2,
MIPS_OPCODE_DMFC2,
MIPS_OPCODE_CFC2,
MIPS_OPCODE_MTC2 = Ob(00100),
MIPS_OPCODE_DMTC2,
MIPS_OPCODE_CTC2,
MIPS_OPCODE_BCC2 = Ob(01000)
};
enum COP1X_func {
MIPS_OPCODE_LWXC1 = Ob(000000),
MIPS_OPCODE_LDXC1,
MIPS_OPCODE_LUXC1 = Ob(000101),
MIPS_OPCODE_SWXC1 = Ob(001000),
MIPS_OPCODE_SDXC1,
MIPS_OPCODE_SUXC1 = Ob(001101),
MIPS_OPCODE_PREFX = Ob(001111),
MIPS_OPCODE_ALNV_PS = Ob(011110),
MIPS_OPCODE_MADD_S = Ob(100000),
MIPS_OPCODE_MADD_D,
MIPS_OPCODE_MADD_PS = Ob(100110),
MIPS_OPCODE_MSUB_S = Ob(101000),
MIPS_OPCODE_MSUB_D,
MIPS_OPCODE_MSUB_PS = Ob(101110),
MIPS_OPCODE_NMADD_S = Ob(110000),
MIPS_OPCODE_NMADD_D,
MIPS_OPCODE_NMADD_PS = Ob(110110),
MIPS_OPCODE_NMSUB_S = Ob(111000),
MIPS_OPCODE_NMSUB_D,
MIPS_OPCODE_NMSUB_PS = Ob(111110)
};
enum COP0_func {
MIPS_OPCODE_MFC0 = Ob(0000),
MIPS_OPCODE_DMFC0,
MIPS_OPCODE_TLBWI,
MIPS_OPCODE_MTC0 = Ob(0100),
MIPS_OPCODE_DMTC0,
MIPS_OPCODE_TLBWR,
MIPS_OPCODE_ERET = Ob(011000),
MIPS_OPCODE_TLBP = Ob(001000),
MIPS_OPCODE_TLBR = Ob(000001),
MIPS_OPCODE_DERET = Ob(011111),
MIPS_OPCODE_WAIT
};
enum COP1_func {
MIPS_OPCODE_F_ADD,
MIPS_OPCODE_F_SUB,
MIPS_OPCODE_F_MUL,// = Ob(000010),
MIPS_OPCODE_F_DIV,
MIPS_OPCODE_F_SQRT,
MIPS_OPCODE_ABS,// = Ob(000101),
MIPS_OPCODE_F_MOV, //=Ob(000110)
MIPS_OPCODE_F_NEG,// = Ob(000111),
MIPS_OPCODE_F_ROUND_L,
MIPS_OPCODE_F_TRUNC_L,
MIPS_OPCODE_F_ROUND_W = Ob(001100),
MIPS_OPCODE_F_TRUNC_W,
MIPS_OPCODE_F_CEIL_L = Ob(001010),
MIPS_OPCODE_F_FLOOR_L,
MIPS_OPCODE_F_CEIL_W = Ob(001110),
MIPS_OPCODE_F_FLOOR_W,
MIPS_OPCODE_F_RECIP = Ob(010101),
MIPS_OPCODE_F_RSQRT,
MIPS_OPCODE_F_MOVCF = Ob(010001),
MIPS_OPCODE_F_MOVZ,
MIPS_OPCODE_F_MOVN,
MIPS_OPCODE_F_CVT_S = Ob(100000),
MIPS_OPCODE_F_CVT_D,// = Ob(100001),
MIPS_OPCODE_F_CVT_W = Ob(100100),
MIPS_OPCODE_F_CVT_L,// = Ob(100101),
MIPS_OPCODE_F_CVT_PS_S,
MIPS_OPCODE_F_CVT_S_PL = Ob(101000),
MIPS_OPCODE_F_MFC1 = Ob(00000),
MIPS_OPCODE_F_CFC1 = Ob(00010),
MIPS_OPCODE_F_MTC1 = Ob(00100),
MIPS_OPCODE_F_CTC1 = Ob(00110)
};
enum COP1_fmt {
MIPS_OPCODE_FMT_S = Ob(10000),
MIPS_OPCODE_FMT_D,
MIPS_OPCODE_FMT_W = Ob(10100),
MIPS_OPCODE_FMT_L,// = Ob(10101),
MIPS_OPCODE_FMT_PS// = Ob(10110)
};
enum COP1_cond {
MIPS_OPCODE_COND_F,
MIPS_OPCODE_COND_UN,
MIPS_OPCODE_COND_EQ,
MIPS_OPCODE_COND_UEQ,
MIPS_OPCODE_COND_OLT,
MIPS_OPCODE_COND_ULT,
MIPS_OPCODE_COND_OLE,
MIPS_OPCODE_COND_ULE,
MIPS_OPCODE_COND_SF,
MIPS_OPCODE_COND_NGLE,
MIPS_OPCODE_COND_SEQ,
MIPS_OPCODE_COND_NGL,
MIPS_OPCODE_COND_LT,
MIPS_OPCODE_COND_NGE,
MIPS_OPCODE_COND_LE,
MIPS_OPCODE_COND_NGT
};
/* XXX: privileged and fpu stuff.. not implemented yet*/
/*
enum {} COP0_rs_field_encoding;
enum {} COP0_function_field_encoding_rsCO;
enum {} COP1_rs_field_encoding;
enum {} COP1_function_field_encoding_rsS;
enum {} COP1_function_field_encoding_rsD;
enum{} COP1_function_field_encoding_rsW_or_rsL;
enum {} COP1_function_field_encoding_rsPS;
*/
/*
* mips instructions
* r2 after an instruction means that instruction
* is only available in the MIPS32 release 2 specification
* */
enum e_mips_instr_types
{
/* arithmetics */
ASM_MIPS_ADD,
ASM_MIPS_ADDI,
ASM_MIPS_ADDIU,
ASM_MIPS_ADDU,
ASM_MIPS_CLO,
ASM_MIPS_CLZ,
/* mips64v2 */
ASM_MIPS_DADD,
ASM_MIPS_DADDI,
ASM_MIPS_DADDIU,
ASM_MIPS_DADDU,
ASM_MIPS_DCLO,
ASM_MIPS_DCLZ,
ASM_MIPS_DDIV,
ASM_MIPS_DDIVU,
/* mips64v2 */
ASM_MIPS_DIV,
ASM_MIPS_DIVU,
/* mips64v2 */
ASM_MIPS_DMULT,
ASM_MIPS_DMULTU,
ASM_MIPS_DSUB,
ASM_MIPS_DSUBU,
/* mips64v2 */
ASM_MIPS_MADD,
ASM_MIPS_MADDU,
ASM_MIPS_MSUB,
ASM_MIPS_MSUBU,
ASM_MIPS_MUL,
ASM_MIPS_MULT,
ASM_MIPS_MULTU,
ASM_MIPS_SLT,
ASM_MIPS_SLTI,
ASM_MIPS_SLTIU,
ASM_MIPS_SLTU,
ASM_MIPS_SUB,
ASM_MIPS_SUBU,
ASM_MIPS_SEB, /*r2*/
ASM_MIPS_SEH, /*r2*/
/* branch */
ASM_MIPS_B,
ASM_MIPS_BAL,
ASM_MIPS_BEQ,
ASM_MIPS_BGEZ,
ASM_MIPS_BGEZAL,
ASM_MIPS_BGTZ,
ASM_MIPS_BLEZ,
ASM_MIPS_BLTZ,
ASM_MIPS_BLTZAL,
ASM_MIPS_BNE,
ASM_MIPS_J,
ASM_MIPS_JAL,
ASM_MIPS_JALR,
ASM_MIPS_JR,
ASM_MIPS_JALR_HB,
ASM_MIPS_JR_HB,
/* cpu execution control*/
// ASM_MIPS_EHB, /*r2*/
ASM_MIPS_NOP,
ASM_MIPS_SSNOP,
/* memory */
ASM_MIPS_LB,
ASM_MIPS_LBU,
/* mips64v2 */
ASM_MIPS_LD,
ASM_MIPS_LDL,
ASM_MIPS_LDR,
/* mips64v2 */
ASM_MIPS_LH,
ASM_MIPS_LHU,
ASM_MIPS_LL,
/* mips64v2 */
ASM_MIPS_LLD,
/* mips64v2 */
ASM_MIPS_LW,
ASM_MIPS_LWL,
ASM_MIPS_LWR,
/* mips64v2 */
ASM_MIPS_LWU,
/* mips64v2 */
ASM_MIPS_PREF,
ASM_MIPS_SB,
ASM_MIPS_SC,
/* mips64v2 */
ASM_MIPS_SCD,
ASM_MIPS_SD,
ASM_MIPS_SDL,
ASM_MIPS_SDR,
/* mips64v2 */
ASM_MIPS_SH,
ASM_MIPS_SW,
ASM_MIPS_SWL,
ASM_MIPS_SWR,
ASM_MIPS_SYNC,
ASM_MIPS_SYNCI, /*r2*/
/* logic */
ASM_MIPS_AND,
ASM_MIPS_ANDI,
ASM_MIPS_LUI,
ASM_MIPS_NOR,
ASM_MIPS_OR,
ASM_MIPS_ORI,
ASM_MIPS_XOR,
ASM_MIPS_XORI,
/* insert/extract */
ASM_MIPS_EXT, /*r2*/
ASM_MIPS_INS, /*r2*/
ASM_MIPS_WSBH, /*r2*/
/* cpu move */
ASM_MIPS_MFHI,
ASM_MIPS_MFLO,
ASM_MIPS_MOVF,
ASM_MIPS_MOVN,
ASM_MIPS_MOVT,
ASM_MIPS_MOVZ,
ASM_MIPS_MTHI,
ASM_MIPS_MTLO,
/* shift */
/* mips64v2 */
ASM_MIPS_DSLL,
ASM_MIPS_DSLL32,
ASM_MIPS_DSLLV,
ASM_MIPS_DSRA,
ASM_MIPS_DSRA32,
ASM_MIPS_DSRAV,
ASM_MIPS_DSRL,
ASM_MIPS_DSRL32,
ASM_MIPS_DSRLV,
/* mips64v2 */
ASM_MIPS_SLL,
ASM_MIPS_SLLV,
ASM_MIPS_SRA,
ASM_MIPS_SRAV,
ASM_MIPS_SRL,
ASM_MIPS_SRLV,
ASM_MIPS_RDHWR, /*r2*/
ASM_MIPS_ROTR, /*r2*/
ASM_MIPS_ROTRV, /*r2*/
/* traps */
ASM_MIPS_BREAK,
ASM_MIPS_SYSCALL,
ASM_MIPS_TEQ,
ASM_MIPS_TEQI,
ASM_MIPS_TGE,
ASM_MIPS_TGEI,
ASM_MIPS_TGEIU,
ASM_MIPS_TGEU,
ASM_MIPS_TLT,
ASM_MIPS_TLTI,
ASM_MIPS_TLTIU,
ASM_MIPS_TLTU,
ASM_MIPS_TNE,
ASM_MIPS_TNEI,
/* obsolete branch */
ASM_MIPS_BEQL,
ASM_MIPS_BGEZALL,
ASM_MIPS_BGEZL,
ASM_MIPS_BGTZL,
ASM_MIPS_BLEZL,
ASM_MIPS_BLTZALL,
ASM_MIPS_BLTZL,
ASM_MIPS_BNEL,
/* COP2 Instructions */
ASM_MIPS_BC2F,
ASM_MIPS_BC2T,
ASM_MIPS_COP2,
ASM_MIPS_LDC2,
ASM_MIPS_LWC2,
ASM_MIPS_SDC2,
ASM_MIPS_SWC2,
ASM_MIPS_CFC2,
ASM_MIPS_CTC2,
ASM_MIPS_DMFC2,
ASM_MIPS_DMTC2,
ASM_MIPS_MFC2,
ASM_MIPS_MTC2,
ASM_MIPS_BC2FL,
ASM_MIPS_BC2TL,
/* COP1X Instructions */
ASM_MIPS_LWXC1,
ASM_MIPS_LDXC1,
ASM_MIPS_LUXC1,
ASM_MIPS_SWXC1,
ASM_MIPS_SDXC1,
ASM_MIPS_SUXC1,
ASM_MIPS_PREFX,
ASM_MIPS_ALNV_PS,
ASM_MIPS_MADD_S,
ASM_MIPS_MADD_D,
ASM_MIPS_MADD_PS,
ASM_MIPS_MSUB_S,
ASM_MIPS_MSUB_D,
ASM_MIPS_MSUB_PS,
ASM_MIPS_NMADD_S,
ASM_MIPS_NMADD_D,
ASM_MIPS_NMADD_PS,
ASM_MIPS_NMSUB_S,
ASM_MIPS_NMSUB_D,
ASM_MIPS_NMSUB_PS,
/* Chuj doklikalem to bo sie wkurwilem, jebane gowno - zycie to bagno... */
/* Privileged instructions... */
// ASM_MIPS_CACHE,
ASM_MIPS_MFC0,
ASM_MIPS_DMFC0,
ASM_MIPS_TLBWI,
ASM_MIPS_MTC0,
ASM_MIPS_DMTC0,
ASM_MIPS_TLBWR,
ASM_MIPS_ERET,
ASM_MIPS_TLBP,
ASM_MIPS_TLBR,
ASM_MIPS_WAIT,
/* EJTAG Instructions... */
ASM_MIPS_DERET,
ASM_MIPS_SDBBP,
/*TODO:
* - FPU insns
* */
/* FPU arithmetics */
ASM_MIPS_ABS_S,
ASM_MIPS_ABS_D,
ASM_MIPS_ABS_PS,
ASM_MIPS_ADD_S,
ASM_MIPS_ADD_D,
ASM_MIPS_ADD_PS,
ASM_MIPS_DIV_S,
ASM_MIPS_DIV_D,
ASM_MIPS_MUL_S,
ASM_MIPS_MUL_D,
ASM_MIPS_MUL_PS,
ASM_MIPS_NEG_S,
ASM_MIPS_NEG_D,
ASM_MIPS_NEG_PS,
ASM_MIPS_RECIP_S,
ASM_MIPS_RECIP_D,
ASM_MIPS_RSQRT_S,
ASM_MIPS_RSQRT_D,
ASM_MIPS_SQRT_S,
ASM_MIPS_SQRT_D,
ASM_MIPS_SUB_S,
ASM_MIPS_SUB_D,
ASM_MIPS_SUB_PS,
/* FPU Branch Instructions */
ASM_MIPS_BC1F,
ASM_MIPS_BC1T,
/* FPU Compare Instruction */
// ASM_MIPS_C.cond.fmt,
/* FPU Convert Instructions */
ASM_MIPS_CEIL_L_S,
ASM_MIPS_CEIL_L_D,
ASM_MIPS_CEIL_W_S,
ASM_MIPS_CEIL_W_D,
ASM_MIPS_CVT_D_S,
ASM_MIPS_CVT_D_W,
ASM_MIPS_CVT_D_L,
ASM_MIPS_CVT_L_S,
ASM_MIPS_CVT_L_D,
ASM_MIPS_CVT_PS_S,
ASM_MIPS_CVT_S_D,
ASM_MIPS_CVT_S_W,
ASM_MIPS_CVT_S_L,
ASM_MIPS_CVT_S_PL,
ASM_MIPS_CVT_S_PU,
ASM_MIPS_CVT_W_S,
ASM_MIPS_CVT_W_D,
ASM_MIPS_FLOOR_L_S,
ASM_MIPS_FLOOR_L_D,
ASM_MIPS_FLOOR_W_S,
ASM_MIPS_FLOOR_W_D,
ASM_MIPS_ROUND_L_S,
ASM_MIPS_ROUND_L_D,
ASM_MIPS_ROUND_W_S,
ASM_MIPS_ROUND_W_D,
ASM_MIPS_TRUNC_L_S,
ASM_MIPS_TRUNC_L_D,
ASM_MIPS_TRUNC_W_S,
ASM_MIPS_TRUNC_W_D,
/* FPU Load, Store and Memory Control Instructions */
ASM_MIPS_LDC1,
ASM_MIPS_LWC1,
ASM_MIPS_SDC1,
ASM_MIPS_SWC1,
/* FPU Move Instructions */
ASM_MIPS_CFC1,
ASM_MIPS_CTC1,
ASM_MIPS_MFC1,
ASM_MIPS_MTC1,
ASM_MIPS_MOV_S,
ASM_MIPS_MOV_D,
ASM_MIPS_MOV_PS,
ASM_MIPS_MOVF_S,
ASM_MIPS_MOVF_D,
ASM_MIPS_MOVF_PS,
ASM_MIPS_MOVT_S,
ASM_MIPS_MOVT_D,
ASM_MIPS_MOVT_PS,
ASM_MIPS_MOVN_S,
ASM_MIPS_MOVN_D,
ASM_MIPS_MOVN_PS,
ASM_MIPS_MOVZ_S,
ASM_MIPS_MOVZ_D,
ASM_MIPS_MOVZ_PS,
/* FPU Absolute Branch Instructions */
ASM_MIPS_BC1FL,
ASM_MIPS_BC1TL,
/* BUGFIX */
ASM_MIPS_DMTC1,
ASM_MIPS_DMFC1,
/* C.cond.fmt glupie instrukcje :) */
ASM_MIPS_C_F_S,
ASM_MIPS_C_F_D,
ASM_MIPS_C_F_PS,
ASM_MIPS_C_UN_S,
ASM_MIPS_C_UN_D,
ASM_MIPS_C_UN_PS,
ASM_MIPS_C_EQ_S,
ASM_MIPS_C_EQ_D,
ASM_MIPS_C_EQ_PS,
ASM_MIPS_C_UEQ_S,
ASM_MIPS_C_UEQ_D,
ASM_MIPS_C_UEQ_PS,
ASM_MIPS_C_OLT_S,
ASM_MIPS_C_OLT_D,
ASM_MIPS_C_OLT_PS,
ASM_MIPS_C_ULT_S,
ASM_MIPS_C_ULT_D,
ASM_MIPS_C_ULT_PS,
ASM_MIPS_C_OLE_S,
ASM_MIPS_C_OLE_D,
ASM_MIPS_C_OLE_PS,
ASM_MIPS_C_ULE_S,
ASM_MIPS_C_ULE_D,
ASM_MIPS_C_ULE_PS,
ASM_MIPS_C_SF_S,
ASM_MIPS_C_SF_D,
ASM_MIPS_C_SF_PS,
ASM_MIPS_C_NGLE_S,
ASM_MIPS_C_NGLE_D,
ASM_MIPS_C_NGLE_PS,
ASM_MIPS_C_SEQ_S,
ASM_MIPS_C_SEQ_D,
ASM_MIPS_C_SEQ_PS,
ASM_MIPS_C_NGL_S,
ASM_MIPS_C_NGL_D,
ASM_MIPS_C_NGL_PS,
ASM_MIPS_C_LT_S,
ASM_MIPS_C_LT_D,
ASM_MIPS_C_LT_PS,
ASM_MIPS_C_NGE_S,
ASM_MIPS_C_NGE_D,
ASM_MIPS_C_NGE_PS,
ASM_MIPS_C_LE_S,
ASM_MIPS_C_LE_D,
ASM_MIPS_C_LE_PS,
ASM_MIPS_C_NGT_S,
ASM_MIPS_C_NGT_D,
ASM_MIPS_C_NGT_PS,
ASM_MIPS_BAD
};
typedef int e_mips_register_type;
enum e_mips_register_types
{
ASM_MIPS_REG_ZERO, /* Zero register (always 0)*/
ASM_MIPS_REG_AT, /* Assembler temporary (reserved) */
ASM_MIPS_REG_V0, /* V0-V1 Value returned by subroutine*/
ASM_MIPS_REG_V1,
ASM_MIPS_REG_A0, /* A0-A3 Arguments to subroutine*/
ASM_MIPS_REG_A1,
ASM_MIPS_REG_A2,
ASM_MIPS_REG_A3,
ASM_MIPS_REG_T0, /* T0-T7 Temporary (local variables) */
ASM_MIPS_REG_T1,
ASM_MIPS_REG_T2,
ASM_MIPS_REG_T3,
ASM_MIPS_REG_T4,
ASM_MIPS_REG_T5,
ASM_MIPS_REG_T6,
ASM_MIPS_REG_T7,
ASM_MIPS_REG_S0, /* S0-S7 Saved registers */
ASM_MIPS_REG_S1, /* (preserved across function calls) */
ASM_MIPS_REG_S2,
ASM_MIPS_REG_S3,
ASM_MIPS_REG_S4,
ASM_MIPS_REG_S5,
ASM_MIPS_REG_S6,
ASM_MIPS_REG_S7,
ASM_MIPS_REG_T8, /* T8-T9 Temporary (local variables) */
ASM_MIPS_REG_T9,
ASM_MIPS_REG_K0, /* K0-K1 Kernel registers (reserved for OS) */
ASM_MIPS_REG_K1,
ASM_MIPS_REG_GP, /* Global pointer */
ASM_MIPS_REG_SP, /* Stack pointer */
ASM_MIPS_REG_FP, /* Frame pointer */
ASM_MIPS_REG_RA, /* Return Address */
};
enum e_mips_cp0_register_types
{
ASM_CP0_REG_INDEX = 0,
ASM_CP0_REG_RANDOM = 1,
ASM_CP0_REG_ENTRYLO0 = 2,
ASM_CP0_REG_ENTRYLO1 = 3,
ASM_CP0_REG_CONF = 3,
ASM_CP0_REG_CONTEXT = 4,
ASM_CP0_REG_PAGEMASK = 5,
ASM_CP0_REG_WIRED = 6,
ASM_CP0_REG_INFO = 7,
ASM_CP0_REG_BADVADDR = 8,
ASM_CP0_REG_COUNT = 9,
ASM_CP0_REG_ENTRYHI = 10,
ASM_CP0_REG_COMPARE = 11,
ASM_CP0_REG_STATUS = 12,
ASM_CP0_REG_CAUSE = 13,
ASM_CP0_REG_EPC = 14,
ASM_CP0_REG_PRID = 15,
ASM_CP0_REG_CONFIG = 16,
ASM_CP0_REG_LLADDR = 17,
ASM_CP0_REG_WATCHLO = 18,
ASM_CP0_REG_WATCHHI = 19,
ASM_CP0_REG_XCONTEXT = 20,
ASM_CP0_REG_FRAMEMASK = 21,
ASM_CP0_REG_DIAGNOSTIC = 22,
ASM_CP0_REG_DEBUG = 23,
ASM_CP0_REG_DEPC = 24,
ASM_CP0_REG_PERFORMANCE = 25,
ASM_CP0_REG_ECC = 26,
ASM_CP0_REG_CACHEERR = 27,
ASM_CP0_REG_TAGLO = 28,
ASM_CP0_REG_TAGHI = 29,
ASM_CP0_REG_ERROREPC = 30,
ASM_CP0_REG_DESAVE = 31
};
/**
* operand types
*/
enum e_mips_operand_type
{
ASM_MIPS_OTYPE_NONE,
ASM_MIPS_OTYPE_REGISTER,
ASM_MIPS_OTYPE_IMMEDIATE,
ASM_MIPS_OTYPE_JUMP,
ASM_MIPS_OTYPE_NOOP,
ASM_MIPS_OTYPE_BRANCH,
ASM_MIPS_OTYPE_REGBASE,
ASM_MIPS_OTYPE_LAST
};
#define ASM_MIPS_OTYPE_NUM ASM_MIPS_OTYPE_LAST
/**
* Structure to declare a mips instruction in e_mips_instr table.
*/
struct e_mips_instr
{
const char *mnemonic;
int code;
int index1;
int index2;
int index3;
int (*func_op)(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
};
/**
* Structure to store register in the structure e_mips_register;
*/
struct e_mips_register
{
const char *ext_mnemonic;
const char *mnemonic;
const char *fpu_mnemonic;
e_mips_register_type code;
};
/**
* This enum contains MIPS_OPCODE_ values which
* are not defined upper.
*
*
*/
enum e_fix_compile_errors
{
// MIPS_OPCODE_EHB,
MIPS_OPCODE_NOP = Ob(00000),
MIPS_OPCODE_SSNOP
};
/**
* Those structures arrays are declared in src/arch/mips/tables_mips.c
*/
extern struct e_mips_instr e_mips_instrs[];
extern struct e_mips_register e_mips_registers[];
#endif
/* Operands fetch */
int asm_mips_operand_fetch(asm_operand *op, u_char *opcode, int otype, asm_instr *ins);
/* Operands */
void asm_mips_operand_none(asm_operand *op, u_char *opcode, int otype, asm_instr *ins);
void asm_mips_operand_i(asm_operand *op, u_char *opcode, int otype, asm_instr *ins);
void asm_mips_operand_j(asm_operand *op, u_char *opcode, int otype, asm_instr *ins);
void asm_mips_operand_r(asm_operand *op, u_char *opcode, int otype, asm_instr *ins);
void asm_mips_operand_t(asm_operand *op, u_char *opcode, int otype, asm_instr *ins);
void asm_mips_operand_noop(asm_operand *op, u_char *opcode, int otype, asm_instr *ins);
void asm_mips_operand_branch(asm_operand *op, u_char *opcode, int otype, asm_instr *ins);
void asm_mips_operand_regbase(asm_operand *op, u_char *opcode, int otype, asm_instr *ins);
/* Opcodes */
int asm_mips_add(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_addi(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_addiu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_addu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_and(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_andi(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_b(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bal(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_beq(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_beql(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bgez(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bgezal(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bgezall(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bgezl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bgtz(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bgtzl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_blez(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_blezl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bltz(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bltzal(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bltzall(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bltzl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bne(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bnel(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_break(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_clo(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_clz(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_div(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_divu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
//int asm_mips_ehb(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ext(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ins(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_j(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_jal(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_jalr(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_jalr_hb(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_jr(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_jr_hb(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lb(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lbu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lh(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lhu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ll(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lui(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lw(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lwl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lwr(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_madd(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_maddu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mfhi(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mflo(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movf(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movn(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movt(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movz(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_msub(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_msubu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mthi(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mtlo(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mul(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mult(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_multu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_nop(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_nor(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_or(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ori(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_pref(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_rdhwr(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_rotr(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_rotrv(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sb(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sc(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_seb(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_seh(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sh(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sll(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sllv(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_slt(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_slti(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sltiu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sltu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sra(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_srav(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_srl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_srlv(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ssnop(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sub(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_subu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sw(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_swl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_swr(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sync(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_synci(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_syscall(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_teq(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_teqi(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tge(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tgei(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tgeiu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tgeu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tlt(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tlti(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tltiu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tltu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tne(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tnei(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_wsbh(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_xor(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_xori(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// Hehe... ;-)
int asm_mips_dadd(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_daddi(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_daddiu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_daddu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dclo(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dclz(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ddiv(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ddivu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dmult(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dmultu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dsub(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dsubu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ld(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ldl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ldr(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lld(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lwu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_scd(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sd(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sdl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sdr(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dsll(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dsll32(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dsllv(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dsra(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dsra32(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dsrav(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dsrl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dsrl32(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dsrlv(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// Coprocesor 2 functions...
int asm_mips_bc2f(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bc2t(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cop2(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ldc2(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lwc2(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sdc2(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_swc2(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cfc2(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ctc2(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dmfc2(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dmtc2(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mfc2(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mtc2(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bc2fl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bc2tl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// COP1X functions...
int asm_mips_lwxc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ldxc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_luxc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_swxc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sdxc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_suxc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_prefx(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_alnv_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_madd_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_madd_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_madd_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_msub_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_msub_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_msub_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_nmadd_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_nmadd_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_nmadd_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_nmsub_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_nmsub_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_nmsub_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// Privilaged Instructions - COP0
int asm_mips_mfc0(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dmfc0(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tlbwi(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mtc0(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dmtc0(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tlbwr(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_eret(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tlbp(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_tlbr(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_wait(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_deret(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sdbbp(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// FPU - arithmetic...
int asm_mips_abs_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_abs_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_abs_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_add_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_add_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_add_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_div_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_div_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mul_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mul_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mul_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_neg_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_neg_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_neg_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_recip_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_recip_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_rsqrt_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_rsqrt_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sqrt_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sqrt_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sub_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sub_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sub_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// FPU Branch Instructions
int asm_mips_bc1f(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bc1t(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// FPU Convert Instructions
int asm_mips_ceil_l_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ceil_l_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ceil_w_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ceil_w_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_d_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_d_w(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_d_l(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_l_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_l_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_ps_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_s_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_s_w(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_s_l(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_s_pl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_s_pu(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_w_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_cvt_w_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_floor_l_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_floor_l_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_floor_w_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_floor_w_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_round_l_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_round_l_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_round_w_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_round_w_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_trunc_l_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_trunc_l_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_trunc_w_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_trunc_w_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// FPU Load, Store and Memory Control Instructions
int asm_mips_ldc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_lwc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_sdc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_swc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// FPU Move Instructions
int asm_mips_cfc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_ctc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mfc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mtc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mov_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mov_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_mov_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movcf_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movcf_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movcf_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movn_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movn_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movn_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movz_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movz_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_movz_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// FPU Absolute Branch Instructions
int asm_mips_bc1fl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_bc1tl(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// BUGFIX
int asm_mips_dmtc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_dmfc1(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
// C.cond.fmt glupie instrukcje :)
int asm_mips_c_f_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_f_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_f_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_un_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_un_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_un_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_eq_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_eq_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_eq_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ueq_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ueq_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ueq_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_olt_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_olt_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_olt_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ult_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ult_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ult_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ole_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ole_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ole_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ule_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ule_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ule_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_sf_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_sf_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_sf_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ngle_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ngle_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ngle_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_seq_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_seq_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_seq_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ngl_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ngl_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ngl_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_lt_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_lt_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_lt_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_nge_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_nge_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_nge_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_le_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_le_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_le_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ngt_s(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ngt_d(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
int asm_mips_c_ngt_ps(asm_instr *ins, u_char *buf, u_int len, asm_processor *proc);
<file_sep>/src/config.h
CFLAGS32 += -Wall
CFLAGS64 += -Wall
STATOPT = -static
STATOPT2 = -DUSE_STATIC
EXTRACFLAGS += -g3
BUILDOPT = -m32
LIBASM_ENABLE_IA32 = 1
LIBASM_ENABLE_SPARC = 1
LIBASM_ENABLE_MIPS = 1
LIBASM_ENABLE_ARM = 1
LIBASM_PACKED_HANDLERS = 1
MAKE = make
BUILDOP =
LDASMOPT = -lasm
LPTHREAD = -lpthread
BITS =
SHELL = /bin/bash
<file_sep>/src/libasm/src/arch/ia32/handlers/op_and_eax_iv.c
/*
** $Id: op_and_eax_iv.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_and_eax_iv" opcode="0x25"/>
*/
int op_and_eax_iv(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
new->instr = ASM_AND;
new->len += 1;
new->ptr_instr = opcode;
new->type = ASM_TYPE_ARITH | ASM_TYPE_WRITEFLAG;
new->flagswritten = ASM_FLAG_CF | ASM_FLAG_ZF | ASM_FLAG_PF |
ASM_FLAG_OF | ASM_FLAG_SF;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new,
asm_fixed_pack(0, ASM_OP_BASE, ASM_REG_EAX,
asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16));
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_FIXED, new);
#endif
new->op[0].content = ASM_OP_BASE | ASM_OP_FIXED;
new->op[0].regset = ASM_REGSET_R32;
new->op[0].ptr = opcode;
new->op[0].len = 0;
new->op[0].baser = ASM_REG_EAX;
new->op[0].regset = asm_proc_is_protected(proc) ?
ASM_REGSET_R32 : ASM_REGSET_R16;
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_group16.c
/**
* @file libasm/src/arch/ia32/handlers/i386_group16.c
*
* @ingroup IA32_instrs
* $Id: i386_group16.c 1397 2009-09-13 02:19:08Z may $
*
* Changelog
* 2007-05-29: operand type fixed.
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for instruction group 16, opcode 0x0f 0xae
* @param new Pointer to instruction structure.
* @param opcode Pointer to data to disassemble.
* @param len Length of data to disassemble.
* @param proc Pointer to processor structure.
* @return Length of instruction
*/
int i386_group16(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
if (new->ptr_instr != 0)
new->ptr_instr = opcode - 1;
new->len += 1;
new->instr = ASM_BAD;
modrm = (struct s_modrm *) opcode + 1;
switch(modrm->r)
{
case 0:
new->instr = ASM_FXSAVE;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
break;
case 1:
new->instr = ASM_FXRSTORE;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
break;
case 2:
new->instr = ASM_LDMXCSR;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
break;
case 3:
new->instr = ASM_STMXCSR;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
break;
case 4:
new->instr = ASM_BAD;
break;
case 5:
new->instr = ASM_LFENCE;
break;
case 6:
new->instr = ASM_MFENCE;
break;
case 7:
new->instr = ASM_SFENCE;
///CLFUSH
break;
}
#if LIBASM_USE_OPERAND_VECTOR
#endif
return (new->len);
}
<file_sep>/src/libaspect/include/libaspect-hash.h
/*
* @file libaspect/include/libaspect-hash.h
**
** Started on Fri Jan 24 20:25:42 2003 jfv
** Last update Fri Dec 22 00:14:56 2006 jfv
**
** $Id: libaspect-hash.h 1440 2010-12-29 02:22:03Z may $
**
*/
#ifndef _LIBHASH_H_
#define _LIBHASH_H_ 1
#ifdef __BEOS__
#include <bsd_mem.h>
#endif
#include "libaspect-list.h"
/**
* @brief Hash table
*/
typedef struct s_hash
{
listent_t *ent;
int size;
int elmnbr;
u_int type;
u_char linearity;
char *name;
} hash_t;
/**
* @brief The hash table of hash tables is accessible to the public
*/
extern hash_t *hash_hash;
/**
* @brief The hash table of list is accessible to the public
*/
extern hash_t *hash_lists;
/* hash.c */
int hash_init(hash_t*, char*, int, u_int); /* Allocate the table */
hash_t *hash_find(char *name); /* Find a hash table */
int hash_register(hash_t *h, char *name); /* Register a hash table */
hash_t *hash_empty(char *name); /* Empty the hash table */
void hash_destroy(hash_t *h); /* Free the table */
int hash_add(hash_t*, char*, void *); /* Add an entry */
int hash_del(hash_t *h, char *key); /* Delete an entry */
void *hash_get(hash_t *h, char *key); /* Get data from key */
void *hash_select(hash_t *h, char *key); /* Get an entry pointer */
listent_t *hash_get_head(hash_t *h, char *b); /* Get a list head */
listent_t *hash_get_ent(hash_t *h, char *key); /* Get an entry metadata */
void hash_print(hash_t *h); /* Print the hash table */
char** hash_get_keys(hash_t *h, int* n); /* Create array of keys */
void hash_free_keys(char **keys); /* Free keys */
int hash_apply(hash_t *h, void *ptr,
int (*f)(listent_t *e, void *p)); /* Apply function */
int hash_merge(hash_t *dst, hash_t *src); /* Fuse hashes */
int hash_inter(hash_t *dst, hash_t *src); /* intersect hashes */
int hash_unmerge(hash_t *dst, hash_t *src); /* Quotient hashes */
int hash_size(hash_t *hash); /* Return the elm nbr */
void* hash_get_one(hash_t *hash); /* Get any object */
void* hash_get_single(hash_t *hash); /* Get _the_ only object */
int hash_set(hash_t *h, char *key, void *data); /* Change meta data for a key */
u_char hash_linearity_get(hash_t *h); /* Get hash table linearity */
void hash_linearity_set(hash_t *h, u_char v); /* Set hash table linearity */
#endif /* _LIBHASH_H_ */
<file_sep>/src/libasm/src/arch/ia32/handlers/i386_xadd.c
/**
* @file libasm/src/arch/ia32/handlers/i386_xadd.c
*
* @ingroup IA32_instrs
* $Id: i386_xadd.c 1397 2009-09-13 02:19:08Z may $
*/
#include <libasm.h>
#include <libasm-int.h>
/**
* Handler for the opcode FF C1
<i386 func="" opcode="0xc1"/>
*/
int i386_xadd(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode;
new->instr = ASM_XADD;
new->len += 1;
#if LIBASM_USE_OPERAND_VECTOR
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_ENCODED, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_GENERAL, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode + 1, ASM_OTYPE_GENERAL, new);
#endif
#else
new->op[0].type = ASM_OTYPE_GENERAL;
new->op[1].type = ASM_OTYPE_GENERAL;
operand_rmv_rv(new, opcode + 1, len - 1, proc);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_movsd.c
/*
** $Id: op_movsd.c 1311 2009-01-14 20:36:48Z may $
**
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_movsd" opcode="0xa5"/>
*/
int op_movsd(asm_instr *new, u_char *opcode, u_int len, asm_processor *proc)
{
new->len += 1;
new->ptr_instr = opcode;
if (asm_proc_opsize(proc))
new->instr = ASM_MOVSW;
else
new->instr = ASM_MOVSD;
new->type = ASM_TYPE_LOAD | ASM_TYPE_STORE | ASM_TYPE_ASSIGN;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_YDEST, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_YDEST, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_XSRC, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode, ASM_OTYPE_XSRC, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/ia32/handlers/op_mov_subreg_ib.c
/**
* @file libasm/src/arch/ia32/handlers/op_mov_subreg_ib.c
*
* @ingroup IA32_instrs
* $Id: op_mov_subreg_ib.c 1397 2009-09-13 02:19:08Z may $
*
*/
#include <libasm.h>
#include <libasm-int.h>
/*
<instruction func="op_mov_subreg_ib" opcode="0xb0"/>
<instruction func="op_mov_subreg_ib" opcode="0xb1"/>
<instruction func="op_mov_subreg_ib" opcode="0xb2"/>
<instruction func="op_mov_subreg_ib" opcode="0xb3"/>
<instruction func="op_mov_subreg_ib" opcode="0xb4"/>
<instruction func="op_mov_subreg_ib" opcode="0xb5"/>
<instruction func="op_mov_subreg_ib" opcode="0xb6"/>
<instruction func="op_mov_subreg_ib" opcode="0xb7"/>
*/
int op_mov_subreg_ib(asm_instr *new, u_char *opcode, u_int len,
asm_processor *proc)
{
struct s_modrm *modrm;
modrm = (struct s_modrm *) opcode;
new->ptr_instr = opcode;
new->type = ASM_TYPE_ASSIGN;
new->instr = ASM_MOV;
new->len += 1;
#if WIP
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_OPMOD, new, 0);
#else
new->len += asm_operand_fetch(&new->op[0], opcode, ASM_OTYPE_OPMOD, new);
#endif
#if WIP
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATEBYTE, new, 0);
#else
new->len += asm_operand_fetch(&new->op[1], opcode + 1, ASM_OTYPE_IMMEDIATEBYTE, new);
#endif
return (new->len);
}
<file_sep>/src/libasm/src/arch/sparc/handlers/asm_sparc_illtrap.c
/**
* @file libasm/src/arch/sparc/handlers/asm_sparc_illtrap.c
** @ingroup SPARC_instrs
*/
/*
**
** $Id: asm_sparc_illtrap.c 1397 2009-09-13 02:19:08Z may $
**
*/
#include "libasm.h"
int
asm_sparc_illtrap(asm_instr * ins, u_char * buf, u_int len,
asm_processor * proc)
{
struct s_decode_branch opcode;
sparc_convert_branch(&opcode, buf);
ins->type = ASM_TYPE_INT | ASM_TYPE_STOP;
ins->instr = ASM_SP_ILLTRAP;
ins->nb_op = 1;
ins->op[0].imm = opcode.immediate;
asm_sparc_op_fetch(&ins->op[0], buf, ASM_SP_OTYPE_IMMEDIATE, ins);
return 4;
}
|
4429767c0a2c52c115c25d70fd467fe6dfe60f12
|
[
"Markdown",
"C",
"Makefile"
] | 168
|
C
|
snpusr/sigtool
|
2c544793ee2f722ea017cdf4180279d1a0fb8348
|
6709bfd71869fd27f578e5298f8726fe348d5e00
|
refs/heads/master
|
<file_sep>$(document).ready(function() {
var socket = io.connect(url);
socket_init(socket);
var text = getText();
var wordArray = text.split(" ");
var textIndex = 0;
$("#text").html(bold(wordArray, textIndex));
$("#inputText").keyup(function() {
var currWord = wordArray[textIndex];
var inputLength = ($(this).val()).length;
if (($(this).val()) == (currWord + " ")) {
textIndex = textIndex + 1;
send_word(socket, textIndex);
$(this).val("");
$("#text").html(bold(wordArray, textIndex));
if (textIndex == wordArray.length) {
alert("DONE!");
}
}
});
$("#add-user").click(function() {
$("#add-user-wrapper").hide();
// this will show the current user table.
register_user(socket, $("#user-name").val());
// show table and ready button
$("#current-user-wrapper").show();
});
$("#join-game").click(function() {
$("#join-game").hide();
start_game(socket);
});
});<file_sep>Typing-Contest
==============
A multiplayer typing game using Node and socket.io.
### Contributors
- <NAME> [http://qimingfang.com](http://qimingfang.com)
- <NAME>
### How to Run
- Clone the repository
- sudo npm install
- To run locally: node server.js
- To run in a prod environment, modify ARG_PROD argument in server.js to point to your own instance.
- Default port is 5000
- Navigate to {{ node_url }}:5000
### What currently does not work?
- Can't support multiple games
- Can't reset games (once you join, you join forever)
- Fetch text dynamically (the text is populated as hard coded string)
<file_sep>$(document).ready(function() {
var p = "http://192.168.0.17";
var l = "http://localhost";
var socket = io.connect(l);
socket_init(socket);
// this would be fetched in some other way. For now it is hard coded.
var text = "The university is broadly organized into seven undergraduate colleges and seven graduate divisions at its main Ithaca campus, with each college and division defining its own admission standards and academic programs in near autonomy. The university also administers two satellite medical campuses, one in New York City and one in Education City, Qatar. Cornell is one of two private land grant universities.";
var wordArray = text.split(" ");
var textIndex = 0;
$("#text").html(bold(wordArray, textIndex));
$("#inputText").keyup(function() {
var currWord = wordArray[textIndex];
var inputLength = ($(this).val()).length;
if (($(this).val()) == (currWord + " ")) {
textIndex = textIndex + 1;
send_word(socket, textIndex);
$(this).val("");
$("#text").html(bold(wordArray, textIndex));
if (textIndex == wordArray.length) {
alert("DONE!");
}
}
});
$("#add-user").click(function() {
console.log("whatsup?");
$("#add-user-wrapper").hide();
// enter preparation screen
$("#current-user-wrapper").show();
console.log("whatsup");
console.log($("#current-user-wrapper").attr("display"));
// this will show the current user table.
register_user(socket, $("#user-name").val());
});
$("#join-game").click(function() {
$("#checkmark_" + socket.socket.sessionid).html("<td><span class='glyphicon glyphicon-ok'></span>");
$("#join-game").hide();
start_game(socket);
})
});<file_sep>var connectCounter = 0;
var users = [];
// num players ready to play game
var ready = 0;
/**
* Initializes the server socket.io sockets behavior
* @param {Object} io
*/
function init_sockets(io) {
io.sockets.on('connection', function(socket) {
connectCounter++;
socket.on('disconnect', function() {
connectCounter--;
});
socket.on('send_word', function(data) {
var data = { id:socket.id, stats:data.stats };
io.sockets.emit('update', data);
});
socket.on('new_user', function(data) {
var data = { id:socket.id, name:data.name };
users.push(data);
io.sockets.emit('refresh', users);
});
socket.on('start_game', function(data) {
ready++;
io.sockets.emit('user_ready', { socket:data.socket });
if (ready == connectCounter) {
ready = 0;
io.sockets.emit('start', {});
}
});
socket.on('disconnect', function() {
console.log("disc");
});
});
}
/*
* Public functions
*/
module.exports.init_sockets = init_sockets;
<file_sep>function bold(wordArray, textIndex) {
var textWithBold = "";
for (var i = 0; i < wordArray.length; i++) {
var currWord = wordArray[i];
if (i == textIndex) {
currWord = "<b>".concat(currWord).concat("</b>");
}
textWithBold = textWithBold.concat(currWord) + " ";
}
return textWithBold;
}
function checkmark() {
return "<td><span class='glyphicon glyphicon-ok'></span>";
}
function getText() {
return "The university is broadly organized into seven undergraduate colleges and seven graduate divisions at its main Ithaca campus, with each college and division defining its own admission standards and academic programs in near autonomy. The university also administers two satellite medical campuses, one in New York City and one in Education City, Qatar. Cornell is one of two private land grant universities.";
}
/**
* Initialize the socket event handlers.
*/
function socket_init(socket) {
socket.on('refresh', function(users) {
// TODO(qiming): don't the entire table.
$("#user_table").html("<tr><td> User </td><td width='50'> Ready </td><td> Count </td></tr>");
for (var i in users) {
var data = users[i];
var new_user = "<tr>";
new_user += "<td>" + data.name + "</td>";
new_user += "<td id='checkmark_" + data.id + "'></td>";
new_user += "<td id='stats_" + data.id + "'>0</td>"; // starts with 0
new_user += "</tr>";
$("#user_table").append(new_user);
}
});
socket.on('user_ready', function(data) {
$("#checkmark_" + data.socket).html(checkmark());
});
// all users clicked start game.
socket.on('start', function(data) {
timer(5, function() {
$("#join-game").hide();
$("#typing-box-wrapper").show();
});
});
// new user joins.
socket.on('register', function(data) {
$("#join-game").attr("name", socket.socket.sessionid);
});
// users' word index counters change.
socket.on('update', function(data) {
$("#stats_" + data.id).html(data.stats);
});
}
/**
* When the user finishes typing a word
*
* @param socket:socket.io socket
* @completed_word_index:int the index of the word that the user
* just completed
*/
function send_word(socket, completed_word_index) {
socket.emit('send_word', { stats : completed_word_index });
}
/**
* Registration function for when the user intializes the game
*
* @param name:string name of the user
* @param callback:function()
*/
function register_user(socket, name) {
socket.emit('new_user', { name: name });
}
/**
* When the user clicks on the start game button to start a new game
*
* @param callback:function()
*/
function start_game(socket) {
socket.emit('start_game', { socket:socket.socket.sessionid });
}
/**
* A countdown timer that executes {@code callback} after
* {@code count} number of seconds
*/
function timer(count, callback) {
var counter = setInterval(timer, 1000);
function timer() {
$("#timer").html(count);
if (count <= 0) {
$("#timer").html("Begin!");
clearInterval(counter);
callback();
}
count--;
}
}
|
f24673eaffdae8a36664aaf2c70ce13e04beb778
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
qimingfang/typing-contest
|
5fa1537e6de3d4847a9bcfee6aad36f46fbd1c19
|
32a720a406d84d4fbed009204cba1bf0f983ed1e
|
refs/heads/main
|
<repo_name>Hrincon1055/react-frontend-asesoftware<file_sep>/src/App.js
import React, { useState } from "react";
import { Container, Col, Row, Navbar } from "react-bootstrap";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
// Mis componentes
import FormClient from "./components/FormClient";
import Clients from "./components/Clients";
// Inicio
function App() {
// state
const [loading, setLoading] = useState(false);
const [editC, seteditC] = useState(null);
// returns
return (
<>
<Navbar bg="dark" variant="dark">
<Container>
<Navbar.Brand href="#home">React Asesoftware</Navbar.Brand>
</Container>
</Navbar>
<br />
<Container>
<Row>
<Col sm={4}>
<FormClient
loading={loading}
setLoading={setLoading}
editC={editC}
seteditC={seteditC}
/>
</Col>
<Col sm={8}>
<Clients
loading={loading}
setLoading={setLoading}
editC={editC}
seteditC={seteditC}
/>
</Col>
</Row>
</Container>
<ToastContainer />
</>
);
}
export default App;
|
e7defd9df0cfde0c10ed652be510cd12a284ddc6
|
[
"JavaScript"
] | 1
|
JavaScript
|
Hrincon1055/react-frontend-asesoftware
|
650683b95e32cf0f4139949bb3e6195d70046520
|
06633ed7ef45e248ce0c397910249379c274b7c8
|
refs/heads/master
|
<repo_name>gustavoJimenezz/claseDeingreso<file_sep>/5-InstruccionWhile/jsIteraciones (10).js
function mostrar()
{
var numnegativos=0;
var numpositivos=0;
var cpostivos=0;
var cnegativos=0;
var cceros=0;
var numerospares=0;
var respuesta='si';
var numero;
//var diferencia=numnegativos-numpositivos
//declarar contadores y variables
while (respuesta=="si") {
numero=parseInt(prompt("ingrese numero"))
if (numero<1) {
numnegativos=numnegativos+numero
cnegativos++}
else if (numero>1){
numpositivos=numpositivos+numero
cpostivos++;
}
else
{cceros++;}
if(numero%2==0)
{numerospares++;}
respuesta=prompt("desea seguir?")
}
var diferencia=numnegativos+numpositivos
alert("1_suma de negativos "+numnegativos+
"\n2_suma de positivos " +numpositivos+
"\n3_cantidad de positivos "+cpostivos+
"\n4_cantidad de negativos "+cnegativos+
"\n5_cantidad de numeros pares "+numerospares+
"\n6_cantidad de ceros "+cceros+
"\n7_promedio de positivos "+(numpositivos/cpostivos)+
"\n9_promedio de negativos "+(numnegativos/cnegativos)+
"\n10_diferenciaa entre positivos y negativos "+diferencia)
}
//FIN DE LA FUNCIÓN
//"cantidad de positivos //"+cpostivos+<br></br>+
//"cantidad de negativos //"+cnegativos+<br></br>+
//"cantidad de numeros pares//"+numerospares+<br></br>+
//"promedio de positivos //"+(numpositivos/cpostivos)+<br></br>+
//"promedio de negativos //"+(numnegativos/cnegativos)+<br></br>+
//"diferenciaa entre positivos y negativos"+diferencia);<file_sep>/5-InstruccionWhile/jsIteraciones (9).js
function mostrar()
{
var numero=0;
var contador=0;
var nummax;
var nummin;
var respuesta='si';
while (respuesta=="si") {
numero=parseInt(prompt("ingrese numero"))
if (contador==0) {
nummax=numero
nummin=numero
} else {
if (numero>nummax) {
nummax=numero
} else {
if(numero<nummin)
nummin=numero
}
}
respuesta=prompt("desea continuar?")
contador++
}
document.getElementById("maximo").value=nummax
document.getElementById("minimo").value=nummin
}
<file_sep>/2-InstruccionIf/jsInstruccionIF (4).js
function mostrar()
{
//tomo la edad
var edad=document.getElementById("edad").value
if (edad>12 && edad<=17) {
alert("la persona es adolescente")
}
}//FIN DE LA FUNCIÓn<file_sep>/2-InstruccionIf/jsInstruccionIF (10).js
function mostrar()
{
//Genero el número RANDOM entre 1 y 10
var ramdom=Math.floor(Math.random() * 10) + 1;
if (ramdom<4) {
alert("vamos,la proxima se puede")
} else {
if (ramdom>8) {
alert("EXELENTE")
} else {
alert("APROBO")
}
}
}//FIN DE LA FUNCIÓN<file_sep>/1-EntradaSalida/jsEntradaSalida-9.js
/*Debemos lograr tomar el importe por ID ,
transformarlo a entero (parseInt), luego
mostrar el importe con un aumento del 10 %
en el cuadro de texto "RESULTADO".*/
function mostrarAumento()
{
var idsueldo= document.getElementById("sueldo").value
var idsueldo=parseInt(idsueldo)
// var resultado= idsueldo*10
// var resultadodos=resultado/100
//var total=idsueldo+resultadodos
//document.getElementById("resultado").value=total
idsueldo=idsueldo*0.1+idsueldo
//var resultadodos=idsueldo+resultado
document.getElementById("resultado").value=idsueldo//resultadodos
}
<file_sep>/5-InstruccionWhile/jsIteraciones (2).js
function mostrar()
{
var numero=10;
while (numero>=1)
{
alert(numero)
numero--;
}
}//FIN DE LA FUNCIÓN<file_sep>/6-InstruccionFor/jsIteracionesFor (3).js
function mostrar()
{
var repetciones = prompt("ingrese el número de repeticiones");
for (var numero=1; numero<=repetciones; numero ++) {
alert("Hola UTN FRA")
}
}//FIN DE LA FUNCIÓN<file_sep>/8-TPs/jsFerreteFacturacion.js
/*1. Para el departamento de facturación:
A. Ingresar tres precios de productos y mostrar la suma de los mismos.
B. Ingresar tres precios de productos y mostrar el promedio de los mismos.
C. ingresar tres precios de productos y mostrar precio final (más IVA 21%).
*/
//function name() {
//var uno=parseInt(document.getElementById("PrecioUno").value);
//var dos=parseInt(document.getElementById("PrecioDos").value);
//var tres=parseInt(document.getElementById("PrecioTres").value);
//}
function Sumar ()
{ var uno=parseInt(document.getElementById("PrecioUno").value);
var dos=parseInt(document.getElementById("PrecioDos").value);
var tres=parseInt(document.getElementById("PrecioTres").value);
alert(uno+dos+tres)
}
function Promedio ()
{
var uno=parseInt(document.getElementById("PrecioUno").value);
var dos=parseInt(document.getElementById("PrecioDos").value);
var tres=parseInt(document.getElementById("PrecioTres").value);
alert(uno+dos+tres/3);
}
function PrecioFinal ()
{
var uno=parseInt(document.getElementById("PrecioUno").value);
var dos=parseInt(document.getElementById("PrecioDos").value);
var tres=parseInt(document.getElementById("PrecioTres").value);
var total=uno+dos+tres
alert((total*0.21)+total)
}<file_sep>/6-InstruccionFor/jsIteracionesFor (4).js
function mostrar()
{
// pausa=document.getElementById("mostrar").value
var contador;
for(contador=0;contador<6;contador+1)
{
alert(contador );
if(contador==3)
{
break;
}
}//FIN DE LA FUNCIÓN<file_sep>/1-EntradaSalida/jsEntradaSalida-7.js
/*Debemos lograr tomar Los numeros por ID ,
transformarlos a enteros (parseInt),realizar la operación correcta y
mostrar el resulto por medio de "ALERT"
ej.: "la Resta es 750"*/
function sumar()
{
var idUno= document.getElementById("numeroUno").value
var idDos= document.getElementById("numeroDos").value
idUno= parseInt(idUno)
idDos= parseInt(idDos)
var sum=idUno+idDos
alert("la suma es "+ sum)
}
function restar()
{
var idUno= document.getElementById("numeroUno").value
var idDos= document.getElementById("numeroDos").value
idUno= parseInt(idUno)
idDos= parseInt(idDos)
var res=idUno-idDos
alert("la resta es "+ res)
}
function multiplicar()
{
var idUno= document.getElementById("numeroUno").value
var idDos= document.getElementById("numeroDos").value
idUno= parseInt(idUno)
idDos= parseInt(idDos)
var mul=idUno*idDos
alert("la suma es "+ mul)
}
function dividir()
{
var idUno= document.getElementById("numeroUno").value
var idDos= document.getElementById("numeroDos").value
idUno= parseInt(idUno)
idDos= parseInt(idDos)
var div=idUno/idDos
alert("la suma es "+ div)
}
<file_sep>/2-InstruccionIf/jsInstruccionIF (5).js
function mostrar()
{
//tomo la edad
var edad=document.getElementById("edad").value
if (!(edad>12 && edad<=17)) {
alert("no es adolescente")
}
}//FIN DE LA FUNCIÓN<file_sep>/1-EntradaSalida/jsEntradaSalida-8.js
/*Debemos lograr tomar Los numeros por ID ,
transformarlos a enteros (parseInt),realizar la operación correcta y
mostrar el resto entre el dividendo y el divisor.
ej.: "El resto es 0 ."*/
function SacarResto()
{
var idUno= document.getElementById("numeroDividendo").value
var idDos= document.getElementById("numeroDivisor").value
idUno= parseInt(idUno)
idDos= parseInt(idDos)
var numresto= idUno%idDos
alert("el resto es "+ numresto)
}
<file_sep>/5-InstruccionWhile/jsIteraciones (6).js
function mostrar()
{
var contador=0;
var calculo;
var acumulador=0;
//contador=prompt("colocar un numero")
while (contador<5)
{
calculo=parseInt(prompt("ingrese valor"))
//calculo=parseInt(calculo)
acumulador=acumulador+calculo;
contador++;
}
document.getElementById('suma').value=acumulador;
document.getElementById('promedio').value=acumulador/5;
}//FIN DE LA FUNCIÓN<file_sep>/5-InstruccionWhile/jsIteraciones (8).js
function mostrar()
{
var positivo=0;
var negativo=1;
var numeros;
var respuesta="si";
while (respuesta=="si")
{numeros=parseInt(prompt("ingrese valor"))
while (isNaN(numeros)) {
numeros=parseInt(prompt("Error: ingrese numeros"))
}
if (numeros<0) {
negativo=negativos*numeros
} else {
positivo=numeros
positivo=positivo+numeros
}
//acumulador=acumulador+numeros;
//contador++;
respuesta=prompt("desea continuar")
}
document.getElementById('suma').value=negativo;
document.getElementById('producto').value=positivo;
}//FIN DE LA FUNCIÓN-
|
674d58c572dc9185a5ebac271cb0948c69c431a4
|
[
"JavaScript"
] | 14
|
JavaScript
|
gustavoJimenezz/claseDeingreso
|
24ce2096d3a2cf266aeac9eb8ef85f6558d9b5c8
|
eb3cd4b971537685bad58a92f0d6e662f92fc19a
|
refs/heads/master
|
<file_sep>jQuery(document).ready(function () {
jQuery("#btnQuery").click(function(){
var code = jQuery('#txt_code').val();
jQuery('#result_info').text("正在查询中,请稍等...");
jQuery('#result_ico').attr("src", "images/code_warring.png");
if (code.length <= 0) {
jQuery("#txt_code").focus();
return false;
}
if (code.length < 10) {
jQuery('#result_info').text("您所输入的防伪编码(" + code + ")无效,请核实.");
jQuery('#result_ico').attr("src", "images/code_warring.png");
jQuery('#resultModal').modal({
backdrop: true,
keyboard: true,
show: true
})
return false;
}
var reg = new RegExp("^[0-9]*$");
if (!reg.test(code)) {
jQuery('#result_info').text("您所输入的防伪编码(" + code + ")无效,请核实.");
jQuery('#result_ico').attr("src", "images/code_warring.png");
jQuery('#resultModal').modal({
backdrop: true,
keyboard: true,
show: true
})
return false;
}
jQuery.getJSON( "http://www.400-315.com/fwqueryjson.ashx?callback=?",
{ FwCode: code },
function(data) {
jQuery('#result_info').text(data.QueryResult);
if(data.CodeState==1){
jQuery('#result_ico').attr("src", "images/code_true.png");}
else{
jQuery('#result_ico').attr("src", "images/code_false.png");
}
jQuery('#resultModal').modal({
backdrop: "static",
keyboard: false,
show: true
})
});
});
});
|
4f231e503f131d5e6f6f2a51d56662da5d10c878
|
[
"JavaScript"
] | 1
|
JavaScript
|
iamludar/china12-315_net
|
1c86ff007fe8293da17bae8219e6ef11317dafdb
|
d16c621cf2fa62729c0671df5fc2daae5796ea8b
|
refs/heads/main
|
<repo_name>WDev2021/mit-xpro-bad-bank<file_sep>/src/pages/CreateAccount.js
import { useContext } from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import UserContext from '../UserContext.js';
function CreateAccount() {
const context = useContext(UserContext);
const formikProps = {
initialValues: {
username: '',
password: ''
},
validate: values => {
const errors = {};
if (!values.username) {
errors.username = 'Required';
}
if (!values.password) {
errors.password = 'Required';
}
return errors;
},
onSubmit: (values, { resetForm }) => {
context.users.push({
username: values.username,
password: <PASSWORD>,
balance: 0
});
resetForm();
alert(`Account created with username: ${values.username}`);
}
};
return (
<div className='content'>
<h2>Create Account</h2>
<Formik {...formikProps}>
<Form>
<div className='form-group'>
<label htmlFor='username'>Username</label>
<Field className='form-control' id='username' name='username' placeholder='acrist' />
<ErrorMessage className='error' name='username' component='div' />
</div>
<div className='form-group'>
<label htmlFor='password'>Password</label>
<Field className='form-control' id='password' name='password' placeholder='****' type='password' />
<ErrorMessage className='error' name='password' component='div' />
</div>
<br/>
<button type='submit' className='btn btn-primary'>Create</button>
</Form>
</Formik>
</div>
);
}
export default CreateAccount;<file_sep>/src/pages/AllData.js
import { useContext } from 'react';
import UserContext from '../UserContext.js';
function AllData() {
const context = useContext(UserContext);
return (
<div className='content'>
<h2>All Data</h2>
<div className='json'>
{JSON.stringify(context, null, 2)}
</div>
</div>
);
}
export default AllData;<file_sep>/src/App.js
import { Route, HashRouter } from 'react-router-dom';
import UserContext from './UserContext.js';
import NavBar from './NavBar.js';
import Home from './pages/Home.js';
import Login from './pages/Login.js';
import CreateAccount from './pages/CreateAccount.js';
import AllData from './pages/AllData.js';
function App() {
return (
<HashRouter>
<NavBar />
<UserContext.Provider value={{
users: [
{ username: 'acrist', password: '<PASSWORD>', balance: '10' }
]
}}>
<Route path='/' exact component={Home} />
<Route path='/create-account' component={CreateAccount} />
<Route path='/login' component={Login} />
<Route path='/all-data' component={AllData} />
</UserContext.Provider>
</HashRouter>
);
}
export default App;
<file_sep>/src/pages/Deposit.js
function Deposit() {
return (
<div className='content'>
<h2>Deposit</h2>
</div>
);
}
export default Deposit;<file_sep>/src/NavBar.js
import * as Bootstrap from 'react-bootstrap';
function NavBar() {
return (
<Bootstrap.Navbar bg="dark" variant="dark">
<Bootstrap.Container>
<Bootstrap.Navbar.Brand href="/#">Navbar</Bootstrap.Navbar.Brand>
<Bootstrap.Nav className="me-auto">
<Bootstrap.Nav.Link href='/#'>Home</Bootstrap.Nav.Link>
<Bootstrap.Nav.Link href='/#/create-account'>Create Account</Bootstrap.Nav.Link>
<Bootstrap.Nav.Link href='/#/login'>Login</Bootstrap.Nav.Link>
<Bootstrap.Nav.Link href='/#/all-data'>All Data</Bootstrap.Nav.Link>
</Bootstrap.Nav>
</Bootstrap.Container>
</Bootstrap.Navbar>
);
}
export default NavBar;
|
d5375361fbdbdeb7eaf9e512f8a7b41881ef9835
|
[
"JavaScript"
] | 5
|
JavaScript
|
WDev2021/mit-xpro-bad-bank
|
db00631ca2a5c95ef27d1d378f9cb94f52aa80ff
|
f9324892b76374cc87be73ea4c0d318263320379
|
refs/heads/master
|
<file_sep>/* ========================================================================= */
/* ==== Floor ============================================================== */
function cw_createFloor() {
var last_tile = null;
var tile_position = new b2Vec2(-5,0);
cw_floorTiles = new Array();
Math.seedrandom(floorseed);
// keep old impossible tracks if not using mutable floors
// if path is mutable over races, create smoother tracks
var roughness = (mutable_floor ? 1.38 : 1.725);
for(var k = 0; k < maxFloorTiles; k++) {
var angle = (Math.random()*3 - 1.5) * roughness*k/maxFloorTiles;
// when approaching the upper or lower edge of the minimap (h=35 or -35),
// bias the angle by 5% to lean towards h=0, to avoid the terrain going off-screen
var angle_bias = (tile_position.y/35);
angle -= angle_bias*angle_bias*sign(angle_bias)/20;
last_tile = cw_createFloorTile(tile_position, angle);
cw_floorTiles.push(last_tile);
last_fixture = last_tile.GetFixtureList();
last_world_coords = last_tile.GetWorldPoint(last_fixture.GetShape().m_vertices[3]);
tile_position = last_world_coords;
}
}
function sign(x) {
x = +x // convert to a number
if (x === 0 || isNaN(x))
return x
return x > 0 ? 1 : -1
}
function cw_createFloorTile(position, angle) {
// Cap the angle to +/-(PI/2) to avoid impossible slopes
angle = Math.max(Math.min(angle, 1.471), -Math.PI/2);
body_def = new b2BodyDef();
body_def.position.Set(position.x, position.y);
var body = world.CreateBody(body_def);
fix_def = new b2FixtureDef();
fix_def.shape = new b2PolygonShape();
fix_def.friction = 0.5;
var coords = new Array();
coords.push(new b2Vec2(0,0));
coords.push(new b2Vec2(0,-groundPieceHeight));
coords.push(new b2Vec2(groundPieceWidth,-groundPieceHeight));
coords.push(new b2Vec2(groundPieceWidth,0));
var center = new b2Vec2(0,0);
var newcoords = cw_rotateFloorTile(coords, center, angle);
fix_def.shape.SetAsArray(newcoords);
body.CreateFixture(fix_def);
return body;
}
function cw_rotateFloorTile(coords, center, angle) {
var newcoords = new Array();
for(var k = 0; k < coords.length; k++) {
nc = new Object();
nc.x = Math.cos(angle)*(coords[k].x - center.x) - Math.sin(angle)*(coords[k].y - center.y) + center.x;
nc.y = Math.sin(angle)*(coords[k].x - center.x) + Math.cos(angle)*(coords[k].y - center.y) + center.y;
newcoords.push(nc);
}
return newcoords;
}
/* ==== END Floor ========================================================== */
/* ========================================================================= */
function cw_drawFloor() {
ctx.strokeStyle = "#000";
ctx.fillStyle = "#666";
ctx.lineWidth = 1/zoom;
ctx.beginPath();
outer_loop:
for(var k = Math.max(0,last_drawn_tile-20); k < cw_floorTiles.length; k++) {
var b = cw_floorTiles[k];
for (f = b.GetFixtureList(); f; f = f.m_next) {
var s = f.GetShape();
var shapePosition = b.GetWorldPoint(s.m_vertices[0]).x;
if((shapePosition > (camera_x - 5)) && (shapePosition < (camera_x + 10))) {
cw_drawVirtualPoly(ctx, b, s.m_vertices, s.m_vertexCount);
}
if(shapePosition > camera_x + 10) {
last_drawn_tile = k;
break outer_loop;
}
}
}
ctx.fill();
ctx.stroke();
}
|
95e7647dac6d2fa61c33ca5844e0091f603c6b99
|
[
"JavaScript"
] | 1
|
JavaScript
|
francesconero/HTML5_Genetic_Cars
|
bdcdd42f4141b9361269383b7f084f30d1c3da23
|
88c25398dd62276ff7ef5dfea4f4b054c349606d
|
refs/heads/master
|
<repo_name>odin-platform/odin-core<file_sep>/README.md
This project has moved to odin/odin-core.
Please use the other project.
/stephane
<file_sep>/attic/plugins/hal/test/test.orm.js
var async = require ('async');
var mocha = require ('mocha');
var should = require ('should');
var TheBulk = require ('thebulk');
var redis = require ('redis');
var orm = require ('../orm.js');
var thebulk = new TheBulk ();
describe ('odin-plugin-hal/orm.js', function () {
var client = redis.createClient ();
describe ('AuthorCollection', function () {
var _client = {};
var coll = new orm.AuthorCollection (_client);
describe ('new AuthorCollection ()', function () {
it ('should create a new AuthorCollection', function (done) {
coll.client.should.eql (_client);
coll.collection.should.eql ({});
done ();
});
});
describe ('AuthorCollection.newAuthor ()', function () {
it ('should return an Author', function (done) {
var firstname = thebulk.string ();
var lastname = thebulk.string ();
var author = coll.newAuthor (null, firstname, lastname);
author.should.have.property ('firstname');
author.should.have.property ('lastname');
done ();
});
});
describe ('AuthorCollection.addAuthor ()', function () {
it ('should add an author to the collection and return it', function (done) {
var firstname = thebulk.string ();
var lastname = thebulk.string ();
var author = coll.addAuthor (null, firstname, lastname);
coll.collection.should.have.property (author.id);
coll.collection[author.id].should.have.property ('firstname', firstname);
coll.collection[author.id].should.have.property ('lastname', lastname);
done ();
});
});
describe ('AuthorCollection.hasAuthor ()', function () {
it ('should add an author to the collection and return it', function (done) {
var author = coll.addAuthor (null, thebulk.string (), thebulk.string ());
coll.hasAuthor (author.id).should.be.true;
done ();
});
});
describe ('AuthorCollection.get ()', function () {
it ('should execute the right methods to get the author list from the database (no redis)', function (done) {
var client = {
smembers: function () {
arguments.length.should.equal (2);
arguments[0].should.eql ('hal:global:authors');
(typeof arguments[1]).should.equal ('function');
done ();
}
};
var coll = new orm.AuthorCollection (client);
coll.get (function () {});
});
});
describe ('AuthorCollection.save ()', function () {
it ('should save the author in the redis database (redis)', function (done) {
var coll = new orm.AuthorCollection (client);
var author1 = coll.addAuthor (null, thebulk.string (), thebulk.string ());
var author2 = coll.addAuthor (null, thebulk.string (), thebulk.string ());
var author3 = coll.addAuthor (null, thebulk.string (), thebulk.string ());
coll.save (function () {
client.smembers ('hal:global:authors', function (err, data) {
data.should.include (author1.id);
data.should.include (author2.id);
data.should.include (author3.id);
async.forEach ([author1, author2, author3], function (author, callback) {
client.hgetall ('hal:author:'+author.id, function (err, data) {
data.firstname.should.equal (author.firstname);
data.lastname.should.equal (author.lastname);
callback (err);
});
}, function (err) {
(err == null).should.be.true;
done ();
});
});
});
});
});
describe ('AuthorCollection.toArray ()', function () {
it ('should return the whole AuthorCollection as an array', function (done) {
var coll = new orm.AuthorCollection (client);
var author1 = coll.addAuthor (null, thebulk.string (), thebulk.string ());
var author2 = coll.addAuthor (null, thebulk.string (), thebulk.string ());
var author3 = coll.addAuthor (null, thebulk.string (), thebulk.string ());
coll.toArray ().should.includeEql (author1.toJSON ());
coll.toArray ().should.includeEql (author2.toJSON ());
coll.toArray ().should.includeEql (author3.toJSON ());
done ();
});
});
describe ('AuthorCollection.forEach ()', function () {
it ('iterates over the AuthorCollection', function (done) {
coll = new orm.AuthorCollection ();
var fn1 = thebulk.string ();
var ln1 = thebulk.string ();
var fn2 = thebulk.string ();
var ln2 = thebulk.string ();
var fn3 = thebulk.string ();
var ln3 = thebulk.string ();
var author1 = coll.addAuthor (null, fn1, ln1);
var author2 = coll.addAuthor (null, fn2, ln2);
var author3 = coll.addAuthor (null, fn3, ln3);
coll.forEach (function (author) {
author.should.have.property ('firstname');
author.should.have.property ('lastname');
(author.firstname === fn1 || author.firstname === fn2 || author.firstname === fn3).should.be.true;
(author.lastname === ln1 || author.lastname === ln2 || author.lastname === ln3).should.be.true;
});
done ();
});
});
});
describe ('Author', function () {
var _client = {};
var firstname = thebulk.string ();
var lastname = thebulk.string ();
var author = new orm.Author (_client, null, firstname, lastname);
describe ('new Author ()', function () {
it ('should create a new author', function (done) {
author.should.have.property ('publications');
author.should.have.property ('user');
author.should.have.property ('client', _client);
author.should.have.property ('firstname', firstname);
author.should.have.property ('lastname', lastname);
var firstname2 = 'Êéèëê';
var lastname2 = 'àâäã';
var author2 = new orm.Author (_client, null, firstname2, lastname2);
author2.should.have.property ('id', 'eeeee,aaaa');
done ();
});
});
describe ('Author.addPublication ()', function () {
it ('should add a publication to the author', function (done) {
var client = {};
var author = new orm.Author (client, null, thebulk.string (), thebulk.string ());
var title1 = thebulk.string ();
var link1 = thebulk.string ();
var pub1 = author.addPublication (title1, link1);
var title2 = thebulk.string ();
var link2 = thebulk.string ();
var pub2 = author.addPublication (title2, link2);
var title3 = thebulk.string ();
var link3 = thebulk.string ();
var pub3 = author.addPublication (title3, link3);
author.publications.hasPublication (pub1.id).should.be.true;
author.publications.hasPublication (pub2.id).should.be.true;
author.publications.hasPublication (pub3.id).should.be.true;
done ();
});
});
describe ('Author.newPublication ()', function () {
it ('should create a new publication', function (done) {
var title = thebulk.string ();
var link = thebulk.string ();
var pub = author.newPublication (title, link);
pub.title.should.equal (title);
pub.link.should.equal (link);
done ();
});
});
describe ('Author.hasPublication ()', function () {
it ('should return wether the author has got the publication', function (done) {
var client = {};
var author = new orm.Author (client, null, thebulk.string (), thebulk.string ());
var title1 = thebulk.string ();
var link1 = thebulk.string ();
var pub1 = author.addPublication (title1, link1);
var title2 = thebulk.string ();
var link2 = thebulk.string ();
var pub2 = author.addPublication (title2, link2);
var title3 = thebulk.string ();
var link3 = thebulk.string ();
var pub3 = author.addPublication (title3, link3);
author.hasPublication (pub1.id).should.be.true;
author.hasPublication (pub2.id).should.be.true;
author.hasPublication (pub3.id).should.be.true;
done ();
});
});
describe ('Author.save ()', function () {
it ('should save the author to the database (no redis)', function (done) {
var client = {
sadd: function () {
(arguments.length == 3).should.be.true;
arguments[0].should.equal ('hal:global:authors');
arguments[1].should.equal (author.id);
arguments[2].call (this);
},
hmset: function () {
arguments[0].should.equal ('hal:author:'+author.id);
arguments[1].should.equal ('firstname');
arguments[2].should.equal (author.firstname);
arguments[3].should.equal ('lastname');
arguments[4].should.equal (author.lastname);
arguments[5].should.equal ('user');
arguments[6].should.equal (author.user);
arguments[7].call (this);
}
};
var author = new orm.Author (client, null, thebulk.string (), thebulk.string ());
author.publications = {
save: function () {
(arguments.length >= 1).should.be.true;
arguments[0].call (this, null, 1);
}
};
author.save (function () {
done ();
});
});
});
describe ('Author.get ()', function () {
it ('should get the author data from the database', function (done) {
// TODO
done ();
});
});
describe ('Author.toJSON ()', function () {
it ('should return an object that describes an author', function (done) {
var author = new orm.Author (client, null, thebulk.string (), thebulk.string ());
author.toJSON ().firstname.should.equal (author.firstname);
author.toJSON ().lastname.should.equal (author.lastname);
done ();
});
});
});
describe ('PublicationCollection', function () {
var _client = {};
var firstname = thebulk.string ();
var lastname = thebulk.string ();
var author = new orm.Author (_client, null, firstname, lastname);
var publication_collection = new orm.PublicationCollection (_client, author);
describe ('new PublicationCollection ()', function () {
it ('should create a new PublicationCollection', function (done) {
publication_collection.should.have.property ('client', _client);
publication_collection.should.have.property ('author', author);
publication_collection.should.have.property ('collection', {});
done ();
});
});
describe ('PublicationCollection.addPublication ()', function () {
it ('should add a Publication to the PublicationCollection and return it', function (done) {
var title = thebulk.string ();
var link = thebulk.string ();
var pub = publication_collection.addPublication (title, link);
pub.title.should.equal (title);
pub.link.should.equal (link);
(pub.id in publication_collection.collection).should.be.true;
publication_collection.collection[pub.id].should.have.property ('title', title);
publication_collection.collection[pub.id].should.have.property ('link', link);
done ();
});
});
describe ('PublicationCollection.newPublication ()', function () {
it ('should return a new Publication', function (done) {
var title = thebulk.string ();
var link = thebulk.string ();
var pub = publication_collection.newPublication (title, link);
pub.title.should.equal (title);
pub.link.should.equal (link);
done ();
});
});
describe ('PublicationCollection.get ()', function () {
it ('should get a PublicationCollection the redis database', function (done) {
// TODO
done ();
});
});
describe ('PublicationCollection.toArray ()', function () {
it ('should return an array that describes a PublicationCollection', function (done) {
var titles = thebulk.more (thebulk.string);
var links = thebulk.more (thebulk.string);
var coll = new orm.PublicationCollection (_client, author);
titles.forEach (function (title, index) {
coll.addPublication (title, links[index]);
});
coll.toArray ().map (function (pub) {return pub.title;}).sort ().should.eql (titles.sort ());
coll.toArray ().map (function (pub) {return pub.link;}).sort ().should.eql (links.sort ());
coll.toArray ().forEach (function (pub) {pub.id.length.should.eql (8)});
done ();
});
});
describe ('PublicationCollection.hasPublication ()', function () {
it ('should return whether a Publication is in a PublicationCollection', function (done) {
var title = thebulk.string ();
var link = thebulk.string ();
var pub = new orm.Publication (_client, null, author, title, link);
publication_collection.addPublication (title, link);
publication_collection.hasPublication (pub.id).should.be.true;
done ();
});
});
});
describe ('Publication', function () {
var _client = {};
var firstname = thebulk.string ();
var lastname = thebulk.string ();
var author = new orm.Author (_client, null, firstname, lastname);
var title = thebulk.string ();
var link = thebulk.string ();
describe ('new Publication ()', function () {
it ('should return a new Publication', function (done) {
var pub = new orm.Publication (_client, null, author, title, link);
pub.should.have.property ('client', _client);
pub.should.have.property ('author', author);
pub.should.have.property ('title', title);
pub.should.have.property ('link', link);
pub.should.have.property ('id', pub.id);
pub.id.length.should.equal (8);
done ();
});
});
describe ('Publication.save ()', function () {
it ('should call the right methods to save an object in the database (no redis)', function (done) {
var _client = {
sadd: function () {
arguments[0].should.equal ('hal:global:publications:'+author.id);
arguments[1].should.equal (pub.id);
arguments.length.should.equal (3);
arguments[arguments.length-1].call (this, null, 1);
},
hmset: function () {
arguments[0].should.equal ('hal:publications:'+pub.id);
arguments[1].should.equal ('title');
arguments[2].should.equal (title);
arguments[3].should.equal ('link');
arguments[4].should.equal (link);
arguments[arguments.length-1].call (this, null, 1);
}
};
var pub = new orm.Publication (_client, null, author, title, link);
pub.save (function (err) {
done ();
});
});
it ('should save an object in the database (redis)', function (done) {
var pub = new orm.Publication (client, null, author, title, link);
pub.save (function (err) {
(err === null).should.be.true;
done ();
});
});
});
describe ('Publication.toJSON ()', function () {
it ('should return an object that describes a publication', function (done) {
var pub = new orm.Publication (client, null, author, title, link);
pub.toJSON ().should.have.property ('title', title);
pub.toJSON ().should.have.property ('link', link);
pub.toJSON ().should.have.property ('id');
var title2 = thebulk.string ();
var pub2 = new orm.Publication (client, null, author, title2, link);
if (title2 !== link)
pub2.id.should.not.eql (pub.id);
else
pub2.id.should.eql (pub.id);
done ();
});
});
});
});
|
c4ed453ac6fb66eb3d04d378992a40b0d0b305b8
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
odin-platform/odin-core
|
99f61ece76bdcef6fdfa860255c019daf322804a
|
c5a85ebdcc04d76db86c244c722f1d7580b2725b
|
refs/heads/master
|
<repo_name>kinnyng/test-struts<file_sep>/src/login_ex/loginAction.java
package login_ex;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
public class loginAction extends Action {
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse) {
loginActionForm myActionForm = (loginActionForm) actionForm;
if (myActionForm.getUsername().equals("test") && myActionForm.getPassword().equals("<PASSWORD>")) {
return actionMapping.findForward("ok");
}
else {
return actionMapping.findForward("false");
}
//throw new java.lang.UnsupportedOperationException("Method $execute() not yet implemented.");
}
}
|
e3e0b7c7e2d70d01e238f0f0f81131a550867a3a
|
[
"Java"
] | 1
|
Java
|
kinnyng/test-struts
|
91df74915da9cf47dc2b56291026d4e6f2a5e702
|
40989a4f32ad78df084df31117b487992e0d4fc4
|
refs/heads/master
|
<repo_name>tammapriya/POM<file_sep>/src/main/java/testcases/TC_EditLead.java
package testcases;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import pages.LoginPage;
import wdMethods.ProjectMethods;
public class TC_EditLead extends ProjectMethods{
@BeforeTest
public void setData() {
testCaseName="TC_EditLead";
testDescription="login to LeafTaps";
testNodes="Leads";
category="Smoke";
authors="chandu";
browserName="chrome";
dataSheetName="TC004";
}
@Test(dataProvider="fetchData")
public void loginAndLogout(String uName,String pwd,String vName,String FFname,String companyname,String cname) {
new LoginPage()
.enterUserName(uName)
.enterPassword(pwd)
.clickLogIn()
.verifyLoggedName(vName)
//.clickLogOut();
.clickCrmsfa()
.clickLeads()
.clickFindLead()
.enterFNameToFindlead(FFname)
.clickEleFindLeadButton()
.clickEleFirstResult()
.verifyTitleViewLead()
.clickEditLead()
.EditCompanyName(companyname)
.clickUpdateLeadbutton()
.verifyCompanyName(cname);
}
}
|
7d466483ed08c82e94392691ee9366d9df8b66db
|
[
"Java"
] | 1
|
Java
|
tammapriya/POM
|
68c3383854fa0f4602700ed29b3b09958fe6194b
|
13254bbc2de8aedede726decc1bb3bcd986d7d15
|
refs/heads/master
|
<file_sep>select * from titleauthor;
select * from publishers;
select * from titles;
select * from authors;
SELECT * FROM sales;
# Challenge 1
CREATE TEMPORARY TABLE first_table
SELECT auts.au_id AS 'AUTHOR ID', auts.au_fname AS 'LAST NAME', auts.au_lname AS 'FIRST NAME', ta.title_id as 'TitleID', title.title as 'Title',title.pub_id as 'Pub ID', pub.pub_name as 'Publisher'
FROM lab_mysql_select.authors AS auts
LEFT JOIN lab_mysql_select.titleauthor AS ta
ON auts.au_id = ta.au_id
LEFT JOIN lab_mysql_select.titles AS title
ON ta.title_id = title.title_id
LEFT JOIN lab_mysql_select.publishers AS pub
ON title.pub_id = pub.pub_id;
SELECT * FROM first_table;
#Challenge 2
SELECT auts.au_fname AS 'LAST NAME', auts.au_lname AS 'FIRST NAME', pub.pub_name as 'Publisher', COUNT(title.title)
FROM lab_mysql_select.authors AS auts
LEFT JOIN lab_mysql_select.titleauthor AS ta
ON auts.au_id = ta.au_id
LEFT JOIN lab_mysql_select.titles AS title
ON ta.title_id = title.title_id
LEFT JOIN lab_mysql_select.publishers AS pub
ON title.pub_id = pub.pub_id
GROUP BY auts.au_fname, auts.au_lname, pub.pub_name
ORDER BY auts.au_lname;
#Challenge 3
SELECT aut.au_id AS 'AUTHOR ID',
aut.au_lname AS 'LAST NAME',
aut.au_fname AS 'FIRST NAME',
ti.title_id AS 'TITLES',
SUM(sa.qty) AS 'total number of titles sold'
FROM lab_mysql_select.authors AS aut
LEFT JOIN lab_mysql_select.titleauthor AS ti
ON aut.au_id = ti.au_id
LEFT JOIN lab_mysql_select.sales as sa
ON ti.title_id = sa.title_id
GROUP BY aut.au_id, ti.title_id
ORDER BY SUM(sa.qty) DESC
LIMIT 3;
#Challenge 4
SELECT aut.au_id AS 'AUTHOR ID',
aut.au_lname AS 'LAST NAME',
aut.au_fname AS 'FIRST NAME',
COUNT(ti.title_id) AS 'TITLES',
SUM(sa.qty) AS 'total number of titles sold'
FROM lab_mysql_select.authors AS aut
LEFT JOIN lab_mysql_select.titleauthor AS ti
ON aut.au_id = ti.au_id
LEFT JOIN lab_mysql_select.sales as sa
ON ti.title_id = sa.title_id
GROUP BY aut.au_id, ti.title_id
ORDER BY SUM(sa.qty) DESC
|
cb3240e76d2efd7d2a0e386fa3cfc1d7fa2b501d
|
[
"SQL"
] | 1
|
SQL
|
cleanspin/lab-mysql-select
|
46e4969d77f2beaa49f07a6f0374b3e248cdad63
|
d791802d4ccfec5745efb48e38d9e6c8abc898c1
|
refs/heads/master
|
<file_sep># HappySad
Built in Visual Studio for ~your~ my convenience.
Sometimes you just need a `happy.exe` and a `sad.exe` for testing or PoCs, or whatever.
*WARNING* Never run random binaries you find on GitHub or wherever. Review them or build these tiny things from source yourself first.<file_sep>#include <string>
#include <Windows.h>
int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, char*, int nShowCmd)
{
char buff[100];
std::string s = "HAPPY";
sprintf_s(buff, "I AM %s", s.c_str());
MessageBox(NULL, buff, s.c_str(), MB_OK | MB_ICONQUESTION);
}
|
4b2cd6724d380f8ae2375e579e3ed88a7a012ef2
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
malcomvetter/HappySad
|
8338342ff4307a1f5e5c31323bafce590f882517
|
7e38ad426b83d62c5b6452a40501553227770929
|
refs/heads/master
|
<repo_name>smasher0310/crawler<file_sep>/crawler.py
import requests
from urllib.parse import urlparse,urljoin
from bs4 import BeautifulSoup
import cfg
import persistence
import time, os
from concurrent.futures import ThreadPoolExecutor
class crawler():
"""A simple Crawler"""
def __init__(self,url):
self.url = url
# do http request
def makeGetRequest(self,url):
try:
response = requests.get(url)
return response
except:
return None
# intial crawl to populate the database
def setup(self):
#create folder
if not os.path.isdir(os.path.join(os.getcwd(),cfg.local_folder)):
# make folder for local files
os.makedirs(os.path.join(os.getcwd(),cfg.local_folder))
# setup connection to DB
persistence.setup()
# add the base url to DB
persistence.addDocument(self.url,self.url)
def do_crawl(self,item):
if cfg.link_count >= cfg.link_limit:
return
# print('Requesting for the page {}'.format(item['link']))
res = self.makeGetRequest(item['link'])
if res is None or (not res.status_code == 200):
return
# if filepath exist, overwrite it
if not item['filePath'] == '':
filepath = item['filePath']
else:
# find the suitable extension
if not res.headers['content-type'] in cfg.file_ext.keys():
filetype = 'unknown'
else:
filetype = cfg.file_ext[res.headers['content-type']]
# create unique filename
filename = '{}.{}'.format(str(time.time_ns()),filetype)
filepath = os.path.join(os.getcwd(),cfg.local_folder,filename)
file = open(filepath,'w')
file.write(res.text)
file.close()
#update the info related with this link
# split(';')[0].split('/')[-1]
persistence.updateDocument(item['_id'],res.status_code,filepath,res.headers['content-type'],len(res.text),True)
# crawl and save links to DB
soup = BeautifulSoup(res.text,'html.parser')
for link in soup.find_all('a'):
# link in DB is >=5000, defer to crawl
if cfg.link_count >= cfg.link_limit:
#mark the page uncrawled and return
persistence.updateDocument(item['_id'],res.status_code,filepath,res.headers['content-type'],len(res.text),False)
return
# print(link.get('href'))
if isAbsolute(link.get('href')):
persistence.addDocument(link.get('href'),item['link'])
else:
# create absolute path
newPath = urljoin(item['link'],link.get('href'))
if isAbsolute(newPath):
persistence.addDocument(newPath,item['link'])
# crawl the links
def crawl(self):
cycleCount = 0
while(1):
cycleCount = cycleCount + 1
print('Cycle {} started'.format(cycleCount))
# get the uncrawled url from DB
items = persistence.getLinks()
if len(items) == 0:
print('All links crawled')
print('sleeping for 5 sec.....................\n\n')
time.sleep(5)
continue
executor = ThreadPoolExecutor(cfg.thread_count)
for item in items:
if cfg.link_count >= cfg.link_limit:
# terminate the threads and reset the counter for next cycle
executor.shutdown(wait=True)
print("Maximum Limit Reached")
cfg.link_count = 0
break
executor.submit(self.do_crawl,item)
executor.shutdown(wait=True)
# sleep for 5s between cycles
crawledDocumentsCount = persistence.countDocuments({'isCrawled' : True})
notCrawledDocumentsCount = persistence.countDocuments({'isCrawled': False})
print('Pages Scraped: {}\t Total Link count: {}'.format(crawledDocumentsCount,crawledDocumentsCount+notCrawledDocumentsCount))
print('sleeping for 5 sec.....................\n\n')
time.sleep(5)
# check if url is absolute URL
def isAbsolute(url):
if bool(urlparse(url).scheme) and bool(urlparse(url).netloc):
return True
return False
def main():
url = cfg.url
print('URl: ',cfg.url)
# check if url is FQ URL
if not isAbsolute(url):
print('Invalid URL')
exit(1)
c = crawler(url)
try:
c.setup()
c.crawl()
except Exception as e:
print('Exception occured',e)
if __name__ == '__main__':
main()
<file_sep>/README.md
A simple web crawler that crawls the specifie url links and store the details in monogDB.<file_sep>/cfg.py
DB_Name = 'crawlerDB'
DB_host = 'localhost'
DB_port = 27017
local_folder = 'local_files'
link_limit = 5000
link_count = 0
thread_count=5
file_ext = {
'text/html; charset=utf-8' : 'html',
'application/json; charset=utf-8' : 'json',
'application/json' : 'json'
}
days = 1
url = 'https://www.flinkhub.com'<file_sep>/persistence.py
from pymongo import MongoClient
import cfg
import time
from datetime import datetime
from datetime import timedelta
links = None
connected = False
def setup():
global connected, links
try:
client = MongoClient(cfg.DB_host,cfg.DB_port)
db = client[cfg.DB_Name]
links = db.links
connected = True
print('Connected to {} DB {}\n'.format(cfg.DB_Name,db))
except:
print('Error in connecting to DB')
def addDocument(url,rootUrl):
ret = links.find_one({
'link': url
})
if not ret is None:
# print('{} already in DB'.format(url))
return
cfg.link_count = cfg.link_count + 1
doc = {
'link': url,
'srcLink': rootUrl,
'isCrawled': False,
'lastCrawlDate': None,
'responseStatus': 404,
'contentType': None,
'contentLen': 0,
'filePath': '',
'createdAt': datetime.now()
}
links.insert_one(doc)
# get the links that has not been crawled yet
def getLinks():
items = links.find({ '$or': [
{"isCrawled" : False},
{'lastCrawlDate' : { '$lt' : datetime.now() - timedelta(days = cfg.days)}}
]
})
itemList = []
for item in items:
itemList.append(item)
return itemList
# # update status of the crawl
def updateDocument(oid,status,filePath,contentType,contentLen,isCrawled):
if not connected:
exit('DB not connectd')
return
try:
links.update_one(
{'_id': oid},
{ '$set' : {
'isCrawled': isCrawled,
'lastCrawlDate': datetime.now(),
'responseStatus': status,
'contentType': contentType,
'contentLen': contentLen,
'filePath': filePath
}
}
)
except Exception as e:
print(e)
def countDocuments(cond):
return links.count_documents(cond)
|
d130e6727bd484764520a2cb62b6fb26e075f949
|
[
"Markdown",
"Python"
] | 4
|
Python
|
smasher0310/crawler
|
ca5f9253d09d7db50e351dbf18882294d58606d6
|
e7e3205e0e599ab6ed97e854bf1c36a0a5b7eab2
|
refs/heads/main
|
<repo_name>hiepcm/bussiness-db-project<file_sep>/server-bussiness-db/app/InterviewerComment.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class InterviewerComment extends Model
{
protected $table = 'interviewer_comment';
protected $fillable = ['id','del_flag','interviewer_id','comment','rating','created_by','modified_by','created_at','updated_at'];
protected $hidden = [
'laravel_through_key'
];
public function interview(){
return $this->belongsToMany(Interview::class, Interviewer::class, 'id', 'interview_id');
}
public function interviewer(){
return $this->belongsTo(Interviewer::class, 'interviewer_id', 'id');
}
public function member_interviewer(){
return $this->belongsToMany(Member::class, Interviewer::class, 'id', 'interview_id');
}
}
<file_sep>/server-bussiness-db/app/CandidateSkill.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CandidateSkill extends Model
{
protected $table = 'candidate_skill';
protected $fillable = ['id','del_flag','candidate_id','skill_id','created_by','modified_by','created_at','updated_at'];
public function candidate(){
return $this->belongsTo(Candidate::class, 'candidate_id', 'id');
}
public function skill(){
return $this->belongsTo(Configuration::class, 'skill_id', 'id');
}
}
<file_sep>/server-bussiness-db/database/seeds/CandidateTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use Carbon\Carbon;
class CandidateTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('candidate')->insert([
array('del_flag'=>false, 'name'=>'<NAME>', 'is_male'=>true, 'birthday'=>'1997-06-21', 'cv'=>'cv1.pdf', 'is_passed'=>false, 'university_id'=>2, 'created_by'=>1, 'modified_by'=>null, 'created_at'=>Carbon::now('Asia/Ho_Chi_Minh'), 'updated_at'=>Carbon::now('Asia/Ho_Chi_Minh')),
array('del_flag'=>false, 'name'=>'<NAME>', 'is_male'=>true, 'birthday'=>'1997-03-16', 'cv'=>'cv2.pdf', 'is_passed'=>false, 'university_id'=>5, 'created_by'=>1, 'modified_by'=>null, 'created_at'=>Carbon::now('Asia/Ho_Chi_Minh'), 'updated_at'=>Carbon::now('Asia/Ho_Chi_Minh')),
array('del_flag'=>false, 'name'=>'<NAME>', 'is_male'=>true, 'birthday'=>'1997-01-21', 'cv'=>'cv3.pdf', 'is_passed'=>false, 'university_id'=>4, 'created_by'=>1, 'modified_by'=>null, 'created_at'=>Carbon::now('Asia/Ho_Chi_Minh'), 'updated_at'=>Carbon::now('Asia/Ho_Chi_Minh')),
array('del_flag'=>false, 'name'=>'<NAME>', 'is_male'=>true, 'birthday'=>'1997-08-11', 'cv'=>'cv4.pdf', 'is_passed'=>false, 'university_id'=>3, 'created_by'=>1, 'modified_by'=>null, 'created_at'=>Carbon::now('Asia/Ho_Chi_Minh'), 'updated_at'=>Carbon::now('Asia/Ho_Chi_Minh')),
array('del_flag'=>false, 'name'=>'<NAME>', 'is_male'=>false, 'birthday'=>'1997-08-11', 'cv'=>'cv5.pdf', 'is_passed'=>false, 'university_id'=>6, 'created_by'=>1, 'modified_by'=>null, 'created_at'=>Carbon::now('Asia/Ho_Chi_Minh'), 'updated_at'=>Carbon::now('Asia/Ho_Chi_Minh'))
]);
}
}
<file_sep>/server-bussiness-db/database/seeds/InterviewTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use Carbon\Carbon;
class InterviewTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('interview')->insert([
array('del_flag'=>false, 'status'=>true, 'evaluation'=>0, 'candidate_id'=>1, 'position_id'=>81, 'date'=>'2019-06-21 10:00:00', 'note'=>'Notes during the interview process', 'created_by'=>1, 'modified_by'=>null, 'created_at'=>Carbon::now('Asia/Ho_Chi_Minh'), 'updated_at'=>Carbon::now('Asia/Ho_Chi_Minh')),
array('del_flag'=>false, 'status'=>true, 'evaluation'=>0, 'candidate_id'=>2, 'position_id'=>78, 'date'=>'2019-06-22 15:00:00', 'note'=>'Notes during the interview process', 'created_by'=>1, 'modified_by'=>null, 'created_at'=>Carbon::now('Asia/Ho_Chi_Minh'), 'updated_at'=>Carbon::now('Asia/Ho_Chi_Minh')),
array('del_flag'=>false, 'status'=>true, 'evaluation'=>0, 'candidate_id'=>3, 'position_id'=>79, 'date'=>'2019-06-23 08:00:00', 'note'=>'Notes during the interview process', 'created_by'=>1, 'modified_by'=>null, 'created_at'=>Carbon::now('Asia/Ho_Chi_Minh'), 'updated_at'=>Carbon::now('Asia/Ho_Chi_Minh')),
array('del_flag'=>false, 'status'=>true, 'evaluation'=>0, 'candidate_id'=>4, 'position_id'=>80, 'date'=>'2019-06-24 13:00:00', 'note'=>'Notes during the interview process', 'created_by'=>1, 'modified_by'=>null, 'created_at'=>Carbon::now('Asia/Ho_Chi_Minh'), 'updated_at'=>Carbon::now('Asia/Ho_Chi_Minh')),
array('del_flag'=>false, 'status'=>true, 'evaluation'=>0, 'candidate_id'=>5, 'position_id'=>94, 'date'=>'2019-06-25 14:00:00', 'note'=>'Notes during the interview process', 'created_by'=>1, 'modified_by'=>null, 'created_at'=>Carbon::now('Asia/Ho_Chi_Minh'), 'updated_at'=>Carbon::now('Asia/Ho_Chi_Minh')),
]);
}
}
<file_sep>/server-bussiness-db/app/Team.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $table = 'team';
protected $fillable = ['id','del_flag','name','leader','description',
'created_by','modified_by','created_at','updated_at'];
protected $hidden = [
'pivot'
];
public function members(){
return $this->belongsToMany(Member::class, TeamMember::class, 'team_id', 'member_id');
}
public function team_members(){
return $this->hasMany(TeamMember::class, 'team_id', 'id');
}
public function member_leader(){
return $this->belongsTo(Member::class, 'leader', 'id');
}
}
<file_sep>/server-bussiness-db/app/Http/Controllers/MemberController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
class MemberController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$username = $request->input('username');
$pwd = $request->input('pwd');
$fullname = $request->input('fullname');
$gender = $request->input('is_male');
$birthday = $request->input('birthday');
$email = $request->input('email');
$phone = $request->input('phone');
$access_level = $request->input('access_level');
if($gender == 'on') {
$gender = 1;
} else {
$gender = 0;
}
$result =\DB::insert('insert into member (del_flag, username, password, fullname, is_male, birthday, email, phone, picture, access_level, created_by, modified_by, created_at, updated_at) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)', ['0', $username, $pwd, $fullname, $gender, $birthday, $email, $phone,'avatar_50.jpg', $access_level, 1, null, Carbon::now('Asia/Tokyo'), Carbon::now('Asia/Tokyo')]);
return view('welcome');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep>/server-bussiness-db/app/TeamMember.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TeamMember extends Model
{
protected $table = 'team_member';
protected $fillable = ['id','del_flag','member_id','team_id','team_member_role',
'created_by','modified_by','created_at','updated_at'];
public function team(){
return $this->belongsTo(Team::class, 'team_id', 'id');
}
public function member(){
return $this->belongsTo(Member::class, 'member_id', 'id');
}
public function member_role(){
return $this->belongsTo(Configuration::class, 'team_member_role', 'id');
}
}
<file_sep>/server-bussiness-db/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Member;
use App\Team;
use App\TeamMember;
use App\Candidate;
use App\CandidateSkill;
use App\CandidateContact;
use App\Interview;
use App\Interviewer;
use App\InterviewerComment;
use App\Configuration;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
// Route::get('test', function () {
// //return DB::table('configuration')->where('id',1)->get();
// return DB::table('configuration')->get();
// });
Route::get('memberRegister', function () {
return view('registerMembers');
})->name('memberRegister');
Route::post('store', 'MemberController@store')->name('registerMember');
Route::get('testmodule', function () {
$getData = Interviewer::find(1);
return $getData->interviewer_comments;
});
<file_sep>/server-bussiness-db/app/Candidate.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Candidate extends Model
{
protected $table = 'candidate';
protected $fillable = ['id','del_flag','name','is_male','birthday','cv','is_passed',
'university_id','created_by','modified_by','created_at','updated_at'];
protected $hidden = [
'pivot'
];
public function skills(){
return $this->belongsToMany(Configuration::class, CandidateSkill::class, 'candidate_id', 'skill_id');
}
public function contacts(){
return $this->belongsToMany(Configuration::class, CandidateContact::class, 'candidate_id', 'contact_id');
}
public function candidate_skills(){
return $this->hasMany(CandidateSkill::class, 'candidate_id', 'id');
}
public function candidate_contacts(){
return $this->hasMany(CandidateContact::class, 'candidate_id', 'id');
}
public function candidate_university(){
return $this->belongsTo(Configuration::class, 'university_id', 'id');
}
public function interviews(){
return $this->hasMany(Interview::class, 'candidate_id', 'id');
}
public function interviewers(){
return $this->hasManyThrough(Interviewer::class, Interview::class, 'candidate_id', 'interview_id', 'id', 'id');
}
}
<file_sep>/server-bussiness-db/app/CandidateContact.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CandidateContact extends Model
{
protected $table = 'candidate_contact';
protected $fillable = ['id','del_flag','candidate_id','contact_id','value','created_by','modified_by','created_at','updated_at'];
public function candidate(){
return $this->belongsTo(Candidate::class, 'candidate_id', 'id');
}
public function contact(){
return $this->belongsTo(Configuration::class, 'contact_id', 'id');
}
}
<file_sep>/server-bussiness-db/app/Interviewer.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Interviewer extends Model
{
protected $table = 'interviewer';
protected $fillable = ['id','del_flag','interview_id','member_id','evaluation',
'created_by','modified_by','created_at','updated_at'];
public function member(){
return $this->belongsTo(Member::class, 'member_id', 'id');
}
public function interview(){
return $this->belongsTo(Interview::class, 'interview_id', 'id');
}
public function interviewer_comments(){
return $this->hasMany(InterviewerComment::class, 'interviewer_id', 'id');
}
}
<file_sep>/README.md
# bussiness-db-project<file_sep>/server-bussiness-db/database/migrations/2020_12_12_154423_create_candidate_skill_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCandidateSkillTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('candidate_skill', function (Blueprint $table) {
$table->bigIncrements('id');
$table->boolean('del_flag')->default(false);
$table->integer('candidate_id')->unsigned();
$table->integer('skill_id')->unsigned();
$table->integer('created_by')->unsigned()->nullable();
$table->integer('modified_by')->unsigned()->nullable();
$table->foreign('candidate_id')->references('id')->on('candidate')->onUpdate('cascade');
$table->foreign('skill_id')->references('id')->on('configuration')->onUpdate('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('candidate_skill');
}
}
<file_sep>/server-bussiness-db/app/Interview.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Interview extends Model
{
protected $table = 'interview';
protected $fillable = ['id','del_flag','status','evaluation','candidate_id','position_id',
'date','note','created_by','modified_by','created_at','updated_at'];
protected $hidden = [
'pivot'
];
public function candidate(){
return $this->belongsTo(Candidate::class, 'candidate_id', 'id');
}
public function position(){
return $this->belongsTo(Configuration::class, 'position_id', 'id');
}
public function interviewers(){
return $this->hasMany(interviewer::class, 'interview_id', 'id');
}
public function member_interviewers(){
return $this->belongsToMany(Member::class, Interviewer::class, 'interview_id', 'member_id');
}
public function comment_interviewers(){
return $this->hasManyThrough(InterviewerComment::class, Interviewer::class, 'interview_id', 'interviewer_id', 'id', 'id');
}
}
<file_sep>/server-bussiness-db/app/Member.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Member extends Model
{
protected $table = 'member';
protected $fillable = ['id','del_flag','username','password','fullname','is_male','birthday',
'email','phone','picture','access_level','created_by','modified_by','created_at','updated_at'];
protected $hidden = [
'password', 'pivot'
];
public function teams(){
return $this->belongsToMany(Team::class, TeamMember::class, 'member_id', 'team_id');
}
public function team_members(){
return $this->hasMany(TeamMember::class, 'member_id', 'id');
}
public function member_role(){
return $this->belongsTo(Configuration::class, 'access_level', 'id');
}
public function leader_of_teams(){
return $this->hasMany(Team::class, 'leader', 'id');
}
public function interviews(){
return $this->belongsToMany(Interview::class, Interviewer::class, 'member_id', 'interview_id');
}
public function interviewers(){
return $this->hasMany(Interviewer::class, 'member_id', 'id');
}
public function interviewer_comment(){
return $this->hasManyThrough(InterviewerComment::class, Interviewer::class, 'member_id', 'interviewer_id', 'id', 'id');
}
}
|
d0234adad7035b83e69b7ef9a1a5c476bd2e0fcb
|
[
"Markdown",
"PHP"
] | 15
|
PHP
|
hiepcm/bussiness-db-project
|
70fb54fb20c9056230eaac6e6f9cfe442a8e2e1a
|
f93d9e85d155fb35c1f26056ba82d77cc206e449
|
refs/heads/master
|
<repo_name>xgch/act7<file_sep>/multiplicar2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tabla del 2</title>
</head>
<body>
<?php
//Tabla del 2
$numero=0;
echo "<h2>Tabla del 2</h2>";
while ($numero<=10) {
$resultado=$numero*2;
echo "2x$numero=$resultado <br>";
$numero++;
}
?>
</body>
</html>
|
aa93f56f5ad84c67d1e9ed96506e16091d89968f
|
[
"PHP"
] | 1
|
PHP
|
xgch/act7
|
ca642ad0b8898c927d25ba1887896d82841cd833
|
7b625e3d00aae20393595dee17adf4b29919a14e
|
refs/heads/master
|
<file_sep>read_epc <- function(){
#specifically reads the household_power_consumption.txt dataset.
compressed_file <- 'epc.zip'
data_file <- 'household_power_consumption.txt'
if(!file.exists(compressed_file)) {
print("downloading the file")
url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(url, compressed_file, method = "curl")
}
if(!file.exists(data_file)) {
print("uncompressing the file")
unzip(compressed_file)
}
print("reading the file")
df <- read.table(data_file, header = TRUE, sep = ';',
colClasses = c('factor', 'factor', 'numeric', 'numeric', 'numeric',
'numeric', 'numeric', 'numeric', 'numeric'),
na.strings = "?")
df$Date <- as.Date(df$Date, format('%d/%m/%Y'))
interesting_dates <- as.Date(c('2007-02-01', '2007-02-02'), format('%Y-%m-%d'))
df$datetime <- with(df, as.POSIXct(paste(Date, Time), format="%Y-%m-%d %H:%M:%S"))
return(df[df$Date %in% interesting_dates,])
}
epc <- read_epc()
png(width = 480, height = 480, file = "plot4.png")
par(mfrow = c(2,2))
plot(epc$datetime, epc$Global_active_power, type = 'l', ylab = "Global Active Power", xlab = "")
plot(epc$datetime, epc$Voltage, type = 'l', ylab = "Voltage", xlab = "datetime")
with(epc, {
plot(datetime, Sub_metering_1, type = 'l', ylab = "Energy sub metering", xlab = "")
lines(datetime, Sub_metering_2, col = 'red')
lines(datetime, Sub_metering_3, col = 'blue')
legend('topright', c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
col = c('black', 'red', 'blue'), lty = 1, box.lwd = 0, bg = "transparent")
})
plot(epc$datetime, epc$Global_reactive_power, type = 'l', xlab = "datetime")
dev.off()
<file_sep>read_epc <- function(){
#specifically reads the household_power_consumption.txt dataset.
compressed_file <- 'epc.zip'
data_file <- 'household_power_consumption.txt'
if(!file.exists(compressed_file)) {
print("downloading the file")
url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(url, compressed_file, method = "curl")
}
if(!file.exists(data_file)) {
print("uncompressing the file")
unzip(compressed_file)
}
print("reading the file")
df <- read.table(data_file, header = TRUE, sep = ';',
colClasses = c('factor', 'factor', 'numeric', 'numeric', 'numeric',
'numeric', 'numeric', 'numeric', 'numeric'),
na.strings = "?")
df$Date <- as.Date(df$Date, format('%d/%m/%Y'))
interesting_dates <- as.Date(c('2007-02-01', '2007-02-02'), format('%Y-%m-%d'))
df$datetime <- with(df, as.POSIXct(paste(Date, Time), format="%Y-%m-%d %H:%M:%S"))
return(df[df$Date %in% interesting_dates,])
}
epc <- read_epc()
plot(epc$datetime, epc$Global_active_power, type = 'l', ylab = "Global Active Power (Kilowatts)", xlab = "")
dev.copy(png, file = "plot2.png", width = 480, height = 480)
dev.off()
<file_sep>read_epc <- function(){
#specifically reads the household_power_consumption.txt dataset.
compressed_file <- 'epc.zip'
data_file <- 'household_power_consumption.txt'
if(!file.exists(compressed_file)) {
print("downloading the file")
url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(url, compressed_file, method = "curl")
}
if(!file.exists(data_file)) {
print("uncompressing the file")
unzip(compressed_file)
}
print("reading the file")
df <- read.table(data_file, header = TRUE, sep = ';',
colClasses = c('factor', 'factor', 'numeric', 'numeric', 'numeric',
'numeric', 'numeric', 'numeric', 'numeric'),
na.strings = "?")
df$Date <- as.Date(df$Date, format('%d/%m/%Y'))
interesting_dates <- as.Date(c('2007-02-01', '2007-02-02'), format('%Y-%m-%d'))
df$datetime <- with(df, as.POSIXct(paste(Date, Time), format="%Y-%m-%d %H:%M:%S"))
return(df[df$Date %in% interesting_dates,])
}
epc <- read_epc()
png(width = 480, height = 480, file = "plot3.png")
with(epc, {
plot(datetime, Sub_metering_1, type = 'l', ylab = "Energy sub metering", xlab = "")
lines(datetime, Sub_metering_2, col = 'red')
lines(datetime, Sub_metering_3, col = 'blue')
legend('topright', c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"),
col = c('black', 'red', 'blue'), lty = 1)
})
dev.off()
|
0c237ad469847d3ddc85f07dcca23d127833c045
|
[
"R"
] | 3
|
R
|
joanenricb/ExData_Plotting1
|
cd81790daa09eb9ad79af72ddc300f6f1210c221
|
b9e2880d259f75639779832b4a77b5464ddd2e41
|
refs/heads/master
|
<file_sep>var raffle = require('raffle');
var express = require('express');
var path = require('path');
var app = express();
app.use('/public', express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index');
});
app.post('/draw', function(req, res) {
var settings = {
key: process.env.MEETUP_KEY,
event_id: process.env.MEETUP_EVENT_ID
};
raffle(settings, function(winner) {
console.log(winner);
return res.json(winner);
});
});
if (!process.env.MEETUP_KEY || !process.env.MEETUP_EVENT_ID) {
console.error('MEETUP_KEY or MEETUP_EVENT_ID env vars not set');
process.exit(-1);
}
app.listen(8001, function() {
console.log('Listening on 8001');
});
|
96c89ae27eb0fe57674490bf0eacc87220e46943
|
[
"JavaScript"
] | 1
|
JavaScript
|
johnfriz/raffle
|
5d35080814e313a83abe651a7f8ef08f35b53e8e
|
66a684b4f47e9fe29f53f7cfd703ffe933abe499
|
refs/heads/master
|
<repo_name>w-v/scale<file_sep>/include/player.h
#ifndef SCALE_PLAYER
#define SCALE_PLAYER
#include <entity.h>
#include <controllable.h>
#include <ncurses.h>
#include <bloc.h>
enum Status {standing, walking, jumping, falling};
class Player : public Controllable, public Entity
{
public:
Status status;
Bloc breakotron = Bloc('@');
void update();
Player(World*);
void react();
void standing();
void walking();
void jumping();
void falling();
void stand();
void walk(float dir);
void jump(float dir);
void fall(float dir);
};
#endif
<file_sep>/include/terrain.h
#ifndef SCALE_TERRAIN
#define SCALE_TERRAIN
#define DRAW_DISTANCE 25 /* in chunks around a center chunk */
/* Forward declarations */
class Chunk;
class Terrain {
public:
void load(Chunk&); /* load chunk i */
Terrain();
};
#endif
<file_sep>/src/bloc.cpp
#include <bloc.h>
#include <ncurses.h>
/*
void Bloc::display(Vec2<int> vcoords){
wmove(stdscr,vcoords.y,vcoords.x);
addch(this->type);
}*/
Bloc Bloc::clone(){
Bloc v(this->ch);
v.bcolor = this->bcolor;
v.bold = this->bold;
v.color = this->color;
v.under = this->under;
return v;
}
<file_sep>/src/entity.cpp
#include <entity.h>
#include <area.h>
Entity::Entity(World* w)
: pos(Vector2f(0.0,0.0)), max_vel(15), acc(Vector2f(0.0,0.0)), vel(Vector2f(0.0,0.0)), world(w), mass(10), holding(Holding(*this))
{
round_coords();
}
Entity::Entity(Vector2f v, World* w)
: pos(v), max_vel(10), acc(Vector2f(0.0,0.0)), vel(Vector2f(0.0,0.0)), world(w), mass(10),holding(Holding(*this))
{
round_coords();
}
void Entity::round_coords(){
coords = pos.array().round().matrix().cast<int>(); /* ugly */
}
void Entity::spawn(int x, Area& area){
pos = area.get_spawnable(x).cast<float>();
round_coords();
}
bool Entity::isongrnd(Area& area){
return coords.y() == area.get_spawnable(coords.x()).y();
}
void Entity::collide(Area& area){
Vector2i v = this->coords+Vector2i(1,0);
if(area.is_solid(v)){
acc(1) = fmin(acc(0),0);
vel(0) = fmin(vel(0),0);
}
v = this->coords+Vector2i(-1,0);
if(area.is_solid(v)){
acc(0) = fmax(acc(0),0);
//acc(1) = fmin(acc(1),0);
vel(0) = fmax(vel(0),0);
//vel(1) = fmin(vel(1),0);
}
v = this->coords+Vector2i(0,1);
if(area.is_solid(v)){
acc(1) = fmin(acc(1),0);
vel(1) = fmin(vel(1),0);
}
v = this->coords+Vector2i(0,-1);
if(area.is_solid(v)){
acc(1) = fmax(acc(1),0);
vel(1) = fmax(vel(1),0);
//acc(0) = fmin(acc(0),0);
//vel(0) = fmin(vel(0),0);
}
}
<file_sep>/include/area.h
#ifndef SCALE_AREA
#define SCALE_AREA
/* Forward declarations */
class View;
class Area;
#include <chunk.h>
#include <deque>
#include <terrain.h>
#include <bloc.h>
#include <Eigen/Dense>
class Area : public std::deque<Chunk>{
public:
void load(View&, Terrain&);
Vector2i get_spawnable(int x);
bool is_loaded(int x); /* is chunk containing coord x loaded ? */
bool is_solid(Vector2i&);
Bloc break_block(Vector2i&);
Area();
};
#endif
<file_sep>/src/terrain.cpp
#include <terrain.h>
#include <chunk.h>
#include <bloc.h>
#include <math.h>
Terrain::Terrain(){
}
void Terrain::load(Chunk& chunk){
for(int i=0;i<chunk.size(0);i++){
for(int j=0;j<chunk.size(1);j++){
if(j > (sin(((double)(i+chunk.coords.x()))/75)*10) + (sin(((double)(i+chunk.coords.x()))/15)*3)+30 ){
chunk.graphic[i][j] = Bloc(' ');
}
else {
chunk.graphic[i][j] = Bloc(77+(i%2)*2);
}
}
}
}
<file_sep>/src/chunk.cpp
#include <chunk.h>
Eigen::Vector2i Chunk::size = Vector2i(CHUNK_SIZE,MAX_HEIGHT);
int Chunk::ground_y(int x){
int y = 0;
while (this->graphic[x][y].ch != ' '){
y++;
}
return y;
}
<file_sep>/src/world.cpp
#include <world.h>
#include <ncurses.h>
#include <view.h>
#include <ctime>
#include <chrono>
World::World()
: ntime(std::chrono::steady_clock::now()), time(std::chrono::steady_clock::now()), player(this), area(), terrain()
{}
void World::tick(){
ntime = std::chrono::steady_clock::now();
player.update();
//time = ntime;
}
void World::load(View& view){
area.load(view,terrain); /* loads all graphics visible in the view */
}
void World::init(View& view){
area.load(view,terrain); /* loads all graphics visible in the view */
player.spawn(0,area);
view.center(player.coords);
}
<file_sep>/include/view.h
#ifndef SCALE_VIEW
#define SCALE_VIEW
/* Forward declarations */
class Area;
#include <entity.h>
#include <world.h>
#include <Eigen/Dense>
using namespace Eigen;
class View {
public:
Matrix2i coords;
/* : world coordinates */
/* forms the window the game is displayed in */
//void follow(Vector2i& pos); /* move the view around pos */
Vector2i update_lim;
Entity& followed;
Vector2i y_down_transf;
void follow(Entity&);
void center(Vector2i&);
void draw(World&);
void draw(Area&);
void draw(Entity&);
void drawd(Displayable&);
void update();
void display(Char&, Vector2i&);
View(Entity& fol);
};
#endif
<file_sep>/src/holding.cpp
/*
* holding.cpp
*
* Created on: 14 mars 2018
* Author: robin
*/
#include <holding.h>
#include <entity.h>
Holding::Holding(Entity& e):
holder(e), is_held_down(false)
{}
void Holding::hold_down(Direction dir){
Vector2i v(0,0);
switch(dir) {
case left :
v(0)--;
break;
case right :
v(0)++;
break;
case up :
case down :
v(1)--;
}
this->coords=holder.coords+v;
}
void Holding::hold_up(){
this->coords=holder.coords+Vector2i(0,1);
}
void Holding::update_coords(){
if(this->is_held_down)
hold_down(holder.dir);
else
hold_up();
}
<file_sep>/include/graphic.h
#ifndef SCALE_GRAPHIC
#define SCALE_GRAPHIC
#include <vector>
#include <char.h>
#include <Eigen/Dense>
//using namespace std;
class GenGraphic {
};
template <class T>
class Graphic : public std::vector<std::vector<T>> , GenGraphic {
public:
Eigen::Vector2i size;
Graphic(Eigen::Vector2i);
};
template <class T>
Graphic<T>::Graphic(Eigen::Vector2i s)
: size(s)
{
this->resize(s.x());
for (int i = 0; i < s.x(); ++i)
this->at(i).resize(s.y());
}
#endif
<file_sep>/src/view.cpp
#include <view.h>
#include <ncurses.h>
View::View(Entity& fol)
: followed(fol)
{
center(fol.coords);
update_lim = Vector2i(20,5);
Vector2i win_size;
getmaxyx(stdscr, win_size.y(), win_size.x());
y_down_transf = Vector2i(0,win_size.y());
}
void View::center(Vector2i& c){
Vector2i win_size;
getmaxyx(stdscr, win_size.y(), win_size.x());
coords << (c - (win_size / 2)),
(c + (win_size / 2));
}
void View::draw(World& world){
this->draw(world.area);
this->draw(world.player);
}
void View::draw(Entity& entity){
this->drawd(entity);
this->drawd(entity.holding);
}
void View::draw(Area& area){
for(int i = 0; i < area.size(); i++){
drawd(area.at(i));
}
}
void View::drawd(Displayable& d){
Vector2i dend = d.coords + d.graphic.size;
Vector2i clip_orig = d.coords.cwiseMax(this->coords.col(0));
Vector2i clip_end = dend.cwiseMin(this->coords.col(1));
Vector2i vorig = clip_orig - this->coords.col(0);
clip_orig = clip_orig - d.coords;
clip_end = clip_end - d.coords;
//mvprintw(1,0,"clip_orig : (%d,%d), clip_end : (%d,%d)",clip_orig.x(),clip_orig.y(),clip_end.x(), clip_end.y() );
Vector2i proj = vorig;
// TODO :
// '=' is needed there for chunks to load top line of view, should not
for(int i = clip_orig.y(); i < clip_end.y(); i++){
for(int j = clip_orig.x(); j < clip_end.x(); j++){
display(d.graphic[j][i], proj);
proj(0)= proj(0)+1;
}
proj(0) = vorig.x();
proj(1) = proj(1)+1;
}
}
void View::display(Char& c, Vector2i& v){
//mvprintw(2,0,"displaying %c at y : %d, x : %d", c.ch, v.y(), v.x());
//if(c.ch != ' '){
wmove(stdscr,y_down_transf.y()-v.y(),v.x());
addch(c.ch);
//}
}
void View::update(){
Vector2i mov;
Matrix2i a;
a << update_lim,-update_lim;
coords += a;
mov = (followed.coords.cwiseMax(coords.col(1)) - coords.col(1) )
- ( coords.col(0) - followed.coords.cwiseMin(coords.col(0)) );
a << -update_lim+mov, update_lim+mov;
coords += a;
}
/*void View::clip(Displayable displ){
Vec2<int> clip_orig = this->box.orig ;
if(clip_orig.x <= displ.coords.x){
clip_orig.x = Vec2<int>(0,0);
}
else{
clip_orig.x = clip_orig.x - displ.coords.x;
}
if(clip_orig.y <= displ.coords.y){
clip_orig.y = Vec2<int>(0,0);
}
else{
clip_orig.y = clip_orig.y - displ.coords.y;
}
Vec2<int> clip_end = this->box.orig+this->box.size;
Vec2<int> chunk_end = displ.coords + displ.graphic.size;
if(clip_end.x >= chunk_end.x){
clip_end.x = displ.graphic.size;
}
else{
clip_end.x = clip_end.x - displ.coords.x;
}
if(clip_end.y >= chunk_end.y){
clip_end.y = displ.graphic.size;
}
else{
clip_end.y = clip_end.y - displ.coords.y;
}
Vec2<int> proj = this->box.orig - displ.coords; */ /* vector from view orig to bottom left bloc of chunk in Y up coords */
/*
proj = Vec2<int>(this->box.size.y,0) - proj; /* same in Y down (ncurses) coords */
/*
for(int i = clip_orig.y; i < clip_end.y; i++){
for(int j = clip_orig.x; j < clip_end.x; j++){
displ.graphic[i][j].display(proj+Vec2<int>(i,j));
}
}
}
*/
<file_sep>/src/char.cpp
/*
* char.cpp
*
* Created on: 5 mars 2018
* Author: robin
*/
#include <char.h>
Char::Char(char c)
: ch(c), color(0), bcolor(0), under(false), bold(false)
{}
Char::Char()
: ch(' '), color(0), bcolor(0), under(false), bold(false)
{}
<file_sep>/src/player.cpp
/*
* player.cpp
*
* Created on: 4 mars 2018
* Author: robin
*/
#include <player.h>
#include <world.h>
#include <xlib3.h>
#include <chrono>
//#include <ncurses.h>
#define WALK_MVT 1200
Player::Player(World* w) : Entity(w){
this->graphic = Graphic<Char>(Vector2i(1,1));
this->graphic[0][0] = Char('o');
holding.graphic = Graphic<Char>(Vector2i(1,1));
holding.graphic[0][0] = Char('@');
status = Status::standing;
}
void Player::update(){
//TODO :
// when player changes direction, reset acc to 0
// more reactive
// more predictable
if(inputs[X_R]){
this->spawn(0, world->area);
}
react();
std::chrono::duration<float> dtime = std::chrono::duration_cast<std::chrono::duration<float>>(world->ntime - world->time);
vel=Vector2f(max_vel,max_vel+5).cwiseMin( ( acc*dtime.count() ) + vel).cwiseMax(Vector2f(-max_vel,-max_vel-5));
collide(world->area);
pos = pos + dtime.count() * vel;
round_coords();
this->holding.update_coords();
if(this->holding.is_held_down)
world->area.break_block(holding.coords);
Vector2i v = coords + Vector2i(0,-1);
if(world->area.is_solid(v)){
if(status == Status::falling){
stand();
//spawn(coords.x(), world->area);
}
}
else{
//if(!isongrnd(world->area) && status != Status::falling){
if(status != Status::falling ){
fall(0);
}
}
}
void Player::react(){
switch(status){
case Status::standing :
standing();
break;
case Status::walking :
walking();
break;
case Status::jumping :
jumping();
break;
case Status::falling :
falling();
break;
}
this->holding.is_held_down = inputs[X_DOWN];
if(inputs[X_LEFT])
dir = left;
if(inputs[X_RIGHT])
dir = right;
if(inputs[X_UP])
dir = down; // NO
}
void Player::standing(){
if(inputs[X_LEFT])
walk(-WALK_MVT);
if(inputs[X_RIGHT])
walk(WALK_MVT);
if(inputs[X_UP])
jump(0);
if( !(inputs[X_UP]||inputs[X_LEFT]||inputs[X_RIGHT]) )
stand();
}
void Player::walking(){
if(inputs[X_LEFT])
walk(-WALK_MVT);
if(inputs[X_RIGHT])
walk(WALK_MVT);
if(inputs[X_UP])
jump(0);
if( !(inputs[X_UP]||inputs[X_LEFT]||inputs[X_RIGHT]) )
stand();
}
void Player::jumping(){
//falling();
jump(0);
}
void Player::falling(){
if(inputs[X_LEFT])
fall(-200);
if(inputs[X_RIGHT])
fall(200);
if( !(inputs[X_LEFT]||inputs[X_RIGHT]) )
fall(0);
}
void Player::stand(){
status = Status::standing;
pos(1) = (float) coords.y();
vel.setZero();
acc.setZero();
}
void Player::walk(float dir){
status = Status::walking;
acc(0) = dir / this->mass;
}
void Player::jump(float dir){
Vector2i v = Vector2i(0,1)+coords;
if( !world->area.is_solid(v) ) {
status = Status::jumping;
//acc(0)/=4;
vel += Vector2f(dir,5000) / mass;
}
}
void Player::fall(float dir){
status = Status::falling;
acc = ( Vector2f(0,-GRAVITY*80) + Vector2f(dir,0) ) / mass;
}
<file_sep>/concept.md
|l|
|l|
~~~~|T| |T|T|M|M|M|
~~|M| |M|
ll /
ll # o /
~~~~TT TTTTMMMMMMMMMMMM
~~MM MM
->player is represented by "o"
blocks are represented by 2 contiguous letters (stone : "MM", dirt : "TT", water : "~~", tree trunk (wood log) : "ll" etc.)
(?) (wouldn't it be better if it was one wide, since you can scale down into one sized blocks)
you can mine blocks (takes a certain time, fade the block letters to black as you do it)
there are enemies ("#" is a possible one)
<!> you can scale down into a block (represented by a letter (one of them (the one youre standing on) if theres 2)) :
(player is here | )
v
|X|X|X|X|X|X|X| |X|X|X|X|X|X|X|
|X|X|X|X|X|X|X|X| o |X|X|X|X|X|X|X|X|
|X|X|X|X|X|X|X|X|X| |X|X|X|X|X|X|X|X|X|
|X|X|X|X|X|X|X|X|X|X| |X|X|X|X|X|X|X|X|X|X|
|X|X|X|X| |X|X|X|X|X| |X|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|X| |X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|X|X| |X|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|X|X|X| |X|X|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|X|X|X|X| |X|X|X|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|X|X|X|X|X|X|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|X|X|X|X|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|X|X|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
|X|X|X|X| |X|X|X|X|
scaling down makes the player able to collect other ressources, find other things etc
contrary to what is represented above, scaled up versions of blocks (letters) are irregular in shape, in composition of blocks etc.
each scale (normal world, scaled up versions of normal world blocks, scaled up versions of blocks of scaled up versions of normal world blocks, etc.) has a different graphic style that identifies it. For example -1 scale (below normal world scale) blocks are like that : "|X|" while normal world blocks are just letters
maybe also other physics laws, things happening like floating things, hanging things etc bizarre stuff that make (it) you feel like (it is) you really come in another world
another cool mechanic could be that you can modify a block at the scale below in order to change its appearance/properties in the current scale
ex : maybe recognize the shape to make another letter
-> you scale down into a "M" block, you mine its sub-level blocks (the "|X|"), rearrange them to form a "N" letter (good enough to be recognisable) and when you come back to the above scale (here normal world, it is now a "N" block).
(?)(but then what if you make a block take the form of "?" -> Id say, elements (=block types) are only letters, you can modify a block to become any other block type, or maybe enemies "#" and other npc "o" and other things but not "?" and other reserved characters)A block that is not recognisable to any shape would become a ?
-> each letter (block type) could be an "element" having its own properties, uses ...
scaling down into a block of a certain type could be a way to obtain a block of any type (including an "o" (another player (or npc))), by modifying its structure
-> at the below scale, contrary to what is displayed above with the M, blocks making a block type could be different, there could be of multiple types, arranged randomly or not.
(?)(2) but then, do you need to get the exact composition of sub blocks of a block type to make it from another one ? That would make it even more difficult to modify blocks
-> could have a device to inject some sublevel blocks into a block to make it a valid block type. You would get those sublevel blocks with another device to wich you could feed a block to get all its sublevel blocks
-> as this would be very tedious, some tools could be aquired to mine quicker, then maybe mass edit (square, defined rectangles, lines, circle, etc) and maybe eventually to apply a pattern, program (in a real programming lg) a quarry (yes !) (or something)
going down in scale can be done by finding objects in the current scale (and maybe combined with objects of greater scales)
there are different ennemies in each scale
enemies can pursue the player through scales but they remain their original size (maybe by scaling down too for some of them), they are huge (the size of the scaled down block) and move very slowly.
they eat up the current scaled up block as they pursue the player, and this could be a way to modify big chunks of the block quickly although not precisely at all
<!> you can mine blocks (at their scale) you previously modified (at the scale below)
-> you could have a device to make set difference union, etc of 2 mined blocks, to speed up the editing process
it could become basically an ascii art editor,
Questions :
- does each block type (=letter) appear in a specific scale
it must be that way
- solve (?)(2)
kinda done
Issues :
- you would spend all this time modifying blocks at a sublevel, it would be complex and tedious but when you go back to normal world you only get a single block and you think "all of this for THAT"
-> modifying blocks at a sublevel should allow you to modify above level more easily, give you grater powers in the above world
-> there should be worlds above the normal world, with a top world (level) being the god world (with only "G" (god) and "D" (godess) blocks)(sounds cheesy I know)
-> the bottom world should be blocks composed with nothing (?)
-> basically if b is bottom level b should be many . forming b+1 type blocks, then if you scale down into a . you get a single ., and if you dive into that then nothing (?) or you cant (yeah, better solution). you get in top of that . and if you fall, you die (haha)
<file_sep>/include/xlib3.h
/*
* xlib3.h
*
* Created on: 13 mars 2018
* Author: robin
*/
#ifndef INCLUDE_XLIB3_H_
#define INCLUDE_XLIB3_H_
#define X_RIGHT 114
#define X_LEFT 113
#define X_UP 111
#define X_DOWN 116
#define X_R 27
#define X_Q 38
void * read_kbd(void *);
#endif /* INCLUDE_XLIB3_H_ */
<file_sep>/include/world.h
#ifndef SCALE_WORLD
#define SCALE_WORLD
#include <vector>
#include <player.h>
#include <area.h>
#include <terrain.h>
#include <chrono>
#include <ctime>
//#define MAX_HEIGHT 256
#define GRAVITY 9.81
class World {
public:
std::chrono::steady_clock::time_point time;
std::chrono::steady_clock::time_point ntime;
Player player;
Area area; /* loaded part of the world */
Terrain terrain; /* responsible for terrain loading */
void tick();
void load(View&);
void init(View&);
World();
};
#endif
<file_sep>/src/scale.cpp
#include <vector>
#include <view.h>
#include <unistd.h>
#include <ncurses.h>
#include <iostream>
#include <Eigen/Dense>
#include <world.h>
#include <chrono>
#define god(x) x=3;y=12
// Initialize ncurses
int init(){
initscr(); /* Start curses */
raw(); /* Disable line buffering */
noecho(); /* Don't print typed characters */
keypad(stdscr, TRUE); /* Read arrow keys and such */
nodelay(stdscr, TRUE);
curs_set(FALSE);
return 0;
}
World world;
int main(){
init();
bool ch = 0;
View view(world.player);
world.init(view);
int fc = 0;
while(!ch){
world.tick(); /* updates player & mob positions, makes things happen */
view.update(); /* updates the "camera" (view) depending on the player movements */
world.load(view);
view.draw(world); /* actually displays on the terminal what has been loaded */
mvprintw(0,0,"%d", world.time);
mvprintw(1,0,"%d", world.ntime);
mvprintw(2,0,"%d", fc++);
std::chrono::duration<double> dtime = std::chrono::duration_cast<std::chrono::duration<double>>(world.ntime - world.time);
mvprintw(3,0,"%f", dtime.count());
world.time = world.ntime;
//std::vector<input>& in = world.player.inputs;
mvprintw(8,0,"%d,%d,%d,%d", world.player.inputs[113],world.player.inputs[114],world.player.inputs[111],world.player.inputs[116]);
mvprintw(4,0,"(%d,%d)",world.player.coords.x(),world.player.coords.y());
mvprintw(5,0,"(%d,%d)(%d,%d)",view.coords.col(0).x(),view.coords.col(0).y(),view.coords.col(1).x(),view.coords.col(1).y());
mvprintw(6,0,"(%f,%f)(%f,%f)(%f,%f)",world.player.acc.x(),world.player.acc.y(),world.player.vel.x(),world.player.vel.y(),world.player.pos.x(),world.player.pos.y());
mvprintw(7,0,"%d", world.player.status);
//mvprintw(2,0,"%c,%c,%c,%c", in[0].ch,in[1].ch,in[2].ch,in[3].ch);
ch = world.player.inputs[38];
refresh();
//usleep(1000000);
//return 0;
}
endwin(); /* End curses mode */
return 0;
}
//endwin(); /* End curses mode */
// exit(0);
/*
Vec2<int> pl(0,0);
int wsize[2];
int ch;
while((ch = getch()) != 'q'){
switch(ch){
case KEY_LEFT :
pl.x--;
break;
case KEY_RIGHT :
pl.x++;
break;
case KEY_UP :
pl.y--;
break;
case KEY_DOWN :
pl.y++;
break;
}
getmaxyx(stdscr,wsize[0],wsize[1]);
if( pl.x > wsize[1] || pl.x < 0 || pl.y > wsize[0] || pl.y < 0 ){
pl.x = 0;
pl.y = 0;
}
clear();
wmove(stdscr,pl.y,pl.x);
addch('o');
refresh();
usleep(10000);
}*/
//}
<file_sep>/include/char.h
#ifndef SCALE_CHAR
#define SCALE_CHAR
class Char {
public :
char ch;
int color;
int bcolor;
bool under;
bool bold;
Char(char c);
Char();
};
#endif
<file_sep>/include/bloc.h
#ifndef SCALE_BLOC
#define SCALE_BLOC
#include <displayable.h>
class Bloc : public Char {
public:
Bloc(char c): Char(c) {}
Bloc();
Bloc clone();
// TODO : make Displayable have a variable type, that way chunk can be a displayable<Bloc>
// while player is a Displayable<Char>
// that way you can use Bloc functions inside of Chunk
//bool isAir();
};
#endif
<file_sep>/include/entity.h
#ifndef SCALE_ENTITY
#define SCALE_ENTITY
/* Forward declarations */
class Area;
class World;
#include <displayable.h>
#include <Eigen/Dense>
#include <holding.h>
using namespace Eigen;
enum Direction : short {left, right, down, up};
class Entity : public Displayable<Char>
{
public:
Vector2f acc;
Vector2f vel;
Vector2f pos; /* Position in float precision */
/* gets rounded to make the Vector2i coords inherited from Displayable */
float max_vel; /* in char per sec */
unsigned short int mass;
Holding holding;
Direction dir = right;
World* world;
void move(Vector2f);
void update_pos();
void round_coords();
Entity(Vector2f, World*);
Entity(World*);
void spawn(int, Area&);
bool isongrnd(Area&);
void collide(Area&);
};
#endif
<file_sep>/src/controllable.cpp
/*
* controllable.cpp
*
* Created on: 6 mars 2018
* Author: robin
*/
#include <controllable.h>
#include <ncurses.h>
#include "../include/xlib3.h"
#include <pthread.h>
Controllable::Controllable(){
for(int i = 0; i < 128; i++)
inputs[i] = 0;
pthread_t pid;
pthread_create(&pid, NULL, read_kbd, (void*) inputs);
}
<file_sep>/include/chunk.h
#ifndef SCALE_CHUNK
#define SCALE_CHUNK
#include <Eigen/Dense>
#include <displayable.h>
#include <bloc.h>
#define MAX_HEIGHT 256
#define CHUNK_SIZE 16
using namespace Eigen;
class Chunk : public Displayable<Bloc> {
public:
static Vector2i size;
Chunk(Vector2i v) : Displayable(v,size) {};
int ground_y(int x);
};
#endif
<file_sep>/Makefile
#
# Link
#
CFLAGS = -Wall -g
single: obj/scale.o obj/world.o
g++ $(CFLAGS) -lncurses -o $@ obj/scale.o obj/world.o
bin/scale: obj/scale.o obj/entity.o obj/utils.o obj/vec2.o obj/displayable.o obj/world.o
g++ $(CFLAGS) -lncurses -o $@ obj/scale.o obj/utils.o obj/entity.o obj/vec2.o obj/displayable.o obj/world.o
#
# Objets
#
obj/scale.o: src/scale.cpp
g++ $(CFLAGS) -lncurses -I./include -c src/scale.cpp -o obj/scale.o
obj/entity.o: src/entity.cpp
g++ $(CFLAGS) -lncurses -I./include -c src/entity.cpp -o obj/entity.o
obj/utils.o: src/utils.cpp
g++ $(CFLAGS) -lncurses -I./include -c src/utils.cpp -o obj/utils.o
obj/vec2.o: src/vec2.cpp
g++ $(CFLAGS) -lncurses -I./include -c src/vec2.cpp -o obj/vec2.o
obj/displayable.o: src/displayable.cpp
g++ $(CFLAGS) -lncurses -I./include -c src/displayable.cpp -o obj/displayable.o
obj/world.o: src/world.cpp
g++ $(CFLAGS) -lncurses -I./include -c src/world.cpp -o obj/world.o
#
# Remove files
#
clean :
rm obj/*.o bin/*
<file_sep>/src/xlib3.cpp
#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <xlib3.h>
#include <pthread.h>
void * read_kbd(void * in)
{
bool * inputs = (bool *) in;
Display *dpy;
XEvent ev;
char *s;
unsigned int kc;
int quit = 0;
if (NULL==(dpy=XOpenDisplay(NULL))) {
perror("Could not connect to X server");
exit(1);
}
XAutoRepeatOff(dpy);
/*
* You might want to warp the pointer to somewhere that you know
* is not associated with anything that will drain events.
* (void)XWarpPointer(dpy, None, DefaultRootWindow(dpy), 0, 0, 0, 0, x, y);
*/
XGrabKeyboard(dpy, DefaultRootWindow(dpy),
True, GrabModeAsync, GrabModeAsync, CurrentTime);
/* A very simple event loop: start at "man XEvent" for more info. */
/* Also see "apropos XGrab" for various ways to lock down access to
* certain types of info. coming out of or going into the server */
for (;!quit;) {
XNextEvent(dpy, &ev);
switch (ev.type) {
case KeyPress:
kc = ((XKeyPressedEvent*)&ev)->keycode;
s = XKeysymToString(XKeycodeToKeysym(dpy, kc, 0));
/* s is NULL or a static no-touchy return string. */
if (kc) inputs[kc] = 1;
if (!strcmp(s, "q")) quit=~0;
break;
case KeyRelease:
kc = ((XKeyReleasedEvent*)&ev)->keycode;
s = XKeysymToString(XKeycodeToKeysym(dpy, kc, 0));
/* s is NULL or a static no-touchy return string. */
if (kc) inputs[kc] = 0;
if (!strcmp(s, "q")) quit=~0;
break;
case Expose:
/* Often, it's a good idea to drain residual exposes to
* avoid visiting Blinky's Fun Club. */
while (XCheckTypedEvent(dpy, Expose, &ev)) /* empty body */ ;
break;
case ButtonPress:
case ButtonRelease:
case MotionNotify:
case ConfigureNotify:
default:
break;
}
}
XUngrabKeyboard(dpy, CurrentTime);
XAutoRepeatOn(dpy);
if (XCloseDisplay(dpy)) {
perror("Could not close connection to X server");
exit(1);
}
pthread_exit((void*) 0);
return 0;
}
<file_sep>/include/displayable.h
#ifndef SCALE_DISPLAYABLE
#define SCALE_DISPLAYABLE
#include <graphic.h>
#include <Eigen/Dense>
using namespace Eigen;
class Displayable {
public:
Graphic graphic;
Vector2i coords; /* chunk coordinates (world coord)
* if chunk coords are (x,y)
* bloc of coords (0,0) inside the chunk
* has world coord of :
* (x*CHUNK_SIZE,y*CHUNK_SIZE)
*
* (1,1) :
* (x*CHUNK_SIZE+1,y*CHUNK_SIZE+1)
* (x is positive to the right)
* (y is positive going up)
*/
Displayable(Vector2i = Vector2i(0,0));
Displayable(Vector2i, Vector2i);
};
#endif
<file_sep>/include/holding.h
/*
* holding.h
*
* Created on: 14 mars 2018
* Author: robin
*/
#ifndef INCLUDE_HOLDING_H_
#define INCLUDE_HOLDING_H_
class Entity;
enum Direction : short;
#include "displayable.h"
class Holding : public Displayable<Char>
{
public :
Entity& holder;
bool is_held_down;
Holding(Entity&);
void hold_down(Direction);
void hold_up();
void update_coords();
};
#endif /* INCLUDE_HOLDING_H_ */
<file_sep>/README.md
# scale

a minecraft -wannabe-like sandbox game in the terminal, with infinite "terrain" generation
Using ncurses and a bit of Xlib for the input because ncurses inputs are terrible for games
This is very much a work in progress
For now it only features block breaking
## TODO
- Block placing
- Better keymap
- The terrain is a sin()*sin(), i am planning to use perlin noise
- Better controls
- Game design
<file_sep>/include/controllable.h
/*
* controllable.h
*
* Created on: 6 mars 2018
* Author: robin
*/
#ifndef INCLUDE_CONTROLLABLE_H_
#define INCLUDE_CONTROLLABLE_H_
#define MAX_SIMULT_INPUT 5
#include <vector>
#include <ncurses.h>
class Controllable{
public:
bool inputs[128];
Controllable();
};
#endif /* INCLUDE_CONTROLLABLE_H_ */
<file_sep>/src/area.cpp
#include <area.h>
#include <view.h>
#include <terrain.h>
#include <stdlib.h>
#include <unistd.h>
#include <bloc.h>
Area::Area(){
}
void Area::load(View& v, Terrain& t){
if(this->empty()){
int orig = v.coords(0,0) / CHUNK_SIZE;
int size = v.coords(0,1) / CHUNK_SIZE;
for(int i = orig-2; i <= size+2; i++){
push_back( Chunk(Vector2i(i*16,0)) );
t.load(this->back());
}
}
else{
int orig = v.coords(0,0) - ( v.coords(0,0) % CHUNK_SIZE );
int size = v.coords(0,1) - ( v.coords(0,1) % CHUNK_SIZE );
//fprintf(stderr,"s: %d o: %d",size + CHUNK_SIZE *2, orig - CHUNK_SIZE *2);
while(this->front().coords.x() != (orig - CHUNK_SIZE *2) ){
//fprintf(stderr,"%d a) %d, %d",v.followed.world->time,this->front().coords.x(),orig - CHUNK_SIZE *2);
//usleep(1000000);
if( this->front().coords.x() > (orig - CHUNK_SIZE *2) ){
push_front( Chunk(Vector2i(this->front().coords.x() - CHUNK_SIZE ,0)) );
t.load(this->front());
}
else {
pop_front();
}
}
while(this->back().coords.x() != (size + CHUNK_SIZE *2) ){
//fprintf(stderr,"b) %d, %d",this->back().coords.x(),(size + CHUNK_SIZE *2) );
//usleep(1000000);
if( this->back().coords.x() < (size + CHUNK_SIZE *2) ){
push_back( Chunk(Vector2i(this->back().coords.x() + CHUNK_SIZE ,0)) );
t.load(this->back());
}
else {
pop_back();
}
}
}
}
bool Area::is_loaded(int x){
int orig = this->front().coords.x();
int end = this->back().coords.x();
return x >= orig && x <= end+CHUNK_SIZE;
}
Vector2i Area::get_spawnable(int x){
int orig = this->front().coords.x();
orig = abs( x - orig ) / CHUNK_SIZE;
int offset = x % CHUNK_SIZE;
Chunk& sp = this->at(orig);
// TODO : make sure there is vertical space to spawn ( if entity.graphic.size > (1,1) )
return Vector2i(x,this->at(orig).ground_y(abs(offset)));
}
bool Area::is_solid(Vector2i& v){
if(!is_loaded(v.x()))
return false;
int orig = this->front().coords.x();
orig = abs( orig - v.x());
int offset = orig % CHUNK_SIZE;
orig/= CHUNK_SIZE;
return this->at(orig).graphic[abs(offset)][v.y()].ch != ' ';
}
Bloc Area::break_block(Vector2i& v){
if(is_loaded(v.x())){
int orig = this->front().coords.x();
orig = abs( v.x() - orig );
int offset = orig % CHUNK_SIZE;
orig/= CHUNK_SIZE;
Bloc broken = this->at(orig).graphic[abs(offset)][v.y()].clone();
this->at(orig).graphic[abs(offset)][v.y()] = Bloc(' ');
return broken;
}
}
// TODO : make a get_chunk and a get_block function
|
fc119de02725431760f67f6629cd57f719562f30
|
[
"Markdown",
"C",
"Makefile",
"C++"
] | 30
|
C++
|
w-v/scale
|
5b6701e7937c54f637a2dabf872cd7e14575e2c8
|
74fff1fbdaa750b8bdd4e7ba4ff5b0e3d383f96f
|
refs/heads/master
|
<repo_name>anirudhasj441/SNAKE-GAME<file_sep>/SNAKE GAME/newfile.py
import random , os
import pygame
pygame.init()
x=540
y=960
DISPLAYSURF=pygame.display.set_mode((x,y))
pygame.display.set_caption('snake game')
bg=(0,0,0)
BLUE=(0,0,255)
white=(255,255,255)
red=(255,0,0)
font=pygame.font.SysFont( None ,30)
font1=pygame.font.SysFont( None ,39)
font3=pygame.font.SysFont( None ,10)
def text_screen(text,colour,x1,y1):
screen_text=font.render(text, True ,colour)
DISPLAYSURF.blit(screen_text,(x1,y1))
def txt(text,colour,x1,y1):
screen_text=font1.render(text, True ,colour)
DISPLAYSURF.blit(screen_text,(x1,y1))
def text_objects(text, font):
textSurface = font.render(text, True, bg)
return textSurface, textSurface.get_rect()
def button(msg, x, y, w, h, ic, ac, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
# pygame.draw.rect(DISPLAYSURF, ac, (x, y, w, h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(DISPLAYSURF, ic, (x, y, w, h))
smallText = pygame.font.SysFont("comicsansms", 20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x + (w / 2)), (y + (h / 2)))
DISPLAYSURF.blit(textSurf, textRect)
gs=False
while not gs:
DISPLAYSURF.fill(white)
txt('WELCOME TO SNAKE GAME',bg,0,100)
text_screen('PRESS ENTER TO PLAY',red,100,150)
for event in pygame.event.get():
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_RETURN:
gs=True
pygame.display.update()
def gameloop():
rex=100
rey=270
size=20
fps=20
clock=pygame.time.Clock()
velx=0
vely=0
score=0
vel=3
ge=False
go=False
while True:
fx=random.randint(10,x//2)
fy=random.randint(10,550)
if fx>(100-60) and fx<(100+60) and fy>=100 and fy<=200:
continue
elif fx>(400-60) and fx<(400+60) and fy>=200 and fy<=300:
continue
elif fy>(100-60) and fy<(100+60) and fx>=100 and fy<=400:
continue
elif fy>(200-60) and fy<(200+60) and fx>=100 and fy<=400:
continue
elif fy>(300-60) and fy<(300+60) and fx>=100 and fy<=400:
continue
else:
break
if os.path.exists('highscore.txt'):
with open('highscore.txt','r') as f1:
highscore=f1.read()
else:
with open('highscore.txt','w') as f1:
f1.write(0)
snk_list=[]
snk_length=1
def plot_snk(DISPLAYSURF,colour,snk_list,sizex,sizey):
for x,y in snk_list:
pygame.draw.rect(DISPLAYSURF,colour,(x,y,sizex,sizey))
while not ge:
for event in pygame.event.get():
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_RIGHT or event.key==pygame.K_6:
velx=vel
vely=0
if event.key==pygame.K_LEFT or event.key==pygame.K_4:
velx=-vel
vely=0
if event.key==pygame.K_UP or event.key==pygame.K_8:
vely=-vel
velx=0
if event.key==pygame.K_DOWN or event.key==pygame.K_2:
vely=vel
velx=0
if event.key==pygame.K_SPACE:
velx=0
vely=0
def right():
velx=vel
vely=0
def left():
velx=-vel
vely=0
def up():
vely=-vel
velx=0
def down():
vely=vel
velx=0
if abs(rex-fx)<=6 and abs(rey-fy)<=6:
score+=10
fx=random.randint(10,x/2)
fy=random.randint(10,550)
snk_length+=3
vel+=1
if rey>600:
rey=0
if rey<0:
rey=600
if rex>x:
rex=0
if rex<0:
rex=x
if rey>(300-30) and rey<(300+10) and rex>=100 and rex<=400:
go=True
if rey>(100-30) and rey<(100+10) and rex>=100 and rex<=400:
go=True
if rey>(200-30) and rey<(200+10) and rex>=100 and rex<=400:
go=True
if rex>(100-30) and rex<(100+10) and rey>=100 and rey<=200:
go=True
if rex>(400-30) and rex<(400+10) and rey>=200 and rey<=300:
go=True
rex=rex+velx
rey=rey+vely
DISPLAYSURF.fill(bg)
pygame.draw.rect(DISPLAYSURF,red,(fx,fy,size,size))
plot_snk(DISPLAYSURF,white,snk_list,size,size)
pygame.draw.line(DISPLAYSURF,white,(0,600),(540,600),20)
pygame.draw.line(DISPLAYSURF,white,(0,0),(0,600),20)
pygame.draw.line(DISPLAYSURF,white,(0,0),(540,0),20)
pygame.draw.line(DISPLAYSURF,white,(540,0),(540,600),20)
pygame.draw.line(DISPLAYSURF,BLUE,(100,100),(400,100),20)
pygame.draw.line(DISPLAYSURF,BLUE,(100,200),(400,200),20)
pygame.draw.line(DISPLAYSURF,BLUE,(100,300),(400,300),20)
pygame.draw.line(DISPLAYSURF,BLUE,(100,100),(100,200),20)
pygame.draw.line(DISPLAYSURF,BLUE,(400,200),(400,300),20)
text_screen("SCORE:"+str(score),red,50,50)
text_screen("HIGH SCORE:"+str(highscore),red,50,25)
if go==True:
if score> int(highscore):
highscore=score
with open('highscore.txt','w') as f2:
f2.write(str(highscore))
DISPLAYSURF.fill(white)
txt("game over",red,120,350)
text_screen("SCORE:"+str(score)+' HIGH SCORE:'+str(highscore),red,80,400)
text_screen('PRESS ENTER TO QUIT',red,145,450)
for event in pygame.event.get():
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_RETURN:
ge=True
if event.key==pygame.K_SPACE:
gameloop()
head=[]
head.append(rex)
head.append(rey)
snk_list.append(head)
if len(snk_list)>snk_length:
del snk_list[0]
if head in snk_list[:-1]:
go=True
pygame.display.update()
clock.tick(fps)
gameloop()
|
d480520ae6d6f2c1924f6a3d8b328bd273b855d9
|
[
"Python"
] | 1
|
Python
|
anirudhasj441/SNAKE-GAME
|
83718db6f72ffdf162a6b86d5fcfe1cb872730f3
|
03c0692a0f5c9df3dcd60a1d62d8216c62448330
|
refs/heads/master
|
<file_sep>package stepDefinition;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class LoginTest {
@Given("^I open the chrome browser$")
public void i_open_the_chrome_browser() {
System.out.println("This is a maven project");
}
@Given("^I go to salesforce home page$")
public void i_go_to_salesforce_home_page() {
System.out.println("This is a maven project");
}
@Given("^I enter username$")
public void i_enter_username() {
System.out.println("This is a maven project");
}
@Given("^I enter password$")
public void i_enter_password() {
System.out.println("This is a maven project");
}
@When("^I click the login button$")
public void i_click_the_login_button() {
System.out.println("This is a maven project");
}
@Then("^I see the dashboard$")
public void i_see_the_dashboard() {
System.out.println("This is a maven project");
}
}
|
d82124fbfe777cf61c5eb3b0981dd0d6a7afa879
|
[
"Java"
] | 1
|
Java
|
MansoorMehfooz/Mansoor-Repository
|
1b70d40828c2effd32304b39d61a24fb577aeb1d
|
0f5ccffcca16fa42b309737be40e9bdac99c2ee9
|
refs/heads/master
|
<file_sep>import os
from setuptools import setup
module_path = os.path.join(os.path.dirname(__file__), 'flask_zipkin.py')
version_line = [line for line in open(module_path)
if line.startswith('__version_info__')][0]
__version__ = '.'.join(eval(version_line.split('__version_info__ = ')[-1]))
with open('README.md', 'r') as f:
long_description = f.read()
setup(
name='Flask-Zipkin',
version=__version__,
url='https://github.com/qiajigou/flask-zipkin',
license='BSD',
author='killpanda',
author_email='<EMAIL>',
description='An zipkin extension for Flask based on py_zipkin.',
long_description=long_description,
long_description_content_type='text/markdown',
py_modules=['flask_zipkin'],
zip_safe=False,
platforms='any',
test_suite='test_flask_zipkin',
install_requires=[
'Flask',
'py_zipkin>=0.13.0',
'requests>=2.11.1',
]
)
|
73012482ca28efe7b1a5380f8c424ea200e535b2
|
[
"Python"
] | 1
|
Python
|
timgates42/flask-zipkin
|
933f84d759827745d824701a3ccdfe7b329aaf56
|
a5f7f8d0a153d1594359b45b103b317f86490641
|
refs/heads/master
|
<repo_name>BlueDG/Practice-with-React<file_sep>/src/App.js
import React, { useState } from "react";
import Counter from "./Counter";
import CounterHooks from "./CounterHooks";
export const Theme = React.createContext();
export default function App() {
const [theme, setTheme] = useState("lightblue");
return (
<>
<Theme.Provider value={{ backgroundColor: theme }}>
<Counter initialValue={0} />
<CounterHooks initialValue={0} />
<button
onClick={() =>
setTheme(prevTheme => {
return prevTheme === "lightblue" ? "red" : "lightblue";
})
}
>
Change button color
</button>
</Theme.Provider>
</>
);
}
<file_sep>/README.md
Practicing with hooks, context and classes.
|
e6f742033bee32ab8647753ffdf734c73480cd60
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
BlueDG/Practice-with-React
|
2557f68812a94d2ffec988274b09ae306b6c2fc3
|
0777c104e4ec1acd4c05138bc83a66acb75081fa
|
refs/heads/main
|
<file_sep>import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Params } from '@angular/router';
import { BookService } from '../../services/book.service';
import { setPageTitle } from '../utils';
@Component({
selector: 'app-edit-book',
templateUrl: './edit-book.component.html',
})
export class EditBookComponent implements OnInit {
constructor(public bookService: BookService, private _route: ActivatedRoute, title: Title) {
setPageTitle(title, 'редактирование книги');
}
ngOnInit(): void {
this._route.params.subscribe((params: Params) => {
this.bookService.getBook(params.id);
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { BookService } from 'src/app/services/book.service';
import { setPageTitle } from '../utils';
@Component({
selector: 'app-create-book',
templateUrl: './create-book.component.html',
})
export class CreateBookComponent implements OnInit {
constructor(public bookService: BookService, title: Title) {
setPageTitle(title, 'добавление книги');
}
ngOnInit(): void {
this.bookService.resetBookData();
}
}
<file_sep>import { Component, EventEmitter, Input, Output, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-backdrop',
templateUrl: './backdrop.component.html',
styleUrls: ['./backdrop.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class BackdropComponent {
@Input() conditionForOpen: boolean;
@Output() onClose = new EventEmitter<() => void>();
constructor() {}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CreateBookComponent } from './pages/create-book/create-book.component';
import { EditBookComponent } from './pages/edit-book/edit-book.component';
import { MainComponent } from './pages/main/main.component';
import { NotFoundComponent } from './pages/not-found/not-found.component';
import { AuthGuard } from './services/auth.guard';
const routes: Routes = [
{ path: '', component: MainComponent },
{ path: 'createBook', component: CreateBookComponent, canActivate: [AuthGuard] },
{ path: 'editBook/:id', component: EditBookComponent, canActivate: [AuthGuard] },
{ path: '**', component: NotFoundComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
<file_sep>import * as bcrypt from 'bcryptjs';
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, DocumentSnapshot } from '@angular/fire/firestore';
import { AngularFireStorage } from '@angular/fire/storage';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { mapData, findUsers } from './utils';
import { IBook, IUpdatedBookField, IUser } from './interfaces';
@Injectable({
providedIn: 'root',
})
export class FirebaseService {
private _connectionToBooks$: AngularFirestoreCollection<IBook>;
private _connectionToUsers$: AngularFirestoreCollection<IUser>;
constructor(_firestore: AngularFirestore, private _storage: AngularFireStorage) {
this._connectionToBooks$ = _firestore.collection<IBook>('books');
this._connectionToUsers$ = _firestore.collection<IUser>('users');
}
fetchAllBooks(): Observable<IBook[]> {
return this._connectionToBooks$.snapshotChanges().pipe(
map((resp) => mapData(resp) as IBook[]),
catchError((error) => throwError(error))
);
}
fetchBook(id: string): Observable<IBook> {
return this._connectionToBooks$
.doc(id)
.get()
.pipe(
map((resp) => mapData(resp as DocumentSnapshot<IBook>) as IBook),
catchError((error) => throwError(error))
);
}
async createBook(newBook: IBook): Promise<void> {
await this._connectionToBooks$.add(newBook);
}
async updateBook(bookId: string, newData: IUpdatedBookField): Promise<void> {
await this._connectionToBooks$.doc(bookId).update(newData);
}
async removeBook(bokId: string): Promise<void> {
await this._connectionToBooks$.doc(bokId).delete();
}
async uploadImg(file: File, bookId: string): Promise<void> {
const data = await this._storage.upload(file.name, file),
imgSrc = await data.ref.getDownloadURL();
await this._connectionToBooks$.doc(bookId).update({ imgSrc });
}
async auth(login: string, password: string): Promise<IUser> {
const user = (await findUsers(this._connectionToUsers$, login))[0],
passwordIsValid = await bcrypt.compare(password, user.password);
if (user && passwordIsValid && user.login === login) {
return user;
}
throw new Error('Невалидные данные!');
}
async createUser(userData: IUser): Promise<IUser> {
const { login } = userData,
users = await findUsers(this._connectionToUsers$, login);
if (!users.length) {
const newUserData: IUser = {
...userData,
password: await bcrypt.hash(userData.password, 5),
},
newUser = await (await this._connectionToUsers$.add(newUserData)).get();
return { id: newUser.id, ...newUser.data() } as IUser;
} else {
throw new Error('Такой пользователь уже существует !');
}
}
}
<file_sep>import { Component, ElementRef, HostListener, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { AbstractControl, FormGroup } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { createEmailControl, createPasswordControl, createLogInControl } from './utils';
@Component({
selector: 'app-auth',
templateUrl: './auth.component.html',
styleUrls: ['./auth.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class AuthComponent implements OnInit {
title: 'Регистрация' | 'Авторизация' = 'Авторизация';
logInForm: FormGroup;
registrationForm: FormGroup;
@ViewChild('track') private _track: ElementRef<HTMLElement>;
constructor(public authService: AuthService) {}
ngOnInit(): void {
this.logInForm = new FormGroup({
login: createLogInControl(),
password: create<PASSWORD>Control(),
});
this.registrationForm = new FormGroup({
email: createEmailControl(),
password: createPasswordControl(),
login: createLogInControl(),
});
}
openRegistration(): void {
this.title = 'Регистрация';
this._track.nativeElement.style.transform = 'translateX(-100%)';
}
closeRegistration(): void {
this.title = 'Авторизация';
setTimeout(() => (this._track.nativeElement.style.transform = 'translateX(0)'), 300);
}
closeAuthPanel(): void {
this.authService.openAuthPanel = false;
this.closeRegistration();
this.logInForm.reset();
this.registrationForm.reset();
}
async submitLogin(): Promise<void> {
try {
const { login, password } = this.logInForm.value;
await this.authService.login(login, password);
this.closeAuthPanel();
} catch (error) {
this.setErrors(this.logInForm.controls);
}
}
async submitRegistration(): Promise<void> {
try {
await this.authService.registration(this.registrationForm.value);
this.closeAuthPanel();
} catch (error) {
this.setErrors(this.registrationForm.controls);
}
}
@HostListener('window:scroll')
private onScroll(): void {
if (window.scrollY > 0 && window.innerWidth > 575) {
this.authService.openAuthPanel = false;
}
}
private setErrors(controls: { [key: string]: AbstractControl }): void {
for (const key in controls) {
controls[key].setErrors({
invalidField: true,
});
}
}
}
<file_sep>import { FormControl, ValidatorFn, Validators } from '@angular/forms';
export const createEmailControl = (...extraValidators: ValidatorFn[]) =>
new FormControl('', [Validators.email, Validators.required, ...extraValidators]);
export const createPasswordControl = (...extraValidators: ValidatorFn[]) =>
new FormControl('', [Validators.required, Validators.minLength(6), ...extraValidators]);
export const createLogInControl = (...extraValidators: ValidatorFn[]) =>
new FormControl('', [Validators.required, ...extraValidators]);
<file_sep>import { Component, HostListener, OnInit, ViewEncapsulation } from '@angular/core';
import { faPlus, faSignOutAlt, faUser } from '@fortawesome/free-solid-svg-icons';
import { AuthService } from '../../services/auth.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class HeaderComponent implements OnInit {
faUser = faUser;
faSignOut = faSignOutAlt;
faPlus = faPlus;
screenWidth = window.innerWidth;
constructor(public authService: AuthService) {}
ngOnInit(): void {}
@HostListener('window:resize', ['$event.target'])
private onResize(window: Window): void {
this.screenWidth = window.innerWidth;
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { HttpClientModule } from '@angular/common/http';
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { AngularFireStorageModule } from '@angular/fire/storage';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component';
import { MainComponent } from './pages/main/main.component';
import { EditBookComponent } from './pages/edit-book/edit-book.component';
import { CreateBookComponent } from './pages/create-book/create-book.component';
import { NotFoundComponent } from './pages/not-found/not-found.component';
import { AuthComponent } from './components/auth/auth.component';
import { BackdropComponent } from './components/backdrop/backdrop.component';
import { InvalidMessageComponent } from './components/auth/invalid-message/invalid-message.component';
import { environment } from '../environments/environment';
import { LoaderDataComponent } from './components/loader-data/loader-data.component';
import { BookRedactorComponent } from './components/book-redactor/book-redactor.component';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
MainComponent,
EditBookComponent,
CreateBookComponent,
NotFoundComponent,
AuthComponent,
BackdropComponent,
InvalidMessageComponent,
LoaderDataComponent,
BookRedactorComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FontAwesomeModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule,
AngularFireStorageModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
<file_sep>export interface IUser {
id?: string;
login: string;
email: string;
password: string;
}
export interface IBook {
id?: string;
// imgSrc: string;
title: string;
publishingYear: number;
ISBN: string;
author: string;
creator: string;
}
export interface IUpdatedBookField {
title?: string;
publishingYear?: number;
ISBN?: string;
author?: string;
}
export interface IDataForUpdateBook {
bookId: string;
dataForUpdate: IUpdatedBookField;
}
<file_sep>import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-loader-data',
templateUrl: './loader-data.component.html',
styleUrls: ['./loader-data.component.scss'],
})
export class LoaderDataComponent implements OnInit {
@Input() loading: boolean;
@Input() funcForLoading: () => void | null = null;
constructor() {}
ngOnInit(): void {
if (this.funcForLoading) {
this.funcForLoading();
}
}
}
<file_sep>import { Title } from '@angular/platform-browser';
import { environment } from '../../environments/environment';
export const setPageTitle = (title: Title, pageName: string): void => {
title.setTitle(`${environment.siteName} | ${pageName}`);
};
<file_sep>import { Injectable } from '@angular/core';
import { async } from 'rxjs/internal/scheduler/async';
import { FirebaseService } from './firebase.service';
import { IUser } from './interfaces';
@Injectable({
providedIn: 'root',
})
export class AuthService {
private _user: IUser;
private _openAuthPanel = false;
private _isAuth = false;
constructor(private _firebaseService: FirebaseService) {}
get user(): IUser {
return this._user;
}
get isAuth(): boolean {
return this._isAuth;
}
get openAuthPanel(): boolean {
return this._openAuthPanel;
}
set openAuthPanel(newState: boolean) {
this._openAuthPanel = newState;
}
toggleAuthPenel(): void {
this._openAuthPanel = !this._openAuthPanel;
}
login = async (login: string, password: string): Promise<void> => {
const user = await this._firebaseService.auth(login, password);
this.auth(user);
};
registration = async (newUserData: IUser): Promise<void> => {
const newUser = await this._firebaseService.createUser(newUserData);
this.auth(newUser);
};
logOut(): void {
this._user = {
login: '',
password: '',
email: '',
};
this._isAuth = false;
localStorage.removeItem('userData');
}
chekAuth(): void {
const userData = localStorage.getItem('userData');
if (userData) {
this._isAuth = true;
this._user = JSON.parse(userData);
}
}
private auth(user: IUser): void {
this._isAuth = true;
this._user = user;
localStorage.setItem('userData', JSON.stringify(user));
}
}
<file_sep>import { AngularFirestoreCollection, DocumentChangeAction, DocumentSnapshot } from '@angular/fire/firestore';
import { IUser } from './interfaces';
export const mapData = <T>(data: DocumentChangeAction<T>[] | DocumentSnapshot<T>) => {
if (data instanceof Array) {
return data.map((el: DocumentChangeAction<T>) => {
const mappedData = el.payload.doc.data() as T,
id = el.payload.doc.id;
return { id, ...mappedData };
});
} else {
const mappedData = data.data() as T,
id = data.id;
return { id, ...mappedData };
}
};
export const findUsers = async (connection: AngularFirestoreCollection<IUser>, login: string): Promise<IUser[]> => {
const response = await connection.ref.where('login', '==', login).get();
return response.docs.map((user) => ({ id: user.id, ...user.data() } as IUser));
};
export const initialBookState = {
title: '',
author: '',
imgSrc: '',
publishingYear: null,
ISBN: '',
creator: '',
};
<file_sep>import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons';
import { AuthService } from 'src/app/services/auth.service';
import { BookService } from 'src/app/services/book.service';
import { BooksService } from 'src/app/services/books.service';
import { IBook, IUpdatedBookField } from '../../services/interfaces';
import { createFormControl } from './utils';
type DataForSubmit = IBook | { bookId: string; dataForUpdate: IUpdatedBookField };
@Component({
selector: 'app-book-redactor',
templateUrl: './book-redactor.component.html',
styleUrls: ['./book-redactor.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class BookRedactorComponent implements OnInit {
faArrowLeft = faArrowLeft;
formIsInvalid: boolean;
bookForm: FormGroup;
@Input() type: 'create' | 'edit';
@Input() funcForSubmit: (dataForUpdate: DataForSubmit) => Promise<void>;
constructor(
private _authService: AuthService,
private _roter: Router,
private _booksServise: BooksService,
public bookService: BookService
) {}
ngOnInit(): void {
const defaultValidator = this.type === 'create' ? Validators.required : Validators.nullValidator;
this.formIsInvalid = this.type === 'edit' ? true : false;
this.bookForm = new FormGroup({
title: createFormControl(defaultValidator),
publishingYear: createFormControl(defaultValidator),
ISBN: createFormControl(
defaultValidator,
Validators.pattern(/(978|979)[ |-][0-9]{1,5}[ |-][0-9]{1,7}[ |-][0-9]{1,7}[0-9]{1}/)
),
author: createFormControl(defaultValidator),
});
}
async submit(): Promise<void> {
try {
let dataForSubmit: DataForSubmit;
const formValue = this.bookForm.value,
alertMsg =
this.type === 'create'
? ` ${this.bookForm.value.title} успешно создана`
: `${this.bookService.book.title} успешно обновлена`;
for (const key in formValue) {
if (!formValue[key]) {
delete formValue[key];
}
}
if (this.type === 'create') {
dataForSubmit = { ...this.bookForm.value, creator: this._authService.user.login };
} else {
dataForSubmit = { bookId: this.bookService.book.id, dataForUpdate: this.bookForm.value };
}
await this.funcForSubmit(dataForSubmit);
this._booksServise.getAllBooks();
this._roter.navigate(['/']);
alert(`Книга ${alertMsg}`);
} catch (error) {
alert(`Ошибка ${error} попробуте перезагурзить страницу`);
}
}
async removeBook(): Promise<void> {
try {
await this.bookService.removeBook(this.bookService.book.id);
alert('Книга успешно удалена!');
this._booksServise.getAllBooks();
this._roter.navigate(['/']);
} catch (error) {
alert(`Ошибка ${error} попробуте перезагурзить страницу`);
}
}
}
<file_sep>import { Injectable } from '@angular/core';
import { FirebaseService } from './firebase.service';
import { IBook } from './interfaces';
@Injectable({
providedIn: 'root',
})
export class BooksService {
private _loading = true;
private _books: IBook[] = [];
constructor(private _firebaseService: FirebaseService) {}
get books(): IBook[] {
return this._books;
}
get loading(): boolean {
return this._loading;
}
getAllBooks = (): void => {
this._firebaseService.fetchAllBooks().subscribe((books) => {
this._loading = false;
this._books = books;
});
};
}
<file_sep>export const environment = {
production: true,
siteName: 'Каталог книг',
firebaseConfig: {
apiKey: '<KEY>',
authDomain: 'book-catalog-f262a.firebaseapp.com',
databaseURL: 'https://book-catalog-f262a.firebaseio.com',
projectId: 'book-catalog-f262a',
storageBucket: 'book-catalog-f262a.appspot.com',
messagingSenderId: '812181493662',
appId: '1:812181493662:web:ceb6b27f966fec51a3e88f',
},
};
<file_sep>import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { setPageTitle } from '../utils';
import { BooksService } from '../../services/books.service';
import { AuthService } from '../../services/auth.service';
import { BookService } from 'src/app/services/book.service';
@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.scss'],
})
export class MainComponent implements OnInit {
imgSrc: string;
constructor(
public booksService: BooksService,
public authService: AuthService,
private _bookServise: BookService,
title: Title
) {
setPageTitle(title, 'главная');
}
ngOnInit(): void {}
async removeBook(id: string): Promise<void> {
try {
await this._bookServise.removeBook(id);
this.booksService.getAllBooks();
} catch (error) {
alert(`Ошибка ${error} попробуйте перезагурзить страницу`);
}
}
}
<file_sep># BookCatalog
Тестовое задание для "Золотой стажировки" по JavaScript
## Использование
Для начала работы с приложением необходимо:
1. Клонировать репозиторий
1. Уставновить все зависимости `npm install`
1. Запустить проект `npm start`
## Деплой
Для использования приложения в production версии необходимо:
1. Выполнить команду `npm run build`
1. Использовать файлы из папки "dist"
## Деплой Firebase
Для деплоя приложения на Firebase необходимо:
1. Выполнить команду `npm run build`
1. Если не установлен Firebase, выполнить команду `npm install -g firebase-tools`
1. Выполнить команду `firebase deploy`
## Посмотреть результат работы над проектом можно [тут](https://book-catalog-f262a.web.app/)
### Приложение размещено с помощью хостинга Firebase
<file_sep>import { Injectable } from '@angular/core';
import { FirebaseService } from './firebase.service';
import { IBook, IDataForUpdateBook } from './interfaces';
import { initialBookState } from './utils';
@Injectable({
providedIn: 'root',
})
export class BookService {
private _loading = true;
private _book: IBook = initialBookState;
constructor(private _firebaseService: FirebaseService) {}
get loading(): boolean {
return this._loading;
}
get book(): IBook {
return this._book;
}
getBook = (id: string): void => {
this._loading = true;
this._firebaseService.fetchBook(id).subscribe((book) => {
this._loading = false;
this._book = book;
});
};
createBook = async (newBook: IBook): Promise<void> => {
await this._firebaseService.createBook(newBook);
};
removeBook = async (bookId: string): Promise<void> => {
await this._firebaseService.removeBook(bookId);
};
updateBook = async (dataForUpdate: IDataForUpdateBook) => {
await this._firebaseService.updateBook(dataForUpdate.bookId, dataForUpdate.dataForUpdate);
};
resetBookData(): void {
this._book = initialBookState;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { setPageTitle } from '../utils';
@Component({
selector: 'app-not-found',
templateUrl: './not-found.component.html',
})
export class NotFoundComponent implements OnInit {
constructor(title: Title) {
setPageTitle(title, '404');
}
ngOnInit(): void {}
}
<file_sep>import { FormControl, Validators, ValidatorFn } from '@angular/forms';
import { IBook } from 'src/app/services/interfaces';
export const createFormControl = (...validators: ValidatorFn[]) => new FormControl('', [...validators]);
export const notNewValue = (oldValue: IBook) => {
return (control: FormControl): { [key: string]: boolean } => {
for (const key in oldValue) {
if (oldValue[key] === control.value) {
return {
notNew: true,
};
}
}
};
};
|
9bc363180f4c69564e2cf1cc61af67b778563afd
|
[
"Markdown",
"TypeScript"
] | 22
|
TypeScript
|
Dan4ykS/book-catalog
|
6b6efaba4f9fafa8c49004893e3b62b1a50781d4
|
7d8b6274d294449fdc31cf583fbfa07bab1e99b6
|
refs/heads/master
|
<repo_name>elelias/CompuInvesting<file_sep>/strategySearch.py
#maketsim.py
#function for the first quizz:
import sys
# QSTK Imports
import QSTK.qstkutil.qsdateutil as du
import QSTK.qstkutil.tsutil as tsu
import QSTK.qstkutil.DataAccess as da
# Third Party Imports
import datetime as dt
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import copy
from simulate import *
from eventProfiler import *
from marketsim import *
def AddOrder(num,date,symbol,action,size,dfOrders):
'''builds an order, which is a series object'''
#if an event is found, buy 100 shares
# sell them after 5 days
series=pd.Series([symbol,action,size,date],index=['symbol','order','size','mydate'] ,name=num)
newdict={}
newdict['symbol']=pd.Series(symbol,index=[num])
newdict['order']=pd.Series(action,index=[num])
newdict['size']=pd.Series(size,index=[num])
newdict['mydate']=pd.Series(date,index=[num])
newFrame=pd.DataFrame(newdict)
#print 'the series is ',series
dfOrders=dfOrders.append(newFrame)
#print dfOrders
#raw_input('')
return dfOrders
#pass
def initializeOrders():
#df=pd.DataFrame(columns=['symbol','order','size','mydate'])
myd={}
myd['symbol']=pd.Series([0],index=[0])
myd['order']=pd.Series('nothing',index=[0])
myd['size']=pd.Series([0],index=[0])
myd['mydate']=pd.Series(dt.datetime(1981,2,1),index=[0])
df=pd.DataFrame(myd)
return df
def getOrdersFromStrategy(dt_start,dt_end):
'''applies a strategy'''
ls_name='sp5002012'
StockQuantity=100
#INITIALIZE THE ORDERS DATA FRAME
dfOrders=initializeOrders()
#
#
#print 'before getEvents'
#GET THE EVENTS
dfEvents,d_data=getEvents(dt_start,dt_end,ls_name)
#valid trading days
dt_timeofday = dt.timedelta(hours=16)
listdays = du.getNYSEdays(dt_start, dt_end, dt_timeofday)
#
#
#CONSTRUCT THE ORDERS WHEN AN EVENT IS FOUND
nfound=0
orderNum=0
print 'before loop'
for idx,series in dfEvents.iterrows():
for sym,value in series.iteritems():
#print 'progress? ',idx,sym,value
if value==1:
nfound+=1
#
#
#==BUILD THE ORDERS
orderNum+=1
dfOrders=AddOrder(orderNum,idx,sym,'Buy',StockQuantity,dfOrders)
#
#
#sellDate=idx+dt.timedelta(5)
#count five days
for ind,date in enumerate(listdays):
if date==idx:
if ind+6<=len(listdays):
sellDate=listdays[ind+5]
else :
sellDate=dt_end
#
#
#
#
orderNum+=1
dfOrders=AddOrder(orderNum,sellDate,sym,'Sell',StockQuantity,dfOrders)
dfOrders=dfOrders[1:]
dfSorted=dfOrders.sort('mydate')
return dfOrders
#print 'here I find ',nfound
if __name__=='__main__':
dt_start = dt.datetime(2008, 1, 1)
dt_end = dt.datetime(2009, 12, 31)
dfOrders=getOrdersFromStrategy(dt_start,dt_end)
#print 'head'
#print dfOrders.head()
startingCash=50000
benchmarkSym='$SPX'
marketSimulation(dt_start,dt_end,startingCash,benchmarkSym,dfOrders)
<file_sep>/simulate.py
#function for the first quizz:
import sys
# QSTK Imports
import QSTK.qstkutil.qsdateutil as du
import QSTK.qstkutil.tsutil as tsu
import QSTK.qstkutil.DataAccess as da
# Third Party Imports
import datetime as dt
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def Compute(close_norm,allocations):
#normalized value of portfolio
np_alloc=np.array(allocations)
valuePortfolio=np.dot(close_norm,np_alloc)
print 'valuePortolio = ',valuePortfolio
#print 'normalized valuePortfolio ',valuePortfolio
#daily returns of the PF
daily_Portfolio=valuePortfolio.copy()
tsu.returnize0(daily_Portfolio)
print 'valuePortolio afer returnize= ',valuePortfolio
#calculate the quantities
avg_P=np.average(daily_Portfolio)
sigma_P=np.std(daily_Portfolio)
sharpe_P=np.sqrt(252)*avg_P/sigma_P
cum_P=valuePortfolio[valuePortfolio.size -1]
return sigma_P,avg_P,sharpe_P,cum_P
def GetNormalizedReturn(dt_start,dt_end, symbols,c_dataobj):
#
#
#
# Keys to be read from the data, it is good to read everything in one go.
ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']
# We need closing prices so the timestamp should be hours=16.
dt_timeofday = dt.timedelta(hours=16)
# Get a list of trading days between the start and the end.
ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)
# Timestamps and symbols are the ones that were specified before.
ldf_data = c_dataobj.get_data(ldt_timestamps, symbols, ls_keys)
d_data = dict(zip(ls_keys, ldf_data))
#normalized returns data frame
df_rets=d_data['close'].copy()
close=df_rets.values
#normalized returns
close_norm=close/close[0,:]
#print 'close norm = ',close_norm.shape
return close_norm
def simulate(dt_start,dt_end, symbols, allocations):
#==========check allocations:
sum_alloc=0
for all in allocations:
sum_alloc+=all
#
if sum_alloc != 1.0:
print 'the allocations are wrong!'
sys.exit(1)
if len(allocations)!=len(symbols):
print 'the sizes are different!'
sys.exit(1)
#=========construct the portfolio
portfolio=zip(symbols,allocations)
print 'portfolio = ',portfolio
#check for bad symbols
#
c_dataobj=da.DataAccess('Yahoo')
ls_all_syms = c_dataobj.get_all_symbols()
# Bad symbols are symbols present in portfolio but not in all syms
ls_bad_syms = list(set(symbols) - set(ls_all_syms))
if len(ls_bad_syms) != 0:
print "Portfolio contains bad symbols : ", ls_bad_syms
sys.exit(1)
#
#
close_norm=GetNormalizedReturn(dt_start,dt_end, symbols,c_dataobj)
#optimize!
sharpe_max=-1
step=0.1
for a in range(0,11):
for b in range (0,11-a):
for c in range(0,11-a-b):
d=10-a-b-c
alloc_a=a*step
alloc_b=b*step
alloc_c=c*step
alloc_d=d*step
allocations=[alloc_a,alloc_b,alloc_c,alloc_d]
vol,daily,sharpe,cumul=Compute(close_norm,allocations)
#print 'sharpe =',sharpe
if sharpe>sharpe_max:
sharpe_max=sharpe
best_alloc=allocations
#print alloc_a,alloc_b,alloc_c,alloc_d
#raw_input('hey')
#
#
#
#
print 'the best sharpe is = ',sharpe_max
print 'with the allocation =',best_alloc
# vol,daily,sharpe,cumul=Compute(close_norm,allocations)
#return vol,daily,sharpe,cumul
if __name__=='__main__':
# List of symbols
ls_symbols=['BRCM', 'TXN', 'IBM', 'HNZ']
#ls_symbols=['C', 'GS', 'IBM', 'HNZ']
#ls_symbols=['BRCM', 'TXN', 'IBM', 'HNZ']
#ls_symbols=['GOOG', 'AAPL', 'GLD', 'XOM']
#ls_symbols=['AXP', 'HPQ', 'IBM', 'HNZ']
#ls_symbols=['AAPL', 'GLD', 'GOOG', 'XOM']
#ls_symbols = ["AAPL", "GLD", "GOOG", "$SPX", "XOM"]
# Start and End date of the charts
dt_start = dt.datetime(2010, 1, 1)
dt_end = dt.datetime(2010, 12, 31)
ls_allocations=(0.4,0.4,0.0,0.2)
#vol,daily,sharpe,cumul=simulate(dt_start,dt_end,ls_symbols,ls_allocations)
simulate(dt_start,dt_end,ls_symbols,ls_allocations)
#print 'volatility= ',vol
#print 'avg daily ret =',daily
#print 'sharpe ratio = ',sharpe
#print 'cumulative return =',cumul
<file_sep>/createOrder.py
import sys
import pandas as pd
import numpy as np
import math
import copy
import QSTK.qstkutil.qsdateutil as du
import datetime as dt
import QSTK.qstkutil.DataAccess as da
import QSTK.qstkutil.tsutil as tsu
import QSTK.qstkstudy.EventProfiler as ep
def createOrder()
'''create an order'''
if __name__=='__main__':
pass
<file_sep>/marketsim.py
#maketsim.py
#function for the first quizz:
import sys
# QSTK Imports
import QSTK.qstkutil.qsdateutil as du
import QSTK.qstkutil.tsutil as tsu
import QSTK.qstkutil.DataAccess as da
# Third Party Imports
import datetime as dt
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import copy
from simulate import *
def parseArgs(args):
startingCash=args[1]
orderFile=args[2]
valuesFile=args[3]
benchmarkSym=args[4]
return startingCash,orderFile,valuesFile,benchmarkSym
def getDataFromYahoo():
c_dataobj=da.DataAccess('Yahoo')
ls_all_syms = c_dataobj.get_all_symbols()
def loadData(ls_keys,symbols,dt_start,dt_end):
c_dataobj=da.DataAccess('Yahoo')
ls_all_syms = c_dataobj.get_all_symbols()
# We need closing prices so the timestamp should be hours=16.
dt_timeofday = dt.timedelta(hours=16)
# Get a list of trading days between the start and the end.
ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)
# Timestamps and symbols are the ones that were specified before.
#print 'the symbols!',symbols
ldf_data = c_dataobj.get_data(ldt_timestamps, symbols, ls_keys)
d_data = dict(zip(ls_keys, ldf_data))
df_rets=d_data['close'].copy()
#df_rets['normclose']=d_data['close']/d_data.iget(0)['close']
return df_rets
def getValuePortfolio(date,portfolio,df_data,outfile):
outformat='%Y-%m-%d-%H'
valuePortfolio=0.0
outfile.write('\n')
outfile.write('======VALUE OF STOCKS at '+str(date.strftime(outformat))+'======'+'\n')
for isym,units in portfolio.iteritems():
priceStock=float(df_data.ix[date][isym])
valueStock=units*priceStock
outfile.write(' there are '+str(units)+' units of stock '+str(isym)+' with a value of '+str(units)+'*'+str(priceStock)+' = '+str(valueStock)+'\n')
valuePortfolio+=valueStock
outfile.write('=====the value is '+str(valuePortfolio)+'\n')
outfile.write('\n')
return valuePortfolio
def processOrder(orderdf,dayData,portfolio,cashBalance,outfile):
'''processes the buy and sell orders in one day'''
actionSign={}
actionSign['Buy']=1
actionSign['Sell']=-1
outformat='%Y-%m-%d-%H'
for rows in orderdf.iterrows():
row=rows[1]
date=row['mydate']
action=row['order']
symbol=row['symbol']
size=float(row['size'])
price=dayData[symbol]
#
outfile.write('\n')
outfile.write('NEW ORDER ARRIVED\n')
outfile.write(' Today the date is '+str(date.strftime(outformat))+ ' and the CASH BALANCE is '+str(cashBalance)+'\n')
if symbol in portfolio:
portfolio[symbol]+=actionSign[action]*size
else:
portfolio[symbol]=actionSign[action]*size
cashBalance-=actionSign[action]*size*price
outfile.write( ' The order is to '+str(action)+' '+str(size)+' shares of '+str(symbol)+ ' at a current price of '+str(price)+'\n')
outfile.write( ' the current CASH BALANCE after executing the order is '+str(cashBalance)+'\n')
outfile.write('\n')
return cashBalance
def AnalyzeStats(thelist,targetDate):
totalValue=[]
for tup in thelist:
totalValue.append(tup[1]+tup[2])
if targetDate==tup[0]:
print 'the value at ',targetDate,' is ',tup[1]+tup[2]
dailyPFValues=np.array(totalValue)
dailyPFValues=dailyPFValues/dailyPFValues[0]
totalreturn=dailyPFValues[-1]
tsu.returnize0(dailyPFValues)
avg_P=np.average(dailyPFValues)
sigma_P=np.std(dailyPFValues)
sharpe_P=np.sqrt(252)*avg_P/sigma_P
return avg_P,sigma_P,sharpe_P,totalreturn
def getOrders(orderFile):
df_orders=pd.read_csv(orderFile,parse_dates=True, names=['year','month','day', 'symbol', 'order', 'size'], header=0 )
df_orders['mydate']=df_orders.apply(lambda x:pd.datetime(x['year'],x['month'],x['day'],16,0),axis=1)
return df_orders
def marketSimulation(dt_start,dt_end,startingCash,benchmarkSym,df_orders):
startingCash=float(startingCash)
cashBalance=float(startingCash)
benchmarkSym=str(benchmarkSym)
benchmarkSymbols=[benchmarkSym]
#print 'the sym = ',benchmarkSym
#get the first and last dates:
dt_start=df_orders['mydate'].iget(0)
dt_end=df_orders['mydate'].iget(-1)
dt_end = dt_end.replace(hour = 23)
#
#
#symbols
symbols=[]
for rows in df_orders.iterrows():
if not rows[1]['symbol'] in symbols:
symbols.append(rows[1]['symbol'])
ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']
#
df_data=loadData(ls_keys,symbols,dt_start,dt_end)
allocations={}
date=0
olddate=0
dailyPortfolio=[]
df_sorted=df_orders.sort('mydate')
#initialize allocations
for sym in symbols:
allocations[sym]=0
#
#benchmark stuff
benchalloc={}
benchalloc[benchmarkSym]=1.0
df_bench_data=loadData(ls_keys,benchmarkSymbols,dt_start,dt_end)
dailyBenchmarkPF=[]
#
#
#LOOP OVER DATES
ordersfile=open('ordersFile.txt','w')
for ind in df_data.index:
#
newdf=df_sorted[df_sorted['mydate']==ind]
if newdf.index.size > 0:
dayData=df_data.ix[ind]
cashBalance=processOrder(newdf,dayData,allocations,cashBalance,ordersfile)
yesterday=ind
valuePortfolioToday=getValuePortfolio(ind,allocations,df_data,ordersfile)
dailyPortfolio.append((ind,cashBalance,valuePortfolioToday))
#get value of benchmark portfolio
valueBenchToday=getValuePortfolio(ind,benchalloc,df_bench_data,ordersfile)
dailyBenchmarkPF.append((ind,0,valueBenchToday))
ordersfile.write('=========TOTAL VALUE OF PORTFOLIO TODAY======\n')
ordersfile.write(' '+str(cashBalance)+' + '+str(valuePortfolioToday)+' = '+str(cashBalance+valuePortfolioToday)+'\n')
ordersfile.write('====================================================\n')
#GET THE STATS
targetDate=dt.datetime(2011,3,28,16,00)
print 'targetDate =' ,targetDate
avg_P,sigma_P,sharpe_P,totRet=AnalyzeStats(dailyPortfolio,targetDate)
print 'sharpe ratio is ',sharpe_P
print 'standard deviation is ',sigma_P
print 'average is ',avg_P
print 'total return is ',totRet
print ' '
avg_P,sigma_P,sharpe_P,totRet=AnalyzeStats(dailyBenchmarkPF,targetDate)
print 'sharpe ratio is ',sharpe_P
print 'standard deviation is ',sigma_P
print 'average is ',avg_P
print 'total return is ',totRet
if __name__=='__main__':
startingCash,orderFile,valuesFile,benchmarkSym=parseArgs(sys.argv)
df_orders=getOrders(orderFile)
marketSimulation(startingCash,benchmarkSym,df_orders)
#def marketsim(df_orders
|
2bc7c2ab970b91abb6b7c6058a7e43d9fb68cec9
|
[
"Python"
] | 4
|
Python
|
elelias/CompuInvesting
|
12efe4bad164aaf4ae93a44ddc49f118e774606c
|
64cdab6f2848bd125c10d4e4087f9adaded43b62
|
refs/heads/master
|
<repo_name>Jdhaimson/joshhaimson<file_sep>/app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
def home
end
def mom
end
def bunko
end
def winecheese
end
def yogapantsandfinance
end
def puzzlesthebar
end
def aroundtheworld
end
def formal
end
end
<file_sep>/README.md
This is the home of the code behind my personal website/blog/whatever else I plan on doing with it.
|
afaeddfd8196be9c19865917fd48136a6ecc677d
|
[
"Markdown",
"Ruby"
] | 2
|
Ruby
|
Jdhaimson/joshhaimson
|
7ee132a49e769c52f17c1c51accaf8b26f6e3a54
|
0e78bd9d32e6da2e17cfeb37583d78787cfbd357
|
refs/heads/master
|
<file_sep>---
layout: post
title: "Python与C的DLL调用"
subtitle: " \"Unity Shader\""
date: 2018-05-02 15:48:00
author: "Mas9uerade"
header-img: "img/watchdog2_sf.jpg"
tags:
- Python
- C
---
> “一个简单的使用Python调用C的DLL中的回调函数”
之前在思考Python如何调用C的Dll,网上也只搜到简单的加法调用,因此测试了一些简单的Python调用C的DLL的方式,附上例子。
## 具体流程 ##
##### 用简单函数指针调用 #####
由于想用C来写所以不能加C++的一些特性
首先是头文件
```C
#ifndef _TEST_ONE_H_
#define _TEST_ONE_H_
//导出方法的定义
#define DLLExport __declspec(dllexport)
//第一阶段只导出最简单的函数
extern "C"
{
int callback1(int a, int b);
int callback2(int a, int b);
DLLExport int test1(int protoid);
}
#endif // ! _TEST_ONE_H_
```
然后是源文件
```C
#include "stdafx.h"
#include "test1.h"
//根据输入的调用函数指针实现加法与减法
int test1(int protoid)
{
int(*l_func)(int, int) = NULL;
if (protoid == 1)
{
l_func = &callback1;
return l_func(1, 1);
}
else if (protoid == 2)
{
l_func = &callback2;
return l_func(1, 3);
}
return 0;
}
int callback1(int a, int b)
{
return a + b;
}
int callback2(int a, int b)
{
return a - b;
}
```
Python调用部分 调用ctypes这个模块实现
```C
from ctypes import *
dll = CDLL("Test1.dll")
print(dll.test1(1))
print(dll.test1(2))
```
##### 函数指针调用与结构体传参 #####
1. 测试了引用传入;
2. 测试了结果的传出(返回)
3. 使用函数指针数组作为回调,同时传入与返回;
```C
extern "C"
{
DLLExport int test2(BasicEvent *ev);
}
extern "C"
{
DLLExport BasicEvent test3(BasicEvent *ev);
}
extern "C"
{
int callback3(BasicEvent*);
int callback4(BasicEvent*);
int callback5(int);
typedef int(*p_func)(BasicEvent*);
p_func funcArr[100]
{
funcArr[3] = callback3,
funcArr[4] = callback4
};
typedef int (*x_func)(int);
x_func funArr2[10]
{
funArr2[0] = callback5
};
}
```
## 然后是源文件,由于返回引用指针时,python无法识别,故把回传的指针强制转换为int
```C
int test2(BasicEvent *ev)
{
int(*m_func)(BasicEvent*) = callback3;
if (ev->id == 3)
{
return callback3(ev);
}
else if (ev->id == 4)
{
return (funcArr[4](ev));
}
ev->len = 19;
return (int)ev;
}
BasicEvent test3(BasicEvent *ev)
{
return *ev;
}
int callback3(BasicEvent *ev)
{
ev->id = 33;
ev->len += 1;
return (int)ev;
}
int callback4(BasicEvent *ev)
{
ev->len += 2;
return (int)ev;
}
int callback5(int a)
{
return a + 10;
}
```
Python调用部分
1. 首先定义结构体
2. 返回结构体的话,需要设置restype返回值的类型
3. 返回引用也需要设置restype返回值类型
```C
from ctypes import *
import struct
class BasicEvent(Structure):
_fields_ = [('a', c_int),
('b', c_int)]
ev = BasicEvent()
ev.a = 3
ev.b = 4
dll1 = CDLL("Test1.dll")
dll1.test3.restype = BasicEvent
dll1.test2.restype = POINTER(BasicEvent)
print(byref(ev))
ev3 = dll1.test3(byref(ev))
print(ev3.a)
print(ev3.b)
ev4 = dll1.test2(byref(ev))
print(ev4)
print(ev4.contents.a)
print(ev4.contents.b)
```
#### 总结
1. Python调用C的Dll,通过ctypes可以实现dll的调用和python数据类型与C数据类型的转换
2. Python传参时需要设置argtype与restype来设置传入参数类型与返回参数类型
3. Python调用DLL返回引用时,需要把C的地址转化为int作为返回值,再由POINTER()方法返回值类型;
<file_sep>/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型
*/
int maxDepth(TreeNode* root)
{
if (root == NULL)
{
return 0;
}
return max(maxDepth(root->left), maxDepth(root->right))+1;
// write code here
}
};<file_sep># 1. 虚函数的实现原理,父类和子类的内存布局
1. 虚函数在父类和子类中都是以虚函数指针表的形式存在的,在内存中存在类的空间(程序代码区RO)
2. 一个由c/C++编译的程序占用的内存分为以下几个部分:
1. 栈区(stack)— 由编译器自动分配释放 ,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构中的栈。
2. 堆区(heap) — 一般由程序员分配释放;
3. 全局区(静态区)(static)—,全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态变量在一块区域(RW), 未初始化的全局变量和未初始化的静态变量在相邻的另一块区域(ZI)。 - 程序结束后由系统释放
4. 文字常量区 —常量字符串就是放在这里的。 程序结束后由系统释放 (RO)
5. 程序代码区—存放函数体的二进制代码。 (RO)
# [2. Readonly和Const的区别](https://www.cnblogs.com/daidaibao/p/4214268.html)
1. const 是静态常量,是指编译器在编译时候会对常量进行解析,并将常量的值替换成初始化的那个值。
2. readonly是动态常量,其值则是在运行的那一刻才获得的,编译器编译期间将其标示为只读常量,而不用常量的值代替,这样动态常量不必在声明的时候就初始化,而可以延迟到构造函数中初始化。
##### 静态常量(Const)和动态常量(Readonly)之间的区别
| | 静态常量(Compile-time Constant) | 动态常量(Runtime Constant) |
| -------------- | -------------------------------------------------- | ------------------------------------------------------------ |
| 定义 | 声明的同时要设置常量值。 | 声明的时候可以不需要进行设置常量值,可以在类的构造函数中进行设置。 |
| 类型限制 | 只能修饰基元类型,枚举类型或者字符串类型。 | 没有限制,可以用它定义任何类型的常量。 |
| 对于类对象而言 | 对于所有类的对象而言,常量的值是一样的。 | 对于类的不同对象而言,常量的值可以是不一样的。 |
| 内存消耗 | 无。 | 要分配内存,保存常量实体。 |
| **综述** | **性能要略高,无内存开销,但是限制颇多,不灵活。** | **灵活,方便,但是性能略低,且有内存开销。** |
1. Const修饰的常量在声明的时候必须初始化;Readonly修饰的常量则可以延迟到构造函数初始化 。
2. Const常量既可以声明在类中也可以在函数体内,但是Static Readonly常量只能声明在类中。Const是静态常量,所以它本身就是Static的,因此不能手动再为Const增加一个Static修饰符。
3. Const修饰的常量在编译期间就被解析,即:经过编译器编译后,我们都在代码中引用Const变量的地方会用Const变量所对应的实际值来代替; Readonly修饰的常量则延迟到运行的时候。
##### 动态常量(Readonly)被赋值后不可以改变
ReadOnly 变量是运行时变量,它在运行时第一次赋值后将不可以改变。其中“不可以改变”分为两层意思:
1. 对于值类型变量,值本身不可以改变(Readonly, 只读)
2. 对于引用类型变量,引用本身(相当于指针)不可改变。
##### Const和Readonly的最大区别(除语法外)
Const的变量是嵌入在IL代码中,编译时就加载好,不依赖外部dll(这也是为什么不能在构造方法中赋值)。Const在程序集更新时容易产生版本不一致的情况。
Readonly的变量是在运行时加载,需请求加载dll,每次都获取最新的值。Readonly赋值引用类型以后,引用本身不可以改变,但是引用所指向的实例的值是可以改变的。在构造方法中,我们可以多次对Readonly赋值。
# [3. C++中的malloc和new关键字的区别](https://www.cnblogs.com/ygsworld/p/11261810.html)
##### 分配的内存空间
1. new操作符从自由存储区(free store)上为对象动态分配内存空间; 自由存储区是C++基于new操作符的一个抽象概念,凡是通过new操作符进行内存申请,该内存即为自由存储区。
2. malloc函数从堆上动态分配内存。而堆是操作系统中的术语,是操作系统所维护的一块特殊内存,用于程序的内存动态分配,C语言使用malloc从堆上分配内存,使用free释放已分配的对应内存。
**那么自由存储区是否能够是堆(问题等价于new是否能在堆上动态分配内存),这取决于operator new 的实现细节。自由存储区不仅可以是堆,还可以是静态存储区,这都看operator new在哪里为对象分配内存。**
##### 返回类型安全性
1. new操作符内存分配成功时,返回的是对象类型的指针,类型严格与对象匹配,无须进行类型转换,故new是符合类型安全性的操作符。
2. malloc内存分配成功则是返回void * ,需要通过强制类型转换将void*指针转换成我们需要的类型。
**类型安全很大程度上可以等价于内存安全,类型安全的代码不会试图方法自己没被授权的内存区域。关于C++的类型安全性可说的又有很多了。**
##### 内存分配失败时的返回值
1. new内存分配失败时,会抛出bac_alloc异常,它不会返回NULL;
2. malloc分配内存失败时返回NULL。
在使用C语言时,我们习惯在malloc分配内存后判断分配是否成功:
##### 是否需要指定内存大小
1. 使用new操作符申请内存分配时无须指定内存块的大小,编译器会根据类型信息自行计算;
2. malloc则需要显式地指出所需内存的尺寸。
##### 是否调用构造函数/析构函数
1. 使用new操作符来分配对象内存时会经历三个步骤:
1. 调用operator new 函数(对于数组是operator new[])分配一块足够大的,原始的,未命名的内存空间以便存储特定类型的对象。
2. 编译器运行相应的构造函数以构造对象,并为其传入初值。
3. 对象构造完成后,返回一个指向该对象的指针。
2. 使用delete操作符来释放对象内存时会经历两个步骤:
1. 调用对象的析构函数。
2. 编译器调用operator delete(或operator delete[])函数释放内存空间。
3. malloc则不会不会调用构造和析构函数
##### 对数组的处理
1. C++提供了new[]与delete[]来专门处理数组类型:
1. new对数组的支持体现在它会分别调用构造函数函数初始化每一个数组元素,释放对象时为每个对象调用析构函数。注意delete[]要与new[]配套使用,不然会找出数组对象部分释放的现象,造成内存泄漏。
2. 至于malloc,它并知道你在这块内存上要放的数组还是啥别的东西,反正它就给你一块原始的内存,在给你个内存的地址就完事。所以如果要动态分配一个数组的内存,还需要我们手动自定数组的大小:
```cpp
int * ptr = (int *) malloc( sizeof(int) );//分配一个10个int元素的数组
```
##### new与malloc是否可以相互调用
operator new /operator delete的实现可以基于malloc,而malloc的实现不可以去调用new。下面是编写operator new /operator delete 的一种简单方式,其他版本也与之类似:
```cpp
void * operator new (sieze_t size)
{
if(void * mem = malloc(size)
return mem;
else
throw bad_alloc();
}
void operator delete(void *mem) noexcept
{
free(mem);
}
```
##### 是否可以被重载
opeartor new /operator delete可以被重载。标准库是定义了operator new函数和operator delete函数的8个重载版本:
```cpp
//这些版本可能抛出异常
void * operator new(size_t);
void * operator new[](size_t);
void * operator delete (void * )noexcept;
void * operator delete[](void *0)noexcept;
//这些版本承诺不抛出异常
void * operator new(size_t ,nothrow_t&) noexcept;
void * operator new[](size_t, nothrow_t& );
void * operator delete (void *,nothrow_t& )noexcept;
void * operator delete[](void *0,nothrow_t& )noexcept;
```
我们可以自定义上面函数版本中的任意一个,前提是自定义版本必须位于全局作用域或者类作用域中。太细节的东西不在这里讲述,总之,我们知道我们有足够的自由去重载operator new /operator delete ,以决定我们的new与delete如何为对象分配内存,如何回收对象。
而malloc/free并不允许重载。
##### 能够直观地重新分配内存
使用malloc分配的内存后,如果在使用过程中发现内存不足,可以使用realloc函数进行内存重新分配实现内存的扩充。realloc先判断当前的指针所指内存是否有足够的连续空间,如果有,原地扩大可分配的内存地址,并且返回原来的地址指针;如果空间不够,先按照新指定的大小分配空间,将原有数据从头到尾拷贝到新分配的内存区域,而后释放原来的内存区域。
new没有这样直观的配套设施来扩充内存。
##### 客户处理内存分配不足
在operator new抛出异常以反映一个未获得满足的需求之前,它会先调用一个用户指定的错误处理函数,这就是new-handler。new_handler是一个指针类型:
```cpp
namespace std
{
typedef void (*new_handler)();
}
```
指向了一个没有参数没有返回值的函数,即为错误处理函数。为了指定错误处理函数,客户需要调用set_new_handler,这是一个声明于的一个标准库函数:
```cpp
namespace std
{
new_handler set_new_handler(new_handler p ) throw();
}
```
set_new_handler的参数为new_handler指针,指向了operator new 无法分配足够内存时该调用的函数。其返回值也是个指针,指向set_new_handler被调用前正在执行(但马上就要发生替换)的那个new_handler函数。
对于malloc,客户并不能够去编程决定内存不足以分配时要干什么事,只能看着malloc返回NULL。
##### 总结
将上面所述的10点差别整理成表格:
| 特征 | new/delete | malloc/free |
| ------------------ | ------------------------------------- | ------------------------------------ |
| 分配内存的位置 | 自由存储区 | 堆 |
| 内存分配失败返回值 | 完整类型指针 | void* |
| 内存分配失败返回值 | 默认抛出异常 | 返回NULL |
| 分配内存的大小 | 由编译器根据类型计算得出 | 必须显式指定字节数 |
| 处理数组 | 有处理数组的new版本new[] | 需要用户计算数组的大小后进行内存分配 |
| 已分配内存的扩充 | 无法直观地处理 | 使用realloc简单完成 |
| 是否相互调用 | 可以,看具体的operator new/delete实现 | 不可调用new |
| 分配内存时内存不足 | 客户能够指定处理函数或重新制定分配器 | 无法通过用户代码进行处理 |
| 函数重载 | 允许 | 不允许 |
| 构造函数与析构函数 | 调用 | 不调用 |
malloc给你的就好像一块原始的土地,你要种什么需要自己在土地上来播种
而new帮你划好了田地的分块(数组),帮你播了种(构造函数),还提供其他的设施给你使用:
当然,malloc并不是说比不上new,它们各自有适用的地方。在C++这种偏重OOP的语言,使用new/delete自然是更合适的。
# 4. 协程和进程的区别,怎么实现,协程程序怎么写,有什么问题
1. 进程拥有自己独立的堆和栈,既不共享堆,亦不共享栈,进程由操作系统调度。
2. 线程拥有自己独立的栈和共享的堆,共享堆,不共享栈,线程亦由操作系统调度(标准线程是的)。
3. 协程和线程一样共享堆,不共享栈,协程由程序员在协程的代码里显示调度。
### Unity协程执行原理
unity中协程执行过程中,通过yield return XXX,将程序挂起,去执行接下来的内容,注意协程不是线程,在为遇到yield return XXX语句之前,协程额方法和一般的方法是相同的,也就是程序在执行到yield return XXX语句之后,接着才会执行的是 StartCoroutine()方法之后的程序,走的还是单线程模式,仅仅是将yield return XXX语句之后的内容暂时挂起,等到特定的时间才执行。
那么挂起的程序什么时候才执行,也就是协同程序主要是update()方法之后,lateUpdate()方法之前调用的
Struct和class的区别,值类型和引用类型区别C#装箱和拆箱
Inline函数有啥作用,和宏定义有啥区别
闭包
Action和function区别,以及内部实现,注册函数如何防止重复,如何删除
Map怎么实现的,Dictionary如何实现
红黑树和avl树还有堆的区别,内存&效率
快排的时间空间复杂度以及实现
堆排的实现,时间空间复杂度
Enum作Key的问题
**Dictionary**的key必须是唯一的标识,因此**Dictionary**需要对 key进行判等的操作,如果key的类型没有实现 IEquatable接口,则默认根据System.Object.Equals()和GetHashCode()方法判断值是否相等。我们可以看看常用作key的几种类型在.NET Framework中的定义:
public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<string>, IEnumerable, IEquatable<string>
public struct Int32 : IComparable, IFormattable, IConvertible, IComparable<int>, IEquatable<int>
public abstract class **Enum** : ValueType, IComparable, IFormattable, IConvertible
注意**Enum**类型的定义与前两种类型的不同,它并没有实现IEquatable接口。因此,当我们使用**Enum**类型作为key值时,**Dictionary**的内部操作就需要将**Enum**类型转换为System.Object,这就导致了Boxing的产生。它是导致**Enum**作为 key值的性能瓶颈。
CLR是什么
il2cpp和mono
如何实现一个扇形进度条
渲染管线流程,mvp变换等,
**渲染管线(管道):顶点着色器——>光栅化——>片段着色器——>alpha测试——>模版测试——>深度测试——>Blend——>Gbuffer——>BrontBuffer——>framebuffer——>显示器**
各种test
Shadowmap实现如何高效实现阴影
CPU和GPU区别,
如何设计几种反走样算法实现、问题、效率
前向渲染和延迟渲染的区别
什么时候用延迟渲染 - 需要几个buffer,需要记录什么信息
大量实时光源渲染
数组和链表区别
C# GC算法
内存管理器实现
如何实现战争迷雾
Pbr最重要的参数,几个方程
**如何搭建一个pbr工作流**
Topk问题以及变种,各种解法
100万个数据快速插入删除和随机访问
1小时燃烧完的绳子,任意根,衡量出15分钟
60 - 30+15
**Unity资源相关问题,内存分布,是否copy等Unity动画相关问题
帧同步和状态同步区别等一系列问题帧同步要注意的问题
**随机数如何保证同步**
**如何设计一个技能系统以及buff系统**
数组第k大的数1~n有一个数字没有,找到这个数如何
分析程序运行效率瓶颈,log分析
**UI背包如何优化**
Unity ui如何自适应
A\*寻路实现
**Unity navimesh**
体素的思想和实现
碰撞检测算法,优化,物理引擎检测优化连续碰撞检测
**设计个UIManager,ui层级关系,ui优化
Mvc思想设计模式准则
Unity优化手段,
dc cpu gpu
** **UML图**
消息管理器实现
lua dofile和require区别
Lua面向对象实现以及与区别
**如何防止大量GC**
**如何实现热更***
游戏AI如何实现,行为树要点**
如何实现一个延时运行功能
| 延时功能 | 是否继承MonoBehaviour | 配合使用的函数 |
| -------------------- | --------------------- | --------------------------------------------------- |
| Update函数 | 是 | Timer.timer |
| Invoke | 是 | CancelInvoke,InvokeRepeating,IsInvoking, |
| Coroutine | 是 | StartCoroutine ,StopCoroutine,StopAllCoroutines, |
| DOTween (HOTween v2) | 否 | 商业授权 |
| VisionTimer.VP_Timer | 否 | 商业授权 |
Mipmap思想,内存变化
```
```<file_sep>//143.重排链表
//给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
//将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
//你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
//示例 1:
//给定链表 1->2->3->4, 重新排列为 1->4->2->3.
//示例 2:
//给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
//通过次数74,391提交次数124,797
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/reorder-list
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//思路 --->
// 1. 快慢指针找到链表重点
// 2. 反转右半部分链表
// 3. 合并链表
namespace ByteDancePopular
{
public partial class Solution
{
public void ReorderList(ListNode head)
{
ListNode mid = GetMiddleNode(head);
ListNode l1 = head;
ListNode l2 = mid.next;
mid.next = null;
l2 = ReverseList(l2);
MergeList(l1, l2);
}
private ListNode GetMiddleNode(ListNode head)
{
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next!= null)
{
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
private ListNode ReverseList(ListNode head)
{
ListNode cur = head;
ListNode prev = null;
while (cur!=null)
{
ListNode nextTmp = cur.next;
cur.next = prev;
prev = cur;
cur = nextTmp;
}
return prev;
}
private void MergeList(ListNode l1, ListNode l2)
{
ListNode l1_tmp;
ListNode l2_tmp;
while (l1 != null && l2 !=null)
{
l1_tmp = l1.next;
l2_tmp = l2.next;
l1.next = l2;
l1 = l1_tmp;
l2.next = l1;
l2 = l2_tmp;
}
}
}
}
<file_sep>---
layout: post
title: "C#数据结构解析"
subtitle: " \"面试小记\""
date: 2020-12-09 15:00:00
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- C#
---
> “面试知识点整理
>
> 摘抄自[Hash算法:双重散列](https://www.cnblogs.com/magic-sea/p/12003883.html),[System.Collections.Generic 源码阅读总结](https://www.cnblogs.com/millionsmultiplication/p/9416325.html)
# C#数据结构解析
## ArrayList ,List
ArrayList 和 List 都是不限制长度的集合类型 ,List相比ArrayList 就内部实现而言除了泛型本质没有太大区别。不过为避免装箱拆箱问题,尽可能使用List
集合内部是由数组实现,默认大小是4,但你使用无参构造函数构造实例时,内部数组大小是0,当你加入第一个元素时,才扩容为4,添加元素时,如果发现内置数组大小不够,内置数组大小会扩容为原来的两倍,每一次扩容都会重新开辟一个数组,拷贝旧数组的数据,如果你要给集合添加大量的元素却不为它初始化一个合适容量,频繁的内存开辟和多余的数组拷贝会导致性能的损耗。
所以使用时建议提供合适的容量。
## Hashtable,Dictionary
### HashTable
Hashtable和Dictionary都是哈希表的实现,很多人说Dictionary内部是由hashtable实现的,这是不恰当的。
Hashtable的构造需要装载因子,装载因子是0.1 到 1.0 范围内的数字 ,是内部存储桶数(count)所占桶数组(buckets)桶数(hashsize)的最大比率 ,当桶数大于装载数(loadsize)时,桶数组就会扩容
hashtable内部解除哈希冲突的算法是双重散列法,是开放地址法中最好的方法之一。
#### 双重散列法
**双重散列**是**线性开型寻址散列**(**开放寻址法**)中的冲突解决技术。这个方法的基本思想是:当发生地址冲突时,按照某种方法继续探测哈希表中的其他存储单元,直到找到空位置为止。这个过程可用下式描述:
**双重散列**使用在发生冲突时将**第二个散列函数**应用于**键**的想法。
**此算法**使用:
**(hash1(key) + i \* hash2(key)) % TABLE_SIZE**
来进行双哈希处理。**hash1()** 和 **hash2()** 是哈希函数,而 **TABLE_SIZE** 是哈希表的大小。当**发生碰撞**时,我们通过重复增加 **步长i** 来寻找键。
第一个Hash函数:**hash1(key) = key % TABLE_SIZE**。
```c++
/**
* 计算首次的Hash值
*
* @param key
* @return
*/
private int hash1(int key)
{
return (key % TABLE_SIZE);
}
```
第二个Hash函数是:**hash2(key) = PRIME – (key % PRIME)**,其中 **PRIME 是小于 TABLE_SIZE 的质数**。
```c++
/**
* 发生碰撞是时继续计算Hash值
*
* @param key
* @return
*/
private int hash2(int key)
{
return (PRIME - (key % PRIME));
}
```
第二个Hash函数表现好的特征:
- 绝对不会产生 0 索引
- 能在整个HashTable 循环探测
- 计算会快点
- 与第一个Hash函数互相独立
- PRIME 与 TABLE_SIZE 是 “相对质数”

```java
package algorithm.hash;
/**
* 双重哈希
*/
public class DoubleHash {
private static final int TABLE_SIZE = 13; // 哈希表大小
private static int PRIME = 7; // 散列函数值
private int[] hashTable;
private int curr_size; // 当前表中存的元素
public DoubleHash() {
this.hashTable = new int[TABLE_SIZE];
this.curr_size = 0;
for (int i = 0; i < TABLE_SIZE; i++)
hashTable[i] = -1;
}
private boolean isFull() {
return curr_size == TABLE_SIZE;
}
/**
* 计算首次的Hash值
*
* @param key
* @return
*/
private int hash1(int key) {
return (key % TABLE_SIZE);
}
/**
* 发生碰撞是时继续计算Hash值
*
* @param key
* @return
*/
private int hash2(int key) {
return (PRIME - (key % PRIME));
}
/**
* 向Hash表中存值
*
* @param key
*/
private void insertHash(int key) {
/* 表是否已满 */
if (isFull()) {
return;
}
/* 获取首次的Hash值 */
int index = hash1(key);
// 如果发生碰撞
if (hashTable[index] != -1) {
/* 计算第二次的Hash值 */
int index2 = hash2(key);
int i = 1;
while (true) {
/* 再次合成新的地址 */
int newIndex = (index + i * index2) % TABLE_SIZE;
// 如果再次寻找时没有发生碰撞,把key存入表中的对应位置
if (hashTable[newIndex] == -1) {
hashTable[newIndex] = key;
break;
}
i++;
}
} else {
// 一开始没有发生碰撞
hashTable[index] = key;
}
curr_size++; // Hash表中当前所存元素数量加1
}
/**
* 打印Hash表
*/
private void displayHash() {
for (int i = 0; i < TABLE_SIZE; i++) {
if (hashTable[i] != -1)
System.out.println(i + " --> " + hashTable[i]);
else
System.out.println(i);
}
}
public static void main(String[] args) {
int[] a = {19, 27, 36, 10, 64};
DoubleHash doubleHash = new DoubleHash();
for (int i = 0; i < a.length; i++)
doubleHash.insertHash(a[i]);
doubleHash.displayHash();
}
}
```
### Dictionary
而不同的是,Dictionary内部解除哈希冲突的算法是链地址法,而且Dictionary的构造不需要装载因子,不受装载因子的限制 ,如果Dictionary非常小,查找,插入,删除等操作拥有近乎O(1)的效率
和ArrayList ,List类似的是Dictionary和hashtable内部也是由数组实现的,所以构造时也需要提供合适容量,防止性能的损耗。
但我们需要另外注意的是你提供给构造函数的容量不一定会是初始时内置数组的长度,构造函数内部会选择一个大于等于你所选择容量的素数作为真实的初始容量。
我们知道Dictionary的最大特点就是可以通过任意类型的key寻找值。而且是通过索引,速度极快。
该特点主要意义:数组能通过索引快速寻址,其他的集合基本都是以此为基础进行扩展而已。 但其索引值只能是int,某些情境下就显出Dictionary的便利性了。
那么问题就来了--C#是怎么做的呢,能使其做到泛型索引。
[
](https://images2018.cnblogs.com/blog/776708/201806/776708-20180625001403462-481994959.png)
我们关注圈中的内容,这是Dictionary的本质 --- 两个数组,。这是典型的用空间换取时间的做法。
先来说下两数组分别代表什么。
1- buckets,int[] ,水桶!不过我觉得用仓库更为形象。eg: buckets = new int[3]; 表示三个仓库,i = buckets [0] ,if i = -1 表示该仓库为空,否则表示第一个仓库存储着东西。这个东西表示数组entries的索引。
2- entries , Entry<TKey,TValue>[] ,Entry是个结构,key,value就是我们的键值真实值,hashCode是key的哈希值,next可以理解为指针,这里先不具体展开。
```c#
[StructLayout(LayoutKind.Sequential)]
private struct Entry
{
public int hashCode;
public int next;
public TKey key;
public TValue value;
}
```
先说一下索引,如何用人话来解释呢?这么说吧,本身操作系统只支持地址寻址,如数组声明时会先存一个header,同时获取一个base地址指向这个header,其后的元素都是通过*(base+index)来进行寻址。
基于这个共识,Dictionary用泛型key索引的实现就得想方设法把key转换到上面数组索引上去。
也就是说要在记录的存储位置和它的关键字之间建立一个确定的对应关系 f,使每个关键字和结构中一个惟一的存储位置相对应。
因而在查找时,只要根据这个对应关系 f 找到给定值 K 的函数值 f(K)。若结构中存在关键字和 K 相等的记录。在此,我们称这个对应关系 f 为哈希 (Hash) 函数,按这个思想建立的表为哈希表。
回到Dictionary,这个f(K)就存在于key跟buckets之间:
dic[key]加值的实现:entries数组加1,获取i-->key-->获取hashCode-->f(hashCode)-->确定key对应buckets中的某个仓库(buckets对应的索引)-->设置仓库里的东西(entries的索引 = i)
dic[key]取值的实现:key-->获取hashCode-->f(hashCode)-->确定key对应buckets中的某个仓库(buckets对应的索引)--> 获取仓库里的东西(entries的索引i,上面有说到)-->真实的值entries[i]
上面的流程中只有一个(f(K)获取仓库索引)让我们很难受,因为不认识,那现在问题变成了这个f(K)如何实现了。
实现:
```c#
int index = hashCode % buckets.Length;
```
这叫做除留余数法,哈希函数的其中一种实现。如果你自己写一个MyDictionary,可以用其他的哈希函数。
举个例子,假设两数组初始大小为3, [this.comparer.GetHashCode(4](http://this.comparer.gethashcode(4/)) & 0x7fffffff = 4:
```c#
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(4, "value");
```
i=0,key=4--> hashCode=4.GetHashCode()=4--> f(hashCode)=4 % 3 = 1-->第1号仓库-->东西 i = 0.
此时两数组状态为:
[
](https://images2018.cnblogs.com/blog/776708/201806/776708-20180625014129387-1575137558.png)
取值按照之前说的顺序进行,仿佛已经完美。但这里还有个问题,不同的key生成的hashCode经过f(K)生成的值不是唯一的。即一个仓库可能会放很多东西。
C#是这么解决的,每次往仓库放东西的时候,先判断有没有东西(buckets[index] 是否为 -1),如果有,则进行修改。
如再:
```c#
dic.Add(7, "value");
dic.Add(10, "value");
```
f(entries[1]. hashCode)=7 % 3 = 1也在第一号仓库,则修改buckets[1] = 1。
同时修改entries[1].next = 0;//上一个仓库的东西
f(entries[2].hashCode)=10 % 3 = 1也在第一号仓库,则再修改buckets[1] = 2。
同时修改entries[1].next = 1;//上一个仓库的东西
这样相当于1号仓库存了一个单向链表,entries:2-1-0。
成功解决。
这里有人如果看过这些集合源码的话知道数组一般会有一个默认大小(当然我们初始化集合的时候也可以手动传入capacity),总之,Length不可能无限大。
那么当集合满的时候,我们需对集合进行扩容,C#一般直接Length*2。那么buckets.Length就是可变的,上面的f(K)结果也就不是恒定的。
C#对此的解决放在了扩容这一步:
[
](https://images2018.cnblogs.com/blog/776708/201806/776708-20180625011910856-956352989.png)
可以看到扩容实质就是新开辟一个更大空间的数组,讲道理是耗资源的。所以我们在初始化集合的时候,每次都给定一个合适的Capacity,讲道理是一个老油条该干的事儿。
上面说的这就是所谓“用空间换取时间的做法”,两个数组存了一个集合,而集合中我们最关心的value仿佛是个主角,一堆配角作陪。
## SortedList
SortedList是支持排序的关联性(键值对 )集合 ,内部采用数组实现,所以和List相同的是,初始化时需要提供一个合适的容量,SortedList内部采用哈希算法实现,和Dictionary类似的是,SortedList内部解除哈希冲突的算法是链地址法。
因为在查找的时候利用了二分搜索,所以查找的性能会好一些,时间复杂度是O(log n)
如果你想要快速查找,又想集合按照key的顺序排列,最后这个集合的操作(添加和移除)比较少的话,就是SortedList了
## SortedSet,SortedDictioanry
SortedSet类似于HashSet,但略有不同的是,SortedSet是有序排列,SortedSet内部实现应该是所有集合中最复杂,是依靠红黑树的原理实现。
SortedDictioanry和Dictionary的区别与HashSet和SortedSet的区别基本一致,因为SortedDictioanry内部本身就是依靠SortedSet实现的,并且SortDictionary内部顺序是以key的顺序为排列的
```C#
public SortedDictionary(IDictionary<TKey,TValue> dictionary, IComparer<TKey> comparer) {
if( dictionary == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
_set = new TreeSet<KeyValuePair<TKey, TValue>>(new KeyValuePairComparer(comparer));
foreach(KeyValuePair<TKey, TValue> pair in dictionary) {
_set.Add(pair);
}
}
```
## LinkedList,Stack,Queue
这3个集合我就不多做解释,完全按这几个基础数据结构的原理来实现。不过Stack,Queue内部采用数组实现,所以也要注意初始化时提供一个恰当的容量啊<file_sep>#include <iostream>
#include <vector>
using namespace std;
int binary_search(int begin_index, int end_index, int val, std::vector<int>& data, int total_len)
{
if (data[end_index] < val)
{
return total_len + 1;
}
int mid;
int marker_index = 0;
while (data[begin_index] <= data[end_index])
{
mid = (begin_index + end_index) / 2;
if (data[mid] < val)
{
begin_index = mid + 1;
//marker_index = mid;
}
if (data[mid] >= val)
{
end_index = mid - 1;
marker_index = mid;
}
}
return marker_index + 1;
}
int main()
{
std::cout << "Hello World!\n";
int a[100] = {3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 8, 8, 12, 13, 15, 16, 21, 21, 22, 24, 24, 27, 28, 32, 34, 35, 35, 36, 36, 39, 40, 41, 41, 42, 44, 44, 45, 45, 47, 47, 47, 47, 48, 48, 50, 51, 51, 53, 53, 53, 54, 54, 54, 56, 56, 57, 59, 60, 60, 60, 60, 61, 62, 63, 65, 65, 65, 65, 67, 67, 68, 70, 71, 71, 74, 75, 75, 79, 81, 84, 84, 86, 86, 87, 90, 90, 90, 90, 91, 92, 93, 94, 94, 94, 95, 97, 97, 98, 98, 99};
std::vector<int> vect;
vect.assign(a, a + 100);
int index = binary_search(0, 99, 97, vect, 100);
cout << index;
std::cout << "Hello World!\n";
}<file_sep>public static class Solution
{
public static int MyAtoi(string s)
{
string content = s.Trim(' ');
char[] byContent = content.ToCharArray();
if (byContent == null|| bycontent.length == 0)
{
return 0;
}
int sign = 1;
int integer = 0;
int last = 0;
int startIndex = 0;
if (byContent[0] == '+')
{
sign = 1;
startIndex++;
}
else if (byContent[0] == '-')
{
sign = -1;
startIndex++;
}
if (startIndex >= byContent.Length)
{
return 0;
}
if (byContent[startIndex] > '9' || byContent[startIndex] <'0')
{
return 0;
}
else
{
for (int i = startIndex; i < byContent.Length; ++i)
{
if (byContent[i] > '9' || byContent[i] < '0')
{
return integer;
}
else
{
last = integer;
integer = sign * (byContent[i] - '0') + integer*10;
if (integer / 10 != last)
{
if (sign == 1)
{
return int.MaxValue;
}
else
{
return int.MinValue;
}
}
}
}
}
return integer;
}
}<file_sep>---
layout: post
title: "My Fantasy in Chongqing"
subtitle: "念念不忘,必有回响"
date: 2020-11-23 01:38:01
author: "Mas9uerade"
header-img: "img/Hongya.jpg"
tags:
- 随想
---
# My Fantasy in Chongqing
周五办理离职,当天晚上飞重庆,循环了一路的《飞奔向你》和《披星戴月地想你》,肾上腺素和多巴胺不停地刺激着我的大脑,我就要再次见到我最喜欢的女孩了。
2天2夜的行程排得很满,想要更深的去了解她,也担心她的会不会太累。其实重庆没有想象中的那么好玩,美食也没有超乎预期的美味,但是就是因为在一起的人,觉得重庆的一切是那么美好。
刺骨的江风变成了飒爽的秋风,辣得嘴唇发麻的辣子鸡也变得让人食欲大开,人物和情节刻画得不细腻的警匪片也变成了难得的佳作,因为有了陪伴在身边的人,一切都不一样了。
<file_sep>---
layout: post
title: "Unix环境高级编程笔记1"
subtitle: " \"Linux\""
date: 2018-05-02 15:48:00
author: "Mas9uerade"
header-img: "img/watchdog2_sf.jpg"
tags:
- Linux
---
> “Unix环境高级编程第二版读书笔记 - 1”
# Unix基础知识 #
## 如何去写一个配置表 ##
### 文件操作函数与文本操作函数
参考[https://????]
### XML的读写
Xml的读写本质是需要一个细分的文本解析过程,但是从头造轮子是不现实的,因此引入libxml2这个MIT开源的Xml - C的库来实现功能,[下载链接]((http://xmlsoft.org/downloads.html));
在Window上编译时发现的问题缺少各种关联库,因此在Windows上测试会比较困难,推荐使用直接使用Linux;
### CSV的读写
CSV的读写就相对简单,只是行读写与分离",",使用到的接口有fopen, fclose, fprintf, fgets, strtok;
```C
#include <stdio.h>\
#include <io.h>
#include <string.h>
#define MAX_LINE 512
int main(int argc, char **argv)
{
char* filename = "./test.csv";
FILE *fp;
fp = fopen(filename, "w+");
fprintf(fp, "id, name, skill \n");
fprintf(fp, "%d, %s, %s \n", 1, "sword", "play");
fprintf(fp, "%d, %s, %s \n", 2, "hugh", "code");
fprintf(fp, "%d, %s, %s \n", 3, "sword", "dance");
fprintf(fp, "%d, %s, %s \n", 4, "sword", "sing");
fclose(fp);
fp = fopen(filename, "r");
int line;
char str_line[MAX_LINE];
char* comma = ",";
char* temp;
char* id;
//第一行为项
fgets(str_line, MAX_LINE, fp);
int rowI = 0;
while (!feof(fp))
{
rowI++;
fgets(str_line, MAX_LINE, fp);
id = strtok(str_line,comma);
if (id == NULL) break;
printf("%s", id);
while((temp = strtok(NULL,comma))!= NULL)
{
printf("%s", temp);
}
}
fclose(fp);
}
```<file_sep>### TCP/HTTP区别
TCP协议对应于传输层,而HTTP协议对应于应用层,从本质上来说,二者没有可比性。Http协议是建立在TCP协议基础之上的,当浏览器需要从服务器获取网页数据的时候,会发出一次Http请求。
Http会通过TCP建立起一个到服务器的连接通道,当本次请求需要的数据完毕后,Http会立即将TCP连接断开,这个过程是很短的。所以Http连接是一种短连接,是一种无状态的连接。所谓的无状态,是指浏览器每次向服务器发起请求的时候,不是通过一个连接,而是每次都建立一个新的连接。如果是一个连接的话,服务器进程中就能保持住这个连接并且在内存中记住一些信息状态。而每次请求结束后,连接就关闭,相关的内容就释放了,所以记不住任何状态,成为无状态连接。
随着时间的推移,html页面变得复杂了,里面可能嵌入了很多图片,这时候每次访问图片都需要建立一次tcp连接就显得低效了。因此Keep-Alive被提出用来解决效率低的问题。从HTTP/1.1起,默认都开启了Keep-Alive,保持连接特性,简单地说,当一个网页打开完成后,客户端和服务器之间用于传输HTTP数据的TCP连接不会关闭,如果客户端再次访问这个服务器上的网页,会继续使用这一条已经建立的连接Keep-Alive不会永久保持连接,它有一个保持时间,可以在不同的服务器软件(如Apache)中设定这个时间。
虽然这里使用TCP连接保持了一段时间,但是这个时间是有限范围的,到了时间点依然是会关闭的,所以我们还把其看做是每次连接完成后就会关闭。后来,通过Session, Cookie等相关技术,也能保持一些用户的状态。但是还是每次都使用一个连接,依然是无状态连接。
HTTP是一个属于应用层的面向对象的协议,由于其简捷、快速的方式,适用于分布式超媒体信息系统。它于1990年提出,经过几年的使用与发展,得到不断地完善和扩展。目前在WWW中使用的是HTTP/1.0的第六版,HTTP/1.1的规范化工作正在进行之中,而且HTTP-NG(Next Generation of HTTP)的建议已经提出。
HTTP协议的主要特点可概括如下:
1.支持客户/服务器模式。
2.简单快速:客户向服务器请求服务时,只需传送请求方法和路径。请求方法常用的有GET、HEAD、POST。每种方法规定了客户与服务器联系的类型不同。由于HTTP协议简单,使得HTTP服务器的程序规模小,因而通信速度很快。
3.灵活:HTTP允许传输任意类型的数据对象。正在传输的类型由Content-Type加以标记。
4.无连接:无连接的含义是限制每次连接只处理一个请求。服务器处理完客户的请求,并收到客户的应答后,即断开连接。采用这种方式可以节省传输时间。
5.无状态:HTTP协议是无状态协议。无状态是指协议对于事务处理没有记忆能力。缺少状态意味着如果后续处理需要前面的信息,则它必须重传,这样可能导致每次连接传送的数据量增大。另一方面,在服务器不需要先前信息时它的应答就较快。
### TCP/UDP 区别
#### 1. 对比
| | UDP | TCP |
| :----------- | :----------------------------------------- | :------------------------------------- |
| 是否连接 | 无连接 | 面向连接 |
| 是否可靠 | 不可靠传输,不使用流量控制和拥塞控制 | 可靠传输,使用流量控制和拥塞控制 |
| 连接对象个数 | 支持一对一,一对多,多对一和多对多交互通信 | 只能是一对一通信 |
| 传输方式 | 面向报文 | 面向字节流 |
| 首部开销 | 首部开销小,仅8字节 | 首部最小20字节,最大60字节 |
| 适用场景 | 适用于实时应用(IP电话、视频会议、直播等) | 适用于要求可靠传输的应用,例如文件传输 |
1. TCP是需要进行连接的,UDP是无连接通信;
2. UDP只保证发送的数据的完整性,没有应答机制,不保证数据的送达,因此会存在丢包,乱序的问题;
3. TCP有拥塞控制,UDP没有;
#### 2. 总结
- TCP向上层提供面向连接的可靠服务 ,UDP向上层提供无连接不可靠服务。
- 虽然 UDP 并没有 TCP 传输来的准确,但是也能在很多实时性要求高的地方有所作为
- 对数据准确性要求高,速度可以相对较慢的,可以选用TCP
#### 1. TCP连接过程
如下图所示,可以看到建立一个TCP连接的过程为(三次握手的过程):

**第一次握手**
客户端向服务端发送连接请求报文段。该报文段中包含自身的数据通讯初始序号。请求发送后,客户端便进入 SYN-SENT 状态。
**第二次握手**
服务端收到连接请求报文段后,如果同意连接,则会发送一个应答,该应答中也会包含自身的数据通讯初始序号,发送完成后便进入 SYN-RECEIVED 状态。
**第三次握手**
当客户端收到连接同意的应答后,还要向服务端发送一个确认报文。客户端发完这个报文段后便进入 ESTABLISHED 状态,服务端收到这个应答后也进入 ESTABLISHED 状态,此时连接建立成功。
这里可能大家会有个疑惑:为什么 TCP 建立连接需要三次握手,而不是两次?这是因为这是为了防止出现失效的连接请求报文段被服务端接收的情况,从而产生错误。

#### 2. TCP断开链接

TCP 是全双工的,在断开连接时两端都需要发送 FIN 和 ACK。
**第一次握手**
若客户端 A 认为数据发送完成,则它需要向服务端 B 发送连接释放请求。
**第二次握手**
B 收到连接释放请求后,会告诉应用层要释放 TCP 链接。然后会发送 ACK 包,并进入 CLOSE_WAIT 状态,此时表明 A 到 B 的连接已经释放,不再接收 A 发的数据了。但是因为 TCP 连接是双向的,所以 B 仍旧可以发送数据给 A。
**第三次握手**
B 如果此时还有没发完的数据会继续发送,完毕后会向 A 发送连接释放请求,然后 B 便进入 LAST-ACK 状态。
**第四次握手**
A 收到释放请求后,向 B 发送确认应答,此时 A 进入 TIME-WAIT 状态。该状态会持续 2MSL(最大段生存期,指报文段在网络中生存的时间,超时会被抛弃) 时间,若该时间段内没有 B 的重发请求的话,就进入 CLOSED 状态。当 B 收到确认应答后,也便进入 CLOSED 状态。
### TCP的滑动窗口
作者:wuxinliulei
链接:https://www.zhihu.com/question/32255109/answer/68558623
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
1)TCP滑动窗口分为接受窗口,发送窗口
滑动窗口协议是**传输层进行流控**的一种措施,**接收方通过通告发送方自己的窗口大小**,从而控制发送方的发送速度,从而达到防止发送方发送速度过快而导致自己被淹没的目的。
对ACK的再认识,ack通常被理解为收到数据后给出的一个确认ACK,ACK包含两个非常重要的信息:
**一是期望接收到的下一字节的序号n,该n代表接收方已经接收到了前n-1字节数据,此时如果接收方收到第n+1字节数据而不是第n字节数据,****接收方是不会发送序号为n+2的ACK的。**举个例子,假如接收端收到1-1024字节,它会发送一个确认号为1025的ACK,但是接下来收到的是2049-3072,它是不会发送确认号为3072的ACK,而依旧发送1025的ACK。
**二是当前的窗口大小m,如此发送方在接收到ACK包含的这两个数据后就可以计算出还可以发送多少字节的数据给对方,假定当前发送方已发送到第x字节,则可以发送的字节数就是y=m-(x-n).这就是滑动窗口控制流量的基本原理**
**重点:发送方根据收到ACK当中的期望收到的下一个字节的序号n以及窗口m,还有当前已经发送的字节序号x,算出还可以发送的字节数。**
**发送端窗口的第一个字节序号一定是ACK中期望收到的下一个字节序号,比如下图:**
**<img src="https://pic1.zhimg.com/50/9c21786770459afa47bfa2e4606cc454_hd.jpg?source=1940ef5c" data-rawwidth="667" data-rawheight="216" class="origin_image zh-lightbox-thumb" width="667" data-original="https://pic2.zhimg.com/9c21786770459afa47bfa2e4606cc454_r.jpg?source=1940ef5c"/>上图52 53 54 55 字节都是可以新发送的字节序**
**接受端窗口的第一个字节序之前一定是已经完全接收的,后面窗口里面的数据都是希望接受的,窗口后面的数据都是不希望接受的。**
```text
http://blog.chinaunix.net/uid-20778955-id-539945.html
http://www.netis.com.cn/flows/2012/08/tcp-%E6%BB%91%E
5%8A%A8%E7%AA%97%E5%8F%A3%E7%9A%84%E7%AE%80%E4%BB%8B/
```
TCP的滑动窗口分为接收窗口和发送窗口
不分析这两种窗口就讨论是不妥当的。
TCP的滑动窗口主要有两个作用,一是提供TCP的可靠性,二是提供TCP的流控特性。同时滑动窗口机制还体现了TCP面向字节流的设计思路。TCP 段中窗口的相关字段。
<img src="https://pic3.zhimg.com/50/d6b970fb6d44aafeeec4a4c9d61a9225_hd.jpg?source=1940ef5c" data-rawwidth="620" data-rawheight="197" class="origin_image zh-lightbox-thumb" width="620" data-original="https://pic1.zhimg.com/d6b970fb6d44aafeeec4a4c9d61a9225_r.jpg?source=1940ef5c"/>
TCP的Window是一个16bit位字段,它代表的是窗口的字节容量,也就是TCP的标准窗口最大为2^16-1=65535个字节。
另外在TCP的选项字段中还包含了一个TCP窗口扩大因子,option-kind为3,option-length为3个字节,option-data取值范围0-14。窗口扩大因子用来扩大TCP窗口,可把原来16bit的窗口,扩大为31bit。
**滑动窗口基本原理**
1)对于TCP会话的发送方,任何时候在其发送缓存内的数据都可以分为4类,“已经发送并得到对端ACK的”,“已经发送但还未收到对端ACK的”,“未发送但对端允许发送的”,“未发送且对端不允许发送”。“已经发送但还未收到对端ACK的”和“未发送但对端允许发送的”这两部分数据称之为发送窗口。
<img src="https://pic1.zhimg.com/50/a1d5c050ad957880094a5f003b1ccd24_hd.jpg?source=1940ef5c" data-rawwidth="664" data-rawheight="177" class="origin_image zh-lightbox-thumb" width="664" data-original="https://pic1.zhimg.com/a1d5c050ad957880094a5f003b1ccd24_r.jpg?source=1940ef5c"/>
当收到接收方新的ACK对于发送窗口中后续字节的确认是,窗口滑动,滑动原理如下图。
<img src="https://pic4.zhimg.com/50/9c21786770459afa47bfa2e4606cc454_hd.jpg?source=1940ef5c" data-rawwidth="667" data-rawheight="216" class="origin_image zh-lightbox-thumb" width="667" data-original="https://pic4.zhimg.com/9c21786770459afa47bfa2e4606cc454_r.jpg?source=1940ef5c"/>
当收到ACK=36时窗口滑动。
2)对于TCP的接收方,在某一时刻在它的接收缓存内存在3种。“已接收”,“未接收准备接收”,“未接收并未准备接收”(由于ACK直接由TCP协议栈回复,默认无应用延迟,不存在“已接收未回复ACK”)。其中“未接收准备接收”称之为接收窗口。
**发送窗口与接收窗口关系**
TCP是双工的协议,会话的双方都可以同时接收、发送数据。TCP会话的双方都各自维护一个“发送窗口”和一个“接收窗口”。其中各自的“接收窗口”大小取决于应用、系统、硬件的限制(TCP传输速率不能大于应用的数据处理速率)。各自的“发送窗口”则要求取决于对端通告的“接收窗口”,要求相同。
<img src="https://pic4.zhimg.com/50/c798dd393fcf7c03b1db78f5bcf0304b_hd.jpg?source=1940ef5c" data-rawwidth="675" data-rawheight="527" class="origin_image zh-lightbox-thumb" width="675" data-original="https://pic1.zhimg.com/c798dd393fcf7c03b1db78f5bcf0304b_r.jpg?source=1940ef5c"/>
**滑动窗口实现面向流的可靠性**
1)最基本的传输可靠性来源于“确认重传”机制。
2)TCP的滑动窗口的可靠性也是建立在“确认重传”基础上的。
3)发送窗口只有收到对端对于本段发送窗口内字节的ACK确认,才会移动发送窗口的左边界。
4)接收窗口只有在前面所有的段都确认的情况下才会移动左边界。当在前面还有字节未接收但收到后面字节的情况下,窗口不会移动,并不对后续字节确认。以此确保对端会对这些数据重传。
**滑动窗口的流控特性**
TCP的滑动窗口是动态的,我们可以想象成小学常见的一个数学题,一个水池,体积V,每小时进水量V1,出水量V2。当水池满了就不允许再注入了,如果有个液压系统控制水池大小,那么就可以控制水的注入速率和量。这样的水池就类似TCP的窗口。应用根据自身的处理能力变化,通过本端TCP接收窗口大小控制来对对对端的发送窗口流量限制。
应用程序在需要(如内存不足)时,通过API通知TCP协议栈缩小TCP的接收窗口。然后TCP协议栈在下个段发送时包含新的窗口大小通知给对端,对端按通知的窗口来改变发送窗口,以此达到减缓发送速率的目的。
### Unity DTOS
#### ECS
ECS+JOB System 可以
#### Brust
### AssetBundle
https://www.cnblogs.com/wang-jin-fu/p/11171626.html
### IL2CPP(Intermediate Language)
在Unity博客和本文中,IL和CIL表示的是同一个东西:翻译过来就是中间语言。它是一种属于 通用语言架构和.NET框架的低阶(lowest-level)的人类可读的编程语言。目标为.NET框架的语言被编译成CIL,然后汇编成字节码。 CIL类似一个面向对象的汇编语言,并且它是完全基于堆栈的,它运行在虚拟机上(.Net Framework, Mono VM)的语言。
具体过程是:C#或者VB这样遵循CLI规范的高级语言,被先被各自的编译器编译成中间语言:IL(CIL),等到需要真正执行的时候,这些IL会被加载到运行时库,也就是VM中,由VM动态的编译成汇编代码(JIT)然后在执行。

正是由于引入了VM,才使得很多动态代码特性得以实现。通过VM我们甚至可以由代码在运行时生成新代码并执行。这个是静态编译语言所无法做到的。回到上一 节我说的Boo和Unity Script,有了IL和VM的概念我们就不难发现,这两者并没有对应的VM虚拟机,Unity中VM只有一个:Mono VM,也就是说Boo和Unity Script是被各自的编译器编译成遵循CLI规范的IL,然后再由Mono VM解释执行的。这也是Unity Script和JavaScript的根本区别。JavaScript是最终在浏览器的JS解析器中运行的(例如大名鼎鼎的Google Chrome V8引擎),而Unity Script是在Mono VM中运行的。本质上说,到了IL这一层级,它是由哪门高级语言创建的也不是那么重要了,你可以用C#,VB,Boo,Unity Script甚至C++,只要有相应的编译器能够将其编译成IL都行!
本 文的主角终于出来了:IL2CPP。有了上面的知识,大家很容易就理解其意义了:把IL中间语言转换成CPP文件。大家如果看明白了上面动态语言的 CLI, IL以及VM,再看到IL2CPP一定心中充满了疑惑。现在的大趋势都是把语言加上动态特性,哪怕是c++这样的静态语言,也出现了适合IL的c++编译 器,为啥Unity要反其道而行之,把IL再弄回静态的CPP呢?这不是吃饱了撑着嘛。根据本文最前面给出的Unity官方博客所解释的,原因有以下几 个:
1.Mono VM在各个平台移植,维护非常耗时,有时甚至不可能完成
Mono的跨平台是通过Mono VM实现的,有几个平台,就要实现几个VM,像Unity这样支持多平台的引擎,Mono官方的VM肯定是不能满足需求的。所以针对不同的新平 台,Unity的项目组就要把VM给移植一遍,同时解决VM里面发现的bug。这非常耗时耗力。这些能移植的平台还好说,还有比如WebGL这样基于浏览 器的平台。要让WebGL支持Mono的VM几乎是不可能的。
2.Mono版本授权受限
大家有没有意识到Mono的版本已经更新到3.X了,但是在Unity中,C#的运行时版本一直停留在2.8,这也是Unity社区开发者抱怨的最多一 条:很多C#的新特性无法使用。这是因为Mono 授权受限,导致Unity无法升级Mono。如果换做是IL2CPP,IL2CPP VM这套完全自己开发的组件,就解决了这个问题。
3.提高运行效率
根据官方的实验数据,换成IL2CPP以后,程序的运行效率有了1.5-2.0倍的提升。
使用Mono的时候,脚本的编译运行如下图所示:

简单的来说,3大脚本被编译成IL,在游戏运行的时候,IL和项目里其他第三方兼容的DLL一起,放入Mono VM虚拟机,由虚拟机解析成机器码,并且执行
IL2CPP做的改变由下图红色部分标明:

在得到中间语言IL后,使用IL2CPP将他们重新变回C++代码,然后再由各个平台的C++编译器直接编译成能执行的原生汇编代码。
**几点注意:**
1.将IL变回CPP的目的除了CPP的执行效率快以外,另一个很重要的原因是可以利用现成的在各个平台的C++编译器对代码执行编译期优化,这样可以进一步减小最终游戏的尺寸并提高游戏运行速度。
\2. 由于动态语言的特性,他们多半无需程序员太多关心内存管理,所有的内存分配和回收都由一个叫做GC(Garbage Collector)的组件完成。虽然通过IL2CPP以后代码变成了静态的C++,但是内存管理这块还是遵循C#的方式,这也是为什么最后还要有一个 IL2CPP VM的原因:它负责提供诸如GC管理,线程创建这类的服务性工作。但是由于去除了IL加载和动态解析的工作,使得IL2CPP VM可以做的很小,并且使得游戏载入时间缩短。
3.由于C++是一门静态语言,这就意味着我们不能使用动态语言的那些酷炫特性。运行时生 成代码并执行肯定是不可能了。这就是Unity里面提到的所谓AOT(Ahead Of Time)编译而非JIT(Just In Time)编译。其实很多平台出于安全的考虑是不允许JIT的,大家最熟悉的有iOS平台,在Console游戏机上,不管是微软的Xbox360, XboxOne,还是Sony的PS3,PS4,PSV,没有一个是允许JIT的。使用了IL2CPP,就完全是AOT方式了,如果原来使用了动态特性的 代码肯定会编译失败。这些代码在编译iOS平台的时候天生也会失败,所以如果你是为iOS开发的游戏代码,就不用担心了。因此就这点而言,我们开发上几乎 不会感到什么问题。
最后给出Unite 2014上官方给出的性能测试截图(数字越小表示运行得越快):


有了IL2CPP,程序尺寸可以相对缩小,运行速度可以提高!看了兴奋吗?其实现有的Unity版本中已经引入了IL2CPP技术。本文下篇就通过一个实际的例子,看看IL2CPP都为我们做了哪些,以及我们需要注意些什么。
### Update FixedUpdate
### 使用了哪些设计模式
### 工具设计
### Unity Canvas
### Batch的规则
https://zhuanlan.zhihu.com/p/103612944
https://blog.csdn.net/akak2010110/article/details/80953370
### Dictionary
##### 1. 哈希冲突情况下的优化方案 - > 当链表长度大于8的时候,转红黑树
### List
### 进程间通信方式
<file_sep>using System;
using System.Collections.Generic;
public class SortedStack<T> where T : IComparable<T>
{
public int Count { get { return container.Count; } }
public bool IsIncrement { get; private set; }
private Stack<T> container;
public SortedStack(bool _isIncrement)
{
IsIncrement = _isIncrement;
container = new Stack<T>();
}
public SortedStack(bool _isIncrement, int capacity)
{
IsIncrement = _isIncrement;
container = new Stack<T>(capacity);
}
public void Push(T item)
{
if (container.Count > 0)
{
while (container.Count > 0)
{
if ((container.Peek().CompareTo(item) >= 0) != IsIncrement)
{
container.Push(item);
return;
}
else
{
container.Pop();
}
}
}
else
{
container.Push(item);
}
}
public T Pop()
{
return container.Pop();
}
public T Peek()
{
return container.Peek();
}
}<file_sep>---
layout: post
title: "Python学习2-反射"
subtitle: " \"Python学习\""
date: 2018-04-15 23:19:00
author: "Mas9uerade"
header-img: "img/watchdog2_sf.jpg"
tags:
- Python
---
> “上周简单地学习了Python的基础语法和API,整理一下加深理解和印象”
## Python中的反射
Pyhthon可查类型、可反射。
反射的方式有:
1.type()查类型;
```python
a = str("sssss")
print(type([]) )
print(type({}))
print(type(''))
print(type(0.0))
```
2.isinstance()查引用;
```python
class Plant:
life = 0
pass
class Tree(Plant): pass # Dummy class derived from Plant
tree = Tree() # A new instance of Tree class
print("isinstance")
print (isinstance(tree, Tree)) # True
print (isinstance(tree, Plant)) # True
print (isinstance(tree, object) ) # True
print (type(tree) is Tree) # False
print (type(tree).__name__ == "instance") # True
print (tree.__class__.__name__ == "Tree") # True
```
3.issubclass()查继承;
```python
print("isubclass")
print (issubclass(Tree, Plant)) # True
print (issubclass(Tree, object)) # False in Python 2
print (issubclass(int, object)) # True
#print (issubclass(tree, Plant)) # Error - tree is not a class
```
4.callable()是否可调用;
```python
print("callable")
print(callable([1,2].pop))
print(callable([1,2].pop()))
```
5.dir()查包含的属性名;
```python
print("Dir")
print(dir(3))
print(dir("HelloWorld"))
print(dir([1,2]))
print(dir(re))
```
6. getattr() 第一个参数是对象实例obj,name是个字符串,是对象的成员函数名字或者成员变量,default当对象没有这个属相的时候就返回默认值,如果没有提供默认值就返回异常。
```python
print("attribute")
print(getattr(tree, "life"))
#print(getattr(tree, "life?")) 没有就会报错
print(getattr(tree, "life?", None))
```
<file_sep>//1249. 移除无效的括号
//给你一个由 '('、')' 和小写字母组成的字符串 s。
//你需要从字符串中删除最少数目的 '(' 或者 ')' (可以删除任意位置的括号),使得剩下的「括号字符串」有效。
//请返回任意一个合法字符串。
//有效「括号字符串」应当符合以下 任意一条 要求:
//空字符串或只包含小写字母的字符串
//可以被写作 AB(A 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」
//可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」
//示例 1:
//输入:s = "lee(t(c)o)de)"
//输出:"lee(t(c)o)de"
//解释:"lee(t(co)de)" , "lee(t(c)ode)" 也是一个可行答案。
//示例 2:
//输入:s = "a)b(c)d"
//输出:"ab(c)d"
//示例 3:
//输入:s = "))(("
//输出:""
//解释:空字符串也是有效的
//示例 4:
//输入:s = "(a(b(c)d)"
//输出:"a(b(c)d)"
//提示:
//1 <= s.length <= 10^5
//s[i] 可能是 '('、')' 或英文小写字母
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/minimum-remove-to-make-valid-parentheses
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
using System.Collections.Generic;
using System.Text;
namespace ByteDancePopular
{
public partial class Solution
{
public string MinRemoveToMakeValid(string s)
{
Stack<int> left = new Stack<int>();
Stack<int> right = new Stack<int>();
for (int i = 0; i < s.Length; ++i)
{
if (s[i] == '(')
{
left.Push(i);
}
else if (s[i] ==')')
{
right.Push(i);
}
}
List<int> removeIndex = new List<int>();
while (right.Count > 0)
{
int indexR = right.Pop();
//在右括号之后的左括号,为废括号,需要删除
while(left.Count > 0 && left.Peek() > indexR)
{
removeIndex .Add(left.Pop());
}
//如果匹配上左括号,则考虑下一个右括号
if (left.Count > 0 && left.Peek() < indexR)
{
left.Pop();
continue;
}
else
{
removeIndex.Add(indexR);
}
}
//若有剩余的右括号/左括号,全部删除
while (left.Count > 0)
{
removeIndex.Add(left.Pop());
}
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < removeIndex.Count; ++i)
{
sb.Remove(removeIndex[i], 1);
}
return sb.ToString();
}
}
}<file_sep> public int LengthOfLongestSubstring(string s)
{
if (string.IsNullOrEmpty(s))
{
return 0;
}
if (s.Length == 1)
{
return 1;
}
List<char> charCollection = new List<char>();
int max = 0;
//滑动窗口实现
for (int i = 0; i < s.Length; ++i)
{
if (charCollection.Contains(s[i]))
{
int index = charCollection.IndexOf(s[i]);
charCollection.RemoveRange(0, index+1);
}
charCollection.Add(s[i]);
max = Math.Max(max, charCollection.Count);
}
return max;
}<file_sep>public class Solution {
public int MinimumOperations(string leaves)
{
int n = leaves.Length;
int[,] dp = new int[3, n];
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < n; ++j)
{
dp[i, j] = 100000000;
}
}
dp[0, 0] = leaves[0] == 'r' ? 0 : 1;
for (int i = 1; i < n; i++)
{
//第一步,计算把 0~ n全红的cost
dp[0, i] = dp[0, i - 1] + (leaves[i] == 'y' ? 1 : 0);
//第二步,计算 从0~n全红到 1~n 全黄的cost
dp[1, i] = Math.Min(dp[0, i - 1], dp[1, i - 1]) + (leaves[i] == 'r' ? 1 : 0);
//第三步, 计算从 1~n 全黄 到2~n全红的cost
dp[2, i] = Math.Min(dp[1, i - 1], dp[2, i - 1]) + (leaves[i] == 'y' ? 1 : 0);
}
return dp[2, n - 1];
}
}<file_sep>//23.合并K个升序链表
//给你一个链表数组,每个链表都已经按升序排列。
//请你将所有链表合并到一个升序链表中,返回合并后的链表。
//示例 1:
//输入:lists = [[1, 4, 5],[1,3,4],[2,6]]
//输出:[1,1,2,3,4,4,5,6]
//解释:链表数组如下:
//[
// 1->4->5,
// 1->3->4,
// 2->6
//]
//将它们合并到一个有序链表中得到。
//1->1->2->3->4->4->5->6
//示例 2:
//输入:lists = []
//输出:[]
//示例 3:
//输入:lists = [[]]
//输出:[]
//提示:
//k == lists.length
//0 <= k <= 10 ^ 4
//0 <= lists[i].length <= 500
//- 10 ^ 4 <= lists[i][j] <= 10 ^ 4
//lists[i] 按 升序 排列
//lists[i].length 的总和不超过 10^4
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
// 思路
// 1. 堆排序/优先队列,逐个插入, 小根堆实现
// 2. 分治,两两合并
namespace ByteDancePopular
{
public partial class Solution
{
public ListNode MergeKLists(ListNode[] lists)
{
if (lists == null || lists.Length == 0)
{
return null;
}
return Merge(lists, 0, lists.Length - 1);
}
public ListNode Merge(ListNode[] lists, int l, int r)
{
if (l == r)
{
return lists[l];
}
if (l > r)
{
return null;
}
int mid = (l + r) / 2;
return MergeTwoSortedLinkLists(Merge(lists, l, mid), Merge(lists, mid + 1, r));
}
public ListNode MergeTwoSortedLinkLists( ListNode l1, ListNode l2)
{
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode head = new ListNode();
ListNode tail = head;
ListNode tl1 = l1;
ListNode tl2 = l2;
while (tl1 != null && tl2!=null)
{
if (tl1.val < tl2.val)
{
tail.next = tl1;
tl1 = tl1.next;
}
else
{
tail.next = tl2;
tl2 = tl2.next;
}
tail = tail.next;
}
tail.next = tl1 == null ? tl2 : tl1;
return head.next;
}
}
}
<file_sep>---
layout: post
title: "Unity3d Shader 学习笔记 3"
subtitle: " \"Unity Shader 入门笔记\""
date: 2020-10-26 22:34:00
author: "Mas9uerade"
header-img: "img/title_holography_s1.png"
tags:
- Unity3d
- Shader
---
> 最近这段时间在找工作,顺便把之前项目里做的一些Shader重新看一遍
### 半透明材质

思路:
就是在uv的贴图上,额外增加Alpha通道的权重处理,再放在全黑的环境下显示
```C
Shader "Custom/Holography"
{
Properties
{
_MainTex("Sprite Texture", 2D) = "white" {}
_Color("Color", Color) = (1.0000, 1.0000, 1.0000, 1.0000)
}
SubShader
{
Tags
{
"RenderType" = "Transparent"
}
ZWrite Off
Cull Off
Blend One One
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "UnityUI.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
half2 uv : TEXCOORD0;
};
sampler2D _MainTex;
uniform float4 _MainTex_ST;
uniform float4 _Color;
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv) * _Color;
col.rgb *= col.a * _Color.a;
return col;
}
ENDCG
}
}
}
```
<file_sep>//528.按权重随机选择
//给定一个正整数数组 w ,其中 w[i] 代表下标 i 的权重(下标从 0 开始),请写一个函数 pickIndex ,它可以随机地获取下标 i,选取下标 i 的概率与 w[i] 成正比。
//例如,对于 w = [1, 3],挑选下标 0 的概率为 1 / (1 + 3) = 0.25 (即,25 %),而选取下标 1 的概率为 3 / (1 + 3) = 0.75(即,75 %)。
//也就是说,选取下标 i 的概率为 w[i] / sum(w) 。
//示例 1:
//输入:
//["Solution","pickIndex"]
//[[[1]],[]]
//输出:
//[null,0]
//解释:
//Solution solution = new Solution([1]);
//solution.pickIndex(); // 返回 0,因为数组中只有一个元素,所以唯一的选择是返回下标 0。
//示例 2:
//输入:
//["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
//[[[1,3]],[],[],[],[],[]]
//输出:
//[null,1,1,1,1,0]
//解释:
//Solution solution = new Solution([1, 3]);
//solution.pickIndex(); // 返回 1,返回下标 1,返回该下标概率为 3/4 。
//solution.pickIndex(); // 返回 1
//solution.pickIndex(); // 返回 1
//solution.pickIndex(); // 返回 1
//solution.pickIndex(); // 返回 0,返回下标 0,返回该下标概率为 1/4 。
//由于这是一个随机问题,允许多个答案,因此下列输出都可以被认为是正确的:
//[null,1,1,1,1,0]
//[null,1,1,1,1,1]
//[null,1,1,1,0,0]
//[null,1,1,1,0,1]
//[null,1,0,1,0,0]
//......诸若此类。
//提示:
//1 <= w.length <= 10000
//1 <= w[i] <= 10 ^ 5
//pickIndex 将被调用不超过 10000 次
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/random-pick-with-weight
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//思路 前缀和 + 二分查找
using System;
namespace ByteDancePopular.BinarySearch.RandomPickWithWeight
{
public class Solution
{
int[] wSum;
Random rd;
public Solution(int[] w)
{
rd = new Random();
wSum = new int[w.Length];
wSum[0] = w[0];
for (int i = 1; i <wSum.Length; ++i)
{
wSum[i] = wSum[i-1] + w[i];
}
}
public int PickIndex()
{
int prvoit = rd.Next(0,wSum[wSum.Length - 1]);
int left = 0, right = wSum.Length - 1;
while (left < right)
{
int mid = (left + right) / 2;
//左半区
if (wSum[mid] > prvoit)
{
right = mid;
}
else
{
left = mid + 1;
}
}
return left;
}
}
}<file_sep>---
layout: post
title: "3D数学基础"
subtitle: " \"向量,矩阵,坐标系\""
date: 2020-12-2 18:15:46
author: "Mas9uerade"
header-img: ""
tags:
- 3D数学
---
> 面试被问了向量,矩阵,旋转矩阵,四元数的问题,需要好好总结一下
>
> 摘抄自 [【Unity技巧】四元数(Quaternion)和旋转](https://blog.csdn.net/candycat1992/article/details/41254799)
# 3D数学基础
## 向量
#### 1. 向量的加减
向量的加减就是每个值的加减
#### 2. 向量的Magnitude
向量的每个分量平方后相加再开根号
#### 3. 向量的点积
点积, 又称内积(Inner Product), dot满足交换率
几何意义:
1. 一个向量在另一个向量上的投影;
2. 点积求Magnitude
3. 点积可以求夹角( cos)
#### 4. 向量的叉积
叉积(cross product),又称外积(outer product),叉积的结果是一个向量
$$
a \times b = (a_x, a_y, a_z) \times (b_x, b_y, b_z) = (a_yb_z - a_zb_y, a_zb_x - a_xb_z, a_xb_y - a_yb_x)
$$
1. 叉积不满足交换律,满足反交换律
2. **叉积的模 等于 a 和b的模再乘于他们间夹角的正弦值**
$$
|a \times b| = |a| |b| sin(\theta)
$$
3. 叉积可以计算平行四边形的面积
## 矩阵
#### 1. 矩阵的乘法
矩阵A (r x n)与矩阵B(n x c)相乘,形成的矩阵是(r x c)大小的
$$
c_{ij} = sum (a_{i1}b_{1j} + a_{i2}b_{2j} +…… + a_{in}b_{nj} = \sum_{k=1}^na_{ik}b_{kj}
$$

**1. 矩阵的乘法不满足交换律 **
**2. 矩阵乘法满足结合律 **
#### 2. 特殊矩阵
**1.方块矩阵**
对角矩阵
**2.单位矩阵**
和任何矩阵相乘都是原来的矩阵
**3.转置矩阵**
转置矩阵是原矩阵的反转 (Transposed Matrix)
**矩阵的转置的转置等于原矩阵**
**4. 逆矩阵**
逆矩阵与原矩阵相乘会是一个单位矩阵
$$
MM^{-1} = I
$$
**性质一:**
**逆矩阵的逆矩阵是原矩阵的本身。**
$$
(M^{-1})^{-1} = M
$$
**性质二:**
**单位矩阵的逆矩阵是它本身**
$$
I^{-1}=I
$$
**性质三:**
**转置矩阵的逆矩阵是逆矩阵的转置**
$$
(M^(T))^{-1} = (M^{-1})^T
$$
**性质四:**
**矩阵串接相乘后的逆矩阵等于反响串接个个矩阵的逆矩阵**
$$
(AB)^{-1} = B^{-1}A^{-1}
$$
$$
(ABCD)^{-1} = D^{-1}C^{-1}B^{-1}A^{-1}
$$
**逆矩阵的几何意义**
**矩阵可以表示一个变换,那么逆矩阵允许我们还原这个变换,或者说是这个变换的反向变换。**
如果我们用变换矩阵M对向量v做了一次变换,然后使用它的逆矩阵 $M^{-1}$ 进行另一次的变换,我们就会得到原来的向量
$$
M^{-1} (Mv) =(M^{-1}M)v = Iv = v
$$
**5.正交矩阵**
正交是矩阵的一个属性,如果一个方阵和它的转置矩阵的乘积是单位矩阵的话,那么这个矩阵即为正交矩阵
$$
MM^T = M^TM =I
$$
矩阵的正交即意味着
$$
M^T = M^{-1}
$$
正交矩阵的特点:
* **矩阵的每一行,即 $c_1, c_2, c_3 $ 都是单位矢量,只有这样他们和自己的点积为1**
* **矩阵的每一行,$ c_1,c_2, c_3 $ 之间互相垂直,只有这样他们之间的点积才能为0**
* **上述两条结论对矩阵的每一列同样适用,如果M是正交矩阵, M^T也会是正交矩阵**
## 矩阵变换
#### 线性变换 (linear transform)
线性变换指可以保留向量加和标量乘的变换。
$$
f(x) + f(y) = f(x+y)
$$
$$
kf(x) = f(kx)
$$
线性变换包括
缩放,
旋转,
错切,错切是在某方向上,按照一定的比例对图形的每个点到某条平行于该方向的直线的有向距离做放缩得到的平面图形。
[](https://baike.baidu.com/pic/错切/7024094/0/b2de9c82d158ccbf2d76e19e1ed8bc3eb035414f?fr=lemma&ct=single)
### 平面的水平和竖直错切
在平面

上,水平错切(或平行于X轴的错切)是一个将任一点

[映射](https://baike.baidu.com/item/映射)到点

的操作,

是固定参数,称为错切因子。
水平错切的效果是将每一点水平移动,移动的长度和该点的纵坐标成比例。若

则

轴上方的所有点都向右移动,

则

轴上方的所有点都向左移动,

轴下方点移动的方向对应相反,而

坐标轴上的点位置不变。平行于

轴的直线保持不变,其他所有线绕与

轴交点转动不同的角度;原来竖直的线则变成斜率

的斜线,如此参数

,

即竖直线倾斜后的倾角,称为错切角。
如果把点的坐标写成一个列向量,则错切可以表示成一个

的矩阵和坐标的乘积:
[](https://baike.baidu.com/pic/错切/7024094/0/7a899e510fb30f242c9caba7cf95d143ad4b030b?fr=lemma&ct=single)
竖直错切的操作类似,就是将x和y互换位置。转制矩阵如下:
(未知原因,图片无法插入)
经过竖直错切后,原来竖直的直线不变,其他线绕其与y轴交点旋转,原来水平的线变成斜率m的线。
### 广义错切
对于向量空间V和其子空间W,一个对于W的错切将变换所有和W平行的向量。
具体来讲,如果V是W和W'的直和,我们把V写成:

那么一个对于W的错切L即:

其中M是从W'到W的一个线性映射。用分块矩阵表示,则L写成:
$$
\begin{bmatrix}
I&M\\
M&I\\
\end{bmatrix}
$$
镜像,
正交投影。
平移变换是非线性的,
#### 仿射变换 (affine transform)
仿射变换是合并线性变换和平移变换的变换类型,可以用一个4x4的矩阵表示,因此我们需要把矢量扩展到四维空间下,即**齐次坐标空间(homogeneous space)**
| 变换名称 | 是否线性变换 | 是否仿射变换 | 是可逆矩阵 | 是正交矩阵 |
| ---------------------- | ------------ | ------------ | ---------- | ---------- |
| 平移矩阵 | N | Y | Y | N |
| 绕坐标轴旋转的旋转矩阵 | Y | Y | Y | Y |
| 绕任意轴的旋转矩阵 | Y | Y | Y | Y |
| 按坐标轴的缩放矩阵 | Y | Y | Y | N |
| 错切矩阵 | Y | Y | Y | N |
| 镜像矩阵 | Y | Y | Y | Y |
| 正交投影矩阵 | Y | Y | N | N |
| 透视投影矩阵 | N | N | N | N |
**齐次坐标空间**
齐次坐标是3x3的矩阵拓展到4x4的矩阵,对于一个点从三维坐标转换为齐次坐标需要把其w分量设置为1,对于方向矢量需要把其w分量设置为0。这样设置会导致,当用一个4x4的矩阵对一个点进行变换时,平移/旋转/缩放都会施用于该点,但若是用于一个方向矢量,平移效果就会被忽略。
#### 平移矩阵
平移矩阵可作用于点,但无法作用于方向向量
$$
\begin{bmatrix}
x&0&0&t_x\\
0&y&0&t_y\\
0&0&z&t_z\\
0&0&0&1
\end{bmatrix}
$$
平移矩阵的逆矩阵就是反向平移得到的矩阵,即
$$
\begin{bmatrix}
x&0&0&-t_x\\
0&y&0&-t_y\\
0&0&z&-t_z\\
0&0&0&1
\end{bmatrix}
$$
因此平移矩阵不是一个正交矩阵
#### 缩放矩阵
缩放矩阵可作用于点,且能作用于方向向量
$$
\begin{bmatrix}
k_x&0&0&0\\
0&k_y&0&0\\
0&0&k_z&0\\
0&0&0&1
\end{bmatrix}
$$
$$
如果 k_x,k_y,k_z 相等,则缩放为统一缩放, 否则为非统一缩放
$$
缩放矩阵的逆矩阵,为反向缩放得到的矩阵,即
$$
\begin{bmatrix}
1/k_x&0&0&0\\
0&1/k_y&0&0\\
0&0&1/k_z&0\\
0&0&0&1
\end{bmatrix}
$$
上述矩阵仅适用于沿坐标轴方向进行缩放。如果想要在任意方向上进行缩放,就需要使用一个复合变换,其中一种方法的主要思想就是,先将缩放周转换为标准坐标轴,然后进行坐标轴缩放,再用逆变换得到原来的缩放轴朝向。
#### 旋转矩阵
**绕X轴旋转**
$$
R_x(\theta) = \begin{bmatrix}
1&0&0&0\\
0&cos(\theta)& -sin(\theta)&0\\
0&sin(\theta)& cos(\theta)&0\\
0&0&0&1
\end{bmatrix}
$$
**绕Y轴旋转**
$$
R_y(\theta) = \begin{bmatrix}
cos(\theta)&0& sin(\theta)&0\\
0&1&0&0\\
-sin(\theta)&0& cos(\theta)&0\\
0&0&0&1
\end{bmatrix}
$$
**绕Z轴旋转**
$$
R_z(\theta) = \begin{bmatrix}
cos(\theta)&-sin(\theta)&0&0\\
sin(\theta)&cos(\theta)&0&0\\
0&0&1&0\\
0&0&0&1
\end{bmatrix}
$$
旋转矩阵的逆矩阵是旋转相反的角度得到的变换矩阵,旋转矩阵为正交矩阵,多个旋转矩阵的串联同样是正交。
#### 复合变换
**先缩放,再旋转,最后平移**
Unity旋转矩阵的旋转顺序是zxy。
$$
当给定一个旋转角度(\theta_x,\theta_y,\theta_z)时,得到的组合旋转矩是\\
M_{rotate_Z} M_{rotate_X} M_{rotate_Y} =
\begin{bmatrix}
cos(\theta_z)&-sin(\theta)&0&0\\
sin(\theta)&cos(\theta)&0&0\\
0&0&1&0\\
0&0&0&1\\
\end{bmatrix}
\begin{bmatrix}
cos(\theta)&0& sin(\theta)&0\\
0&1&0&0\\
-sin(\theta)&0& cos(\theta)&0\\
0&0&0&1\\
\end{bmatrix}
\begin{bmatrix}
1&0&0&0\\
0&cos(\theta)& -sin(\theta)&0\\
0&sin(\theta)& cos(\theta)&0\\
0&0&0&1\\
\end{bmatrix}
$$
当给定
#### 坐标空间变换
**定义一个坐标空间需要指明其原点位置以及3个坐标轴的方向,这是相对于其他空间的,因此每个空间都为其他空间的子空间,每个空间都会拥有父空间。**
坐标空间的变换即为在父空间和子空间之间对点和矢量进行变换。
因此,
$$
A_P = M_{C->P}A_C
$$
$$
A_c = M_{P->C}A_C
$$
$$
且M_{C->P} 与 M_{P->C}互为逆矩阵
$$
# 四元数介绍
[四元数](http://zh.wikipedia.org/wiki/四元數)又是什么呢?简单来说,四元数本质上是一种高阶复数,是一个四维空间,相对于复数的二维空间。我们高中的时候应该都学过复数,一个复数由实部和虚部组成,即x = a + bi,i是虚数单位,如果你还记得的话应该知道i^2 = -1。而四元数其实和我们学到的这种是类似的,不同的是,它的虚部包含了三个虚数单位,i、j、k,即一个四元数可以表示为x = a + bi + cj + dk。那么,它和旋转为什么会有关系呢?
在Unity里,tranform组件有一个变量名为rotation,它的类型就是四元数。很多初学者会直接取rotation的x、y、z,认为它们分别对应了Transform面板里R的各个分量。当然很快我们就会发现这是完全不对的。实际上,四元数的x、y、z和R的那三个值从直观上来讲没什么关系,当然会存在一个表达式可以转换,在后面会讲。
大家应该和我一样都有很多疑问,既然已经存在了这两种旋转表示方式,为什么还要使用四元数这种听起来很难懂的东西呢?我们先要了解这三种旋转方式的优缺点:
- **矩阵旋转**
- - 优点:
- - 旋转轴可以是任意向量;
- 缺点:
- - 旋转其实只需要知道一个向量+一个角度,一共4个值的信息,但矩阵法却使用了16个元素;
- 而且在做乘法操作时也会增加计算量,造成了空间和时间上的一些浪费;
- **欧拉旋转**
- - 优点:
- - 很容易理解,形象直观;
- 表示更方便,只需要3个值(分别对应x、y、z轴的旋转角度);但按我的理解,它还是转换到了3个3*3的矩阵做变换,效率不如四元数;
- 缺点:
- - 之前提到过这种方法是要按照一个固定的坐标轴的顺序旋转的,因此不同的顺序会造成不同的结果;
- 会造成[万向节锁](http://zh.wikipedia.org/wiki/萬向鎖)(Gimbal Lock)的现象。这种现象的发生就是由于上述固定坐标轴旋转顺序造成的。理论上,欧拉旋转可以靠这种顺序让一个物体指到任何一个想要的方向,但如果在旋转中不幸让某些坐标轴重合了就会发生万向节锁,这时就会丢失一个方向上的旋转能力,也就是说在这种状态下我们无论怎么旋转(当然还是要原先的顺序)都不可能得到某些想要的旋转效果,除非我们打破原先的旋转顺序或者同时旋转3个坐标轴。这里有个[视频](http://v.youku.com/v_show/id_XNzkyOTIyMTI=.html)可以直观的理解下;
- 由于万向节锁的存在,欧拉旋转无法实现球面平滑插值;
- **四元数旋转**
- - 优点:
- - 可以避免万向节锁现象;
- 只需要一个4维的四元数就可以执行绕任意过原点的向量的旋转,方便快捷,在某些实现下比旋转矩阵效率更高;
- 可以提供平滑插值;
- 缺点:
- - 比欧拉旋转稍微复杂了一点点,因为多了一个维度;
- 理解更困难,不直观;
# 四元数和欧拉角
## 基础知识
前面说过,一个四元数可以表示为q = w + xi + yj + zk,现在就来回答这样一个简单的式子是怎么和三维旋转结合在一起的。为了方便,我们下面使用q = ((x, y, z),w) = (v, w),其中v是向量,w是实数,这样的式子来表示一个四元数。
我们先来看问题的答案。我们可以使用一个四元数q=((x,y,z)sinθ2, cosθ2) 来执行一个旋转。具体来说,如果我们想要把空间的一个点P绕着单位向量轴u = (x, y, z)表示的旋转轴旋转θ角度,我们首先把点P扩展到四元数空间,即四元数p = (P, 0)。那么,旋转后新的点对应的四元数(当然这个计算而得的四元数的实部为0,虚部系数就是新的坐标)为:
p′=qpq−1
其中,q=(cosθ2, (x,y,z)sinθ2) ,q−1=q∗N(q),由于u是单位向量,因此
N(q)=1,即q−1=q∗。右边表达式包含了四元数乘法。相关的定义如下:
- **四元数乘法:**
$$
q_1q_2=(\vec{v_1}×\vec{v_2}+w_1\vec{v_2}+w_2\vec{v_1},w_1w_2−\vec{v_1}⋅\vec{v_2})
$$
- **共轭四元数:**
$$
q^∗=(−v⃗ ,w)
$$
- **四元数的模:**
$$
N(q) = \sqrt{(x^2 + y^2 + z^2 +w^2)}
$$
**即四元数到原点的距离**
- **四元数的逆:**
$$
q^{−1}=q∗N(q)
$$
它的证明这里不再赘述,有兴趣的可以参见[这篇文章](http://www.cnblogs.com/yiyezhai/p/3176725.html)。主要思想是构建了一个辅助向量k,它是将p绕旋转轴旋转θ/2得到的。证明过程尝试证明wk∗=kv∗,以此证明w与v、k在同一平面内,且与v夹角为θ。
我们举个最简单的例子:把点P(1, 0, 1)绕旋转轴u = (0, 1, 0)旋转90°,求旋转后的顶点坐标。首先将P扩充到四元数,即p = (P, 0)。而q = (u*sin45°, cos45°)。求p′=qpq−1的值。建议大家一定要在纸上计算一边,这样才能加深印象,连笔都懒得动的人还是不要往下看了。最后的结果p` = ((1, 0, -1), 0),即旋转后的顶点位置是(1, 0, -1)。
如果想要得到复合旋转,只需类似复合矩阵那样左乘新的四元数,再进行运算即可。
我们来总结下四元数旋转的**几个需要注意的地方**:
- 用于旋转的四元数,每个分量的范围都在(-1,1);
- 每一次旋转实际上需要两个四元数的参与,即q和q*;
- 所有用于旋转的四元数都是单位四元数,即它们的模是1;
下面是几点建议:
- 实际上,在Unity里即便你不知道上述公式和变换也丝毫不妨碍我们使用四元数,但是有一点要提醒你,**除非你对四元数非常了解,那么不要直接对它们进行赋值**。
- 如果你不想知道原理,只想在Unity里找到对应的函数来进行四元数变换,那么你可以使用这两个函数:[Quaternion.Euler](http://docs.unity3d.com/ScriptReference/Quaternion.Euler.html)和[Quaternion.eulerAngles](http://docs.unity3d.com/ScriptReference/Quaternion-eulerAngles.html)。它们基本可以满足绝大多数的四元数旋转变换。
## 和其他类型的转换
首先是***\*轴角到四元数\****:
给定一个单位长度的旋转轴(x, y, z)和一个角度θ。对应的四元数为:
q=((x,y,z)sinθ2, cosθ2)
这个公式的推导过程上面已经给出。
**欧拉角到四元数**:
给定一个欧拉旋转(X, Y, Z)(即分别绕x轴、y轴和z轴旋转X、Y、Z度),则对应的四元数为:
$$
x = sin(Y/2)sin(Z/2)cos(X/2)+cos(Y/2)cos(Z/2)sin(X/2)\\
y = sin(Y/2)cos(Z/2)cos(X/2)+cos(Y/2)sin(Z/2)sin(X/2)\\
z = cos(Y/2)sin(Z/2)cos(X/2)-sin(Y/2)cos(Z/2)sin(X/2)\\
w = cos(Y/2)cos(Z/2)cos(X/2)-sin(Y/2)sin(Z/2)sin(X/2)\\
q = ((x, y, z), w)
$$
它的证明过程可以依靠轴角到四元数的公式进行推导。
其他**参考链接**:
\1. [Euler to Quaternion](http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm)
\2. [Quaternion To Euler](http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm)
\3. [AngleAxis to Quaternion](http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
\4. [Quaternion to AngleAxis](http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm)
# 四元数的插值
这里的插值指的是球面线性插值。
设t是一个在0到1之间的变量。我们想要基于t求Q1到Q2之间插值后四元数Q。它的公式是:
$$
Q_3 = (sin((1-t)A)/sin(A))*Q_1 + (sin((tA)/sin(A))*Q_2)
$$
$$
Q = Q_3/|Q_3|,即单位化
$$
# 四元数的创建
在了解了上述知识后,我们就不需要那么惧怕四元数了,实际上它和矩阵类似,不同的只是它的表示方式以及运算方式。那么在Unity里如何利用四元数进行旋转呢?Unity里提供了非常多的方式来创建一个四元数。例如Quaternion.AngleAxis(float angle, Vector3 axis),它可以返回一个绕轴线axis旋转angle角度的四元数变换。我们可以一个Vector3和它进行左乘,就将得到旋转后的Vector3。在Unity里只需要用一个“ * ”操作符就可以进行四元数对向量的变换操作,相当于我们上述讲到的p′=qpq−1操作。如果我们想要进行多个旋转变换,只需要左乘其他四元数变换即可。例如下面这样:
```csharp
Vector3 newVector = Quaternion.AngleAxis(90, Vector3.up) * Quaternion.LookRotation(someDirection) * someVector;
```
尽管欧拉角更容易我们理解,但四元数比欧拉角要强大很多。Unity提供了这两种方式供我们选择,我们可以选择最合适的变换。
例如,如果我们需要对旋转进行插值,我们可以首先使用 Quaternion .eulerAngles 来得到欧拉角度,然后使用 Mathf.Clamp 对其进行插值运算。
最后更新Quaternion.eulerAngles或者使用Quaternion.Euler(yourAngles)来创建一个新的四元数。
又例如,如果你想要组合旋转,比如让人物的脑袋向下看或者旋转身体,两种方法其实都可以,但一旦这些旋转不是以世界坐标轴为旋转轴,比如人物扭动脖子向下看等,那么四元数是一个更合适的选择。Unity还提供了transform.forward, transform.right and transform.up 这些非常有用的轴,这些轴可以和Quaternion.AngleAxis组合起来,来创建非常有用的旋转组合。例如,下面的代码让物体执行低头的动作:
```csharp
transform.rotation = Quaternion.AngleAxis(degrees, transform.right) * transform.rotation;
```
关于Quaternion的其他函数,后面再补充吧,原理类似~
# 补充:欧拉旋转
在文章开头关于欧拉旋转的细节没有解释的太清楚,而又有不少人询问相关问题,我尽量把自己的理解写到这里,如有不对还望指出。
## 欧拉旋转是怎么运作的
欧拉旋转是我们最容易理解的一种旋转方式。以我们生活中为例,一个舞蹈老师告诉我们,完成某个舞蹈动作需要先向你的左边转30°,再向左侧弯腰60°,再起身向后弯腰90°(如果你能办到的话)。上面这样一个旋转的过程其实和我们在三维中进行欧拉旋转很类似,即我们是通过指明绕三个轴旋转的角度来进行旋转的,不同的是,日常生活中我们更愿意叫这些轴为前后左右上下。而这也意味着我们需要指明一个旋转顺序。这是因为,先绕X轴旋转90°、再绕Y轴30°和先绕Y轴旋转90°、再绕X轴30°得到的是不同的结果。
在Unity里,欧拉旋转的旋转顺序是Z、X、Y,这在相关的API文档中都有说明,例如[Transform.Rotate](http://docs.unity3d.com/ScriptReference/Transform.Rotate.html)。其实文档中说得不是非常详细,还有一个细节我们需要明白。如果你仔细想想,就会发现有一个非常重要的东西我们没有说明白,那就是旋转时使用的坐标系。给定一个旋转顺序(例如这里的Z、X、Y),以及它们对应的旋转角度(α,β,r),有两种坐标系可以选择:
1. 绕坐标系E下的Z轴旋转α,绕坐标系E下的Y轴旋转β,绕坐标系E下的X轴旋转r,即进行一次旋转时不一起旋转当前坐标系;
2. 绕坐标系E下的Z轴旋转α,绕坐标系E在绕Z轴旋转α后的新坐标系E'下的Y轴旋转β,绕坐标系E'在绕Y轴旋转β后的新坐标系E''下的X轴旋转r, 即在旋转时,把坐标系一起转动;
很容易知道,这两种选择的结果是不一样的。但如果把它们的旋转顺序颠倒一下,其实结果就会一样。说得明白点,在第一种情况下、按ZXY顺序旋转和在第二种情况下、按YXZ顺序旋转是一样的。证明方法可以看下[这篇文章](http://www.cnitblog.com/luckydmz/archive/2010/09/07/68674.html)。而Unity文档中说明的旋转顺序指的是在第一种情况下的顺序。
如果你还是不懂这意味着什么,可以试着调用下这个函数。例如,你认为下面代码的结果是什么:
```csharp
transform.Rotate(new Vector3(0, 30, 90));
```
原模型的方向和执行结果如下:
 
而我们可以再分别执行下面的代码:
```csharp
// First case
transform.Rotate(new Vector3(0, 30, 0));
transform.Rotate(new Vector3(0, 0, 90));
// Second case
// transform.Rotate(new Vector3(0, 0, 90));
// transform.Rotate(new Vector3(0, 30, 0));
```
两种情况的结果分别是:
 
可以发现,调用transform.Rotate(new Vector3(0, 30, 90));是和第一种情况中的代码是一样的结果,即先旋转Y、再旋转Z。进一步实验,我们会发现transform.Rotate(new Vector3(30, 90, -40));的结果是和transform.Rotate(new Vector3(0, 90, 0));transform.Rotate(new Vector3(30, 0, 0));transform.Rotate(new Vector3(0, 0, -40));的结果一样的。你会问了,文档中不是明明说了旋转顺序是Z、X、Y吗?怎么现在完全反过来了呢?原因就是我们之前说的两种坐标系的选择。在一次调用transform.Rotate的过程中,坐标轴是不随每次单个坐标轴的旋转而旋转的。而在调用transform.Rotate后,这个旋转坐标系才会变化。也就是说,transform.Rotate(new Vector3(30, 90, -40));执行时使用的是第一种情况,而transform.Rotate(new Vector3(0, 90, 0));transform.Rotate(new Vector3(30, 0, 0));transform.Rotate(new Vector3(0, 0, -40));每一句则是分别使用了上一句执行后的坐标系,即第二种坐标系情况。因此,我们看起来顺序好像是完全是反了,但结果是一样的。
上面只是说了一些容易混淆的地方,更多的内容大家可以搜搜wiki之类的。
## 数学模型
欧拉旋转的数学实现就是使用矩阵。而最常见的表示方法就是3*3的矩阵。在[Wiki](http://en.wikipedia.org/wiki/Gimbal_lock)里我们可以找到这种矩阵的表示形式,以下以按XYZ的旋转顺序为例,三个矩阵分别表示了:

在计算时,我们将原来的旋转矩阵右乘(这里使用的是列向量)上面的矩阵。从这里我们也可以证明上面所说的两种坐标系选择是一样的结果,它们之间的不同从这里来看其实就是矩阵相乘时的顺序不同。第一种坐标系情况,指的是在计算时,先从左到右直接计算R中3个矩阵的结果矩阵,最后再和原旋转矩阵相乘,因此顺序是XYZ;而第二种坐标系情况,指的是在计算时,从右往左依次相乘,因此顺序是反过来的,ZYX。你可以验证R左乘和右乘的结果表达式,就可以相信这个结论了!
## 万向节锁
虽然欧拉旋转非常容易理解,但它会造成臭名昭著的万向节锁问题。我之前给出了链接大家可能都看了,但还是不明白这是怎么回事。这里[有一篇文章](http://blog.csdn.net/huazai434/article/details/6458257)是我目前找到说得最容易懂的中文文章,大家可以看看。
如果你还是不明白,我们来做个试验。还是使用之前的模型,这次我们直接在面板中把它的欧拉角中的X值设为90°,其他先保持不变:

此时模型是脸朝下(下图你看到的只是一个头顶):

现在,如果我让你不动X轴,只设置Y和Z的值,把这个模型的脸转上来,让它向侧面看,你可以办到吗?你可以发现,这时候无论你怎么设置Y和Z的值,模型始终是脸朝下、在同一平面旋转,看起来就是Y和Z控制的是同一个轴的旋转,下面是我截取的任意两种情况:
 
这就是一种万向节锁的情况。这里我们先设置X轴为90°也是有原因的,这是因为Unity中欧拉角的旋转顺序是ZXY,即X轴是第二个旋转轴。当我们在面板中设置任意旋转值时,Unity实际是按照固定的ZXY顺序依次旋转特定角度的。
在代码里,我们同样可以重现万向节锁现象。
```csharp
transform.Rotate(new Vector3(0, 0, 40));
transform.Rotate(new Vector3(0, 90, 0));
transform.Rotate(new Vector3(80, 0, 0));
```
我们只需要固定中间一句代码,即使Y轴的旋转角度始终为90°,那么你会发现无论你怎么调整第一句和最后一句中的X或Z值,它会像一个钟表的表针一样总是在同一个平面上运动。
万向节锁中的“锁”,其实是给人一种误导,这可能也是让很多人觉得难以理解的一个原因。实际上,实际上它并没有锁住任何一个旋转轴,只是说我们会在这种旋转情况下会感觉丧失了一个维度。以上面的例子来说,尽管固定了第二个旋转轴的角度为90°,但我们原以为依靠改变其他两个轴的旋转角度是可以得到任意旋转位置的(因为按我们理解,两个轴应该控制的是两个空间维度),而事实是它被“锁”在了一个平面,即只有一个维度了,缺失了一个维度。而只要第二个旋转轴不是±90°,我们就可以依靠改变其他两个轴的旋转角度来得到任意旋转位置。
## 数学解释
我们从最简单的矩阵来理解。还是使用XYZ的旋转顺序。当Y轴的旋转角度为90°时,我们会得到下面的旋转矩阵:

我们对上述矩阵进行左乘可以得到下面的结果:

可以发现,此时当我们改变第一次和第三次的旋转角度时,是同样的效果,而不会改变第一行和第三列的任何数值,从而缺失了一个维度。
我们再尝试着理解下它的本质。[Wiki](http://en.wikipedia.org/wiki/Gimbal_lock)上写,万向节锁出现的本质原因,是因为从欧拉角到旋转的映射并不是一个覆盖映射,即它并不是在每个点处都是局部同胚的。不懂吧。。。恩,我们再来通俗一下解释,这意味着,从欧拉角到旋转是一个多对一的映射(即不同的欧拉角可以表示同一个旋转方向),而且并不是每一个旋转变化都可以用欧拉角来表示。其他更多的大家去参考wiki吧。
建议还是多看看视频,尤其是后面的部分。当然,如果还是觉得懵懵懂懂的话,在《3D数学基础:图形与游戏开发》一书中有一话说的很有道理,“如果您从来没有遇到过万向锁情况,你可能会对此感到困惑,而且不幸的是,很难在本书中讲清楚这个问题,你需要亲身经历才能明白。”因此,大家也不要纠结啦,等到遇到的时候可以想到是因为万向节锁的原因就好。<file_sep>public static string LongestPalindrome(string s)
{
if (s.Length == 1)
{
return s;
}
char[] charArr = s.ToCharArray();
bool[,] dpCache = new bool[charArr.Length, charArr.Length];
for (int i = 0; i < charArr.Length; ++i)
{
dpCache[i, i] = true;
}
int leftIndex = 0;
int maxLen = 1;
for (int i = 1; i < charArr.Length; ++i)
{
for (int j = 0; j <= i; j++)
{
if (charArr[i] != charArr[j])
{
dpCache[j, i] = false;
}
else
{
if (i - j < 3)
{
dpCache[j, i] = true;
}
else
{
dpCache[j, i] = dpCache[j + 1, i - 1];
}
}
if (dpCache[j, i] == true && i - j + 1 > maxLen)
{
maxLen = i - j + 1;
leftIndex = j;
}
}
}
return s.Substring(leftIndex, maxLen);
}<file_sep>//HashMap
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
public bool CanConvert(string str1, string str2)
{
Dictionary<char, char> map = new Dictionary<char, char>(26);
HashSet<char> usedInStr2 = new HashSet<char>();
if(string.Equals(str1, str2))
{
return true;
}
for (int i = 0; i < str2.Length; ++i)
{
char c2 = str2[i];
char c1 = str1[i];
if (!usedInStr2.Contains(c2))
{
usedInStr2.Add(c2);
}
if (map.ContainsKey(c1))
{
if (map[c1] != c2)
{
return false;
}
}
else
{
map[c1] = c2;
}
}
if (usedInStr2.Count >= 26)
{
return false;
}
else
{
return true;
}
}
}
}<file_sep>// 1018. 可被 5 整除的二进制前缀
//给定由若干 0 和 1 组成的数组 A。我们定义 N_i:从 A[0] 到 A[i] 的第 i 个子数组被解释为一个二进制数(从最高有效位到最低有效位)。
//返回布尔值列表 answer,只有当 N_i 可以被 5 整除时,答案 answer[i] 为 true,否则为 false。
//示例 1:
//输入:[0,1,1]
//输出:[true,false,false]
//解释:
//输入数字为 0, 01, 011;也就是十进制中的 0, 1, 3 。只有第一个数可以被 5 整除,因此 answer[0] 为真。
//示例 2:
//输入:[1,1,1]
//输出:[false,false,false]
//示例 3:
//输入:[0,1,1,1,1,1]
//输出:[true,false,false,false,true,false]
//示例 4:
//输入:[1,1,1,0,1]
//输出:[false,false,false,false,false]
//提示:
//1 <= A.length <= 30000
//A[i] 为 0 或 1
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/binary-prefix-divisible-by-5
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
public IList<bool> PrefixesDivBy5(int[] A)
{
List<bool> list = new List<bool>();
int prefix = 0;
int length = A.Length;
for (int i = 0; i < length; i++)
{
prefix = ((prefix << 1) + A[i]) % 5;
list.Add(prefix == 0);
}
return list;
}
}
}<file_sep>using System;
//746.使用最小花费爬楼梯
//数组的每个索引作为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。
//每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
//您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
//示例 1:
//输入: cost = [10, 15, 20]
//输出: 15
//解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。
// 示例 2:
//输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
//输出: 6
//解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。
//注意:
//cost 的长度将会在[2, 1000]。
//每一个 cost[i] 将会是一个Integer类型,范围为[0, 999]。
//思路 -> dp
namespace ByteDancePopular
{
public partial class Solution
{
public int MinCostClimbingStairs(int[] cost)
{
int dp0 = cost[0];
int dp1 = cost[1];
int dp2 = 0;
for (int i = 2; i < cost.Length; ++i)
{
dp2 = Math.Min(dp0 + cost[i], dp1 + cost[i]);
dp0 = dp1;
dp1 = dp2;
}
int ret = Math.Min(dp0, dp1);
return ret;
}
}
}
<file_sep>//424.替换后的最长重复字符
//给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 k 次。在执行上述操作后,找到包含重复字母的最长子串的长度。
//注意:
//字符串长度 和 k 不会超过 10^4。
//示例 1:
//输入:
//s = "ABAB", k = 2
//输出:
//4
//解释:
//用两个'A'替换为两个 'B',反之亦然。
//示例 2:
//输入:
//s = "AABABBA", k = 1
//输出:
//4
//解释:
//将中间的一个'A'替换为 'B',字符串变为 "AABBBBA"。
//子串 "BBBB" 有最长重复字母, 答案为 4。
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/longest-repeating-character-replacement
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//思路
// 1. 当k >= s长度时, 替换即可满足 s.Length
// 2. 当k < s.Length时, 只需要维护一个长度动态变更的滑动窗口
// 3. 当窗口扩张时,必定是因为 k有余裕 或者 扩张进入的是一个目前最大出现次数的值
// 4. 当窗口收缩时,必定是因为 扩张的值并非最大出现次数的值,且k不余裕,所以收缩会伴随着滑动
using System;
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
public int CharacterReplacement(string s, int k)
{
if (s.Length == 0)
{
return 0 ;
}
if (k >= s.Length)
{
return s.Length;
}
int[] count = new int[26];
int left = 0, right = 0, max = 0, ret = 0;
while(right < s.Length)
{
int idx = s[right] - 'A';
count[idx]++;
max = Math.Max(max, count[idx]);
if (right - left +1 -max >k)
{
count[s[left] - 'A']--;
left++;
}
ret = Math.Max(ret, right - left + 1);
right++;
}
return ret;
}
//双指针滑动
public IList<IList<int>> LargeGroupPositions(string s)
{
IList<IList<int>> ret = new List<IList<int>>();
if (string.IsNullOrEmpty(s))
{
return ret;
}
int left = 0, right = 0;
Stack<int> validZone = new Stack<int>();
int leftMarker = 0;
while (right < s.Length)
{
char cl = s[left];
char cr = s[right];
if (cl == cr)
{
leftMarker = left;
validZone.Push(right);
right++;
}
else
{
if (validZone.Count >= 3)
{
List<int> zone = new List<int>();
zone.Add(leftMarker);
zone.Add(validZone.Pop());
ret.Add(zone);
}
validZone.Clear();
left = right;
leftMarker = left;
validZone.Push(right);
right++;
}
}
if (validZone.Count >= 3)
{
List<int> zone = new List<int>();
zone.Add(leftMarker);
zone.Add(validZone.Pop());
ret.Add(zone);
}
return ret;
}
}
}<file_sep>//3. 无重复字符的最长子串
//给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
//示例 1:
//输入: s = "abcabcbb"
//输出: 3
//解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
//示例 2:
//输入: s = "bbbbb"
//输出: 1
//解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
//示例 3:
//输入: s = "pwwkew"
//输出: 3
//解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
// 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
//示例 4:
//输入: s = ""
//输出: 0
//提示:
//0 <= s.length <= 5 * 104
//s 由英文字母、数字、符号和空格组成
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
using System;
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
public int LengthOfLongestSubstring(string s)
{
HashSet<char> ts = new HashSet<char>();
int left = 0, right = 0;
int len = 0;
int maxLen = 0;
while (right < s.Length)
{
char c = s[right];
if (ts.Contains(c))
{
ts.Remove(s[left]);
left++;
len--;
}
else
{
ts.Add(c);
right++;
len++;
maxLen = Math.Max(maxLen, len);
}
}
return maxLen;
}
}
}<file_sep>---
layout: post
title: "Unity3d Shader 入门精要笔记(1)"
subtitle: " \"Unity Shader 入门笔记\""
date: 2018-03-12 10:00:00
author: "Mas9uerade"
header-img: "img/unityshader.jpg"
tags:
- Unity3d
- Shader
---
> “在读[CandyCat](Http://CandyCat1992.github.io)的Unity Shader入门精要之后,发现忘得比看得快,所以索性重看一遍并记了一段笔记”
### 渲染流程分为三个阶段
1. 应用阶段(Application Stage); CPU实现
1. 把数据加载到显存中;
硬盘(HDD) -> RAM -> VRAM
2. 设置渲染状态;
使用哪种类型的着色器,光源属性,材质等;
3. 调用Draw Call;
2. 几何阶段(Geometry Stage); GPU实现
3. 光栅化阶段(Rasterizer Stage); GPU实现
### GPU渲染流水线
#### 1 . 几何阶段
#### **顶点数据 (显存)-> 顶点着色器 -> 曲面细分着色器 -> 几何着色器 -> 裁剪 -> 屏幕映射**
###### 顶点着色器(Vertex Shader)
完全可编程, 实现顶点的空间变化,顶点着色的功能;
1. 实现坐标变换,把顶点坐标从模型空间转换到齐次裁剪空间,之后使用透视除法,获得归一化的设备坐标(Normalized Device Coordinates);
2. 逐顶点光照,
##### 曲面细分着色器(Tessellation Shader)
可选着色器,用于细分图元;
##### 几何着色器(Geometry Shader)
可选着色器,可以被用于执行逐图元的着色操作,或者被用于产生更多的图元;
##### 裁剪(Clipping)
可配置,剔除不在摄像机视野内的顶点,剔除某些三角图元的面片;
##### 屏幕映射(Screen Mapping)
把每个图元的x,y坐标转换到屏幕坐标系;
注意: OpenGL与DirectX的屏幕坐标系不同;
#### 2. 光栅化阶段
#### **屏幕映射 -> 三角形设置 -> 三角形遍历 -> 片元着色器 -> 逐片元操作 -> 屏幕图像**
##### 三角形设置(Triangle Setup)
计算光栅化一个三角形网络所需的信息,通过顶点计算三角形边界的表达方式;
##### 三角形遍历(Triangle Travelsal)
检查每个像素是否被一个三角网络覆盖,若被覆盖则生成一个片元(Fragment),最终输出片元序列(包含了最终颜色,屏幕坐标信息,深度信息,法线,纹理坐标等);
##### 片元着色器(Fragment Shader)
可编程着色器,在DirectX中也称像素着色器(Pixel Shader),实质上是通过对顶点插值,通过颜色、纹理的计算,输出最终的颜色信息。
##### 逐片元操作(Per-Fragment Operations)
**片元 -> 模板测试 ->深度测试 -> 混合 -> 颜色缓冲区(帧缓冲区)**
OpenGL的说法,在DirectX中为输出合并阶段(Output-Merger)
1. 决定每个片元的可见性,涉及到了深度测试,模板测试等;
2. 若一个片元通过测试,就需要将该片元的颜色与存储在颜色缓冲区中的颜色进行混合。
##### 颜色缓冲区(帧缓冲区)
就是帧缓冲区(图形设备的内存),需要渲染的场景的每一个像素都最终写入该缓冲区,然后由他渲染到屏幕上显示。
##### 模板测试(Stencil Test)
~~GPU会首先模板缓冲区(Stencil Buffer)中该片元位置的模板值,将该值与读取到的参考值进行比较,进而修改模板缓冲区,....~~ 模板测试中可进行渲染阴影,轮廓渲染等。
##### 深度测试
主要影响透明效果
#### DrawCall相关
1. draw call 对帧率的影响在于cpu提交命令的速度;
2. 减少draw call需要避免使用大量很小的网格,避免使用过多的材质。
### 着色器介绍
```c
Shader
{
subShader
{
pass
{
}
}
}
```
#### 1. 表面着色器(Surface Shader)
Unity特有的对于顶点/片元着色器Vertex/Fragment Shader的抽象封装,自动完成了光照细节的处理,但相应的渲染代价更大,性能更低。
写在SubShader内,不需要考虑pass的渲染问题。
#### 2.顶点/片元着色器(Vertex/Fragment Shader)
写在Pass内,可以通过选择pass控制渲染的实现细节;
<file_sep>//设计和构建一个“最近最少使用”缓存,该缓存会删除最近最少使用的项目。缓存应该从键映射到值(允许你插入和检索特定键对应的值),并在初始化时指定最大容量。当缓存被填满时,它应该删除最近最少使用的项目。
//它应该支持以下操作: 获取数据 get 和 写入数据 put 。
//获取数据 get(key) -如果密钥(key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 - 1。
//写入数据 put(key, value) -如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/lru-cache-lcci
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
using System.Collections.Generic;
public class LRUCache
{
public class DLinkedNode
{
public int key;
public int val;
public DLinkedNode next;
public DLinkedNode prev;
public DLinkedNode() { }
public DLinkedNode (int _key, int _val)
{
key = _key;
val = _val;
}
}
Dictionary<int, DLinkedNode> pair;
DLinkedNode Head = null;
DLinkedNode Tail = null;
public int Capacity;
public LRUCache(int capacity)
{
pair = new Dictionary<int, DLinkedNode>(capacity);
Capacity = capacity;
// 使用伪头部和伪尾部节点
Head = new DLinkedNode();
Tail = new DLinkedNode();
Head.next = Tail;
Tail.prev = Head;
}
public int Get(int key)
{
if (pair.ContainsKey(key))
{
MoveToHead(pair[key]);
return pair[key].val;
}
else
{
return -1;
}
}
public void Put(int key, int value)
{
if (pair.ContainsKey(key))
{
pair[key].val = value;
MoveToHead(pair[key]);
}
else
{
DLinkedNode entry = new DLinkedNode(key, value);
AddToHead(entry);
pair[key] = entry;
if (Capacity < pair.Count)
{
DLinkedNode tail = RemoveTail();
pair.Remove(tail.key);
}
}
}
private void AddToHead(DLinkedNode node)
{
node.prev = Head;
node.next = Head.next;
Head.next.prev = node;
Head.next = node;
}
private void RemoveNode(DLinkedNode node)
{
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void MoveToHead(DLinkedNode node)
{
RemoveNode(node);
AddToHead(node);
}
private DLinkedNode RemoveTail()
{
DLinkedNode res = Tail.prev;
RemoveNode(res);
return res;
}
}<file_sep>#### [440. 字典序的第K小数字](https://leetcode-cn.com/problems/k-th-smallest-in-lexicographical-order/)
难度-困难
给定整数 `n` 和 `k`,找到 `1` 到 `n` 中字典序第 `k` 小的数字。
注意:1 ≤ k ≤ n ≤ 10^9。
**示例 :**
```
输入:
n: 13 k: 2
输出:
10
解释:
字典序的排列是 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],所以第二小的数字是 10。
```
题解思路:
1. 字典序 -> 十叉树遍历(需要去除头节点的0,从1~9作为根节点分别遍历)
2. 确定某个节点下的子节点个数
```c#
/* 计算[n,n+1]之间存在多少个数字 */
/* 计算每扩大10倍有多少数字,相加即可 */
long GetNodeNums(int n, int max)
{
long ans = 1;
long left = (long)n * 10 + 0; // 扩大十倍的左边界
long right = (long)n * 10 + 9; // 扩大十倍的右边界
while (max >= left)
{
if (max <= right)
{
ans += (max - left + 1); // max 在 [l,r]之间
}
else
{
ans += (right - left + 1); // max 在 下一层
}
left = left * 10 + 0; // 下一层
right = right * 10 + 9;
}
return ans;
}
```
二、
初始化 l = 1, r = 9, k = k(还差数字个数)
令f(x)表示[x,x+1]之间数字个数
步骤1:遍历 i -> [l,r]
步骤2:
如果 k > i, k-=f(i).即第k个数不在[i,i+1]中,还需要找k-=f(i)个数。
如果 k <= i, k--,l=i10 ,r=i10+9,返回步骤1. 即第k个数在[i,i+1]中,还需找k-1个数,接下来查找区间为[i10,i10+9]。
```c#
int findKthNumber(int n, int k)
{
int l = 1;
int r = 9;
while(k)
{
for(int i = l; i <= r; ++i)
{
int f = GetNodeNums(i, n);
if(k > f)
{
k -= f;
}
else
{
k--;
if(k == 0) return i;
l = i * 10 + 0;
r = i * 10 + 9;
break;
}
}
}
return 0;
}
```
<file_sep>---
layout: post
title: "Unix环境高级编程笔记2"
subtitle: " \"Linux\""
date: 2018-08-24 15:48:00
author: "Mas9uerade"
header-img: "img/watchdog2_sf.jpg"
tags:
- Linux
---
> “Unix环境高级编程第二版读书笔记 - 2”
# Unix基础知识 #
## 进程控制 ##
### 1.进程标志符 进程ID
在linux中进程的id是区分进程的别一标准。
调度进程ID为0
init进程ID为1
......
孤儿进程
```C
#include <unistd.h>
pid_t getpid(void); //获取当前进程ID
pid_t getppid(void); //获取父进程ID
uid_t getuid(void); //该进程的用户ID
.....
```
### 2. fork函数创造子进程
fork函数用于创建一个新进程
```C
#include <unistd.h>
pid_t fork(void);
```
1. fork函数被调用一次会有两个返回值,它在父进程中返回新的子进程的ID,而在子进程中返回值为0。
在linux中之所以需要这么做的原因是linux中没有像Windows那样可以通过共同的进程名访问到所有子进程,因此每次创建子进程都需要在父进程返回子进程id,用于控制子进程。
2. fork之后,子进程作为父进程的福本,获得父进程数据空间、堆、栈的福本,不是完全的一个new出来的进程,可以继续fork时父进程的状态进行工作,但是这个地方做的不是完全的深拷贝,而是在写时复制(Copy-On-Write,COW),提升了一部分效率;
3. fork后的子进程与父进程共享同一文件偏移量;
vfork已被废弃,先不讨论;
### 3. exit函数
进程结束的方法有5种
1. 在main中执行return,等效于调用exit;
2. 调用exit;
3. 调用_exit或_Exit函数;
4. 进程的最后一个线程在其启动例程中执行返回语句。但是,该线程的返回值不会用作进程返回值。当最后一个线程从启动例程返回时,该进程以终止状态0返回;
5. 进程的最后一个线程调用pthread_exit函数;
3种异常终止方式:
1. 调用abort;
2. 当进程接收到某些信号,信号可由进程自身,其他进程或内核产生。例如,进程越出其地址空间访问存储单元或者除以0,内核就会为该进程产生对应信号();
3. 最后一个线程对“cancellation”请求做出响应, 按系统默认,“Cancellation”以延迟方式发生。
不论进程如何终止,都会执行内核为进程关闭所有打开描述符,释放内存等操作的代码。(避免IO冲突/内存泄漏)
### 4. 孤儿进程与僵死进程-[参考链接](https://www.cnblogs.com/Anker/p/3271773.html)
孤儿进程:一个父进程退出,而它的一个或多个子进程还在运行,那么那些子进程将成为孤儿进程。孤儿进程将被init进程(进程号为1)所收养,并由init进程对它们完成状态收集工作。
僵死进程:一个进程使用fork创建子进程,如果子进程退出,而父进程并没有调用wait或waitpid获取子进程的状态信息,那么子进程的进程描述符仍然保存在系统中。这种进程称之为僵死进程。
#### 4.1 问题及危害
Unix提供了一种机制可以保证只要父进程想知道子进程结束时的状态信息, 就可以得到。这种机制就是: 在每个进程退出的时候,内核释放该进程所有的资源,包括打开的文件,占用的内存等。 但是仍然为其保留一定的信息(包括进程号the process ID,退出状态the termination status of the process,运行时间the amount of CPU time taken by the process等)。直到父进程通过wait / waitpid来取时才释放。 但这样就导致了问题,如果进程不调用wait / waitpid的话, 那么保留的那段信息就不会释放,其进程号就会一直被占用,但是系统所能使用的进程号是有限的,如果大量的产生僵死进程,将因为没有可用的进程号而导致系统不能产生新的进程. 此即为僵尸进程的危害,应当避免。
孤儿进程是没有父进程的进程,孤儿进程这个重任就落到了init进程身上,init进程就好像是一个民政局,专门负责处理孤儿进程的善后工作。每当出现一个孤儿进程的时候,内核就把孤 儿进程的父进程设置为init,而init进程会循环地wait()它的已经退出的子进程。这样,当一个孤儿进程凄凉地结束了其生命周期的时候,init进程就会代表党和政府出面处理它的一切善后工作。因此孤儿进程并不会有什么危害。
任何一个子进程(init除外)在exit()之后,并非马上就消失掉,而是留下一个称为僵尸进程(Zombie)的数据结构,等待父进程处理。这是每个 子进程在结束时都要经过的阶段。如果子进程在exit()之后,父进程没有来得及处理,这时用ps命令就能看到子进程的状态是“Z”。如果父进程能及时 处理,可能用ps命令就来不及看到子进程的僵尸状态,但这并不等于子进程不经过僵尸状态。 如果父进程在子进程结束之前退出,则子进程将由init接管。init将会以父进程的身份对僵尸状态的子进程进行处理。
#### 4.2 僵尸进程危害场景:
例如有个进程,它定期的产 生一个子进程,这个子进程需要做的事情很少,做完它该做的事情之后就退出了,因此这个子进程的生命周期很短,但是,父进程只管生成新的子进程,至于子进程 退出之后的事情,则一概不闻不问,这样,系统运行上一段时间之后,系统中就会存在很多的僵死进程,倘若用ps命令查看的话,就会看到很多状态为Z的进程。 严格地来说,僵死进程并不是问题的根源,罪魁祸首是产生出大量僵死进程的那个父进程。因此,当我们寻求如何消灭系统中大量的僵死进程时,答案就是把产生大 量僵死进程的那个元凶枪毙掉(也就是通过kill发送SIGTERM或者SIGKILL信号啦)。枪毙了元凶进程之后,它产生的僵死进程就变成了孤儿进 程,这些孤儿进程会被init进程接管,init进程会wait()这些孤儿进程,释放它们占用的系统进程表中的资源,这样,这些已经僵死的孤儿进程 就能瞑目而去了。
#### 4.3 僵尸进程的解决方法
1. 通过信号机制
子进程退出时向父进程发送SIGCHILD信号,父进程处理SIGCHILD信号。在信号处理函数中调用wait进行处理僵尸进程。
2. fork两次
《Unix 环境高级编程》8.6节说的非常详细。原理是将子进程成为孤儿进程,从而其的父进程变为init进程,通过init进程可以处理僵尸进程。
### 5. wait 与 waitpid函数
```C
pid_t wait(int *statloc);
pid_t waitpid(pid_t pid, int *statloc, int options);
其中startloc是作为进程状态的输出指针,若不关心返回的进程状态,可设为空
具体返回的类型需要查定义宏
```
当一个进程终止时,内核就像其父进程发送SIGCHLD信号(signal children)。因为子进程的终止是异步事件,所以这种信号实际上是内核向父进程发起的异步通知。此时,父进程可以选择调用wait或者waitpid来获取其终止状态,在父进程调用wait或者waitpid的时候,有三种可能情况
1. 如果其所有子线程都在运行中,则阻塞直至有一子线程终止;
2. 如果已经有一个子线程已终止,正等待父线程来获取其终止状态,则成功获取终止状态并立即返回;
3. 如果没有任何子线程,则立即出错返回;
其中waitpid提供了wait函数没有提供的三个功能:
1. 顾名思义,waitpid可等待某一制定进程,而wait则返回任一终止子进程的状态;
2. waitpid提供了一个wait的非阻塞版本;
3. waitpid支持作业控制;
4. waitpid相对于wait多了一个pid与option的输入,用于指定进程与模式,同样模式需要查看定义宏
#### 5.1 之后还有waitid, wait2, wait3......
### 6. 竞争状态Race Condition
当多个进程都企图对共享数据进行某种处理时,而最后的结果又取决于进程运行的顺序,这就可以被理解为发生了竞争状态。
当多个进程都企图对共享数据进行某种处理,而最后的结果又取决于进程进行的顺序时,则我们认为这发生了竞争条件。一个例子是在fork出子进程之后,父、子进程的执行顺序是不确定的,这种不确定决定了后面程序的结果,那么这便产生了一个竞争条件。
如果一个进程希望等待一个子进程终止,则它必须调用wait或waitpid函数。如果一个进程要等待其父进程终止,则可使用如下的轮询方式:
```C
while (getppid() != 1)
sleep(1);
```
这样的轮询(polling)需要休眠、唤醒等工作,很显然浪费了CPU资源。
为了避免竞争条件与轮询,UNIX中使用了信号机制与STREAM(管道)。
### 7. exec函数
当我们创建了一个进程之后,通常将子进程替换成新的进程映象,这可以用exec系列的函数来进行。当然,exec系列的函数也可以将当前进程替换掉。
exec只是用磁盘上的一个新程序替换了当前进程的正文段, 数据段, 堆段和栈段.
其中由于进程id没有改变,与进程id相关的其他一切都没改变(进程父子关系,用户组,文件锁,进程信号屏蔽等)
<file_sep>---
layout: post
title: "Unity Shader 概念重析"
subtitle: " \"面试小记\""
date: 2020-11-29 15:48:49
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- Unity
- Unity Shader
---
> “面试知识点整理,转自 [[Unity 官方推送](https://mp.weixin.qq.com/s/gVsOjetvZKdQrtZ0wFOAdQ)]
# Unity Shader 总结
## 1. Unity Shader 概念重析
### **1 .1 三大 Shader 编程语言(CG/HLSL/GLSL)**
Shader Language的发展方向是设计出在便携性方面可以和C++、Java等相比的高级语言,“赋予程序员灵活而方便的编程方式”,并“尽可能的控制渲染过程”同时“利用图形硬件的并行性,提高算法效率”。
Shader Language目前主要有3种语言:基于 OpenGL 的 OpenGL Shading Language,简称 GLSL; 基于 DirectX 的 High Level Shading Language, 简称 HLSL; 基于 NVIDIA 公司的 C for Graphic,简称 Cg 语言。
### 1.2 渲染管线
渲染管线也称为渲染流水线,是显示芯片内部处理图形信号相互独立的并行处理单元。

### 1.3 Shader的基础定义
Gpu流水线上一些可高度编程的阶段,而由着色器编译出来的最终代码是会在Gpu上运行的;有一些特定类型的着色器,如顶点着色器,片元着色器等。依靠着色器我们可以控制流水线中的渲染细节,例如用顶点着色器来进行顶点变换及传递数据,用片元着色器来进行逐像素渲染。
### 1.4 Unity Shader并非真正的Shader
Unity Shader实际上指的就是一个ShaderLab文件。以.shader作为后缀的一种文件。在Unity shader里面,我们可以做的事情远多于一个传统意义上的Shader。在传统的shader中,我们仅可以编写特定类型的Shader,例如顶点着色器,片元着色器等。在Unity Shader中,我们可以在同一个文件里面同时包含需要的顶点着色器和片元着色器代码。在传统shader中,我们无法设置一些渲染设置,例如是否开启混合,深度测试等,这些是开发者在另外的代码中自行设置的。而Unity shader中,我们通过一行特定的指令就可以完成这些设置。在传统shader中,我们需要编写冗长的代码设置着色器的输入和输出,要小心的处理这些输入输出的位置对应关系等。而在Unity shader中,我们只需要在特定语句块中声明一些属性,就可以依靠材质来方便的改变这些属性。而对于模型自带的数据(如顶点,纹理坐标,法线等),Unity Shader也提供了直接访问的方法,不需要开发者自行编码来传给着色器。
## 2. **Unity Shader 关键知识点提炼**
### 2.1 Cg编程
通常采用动态编译的方式(Cg也支持静态编译方式),即在宿主程序运行时,利用Cg运行库(Cg Runtimer Library)动态编译Cg代码。
Cg数据类型:

### 2.2 **Unity Shader ShaderLab编程**
**01 基础功能类型函数**

**几何函数:**

**纹理函数:**

***02*** **渲染顺序(Render Queue)**

***03*** **透明效果**:只要一个片元的透明度不满足条件(通常小于某个阈值),那么就舍弃对应的片元。被舍弃的片元不会在进行任何的处理,也不会对颜色缓冲产生任何影响;否则,就会按照普通的不透明物体来处理,即进行深度测试,深度写入等等。虽然简单,但是很极端,要么完全透明,要么完全不透明。
**透明度混合**:可以得到真正的半透明效果,它会使当前片元的透明度作为混合因子,与已经储存在颜色缓冲中的颜色值进行混合么,得到新的颜色。但是,透明度混合需要关闭深度写入,这使得我们要非常小心物体的渲染顺序。注意:透明度混合只关闭了深度写入,但没有关闭深度测试。这表示当使用透明度混合渲染一个片元时,还是会比较它的深度值与当前深度缓冲中的深度值,如果深度值距离摄像机更远,那么就不会在进行混合操作。比如一个不透明物体在透明物体前面,我们先渲染不透明物体,可以正常的挡住不透明物体。
**混合操作:**

**混合因子:**


**常见混合操作类型应用:**
**A** //正常(Normal)透明度混合 Blend SrcAlpha OneMinusSrcAlpha
**B** //柔和相加 Blend OneMinusDstColor One
**C** //正片叠底 Blend DstColor Zero
**D** //两倍相乘 Blend DstColor SrcColor
**E** //变暗 BlendOp min Blend One One
**F** //变亮 Blend OneMinusDstColor One Blend One OneMinusSrcColor
**G** //线性减淡 Blend One One
## 3. 光照模型

## 4. 表面着色器
用。使用表面着色器,用户仅需要编写最关键的表面函数,其余周边代码将由Unity自动生成,包括适配各种光源类型、渲染实时阴影以及集成到前向/延迟渲染管线中等。
**01 编写表面着色器有几个规则**
表面着色器的实现代码需要放在CGPROGRAM..ENDCG代码块中,而不是Pass结构中,它会自己编译到各个Pass。
使用#pragma surface..命令来指明它是一个表面着色器。
**A ** #pragma surface surfaceFunction lightModel [optionalparams]:Surface Shader和CG其他部分一样,代码也是要写在CGPROGRAM和ENDCG之间。但区别是,它必须写在SubShader内部,而不能写在Pass内部。Surface Shader自己会自动生成所需的各个Pass。由上面的编译格式可以看出,surfaceFunction和lightModel是必须指定的。
**B** surfaceFunction通常就是名为surf的函数(函数名可以任意),它的函数格式是固定的:
void surf (Input IN, inout SurfaceOutput o)
void surf (Input IN, inout SurfaceOutputStandard o)
void surf (Input IN, inout SurfaceOutputStandardSpecular o)
**C** lightModel也是必须指定的。由于Unity内置了一些光照函数——Lambert(diffuse)和Blinn-Phong(specular),因此这里在默认情况下会使用内置的Lambert模型。当然我们也可以自定义。
**D** optionalparams包含了很多可用的指令类型,包括开启、关闭一些状态,设置生成的Pass类型,指定可选函数等。除了上述的surfaceFuntion和lightModel,我们还可以自定义两种函数:vertex:VertexFunction和finalcolor:ColorFunction。也就是说,Surface Shader允许我们自定义四种函数。
**02 计算函数汇总**
**//最重要的计算函数**
void surf (Input IN, inout SurfaceOutput o)
void surf (Input IN, inout SurfaceOutputStandard o)
void surf (Input IN, inout SurfaceOutputStandardSpecular o)
**//顶点修改**
void vert (inout appdata_full v)
void vert(inout appdata_full v, out Input o)
//unity老版本(新版本兼容)不包含GI的
half4 Lighting (SurfaceOutput s, half3 lightDir, half atten)
half4 Lighting (SurfaceOutput s, half3 lightDir, half3 viewDir, half atten)
**//unity新版本(包含GI,要自定义GI函数)**
half4 Lighting (SurfaceOutput s, UnityGI gi)
half4 Lighting (SurfaceOutput s, half3 viewDir, UnityGI gi)
**//延迟渲染**
half4 Lighting_Deferred (SurfaceOutput s, UnityGI gi, out half4 outDiffuseOcclusion, out half4 outSpecSmoothness, out half4 outNormal)
//遗留的延迟渲染
half4 Lighting_PrePass (SurfaceOutput s, half4 light)
**//自定义GI**
half4 Lighting_GI (SurfaceOutput s, UnityGIInput data, inout UnityGI gi);
**//着色**
void frag(Input IN, SurfaceOutput o, inout fixed4 color)
**//最终颜色修改**
void final(Input IN, SurfaceOutput o, inout fixed4 color)
void final(Input IN, SurfaceOutputStandard o, inout fixed4 color)
void final(Input IN, SurfaceOutputStandardSpecular o, inout fixed4 color)
两个结构体就是指struct Input和SurfaceOutput。其中Input结构体是允许我们自定义的。如下表。这些变量只有在真正使用的时候才会被计算生成。在一个贴图变量之前加上uv两个字母,就代表提取它的uv值,例如uv_MainTex 。
另一个结构体是(SurfaceOutput、SurfaceOutputStandard和SurfaceOutputStandardSpecular)。我们也可以自定义这个结构体内的变量,自定义最少需要有4个成员变量:Albedo、Normal、Emission和Alpha,缺少一个都会报错。关于它最难理解的也就是每个变量的具体含义以及工作机制(对像素颜色的影响)。
```CG
struct SurfaceOutput
{
fixed3 Albedo;
fixed3 Normal;
fixed3 Emission;
half Specular;
fixed Gloss;
fixed Alpha;
};
```
**Albedo**:我们通常理解的对光源的反射率。它是通过在Fragment Shader中计算颜色叠加时,和一些变量(如vertex lights)相乘后,叠加到最后的颜色上的。(漫反射颜色)
**Normal**:即其对应的法线方向。只要是受法线影响的计算都会受到影响。
**Emission**:自发光。会在Fragment 最后输出前(调用final函数前,如果定义了的话),使用下面的语句进行简单的颜色叠加:c.rgb += o.Emission;
**Specular**:高光反射中的指数部分的系数。影响一些高光反射的计算。按目前的理解,也就是在光照模型里会使用到(如果你没有在光照函数等函数——包括Unity内置的光照函数,中使用它,这个变量就算设置了也没用)。有时候,你只在surf函数里设置了它,但也会影响最后的结果。这是因为,你可能使用了Unity内置的光照模型,如BlinnPhong,它会使用如下语句计算高光反射的强度(在Lighting.cginc里):float spec = pow (nh, s.Specular*128.0) * s.Gloss;
**Gloss**:高光反射中的强度系数。和上面的Specular类似,一般在光照模型里使用。
**Alpha**:通常理解的透明通道。在Fragment Shader中会直接使用下列方式赋值(如果开启了透明通道的话):c.a = o.Alpha;
**Unity Shader实战应用**
因为涉及的代码量比较大,小编这边直接在GitHub上分享通用效果测试的工程。

部分测试效果展示(雪融&火焰流动效果):<file_sep>// 42. 接雨水 问题 - 单调栈
using System;
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
public int Trap(int[] height)
{
//单调递减的栈
Stack<int> trapArea = new Stack<int>();
int ret = 0, current = 0;
Stack<int> stack = new Stack<int>();
while (current < height.Length)
{
while (stack.Count>0 && height[current] > height[stack.Peek()])
{
int top = stack.Pop();
if (stack.Count ==0)
{
break;
}
int distance = current - stack.Peek() - 1;
int bounded_height = Math.Min(height[current], height[stack.Peek()]) - height[top];
ret += distance * bounded_height;
}
stack.Push(current++);
}
return ret;
}
}
}
<file_sep>//199.二叉树的右视图
//给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
//示例:
//输入:[1,2,3,null,5,null,4]
//输出:[1, 3, 4]
//解释:
//1 < ---
/// \
//2 3 < ---
// \ \
// 5 4 < ---
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/binary-tree-right-side-viewz
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
using System;
using System.Collections.Generic;
//思路
// 1. 右序优先的深度遍历,记录信息,深度,最大深度,值
// 2. 左序优先的层级遍历,记录信息,深度,最大深度
namespace ByteDancePopular
{
public partial class Solution
{
public IList<int> RightSideView(TreeNode root)
{
if (root == null)
{
return new List<int>(0);
}
TreeNode node = root;
Stack<TreeNode> nodeStack = new Stack<TreeNode>();
Stack<int> depthStack = new Stack<int>();
Dictionary<int, int> rightView = new Dictionary<int, int>();
nodeStack.Push(root);
depthStack.Push(0);
int maxDepth = -1;
int depth = -1;
while (nodeStack.Count > 0)
{
node = nodeStack.Pop();
depth = depthStack.Pop();
if (node!= null)
{
maxDepth = Math.Max(depth, maxDepth);
if (!rightView.ContainsKey(depth))
{
rightView.Add(depth, node.val);
}
}
//栈先进后出
if (node.left != null)
{
nodeStack.Push(node.left);
depthStack.Push(depth + 1);
}
if (node.right != null)
{
nodeStack.Push(node.right);
depthStack.Push(depth + 1);
}
}
List<int> ret = new List<int>(maxDepth +1);
for (int i = 0; i <= maxDepth; ++i)
{
ret.Add(rightView[i]);
}
return ret;
}
public IList<int> RightSideView2(TreeNode root)
{
if (root == null)
{
return new List<int>(0);
}
Dictionary<int, int> rightView = new Dictionary<int, int>();
Queue<TreeNode> nodeQueue = new Queue<TreeNode>();
Queue<int> depthQueue = new Queue<int>();
TreeNode node;
int depth = 0;
int maxDepth = 0;
nodeQueue.Enqueue(root);
depthQueue.Enqueue(0);
while (nodeQueue.Count > 0)
{
node =nodeQueue.Dequeue();
depth = depthQueue.Dequeue();
maxDepth = Math.Max(maxDepth, depth);
if (!rightView.ContainsKey(depth))
{
rightView.Add(depth, node.val);
}
if (node.right != null)
{
nodeQueue.Enqueue(node.right);
depthQueue.Enqueue(depth + 1);
}
if (node.right != null)
{
nodeQueue.Enqueue(node.left);
depthQueue.Enqueue(depth + 1);
}
}
List<int> ret = new List<int>(maxDepth + 1);
for (int i = 0; i <= maxDepth; ++i)
{
ret.Add(rightView[i]);
}
return ret;
}
}
}
<file_sep>---
layout: post
title: "Unity3d Shader 入门2"
subtitle: " \"Unity Shader\""
date: 2018-05-02 15:48:00
author: "Mas9uerade"
header-img: "img/watchdog2_sf.jpg"
tags:
- Unity3d
- Shader
---
> “一些基本的[Unity特效](https://github.com/Mas9uerade/UnityShaderEffect)的制作方式”
最近在工程中需要用到一些简单的特效,所以用之前学习的UnityShader制作了相关的特效。
## 特效效果 ##
##### 原图 #####

##### RGB转为灰度图

##### 毛玻璃效果

## 基本思路
1. 首先确定层级,把UI分为两部分,第一部分是会被施加特效的部分,第二部分为不会被施加特效的部分,第二部分是盖在第一部分的UI,然后在两个层级之间插入一张尺寸相同的Image用于覆盖底图,作为施加特效的图片;
1. 之后需要实现的就是获取在特效前的纹理,进行对应的特效处理,最后输出为shader,附加到材质球上;
1. 在特效图片上附上制作的材质球,通过Enable/Disable该图片实现特效的输出与关闭。
### 纹理获取
参照UnityManual中的[GrabPass的Example](https://docs.unity3d.com/Manual/SL-GrabPass.html), 使用GrabPass获取底层纹理:
1. 设置渲染队列为Trasparent,透明图层渲染;
2. 获取采样的纹理;
```C
GrabPass
{
"_BackgroundTexture"
}
sampler2D _BackgroundTexture;
```
3. 重载片元着色片段fragment frag,一般在这个阶段进行特效处理,因此之后我们处理灰度与模糊的特效只需要修改这个函数;
附上[Unity的Example源码]((https://docs.unity3d.com/Manual/SL-GrabPass.html)):
```C
Shader "GrabPassInvert"
{
SubShader
{
// Draw ourselves after all opaque geometry
Tags { "Queue" = "Transparent" }
// Grab the screen behind the object into _BackgroundTexture
GrabPass
{
"_BackgroundTexture"
}
// Render the object with the texture generated above, and invert the colors
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f
{
float4 grabPos : TEXCOORD0;
float4 pos : SV_POSITION;
};
v2f vert(appdata_base v) {
v2f o;
// use UnityObjectToClipPos from UnityCG.cginc to calculate
// the clip-space of the vertex
o.pos = UnityObjectToClipPos(v.vertex);
// use ComputeGrabScreenPos function from UnityCG.cginc
// to get the correct texture coordinate
o.grabPos = ComputeGrabScreenPos(o.pos);
return o;
}
sampler2D _BackgroundTexture;
half4 frag(v2f i) : SV_Target
{
half4 bgcolor = tex2Dproj(_BackgroundTexture, i.grabPos);
return 1 - bgcolor;
}
ENDCG
}
}
}
```
### 黑白特效
RGB色彩转为灰度,需要用到心理学公式:
$$
Gray = R*0.299 + G*0.587 + B*0.114
$$
因此,只需要将片元着色部分修改
```C
half4 frag(v2f i) : SV_Target
{
half4 bgcolor = tex2Dproj(_BackgroundTexture, i.grabPos);
float gray = dot(bgcolor.rgb, float3(0.299, 0.587, 0.114));
bgcolor = (gray, gray, gray);
return bgcolor;
}
```
### 模糊特效
模糊的思路主要是使用了贴图扰动的思路,
```C
sampler2D _BackgroundTexture;
uniform half4 _BackgroundTexture_TexelSize;
half4 frag(v2f i) : SV_Target
{
half4 bgcolor = tex2Dproj(_BackgroundTexture, i.grabPos);
half4 noise1 = tex2Dproj(_BackgroundTexture, i.grabPos*4);
half4 norbase1 = tex2D(_BackgroundTexture, i.grabPos + (4 * _BackgroundTexture_TexelSize * noise1.xy));
half4 norbase2 = tex2D(_BackgroundTexture, i.grabPos - (4 * _BackgroundTexture_TexelSize * noise1.yz));
half4 norbase3 = tex2D(_BackgroundTexture, i.grabPos + (4 * _BackgroundTexture_TexelSize * noise1.zx));
bgcolor = (norbase1 + norbase2 + norbase3) / 3;
return bgcolor;
}
```
<file_sep>---
layout: post
title: "Unity Draw Call 优化"
subtitle: " \"面试小记\""
date: 2020-10-20 00:55:00
author: "Mas9uerade"
header-img: "img/unityshader.jpg"
tags:
- Unity3d
- Optimize
---
> “最近面试被问到Unity的Draw Call优化相关的问题,遂学习了一遍并做笔记,转载自 [](http://www.cnblogs.com/xsln/p/5151951.html)”
## Unity Draw Call 优化
*Drawcall影响的是CPU的效率。因为draw call是CPU调用图形接口在屏幕上绘制对应的东西。
### Batch
为了在屏幕上draw一个物件(因为render和draw有些区别,所以为了区分清楚,这些概念用英文),引擎需要提供一个draw call的API。draw call调用性能开销是很大的,会导致CPU部分的性能负载。这通常是因为draw call间的状态改变(例如不同材质间的切换)导致,因为这些行为会导致显卡驱动进行开销很大的验证和转化步骤。
Unity用static batch来处理这件事情。static batch的目的是为了用尽可能少的缓冲区来重组尽可能多的mesh,从而获得更好的性能。因而static batch会出现一些巨大的mesh被渲染,而不是很多的小mesh被渲染。合并后的这些资源虽然在不同的地方出现,但是Unity会认为是同样的资源(因为这些小资源已经合并了)来循环进行渲染。它会为每个static bached mesh来做一系列的快速的draw call。
构建时做batch,在Unity5中只有一种方式,会构建index buffer, 然后一个draw call会被提交来用来处理合并的mesh里的每个可见的子mesh
#### 材质
只有使用同样材质的物件才能够合并。因而,如果你想获得好的合并效果,你需要尽可能多的使不同的物件贡献同样的材质。
如果你有两个典型的材质,它们仅仅只是贴图不同,你可以合并这些贴图到一个大的贴图里----这个过程通常叫做texture atlasing(也就是图集)。一旦贴图在同一个图集里,你就能只使用一个材质来代替。
*texture atlasing可参见以下网页https://en.wikipedia.org/wiki/Texture_atlas
如果你需要从脚本里获得共享重用的材质属性,你要注意修改Rendering.material将会创建这个材质的拷贝。因而你需要使用Renderer.sharedMaterial来获取找个共享的材质。
#### Static Batching(静态批次)
静态批次,对于没有移动且公用材质的物件,能有效减少drawcall。一般来说,静态批次比动态批次更有效,但它会占用更多的内存,也会消耗更少的CPU。
为了达到静态批次的效果,你需要显式的注明哪些物件是静态的,不移动,不旋转也不缩放的。你可以通过下面的方式来表明使用静态批次:
使用静态批次,需要额外的内存来存储合并的图形。如果一些物件使用的是同一份几何图形,做静态批次后,每个物件都会创建一份几何图形,无论是在编辑器还是运行时。这不是个好的方案,因此有时不得不避免采用静态批次(虽然会损失渲染的性能),但是可以保持一个较小的内存。例如,在一个密集的森林里把树都标记成需要静态批次的,会有严重的内存影响。
静态批次是通过转换一堆的静态物件到世界坐标系,来构建一个大的顶点和索引buffer。可见的物件在同一个静态批次,而且不会有状态的切换(状态切换的代价是很大的)
Dynamic Batching(动态批次)
当物件使用相同的材质,并且满足一定的条件时,Unity会自动合并物件来减少draw call。Dynamic batching 是自动做的,不需要教你做其他的事情。
Tips:
*Batching动态物件会给个顶点增加额外的开销,所以batch只适用于所有mesh合起来少于900个顶点的情况
**如果你的shader用的是vertex position, normal和 single UV,你能合并300个顶点;如果你的shader用的是vertex position ,normal, UV0, UV1和Tangent,只能达到180个
**PS:这条Unity5的规则数目新的版本里有可能会变
*一般来说,物件应该使用相同的trasform scale。
**对于不规则缩放的物件除外;如果一些物件有自己的不同的不规则的transform,他们还是会被batch的
*用不同的材质实例,会导致物件不被batch(即便这些材质实例实际上是相同的)
*使用光照图的物件会有额外的渲染参数:包括光照图的索引、相对光照图缩放和偏移。最好动态的光照图的物件能指向同一个光照图的位置,这样可以batch
*接收实时阴影的物件不会batch
*多通道的shader会破坏batch。几乎unity中所有的着色器在前向渲染中都支持多个光源,并为它们有效地开辟多个通道。为了“额外的每个像素光照”的draw call是不会batch的
Other batching tips
目前,只有Mesh Render和粒子系统被batch。其他的组件(如skin mesh, 布料)都不会被batch。另外半透明的shader因为要渲染半透明的效果常常要求物件是从后往前来绘制。Unity会按照这个顺序给物件排序,然后再尝试batch他们。但是因为顺序是严格要求的,所以半透明的物件能被batch的效果远不如不透明的物件。
一些Unity的render不能被batch。比如shadow casters,摄像机的深度图和GUI都会batch.
<file_sep>---
layout: post
title: "Python学习3-Delegate"
subtitle: " \"Python学习\""
date: 2018-04-17 00:20:00
author: "Mas9uerade"
header-img: "img/watchdog2_sf.jpg"
tags:
- Python
---
> “Python的委托”
## Python中的Delegate
首先,python是一个动态语言,附上一段[Wiki](https://https://en.wikipedia.org/wiki/Dynamic_programming_language)上对动态语言的定义。
Dynamic programming language, in computer science, is a class of high-level programming languages which, at runtime, execute many common programming behaviors that static programming languages perform during compilation. These behaviors could include extension of the program, by adding new code, by extending objects and definitions, or by modifying the type system. Although similar behaviours can be emulated in nearly any language, with varying degrees of difficulty, complexity and performance costs, dynamic languages provide direct tools to make use of them. Many of these features were first implemented as native features in the Lisp programming language.
Most dynamic languages are also dynamically typed, but not all are. Dynamic languages are frequently (but not always) referred to as "scripting languages", although the term "scripting language" in its narrowest sense refers to languages specific to a given run-time environment.
因此,Python的委托的实现,非常简单,在这个例子中,B的一个属性为A(),并重载了getattr(), 使得B可以通过getattr()访问A的属性,从而访问了A的函数f_one(),但也由于重载的原因,不能访问自己的函数f_three();
```python
class A:
def f_one(self, x):
pass
def f_two(self):
pass
class B():
def __init__(self):
self._a = A()
def f_three(self):
pass
def __getattr__(self, name):
return getattr(self._a, name)
b = B();
print(b.__getattr__("f_one"))
#print(b.__getattr__(("f_three")))
```
这个例子是展示使用getattr()直接访问属性的办法,直接让一个Class获取了wrapper的属性,去调用wrapper的函数
```python
class Wrapper:
def __init__(self, obj):
self.wrapper = obj
def __getattr__(self, item):
print("trace:", item)
return getattr(self.wrapper, item)
if __name__ == '__main__':
x = Wrapper([1, 2, 3, 4])
x.append(35)
x.remove(2)
print(x.wrapper) # [1,3,4,35]
pass
```
最后是C#式的Delegate的实现,全局函数,类的函数,回调都能被成功调用
```python
# C#式的delegate
class Foo(object):
def __init__(self):
self._bar_observers = []
def add_bar_observer(self, observer):
self._bar_observers.append(observer)
def notify_bar(self, param):
for observer in self._bar_observers:
observer(param)
def observer(param):
print ("observer(%s)" % param)
class Baz(object):
def observer(self, param):
print ("Baz.observer(%s)" % param)
class CallableClass(object):
def __call__(self, param):
print ("CallableClass.__call__(%s)" % param)
baz = Baz()
foo = Foo()
class BaseEvent(object):
temp = 0
def __init__(self):
self.temp = 1
class BigEvent(BaseEvent):
def __init__(self):
super(BigEvent, self).__init__()
print("BigEvent Run fast")
#super相当于C#的base
class EventCenter:
def __init__(self):
self. delList = dict()
def addevent(self, eventid, eventhandle):
if eventid in self.delList.keys():
self.delList[eventid].append(eventhandle)
else:
self.delList.setdefault(eventid,[])
self.delList[eventid].append(eventhandle)
def sendevnet(self, eventid, param):
if eventid in self.delList.keys():
for evhandle in self.delList.get(eventid):
evhandle(param)
#self.delList[eventid](param)
#print(self.delList[eventid](param))
def removeevent(self,eventid, eventhandle):
if eventid in self.delList.keys():
dictitem = {eventid: []}
for evhandle in self.delList.get(eventid):
if eventhandle != evhandle:
dictitem[eventid].append(evhandle)
if dictitem.values().__len__() > 0:
self.delList.update(dictitem)
def method1(baseevent):
print("method1", baseevent.temp)
def method2(baseevent):
print("method2", baseevent.temp)
def method3(baseevent):
print("method3", baseevent.temp)
aeventcenter = EventCenter()
baseev = BaseEvent()
bigev = BigEvent()
aeventcenter.addevent(1, method2)
aeventcenter.addevent(1,method1)
aeventcenter.addevent(1,method3)
aeventcenter.removeevent(1, method3)
aeventcenter.sendevnet(1,bigev)
foo.add_bar_observer(observer) # function
foo.add_bar_observer(baz.observer) # bound method
foo.add_bar_observer(CallableClass()) # callable instance
foo.notify_bar(3)
```
最后用Python实现一个事件中心
```python
#事件基类
class BaseEvent(object):
temp = 0
def __init__(self):
self.temp = 1
#事件子类
class BigEvent(BaseEvent):
def __init__(self):
super(BigEvent, self).__init__()
print("BigEvent Run fast")
#super相当于C#的base
#事件中心
class EventCenter:
def __init__(self):
self. delList = dict() #使用dict持有引用
#注册事件
def addevent(self, eventid, eventhandle):
if eventid in self.delList.keys():
self.delList[eventid].append(eventhandle)
else:
self.delList.setdefault(eventid,[])
self.delList[eventid].append(eventhandle)
#发送事件 -- python的优势在这里体现,参数的传入不需要限定类型
def sendevnet(self, eventid, param):
if eventid in self.delList.keys():
for evhandle in self.delList.get(eventid):
evhandle(param)
#self.delList[eventid](param) 这个方式是不行的
#print(self.delList[eventid](param))
#删除事件 -- Python的Dict相较于C#的dict和delegate的难用也体现出来了
def removeevent(self,eventid, eventhandle):
if eventid in self.delList.keys():
dictitem = {eventid: []}
for evhandle in self.delList.get(eventid):
if eventhandle != evhandle:
dictitem[eventid].append(evhandle)
if dictitem.values().__len__() > 0:
self.delList.update(dictitem)
def method1(baseevent):
print("method1", baseevent.temp)
def method2(baseevent):
print("method2", baseevent.temp)
def method3(baseevent):
print("method3", baseevent.temp)
aeventcenter = EventCenter()
baseev = BaseEvent()
bigev = BigEvent()
aeventcenter.addevent(1, method2)
aeventcenter.addevent(1,method1)
aeventcenter.addevent(1,method3)
aeventcenter.removeevent(1, method3)
aeventcenter.sendevnet(1,bigev)
```
<file_sep># UGUI drawcall合并原理
高数量的drawcall带来的坏处不用多说了,本篇重点说的是UGUI是如何合并drawcall的。 通过这篇博客,你将学会如何精算一个UGUI界面到底有几个drawcall,并且能想象出各UI控件的渲染顺序(即Frame Debugger窗口里的渲染顺序)。
以下案列的unity版本:

\##一、 概念篇
在学习本篇之前,你需要了解以下几个名词。
### bottomUI
A是B的bottomUI需要满足:(单条只是必要条件,1、2、3合起来才是充分条件)
1. **B的mesh构成的矩形和A的mesh构成的矩形有相交,注意不是RectTransform的矩形相交,这点需要认真理解一下,下面给出一组案列帮助大家理解。**
2. **A.siblingIndex < B.siblingIndex (即在Hierachy里A在B之上)**
3. **如果B有多个UI满足1、2条规则,则B的bottomUI应取siblingIndex差值的绝对值最小的那个(有点绕哈,depth的案例有这种情况)**


黑色的线框即是mesh的矩形了,上图的Text组件和image组件是没有相交的,但注意他们的RectTransform其实是已经有相交了。此时,**Text组件不能算作Image组件的bottomUI**,因为不满足第1条。
### 合批
当两个UI控件的材质球的instanceId(材质球的instanceId和纹理)一样,那么这两个UI控件才有可能合批
### depth
depth是UGUI做渲染排序的第一参考值,它是通过一些简单的规则计算出来的。 在理解了bottomUI的基础上,depth就很好算了。先给出计算规则:

下面给出一个案例来帮助理解:


根据树的深度优先遍历,容易得到UI节点遍历顺序:I1、T1、I2、R2、R1
根据depth的计算规则,得到每个UI控件的depth值
| UI控件名称 | depth值 | 说明(I=Image、T=Text、R=RawImage) |
| ---------- | ------- | ------------------------------------------------------------ |
| I1 | 0 | |
| T1 | 1 | |
| I2 | 2 | I2的bottomUI是T1,且两者的mesh有相交,还不能合批,所以I2.depth = T1.depth + 1 = 1 + 1 = 2 |
| R2 | 2 | 先来确定R2的bottomUI应该是I2,而非I1,因为依据bottomUI规则的第3条,R2.siblingIndex - I2.siblingIndex = 1,R2.siblingIndex - I1.siblingIndex = 3。然后R2和I2能够合批(为什么能够合批,后文会做解释),所以 R2.depth = I2.depth = 2 |
| R1 | 2 | |
这样就算出了各个UI控件的depth值了。
不要以为 I2 和 R2 的控件类型不一样就不能合批了,UGUI的渲染引擎不会去考虑两个UI控件类型是否一样,它只考虑两个UI控件的材质球及其参数是否一样,如果一样,就可以合批,否则不能合批。而实际项目中,我们往往都会认为一个RawImage就会占用一个drawcall,其实这个说法只是一种经验,并不完全正确。因为我们使用RawImage的时候都是拿来显示一些单张的纹理,比如好友列表里的头像,如果这些头像都是玩家自定义上传的头像,往往互不相同,当渲染到RawImage的时候,就会导致头像的材质球使用的纹理不同而导致不能合批而各占一个drawcall。但如果是使用的系统头像,那么就可以让两个使用了相同系统头像的RawImage合批。我们这个案例,I2和R2使用的材质球(Default UI Material) 和 纹理(Unity White)都是一样的,所以能够合批。
### 材质球ID
材质球的 InstanceID
### 纹理ID
纹理的InstanceID
## 二、排序and计算drawcall 数
有了上面的数据,UGUI会对所有的UI控件(CanvasRenderer)按depth、材质球ID、纹理ID做一个排序,那么这些字段的排序优先级也是有规定的:

给出一个案列来帮助理解:






| UI控件名称 | 使用的材质球 | 使用的纹理 |
| ---------- | ------------------------------------ | ------------------------------------- |
| I1 | M_InstID_Bigger | texture_InstID_Smaller |
| I2 | M_InstID_Smaller | texture_InstID_Smaller |
| R1 | M_InstID_Bigger | texture_InstID_Bigger |
| T1 | UI Default Matiaral(UGUI 默认材质球) | Font Texture(unity自带的一个字体纹理) |
步骤1:先算各个UI控件的depth值
| UI控件名称 | depth值 |
| ---------- | ------- |
| I1 | 0 |
| I2 | 0 |
| R1 | 0 |
| T1 | 1 |
步骤二:排序
1、**按depth值做升序排序。**得 I1、I2、R1、T1
2、**材质球ID排序。**因为 I1、I2、R1的depth值相等,那么再对他们进行材质球ID进行升序排序,得:
**I2.materialID < I1.materialID = R1.materialID**
所以经过材质球排序后:I2、I1、R1、T1
3、**纹理ID排序。\**因为I1和R1的材质球ID相同,故需要进行\**纹理ID降序**排序,得 R1.TexutureID > I1.TextureID
所以经过纹理排序后:I2、R1、I1、T1
至此,就把所有的UI控件都排好序了,得到了所谓的 VisibleList = {I2,R1,I1,T1}
用表格来表示:
| UI控件名称 | depth值 |
| ---------- | ------- |
| I2 | 0 |
| R1 | 0 |
| I1 | 0 |
| T1 | 1 |
步骤三:**合批。**对depth相等的连续相邻UI控件进行合批(注意只有depth相等的才考虑合批,如果depth不相等,即使符合合批条件,也不能合批)。很显然,I2,I1,R1虽然他们depth相等,但不符合合批条件,所以都不能合批。
步骤四:**计算drawcall。**合批步骤完成后就可以计算drawcall数了,即drawcall count = 合批1 + 合批2 + … + 合批n = n * 1 = n (其中 合批i = 1)
所以这个案例的 drawcall count = 1 + 1 + 1 + 1 = 4。渲染顺序(就是我们最终排好序的顺序)是:先画 I2,其次 R1,其次 I1,最后T1。只要打开 Window > Frame Debugger 窗口就可以轻松验证,这里就不贴图了。
最后,希望想搞明白点的能动动手,自己建一个空工程,摆弄一些案例,利用本文的知识来自己算算drawcall数及推出UGUI的渲染顺序。最后经过反复的练习能够总结出一些用较少的drawcall来拼UI的规律。
下一篇,将探究臭名昭著的mask,看看它是不是真的那么不堪,还是我们了解的还不够!
虽然 Mask 的名声不是很好,但是在做界面的时候很多时候都需要它,比如滚动列表。要想精算出一个UI的drawcall数和渲染顺序,光掌握[上一篇](https://blog.csdn.net/akak2010110/article/details/80953370)的知识或许还有些吃力,因为mask在项目里真的太常见了。也往往是UI的drawcall数的一个重灾区。本文不说Mask和RectMask2D是如何实现的,仅仅设立一些案例来总结出两者的性质,希望能给我们做UI时一些实用的指导性作用。也希望看完了本文之后,能了解这两者的区别。
希望看到这篇文章的朋友确定已经掌握了上一篇的知识。
# 一、RectMask2D
RectMask2D不需要依赖一个Image组件,其裁剪区域就是它的RectTransform的rect大小。
## 性质1:RectMask2D节点下的所有孩子都不能与外界UI节点合批且多个RectMask2D之间不能合批。
## 性质2:计算depth的时候,所有的RectMask2D都按一般UI节点看待,只是它没有CanvasRenderer组件,不能看做任何UI控件的bottomUI。
# 二、Mask
Mask组件需要依赖一个Image组件,裁剪区域就是Image的大小。
## 性质1:Mask会在首尾(首=Mask节点,尾=Mask节点下的孩子遍历完后)多出两个drawcall,多个Mask间如果符合合批条件这两个drawcall可以对应合批(mask1 的首 和 mask2 的首合;mask1 的尾 和 mask2 的尾合。首尾不能合)
## 性质2:计算depth的时候,当遍历到一个Mask的首,把它当做一个不可合批的UI节点看待,但注意可以作为其孩子UI节点的bottomUI。
## 性质3:Mask内的UI节点和非Mask外的UI节点不能合批,但多个Mask内的UI节点间如果符合合批条件,可以合批。
从Mask的性质3可以看出,并不是Mask越多越不好,因为Mask间是可以合批的。得出以下结论:
**当一个界面只有一个mask,那么,RectMask2D 优于 Mask**
**当有两个mask,那么,两者差不多。**
**当 大于两个mask,那么,Mask 优于 RectMask2D。**
# 三、drawcall数和渲染顺序
利用本文的性质,再利用上一篇的知识,就可以精算出一个带有mask的UI的drawcall数和渲染顺序。多利用 Frame Debugger 窗口多多练习,熟能生巧!!<file_sep>### Unity PBR简介
#### Diffusion & Reflection
“漫反射”和“镜面反射”分别描述了物体表面和光的最基本的相互作用。当光线以电磁波的形式传播到物体表面时,会产生反射——光线朝物体表面法线的另一侧离开。这种行为跟一个球碰撞到地面发生弹射的行为一样。在光滑的表面,将产生完美的反射现象。“镜面反射”经常用来描述这种现象。 并不是所有的光在物体表面都产生镜面反射。还有一部分进入物体内部。这部分光要不被物体吸收(通常转化为热能),要不在物体内部散射,其中一部分会从物体表面散射出来而被重新看到。这种现象称为“漫反射”或更复杂一点的“次表面散射”。

吸收或散射根据物体表面颜色不同而不同(比如,如果物体表面呈现蓝色,表示的是物体表面吸收蓝色以外所有的光,散射出蓝色波长的光)。通常散射方向具有相当的随机性,我们可以认为散射的方向是任何方向。通常着色程序用一个颜色变量称为“albedo”或“diffuse color”来近似描述物体表面散射颜色。
#### **Translucency & Transparency**
某些材质的漫反射要复杂一些——比如那些具有很长散射距离的材质:皮肤、蜡等的散射,通常一个简单的颜色变量是不够的,着色系统还需要考虑这些被照射物体的形状和厚度,如果物体足够薄,可以看到光从其背后散射出来,物体呈现半透明状;如果漫反射非常的小——比如玻璃,几乎没法注意到散射现象,光线完整的从物体的一边穿透到另一边,物体呈现全透明状。不同物体的次表面散射不尽相同,通常需要专门的“次表面散射”着色模型去模拟它。
#### **Energy Conservation**
根据上面的描述我们得到一个结论:漫反射和镜面反射是互斥的。这是因为被物体散射的光线必须进入物体表面(那它就不能被镜面反射了)。这个结论符合“能量守恒”,也就是说离开表面的光不可能比原始的入射光要亮。着色系统很容易做到这一点:假设1表示100%光能,用1减去镜面反射的光,剩下的就属于漫反射部分。这意味着强烈高光的物体几乎没有漫反射现象,原因就是没有光进入到物体表面,大部分被镜面反射了。反之亦然。

能量守恒是PBR的一个重要概念。它可以保证美术合适的设置材质的反射率和albedo值,而不破坏物理规则。虽然在着色系统中强制能量守恒的物理限制并不等价于最后好看的着色效果,但起码可以使得渲染效果不至于背离物理规则太远,保证在不同光照条件下物体的光照表现一致性。
#### **Metals**
金属作为最常见导电材质,有几点特性值得被特殊提及。 首先,金属大多比绝缘体更容易发生镜面反射。导体一般的镜面反射率高达60-90%,而绝缘体一般在0-20%的范围。这种高反射率阻止了大部分光到达其内部产生散射,使得金属看起来很闪亮。 其次,导体的反射率在可见光谱中呈现多样变化,使得它们的反射光具有颜色(白光照射下)。反射光具有颜色很奇怪,但确实在我们日常的材质中出现(比如,金、铜和黄铜)。绝缘体大部分情况下不会呈现出这种效果,它们的反射光的颜色是一般跟光源颜色一致。 最后,导体通常对进入其表面的光是吸收而不是散射。这意味着理论上导体不会表现出任何的漫反射,但实际中由于金属表面氧化等原因,还是会表现出部分散射效果。根据金属的这些特性呢,PBR着色系统用“metalness”作为输入来表示材料的金属程度,而不是albedo & reflectivity。
#### Fresnel
Fresnel现象是光照反射现象中不可或缺的部分。计算机图形学中Fresnel用来定义不同角度下的不同反射率——入射光方向越平行于物体表面,反射率越高。这意味着物体表面在Fresnel效果作用下,物体的边缘会更亮。大部分人可能已经对Fresnel效果已经有所了解,并且Fresnel效果在计算机图形中也不是新东西,然而,PBR对Fresnel估算公式做了一些重要的纠正。 首先,入射光方向接近平行于物体表面时,一切光滑物体边缘表现为完美镜面反射,只要它足够光滑并且在合适的观察角度(也接近平行于物体表面)下,任何材质物体都表现为完美镜面反射。这有点违反直觉,但物理现象就是如此。 其次对Fresnel属性的观察发现不同材质的随入射光角度变化得到的Fresnel变化曲线和梯度差异并不大。对我们来讲意味着:如果我们期望渲染更加真实,美术对Fresnel行为的控制应该被降低,而不是被放大,或者说,没必要暴露多余的Fresnel参数让美术去调节。少了参数控制,就简化了美术内容生成,这是个利好。PBR光照模型根据光泽度和反射率就可以自动去计算合适的Fresnel效果。

Fresnel效果会随着物体表面的光滑度变低快速的变弱,接下来的内容会介绍到这些。
#### MicroSurface
散射和反射都依赖物体表面的朝向。宏观上来看,物体表面朝向由物体的网格形状决定,或者是网格的法线贴图决定。渲染系统根据法线信息已经可以很好的渲染散射和反射。但是真实世界的表面在微观世界是不完美的:小坑,小裂缝和小块,这些不容易被肉眼看到的微观世界下的表面特性对散射和反射仍产生巨大影响。

上图中,平行的入射光线被粗糙的表面分散反射。因为光线发生碰撞的微表面的朝向各不相同,就像把球扔向凹凸不平的地面一样,球的弹射方向是不可预测的。简短的说,表面越粗糙,放射的光线越分散,呈现出“模糊”状。不过对每一个微表面进行反射估值在实时渲染计算中是不现实的,所以我们不直接描述微表面细节,而是通过一个粗糙度的概念和一个相当精确的光照模型得到接近的结果,这个通用的粗糙度叫做是“Gloss”, “Smoothness”, 或“Roughness”。在材质中可以是一张贴图或一个固定值。材质中的微表面细节是非常重要的属性,它用来模拟真实世界中的各种微表面特征。光泽度贴图不是一个新概念,但是它在基于物理的着色中占有关键的地位,因为它对光的反射效果有决定性的影响。接下来我们将会看到。
#### **Energy Conservation (Again)**
假设我们的着色系统已经考虑了微表面细节,反射多少入射光才是合适的是个值得研究的课题。光滑的表面会比粗糙的表面得到更加清楚的高光,这是符合能量守恒物理定律的:不同的材质反射了相同量级的入射光,但粗糙的表面反射的光线更加分散,看起来更模糊更暗,而光滑的表面反射更加集中,看起来更清晰更亮。

#### **All Hail Microsurface**
基于上面的认识我们得到一个结论:物体微表面光泽度直接影响了表面的光照表现。这意味着美术人员只用通过调整光泽贴图的形状和强度就可得到物体表面的划痕、凹痕、磨损或抛光等效果,而不额外需要高光遮罩贴图或反射率这些参数设置。
微表面细节和反射率在物理上是相互联系的,就像之前描述的散射和反射一样,抛开它们之间的联系而单独分离的去设置它们有可能违背背后的光学物理规则。
还有,对真实世界观察发现,材质之间的反射率的差异并不明显,比如水坑和泥巴,它们有非常相近的反射率,但泥巴非常粗糙,而水坑非常光滑,它们呈现出截然不同的反射表现。美术人员在创建这样的场景应该选择光泽度而不是反射率来做为主要的材质差异设置项,见下图:

微表面属性对其他一些效果也有略微影响。比如,Fresnel效果在粗糙表面上会变弱,还有,大或凹微表面会“捕获”更多的光线,导致光在表面出线多次反射,从而被吸收的光量增加,亮度降低。不同的PBR系统处理这些细节的方式可能有些不同,最后呈现的结果也可能有些许不同,但总体还是遵守能量守恒的。
<file_sep>//445.两数相加 II
//给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
//你可以假设除了数字 0 之外,这两个数字都不会以零开头。
//进阶:
//如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
//示例:
//输入:(7 -> 2 -> 4 -> 3) +(5-> 6-> 4)
//输出:7-> 8-> 0-> 7
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/add-two-numbers-ii
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//和第一题的区别在于是倒序的,且不能翻转链表
//思路 -> 空间换时间,存储链表数据 -> 先遍历的在底下,用栈
using System;
using System.Collections;
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
public ListNode AddTwoNumbers2(ListNode l1, ListNode l2)
{
Stack<int> stack1 = new Stack<int>();
Stack<int> stack2 = new Stack<int>();
while (l1 != null)
{
stack1.Push(l1.val);
l1 = l1.next;
}
while (l2 != null)
{
stack2.Push(l2.val);
l2 = l2.next;
}
int a, b;
int val = 0;
int sum = 0;
int carry = 0;
//ListNode head = new ListNode(0);
ListNode cur = null;
while (stack1.Count > 0 || stack2.Count > 0 || carry > 0)
{
a = stack1.Count > 0 ? stack1.Pop() : 0;
b = stack2.Count > 0 ? stack2.Pop() : 0;
sum = a + b + carry;
val = sum >= 10 ? sum - 10 : sum;
carry = sum >= 10 ? 1 : 0;
ListNode node = new ListNode(val);
node.next = cur;
cur = node;
//head.next = node;
}
return cur;
}
}
}
<file_sep># 计算机图形学入门笔记
## L2 Review of Linear Algebra 线性代数回顾
### 1. Vector(向量)
#### 1. Dot Product (点乘)
#### 2. Cross Product(叉乘)
## L3 Transformation
#### 变换需要使用方面
1. Modeling
1. Moving
2. Rotating
3. Scaling
2. Viewing
1. 3D -> 2D Projection
#### 二维变换
1. Scale Transform(缩放变换)
2. Reflection Transform (翻转变换)
3. Shear Transform (切变)
#### 齐次坐标
## L4 Rasterization
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
public class Solution
{
public class Meeting : IComparable<Meeting>
{
public int startDay;
public int endDay;
public Meeting(int _startDay, int _endDay)
{
startDay = _startDay;
endDay = _endDay;
}
public int CompareTo(Meeting other)
{
if (endDay > other.endDay)
{
return 1;
}
else if (endDay < other.endDay)
{
return -1;
}
else
{
if (startDay <other.startDay)
{
return -1;
}
else if (startDay > other.startDay)
{
return 1;
}
else
{
return 0;
}
}
}
}
public class MeetingInPool: IComparable<MeetingInPool>
{
public int startDay;
public int endDay;
public MeetingInPool(int _startDay, int _endDay)
{
startDay = _startDay;
endDay = _endDay;
}
public int CompareTo(MeetingInPool other)
{
if (startDay > other.startDay)
{
return 1;
}
else if (startDay < other.startDay)
{
return -1;
}
else
{
return 0;
}
}
public Meeting ToMeeting()
{
return new Meeting(startDay, endDay);
}
}
public static int MaxEvents(int[][] events)
{
if (events == null || events.Length == 0)
{
return 0;
}
PriorityQueue<Meeting> pq = new PriorityQueue<Meeting>();
PriorityQueue<MeetingInPool> pool = new PriorityQueue<MeetingInPool>();
List<int> viewMeeting = new List<int>();
int today = 0;
int meetingCount = 0;
for (int i = 0; i < events.Length; ++i)
{
pool.Enqueue(new MeetingInPool(events[i][0], events[i][1]));
}
//还有会议没开始
while (pool.Count>0 ||pq.Count>0)
{
today++;
//载入可选队列
while (pool.Count >0 && pool.Peek().startDay <= today)
{
pq.Enqueue(pool.Dequue().ToMeeting());
}
//清掉过期的会议
while (pq.Count>0 && pq.Peek().endDay < today)
{
pq.Dequue();
}
//开会
if (pq.Count >0)
{
pq.Dequue();
meetingCount++;
}
}
return meetingCount;
}
//public class PriorityIntQueue
//{
// private List<int> data;
// public PriorityIntQueue()
// {
// data = new List<int>();
// }
// public int Count
// {
// get
// {
// return data.Count;
// }
// }
// public void Enqueue(int item)
// {
// data.Add(item);
// int childIndex = data.Count - 1;
// while (childIndex > 0)
// {
// int parentIndex = (childIndex - 1) / 2;
// if (data[childIndex] >= data[parentIndex])
// {
// break;
// }
// int tmp = data[childIndex];
// data[childIndex] = data[parentIndex];
// data[parentIndex] = tmp;
// }
// }
// public int Dequeue()
// {
// int lastIndex = data.Count - 1;
// int front = data[0];
// data[0] = data[lastIndex];
// data.RemoveAt(lastIndex);
// --lastIndex;
// int parentIndex = 0;
// while(true)
// {
// int childIndex = parentIndex * 2 + 1;
// if (childIndex > lastIndex)
// {
// break;
// }
// int rightChild = childIndex + 1;
// if (rightChild <= lastIndex && data[rightChild] < data[childIndex])
// {
// childIndex = rightChild;
// }
// if (data[parentIndex] < data[childIndex])
// {
// break;
// }
// int tmp = data[parentIndex];
// data[parentIndex] = data[childIndex];
// data[childIndex] = tmp;
// parentIndex = childIndex;
// }
// return front;
// }
//}
//优先队列的实现方式是小根堆/大根堆
public class PriorityQueue<T> where T : IComparable<T>
{
private List<T> data;
public PriorityQueue()
{
this.data = new List<T>();
}
public int Count
{
get
{
return data.Count;
}
}
public void Enqueue(T item)
{
data.Add(item);
int childIndex = data.Count - 1;
while (childIndex > 0)
{
int parentIndex = (childIndex - 1) / 2;
//此时已经完成了小节点的上浮
if (data[childIndex].CompareTo(data[parentIndex]) >= 0)
{
break;
}
//否则交换节点
T tmp = data[childIndex];
data[childIndex] = data[parentIndex];
data[parentIndex] = tmp;
childIndex = parentIndex;
}
}
public T Peek()
{
return data[0];
}
public T Dequue()
{
//交换节点数据去尾,减少时间复杂度
int lastIndex = data.Count -1;
T frontItem = data[0]; // fetch the front
data[0] = data[lastIndex];
data.RemoveAt(lastIndex);
--lastIndex;
int parentIndex = 0;
//小根堆维护
while (true)
{
int childIndex = parentIndex * 2 + 1; // left child index of parent
if (childIndex > lastIndex) break; // no children so done
int rightChild = childIndex + 1; // right child
// if there is a rc (ci + 1), and it is smaller than left child, use the rc instead
if (rightChild <= lastIndex && data[rightChild].CompareTo(data[childIndex]) < 0)
{
childIndex = rightChild;
}
// parent is smaller than (or equal to) smallest child so done
if (data[parentIndex].CompareTo(data[childIndex]) <= 0)
{
break;
}
T tmp = data[parentIndex];
data[parentIndex] = data[childIndex];
data[childIndex] = tmp; // swap parent and child
parentIndex = childIndex;
}
return frontItem;
}
}
}
<file_sep>---
layout: post
title: "平衡二叉树"
subtitle: " \"面试小记\""
date: 2020-11-15 09:44:09
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- 数据结构
---
> “面试知识点整理”
## 平衡二叉树
平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

### 平衡因子
某结点的左子树与右子树的高度(深度)差即为该结点的平衡因子(BF,Balance Factor)。平衡二叉树上所有结点的平衡因子只可能是 -1,0 或 1。如果某一结点的平衡因子绝对值大于1则说明此树不是平衡二叉树。**为了方便计算每一结点的平衡因子我们可以为每个节点赋予height这一属性,表示此节点的高度。**
### 基础设计
首先我们可以设计出AVL树节点,并且实现一些简单通用的方法供后续操作。
```java
/**
* AVLTree是BST,所以节点值必须是可比较的
*/
public class AvlTree<E extends Comparable<E>>{
private class Node{
public E e;
public Node left;
public Node right;
public int height;
public Node(E e){
this.e = e;
this.left = null;
this.right = null;
this.height = 1;
}
}
private Node root;
private int size;
public AvlTree(){
root=null;
size=0;
}
//获取某一结点的高度
private int getHeight(Node node){
if(node==null){
return 0;
}
return node.height;
}
public int getSize(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
/**
* 获取节点的平衡因子
* @param node
* @return
*/
private int getBalanceFactor(Node node){
if(node==null){
return 0;
}
return getHeight(node.left)-getHeight(node.right);
}
//判断树是否为平衡二叉树
public boolean isBalanced(){
return isBalanced(root);
}
private boolean isBalanced(Node node){
if(node==null){
return true;
}
int balanceFactory = Math.abs(getBalanceFactor(node));
if(balanceFactory>1){
return false;
}
return isBalanced(node.left)&&isBalanced(node.right);
}
}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
```
## 添加节点
往平衡二叉树中添加节点很可能会导致二叉树失去平衡,所以我们需要在每次插入节点后进行平衡的维护操作。**插入节点破坏平衡性有如下四种情况:**
### LL(右旋)
LL的意思是向左子树(L)的左孩子(L)中插入新节点后导致不平衡,这种情况下需要右旋操作,而不是说LL的意思是右旋,后面的也是一样。

我们将这种情况抽象出来,得到下图:

我们需要对节点y进行平衡的维护。**步骤如下图所示:**

```java
/**
* 右旋转
*/
private Node rightRotate(Node y){
Node x = y.left;
Node t3 = x.right;
x.right = y;
y.left = t3;
//更新height
y.height = Math.max(getHeight(y.left),getHeight(y.right))+1;
x.height = Math.max(getHeight(x.left),getHeight(x.right))+1;
return x;
}
```
### RR

我们将这种情况抽象出来,得到下图:

我们需要对节点y进行平衡的维护。**步骤如下图所示:**

```java
/**
* 左旋转
*/
private Node leftRotate(Node y){
Node x = y.right;
Node t2 = x.left;
x.left = y;
y.right = t2;
//更新height
y.height = Math.max(getHeight(y.left),getHeight(y.right))+1;
x.height = Math.max(getHeight(x.left),getHeight(x.right))+1;
return x;
}
```
### LR

我们将这种情况抽象出来,得到下图:

我们需要对节点y进行平衡的维护。**步骤如下图所示:**

**第三个图中x和z反了,失误**
### RL

我们将这种情况抽象出来,得到下图:

我们需要对节点y进行平衡的维护。**步骤如下图所示:**

**第二个图中y的左孩子为T1,第三个图中x和z反了,孩子也错了,应该是从左至右T1,T2,T3,T4,失误。。。**
### 添加节点代码
```java
// 向二分搜索树中添加新的元素(key, value)
public void add(E e){
root = add(root, e);
}
// 向以node为根的二分搜索树中插入元素(key, value),递归算法
// 返回插入新节点后二分搜索树的根
private Node add(Node node, E e){
if(node == null){
size ++;
return new Node(e);
}
if(e.compareTo(node.e) < 0)
node.left = add(node.left, e);
else if(e.compareTo(node.e) > 0)
node.right = add(node.right, e);
//更新height
node.height = 1+Math.max(getHeight(node.left),getHeight(node.right));
//计算平衡因子
int balanceFactor = getBalanceFactor(node);
if(balanceFactor > 1 && getBalanceFactor(node.left)>0) {
//右旋LL
return rightRotate(node);
}
if(balanceFactor < -1 && getBalanceFactor(node.right)<0) {
//左旋RR
return leftRotate(node);
}
//LR
if(balanceFactor > 1 && getBalanceFactor(node.left) < 0){
node.left = leftRotate(node.left);
return rightRotate(node);
}
//RL
if(balanceFactor < -1 && getBalanceFactor(node.right) > 0){
node.right = rightRotate(node.right);
return leftRotate(node);
}
return node;
}
12345678910111213141516171819202122232425262728293031323334353637383940
```
## 删除节点
在删除AVL树节点前需要知道二分搜索树的节点删除操作[【点此学习吧!】](https://blog.csdn.net/qq_25343557/article/details/84330095#t7),和二分搜索树删除节点不同的是我们删除AVL树的节点后需要进行平衡的维护操作。
```java
public E remove(E e){
Node node = getNode(root, e);
if(node != null){
root = remove(root, e);
return node.e;
}
return null;
}
private Node remove(Node node, E e){
if( node == null )
return null;
Node retNode;
if( e.compareTo(node.e) < 0 ){
node.left = remove(node.left , e);
retNode = node;
}
else if(e.compareTo(node.e) > 0 ){
node.right = remove(node.right, e);
retNode = node;
}
else{ // e.compareTo(node.e) == 0
// 待删除节点左子树为空的情况
if(node.left == null){
Node rightNode = node.right;
node.right = null;
size --;
retNode = rightNode;
}
// 待删除节点右子树为空的情况
else if(node.right == null){
Node leftNode = node.left;
node.left = null;
size --;
retNode = leftNode;
}else {
// 待删除节点左右子树均不为空的情况
// 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
// 用这个节点顶替待删除节点的位置
Node successor = minimum(node.right);
successor.right = remove(node.right, successor.e);
successor.left = node.left;
node.left = node.right = null;
retNode = successor;
}
}
if(retNode==null)
return null;
//维护平衡
//更新height
retNode.height = 1+Math.max(getHeight(retNode.left),getHeight(retNode.right));
//计算平衡因子
int balanceFactor = getBalanceFactor(retNode);
if(balanceFactor > 1 && getBalanceFactor(retNode.left)>=0) {
//右旋LL
return rightRotate(retNode);
}
if(balanceFactor < -1 && getBalanceFactor(retNode.right)<=0) {
//左旋RR
return leftRotate(retNode);
}
//LR
if(balanceFactor > 1 && getBalanceFactor(retNode.left) < 0){
node.left = leftRotate(retNode.left);
return rightRotate(retNode);
}
//RL
if(balanceFactor < -1 && getBalanceFactor(retNode.right) > 0){
node.right = rightRotate(retNode.right);
return leftRotate(retNode);
}
return retNode;
}
```<file_sep>//1259.不相交的握手
//偶数 个人站成一个圆,总人数为 num_people 。每个人与除自己外的一个人握手,所以总共会有 num_people / 2 次握手。
//将握手的人之间连线,请你返回连线不会相交的握手方案数。
//由于结果可能会很大,请你返回答案 模 10^9+7 后的结果。
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/handshakes-that-dont-cross
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
using System;
using System.Collections.Generic;
//解题思路
//以1和其他点相连作为分割点
//分割要求必须剩下的两堆点都是偶数个
namespace ByteDancePopular
{
public partial class Solution
{
public int NumberOfWays(int num_people)
{
long[] dp = new long[num_people / 2 + 1];
long modulus = (long)Math.Pow(10, 9) + 7;
dp[0] = 1;
for (int i =1; i < num_people/2+1; ++i)
{
for (int j =1; j <= i; ++j)
{
dp[i] += dp[j - 1] * dp[i - j];
dp[i] %= modulus;
}
}
return (int)dp[num_people / 2];
}
}
}<file_sep>namespace ByteDancePopular
{
public partial class Solution
{
public ListNode ReverseList_Recursion(ListNode head)
{
if (head == null || head.next == null)
{
return head;
}
ListNode p = ReverseList_Recursion(head.next);
head.next.next = head;
head.next = null;
return p;
}
public ListNode ReverseList_Iteration(ListNode head)
{
ListNode node = head;
ListNode cur = null;
while (node != null)
{
ListNode tmp = node.next;
node.next = cur;
cur = node;
node = tmp;
}
return cur;
}
}
}<file_sep>---
layout: post
title: "Welcome to Mas9uerade's Blog"
subtitle: " \"Hello World, Hello Blog\""
date: 2018-04-14 17:57:00
author: "Mas9uerade"
header-img: "img/watchdog2_sf.jpg"
tags:
- 闲谈
---
> “First Time to Blog”
## 前言
第一次写博客,原因为想要一个地方记录一些之前做的学习笔记,正好[nankenan](https://nankenan.github.io)给我这个没点过任何前端技能点的推荐了github的主页与jekyll。
之后,沉迷在了尝试模版而不是博客本身,最后索性从git上fork了[Hux](https://huxpro.github.io) 的模板,几乎不做修改地就拿来使用了。
期间经历了每晚11点前家里的电脑Git Clone龟速到崩溃(明明我的socks看youtube 720p 丝滑流畅),所以先记下了几个Trick(虽然尝试过全部都没用)。
1. 修改Hosts文件, 在访问过程中能跳过dns解析步骤.
2. 减少Clone的Depth.
目前暂定目标一个月两份笔记更新到2019年吧.<file_sep>using System;
using System.Collections.Generic;
//优先队列的实现方式是小根堆/大根堆
public class PriorityQueue<T> where T : IComparable<T>
{
private List<T> data;
public PriorityQueue()
{
this.data = new List<T>();
}
public PriorityQueue(int capacity)
{
this.data = new List<T>(capacity);
}
public int Count
{
get
{
return data.Count;
}
}
public void Enqueue(T item)
{
data.Add(item);
int childIndex = data.Count - 1;
while (childIndex > 0)
{
int parentIndex = (childIndex - 1) / 2;
//此时已经完成了小节点的上浮
if (data[childIndex].CompareTo(data[parentIndex]) >= 0)
{
break;
}
//否则交换节点
T tmp = data[childIndex];
data[childIndex] = data[parentIndex];
data[parentIndex] = tmp;
childIndex = parentIndex;
}
}
public T Peek()
{
return data[0];
}
public T Dequue()
{
//交换节点数据去尾,减少时间复杂度
int lastIndex = data.Count - 1;
T frontItem = data[0]; // fetch the front
data[0] = data[lastIndex];
data.RemoveAt(lastIndex);
--lastIndex;
int parentIndex = 0;
//小根堆维护
while (true)
{
int childIndex = parentIndex * 2 + 1; // left child index of parent
if (childIndex > lastIndex) break; // no children so done
int rightChild = childIndex + 1; // right child
// if there is a rc (ci + 1), and it is smaller than left child, use the rc instead
if (rightChild <= lastIndex && data[rightChild].CompareTo(data[childIndex]) < 0)
{
childIndex = rightChild;
}
// parent is smaller than (or equal to) smallest child so done
if (data[parentIndex].CompareTo(data[childIndex]) <= 0)
{
break;
}
T tmp = data[parentIndex];
data[parentIndex] = data[childIndex];
data[childIndex] = tmp; // swap parent and child
parentIndex = childIndex;
}
return frontItem;
}
}
<file_sep># 甜蜜的开始
11月23号1点38分,昨天凌晨的时候,我向我今生最喜欢的女生表白了,世界兜兜转转这么多年,身边的人离开又回来,我又回到了最初的起点,这十年来有太多的错过了,多到每一次想起眼角总会不经意湿润,但也正因为这些经历,我才变成了现在的样子,习惯陪着她,还喜欢她爱着她。
第一次的错过是高考的遗憾
第二次的错过是对异地的恐惧
第三次的错过是对未来的迷茫
往后余生,我希望能不要再错过,也不要再放过,我希望能够两个人一起成长,去面对未来的风风雨雨,去经历未曾见过的风景,去看大好河山,去看历史变迁,停观晚霞日落,期待海上升日,一起度过一个个有纪念意义的日子,也一起度过一个个平凡普通的夜晚,能够一起去分享人生的快乐和一同去承担对应的失落。
把心愿本上的一个个心愿实现
把地图上的一个个景点涂上标记
<file_sep>---
layout: post
title: "Unity GC"
subtitle: " \"面试小记\""
date: 2020-11-29 23:48:39
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- Unity
---
> “面试知识点整理
## 为什么需要GC
为什么要使用GC呢?也可以说是为什么要使用内存自动管理?有下面的几个原因:
1、提高了软件开发的抽象度;
2、程序员可以将精力集中在实际的问题上而不用分心来管理内存的问题;
3、可以使模块的接口更加的清晰,减小模块间的偶合;
4、大大减少了内存人为管理不当所带来的Bug;
5、使内存管理更加高效。
总的说来就是GC可以使程序员可以从复杂的内存问题中摆脱出来,从而提高了软件开发的速度、质量和安全性。
### GC (garbage collection)简介
在游戏运行的时候,数据主要存储在内存中,当游戏的数据在不需要的时候,存储当前数据的内存就可以被回收以再次使用。内存垃圾是指当前废
弃数据所占用的内存,垃圾回收(GC)是指将废弃的内存重新回收再次使用的过程。
Unity中将垃圾回收当作内存管理的一部分,如果游戏中废弃数据占用内存较大,则游戏的性能会受到极大影响,此时垃圾回收会成为游戏性能的一大障碍点。
### GC的定义
GC如其名,就是垃圾收集,当然这里仅就内存而言。Garbage Collector(垃圾收集器,在不至于混淆的情况下也成为GC)以应用程序的root为基础,遍历应用程序在Heap上动态分配的所有对象[2],通过识别它们是否被引用来确定哪些对象是已经死亡的、哪些仍需要被使用。已经不再被应用程序的root或者别的对象所引用的对象就是已经死亡的对象,即所谓的垃圾,需要被回收。这就是GC工作的原理。为了实现这个原理,GC有多种算法。比较常见的算法有Reference Counting,Mark Sweep,Copy Collection等等。目前主流的虚拟系统.NET CLR,Java VM和Rotor都是采用的**Mark Sweep算法**。
### Unity内存管理机制简介
Unity主要采用自动内存管理的机制,开发时在代码中不需要详细地告诉unity如何进行内存管理,unity内部自身会进行内存管理。这和使用C++开发需要随时管理内存相比,有一定的优势,当然带来的劣势就是需要随时关注内存的增长。
Unity的自动内存管理可以理解为以下几个部分:
1.Unity内部有两个内存管理池:堆内存和堆栈内存。堆栈内存(stack)主要用来存储较小的和短暂的数据,堆内存(heap)主要用来存储较大的和存储时间较长的数据。
2.Unity中的变量只会在堆栈或者堆内存上进行内存分配,值类型变量都在堆栈上进行内存分配,其他类型的变量都在堆内存上分配。
3.只要变量处于激活状态,则其占用的内存会被标记为使用状态,则该部分的内存处于被分配的状态。
4.一旦变量不再激活,则其所占用的内存不再需要,该部分内存可以被回收到内存池中被再次使用,这样的操作就是内存回收。处于堆栈上的内存回收及其快速,处于堆上的内存并不是及时回收的,此时其对应的内存依然会被标记为使用状态。
5.垃圾回收主要是指堆上的内存分配和回收,Unity中会定时对堆内存进行GC操作。
**一、Mark-Compact 标记压缩算法**
简单地把.NET的GC算法看作Mark-Compact算法。阶段1: Mark-Sweep 标记清除阶段,先假设heap中所有对象都可以回收,然后找出不能回收的对象,给这些对象打上标记,最后heap中没有打标记的对象都是可以被回收的;阶段2: Compact 压缩阶段,对象回收之后heap内存空间变得不连续,在heap中移动这些对象,使他们重新从heap基地址开始连续排列,类似于磁盘空间的碎片整理。

Heap内存经过回收、压缩之后,可以继续采用前面的heap内存分配方法,即仅用一个指针记录heap分配的起始地址就可以。主要处理步骤:将线程挂起→确定roots→创建reachable objects graph→对象回收→heap压缩→指针修复。可以这样理解roots:heap中对象的引用关系错综复杂(交叉引用、循环引用),形成复杂的graph,roots是CLR在heap之外可以找到的各种入口点。
GC搜索roots的地方包括全局对象、静态变量、局部对象、函数调用参数、当前CPU寄存器中的对象指针(还有finalization queue)等。主要可以归为2种类型:已经初始化了的静态变量、线程仍在使用的对象(stack+CPU register) 。 Reachable objects:指根据对象引用关系,从roots出发可以到达的对象。例如当前执行函数的局部变量对象A是一个root object,他的成员变量引用了对象B,则B是一个reachable object。从roots出发可以创建reachable objects graph,剩余对象即为unreachable,可以被回收 。

指针修复是因为compact过程移动了heap对象,对象地址发生变化,需要修复所有引用指针,包括stack、CPU register中的指针以及heap中其他对象的引用指针。Debug和release执行模式之间稍有区别,release模式下后续代码没有引用的对象是unreachable的,而debug模式下需要等到当前函数执行完毕,这些对象才会成为unreachable,目的是为了调试时跟踪局部对象的内容。传给了COM+的托管对象也会成为root,并且具有一个引用计数器以兼容COM+的内存管理机制,引用计数器为0时,这些对象才可能成为被回收对象。Pinned objects指分配之后不能移动位置的对象,例如传递给非托管代码的对象(或者使用了fixed关键字),GC在指针修复时无法修改非托管代码中的引用指针,因此将这些对象移动将发生异常。pinned objects会导致heap出现碎片,但大部分情况来说传给非托管代码的对象应当在GC时能够被回收掉。
**二、 Generational 分代算法**
程序可能使用几百M、几G的内存,对这样的内存区域进行GC操作成本很高,分代算法具备一定统计学基础,对GC的性能改善效果比较明显。将对象按照生命周期分成新的、老的,根据统计分布规律所反映的结果,可以对新、老区域采用不同的回收策略和算法,加强对新区域的回收处理力度,争取在较短时间间隔、较小的内存区域内,以较低成本将执行路径上大量新近抛弃不再使用的局部对象及时回收掉。分代算法的假设前提条件:
1、大量新创建的对象生命周期都比较短,而较老的对象生命周期会更长;
2、对部分内存进行回收比基于全部内存的回收操作要快;
3、新创建的对象之间关联程度通常较强。heap分配的对象是连续的,关联度较强有利于提高CPU cache的命中率,.NET将heap分成3个代龄区域: Gen 0、Gen 1、Gen 2;

Heap分为3个代龄区域,相应的GC有3种方式: # Gen 0 collections, # Gen 1 collections, #Gen 2 collections。如果Gen 0 heap内存达到阀值,则触发0代GC,0代GC后Gen 0中幸存的对象进入Gen1。如果Gen 1的内存达到阀值,则进行1代GC,1代GC将Gen 0 heap和Gen 1 heap一起进行回收,幸存的对象进入Gen2。
2代GC将Gen 0 heap、Gen 1 heap和Gen 2 heap一起回收,Gen 0和Gen 1比较小,这两个代龄加起来总是保持在16M左右;Gen2的大小由应用程序确定,可能达到几G,因此0代和1代GC的成本非常低,2代GC称为full GC,通常成本很高。粗略的计算0代和1代GC应当能在几毫秒到几十毫秒之间完成,Gen 2 heap比较大时,full GC可能需要花费几秒时间。大致上来讲.NET应用运行期间,2代、1代和0代GC的频率应当大致为1:10:100。
**三、Finalization Queue和Freachable Queue**
这两个队列和.NET对象所提供的Finalize方法有关。这两个队列并不用于存储真正的对象,而是存储一组指向对象的指针。当程序中使用了new操作符在Managed Heap上分配空间时,GC会对其进行分析,如果该对象含有Finalize方法则在Finalization Queue中添加一个指向该对象的指针。
在GC被启动以后,经过Mark阶段分辨出哪些是垃圾。再在垃圾中搜索,如果发现垃圾中有被Finalization Queue中的指针所指向的对象,则将这个对象从垃圾中分离出来,并将指向它的指针移动到Freachable Queue中。这个过程被称为是对象的复生(Resurrection),本来死去的对象就这样被救活了。为什么要救活它呢?因为这个对象的Finalize方法还没有被执行,所以不能让它死去。Freachable Queue平时不做什么事,但是一旦里面被添加了指针之后,它就会去触发所指对象的Finalize方法执行,之后将这个指针从队列中剔除,这是对象就可以安静的死去了。
.NET Framework的System.GC类提供了控制Finalize的两个方法,ReRegisterForFinalize和SuppressFinalize。前者是请求系统完成对象的Finalize方法,后者是请求系统不要完成对象的Finalize方法。ReRegisterForFinalize方法其实就是将指向对象的指针重新添加到Finalization Queue中。这就出现了一个很有趣的现象,因为在Finalization Queue中的对象可以复生,如果在对象的Finalize方法中调用ReRegisterForFinalize方法,这样就形成了一个在堆上永远不会死去的对象,像凤凰涅槃一样每次死的时候都可以复生。
**托管资源:**
.NET中的所有类型都是(直接或间接)从System.Object类型派生的。
CTS中的类型被分成两大类——引用类型(reference type,又叫托管类型[managed type]),分配在内存堆上;值类型(value type),分配在堆栈上。如图:

值类型在栈里,先进后出,值类型变量的生命有先后顺序,这个确保了值类型变量在退出作用域以前会释放资源。比引用类型更简单和高效。堆栈是从高地址往低地址分配内存。
引用类型分配在托管堆(Managed Heap)上,声明一个变量在栈上保存,当使用new创建对象时,会把对象的地址存储在这个变量里。托管堆相反,从低地址往高地址分配内存,如图:

.NET中超过80%的资源都是托管资源。
**非托管资源:**
ApplicationContext, Brush, Component, ComponentDesigner, Container, Context, Cursor, FileStream, Font, Icon, Image, Matrix, Object, OdbcDataReader, OleDBDataReader, Pen, Regex, Socket, StreamWriter, Timer, Tooltip, 文件句柄, GDI资源, 数据库连接等等资源。可能在使用的时候很多都没有注意到!
**.NET的GC机制有这样两个问题:**
首先,GC并不是能释放所有的资源。它不能自动释放非托管资源。
第二,GC并不是实时性的,这将会造成系统性能上的瓶颈和不确定性。
GC并不是实时性的,这会造成系统性能上的瓶颈和不确定性。所以有了IDisposable接口,IDisposable接口定义了Dispose方法,这个方法用来供程序员显式调用以释放非托管资源。使用using语句可以简化资源管理。
示例:
```csharp
///summary
/// 执行SQL语句,返回影响的记录数
////summary
///param name="SQLString"SQL语句/param
///returns影响的记录数/returns
publicstaticint ExecuteSql(string SQLString)
{
using (SqlConnection connection =new SqlConnection(connectionString))
{
using (SqlCommand cmd =new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
}
```
当你用Dispose方法释放未托管对象的时候,应该调用GC.SuppressFinalize。如果对象正在终结队列(finalization queue), GC.SuppressFinalize会阻止GC调用Finalize方法。因为Finalize方法的调用会牺牲部分性能。如果你的Dispose方法已经对委托管资源作了清理,就没必要让GC再调用对象的Finalize方法(MSDN)。附上MSDN的代码,大家可以参考。
```csharp
publicclass BaseResource : IDisposable
{
// 指向外部非托管资源
private IntPtr handle;
// 此类使用的其它托管资源.
private Component Components;
// 跟踪是否调用.Dispose方法,标识位,控制垃圾收集器的行为
privatebool disposed =false;
// 构造函数
public BaseResource()
{
// Insert appropriate constructor code here.
}
// 实现接口IDisposable.
// 不能声明为虚方法virtual.
// 子类不能重写这个方法.
publicvoid Dispose()
{
Dispose(true);
// 离开终结队列Finalization queue
// 设置对象的阻止终结器代码
//
GC.SuppressFinalize(this);
}
// Dispose(bool disposing) 执行分两种不同的情况.
// 如果disposing 等于 true, 方法已经被调用
// 或者间接被用户代码调用. 托管和非托管的代码都能被释放
// 如果disposing 等于false, 方法已经被终结器 finalizer 从内部调用过,
//你就不能在引用其他对象,只有非托管资源可以被释放。
protectedvirtualvoid Dispose(bool disposing)
{
// 检查Dispose 是否被调用过.
if (!this.disposed)
{
// 如果等于true, 释放所有托管和非托管资源
if (disposing)
{
// 释放托管资源.
Components.Dispose();
}
// 释放非托管资源,如果disposing为 false,
// 只会执行下面的代码.
CloseHandle(handle);
handle = IntPtr.Zero;
// 注意这里是非线程安全的.
// 在托管资源释放以后可以启动其它线程销毁对象,
// 但是在disposed标记设置为true前
// 如果线程安全是必须的,客户端必须实现。
}
disposed =true;
}
// 使用interop 调用方法
// 清除非托管资源.
[System.Runtime.InteropServices.DllImport("Kernel32")]
privateexternstatic Boolean CloseHandle(IntPtr handle);
// 使用C# 析构函数来实现终结器代码
// 这个只在Dispose方法没被调用的前提下,才能调用执行。
// 如果你给基类终结的机会.
// 不要给子类提供析构函数.
~BaseResource()
{
// 不要重复创建清理的代码.
// 基于可靠性和可维护性考虑,调用Dispose(false) 是最佳的方式
Dispose(false);
}
// 允许你多次调用Dispose方法,
// 但是会抛出异常如果对象已经释放。
// 不论你什么时间处理对象都会核查对象的是否释放,
// check to see if it has been disposed.
publicvoid DoSomething()
{
if (this.disposed)
{
thrownew ObjectDisposedException();
}
}
// 不要设置方法为virtual.
// 继承类不允许重写这个方法
publicvoid Close()
{
// 无参数调用Dispose参数.
Dispose();
}
publicstaticvoid Main()
{
// Insert code here to create
// and use a BaseResource object.
}
}
```
**GC.Collect() 方法**
作用:强制进行垃圾回收。
GC的方法:

**GC注意事项:**
1、只管理内存,非托管资源,如文件句柄,GDI资源,数据库连接等还需要用户去管理。
2、循环引用,网状结构等的实现会变得简单。GC的标志-压缩算法能有效的检测这些关系,并将不再被引用的网状结构整体删除。
3、GC通过从程序的根对象开始遍历来检测一个对象是否可被其他对象访问,而不是用类似于COM中的引用计数方法。
4、GC在一个独立的线程中运行来删除不再被引用的内存。
5、GC每次运行时会压缩托管堆。
6、你必须对非托管资源的释放负责。可以通过在类型中定义Finalizer来保证资源得到释放。
7、对象的Finalizer被执行的时间是在对象不再被引用后的某个不确定的时间。注意并非和C++中一样在对象超出声明周期时立即执行析构函数
8、Finalizer的使用有性能上的代价。需要Finalization的对象不会立即被清除,而需要先执行Finalizer.Finalizer,不是在GC执行的线程被调用。GC把每一个需要执行Finalizer的对象放到一个队列中去,然后启动另一个线程来执行所有这些Finalizer,而GC线程继续去删除其他待回收的对象。在下一个GC周期,这些执行完Finalizer的对象的内存才会被回收。
9、.NET GC使用"代"(generations)的概念来优化性能。代帮助GC更迅速的识别那些最可能成为垃圾的对象。在上次执行完垃圾回收后新创建的对象为第0代对象。经历了一次GC周期的对象为第1代对象。经历了两次或更多的GC周期的对象为第2代对象。代的作用是为了区分局部变量和需要在应用程序生存周期中一直存活的对象。大部分第0代对象是局部变量。成员变量和全局变量很快变成第1代对象并最终成为第2代对象。
10、GC对不同代的对象执行不同的检查策略以优化性能。每个GC周期都会检查第0代对象。大约1/10的GC周期检查第0代和第1代对象。大约1/100的GC周期检查所有的对象。重新思考Finalization的代价:需要Finalization的对象可能比不需要Finalization在内存中停留额外9个GC周期。如果此时它还没有被Finalize,就变成第2代对象,从而在内存中停留更长时间。<file_sep>---
layout: post
title: "Map类的实现"
subtitle: " \"面试小记\""
date: 2020-11-15 09:44:09
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- 数据结构
---
> “面试知识点整理”
# Map
hashmap的底层数据结构散列表,即:数组+链表,创建的时候初始化一个数组,每个节点可以为一个链表
# 一,前言
### 1.1,概述
现实生活中,我们常会看到这样的一种集合:IP地址与主机名,身份证号与个人,系统用户名与系统用户对象等,这种一一对应的关系,就叫做映射(K-V)。Java提供了专门的集合类用来存放这种对象关系的对象,即`java.util.Map`接口。
- `Collection`中的集合,元素是孤立存在的(理解为单身),向集合中存储元素采用一个个元素的方式存储。
- `Map`中的集合,元素是成对存在的(理解为夫妻)。每个元素由键与值两部分组成,通过键(K)可以找对所对应的值(V)。
- `Collection`中的集合称为单列集合,`Map`中的集合称为双列集合。
- 需要注意的是,`Map`中的集合不能包含重复的键,值可以重复;每个键只能对应一个值。

通过查看Map接口描述,看到Map有多个子类,这里我们主要讲解常用的HashMap集合、LinkedHashMap集合。
- **HashMap<K,V>**:存储数据采用的哈希表结构,元素的存取顺序不能保证一致。由于要保证键的唯一、不重复,需要重写键的hashCode()方法、equals()方法。
- **LinkedHashMap<K,V>**:HashMap下有个子类LinkedHashMap,存储数据采用的哈希表结构+链表结构。通过链表结构可以保证元素的存取顺序一致;通过哈希表结构可以保证的键的唯一、不重复,需要重写键的hashCode()方法、equals()方法。
> tips:Map接口中的集合都有两个泛型变量<K,V>,在使用时,要为两个泛型变量赋予数据类型。两个泛型变量<K,V>的数据类型可以相同,也可以不同。
### 1.2,常用方法
Map接口中定义了很多方法,常用的如下:
- `public V put(K key, V value)`: 把指定的键与指定的值添加到Map集合中。
- `public V remove(Object key)`: 把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值。
- `public V get(Object key)` 根据指定的键,在Map集合中获取对应的值。
- `boolean containsKey(Object key)` 判断集合中是否包含指定的键。
- `public Set<K> keySet()`: 获取Map集合中所有的键,存储到Set集合中。
- `public Set<Map.Entry<K,V>> entrySet()`: 获取到Map集合中所有的键值对对象的集合(Set集合)。
> tips:
>
> 1,使用put方法时,若指定的键(key)在集合中没有,则没有这个键对应的值,返回null,并把指定的键值添加到集合中;
>
> 2,若指定的键(key)在集合中存在,则返回值为集合中键对应的值(该值为替换前的值),并把指定键所对应的值,替换成指定的新值。
# 二,哈希表
Map的底层都是通过哈希表进行实现的,那先来看看什么是哈希表。
**JDK1.8**之前,哈希表底层采用**数组+链表**实现,即使用链表处理冲突,同一hash值的链表都存储在一个链表里。但是当位于一个桶中的元素较多,即hash值相等的元素较多时,通过key值依次查找的效率较低。
**JDK1.8中**,哈希表存储采用**数组+链表+红黑树**实现,当链表长度超过阈值(8)时,将链表转换为**红黑树**,这样大大减少了查找时间。如下图(画的不好看,只是表达一个意思。):

说明:
1,进行键值对存储时,先通过hashCode()计算出键(K)的哈希值,然后再数组中查询,如果没有则保存。
2,但是如果找到相同的哈希值,那么接着调用equals方法判断它们的值是否相同。只有满足以上两种条件才能认定为相同的数据,因此对于Java中的包装类里面都重写了hashCode()和equals()方法。
**JDK1.8**引入红黑树大程度优化了HashMap的性能,根据对象的hashCode和equals方法来决定的。如果我们往集合中存放自定义的对象,那么保证其唯一,就必须复写hashCode和equals方法建立属于当前对象的比较方式。
下面说说关于hashCode()和equals()方法。
### 2.1,hashCode()和equals()
关于hashCode()我们先来看看API文档的解释。

再来看equals()的API解释:

总结:通过直接观看API文档中的解释,在结合哈希表的特点。我们得知为什么要使用hashCode()方法和equals()方法来作为元素是否相同的判断依据。
1,使用hashCode()方法可以提高查询效率,假如现在有10个位置,存储某个元素如果说没有哈希值的使用,要查找该元素就要全部遍历,在效率上是缓慢的。而通过哈希值就可以很快定位到该元素的位置,节省了遍历数组的时间。
2,但是通过哈希值就能确定唯一的值吗,当然不是。因此才需要使用equals再次进行判断。判断的目的在于当元素哈希值相等时,使用equals判断它们到底是不是同一个对象,如果是则代表是同一个元素,否则不是同一个元素那么就将其保存到链表上。
因此哈希值的使用就是为提高查询速度,equals的使用就是判断对象是否为重复元素。
### 2.2,Map遍历方式
在文章上面讲述到,map保存的是键值对形式,也就是说K和V的类型有可能是不一样的,也有可能是自定义的对象。因此不能像使用普通for循环遍历集合去遍历map集合。别急,在Map中已经为我们提供的两种方式,keySet()和entrySet()。
1,keySet()方式

通过该方法可以获取map中的全部key,返回的是一个set集合。那么获取到map中的key难道还拿不到对应的value吗。请看如下代码:

```
Map<String,Object> map = new HashMap<>();
map.put("Hello","World");
map.put("你好","世界");
// 1,通过ketSet方式获取map集合中的key
Set<String> keySet = map.keySet();
// 通过迭代器方式获取key,先获取一个迭代器
Iterator<String> setIterator = keySet.iterator();
while(setIterator.hasNext()){
// 获取key
String keyMap = setIterator.next();
Object obj = map.get(keyMap);
System.out.println("map--->"+obj);
}
// 2,使用增强for遍历set集合
for(String key : keySet){
System.out.println(map.get(key));
}
// 简化for循环
for(String key : map.keySet()){
System.out.println(map.get(key));
}
```

2,entrySet()

我们已经知道,`Map`中存放的是两种对象,一种称为**key**(键),一种称为**value**(值),它们在在`Map`中是一一对应关系,这一对对象又称做`Map`中的一个`Entry(项)`。`Entry`将键值对的对应关系封装成了对象。即键值对对象,这样我们在遍历`Map`集合时,就可以从每一个键值对(`Entry`)对象中获取对应的键与对应的值。
既然Entry表示了一对键和值,那么也同样提供了获取对应键和对应值得方法:
- `public K getKey()`:获取Entry对象中的键。
- `public V getValue()`:获取Entry对象中的值。
在Map集合中也提供了获取所有Entry对象的方法:
- `public Set<Map.Entry<K,V>> entrySet()`: 获取到Map集合中所有的键值对对象的集合(Set集合)。

```
// 使用Entry键值对
Set<Map.Entry<String, Object>> entrySet = map.entrySet();
// 1,使用迭代器
Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
while(iterator.hasNext()){
Map.Entry<String, Object> entry = iterator.next();
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
System.out.println("=============================");
// 2,使用for循环遍历
for(Map.Entry<String,Object> entry : map.entrySet()){
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
```

# 三,Hash Map实现原理
### 3.1,常量的使用

```
//创建 HashMap 时未指定初始容量情况下的默认容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//HashMap 的最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//HashMap 默认的装载因子,当 HashMap 中元素数量超过 容量装载因子时,进行resize()操作,至为什么是0.75,官方说法是这个值是最佳的阈值。
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//用来定义在哈希冲突的情况下,转变为红黑树的阈值
static final int TREEIFY_THRESHOLD = 8;
// 用来确定何时将解决 hash 冲突的红黑树转变为链表
static final int UNTREEIFY_THRESHOLD = 6;
/* 当需要将解决 hash 冲突的链表转变为红黑树时,需要判断下此时数组容量,若是由于数组容量太小(小于 MIN_TREEIFY_CAPACITY )导致的 hash 冲突太多,则不进行链表转变为红黑树操作,转为利用 resize() 函数对 hashMap 扩容 */
17 static final int MIN_TREEIFY_CAPACITY = 64;
```

### 3.2,node节点类

```
// Node是单向链表,它实现了Map.Entry接口并且实现数组及链表的数据结构
static class Node<k,v> implements Map.Entry<k,v> {
final int hash; // 保存元素的哈希值
final K key; // 保存节点的key
V value; // 保存节点的value
Node<k,v> next; // 链表中,指向下一个链表的节点
//构造函数Hash值 键 值 下一个节点
Node(int hash, K key, V value, Node<k,v> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + = + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
//重写equals方法,与我们上文中讲述的原理
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<!--?,?--> e = (Map.Entry<!--?,?-->)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
```

### 3.3,红黑树源码

```
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // 定义红黑树父节点
TreeNode<K,V> left; // 左子树
TreeNode<K,V> right; // 右子树
TreeNode<K,V> prev; // 上一个节点,后期会根据上一个节点作相应判断
boolean red; // 判断颜色的属性
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
/**
* 返回根节点
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
```

### 3.4,构造函数
第一种构造函数,指定初始化容量大小及装载因子。

```
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
```

第二种构造函数,仅指定装载因子。
```
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
```
第三种构造函数,所有的参数都使用默认值。
```
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
```
### 3.5,put方法

```
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab;
Node<K,V> p;
int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 1,如果table的在(n-1)&hash的值是空,就新建一个节点插入在该位置
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 2,否则表示有冲突,开始处理冲突
else {
Node<K,V> e;
K k;
// 3,接着检查第一个Node,p是不是要找的值
if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
// 4,如果指针为空就挂在后面
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 5,如果有相同的key值就结束遍历
if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 6,就是链表上有相同的key值
if (e != null) { // existing mapping for key,就是key的Value存在
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;//返回存在的Value值
}
}
++modCount;
// 7,如果当前大小大于定义的阈值,0.75f
if (++size > threshold)
resize();//扩容两倍
afterNodeInsertion(evict);
return null;
}
```

### 3.6,get方法

```
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
// 1,通过哈希值和key查找元素
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab;//Entry对象数组
Node<K,V> first,e;
int n;
K k;
// 2,找到插入的第一个Node,方法是hash值和n-1相与,tab[(n - 1) & hash]
// 表示在一条链上的hash值相同的
if ((tab = table) != null && (n = tab.length) > 0 &&(first = tab[(n - 1) & hash]) != null) {
// 3,检查第一个Node是不是要找的Node
if (first.hash == hash && // always check first node
// 4,判断条件是hash值要相同,key值要相同
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 5,检查下一个元素
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 6,遍历后面的链表,找到key值和hash值都相同的Node节点
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
```

### 3.7,扩容机制
hashmap扩容是一件相对很耗时的事情,在初始化hash表结构时,如果没有指定大小则默认为16,也就是node数组的大小。当容量达到最大值时,扩容到原来的2倍。

```
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// 1,判断旧表的长度不是空,且大于最大容量
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 2,把新表的长度设置为旧表长度的两倍,newCap=2*oldCap
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// 3,把新表的阈值设置为旧表阈值的两倍,newThr=oldThr*2
newThr = oldThr << 1; // double threshold
}
// 初始容量设置新的阈值
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;//新表长度乘以加载因子
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
// 4,创建新的表,并初始化原始数据
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;//把新表赋值给table
// 原表不是空要把原表中数据移动到新表中
if (oldTab != null) {
// 开始遍历原来的旧表
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)//说明这个node没有链表直接放在新表的e.hash & (newCap - 1)位置
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order保证顺序
//新计算在新表的位置,并进行搬运
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;//记录下一个结点
//新表是旧表的两倍容量,实例上就把单链表拆分为两队,
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {//lo队不为null,放在新表原位置
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {//hi队不为null,放在新表j+oldCap位置
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
```

map集合的扩容要比list集合复杂的多。
# 四,Linked Hash Map
对于LinkedHashMap而言,它继承与HashMap、底层使用**哈希表与双向链表**来保存所有元素。其基本操作与父类HashMap相似,它通过重写父类相关的方法,来实现自己的链接列表特性,同时它也保证元素是有序的。
# 五,Hash Table
Hashtable的实现原理和Hash Map是类似的,但区别是它是线程安全的,也正因为如此导致查询速度较慢。

**注意:Hash Table中K和V是不允许存储null值。**
# 六,Hash Set
Hash Set底层就是通过Hash Map实现的。

从源码看出这简直是赤裸裸的new了一个Hash Map,虽然原理类似但多少有区别,毕竟这是两个体系的集合。
最根本区别在于set集合存储单值对象。而map是键值对,但有一个相同点是都不能存储重复元素。
**注意:Hash Set也是线程不安全的。**<file_sep>---
layout: post
title: "Python序列化和反序列化"
subtitle: "初学Python"
date: 2018-04-16 12:14:00
author: "Nankenan"
header-img: "img/watchdog2_sf.jpg"
tags:
- Python
---
> Reposted from [nankenan](https://nankenan.github.io)
# Python序列化和反序列化
转载于https://www.cnblogs.com/sun-haiyu/p/7087088.html
通过将对象序列化可以将其存储在变量或者文件中,可以保存当时对象的状态,实现其生命周期的延长。并且需要时可以再次将这个对象读取出来。Python中有几个常用模块可实现这一功能。
## pickle模块
### 存储在变量中
`dumps(obj)`返回存入的**字节**
```
dic = {'age': 23, 'job': 'student'}
byte_data = pickle.dumps(dic)
# out -> b'\x80\x03}q\x00(X\x03\x00\x00\...'
print(byte_data)
```
### 读取数据
数据以字节保存在了`byte_data`变量中,需要再次使用的时候使用`loads`函数就行了。
```
obj = pickle.loads(byte_data)
print(obj)
```
### 存储在文件中
也可以存在文件中,使得对象持久化。使用的是`dump`和`load`函数,注意和上面的区别,少了`s`。由于**pickle写入的是二进制数据**,所以打开方式需要以`wb`和`rb`的模式。
```
# 序列化
with open('abc.pkl', 'wb') as f:
dic = {'age': 23, 'job': 'student'}
pickle.dump(dic, f)
# 反序列化
with open('abc.pkl', 'rb') as f:
aa = pickle.load(f)
print(aa)
print(type(aa)) # <class 'dict'>
```
## 序列化用户自定义对象
假如我写了个类叫做Person
```
class Person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job
def work(self):
print(self.name, 'is working...')
```
pickle当然也能写入,**不仅可以写入类本身,也能写入它的一个实例**。
```
# 将实例存储在变量中,当然也能存在文件中
a_person = Person('abc', 22, 'waiter')
person_abc = pickle.dumps(a_person)
p = pickle.loads(person_abc)
p.work()
# 将类本身存储在变量中,loads的时候返回类本身,而非它的一个实例
class_Person = pickle.dumps(Person)
Person = pickle.loads(class_Person)
p = Person('Bob', 23, 'Student')
p.work()
# 下面这个例子演示的就是将类存储在文件中
# 序列化
with open('person.pkl', 'wb') as f:
pickle.dump(Person, f)
# 反序列化
with open('person.pkl', 'rb') as f:
Person = pickle.load(f)
aa = Person('gg', 23, '6')
aa.work()
```
## json模块
pickle可以很方便地序列化所有对象。不过json作为更为标准的格式,具有更好的可读性(pickle是二进制数据)和跨平台性。是个不错的选择。
json使用的四个函数名和pickle一致。
### 序列化为字符串
```
dic = {'age': 23, 'job': 'student'}
dic_str = json.dumps(dic)
print(type(dic_str), dic_str)
# out: <class 'str'> {"age": 23, "job": "student"}
dic_obj = json.loads(dic_str)
print(type(dic_obj), dic_obj)
# out: <class 'dict'> {'age': 23, 'job': 'student'}
```
可以看到,`dumps`函数将对象转换成了字符串。`loads`函数又将其恢复成字典。
### 存储为json文件
也可以存储在json文件中
```
dic = {'age': 23, 'job': 'student'}
with open('abc.json', 'w', encoding='utf-8') as f:
json.dump(dic, f)
with open('abc.json', encoding='utf-8') as f:
obj = json.load(f)
print(obj)
```
### 存储自定义对象
还是上面的Person对象。如果直接序列化会报错
```
aa = Person('Bob', 23, 'Student')
with open('abc.json', 'w', encoding='utf-8') as f:
json.dump(aa, f) # 报错
```
`Object of type 'Person' is not JSON serializable`此时`dump`函数里传一个参`default`就可以了,这个参数接受一个函数,这个函数可以将对象转换为字典。
写一个就是了
```
def person2dict(person):
return {'name': person.name,
'age': person.age,
'job': person.job}
```
这样返回的就是一个字典了,对象实例有个方法可以简化这一过程。直接调用实例的`__dict__`。例如
```
print(aa.__dict) # {'name': 'Bob', 'age': 23, 'job': 'Student'}
```
很方便。
同时在读取的时候load出来的是一个字典,再转回对象就可,同样需要一个`object_hook`参数,该参数接收一个函数,用于将字典转为对象。
```
def dict2person(dic):
return Person(dic['name'], dic['age'], dic['job'])
```
于是完整的程序应该写成下面这样
```
with open('abc.json', 'w', encoding='utf-8') as f:
json.dump(aa, f, default=person2dict)
with open('abc.json', encoding='utf-8') as f:
obj = json.load(f, object_hook=dict2person)
print(obj.name, obj.age, obj.job)
obj.work()
```
由于可以使用`__dict__`代替`person2dict`函数,再使用lambda函数简化。
```
with open('abc.json', 'w', encoding='utf-8') as f:
json.dump(aa, f, default=lambda obj: obj.__dict__)
```
以上是存储到文件,存储到变量也是类似操作。
不过就我现在所学,不知道如何像pickle一样方便的将我们自定义的**类本身**使用json序列化,或许要用到其他扩展函数。以后用到了再说。<file_sep>---
layout: post
title: "C#引用类型与值类型的区别"
subtitle: " \"面试小记\""
date: 2020-11-15 09:44:09
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- C#
---
> “面试知识点整理”
# struct和class的区别
**class和struct最本质的区别是class是引用类型,而struct是值类型,它们在内存中的分配情况有所区别。**
什么是class?
class(类)是面向对象编程的基本概念,是一种自定义数据结构类型,通常包含字段、属性、方法、属性、构造函数、索引器、操作符等。在.NET中,所有的类都最终继承自System.Object类,因此是一种引用类型,也就是说,new一个类的实例时,在堆栈(stack)上存放该实例在**托管堆(managed heap)中的地址**,而实例的值保存在**托管堆(managed heap)**中。
什么是struct?
struct(结构)是一种值类型,用于将一组相关的变量组织为一个单一的变量实体 。所有的结构都继承自System.ValueType类,因此是一种值类型,也就是说,struct实例在创建时分配在线程的**堆栈(stack)**上,它本身存储了值。所以在使用struct时,我们可以将其当作int、char这样的基本类型类对待。
# 值类型和引用类型区别
什么是值类型:
- 进一步研究文档,你会发现所有的结构都是抽象类型System.ValueType的直接派生类,而System.ValueType本身又是直接从System.Object派生的。根据定义所知,所有的值类型都必须从System.ValueType派生,所有的枚举都从System.Enum抽象类派生,而后者又从System.ValueType派生。
- 所有的值类型都是隐式密封的(sealed),目的是防止其他任何类型从值类型进行派生。
什么是引用类型:
- 在c#中所有的类都是引用类型,包括接口。
区别和性能
- 区别:
- 值类型通常被人们称为轻量级的类型,因为在大多数情况下,值类型的的实例都分配在线程栈中,因此它不受垃圾回收的控制,缓解了托管堆中的压力,减少了应用程序的垃圾回收的次数,提高性能。
- 所有的引用类型的实例都分配在托管堆上,c#中new操作符会返回一个内存地址指向当前的对象。所以当你在创建个一个引用类型实例的时候,你必须要考虑以下问题:
- 内存是在托管堆上分配的
- 在分配每一个对象时都会包含一些额外的成员(类型对象指针,同步块索引),这些成员必须初始化
- 对象中的其他字节总是设为零
- 在分配对象时,可能会进行一次垃圾回收操作(如果托管堆上的内存不够分配一次对象时)
- 性能:
- 在设计一个应用程序时,如果都是应用类型,那么应用程序的性能将显著下降,因为这会加大托管堆的压力,增加垃圾回收的次数。
- 虽然值类型是一个轻量级的类型,但是如果大量的使用值类型的话,也会有损应用程序的性能(例如下面要讲的装箱和拆箱操作,传递实例较大的值类型,或者返回较大的值类型实例)。
- 由于值类型实例的值是自己本身,而引用类型的实例的值是一个引用,所以如果将一个值类型的变量赋值给另一个值类型的变量,会执行一次逐字段的复制,将引用类型的变量赋值给另一个引用类型的变量时,只需要复制内存地址,所以在对大对象进行赋值时要避免使用值类型。例如下面的代码
```c#
class SomRef
{
public int x;
}
struct SomeVal
{
public int x;
}
class Program
{
static void ValueTypeDemo()
{
SomRef r1 = new SomRef();//在堆上分配
SomeVal v1 = new SomeVal();//在栈上分配
r1.x = 5;//提领指针
v1.x = 5;//在栈上修改
SomRef r2 = r1;//只复制引用(指针)
SomeVal v2 = v1;//在栈上分配并复制成员
}
}
```
值类型传参进函数的修改,在出栈后不保留直接丢弃了;
引用类型传参进函数后,修改会保留,因为在托管堆中;
# C#装箱和拆箱
```c#
int i = 5;
object o = i;
int j = (int)o;
Int16 y=(Int16)o;
```
什么是装箱,什么是拆箱
- 什么是装箱:所谓装箱就是将值类型转化为引用类型的过程(例如上面代码的第2行),在装箱时,你需要知道编译器内部都干了什么事:
- 在托管堆中分配好内存,分配的内存量是值类型的各个字段需要的内存量加上托管堆上所以对象的两个额外成员(类型对象指针,同步块索引)需要的内存量
- 值类型的字段复制到新分配的堆内存中
- 返回对象的地址,这个地址就是这个对象的引用
- 什么是装箱:将已装箱的值类型实例(此时它已经是引用类型了)转化成值类型的过程(例如上面代码的第3行),注意:拆箱不是直接将装箱过程倒过来,拆箱的代价比装箱要低的多,拆箱其实就是获取一个指针的过程。一个已装箱的实例在拆箱时,编译器在内部都干了下面这些事:
- 如果包含了“对已装箱类型的实例引用”的变量为null时,会抛出一个NullReferenceException异常。
- 如果引用指向的对象不是所期待的值类型的一个已装箱实例,会抛出一个InvalidCastException异常(例如上面代码的第4行)。
1. 它们在什么情况下发生,以及如何避免
```c#
static void Main(string[] args)
{
int v = 5;
object o = v;
v = 123;
Console.WriteLine(v+","+(int)o);
}
```
通过上面的分析我们已经知道了,装箱和拆箱/复制操作会对应用程序的速度和内存消耗产生不利的影响(例如消耗内存,增加垃圾回收次数,复制操作),所以我们应该注意编译器在什么时候会生成代码来自动这些操作,并尝试手写这些代码,尽量避免自动生成代码的情况。
- 你能一眼从上面的代码中看出进行了几次装箱操作吗?正取答案是3次。分别进行了哪三次呢,我们来看一下:第一次object o=v;第二次在执行 Console.WriteLine(v+","+(int)o);时将v进行装箱,然后对o进行拆箱后又装箱。也就是说装箱过程总是在我们不经意的时候进行的,所以只有我们充分了解了装箱的内部机制,才能有效的避免装箱操作,从而提高应用程序的性能。所以对上面的代码进行如下修改可以减少装箱次数,从而提高性能:
```c#
static void Main(string[] args)
{
int v = 5;
object o = v;
v = 123;
Console.WriteLine(v.ToString() + "," + ((int)o).ToString());//((int)o).ToString()代码本身没有任何意义,只为演示装箱和拆箱操作
}
```
- 下面来讨论一下编译器都会在什么时候自动生成代码来完成这些操作
- 使用非泛型集合时:比如ArrayList,因为这些集合需要的对象都是object,如果你将一个值类型的对象添加到集合中时会执行一次装箱操作,当你取值时会执行一次拆箱操作,所以在应用程序中应避免使用这种非泛型的集合。
- 大家都知道System.Object是所有类型的基类,当你调用object类型的非虚方法时会进行装箱操作(例如GetType方法)。在调用object的虚方法时,如果你的值类型没有重写虚方法也要进行装箱操作,所以在定义自己的值类型时,应重写object内部的虚方法(例如ToString方式)
- 将值类型转化为接口类型时也会进行装箱操作,这是因为接口类型必须包含对堆上的一个对象的引用。
#### 三,泛型的出现(本节只简单介绍泛型对装箱和拆箱所起的作用,关于泛型的具体细节请参考下一篇文章)
- - 什么泛型
- 泛型是CLR和编程语言提供的一种特殊机制,它在c#2中才被提供出来。
- 它对避免装箱有什么作用?
- 在使用泛型时需要指定要装配的类型,这样可以减少装箱操作,比如下面的代码
```c#
static void Main(string[] args)
{
ArrayList dateList = new ArrayList {DateTime.Now};
IList<DateTime> dateT = new List<DateTime> {
DateTime.Now
};
}
```
#### 四,在设计时如何选择类和结构体
在面试的时候,我们经常被问的一个问题(还有另外一个问题,如何选择抽象类和接口,下次我会单独聊聊这个问题),下面我们来聊聊在设计时应该如何选择结构体和类
- - 什么是结构体
- 结构体是一种特殊的值类型,所以它拥有值类型所以的特权(实例一般分配在线程栈上)和限制(不能被派生,所以没有 abstract 和 sealed,未装箱的实例不能进行线程同步的访问)。
- 什么情况下选择结构体,什么情况下选择类
- 在大多数的情况下,都应该选择类,除非满足以下情况,才考虑选择结构体:
- 类型具有基元类型的行为
- 类型不需要从其它任何类型继承
- 类型也不会派生出任何其它类型
- 类型的实例较小(约为16字节或者更小)
- 类型的实例较大,但是不作为方法的参数传递,也不作为方法的返回值。<file_sep>**本篇的任务是回答:在Untiy的渲染流程中CPU和GPU分别做了什么。**
渲染到设备屏幕显示的每一帧的画面,都经历几个阶段的加工过程:
- 应用程序阶段(CPU):识别出潜在可视的网格实例,并把他们及其材质提交给GPU以供渲染。
- 几何阶段(GPU):进行顶点变换等计算,并将三角形转换到齐次空间并进行裁剪。
- 光栅化阶段(GPU):把三角形转换为片元,并对片元执行着色。片元经过多种测试(深度测试,alpha测试等)之后,最终与帧缓冲混合。
## CPU的工作流程:
CPU
1. 准备好需要被渲染的对象。也就是哪些物体需要被渲染,哪些物体需要被剔除(culled),剔除的常用方式包括视锥体剔除和遮挡剔除,并对需要渲染的对象进行排序。
2. 设置每个对象的渲染状态。渲染状态包括所使用的着色器、光源、材质等。
3. 发送DrawCall。当给定一个DrawCall时,GPU会根据渲染状态和输入的顶点数据进行计算。
Unity的渲染顺序可以简单的理解为是从近到远(实际上要复杂的多)。根据渲染对象的排序,会为每一个渲染对象的每一个材质,生成一个渲染批次batch。在不考虑动态批处理和静态批处理的情况下,总的batch量就是每个渲染对象所包含的材质的总和。但是因为存在动态/静态批处理的情况,所以实际产生的batch数量要小于前面计算的总和。
在我一贯的测试过程中,SetPass call与渲染状态的切换是最吻合的,所以我将SetPass call简单的理解成设置渲染状态。但是,要说明的是,这只是我的个人想法,并没有其他支持。
SetPass call 和Draw call作为渲染命令队列的组成内容,担负着不同的任务。可以这样理解,SetPass call是告诉GPU接下来要用到哪些资源了,抓紧准备起来,而draw call则是把要求GPU根据顶点数据进行绘制。所以在执行SetPass call时,会向现存中传递大量的资源信息,包括纹理资源也是在这时候加载到缓存中,仅当下一个需要渲染的网格需要变更渲染状态时,才会产生SetPass call。所以,SetPass call和Draw call虽然是相伴产生的,但是两者却不一定对等。在某些情况下,一个batch可能会用到多个pass,比如mesh的反向描边。对于不同的pass,CPU将发送新的SetPass call 和Draw call。而在静态批处理中,因为顶点限制而不能在同一批次处理而被分割的紧邻的多个批次,因为使用的是相同的渲染设置,所以也只会产生一个SetPass call。
通常来说在优化时我们关注的是DrawCall,但也有不同的声音说,SetPass call更有意义。我觉得用哪个做分析从优化角度来说,差别不大。他们传递的都是指令和地址,真正耗时的是执行绘制阶段。并且两者的产生也基本是相伴的。
## GPU的工作流程:

### 顶点着色器:
顶点着色器负责变换及着色/光照顶点。顶点着色器的输入来自于CPU,CPU输入的每个顶点都会执行一次顶点着色器,顶点着色器本身无法创建和销毁顶点,并且无法得到顶点与顶点之间的关系。正因为这样的独立关系,GPU可以利用自身的特性进行并行运算,所以顶点着色器的运算速度非常快。在此阶段也会进行透视投影、顶点光照、纹理计算、蒙皮。也可以通过修改顶点位置生成程序式动画(procedural animation),例如模拟风吹草动,碧波荡漾。
### 几何着色器:
几何着色器因为在手机端不支持,所以Unity开发程序员也许并不熟悉。几何着色器也是完全可编程的。几何着色器处理以齐次裁剪空间表示的整个图元(三角形,线段,点)。它能够剔除和修改输入的图元,也能生成新的图元。典型应用包括阴影的体积拉伸(shadow volume extrusion)、渲染立方体贴图(cube map)的六个面、在网格的轮廓边拉伸毛发(fur fin)、从点数据生成粒子四边形、动态镶嵌、把线段以分形细分(fractal subdivision)模拟闪电效果、布料模拟等。
### 裁剪:
最常用的裁剪设置是CULL OFF/BACK/FRONT,分别是不剔除/背面剔除/正面剔除。这里的正反面与摄像机没有一分钱的关系,而是通过法线方向决定的。
### 屏幕映射:
这里注意一点,虽然屏幕映射是玩家不可配置和编程的,但是屏幕分辨率确实玩家可以设置的,较小的屏幕分辨率对光栅化阶段是有非常重要的优化效果的。
### 三角形遍历:
三角形遍历阶段把三角形分解为片段(光栅化)。通常每个像素会产生一个片元,除非是使用MSAA,那么每个像素就会产生多个片元。**三角形遍历也会对顶点属性进行插值,以生成每个片元的属性,供像素着色器使用。**
### 片元着色器:
片元着色器是完全可编程的。其工作是为每个片元着色。片元着色器也能丢弃一些片元,例如根据透明度做剔除。像素着色器可以对多个纹理进行采样并计算逐像素光照和任何会影响片元颜色的计算。此阶段的输入是一组片元属性,这些属性是在三角形遍历阶段通过对顶点属性插值所得。输出则是一个颜色矢量。
### 逐片元操作:
该阶段也称为合并阶段(merge stage)或混合阶段(blending stage),NVIDIA称之为光栅化运算阶段(raster operations stage,ROP)。此阶段不可编程,但是可以高度配置化。最常用的逐片元操作测试包括深度测试ZTest、Alpha测试、模板测试Stencil test,当片元通过了所有测试以后,其颜色就会与帧缓冲原来的颜色进行混合(Blend),混合的方式是可配置的,如Blend One One。在该阶段另一个重要的配置是深度写入ZWrite。
<file_sep>//864.获取所有钥匙的最短路径
//给定一个二维网格 grid。 "." 代表一个空房间, "#" 代表一堵墙, "@" 是起点,("a", "b", ...)代表钥匙,("A", "B", ...)代表锁。
//我们从起点开始出发,一次移动是指向四个基本方向之一行走一个单位空间。我们不能在网格外面行走,也无法穿过一堵墙。如果途经一个钥匙,我们就把它捡起来。除非我们手里有对应的钥匙,否则无法通过锁。
//假设 K 为钥匙/锁的个数,且满足 1 <= K <= 6,字母表中的前 K 个字母在网格中都有自己对应的一个小写和一个大写字母。换言之,每个锁有唯一对应的钥匙,每个钥匙也有唯一对应的锁。另外,代表钥匙和锁的字母互为大小写并按字母顺序排列。
//返回获取所有钥匙所需要的移动的最少次数。如果无法获取所有钥匙,返回 -1 。
//示例 1:
//输入:["@.a.#","###.#","b.A.B"]
//输出:8
//示例 2:
//输入:["@..aA","..B#.","....b"]
//输出:6
//提示:
//1 <= grid.length <= 30
//1 <= grid[0].length <= 30
//grid[i][j] 只含有 '.', '#', '@', 'a' - 'f' 以及 'A' - 'F'
//钥匙的数目范围是[1, 6],每个钥匙都对应一个不同的字母,正好打开一个对应的锁。
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/shortest-path-to-get-all-keys
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
// 思路
// BFS 不同钥匙获取的状态下,visited 状态不同
using System;
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
private class PathNode
{
public int x;
public int y;
public int key;
public int len;
public PathNode(int _key, int _x, int _y, int _len)
{
key = _key;
x = _x;
y = _y;
len = _len;
}
}
public int ShortestPathAllKeys(string[] grid)
{
int row = grid.Length;
int col = grid[0].Length;
//起点位置
int startX = 0, startY =0;
int[] dirRow = new int[] { -1, 0, 1, 0 };
int[] dirCol = new int[] { 0, 1, 0, -1 };
//获取钥匙集合
HashSet<char> keys = new HashSet<char>();
for (int i = 0; i < grid.Length; ++i)
{
for (int j = 0; j < grid[i].Length; ++j)
{
if (grid[i][j] >= 'a' && grid[i][j] <= 'f')
{
keys.Add(grid[i][j]);
}
if (grid[i][j] == '@')
{
startX = j;
startY = i;
}
}
}
int keycount = keys.Count;
if (keycount == 0) return 0;
int allKeyFlag = 0;
for (int i = 0; i <keycount;++i)
{
allKeyFlag += (int)Math.Pow(2, i);
}
//初始化状态图
bool[][][] vistied = new bool[(int)Math.Pow(2, keycount)][][];
for (int i = 0; i < vistied.Length; ++i)
{
vistied[i] = new bool[row][];
for (int j = 0; j < vistied[i].Length; ++j)
{
vistied[i][j] = new bool[col];
}
}
//
Queue<PathNode> choice = new Queue<PathNode>();
choice.Enqueue(new PathNode(0, startX, startY, 0));
vistied[0][startY][startX] = false;
PathNode node = null;
Console.WriteLine("===============================");
while (choice.Count > 0)
{
node = choice.Dequeue();
int key = node.key;
if (vistied[key][node.y][node.x])
{
continue;
}
vistied[key][node.y][node.x] = true;
Console.WriteLine(string.Format("Key:{0}, Try {1},{2} , len:{3} ", key, node.x, node.y, node.len));
if (key == allKeyFlag)
{
return node.len;
}
for (int i = 0; i < dirRow.Length; ++i)
{
int x = node.x + dirRow[i];
int y = node.y + dirCol[i];
x = Math.Max(0, x);
x = Math.Min(x, col - 1);
y = Math.Max(0, y);
y = Math.Min(y, row - 1);
char c = grid[y][x];
if (vistied[key][y][x])
{
continue;
}
else if (c == '#')
{
continue;
}
else if (c >='A' && c <= 'F')
{
if ((key >> c-'A' & 1) ==1)
{
//vistied[key][x][y] = true;
choice.Enqueue(new PathNode(key, x, y, node.len + 1));
}
}
else if (c >= 'a' && c <= 'f')
{
//vistied[key][x][y] = true;
int tmpkey = (1 << (c - 'a')) | key;
choice.Enqueue(new PathNode(tmpkey, x, y, node.len + 1));
}
else if (c == '.' || c == '@')
{
//vistied[key][x][y] = true;
choice.Enqueue(new PathNode(key, x, y, node.len + 1));
}
else
{
continue;
}
}
}
return 0;
}
}
}<file_sep>// 41. 缺失的第一个正数
// first - missing-positive
//给你一个未排序的整数数组,请你找出其中没有出现的最小的正整数。
//示例 1:
//输入:[1,2,0]
//输出: 3
//示例 2:
//输入:[3,4,-1,1]
//输出: 2
//示例 3:
//输入:[7,8,9,11,12]
//输出: 1
//提示:
//你的算法的时间复杂度应为O(n),并且只能使用常数级别的额外空间。
//原地哈希
namespace ByteDancePopular
{
public partial class Solution
{
public int FirstMissingPositive(int[] nums)
{
int n = nums.Length;
for (int i = 0; i < n; ++i)
{
while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i] && nums[i]-1 >= 0)
{
int tmp = nums[nums[i] - 1];
nums[nums[i] - 1] = nums[i];
nums[i] = tmp;
}
}
for (int i = 0; i < n; ++i)
{
if (nums[i] != i + 1)
{
return i + 1;
}
}
return n + 1;
}
}
}<file_sep>//93. 复原IP地址
//给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
//有效的 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。
//例如:"0.1.2.201" 和 "192.168.1.1" 是 有效的 IP 地址,但是 "0.011.255.245"、"192.168.1.312" 和 "192.168@1.1" 是 无效的 IP 地址。
//示例 1:
//输入:s = "25525511135"
//输出:["255.255.11.135","255.255.111.35"]
//示例 2:
//输入:s = "0000"
//输出:["0.0.0.0"]
//示例 3:
//输入:s = "1111"
//输出:["1.1.1.1"]
//示例 4:
//输入:s = "010010"
//输出:["0.10.0.10","0.100.1.0"]
//示例 5:
//输入:s = "101023"
//输出:["172.16.31.10","172.16.58.3","10.1.0.23","10.10.2.3","172.16.58.3"]
//提示:
//0 <= s.length <= 3000
//s 仅由数字组成
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/restore-ip-addresses
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
using System.Collections.Generic;
using System.Text;
//思路 -> 深搜回溯
//1. 当不满足条件时回溯 -> 1.字段数值 不属于 0~0xff 2.遍历完,不满足字符串和ip字段的长度限制
namespace ByteDancePopular
{
public partial class Solution
{
static int SEG_COUNT = 4;
List<string> ans = new List<string>();
int[] segments = new int[SEG_COUNT];
public IList<string> RestoreIpAddresses(string s)
{
ans = new List<string>();
BackTraceIPAddress(s, 0, 0);
return ans;
}
private void BackTraceIPAddress(string s, int left,int segid)
{
if (segid == SEG_COUNT)
{
if (left == s.Length)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < segments.Length; ++i)
{
sb.Append(segments[i]);
if (i != SEG_COUNT -1)
{
sb.Append(".");
}
}
ans.Add(sb.ToString());
}
return;
}
//ip字段超出4个直接回溯
if (segid >= SEG_COUNT)
{
return;
}
//当回溯完最后一个字符,还不满足4个ip字段的话,则回溯
if (left == s.Length)
{
return;
}
//由于不能有前导0,如果有0,则该字段必然为0,直接下一个字段
if (s[left] == '0')
{
segments[segid] = 0;
BackTraceIPAddress(s, left + 1, segid+1);
}
int addr = 0;
for (int right = left; right< s.Length; ++right)
{
addr = addr * 10 + (s[right] - '0');
if (addr > 0 && addr <= 0xFF)
{
segments[segid] = addr;
BackTraceIPAddress(s, right + 1, segid + 1);
}
else
{
break;
}
}
}
}
}<file_sep>//56. 合并区间
//给出一个区间的集合,请合并所有重叠的区间。
//示例 1:
//输入: intervals = [[1, 3],[2,6],[8,10],[15,18]]
//输出:[[1,6],[8,10],[15,18]]
//解释: 区间[1, 3] 和[2, 6] 重叠, 将它们合并为[1, 6].
//示例 2:
//输入: intervals = [[1, 4],[4,5]]
//输出:[[1,5]]
//解释: 区间[1, 4] 和[4, 5] 可被视为重叠区间。
//注意:输入类型已于2019年4月15日更改。 请重置默认代码定义以获取新方法签名。
//提示:
//intervals[i][0] <= intervals[i][1]
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/merge-intervals
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//思路
// 先排序起点,再合并
using System;
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
public int[][] Merge(int[][] intervals)
{
List<int[]> list = new List<int[]>();
for (int i = 0; i < intervals.Length; ++i)
{
list.Add(intervals[i]);
}
list.Sort((a, b) =>
{
return a[0] - b[0];
});
List<int[]> ret = new List<int[]>();
ret.Add(list[0]);
for (int i = 1; i < list.Count; ++i)
{
int retIndex = ret.Count - 1;
//可合并的区间
if (list[i][0] <= ret[retIndex][1])
{
ret[retIndex][1] = Math.Max(ret[retIndex][1], list[i][1]);
}
else
{
ret.Add(list[i]);
}
}
return ret.ToArray();
}
}
}
<file_sep>---
layout: post
title: "C#委托"
subtitle: " \"面试小记\""
date: 2020-11-15 09:44:09
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- C#
---
> “面试知识点整理”
# Action和function区别
[Delegate](https://docs.microsoft.com/zh-cn/dotnet/api/system.delegate?view=netstandard-1.4)类是委托类型的基类。 但是,只有系统和编译器才能显式从 [Delegate](https://docs.microsoft.com/zh-cn/dotnet/api/system.delegate?view=netstandard-1.4) 类或 [MulticastDelegate](https://docs.microsoft.com/zh-cn/dotnet/api/system.multicastdelegate?view=netstandard-1.4) 类派生。 也不允许从委托类型派生新类型。 [Delegate](https://docs.microsoft.com/zh-cn/dotnet/api/system.delegate?view=netstandard-1.4)类不被视为委托类型; 它是用于派生委托类型的类。
大多数语言都实现 `delegate` 关键字,这些语言的编译器可以从 [MulticastDelegate](https://docs.microsoft.com/zh-cn/dotnet/api/system.multicastdelegate?view=netstandard-1.4) 类派生; 因此,用户应使用 `delegate` 语言提供的关键字。
**Action 与 Func是.NET类库中增加的内置委托,以便更加简洁方便的使用委托。**
两种委托类型的区别在于:Action委托签名不提供返回类型,而Func提供返回类型。
# 内部实现
**泛型签名的函数指针**
Action委托具有Action<T>、Action<T1,T2>、Action<T1,T2,T3>……Action<T1,……T16>多达16个的重载,其中传入参数均采用泛型中的类型参数T,涵盖了几乎所有可能存在的无返回值的委托类型。
Func则具有Func<TResult>、Func<T,Tresult>……Func<T1,T2,T3……,Tresult>17种类型重载,T1……T16为出入参数,Tresult为返回类型。
# 注册函数如何防止重复
1. 注册函数的时候,先获取委托列表,使用反射进行便利,对比委托列表里的函数名和实例对象
2. 先删除,再注册
# 如何删除
### Delegate.Remove(Delegate, Delegate) 方法
- 命名空间:
[System](https://docs.microsoft.com/zh-cn/dotnet/api/system?view=netstandard-1.4)
- 程序集:
System.Runtime.dll
从一个委托的调用列表中移除另一个委托的最后一个调用列表。
C#复制
```csharp
public static Delegate Remove (Delegate source, Delegate value);
```
#### 参数
- source
[Delegate](https://docs.microsoft.com/zh-cn/dotnet/api/system.delegate?view=netstandard-1.4)
委托,将从中移除 `value` 的调用列表。
- value
[Delegate](https://docs.microsoft.com/zh-cn/dotnet/api/system.delegate?view=netstandard-1.4)
委托,它提供将从其中移除 `source` 的调用列表的调用列表。
#### 返回
- [Delegate](https://docs.microsoft.com/zh-cn/dotnet/api/system.delegate?view=netstandard-1.4)
一个新委托,其调用列表的构成方法为:获取 `source` 的调用列表,如果在 `value` 的调用列表中找到了 `value` 的调用列表,则从中移除 `source` 的最后一个调用列表。 如果 `source` 为 `null`,或在 `value` 的调用列表中没有找到 `value` 的调用列表,则返回 `source`。 如果 `value` 的调用列表等于 `source` 的调用列表,或 `source` 为空引用,则返回空引用。
#### 例外
[MemberAccessException](https://docs.microsoft.com/zh-cn/dotnet/api/system.memberaccessexception?view=netstandard-1.4)
调用方不能访问由委托表示的方法(例如,在方法为私有方法的情况下)。
[ArgumentException](https://docs.microsoft.com/zh-cn/dotnet/api/system.argumentexception?view=netstandard-1.4)
委托类型不匹配。
## 注解
如果的调用列表 `value` 与的调用列表中的一组连续元素相匹配,则在的 `source` 调用列表 `value`中将出现的调用列表 `source` 。 如果的调用列表 `value` 在的调用列表中出现多次 `source` ,则将删除最后一个匹配项。
<file_sep>class Solution {
public:
/**
* retrun the longest increasing subsequence
* @param arr int整型vector the array
* @return int整型vector
*/
vector<int> LIS(vector<int>& arr) {
// write code here
// 如果有多个答案,输出其中字典序最小的
// 二分,动态规划DP
// 本题的本质是求最长上升子序列,采用动态规划
// dp存储每个元素往前的最长子数列大小
// dp[i] = max(dp[i], dp[j]+1), j为0到i-1中比arr[i]小的子数列数据
// 为了避免重复比较,用end数组村粗最长上升子序列
// 当arr[i]>end[len]时,arr[i]添加到end后面
// 否则 从end 0->len范围内查找到第一个比arr[i]大的元素进行替换,此处采用二分法查找
int n = arr.size();
vector<int> end(n+1); // 下标从1开始
// 存储每个元素的最大子序列个数
vector<int> dp(n);
int len = 1;
// 子序列的第一个元素默认为数组的第一个元素
end[1] = arr[0];
// 第一个元素的最大子序列个数肯定是1
dp[0] = 1;
for(int i=0; i < n; i++) {
if(end[len] < arr[i]){
// 当arr[i] > end[len]时,arr[i]添加到end后面
end[++len] = arr[i];
dp[i] = len;
}
else {
// 当前元素小于end中的最后一个元素,利用二分法寻找第一个大于arr[i]的元素
// end[i] 替换为当前元素dp[]
int l = 0;
int r = len;
while(l <= r) {
int mid = (l+r)>>1; // 位运算,相当于除以2
if(end[mid] >= arr[i]) {
r = mid-1;
}
else l = mid+1;
}
end[l] = arr[i];
dp[i] = l;
}
}
vector<int> res(len);
for(int i = n-1; i >= 0; i--) {
if(dp[i] == len) {
res[--len] = arr[i];
}
}
return res;
}
};<file_sep>struct ListNode {
int val;
struct ListNode* next;
ListNode(int x) :
val(x), next(NULL) {
}
};
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode* tmpNode = nullptr;
if (l2 == nullptr)
return l1;
else if (l1 == nullptr)
return l2;
if (l1->val < l2->val)
{
tmpNode = l1;
l1 = l1->next;
}
else
{
tmpNode = l2;
l2 = l2->next;
}
ListNode* head = tmpNode;
while (!(l1 == nullptr && l2 == nullptr))
{
if (l1 == nullptr)
{
tmpNode->next = l2;
l2 = l2->next;
tmpNode = tmpNode->next;
}
else if (l2 == nullptr)
{
tmpNode->next = l1;
l1 = l1->next;
tmpNode = tmpNode->next;
}
else
{
if (l1->val < l2->val)
{
tmpNode->next = l1;
l1 = l1->next;
tmpNode = tmpNode->next;
}
else
{
tmpNode->next = l2;
l2 = l2->next;
tmpNode = tmpNode->next;
}
}
}
return head;
}<file_sep>#### [97. 交错字符串](https://leetcode-cn.com/problems/interleaving-string/)
难度困难384
给定三个字符串 `s1`、`s2`、`s3`,请你帮忙验证 `s3` 是否是由 `s1` 和 `s2` **交错** 组成的。
两个字符串 `s` 和 `t` **交错** 的定义与过程如下,其中每个字符串都会被分割成若干 **非空** 子字符串:
- `s = s1 + s2 + ... + sn`
- `t = t1 + t2 + ... + tm`
- `|n - m| <= 1`
- **交错** 是 `s1 + t1 + s2 + t2 + s3 + t3 + ...` 或者 `t1 + s1 + t2 + s2 + t3 + s3 + ...`
**提示:**`a + b` 意味着字符串 `a` 和 `b` 连接。
**示例 1:**

```
输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
输出:true
```
**示例 2:**
```
输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
输出:false
```
**示例 3:**
```
输入:s1 = "", s2 = "", s3 = ""
输出:true
```
**提示:**
- `0 <= s1.length, s2.length <= 100`
- `0 <= s3.length <= 200`
- `s1`、`s2`、和 `s3` 都由小写英文字母组成
### 题解
输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
输出:true
| | 0 | a/1 | a/2 | b/3 | c | c |
| ---- | ---- | ---- | ------- | ----------------- | ----------------- | ------------- |
| 0 | T | T(a) | T(aa) | F(aad ! = aab) | F(aadb != aabc ) | |
| d/1 | F | F | T(aad) | T(aadb) | F | |
| b/2 | | | T(aadb) | T(aadbb) 3+2-1 == | T(aadbbc) | F |
| b | | | F | F | T(aadbbcb) | T(aadbbcbc) |
| c | | | | | T(aadbbcbc) | F |
| a | | | | | T(aadbbcbca) | T(aadbbcbcac) |
<file_sep>---
layout: post
title: "Python解析Xml文件"
subtitle: " \"Unity Shader\""
date: 2018-05-02 15:48:00
author: "Mas9uerade"
header-img: "img/watchdog2_sf.jpg"
tags:
- Python
- xml
---
> “简单的笔记”
最近在工程中需要去裁剪一些图集,所以写了一个根据xml数据裁剪图集的小脚本。
## 基本思路
1. 使用Python的PIL库打开图集;
2. 解析Xml配置表获取图片的像素位置与大小,调用Crop()进行裁剪;
### 附上脚本
```Python
from PIL import Image
import os
from xml.dom.minidom import parse
import xml.dom.minidom as xmldom
#图集路径与配置表路径
imgPath = "./TroopCardAll.png"
xmlPath = "./TroopCardAll.xml"
# 使用PIL打开图像
img = Image.open(imgPath)
# 使用minidom解析器打开 XML 文档
DOMTree = xmldom.parse(xmlPath)
# 获取子节点
collection = DOMTree.documentElement
print("DocumentElement:", collection)
# 子节点的签名为 SubTexture
subTextures = collection.getElementsByTagName("SubTexture")
print("getElementsByTagName:", type(subTextures))
print(len(subTextures))
# 遍历子节点并切图
for subTexture in subTextures:
name = subTexture.getAttribute("name")
x = int(subTexture.getAttribute("x"))
y = int(subTexture.getAttribute("y"))
w = int(subTexture.getAttribute("width"))
h = int(subTexture.getAttribute("height"))
print("name:", name, "x:", x, "y:", y, "w:", w, "h:", h)
subImg = img.crop((x, y, x+w, y+h))
filename = ("./TroopCardAll/" + name + ".png")
print(filename)
# 确认是否有子路经并存储
if "/" in name:
dir = name.rfind("/")
fileDir = "./TroopCardAll/" + name[0:dir]
if not (os.path.exists(fileDir)):
os.makedirs(fileDir)
print("CreateDir:", fileDir)
# 存储图片
subImg.save(filename)
print("Done")
```<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp2
{
public class MaxNumofSubstring
{
public class Line
{
public int Start;
public int End;
public Line(int _start, int _end)
{
Start = _start;
End = _end;
}
}
public IList<string> MaxNumOfSubstrings(string s)
{
if (string.IsNullOrEmpty(s))
{
return new List<string>();
}
List<string> ret = new List<string>();
List<Line> tmp = new List<Line>();
//获取线段
Line[] lines = new Line[26];
for (int i = 0; i < lines.Length; ++i)
{
lines[i] = new Line(-1, -1);
}
for (int i = 0; i < s.Length; ++i)
{
int charIndex = s[i] - 'a';
if (lines[charIndex].Start == -1)
{
lines[charIndex].Start = i;
}
lines[charIndex].End = i;
}
//合并
for (int i = 0; i < lines.Length; ++i)
{
int charIndex =i;
int start = lines[charIndex].Start;
if (start == -1)
{
continue;
}
int end = lines[charIndex].End;
for (int j = start+1; j <end; ++j)
{
int charIndex2 = s[j] - 'a';
if (charIndex2 == charIndex)
{
continue;
}
int subStart = lines[charIndex2].Start;
if (subStart == -1)
{
continue;
}
int subEnd = lines[s[j]-'a'].End;
if (subEnd > end || subStart < start)
{
lines[charIndex2].End = Math.Max(subEnd, end);
lines[charIndex].End = Math.Max(subEnd, end);
lines[charIndex2].Start = Math.Min(start, subStart);
lines[charIndex].Start = Math.Min(start, subStart);
end = Math.Max(subEnd, end);
start = Math.Min(start, subStart);
j = start + 1;
}
}
}
//贪心
Line first = lines[s[0] - 'a'];
int frontIndex = first.Start, backIndex = first.End;
tmp.Add(lines[s[0] - 'a']);
for (int i = 1; i < s.Length;++i)
{
int charIndex = s[i] - 'a';
int start = lines[charIndex].Start;
int end = lines[charIndex].End;
if (start == -1)
{
continue;
}
for (int j = 0; j <tmp.Count; ++j)
{
if (start > tmp[j].Start && end < tmp[j].End)
{
if (backIndex == tmp[j].End)
{
backIndex = end;
}
tmp[j].Start = start;
tmp[j].End = end;
break;
}
if (start > backIndex )
{
tmp.Add(new Line(start, end));
backIndex = end;
break;
}
}
//frontIndex = Math.Min(start, frontIndex);
//backIndex = Math.Max(end, backIndex);
}
for (int i = 0; i <tmp.Count; ++i)
{
ret.Add(s.Substring(tmp[i].Start, tmp[i].End - tmp[i].Start + 1));
}
return ret;
}
}
}
<file_sep>/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution
{
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null)
{
this.val = val;
this.next = next;
}
}
public void ReorderList(ListNode head)
{
ListNode front = head;
ListNode end = head;
Stack<ListNode> stackNode = new Stack<ListNode>();
while (end.next != null )
{
}
}
}<file_sep>//二分查找确定最长子字串的长度,再确定具体的子字串
using System;
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
public string LongestDupSubstring(string s)
{
int n = s.Length;
if (n == 0 || n == 1)
{
return "";
}
//把字符串转换成数字
int[] nums = new int[s.Length];
for (int i = 0; i < s.Length; ++i)
{
nums[i] = (int)s[i] - (int)'a';
}
long modulus = (long)Math.Pow(2,32);
int a = 26;
int left = 1;
int right = s.Length;
int L;
//
while (left != right)
{
L = left + (right - left) / 2;
if (SubStringBinarySerach(L, a, modulus, n, nums, s) != -1)
{
left = L + 1;
}
else
{
right = L;
}
}
int start = SubStringBinarySerach(left - 1, a, modulus, n, nums,s);
return start != -1 ? s.Substring(start, left - 1) : "";
}
int SubStringBinarySerach(int L, int a, long modulus, int n, int[] nums, string s)
{
long h = 0;
for (int i = 0; i < L; ++i) h = (h * a + nums[i]) % modulus;
// already seen hashes of strings of length L
HashSet<long> seen = new HashSet<long>();
Dictionary<long, int> dictStart = new Dictionary<long, int>();
seen.Add(h);
dictStart[h] = 0;
//tmpStr.Add(s.Substring(0, L));
// const value to be used often : a**L % modulus
long aL = 1;
for (int i = 1; i <= L; ++i) aL = (aL * a) % modulus;
for (int start = 1; start < n - L + 1; ++start)
{
// compute rolling hash in O(1) time
h = (h * a - nums[start - 1] * aL % modulus + modulus) % modulus;
h = (h + nums[start + L - 1]) % modulus;
if (seen.Contains(h))
{
if (CompareTwoArray(nums, dictStart[h], start, L))
{
return start;
}
}
seen.Add(h);
dictStart[h] = start;
}
return -1;
}
bool CompareTwoArray(int[] nums, int index1, int index2, int len)
{
for (int i = 0; i < len; ++i)
{
if (nums[index1+i] != nums[i+index2])
{
return false;
}
}
return true;
}
}
}<file_sep>using System.Collections.Generic;
public class Solution
{
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null)
{
this.val = val;
this.next = next;
}
}
public void ReorderList(ListNode head)
{
if (head == null)
{
return;
}
ListNode front = head;
ListNode end = head;
Stack<ListNode> stackNode = new Stack<ListNode>();
while (end != null)
{
stackNode.Push(end);
end = end.next;
}
while (head != stackNode.Peek())
{
ListNode last = stackNode.Pop();
ListNode tmp = head.next;
if (tmp != last)
{
head.next = last;
last.next = tmp;
head = tmp;
}
else
{
head.next = last;
last.next = null;
return;
}
}
head.next = null;
}
}<file_sep>public class Solution {
public int MaxProfit(int[] prices)
{
int minprice = Integer.MAX_VALUE;
int maxprofit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minprice) {
minprice = prices[i];
} else if (prices[i] - minprice > maxprofit) {
maxprofit = prices[i] - minprice;
}
}
return maxprofit;
}
}<file_sep>/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution
{
public:
/**
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root)
{
// write code here
vector<vector<int>> result;
if (root == NULL)
{
return result;
}
queue<TreeNode*> queueTree;
queueTree.push(root);
while(!queueTree.empty())
{
int len = queueTree.size();
vector<int> val;
for (int i = 0; i <len; i++)
{
TreeNode* root = queueTree.front();
queueTree.pop();
val.push_back(root->val);
if(root->left != NULL)
{
queueTree.push(root->left);
}
if(root->right != NULL)
{
queueTree.push(root->right);
}
}
result.push_back(val);
}
return result;
}
};<file_sep>using System;
using System.Collections.Generic;
namespace ByteDancePopular
{
//1、将所有自行车加入队列;
//2、计算每个自行车距离最近的工人,把自行车分配给该工人;
//3、如果自行车分配的工人已经分配了自行车,且该自行车距离该工人的距离小于之前已经分配的距离,则更新,把已经分配的自行车重新放回队列;
//4、如果自行车分配的工人已经分配了自行车,且该自行车距离该工人的距离等于之前等于分配的距离,计算该工人对应的自行车ID是不是小于已经分配自行车ID,满足则更新,把已经分配的自行车重新放回队列;
//5、如果自行车分配的工人已经分配了自行车,且该自行车距离该工人的距离等于之前已经分配的距离,计算该自行车ID分配的工人ID是否小于已经分配的工人ID,满足则更新,把已经分配的自行车重新放回队列;
public partial class Solution
{
public class BikeWokrerPair
{
public int WokrerIndex;
public int BikeIndex;
public int Distance;
}
//public int[] AssignBikes(int[][] workers, int[][] bikes)
//{
// Queue<BikeWokrerPair> queuePair = new Queue<BikeWokrerPair>();
// //key 是自行车, value 是工人
// Dictionary<int, int> dictPair = new Dictionary<int, int>();
// //长度
// int workerLen = workers.Length;
// int bikeLen = bikes.Length;
// List<int> AvaiableWorker = new List<int>(workerLen);
// for (int i = 0; i <workerLen; ++i)
// {
// AvaiableWorker.Add(i);
// }
// List<int> AvaiableBike = new List<int>(bikeLen);
// for(int i = 0; i < bikeLen; ++i)
// {
// AvaiableBike.Add(i);
// }
// SortedList<>
// int[][] distance = new int[workerLen][];
// for (int i =0; i < workerLen; ++i)
// {
// distance[i] = new int[bikeLen];
// for (int j =0; j < bikeLen; ++j)
// {
// distance[i][j] = Math.Abs(bikes[i][0] - workers[i][0]) + Math.Abs(bikes[i][1] - workers[i][1]);
// }
// }
// for (int i = 0; i < bikes.Length; ++i)
// {
// queuePair.Enqueue(new BikeWokrerPair()
// {
// BikeIndex = i,
// Distance = -1,
// });
// }
// while(queuePair.Count > 0)
// {
// BikeWokrerPair pair =queuePair.Dequeue();
// for (int i = 0; i < workers.Length; ++i)
// {
// int distance = Math.Abs(workers[i][0] - bikes[pair.BikeIndex][0]) + Math.Abs(workers[i][1] - bikes[pair.BikeIndex][1]);
// if (pair.Distance == -1)
// {
// pair.Distance = distance;
// pair.WokrerIndex = i;
// dictPair[pair.BikeIndex] = pair.WokrerIndex;
// }
// else
// {
// if (pair.Distance > distance)
// {
// }
// else
// {
// }
// }
// }
// }
//}
}
}<file_sep>using System;
using System.Collections.Generic;
//670.最大交换
//给定一个非负整数,你至多可以交换一次数字中的任意两位。返回你能得到的最大值。
//示例 1 :
//输入: 2736
//输出: 7236
//解释: 交换数字2和数字7。
//示例 2 :
//输入: 9973
//输出: 9973
//解释: 不需要交换。
//注意:
//给定数字的范围是[0, 10^8]
namespace ByteDancePopular
{
public partial class Solution
{
public int MaximumSwap(int num)
{
int[] last = new int[9];
string strNum = num.ToString();
for (int i = 0; i < strNum.Length; ++i)
{
int index = strNum[i] - '1';
if (index >= 0)
{
last[index] = i;
}
}
for (int i = 0; i < strNum.Length; ++i)
{
for (int j = last.Length - 1; j >= 0; --j)
{
if (strNum[i] < (j+ '1') && i < last[j])
{
//交换
char[] charNum = strNum.ToCharArray();
charNum[last[j]] = charNum[i];
charNum[i] = (char)( j + '1');
string strRet = new string(charNum);
return int.Parse(strRet);
}
}
}
return num;
}
}
}<file_sep>public double FindMedianSortedArrays(int[] nums1, int[] nums2)
{
int m = nums1.Length;
int n = nums2.Length;
//处理任何一个nums为空数组的情况
if (m == 0)
{
if (n % 2 != 0)
{
return nums2[n / 2];
}
else
{
return (nums2[n / 2] + nums2[n / 2 - 1]) / 2.0;
}
}
if (n == 0)
{
if (m % 2 != 0)
{
return 1.0 * nums1[m / 2];
}
else
{
return (nums1[m / 2] + nums1[m / 2 - 1]) / 2.0;
}
}
int total = m + n;
//总数为奇数,找第 total / 2 + 1 个数
if ((total & 1) == 1)
{
return find_kth(nums1, 0, nums2, 0, total / 2 + 1);
}
//总数为偶数,找第 total / 2 个数和第total / 2 + 1个数的平均值
return (find_kth(nums1, 0, nums2, 0, total / 2) + find_kth(nums1, 0, nums2, 0, total / 2 + 1)) / 2.0;
}
//寻找a 和 b 数组中,第k个数字
double find_kth(int[] a, int a_begin, int[] b, int b_begin, int k)
{
//当a 或 b 超过数组长度,则第k个数为另外一个数组第k个数
if (a_begin >= a.Length)
{
return b[b_begin + k - 1];
}
if (b_begin >= b.Length)
{
return a[a_begin + k - 1];
}
//k为1时,两数组最小的那个为第一个数
if (k == 1)
{
return Math.Min(a[a_begin], b[b_begin]);
}
int mid_a = int.MaxValue;
int mid_b = int.MaxValue;
//mid_a / mid_b 分别表示 a数组、b数组中第 k / 2 个数
if (a_begin + k / 2 - 1 < a.Length)
{
mid_a = a[a_begin + k / 2 - 1];
}
if (b_begin + k / 2 - 1 < b.Length)
{
mid_b = b[b_begin + k / 2 - 1];
}
//如果a数组的第 k / 2 个数小于b数组的第 k / 2 个数,表示总的第 k 个数位于 a的第k / 2个数的后半段,或者是b的第 k / 2个数的前半段
//由于范围缩小了 k / 2 个数,此时总的第 k 个数实际上等于新的范围内的第 k - k / 2个数,依次递归
if (mid_a < mid_b)
{
return find_kth(a, a_begin + k / 2, b, b_begin, k - k / 2);
}
//否则相反
else
{
return find_kth(a, a_begin, b, b_begin + k / 2, k - k / 2);
}
} <file_sep>using System.Globalization;
using System;
public class Solution
{
public IList<string> SummaryRanges(int[] nums)
{
int left = 0; int right = 0;
while (right < nums.Length)
{
if (right - left = NumberStyles)
}
}
}<file_sep>---
layout: post
title: "求职小记"
subtitle: " \"个人求职心路历程\""
date: 2020-10-19 01:43:00
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- 心路历程
---
> 在决定离职后的第2个月,准备找工作的第1个月,我发现我将要面对的求职环境可能比我之前想象得更为严峻
### 求职期间的压力来源
于我而言,求职期间的压力来源大概可以分为由内而外和由外至内的,即自我产生的和外在环境给予的压迫。
首先,由外至内产生的压力会从经济层面体现的,今年的年终奖应该是没有了,给自己预留的存款也会显而易见地减少,会造成一种安全感的缺失。
其次,外在的压力来源还有亲朋好友和不熟的陌生人,亲朋好友的话,会时不时地问你找工作的进展如何,会让你开始对找工作的进展感到焦虑,而且还会害怕被Judge为没法找到工作的loser。
陌生人的社交压力与亲朋好友的压力相似,不过会集中在被Judge的焦虑和社交地位下降的妄想上。个人感觉这不是一个良好的心理状态,没有交集的人,在乎别人的看法有什么意义呢?
内在压力是目前求职期间带给我的主要压力,因为求职说白了就是把自己通过简历摆上招聘网站展示给企业的HR、面试官,让别人去定义你的价值以及他们是否能够承受和接受你。这个阶段,我会不断地审视自己的过去的经历、现在的能力以及未来的潜能。
每一次的失败都会加深自我怀疑,简历石沉大海,会思考简历是不是不够优秀,过去的工作经历是不是不够优秀;面试表现不佳,会懊恼准备不够充分,怀疑自己是不是不够努力,没有全身心地为了未来投入自己的effort,在每一次休息放松的时候,都会感到负罪感。这时候,会开始找内在原因和外在原因,一方面,我开始不停地优化简历,另一方面,也在思考是不是现在是不是一个合适的时机来做这件事。
除此之外,我的压力来源还有一个就是给自己的离职倒计时,住的公寓只续了3个月,还有一个月就要到期了,在此之前就要再做一次抉择,留在深圳还是回家待业。
### 排解压力的办法
这些压力,这些焦虑是有些无法解决,有些事可以排解的,我的方式主要有三种:首先是运动,运动的解压效果真的很棒;其次,是寻求安慰和帮助;第三,自我提升。
运动的话,就是用跑步和健身去消耗自己的精力,因为健身是一件提升得很慢、反馈不是特别明显的事,但是可以暗示自己every step makes a difference。
寻求帮助和安慰,是多和朋友们交流和联系,去尝试获取他们的支持,虽然如果得到了他们的负面反馈,会获得一些比较tough的思考,去想自己是不是不应该去辞职,反而应该在职期间慢慢地去找工作。但是一旦获得了支持,就获得了继续前行的动力,毕竟,人还是社会性的动物,他人的认可还是比较重要的。
除此之外,就默默地准备面试、刷题,在这个过程中能够看到自己的提升,也还不错。
最后,就是刷[《无业游民》的播客](https://www.ibm.com/developerworks/cn/linux/l-ipc/part2/index1.html), 真的有点治愈<file_sep>//5.最长回文子串
//给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
//示例 1:
//输入: "babad"
//输出: "bab"
//注意: "aba" 也是一个有效答案。
//示例 2:
//输入: "cbbd"
//输出: "bb"
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/longest-palindromic-substring
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
// 思路
// 选定 回文中心, 向两边拓展, 拓展基于dp
// 回文中心 有两种 1个的 和两个的
using System;
namespace ByteDancePopular
{
public partial class Solution
{
public string LongestPalindrome(string s)
{
if (s.Length == 0 || s.Length == 1)
{
return s;
}
int maxlen = 1;
string ret = s[0].ToString();
int markerleft = 0, markerright = 0;
for (int i = 1; i < s.Length; ++i)
{
int left = i - 1;
int right = i + 1;
int len = 1;
len = GetPalindromicSubstringLen(s, left, right, len);
if (maxlen < len)
{
markerleft = i - len / 2;
maxlen = len;
}
//偶数回文中心的情况
left = i - 1;
right = i;
len = 0;
len = GetPalindromicSubstringLen(s, left, right, len);
if (maxlen < len)
{
markerleft = i - len / 2;
maxlen = len;
}
}
return s.Substring(markerleft, maxlen);
}
private int GetPalindromicSubstringLen (string s, int left, int right, int initlen)
{
bool dp = true;
int len = initlen;
while (left >= 0 && right < s.Length && dp)
{
if (s[left] == s[right])
{
dp = true;
len = right - left + 1;
left--;
right++;
}
else
{
dp = false;
}
}
return len;
}
}
}
<file_sep>public class Solution {
public string Convert(string s, int numRows)
{
if (numRows == 1)
{
return s;
}
int cycle = 2 * numRows -2;
List<List<char>> result = new List<List<char>>();
for (int i = 0; i < numRows; ++i)
{
result.Add(new List<char>());
}
for (int i = 0; i < s.Length; ++i)
{
int round = i / cycle;
int index = i % cycle;
int col = round * (numRows -1) + (index > numRows-1? index-(numRows-1): 0);
int row = index > numRows-1 ? (numRows-1) - (index- (numRows-1)) : index;
result[row].add(s[i]);
}
stringbuilder sb = new stringBuilder();
for (int i = 0; i < result.Length; ++i)
{
for (int j = 0; j < result[i].Length; ++j)
{
sb.append(result[i][j]);
}
}
return sb.ToString();
}
}<file_sep>---
layout: post
title: "TopK排序"
subtitle:
date: 2020-12-2 18:15:46
author: "Mas9uerade"
header-img: ""
tags:
- 基础
---
# TopK排序算法总结
**问题描述**:
从arr[1, n]这n个数中,找出最大的k个数,这就是经典的TopK问题。
**栗子**:
从arr[1, 12]={5,3,7,1,8,2,9,4,7,2,6,6} 这n=12个数中,找出最大的k=5个。
**一、排序**

排序是最容易想到的方法,将n个数排序之后,取出最大的k个,即为所得。
**伪代码**:
sort(arr, 1, n);
return arr[1, k];
**时间复杂度**:O(n*lg(n))
**分析**:明明只需要TopK,却将全局都排序了,这也是这个方法复杂度非常高的原因。那能不能不全局排序,而只局部排序呢?这就引出了第二个优化方法。
**二、局部排序**
不再全局排序,只对最大的k个排序。

冒泡是一个很常见的排序方法,每冒一个泡,找出最大值,冒k个泡,就得到TopK。
**伪代码**:
for(i=1 to k){
bubble_find_max(arr,i);
}
return arr[1, k];
**时间复杂度**:O(n*k)
**分析**:冒泡,将全局排序优化为了局部排序,非TopK的元素是不需要排序的,节省了计算资源。不少朋友会想到,需求是TopK,是不是这最大的k个元素也不需要排序呢?这就引出了第三个优化方法。
**三、堆**
**思路**:只找到TopK,不排序TopK。

先用前k个元素生成一个小顶堆,这个小顶堆用于存储,当前最大的k个元素。

接着,从第k+1个元素开始扫描,和堆顶(堆中最小的元素)比较,如果被扫描的元素大于堆顶,则替换堆顶的元素,并调整堆,以保证堆内的k个元素,总是当前最大的k个元素。

直到,扫描完所有n-k个元素,最终堆中的k个元素,就是猥琐求的TopK。
**伪代码**:
heap[k] = make_heap(arr[1, k]);
for(i=k+1 to n){
adjust_heap(heep[k],arr[i]);
}
return heap[k];
**时间复杂度**:O(n*lg(k))
画外音:n个元素扫一遍,假设运气很差,每次都入堆调整,调整时间复杂度为堆的高度,即lg(k),故整体时间复杂度是n*lg(k)。
**分析**:堆,将冒泡的TopK排序优化为了TopK不排序,节省了计算资源。堆,是求TopK的经典算法,那还有没有更快的方案呢?
**四、随机选择**
随机选择算在是《算法导论》中一个经典的算法,其时间复杂度为O(n),是一个线性复杂度的方法。
这个方法并不是所有同学都知道,为了将算法讲透,先聊一些前序知识,一个所有程序员都应该烂熟于胸的经典算法:快速排序。
画外音:
(1)如果有朋友说,“不知道快速排序,也不妨碍我写业务代码呀”…额...
(2)除非校招,我在面试过程中从不问快速排序,默认所有工程师都知道;
**其伪代码是**:
void quick_sort(int[]arr, int low, inthigh){
if(low== high) return;
int i = partition(arr, low, high);
quick_sort(arr, low, i-1);
quick_sort(arr, i+1, high);
}
其核心算法思想是,分治法。
**分治法**(Divide&Conquer),把一个大的问题,转化为若干个子问题(Divide),每个子问题“**都**”解决,大的问题便随之解决(Conquer)。这里的关键词是**“都”**。从伪代码里可以看到,快速排序递归时,先通过partition把数组分隔为两个部分,两个部分“都”要再次递归。
分治法有一个特例,叫减治法。
**减治法**(Reduce&Conquer),把一个大的问题,转化为若干个子问题(Reduce),这些子问题中“**只**”解决一个,大的问题便随之解决(Conquer)。这里的关键词是**“只”**。
**二分查找binary_search**,BS,是一个典型的运用减治法思想的算法,其伪代码是:
int BS(int[]arr, int low, inthigh, int target){
if(low> high) return -1;
mid= (low+high)/2;
if(arr[mid]== target) return mid;
if(arr[mid]> target)
return BS(arr, low, mid-1, target);
else
return BS(arr, mid+1, high, target);
}
从伪代码可以看到,二分查找,一个大的问题,可以用一个mid元素,分成左半区,右半区两个子问题。而左右两个子问题,只需要解决其中一个,递归一次,就能够解决二分查找全局的问题。
通过分治法与减治法的描述,可以发现,分治法的复杂度一般来说是大于减治法的:
快速排序:O(n*lg(n))
二分查找:O(lg(n))
话题收回来,**快速排序**的核心是:
i = partition(arr, low, high);
**这个partition是干嘛的呢?**
顾名思义,partition会把整体分为两个部分。
更具体的,会用数组arr中的一个元素(默认是第一个元素t=arr[low])为划分依据,将数据arr[low, high]划分成左右两个子数组:
- 左半部分,都比t大
- 右半部分,都比t小
- 中间位置i是划分元素

以上述TopK的数组为例,先用第一个元素t=arr[low]为划分依据,扫描一遍数组,把数组分成了两个半区:
- 左半区比t大
- 右半区比t小
- 中间是t
partition返回的是t最终的位置i。
很容易知道,partition的时间复杂度是O(n)。
画外音:把整个数组扫一遍,比t大的放左边,比t小的放右边,最后t放在中间N[i]。
**partition和TopK问题有什么关系呢?**
TopK是希望求出arr[1,n]中最大的k个数,那如果找到了**第k大**的数,做一次partition,不就一次性找到最大的k个数了么?
画外音:即partition后左半区的k个数。
问题变成了arr[1, n]中找到第k大的数。
再回过头来看看**第一次**partition,划分之后:
i = partition(arr, 1, n);
- 如果i大于k,则说明arr[i]左边的元素都大于k,于是只递归arr[1, i-1]里第k大的元素即可;
- 如果i小于k,则说明说明第k大的元素在arr[i]的右边,于是只递归arr[i+1, n]里第k-i大的元素即可;
画外音:这一段非常重要,多读几遍。
这就是**随机选择**算法randomized_select,RS,其伪代码如下:
int RS(arr, low, high, k){
if(low== high) return arr[low];
i= partition(arr, low, high);
temp= i-low; //数组前半部分元素个数
if(temp>=k)
return RS(arr, low, i-1, k); //求前半部分第k大
else
return RS(arr, i+1, high, k-i); //求后半部分第k-i大
}

这是一个典型的减治算法,递归内的两个分支,最终只会执行一个,它的时间复杂度是O(n)。
再次强调一下:
- 分治法,大问题分解为小问题,小问题都要递归各个分支,例如:快速排序
- 减治法,大问题分解为小问题,小问题只要递归一个分支,例如:二分查找,随机选择
通过随机选择(randomized_select),找到arr[1, n]中第k大的数,再进行一次partition,就能得到TopK的结果。
**五、总结**
TopK,不难;其思路优化过程,不简单:
- 全局排序,O(n*lg(n))
- 局部排序,只排序TopK个数,O(n*k)
- 堆,TopK个数也不排序了,O(n*lg(k))
- 分治法,每个分支“都要”递归,例如:快速排序,O(n*lg(n))
- 减治法,“只要”递归一个分支,例如:二分查找O(lg(n)),随机选择O(n)
- TopK的另一个解法:随机选择+partition
<file_sep>---
layout: post
title: "Python Number(数字)"
subtitle: "初学python"
date: 2018-04-16 12:11:00
author: "nankenan"
header-img: "img/watchdog2_sf.jpg"
tags:
- Python
---
> Reposted from [nankenan](https://nankenan.github.io)
# Python Number(数字)
转载于http://www.runoob.com/python/python-numbers.html
Python 中数学运算常用的函数基本都在 math 模块、cmath 模块中。
Python math 模块提供了许多对浮点数的数学运算函数。
Python cmath 模块包含了一些用于复数运算的函数。
Python Number 数据类型用于存储数值。
数据类型是不允许改变的,这就意味着如果改变 Number 数据类型的值,将重新分配内存空间。
以下实例在变量赋值时 Number 对象将被创建:
```python
var1 = 1
var2 = 10
```
可以通过使用del语句删除单个或多个对象,例如:
```python
del var
del var_a, var_b
```
Python 支持四种不同的数值类型:
- **整型(Int)** - 通常被称为是整型或整数,是正或负整数,不带小数点。
- **长整型(long integers)** - 无限大小的整数,整数最后是一个大写或小写的L。
- **浮点型(floating point real values)** - 浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示(2.5e2 = 2.5 x 102 = 250)
- **复数(complex numbers)** - 复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型。
| int | long | float | complex |
| ------ | --------------------- | ---------- | ---------- |
| 10 | 51924361L | 0.0 | 3.14j |
| 100 | -0x19323L | 15.20 | 45.j |
| -786 | 0122L | -21.9 | 9.322e-36j |
| 080 | 0xDEFABCECBDAECBFBAEl | 32.3+e18 | .876j |
| -0490 | 535633629843L | -90. | -.6545+0J |
| -0x260 | -052318172735L | -32.54e100 | 3e+26J |
| 0x69 | -4721885298529L | 70.2-E12 | 4.53e-7j |
- 长整型也可以使用小写"L",但是还是建议您使用大写"L",避免与数字"1"混淆。Python使用"L"来显示长整型。
- Python还支持复数,复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型
## Python数学函数
| 函数 | 返回值(描述) |
| ----------------- | ------------------------------------------------------------ |
| abs(x) | 返回数字的绝对值,如abs(-10) 返回 10 |
| ceil(x) | 返回数字的上入整数,如math.ceil(4.1) 返回 5 |
| cmp(x,y) | 如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1 |
| exp(x) | 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045 |
| fabs(x) | 返回数字的绝对值,如math.fabs(-10) 返回10.0 |
| floor(x) | 返回数字的下舍整数,如math.floor(4.9)返回 4 |
| log(x) | 如math.log(math.e)返回1.0,math.log(100,10)返回2.0 |
| long10(x) | 返回以10为基数的x的对数,如math.log10(100)返回 2.0 |
| max(x1,x2...) | 返回给定参数的最大值,参数可以为序列。 |
| min(x1,x2...) | 返回给定参数的最小值,参数可以为序列。 |
| modf(x) | 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。 |
| pow(x,y) | 返回x的y次方 |
| round( x [, n] ) | 返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。 |
| sqrt(x) | 返回数字x的平方根 |
## Python随机数函数
随机数可以用于数学,游戏,安全等领域中,还经常被嵌入到算法中,用以提高算法效率,并提高程序的安全性。
Python包含以下常用随机数函数:
| 函数 | 描述 |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| [choice(seq)](http://www.runoob.com/python/func-number-choice.html) | 从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。 |
| [randrange ([start,\] stop [,step])](http://www.runoob.com/python/func-number-randrange.html) | 从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省值为1 |
| [random()](http://www.runoob.com/python/func-number-random.html) | 随机生成下一个实数,它在[0,1)范围内。 |
| [seed([x\])](http://www.runoob.com/python/func-number-seed.html) | 改变随机数生成器的种子seed。如果你不了解其原理,你不必特别去设定seed,Python会帮你选择seed。 |
| [shuffle(lst)](http://www.runoob.com/python/func-number-shuffle.html) | 将序列的所有元素随机排序 |
| [uniform(x, y)](http://www.runoob.com/python/func-number-uniform.html) | 随机生成下一个实数,它在[x,y]范围内。 |
------
## Python三角函数
Python包括以下三角函数:
| 函数 | 描述 |
| ------------------------------------------------------------ | ------------------------------------------------- |
| [acos(x)](http://www.runoob.com/python/func-number-acos.html) | 返回x的反余弦弧度值。 |
| [asin(x)](http://www.runoob.com/python/func-number-asin.html) | 返回x的反正弦弧度值。 |
| [atan(x)](http://www.runoob.com/python/func-number-atan.html) | 返回x的反正切弧度值。 |
| [atan2(y, x)](http://www.runoob.com/python/func-number-atan2.html) | 返回给定的 X 及 Y 坐标值的反正切值。 |
| [cos(x)](http://www.runoob.com/python/func-number-cos.html) | 返回x的弧度的余弦值。 |
| [hypot(x, y)](http://www.runoob.com/python/func-number-hypot.html) | 返回欧几里德范数 sqrt(x*x + y*y)。 |
| [sin(x)](http://www.runoob.com/python/func-number-sin.html) | 返回的x弧度的正弦值。 |
| [tan(x)](http://www.runoob.com/python/func-number-tan.html) | 返回x弧度的正切值。 |
| [degrees(x)](http://www.runoob.com/python/func-number-degrees.html) | 将弧度转换为角度,如degrees(math.pi/2) , 返回90.0 |
| [radians(x)](http://www.runoob.com/python/func-number-radians.html) | 将角度转换为弧度 |
------
## Python数学常量
| 常量 | 描述 |
| ---- | ------------------------------------- |
| pi | 数学常量 pi(圆周率,一般以π来表示) |
| e | 数学常量 e,e即自然常数(自然常数)。 |<file_sep># Mas9uerade's Blog
##### This blog is forked from the boilerplate of [Hux Blog](https://github.com/Huxpro/huxpro.github.io), all documents is over there!
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp2
{
public class BusStation
{
public class Vector2<T>
{
public T X;
public T Y;
public Vector2(T x, T y )
{
X = x;
Y = y;
}
}
public int NumBusesToDestination(int[][] routes, int S, int T)
{
if (routes==null || routes.Length == 0)
{
return -1;
}
if (S==T)
{
return 0;
}
//邻接表
List<List<int>> routeGraph = new List<List<int>>(routes.Length);
for (int i = 0; i < routes.Length; ++i)
{
routeGraph.Add(new List<int>());
}
for (int i = 0; i <routes.Length; ++i)
{
for (int j = i+1; j < routes.Length; ++j )
{
if (IsRouteIntersect(routes[i], routes[j]))
{
routeGraph[i].Add(j);
routeGraph[j].Add(i);
}
}
}
HashSet<int> seen = new HashSet<int>();
HashSet<int> target = new HashSet<int>();
Queue<Vector2<int>> queue = new Queue<Vector2<int>>();
for (int i =0; i < routes.Length; ++i)
{
bool match = BinarySearch(0, routes[i].Length-1, routes[i], S);
if (match)
{
seen.Add(i);
queue.Enqueue(new Vector2<int>(i, 0));
}
if (BinarySearch(0, routes[i].Length - 1, routes[i], T))
{
target.Add(i);
}
}
while (queue.Count>0)
{
Vector2<int> info = queue.Dequeue();
int node = info.X, depth = info.Y;
if (target.Contains(node))
{
return depth + 1;
}
foreach (int nei in routeGraph[node])
{
if (!seen.Contains(nei))
{
seen.Add(nei);
queue.Enqueue(new Vector2<int>(nei, depth + 1));
}
}
}
return -1;
}
//是否相交
public bool IsRouteIntersect(int[] route1, int[] route2)
{
int i =0, j = 0;
while (i < route1.Length && j < route2.Length)
{
if (route1[i] == route2[j])
{
return true;
}
if (route1[i] > route2[j])
{
j++;
}
else
{
i++;
}
}
return false;
}
public bool BinarySearch(int beginIndex, int endIndex, int[] data, int val)
{
if (data[endIndex] < val)
{
return false;
}
if (data[endIndex] == val || data[beginIndex] == val)
{
return true;
}
int mid;
while (beginIndex < data.Length && endIndex >= 0 && data[beginIndex] <= data[endIndex])
{
mid = (beginIndex + endIndex) / 2;
if (data[mid] < val)
{
beginIndex = mid + 1;
}
else if (data[mid] > val)
{
endIndex = mid - 1;
}
else
{
return true;
}
}
return false;
}
}
}
<file_sep>---
layout: post
title: "Unity渲染学习"
subtitle: " \"面试小记\""
date: 2020-12-09 15:00:00
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- 渲染
---
> 面试知识点整理
>
## 渲染路径
### 前向渲染
## 一、前向渲染中的原理
前向渲染是通过深度缓冲和颜色缓冲来实现的,使用深度缓冲来决定一个片元是否可见,如果可见,则更新颜色缓冲区中的颜色值。如果场景中有n个物体受m个光源的影响,那么要渲染整个场景,则需要n*m个pass,如果m较多的话,这个开销还是比较大的。那么如何在得到理想效果的同时来节省性能呢,unity提供了一些策略来进行处理前向渲染的光照计算问题;
## 二、unity中的前向渲染
**对光源处理方式分类**:unity在渲染每一个物体之前都会根据光源自身的设置以及光源对该物体的影响程度对场景中的所有光源进行一个重要度排序,然后根据排序的结果以及quality settings等将会决定这些光源的处理方式;
unity中对光照的处理方式有三种分类:逐顶点(最多有四个光源类型可以用逐顶点),逐像素,球谐函数(SH)。决定光照的处理方式有很多因素,每个光照只能按照一种处理方式来处理,下面会一一介绍。
首先每个unity光照都有一个属性叫做**render mode**,一共有三个选项,important,auto, not important;
如果一个光照被声明为important,它就是逐像素处理的,如果被声明为not important,它就是逐顶点处理或球谐处理,如果被声明为Auto,则要根据unity的quality setting中设置的pixel light count来决定。具体解释一下,如果一个光照被声明为important,那么它如果不是最重要的平行光,它就是逐像素处理的,它就需要使用forwardadd的pass,(forwardadd下面会介绍),如果它被声明为not important,而且它是点光源,就使用顶点处理的方式,前提是点光源的数量要不大于四个,如果超过四个了,或者是其它类型的光源,就要使用SH方式。在Auto类别中的,要根据pixel light count,如果pixed light count为5,但是important类型的光源不够(最重要的平行光不计算在内),那么就要从auto中取,其中平行光>其它光源(点光源应该是放在最后的,但我也不确定这一点),如果auto还不够,就算了,**不能从not important中取**。就是通过以上这种逻辑来确定一个光源的处理方式。
首先要明白一点,这些处理方式的计算并不是来计算光照模型,而是来计算填充unity提供的一些内置变量,至于我们作为开发者如何使用这些变量,就是完全自由的,我们可以使用一个逐像素的光照在一个pass里写一个逐顶点光照模型的计算程序。
前向渲染有两种,一个**forwardbase**,用来计算环境光、最重要的平行光、逐顶点和球谐函数以及光照贴图。被声明为forwardbase渲染路径的pass在一个物体的渲染中只能被执行一次,由于环境光只需要执行一次计算,所以要放在该pass中,最重要的平行光一般是指强度最大的平行光,逐顶点的计算通常需要使用到相关的内置变量做计算,如果一个光照是按照逐顶点光照来处理,它就会把该光照的信息计算之后填充到相应内置变量里,但是如果在forwardbase的pass里没有进行处理计算,那么也是看不到任何效果的。
```
float4 lightPos1 = float4(unity_4LightPosX0[0], unity_4LightPosY0[0], unity_4LightPosZ0[0],1);
fixed3 lightDir1 = normalize(lightPos1-i.worldPos).xyz;
fixed3 diff1 = unity_LightColor[0]*albedo*max(0,dot(lightDir1,worldNormal));
```
一个**forwardadd**是用来计算逐像素光照的,也就是如果一个光照的处理方式是逐像素的(最重要平行光除外),它就会使用该pass,该类型的pass可以被多个逐像素光照重复执行。
注意事项:
A.预编译指令,#pragma multi_compile_fwdbase,#pragma multi_compile_fwdadd,#pragma multi_compile_fwdadd_fullshadows;它能够帮助我们得到正确的内置变量。
B.base pass中渲染的平行光默认是支持阴影的,而add pass默认是不支持的,所有需要使用#pragma multi_compile_fwdadd_fullshadows代替原有预编译指令,可以为点光源和聚光灯开启阴影效果。
C.add base中的渲染设置中添加了blend命令,因为add pass需要和帧缓存中数据进行叠加,如果没有开启混合,那么就会直接覆盖掉之前的结果,显然是不对的。
D.对于前向渲染来所,一个unityshader通常会定义一个Base Pas(也可以定义多次,例如双面渲染就需要两次等)以及一个add pass,一个base pass仅会执行一次,而一个add pass会执行多次。
E.用同一个add pass在处理不同的光源类型时,可以通过使用宏来做出判断,比如计算光的方向,
```cg
#ifdef USING_DIRECTIONAL_LIGHT
fixed3 worldLightDir=normalize(_WorldSpaceLightPos0.xyz);
#else
fixed3 worldLightDir=normalize(_WorldSpaceLightPos0.xyz-i.worldPos.xyz);
#endif
```
## 延迟渲染
1. 第一个Pass用于渲染G-Pass,把物体的漫反射颜色/高光反射颜色/平滑度/法线/自发光/深度等信息渲染到Gbuffer
2. 根据G-buffer的数值计算最终的光照颜色,再存储到缓冲中。
<file_sep>int maxsumofSubarray(vector<int>& arr)
{
if (arr.size() == 0)
{
return 0;
}
if (arr.size() == 1)
{
return arr[0];
}
int max = arr[0];
int end_index = 0;
int relink_cost = 0;
for (int i = 1; i < arr.size(); ++i)
{
//判断是否可以续链
if (end_index == i - 1)
{
//判断取 arr[i] 与 max + arr[i] 与 max 的最大值,若取max 则不续链
if (max > arr[i] && max > max + arr[i])
{
max = max;
//此时已经断链了,需要增加relink_cost
relink_cost += arr[i];
}
else
{
end_index = i;
//如果单取一个元素大于之前的累加,则单取元素
if (arr[i] >= max + arr[i])
{
max = arr[i];
}
else
{
max = arr[i] + max;
}
}
}
//若不可续链,则判断arr[i] 与 max 的最大值
else
{
if (arr[i] >= max)
{
max = arr[i];
end_index = i;
relink_cost = 0;
}
else
{
relink_cost += arr[i];
//接链收益大,则接链
if (relink_cost + max >= max)
{
max = relink_cost + max;
end_index = i;
relink_cost = 0;
}
}
}
}
return max;
}<file_sep>//679. 24 点游戏
//你有 4 张写有 1 到 9 数字的牌。你需要判断是否能通过 *,/,+,-,(,) 的运算得到 24。
//示例 1:
//输入:[4, 1, 8, 7]
//输出: True
//解释: (8 - 4) * (7 - 1) = 24
//示例 2:
//输入:[1, 2, 1, 2]
//输出: False
//注意:
//除法运算符 / 表示实数除法,而不是整数除法。例如 4 / (1 - 2 / 3) = 12 。
//每个运算符对两个数进行运算。特别是我们不能用 - 作为一元运算符。例如,[1, 1, 1, 1] 作为输入时,表达式 - 1 - 1 - 1 - 1 是不允许的。
//你不能将数字连接在一起。例如,输入为[1, 2, 1, 2] 时,不能写成 12 + 12 。
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/24-game
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//思路
//暴力, 维护一个数字池,
using System;
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
private static int Point24Add = 0, Point24Minus = 2, Point24Multiply = 1, Point24Divided = 3;
private static double MiniGap = 0.0000001f;
public bool JudgePoint24(int[] nums)
{
List<double> list = new List<double>();
for (int i = 0; i < nums.Length; ++i)
{
list.Add(nums[i]);
}
double a = 9, b = 1;
//Console.WriteLine(a - b);
return Solve(list);
}
public bool Solve(List<Double> list)
{
if (list.Count == 0)
{
return false;
}
if (list.Count == 1)
{
return Math.Abs(list[0] - 24) < MiniGap;
}
int size = list.Count;
if (size == 3)
{
//Console.WriteLine(string.Format("{0},{1},{2}", list[0], list[1], list[2]));
}
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (i != j)
{
List<Double> list2 = new List<Double>();
for (int k = 0; k < size; k++)
{
if (k != i && k != j)
{
list2.Add(list[k]);
}
}
for (int k = 0; k < 4; k++)
{
if ( k < 2 && i > j)
{
continue;
}
if (k == Point24Add)
{
list2.Add(list[i] + list[j]);
}
else if (k == Point24Multiply)
{
list2.Add(list[i] * list[j]);
}
else if (k == Point24Minus)
{
list2.Add(list[i] - list[j]);
}
else if (k == Point24Divided)
{
if (Math.Abs(list[j]) < MiniGap)
{
continue;
}
else
{
list2.Add(list[i] / list[j]);
}
}
if (Solve(list2))
{
return true;
}
list2.RemoveAt(list2.Count - 1);
}
}
}
}
return false;
}
private bool JudgePoint24Permuation(int d1, int d2, int d3, int d4)
{
List<double> listd1 = CalculateFormular(d1, d2);
List<double> listd2 = CalculateFormular(d3, d4);
for (int i = 0; i < listd1.Count; ++i)
{
for (int j = 0; j < listd2.Count; ++j)
{
if (JudgePoint24ByTwoDigit(listd1[i], listd2[j]))
{
return true;
}
}
}
return false;
}
private List<double> CalculateFormular(double a, double b)
{
List<double> ret = new List<double>();
ret.Add(a + b);
ret.Add(a - b);
ret.Add(b - a);
if (Math.Abs(a) > MiniGap && Math.Abs(b) > MiniGap)
{
ret.Add(a * b);
ret.Add(a / b);
ret.Add(b / a);
}
return ret;
}
private bool JudgePoint24ByTwoDigit(double a, double b)
{
if (Math.Abs(a + b - 24) < MiniGap)
{
return true;
}
else if (Math.Abs(a * b -24) < MiniGap)
{
return true;
}
else if (Math.Abs(a - b - 24) < MiniGap || Math.Abs(b-a-24)< MiniGap)
{
return true;
}
else if (Math.Abs (a) > MiniGap && Math.Abs(b) > MiniGap && ((Math.Abs(a / b -24) < MiniGap) || Math.Abs(b/a - 24) < MiniGap))
{
return true;
}
else
{
return false;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
public class CLargestRectangleArea
{
public int LargestRectangleArea(int[] heights)
{
int max_area = 0;
Stack<int> stack = new Stack<int>();
for (int i = 0; i < heights.Length; ++i)
{
while (stack.Count>0 && heights[stack.Peek()] >= heights[i])
{
int index = stack.Peek();
stack.Pop();
int left_less_index = stack.Count==0 ? -1 : stack.Peek();
int area = heights[index] * (i - (left_less_index + 1));
if (area > max_area)
{
max_area = area;
}
}
stack.Push(i);
}
while (stack.Count> 0)
{
int index = stack.Peek();
stack.Pop();
int left_less_index = stack.Count==0 ? -1 : stack.Peek();
int area = heights[index] * (heights.Length - (left_less_index + 1));
if (area > max_area)
{
max_area = area;
}
}
return max_area;
}
}
public class SortedStack<T> where T : IComparable<T>
{
public bool IsIncrement { get; private set; }
private Stack<T> container;
public SortedStack(bool _isIncrement)
{
IsIncrement = _isIncrement;
}
public void Push(T item)
{
while (container.Count > 0)
{
if ((container.Peek().CompareTo(item) >0) != IsIncrement)
{
container.Push(item);
return;
}
else
{
container.Pop();
}
}
}
public T Peek()
{
return container.Peek();
}
}
}
<file_sep>//4. 寻找两个正序数组的中位数
//给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。
//进阶:你能设计一个时间复杂度为 O(log (m+n)) 的算法解决此问题吗?
//示例 1:
//输入:nums1 = [1, 3], nums2 = [2]
//输出:2.00000
//解释:合并数组 = [1, 2, 3] ,中位数 2
//示例 2:
//输入:nums1 = [1, 2], nums2 = [3, 4]
//输出:2.50000
//解释:合并数组 = [1, 2, 3, 4] ,中位数(2 + 3) / 2 = 2.5
//示例 3:
//输入:nums1 = [0, 0], nums2 = [0, 0]
//输出:0.00000
//示例 4:
//输入:nums1 = [], nums2 = [1]
//输出:1.00000
//示例 5:
//输入:nums1 = [2], nums2 = []
//输出:2.00000
//提示:
//nums1.length == m
//nums2.length == n
//0 <= m <= 1000
//0 <= n <= 1000
//1 <= m + n <= 2000
//- 10^6 <= nums1[i], nums2[i] <= 10^6
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//思路:
// 1. 二分查找 先剔除K/2的元素,再剔除K/4元素, 直到K个元素在最前
using System;
namespace ByteDancePopular
{
public partial class Solution
{
public double FindMedianSortedArrays(int[] nums1, int[] nums2)
{
int m = nums1.Length;
int n = nums2.Length;
//奇数为中位数
double ret = 0;
//偶数要取中间两个值
if ((m + n)%2 == 0)
{
int median1 = GetKthElement(nums1, nums2, (m + n) / 2 + 1);
int median2 = GetKthElement(nums1, nums2, (m + n) / 2);
ret = (double)(median1 + median2) * 0.5f;
}
else
{
ret = GetKthElement(nums1, nums2, (m + n) / 2 + 1);
}
return ret;
}
/// <summary>
/// 返回第N个数
/// </summary>
/// <returns></returns>
private int GetKthElement(int[] nums1, int[] nums2, int k)
{
int m = nums1.Length;
int n = nums2.Length;
int index1 = 0, index2 = 0;
while (true)
{
if (index1 == m)
{
return nums2[index2 + k - 1];
}
if (index2 == n)
{
return nums1[(index1 + k - 1)];
}
if (k == 1)
{
return Math.Min(nums1[index1], nums2[index2]);
}
int half = k / 2;
int newIndex1 = Math.Min(half + index1, m) - 1;
int newIndex2 = Math.Min(half + index2, n) - 1;
int a = nums1[newIndex1];
int b = nums2[newIndex2];
if (a < b)
{
k -= (newIndex1 - index1 + 1);
index1 = newIndex1 + 1;
}
else
{
k -= (newIndex2 - index2 + 1);
index2 = newIndex2 + 1;
}
}
}
}
}<file_sep> ListNode* removeNthFromEnd(ListNode* head, int n)
{
// write code here
if(head == nullptr || n <=0)
{
return head;
}
ListNode* low = head;
ListNode* fast = head;
while(n-- && fast)
{
fast = fast->next;
}
if (fast == NULL)
{
return head->next;
}
while(fast->next != NULL)
{
fast = fast->next;
low = low->next;
}
low->next = low->next->next;
return head;
}<file_sep>//440.字典序的第K小数字
//给定一个整数 n, 返回从 1 到 n 的字典顺序。
//例如,
//给定 n =1 3,返回 [1,10,11,12,13,2,3,4,5,6,7,8,9] 。
//请尽可能的优化算法的时间复杂度和空间复杂度。 输入的数据 n 小于等于 5,000,000。
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/lexicographical-numbers
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//N叉树的前序遍历
using System;
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
public IList<int> LexicalOrder(int n)
{
List<int> ret = new List<int>();
for (int i = 1; i <= 9; ++i)
{
DfsTenBranchTree(ret, i, n);
}
return ret;
}
private void DfsTenBranchTree(List<int> list, int num, int max)
{
if (num > max)
{
return;
}
list.Add(num);
for (int i =0; i <= 9; ++i)
{
DfsTenBranchTree(list, num * 10 + i, max);
}
}
}
}<file_sep>// 726. 原子的数量
// https://leetcode-cn.com/problems/number-of-atoms/
using System;
using System.Collections.Generic;
using System.Text;
namespace ByteDancePopular
{
public partial class Solution
{
bool IsUpper(char c) { return c >= 'A' && c <= 'Z'; }
bool IsLower(char c) { return c >= 'a' && c <= 'z'; }
bool IsDigit(char c) { return c >= '0' && c <= '9'; }
public string CountOfAtoms(string formula)
{
Dictionary<string,int> ret = Parse(formula, 0, formula.Length - 1);
List<string> sortKey = new List<string>();
foreach(string key in ret.Keys)
{
sortKey.Add(key);
}
sortKey.Sort();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sortKey.Count; ++i)
{
string key = sortKey[i];
sb.Append(key);
if (ret[key] > 1)
{
sb.Append(ret[key]);
}
}
return sb.ToString();
}
public int index;
public Dictionary<string, int> Parse(string formula, int l, int r)
{
index = r;
Dictionary<string, int> ret = new Dictionary<string, int>();
int val = 1;
string atom = "";
while (index >= l)
{
//第一次数字
if (IsDigit(formula[index]))
{
Stack<int> dig = new Stack<int>();
dig.Push(formula[index] - '0');
index--;
//向前查找连续数字
while (index>=l && IsDigit(formula[index]))
{
dig.Push(formula[index] - '0');
index--;
}
//
val = 0;
while (dig.Count != 0)
{
val = dig.Pop() + val *10;
}
}
else if (IsLower(formula[index]))
{
index--;
StringBuilder sb = new StringBuilder();
sb.Append(formula[index]);
sb.Append(formula[index + 1]);
atom = sb.ToString();
if (!ret.ContainsKey(atom))
{
ret[atom] = 0;
}
ret[atom] += val;
index--;
//重置回默认系数
val = 1;
}
else if (IsUpper(formula[index]))
{
atom = formula[index].ToString();
if (!ret.ContainsKey(atom))
{
ret[atom] = 0;
}
ret[atom] += val;
index--;
//重置回默认系数
val = 1;
}
//如果是括号,递归
else if (formula[index] == ')')
{
index--;
Merge(ret,Parse(formula, l, index), val);
val = 1;
}
//结束的括号,退出一层递归
else if (formula[index] == '(')
{
index--;
val = 1;
return ret;
}
}
return ret;
}
public void Merge(Dictionary<string, int> main, Dictionary<string ,int> sub, int multiply)
{
foreach(string key in sub.Keys)
{
if (!main.ContainsKey(key))
{
main[key] = 0;
}
main[key] += multiply * sub[key];
}
}
}
}
<file_sep>//135.分发糖果
//老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。
//你需要按照以下要求,帮助老师给这些孩子分发糖果:
//每个孩子至少分配到 1 个糖果。
//相邻的孩子中,评分高的孩子必须获得更多的糖果。
//那么这样下来,老师至少需要准备多少颗糖果呢?
//示例 1:
//输入:[1,0,2]
//输出: 5
//解释: 你可以分别给这三个孩子分发 2、1、2 颗糖果。
//示例 2:
//输入:[1,2,2]
//输出: 4
//解释: 你可以分别给这三个孩子分发 1、2、1 颗糖果。
// 第三个孩子只得到 1 颗糖果,这已满足上述两个条件。
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/candy
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//思路
// 1. 从左到右遍历,只要右边比左边大,则右边为左边加一
// 2. 从右到左遍历,只要左边比右边大,则左边比右边加一
using System;
namespace ByteDancePopular
{
public partial class Solution
{
public int Candy(int[] ratings)
{
if (ratings == null || ratings.Length == 0)
{
return 0;
}
if (ratings.Length == 1)
{
return 1;
}
int[] candice = new int[ratings.Length];
//全部只给1颗
for(int i = 0; i < ratings.Length; ++i)
{
candice[i] = 1;
}
for (int i = 1; i < ratings.Length; ++i)
{
if (ratings[i] > ratings[i-1])
{
candice[i] = Math.Max(candice[i - 1] + 1, candice[i]);
}
}
for (int i = ratings.Length -2; i >= 0; --i)
{
if (ratings[i] > ratings[i+1])
{
candice[i] = Math.Max(candice[i + 1] + 1, candice[i]);
}
}
int ret = 0;
for (int i = 0; i < candice.Length; ++i)
{
ret += candice[i];
}
return ret;
}
}
}<file_sep>
//407 接雨水 https://www.youtube.com/watch?v=cJayBq38VYw
// """
// 水从高出往低处流,某个位置储水量取决于四周最低高度,从最外层向里层包抄,用小顶堆动态找到未访问位置最小的高度
// """
using System;
namespace ByteDancePopular
{
public partial class Solution
{
private class RainTrapBlock:IComparable<RainTrapBlock>
{
public int row;
public int col;
public int h;
public RainTrapBlock(int _r, int _c, int _h)
{
row = _r;
col = _c;
h = _h;
}
public int CompareTo(RainTrapBlock other)
{
if (other.h > h)
{
return -1;
}
else if (other.h < h)
{
return 1;
}
else
{
return 0;
}
}
}
public int TrapRainWater(int[][] heightMap)
{
int m = heightMap.Length;
int n = heightMap[0].Length;
//防止扩容
PriorityQueue<RainTrapBlock> border = new PriorityQueue<RainTrapBlock>(2*(m+n+20));
bool[][] vistid = new bool[m][];
//边界先入优先队列
for (int i = 0; i < m; ++i)
{
vistid[i] = new bool[n];
border.Enqueue(new RainTrapBlock(i, 0, heightMap[i][0]));
vistid[i][0] = true;
border.Enqueue(new RainTrapBlock(i, n - 1, heightMap[i][n - 1]));
vistid[i][n - 1] = true;
}
for (int i = 1; i < n-1; ++i)
{
vistid[0][i] = true;
vistid[m - 1][i] = true;
border.Enqueue(new RainTrapBlock(0, i, heightMap[0][i]));
border.Enqueue(new RainTrapBlock(m - 1, i, heightMap[m - 1][i]));
}
int currentMax = border.Peek().h;
int trapSum = 0;
while(border.Count >0)
{
RainTrapBlock block = border.Dequue();
//边界无法储水
if (block.row == 0 || block.row == m-1 || block.col == n-1 || block.col == 0)
{
}
else
{
if (block.h < currentMax)
{
trapSum += currentMax - block.h;
}
}
currentMax = Math.Max(currentMax, block.h);
//上
if (block.row-1 >0 && block.row - 1< m-1 && !vistid[block.row - 1][block.col])
{
border.Enqueue(new RainTrapBlock(block.row - 1, block.col, heightMap[block.row - 1][block.col]));
vistid[block.row - 1][block.col] = true;
}
//下
if (block.row + 1 > 0 && block.row + 1 < m - 1 && !vistid[block.row + 1][block.col])
{
border.Enqueue(new RainTrapBlock(block.row + 1, block.col, heightMap[block.row + 1][block.col]));
vistid[block.row + 1][block.col] = true;
}
//左
if (block.col -1 > 0 && block.col - 1 < n - 1 && !vistid[block.row][block.col-1])
{
border.Enqueue(new RainTrapBlock(block.row, block.col-1, heightMap[block.row][block.col-1]));
vistid[block.row][block.col-1] = true;
}
//右
if (block.col + 1 > 0 && block.col + 1 < n - 1 && !vistid[block.row][block.col + 1])
{
border.Enqueue(new RainTrapBlock(block.row, block.col +1, heightMap[block.row][block.col + 1]));
vistid[block.row][block.col+1] = true;
}
}
return trapSum;
}
}
}<file_sep> vector<vector<int> > threeOrders(TreeNode* root)
{
vector<vector<int>> result(3);
if (root == NULL)
{
return result;
}
travel_deep(root, result);
}
void travel_deep(TreeNode* root, vector<vector<int>> &result)
{
if (root)
{
result[0].push_back(root->val);
travel_deep(root->left, result);
result[1].push_back(root->val);
travel_deep(root->right, result);
result[2].push_back(root->val);
}
}<file_sep>using System;
using System.Collections.Generic;
public class CMinTransfer
{
public int MinTransfers(int[][] transactions)
{
int res = int.MaxValue;
Dictionary<int, int> loans = new Dictionary<int, int>();
int[] accounts;
if (transactions == null || transactions.Length == 0)
{
return 0;
}
for (int i = 0; i < transactions.Length; ++i)
{
int[] lend = transactions[i];
int lender = lend[0];
int borrower = lend[1];
if (!loans.ContainsKey(lender))
{
loans[lender] = 0;
}
if (!loans.ContainsKey(borrower))
{
loans[borrower] = 0;
}
loans[lender] += lend[2];
loans[borrower] -= lend[2];
}
accounts = new int[loans.Values.Count];
loans.Values.CopyTo(accounts, 0);
DFS(0, 0, ref res, ref accounts);
return res;
}
public void DFS(int index, int count, ref int res, ref int[] accounts)
{
if (count >= res) return;
while (index < accounts.Length &&accounts[index] == 0)
{
index++;
}
if (index == accounts.Length)
{
res = Math.Min(res, count);
return;
}
if (index == accounts.Length)
{
res = Math.Min(res, count);
return;
}
for (int j = index + 1; j < accounts.Length; ++j)
{
if (accounts[index] * accounts[j] < 0)
{
accounts[j] += accounts[index];
DFS(index + 1, count + 1, ref res, ref accounts);
accounts[j] -= accounts[index];
}
}
}
}
<file_sep>//460.LFU 缓存
//请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。
//实现 LFUCache 类:
//LFUCache(int capacity) -用数据结构的容量 capacity 初始化对象
//int get(int key) -如果键存在于缓存中,则获取键的值,否则返回 - 1。
//void put(int key, int value) -如果键已存在,则变更其值;如果键不存在,请插入键值对。当缓存达到其容量时,则应该在插入新项之前,使最不经常使用的项无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最久未使用 的键。
//注意「项的使用次数」就是自插入该项以来对其调用 get 和 put 函数的次数之和。使用次数会在对应项被移除后置为 0 。
//进阶:
//你是否可以在 O(1) 时间复杂度内执行两项操作?
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/lfu-cache
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//设计思路:
// 1. 一个是记载数据的双向链表
// 2. 一个是记载频次的双向链表
using System.Collections.Generic;
public class LFUCache
{
public class DLinkedNode
{
public int key;
public int val;
public int freq;
public DLinkedNode() { }
public DLinkedNode(int _key, int _val)
{
key = _key;
val = _val;
freq = 1;
}
}
private Dictionary<int, DLinkedNode> cache;
private Dictionary<int, LinkedList<DLinkedNode>> freqDict;
public int Capacity;
private int minFreq = 1;
public LFUCache(int capacity)
{
cache = new Dictionary<int, DLinkedNode>(capacity);
freqDict = new Dictionary<int, LinkedList<DLinkedNode>>();
Capacity = capacity;
}
public int Get(int key)
{
//判断容量为0的情况
if (Capacity == 0) return -1;
if (cache.ContainsKey(key))
{
//移除在原freq列表里的元素,添加到新列表里
freqDict[cache[key].freq].Remove(cache[key]);
//移除之后判断列表是否为空更新minifreq
if (freqDict[minFreq].Count == 0)
{
if (minFreq == cache[key].freq)
{
minFreq++;
}
}
cache[key].freq++;
if (!freqDict.ContainsKey(cache[key].freq))
{
freqDict[cache[key].freq] = new LinkedList<DLinkedNode>();
}
freqDict[cache[key].freq].AddLast(cache[key]);
return cache[key].val;
}
else
{
return -1;
}
}
public void Put(int key, int value)
{
//判断容量为0的情况
if (Capacity == 0) return;
if (cache.ContainsKey(key))
{
cache[key].val = value;
freqDict[cache[key].freq].Remove(cache[key]);
//当链表为空,则minifreq为此频率时,minifreq++;
if (freqDict[minFreq].Count == 0)
{
if (minFreq == cache[key].freq)
{
minFreq++;
}
}
cache[key].freq++;
}
else
{
//若超出容量则要移除
if (cache.Count == Capacity)
{
int rm_key = freqDict[minFreq].First.Value.key;
freqDict[minFreq].RemoveFirst();
cache.Remove(rm_key);
}
cache[key] = new DLinkedNode(key, value);
minFreq = 1;
}
if (!freqDict.ContainsKey(cache[key].freq))
{
freqDict[cache[key].freq] = new LinkedList<DLinkedNode>();
}
freqDict[cache[key].freq].AddLast(cache[key]);
}
}<file_sep>//316.去除重复字母
//单调栈
//给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
//注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/remove-duplicate-letters
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
using System;
using System.Text;
namespace ByteDancePopular
{
public partial class Solution
{
public string RemoveDuplicateLetters(string s)
{
bool[] visited = new bool[26];
int[] nums = new int[26];
for (int i = 0; i < s.Length; ++i)
{
nums[s[i] - 'a']++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; ++i)
{
//当遍历到字符串上的某个字符时,判断是否比当前末尾的字符小,如果比当前末尾的字符小,且末尾字符在后续还会出现,则移除末尾字符,替换为当前字符
char ch = s[i];
int index = ch - 'a';
if (!visited[index])
{
if (sb.Length>0)
{
char lastCh = sb[sb.Length - 1];
while (sb.Length > 0 && ch < lastCh && nums[lastCh - 'a'] > 0)
{
sb.Remove(sb.Length - 1, 1);
visited[lastCh - 'a'] = false;
if (sb.Length > 0)
{
lastCh = sb[sb.Length - 1];
}
else
{
break;
}
}
}
sb.Append(ch);
visited[index] = true;
}
nums[index]--;
}
return sb.ToString();
}
}
}<file_sep>//31. 下一个排列
//实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
//如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
//必须 原地 修改,只允许使用额外常数空间。
//示例 1:
//输入:nums = [1,2,3]
//输出:[1,3,2]
//示例 2:
//输入:nums = [3, 2, 1]
//输出:[1,2,3]
//示例 3:
//输入:nums = [1, 1, 5]
//输出:[1,5,1]
//示例 4:
//输入:nums = [1]
//输出:[1]
//提示:
//1 <= nums.length <= 100
//0 <= nums[i] <= 100
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/next-permutation
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
using System;
using System.Collections.Generic;
//思路
//前序遍历找到递增的位置,倒序遍历找到比这个值大一点的数
namespace ByteDancePopular
{
public partial class Solution
{
public void NextPermutation(int[] nums)
{
//需要替换的位置
int incrementIndex = -1;
int val = -1;
for (int i = nums.Length -1; i >= 1; --i)
{
if (nums[i] > nums[i-1])
{
incrementIndex = i - 1;
val = nums[incrementIndex];
break;
}
}
//则为全递减排列,直接反转
if (incrementIndex == -1)
{
ReversePermutation(ref nums, 0, nums.Length -1);
return;
}
int nextIndex = incrementIndex + 1;
int nextVal = nums[nextIndex];
for (int i = nums.Length - 1; i > incrementIndex; --i)
{
if (nums[i] > val)
{
if (nextVal >= nums[i])
{
nextVal = nums[i];
nextIndex = Math.Max(i, nextIndex);
}
}
}
//交换位置
nums[incrementIndex] = nextVal;
nums[nextIndex] = val;
ReversePermutation(ref nums, incrementIndex + 1, nums.Length - 1);
}
private void ReversePermutation(ref int[] nums, int left, int right)
{
int tmp = -1;
while (left < right)
{
tmp = nums[left];
nums[left] = nums[right];
nums[right] = tmp;
left++;
right--;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
// Demonstrate a Priority Queue implemented with a Binary Heap
namespace PriorityQueues
{
class PriorityQueuesProgram
{
static void Main(string[] args)
{
Console.WriteLine("\nBegin Priority Queue demo");
Console.WriteLine("\nCreating priority queue of Employee items\n");
PriorityQueue<Employee> pq = new PriorityQueue<Employee>();
Employee e1 = new Employee("Aiden", 1.0);
Employee e2 = new Employee("Baker", 2.0);
Employee e3 = new Employee("Chung", 3.0);
Employee e4 = new Employee("Dunne", 4.0);
Employee e5 = new Employee("Eason", 5.0);
Employee e6 = new Employee("Flynn", 6.0);
Console.WriteLine("Adding " + e5.ToString() + " to priority queue");
pq.Enqueue(e5);
Console.WriteLine("Adding " + e3.ToString() + " to priority queue");
pq.Enqueue(e3);
Console.WriteLine("Adding " + e6.ToString() + " to priority queue");
pq.Enqueue(e6);
Console.WriteLine("Adding " + e4.ToString() + " to priority queue");
pq.Enqueue(e4);
Console.WriteLine("Adding " + e1.ToString() + " to priority queue");
pq.Enqueue(e1);
Console.WriteLine("Adding " + e2.ToString() + " to priority queue");
pq.Enqueue(e2);
Console.WriteLine("\nPriory queue is: ");
Console.WriteLine(pq.ToString());
Console.WriteLine("\n");
Console.WriteLine("Removing an employee from priority queue");
Employee e = pq.Dequeue();
Console.WriteLine("Removed employee is " + e.ToString());
Console.WriteLine("\nPriory queue is now: ");
Console.WriteLine(pq.ToString());
Console.WriteLine("\n");
Console.WriteLine("Removing a second employee from queue");
e = pq.Dequeue();
Console.WriteLine("\nPriory queue is now: ");
Console.WriteLine(pq.ToString());
Console.WriteLine("\n");
Console.WriteLine("Testing the priority queue");
TestPriorityQueue(50000);
Console.WriteLine("\nEnd Priority Queue demo");
Console.ReadLine();
} // Main()
static void TestPriorityQueue(int numOperations)
{
Random rand = new Random(0);
PriorityQueue<Employee> pq = new PriorityQueue<Employee>();
for (int op = 0; op < numOperations; ++op)
{
int opType = rand.Next(0, 2);
if (opType == 0) // enqueue
{
string lastName = op + "man";
double priority = (100.0 - 1.0) * rand.NextDouble() + 1.0;
pq.Enqueue(new Employee(lastName, priority));
if (pq.IsConsistent() == false)
{
Console.WriteLine("Test fails after enqueue operation # " + op);
}
}
else // dequeue
{
if (pq.Count() > 0)
{
Employee e = pq.Dequeue();
if (pq.IsConsistent() == false)
{
Console.WriteLine("Test fails after dequeue operation # " + op);
}
}
}
} // for
Console.WriteLine("\nAll tests passed");
} // TestPriorityQueue
} // class PriorityQueuesProgram
// ===================================================================
public class Employee : IComparable<Employee>
{
public string lastName;
public double priority; // smaller values are higher priority
public Employee(string lastName, double priority)
{
this.lastName = lastName;
this.priority = priority;
}
public override string ToString()
{
return "(" + lastName + ", " + priority.ToString("F1") + ")";
}
public int CompareTo(Employee other)
{
if (this.priority < other.priority) return -1;
else if (this.priority > other.priority) return 1;
else return 0;
}
} // Employee
// ===================================================================
public class PriorityQueue<T> where T : IComparable<T>
{
private List<T> data;
public PriorityQueue()
{
this.data = new List<T>();
}
public void Enqueue(T item)
{
data.Add(item);
int ci = data.Count - 1; // child index; start at end
while (ci > 0)
{
int pi = (ci - 1) / 2; // parent index
if (data[ci].CompareTo(data[pi]) >= 0) break; // child item is larger than (or equal) parent so we're done
T tmp = data[ci]; data[ci] = data[pi]; data[pi] = tmp;
ci = pi;
}
}
public T Dequeue()
{
// assumes pq is not empty; up to calling code
int li = data.Count - 1; // last index (before removal)
T frontItem = data[0]; // fetch the front
data[0] = data[li];
data.RemoveAt(li);
--li; // last index (after removal)
int pi = 0; // parent index. start at front of pq
while (true)
{
int ci = pi * 2 + 1; // left child index of parent
if (ci > li) break; // no children so done
int rc = ci + 1; // right child
if (rc <= li && data[rc].CompareTo(data[ci]) < 0) // if there is a rc (ci + 1), and it is smaller than left child, use the rc instead
ci = rc;
if (data[pi].CompareTo(data[ci]) <= 0) break; // parent is smaller than (or equal to) smallest child so done
T tmp = data[pi]; data[pi] = data[ci]; data[ci] = tmp; // swap parent and child
pi = ci;
}
return frontItem;
}
public T Peek()
{
T frontItem = data[0];
return frontItem;
}
public int Count()
{
return data.Count;
}
public override string ToString()
{
string s = "";
for (int i = 0; i < data.Count; ++i)
s += data[i].ToString() + " ";
s += "count = " + data.Count;
return s;
}
public bool IsConsistent()
{
// is the heap property true for all data?
if (data.Count == 0) return true;
int li = data.Count - 1; // last index
for (int pi = 0; pi < data.Count; ++pi) // each parent index
{
int lci = 2 * pi + 1; // left child index
int rci = 2 * pi + 2; // right child index
if (lci <= li && data[pi].CompareTo(data[lci]) > 0) return false; // if lc exists and it's greater than parent then bad.
if (rci <= li && data[pi].CompareTo(data[rci]) > 0) return false; // check the right child too.
}
return true; // passed all checks
} // IsConsistent
} // PriorityQueue
} // ns
<file_sep>---
layout: post
title: "Unity 协程与进程"
subtitle: " \"面试小记\""
date: 2020-11-15 09:44:09
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- Unity3d
---
> “面试知识点整理”
# 协程和进程和线程的区别
1. 进程拥有自己独立的堆和栈,既不共享堆,亦不共享栈,进程由操作系统调度。
2. 线程拥有自己独立的栈和共享的堆,共享堆,不共享栈,线程亦由操作系统调度(标准线程是的)。
3. 协程和线程一样共享堆,不共享栈,协程由程序员在协程的代码里显示调度。
### Unity协程执行原理
unity中协程执行过程中,通过yield return XXX,将程序挂起,去执行接下来的内容,注意协程不是线程,在为遇到yield return XXX语句之前,协程额方法和一般的方法是相同的,也就是程序在执行到yield return XXX语句之后,接着才会执行的是 StartCoroutine()方法之后的程序,走的还是单线程模式,仅仅是将yield return XXX语句之后的内容暂时挂起,等到特定的时间才执行。
那么挂起的程序什么时候才执行,也就是协同程序主要是update()方法之后,lateUpdate()方法之前调用的
### 迭代器
在使用协程的时候,我们总是要声明一个返回值为**IEnumerator**的函数,并且函数中会包含**yield return xxx**或者**yield break**之类的语句。就像文档里写的这样
```java
private IEnumerator WaitAndPrint(float waitTime)
{
yield return new WaitForSeconds(waitTime);
print("Coroutine ended: " + Time.time + " seconds");
}
```
想要理解IEnumerator和yield就不得不说一下迭代器。迭代器是C#中一个十分强大的功能,只要类继承了IEnumerable接口或者实现了GetEnumerator()方法就可以使用foreach去遍历类,遍历输出的结果是根据GetEnumerator()的返回值IEnumerator确定的,为了实现IEnumerator接口就不得不写一堆繁琐的代码,而yield关键字就是用来简化这一过程的。是不是很绕,理解这些内容需要花些时间。
**不理解也没关系,目前只需要明白一件事,当在IEnumerator函数中使用yield return语句时,每使用一次,迭代器中的元素内容就会增加一个。就向往列表中添加元素一样,每Add一次元素内容就会多一个。**
```c#
IEnumerator TestCoroutine()
{
yield return null; //返回内容为null
yield return 1; //返回内容为1
yield return "sss"; //返回内容为"sss"
yield break; //跳出,类似普通函数中的return语句
yield return 999; //由于break语句,该内容无法返回
}
void Start()
{
IEnumerator e = TestCoroutine();
while (e.MoveNext())
{
Debug.Log(e.Current); //依次输出枚举接口返回的值
}
}
/* 枚举接口的定义
public interface IEnumerator
{
object Current
{
get;
}
bool MoveNext();
void Reset();
}*/
/*运行结果:
Null
1
sss
*/
```
首先注意注释部分枚举接口的定义
Current属性为只读属性,返回枚举序列中的当前位的内容
MoveNext()把枚举器的位置前进到下一项,返回布尔值,新的位置若是有效的,返回true;否则返回false
Reset()将位置重置为原始状态
**再看下Start函数中的代码,就是将yield return 语句中返回的值依次输出。**
**第一次MoveNext()后,Current位置指向了yield return 返回的null,该位置是有效的(这里注意区分位置有效和结果有效,位置有效是指当前位置是否有返回值,即使返回值是null;而结果有效是指返回值的结果是否为null,显然此处返回结果是无意义的)所以MoveNext()返回值是true;
第二次MoveNext()后,Current新位置指向了yield return 返回的1,该位置是有效的,MoveNext()返回true
第三次MoveNext()后,Current新位置指向了yield return 返回的"sss",该位置也是有效的,MoveNext()返回true
第四次MoveNext()后,Current新位置指向了yield break,无返回值,即位置无效,MoveNext()返回false,至此循环结束**
最后输出的运行结果跟我们分析是一致的。关于C#是如何实现迭代器的功能,有兴趣的可以看下容器类源码中关于迭代器部分的实现就明白了,[MSDN](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/iterators)上也有关于迭代器的详细讲解。
### 原理
先来回顾下Unity的协程具体有些功能:
1. 将协程代码中由yield return语句分割的部分分配到每一帧去执行。
2. yield return 后的值是等待类([WaitForSeconds](https://docs.unity3d.com/ScriptReference/WaitForSeconds.html)、[WaitForFixedUpdate](https://docs.unity3d.com/ScriptReference/WaitForFixedUpdate.html))时需要等待相应时间。
3. yield return 后的值还是协程([Coroutine](https://docs.unity3d.com/ScriptReference/Coroutine.html))时需要等待嵌套部分协程执行完毕才能执行接下来内容。
```java
// case 1
IEnumerator Coroutine1()
{
//do something xxx //假如是第N帧执行该语句
yield return 1; //等一帧
//do something xxx //则第N+1帧执行该语句
}
// case 2
IEnumerator Coroutine2()
{
//do something xxx //假如是第N秒执行该语句
yield return new WaitForSeconds(2f); //等两秒
//do something xxx //则第N+2秒执行该语句
}
// case 3
IEnumerator Coroutine3()
{
//do something xxx
yield return StartCoroutine(Coroutine1()); //等协程Coroutine1执行完
//do something xxx
}
```
好了,知道了IEnumerator函数和yield return语法之后,在看到上面几个协程的功能,是不是对如何实现协程有点头绪了?
# 协程的实现
#### case1 : 分帧
实现分帧执行之前,先将上述迭代器的代码简单修改下,看下输出结果
```java
IEnumerator TestCoroutine()
{
Debug.Log("TestCoroutine 1");
yield return null;
Debug.Log("TestCoroutine 2");
yield return 1;
}
void Start()
{
IEnumerator e = TestCoroutine();
while (e.MoveNext())
{
Debug.Log(e.Current); //依次输出枚举接口返回的值
}
}
/*运行结果
TestCoroutine 1
Null
TestCoroutine 2
1
*/
```
前面有说过,每次MoveNext()后会返回yield return后的内容,那yield return之前的语句怎么办呢?
**当然也执行啊,遇到yield return语句之前的内容都会在MoveNext()时执行的。**
**到这里应该很清楚了,只要把MoveNext()移到每一帧去执行,不就实现分帧执行几段代码了么!**
既然要分配在每一帧去执行,那当然就是Update和LateUpdate了。**这里我个人喜欢将实现代码放在LateUpdate之中,为什么呢?因为Unity中协程的调用顺序是在Update之后,LateUpdate之前,所以这两个接口都不够准确**;但在LateUpdate中处理,至少能保证协程是在所有脚本的Update执行完毕之后再去执行。

现在可以实现最简单的协程了
```java
IEnumerator e = null;
void Start()
{
e = TestCoroutine();
}
void LateUpdate()
{
if (e != null)
{
if (!e.MoveNext())
{
e = null;
}
}
}
IEnumerator TestCoroutine()
{
Log("Test 1");
yield return null; //返回内容为null
Log("Test 2");
yield return 1; //返回内容为1
Log("Test 3");
yield return "sss"; //返回内容为"sss"
Log("Test 4");
yield break; //跳出,类似普通函数中的return语句
Log("Test 5");
yield return 999; //由于break语句,该内容无法返回
}
void Log(object msg)
{
Debug.LogFormat("<color=yellow>[{0}]</color>{1}", Time.frameCount, msg.ToString());
}
```

再来看看运行结果,黄色中括号括起来的数字表示当前在第几帧,很明显我们的协程完成了每一帧执行一段代码的功能。
#### case2: 延时等待
要是完全理解了case1的内容,相信你自己就能完成“延时等待”这一功能,其实就是加了个计时器的判断嘛!
**既然要识别自己的等待类,那当然要获取Current值根据其类型去判定是否需要等待。假如Current值是需要等待类型,那就延时到倒计时结束;而Current值是非等待类型,那就不需要等待,直接MoveNext()执行后续的代码即可。**
这里着重说下“延时到倒计时结束”。既然知道Current值是需要等待的类型,那此时肯定不能在执行MoveNext()了,否则等待就没用了;接下来当等待时间到了,就可以继续MoveNext()了。可以简单的加个标志位去做这一判断,同时驱动MoveNext()的执行。
```java
private void OnGUI()
{
if (GUILayout.Button("Test")) //注意:这里是点击触发,没有放在start里,为什么?
{
enumerator = TestCoroutine();
}
}
void LateUpdate()
{
if (enumerator != null)
{
bool isNoNeedWait = true, isMoveOver = true;
var current = enumerator.Current;
if (current is MyWaitForSeconds)
{
MyWaitForSeconds waitable = current as MyWaitForSeconds;
isNoNeedWait = waitable.IsOver(Time.deltaTime);
}
if (isNoNeedWait)
{
isMoveOver = enumerator.MoveNext();
}
if (!isMoveOver)
{
enumerator = null;
}
}
}
IEnumerator TestCoroutine()
{
Log("Test 1");
yield return null; //返回内容为null
Log("Test 2");
yield return 1; //返回内容为1
Log("Test 3");
yield return new MyWaitForSeconds(2f); //等待两秒
Log("Test 4");
}
```

运行结果里黄色表示当前帧,青色是当前时间,很明显等待了2秒(虽然有少许误差但总体不影响)。
**上述代码中,把函数触发放在了Button点击中而不是Start函数中?
这是因为我是用Time.deltaTime去做计时,假如放在了Start函数中,Time.deltaTime会受Awake这一帧执行时间影响,时间还不短(我测试时有0.1s左右),导致运行结果有很大误差,不到2秒就结束了,有兴趣的可以自己试一下~**
#### case3: 协程嵌套等待
协程嵌套等待也就是下面这种样子,在实际情况中使用的也不少。
```java
IEnumerator Coroutine1()
{
//do something xxx
yield return null;
//do something xxx
yield return StartCoroutine(Coroutine2()); //等待Coroutine2执行完毕
//do something xxx
yield return 3;
}
IEnumerator Coroutine2()
{
//do something xxx
yield return null;
//do something xxx
yield return 1;
//do something xxx
yield return 2;
}
```
实现原理的话基本与延时等待完全一致,这里我就不贴例子代码了,最后会放出完整工程的。
需要注意下协程嵌套时的执行顺序,先执行完内层嵌套代码再执行外层内容;即更新结束条件时要先更新内层协程(上例Coroutine2)在更新外层协程(上例Coroutine1)。<file_sep># Enum作Key的问题
**Dictionary**的key必须是唯一的标识,因此**Dictionary**需要对 key进行判等的操作,如果key的类型没有实现 IEquatable接口,则默认根据System.Object.Equals()和GetHashCode()方法判断值是否相等。我们可以看看常用作key的几种类型在.NET Framework中的定义:
``` csharp
public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<string>, IEnumerable, IEquatable<string>
public struct Int32 : IComparable, IFormattable, IConvertible, IComparable<int>, IEquatable<int>
public abstract class **Enum** : ValueType, IComparable, IFormattable, IConvertible
```
注意**Enum**类型的定义与前两种类型的不同,它并没有实现IEquatable接口。因此,当我们使用**Enum**类型作为key值时,**Dictionary**的内部操作就需要将**Enum**类型转换为System.Object,这就导致了Boxing的产生。它是导致**Enum**作为 key值的性能瓶颈。
<file_sep>using System;
//二叉堆 用于最大堆和最小堆的生成
public class BinaryHeap
{
public int[] tree;
public BinaryHeapNode root;
public int layer;
public int nodeCount;
public void Swap(int i, int j)
{
if (tree.Length <= i || tree.Length <=j)
{
return;
}
int tmp = tree[i];
tree[i] = tree[j];
tree[j] = tmp;
}
public void Heapify(int index, int count)
{
if (index > count)
{
return;
}
int c1 = index *2 +1;
int c2 = index*2+2;
int max = index;
if (c1 < count && tree[c1] > tree[max])
{
max = c1;
}
if (c2 <count && tree[c2] > tree[max])
{
max = c2;
}
if (max != index)
{
Swap(max, i);
Heapify(count, max);
}
}
//单个节点
public class BinaryHeapNode
{
public int value;
public BinaryHeapNode leftChild;
public BinaryHeapNode rightChild;
public void Swap(ref BinaryHeapNode node1, ref BinaryHeapNode node2)
{
int tmp = node2.value;
node2.value = node1.value;
node1.value = tmp;
}
//大根堆
public void Heapify()
{
if (leftChild!=null && leftChild.value> value)
{
if (rightChild != null)
{
if (leftChild.value> rightChild.value)
{
Swap(ref this, ref this.leftChild);
}
else
{
Swap(ref this, ref this.rightChild);
}
}
}
else if (rightChild != null && rightChild.value > value)
{
if (leftChild != null)
{
Swap(ref this, ref this.rightChild);
}
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using ByteDancePopular;
namespace ByteDancePopular
{
class MainClass
{
public static void Main(string[] args)
{
Console.Clear();
//Console.WriteLine("Hello World!");
Solution sol = new Solution();
int[] arr = new int[] { -1, 5, -7, 2, -1, 0, 7, 6, 2, 4};
sol.KConcatenationMaxSum(arr, 5);
//LRUCache cache = new LRUCache(2);
//cache.Put(1, 1);
//cache.Put(2, 2);
//cache.Get(1); // 返回 1
//cache.Put(3, 3); // 该操作会使得密钥 2 作废
//cache.Get(2); // 返回 -1 (未找到)
//cache.Put(4, 4); // 该操作会使得密钥 1 作废
//cache.Get(1); // 返回 -1 (未找到)
//cache.Get(3); // 返回 3
//cache.Get(4); // 返回 4
//LFUCache lFUCache = new LFUCache(0);
//lFUCache.Put(0, 0);
//lFUCache.Get(0);
//lFUCache.Put(2, 2);
//int p = lFUCache.Get(1); // 返回 1
//lFUCache.Put(3, 3); // 去除键 2
//p = lFUCache.Get(2); // 返回 -1(未找到)
//p = lFUCache.Get(3); // 返回 3
//lFUCache.Put(4, 4); // 去除键 1
//p = lFUCache.Get(1); // 返回 -1(未找到)
//p = lFUCache.Get(3); // 返回 3
//p = lFUCache.Get(4); // 返回 4
}
}
}
<file_sep>---
layout: post
title: "闭包与优化"
subtitle: " \"面试小记\""
date: 2020-11-15 09:44:09
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- Unity3d
- C#
---
> “面试知识点整理”
# 闭包
## 闭包的概念
> 内层的函数可以引用包含在它外层的函数的变量,即使外层函数的执行已经终止。但该变量提供的值并非变量创建时的值,而是在父函数范围内的最终值
## 闭包的优点
使用闭包,我们可以轻松的访问外层函数定义的变量,这在匿名方法中普遍使用。比如有如下场景,在winform应用程序中,我们希望做这么一个效果,当用户关闭窗体时,给用户一个提示框。我们将添加如下代码:
```c#
private void Form1_Load(object sender, EventArgs e)
{
string tipWords = "您将关闭当前对话框";
this.FormClosing += delegate
{
MessageBox.Show(tipWords);
};
}
```
若不使用匿名函数,我们就需要使用其他方式来将tipWords变量的值传递给FormClosing注册的处理函数,这就增加了不必要的工作量。
## 闭包陷阱
应用闭包,我们要注意一个陷阱。比如有一个用户信息的数组,我们需要遍历每一个用户,对各个用户做处理后输出用户名。
```c#
public class UserModel
{
public string UserName
{
get;
set;
}
public int UserAge
{
get;
set;
}
}
```
```c#
List<UserModel> userList = new List<UserModel>
{
new UserModel{ UserName="jiejiep", UserAge = 26},
new UserModel{ UserName="xiaoyi", UserAge = 25},
new UserModel{ UserName="zhangzetian", UserAge=24}
};
for(int i = 0 ; i < 3; i++)
{
ThreadPool.QueueUserWorkItem((obj) =>
{
//TODO
//Do some process...
//...
Thread.Sleep(1000);
UserModel u = userList[i];
Console.WriteLine(u.UserName);
});
}
```
我们预期的输出是, jiejiep, xiaoyi, zhangzetian
但是实际我们运行后发现,程序会报错,提示索引超出界限。
为什么没有达到我们预期的效果呢?让我们再来看一下闭包的概念。内层函数引用的外层函数的变量的最终值。就是说,当线程中执行方法时,方法中的i参数的值,始终是userList.Count。原来如此,那我们该如何
避免闭包陷阱呢?C#中普遍的做法是,将匿名函数引用的变量用一个临时变量保存下来,然后在匿名函数中使用临时变量。
```c#
List<UserModel> userList = new List<UserModel>
{
new UserModel{ UserName="jiejiep", UserAge = 26},
new UserModel{ UserName="xiaoyi", UserAge = 25},
new UserModel{ UserName="zhangzetian", UserAge=24}
};
for(int i = 0 ; i < 3; i++)
{
UserModel u = userList[i];
ThreadPool.QueueUserWorkItem((obj) =>
{
//TODO
//Do some process...
//...
Thread.Sleep(1000);
//UserModel u = userList[i];
Console.WriteLine(u.UserName);
});
}
```
## NET编译器与闭包
提出了问题,给出了解决方案,我们总算知道该怎么正确使用闭包了。但是dotNET是如何实现闭包的呢?执着的程序猿们,不会满足于这种表象的解决方案,让我们来看看dotNET是如何实现闭包的。我们可以微软提供的isdasm.exe来查看编译后的代码。我们先来看看有问题的代码。将IL代码翻译后,可以得到如下的伪代码。
```c#
public class TempClass5
{
public List<UserModel> UserList;
}
public class TempClass8
{
public int i = 0;
public TempClass5 c5;
public ShowMessage(object o)
{
Thread.Sleep(1000);
Console.WriteLine(c5.UserList[i].UserName);
}
}
```
```c#
public class Program
{
TempClass5 c55 = new TempClass5();
c55.UserList = new List<UserModel>();
c55.UserList.Add(new UserModel{ UserName="jiejiep", UserAge = 26});
c55.UserList.Add(new UserModel{ UserName="xiaoyi", UserAge = 25});
c55.UserList.Add(new UserModel{ UserName="zhangzetian", UserAge=24});
TempClass8 c8 = new TempClass8();
c8.c5 = c55;
WaitCallback callback = c8.ShowMessage;
for(int c8.i=0; c8.i < 3; c8.i++)
{
ThreadPool.QueueUserWorkItem(callback);
}
}
```
原来,编译器为我们生成了一个临时类,该类包含一个 int成员i,一个TempClass5实例c5, 一个实例方法 ShowMessage(object) 。再看看遍历部分的代码,我们顿时就豁然开朗了,原来一直都只有一个 TempClass8实例,遍历时始终改变的是tempCls对象的i字段的值。所以最后输出的,始终是最后一个遍历得到的元素的 UserName 。
我们再来看看使用临时变量后的代码,编译器是如何处理的呢。
```c#
public class Program
{
TempClass5 c55 = new TempClass5();
c55.UserList = new List<UserModel>();
c55.UserList.Add(new UserModel{ UserName="jiejiep", UserAge = 26});
c55.UserList.Add(new UserModel{ UserName="xiaoyi", UserAge = 25});
c55.UserList.Add(new UserModel{ UserName="zhangzetian", UserAge=24});
for(int i=0; i < 3; i++)
{
TempClass8 c8 = new TempClass8();
c8.c5 = c55;
c8.i = i;
WaitCallback callback = c8.ShowMessage;
ThreadPool.QueueUserWorkItem(callback);
}
}
```
我们看到,使用临时变量这种解决方案时,编译器相当于是每次遍历时都实例化了一个 TempClass8对象。所以内层函数引用的c8的i成员始终是遍历对应的元素。故能有效的解决闭包带来的陷阱。
## Enum作Key的问题
**Dictionary**的key必须是唯一的标识,因此**Dictionary**需要对 key进行判等的操作,如果key的类型没有实现 IEquatable接口,则默认根据System.Object.Equals()和GetHashCode()方法判断值是否相等。我们可以看看常用作key的几种类型在.NET Framework中的定义:
``` csharp
public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<string>, IEnumerable, IEquatable<string>
public struct Int32 : IComparable, IFormattable, IConvertible, IComparable<int>, IEquatable<int>
public abstract class **Enum** : ValueType, IComparable, IFormattable, IConvertible
```
注意**Enum**类型的定义与前两种类型的不同,它并没有实现IEquatable接口。因此,当我们使用**Enum**类型作为key值时,**Dictionary**的内部操作就需要将**Enum**类型转换为System.Object,这就导致了Boxing的产生。它是导致**Enum**作为 key值的性能瓶颈。
<file_sep>---
layout: post
title: "Unix环境高级编程笔记3"
subtitle: " \"Linux\""
date: 2018-08-24 15:48:00
author: "Mas9uerade"
header-img: "img/watchdog2_sf.jpg"
tags:
- Linux
---
> “Unix环境高级编程第二版读书笔记 - 3 摘抄 https://www.ibm.com/developerworks/cn/linux/l-ipc/part2/index1.html
# [进程间通讯-信号](https://www.ibm.com/developerworks/cn/linux/l-ipc/part2/index1.html)
## 1、信号及信号来源
### 信号本质
信号是在软件层次上对中断机制的一种模拟,在原理上,一个进程收到一个信号与处理器收到一个中断请求可以说是一样的。信号是异步的,一个进程不必通过任何操作来等待信号的到达,事实上,进程也不知道信号到底什么时候到达。
信号是进程间通信机制中唯一的异步通信机制,可以看作是异步通知,通知接收信号的进程有哪些事情发生了。信号机制经过POSIX实时扩展后,功能更加强大,除了基本通知功能外,还可以传递附加信息。
### 信号来源
信号事件的发生有两个来源:硬件来源,比如我们按下了键盘或者其它硬件故障;软件来源,最常用发送信号的系统函数是kill, raise, alarm和setitimer以及sigqueue函数,软件来源还包括一些非法运算等操作。
## 2、信号的种类
可以从两个不同的分类角度对信号进行分类:
1. 可靠性方面:可靠信号与不可靠信号;
2. 与时间的关系上:实时信号与非实时信号。
系统所支持的所有信号都可以查到
### 2.1 可靠信号与不可靠信号
#### "不可靠信号"
Linux信号机制基本上是从Unix系统中继承过来的。早期Unix系统中的信号机制比较简单和原始,后来在实践中暴露出一些问题,因此,把那些建立在早期机制上的信号叫做"不可靠信号",信号值小于SIGRTMIN(Red hat 7.2中,SIGRTMIN=32,SIGRTMAX=63)的信号都是不可靠信号。这就是"不可靠信号"的来源。它的主要问题是:
进程每次处理信号后,就将对信号的响应设置为默认动作。在某些情况下,将导致对信号的错误处理;因此,用户如果不希望这样的操作,那么就要在信号处理函数结尾再一次调用signal(),重新安装该信号。
信号可能丢失,后面将对此详细阐述。
因此,早期unix下的不可靠信号主要指的是进程可能对信号做出错误的反应以及信号可能丢失。
Linux支持不可靠信号,但是对不可靠信号机制做了改进:在调用完信号处理函数后,不必重新调用该信号的安装函数(信号安装函数是在可靠机制上的实现)。因此,Linux下的不可靠信号问题主要指的是信号可能丢失。
#### "可靠信号"
随着时间的发展,实践证明了有必要对信号的原始机制加以改进和扩充。所以,后来出现的各种Unix版本分别在这方面进行了研究,力图实现"可靠信号"。由于原来定义的信号已有许多应用,不好再做改动,最终只好又新增加了一些信号,并在一开始就把它们定义为可靠信号,这些信号支持排队,不会丢失。同时,信号的发送和安装也出现了新版本:信号发送函数sigqueue()及信号安装函数sigaction()。POSIX.4对可靠信号机制做了标准化。但是,POSIX只对可靠信号机制应具有的功能以及信号机制的对外接口做了标准化,对信号机制的实现没有作具体的规定。
信号值位于SIGRTMIN和SIGRTMAX之间的信号都是可靠信号,可靠信号克服了信号可能丢失的问题。Linux在支持新版本的信号安装函数sigation()以及信号发送函数sigqueue()的同时,仍然支持早期的signal()信号安装函数,支持信号发送函数kill()。
注:不要有这样的误解:由sigqueue()发送、sigaction安装的信号就是可靠的。事实上,可靠信号是指后来添加的新信号(信号值位于SIGRTMIN及SIGRTMAX之间);不可靠信号是信号值小于SIGRTMIN的信号。信号的可靠与不可靠只与信号值有关,与信号的发送及安装函数无关。目前linux中的signal()是通过sigation()函数实现的,因此,即使通过signal()安装的信号,在信号处理函数的结尾也不必再调用一次信号安装函数。同时,由signal()安装的实时信号支持排队,同样不会丢失。
对于目前linux的两个信号安装函数:signal()及sigaction()来说,它们都不能把SIGRTMIN以前的信号变成可靠信号(都不支持排队,仍有可能丢失,仍然是不可靠信号),而且对SIGRTMIN以后的信号都支持排队。这两个函数的最大区别在于,经过sigaction安装的信号都能传递信息给信号处理函数(对所有信号这一点都成立),而经过signal安装的信号却不能向信号处理函数传递信息。对于信号发送函数来说也是一样的。
### 2.2 实时信号与非实时信号
早期Unix系统只定义了32种信号,Ret hat7.2支持64种信号,编号0-63(SIGRTMIN=31,SIGRTMAX=63),将来可能进一步增加,这需要得到内核的支持。前32种信号已经有了预定义值,每个信号有了确定的用途及含义,并且每种信号都有各自的缺省动作。如按键盘的CTRL ^C时,会产生SIGINT信号,对该信号的默认反应就是进程终止。后32个信号表示实时信号,等同于前面阐述的可靠信号。这保证了发送的多个实时信号都被接收。实时信号是POSIX标准的一部分,可用于应用进程。
非实时信号都不支持排队,都是不可靠信号;实时信号都支持排队,都是可靠信号。<file_sep>
public static class Solution
{
//正则表达式匹配
public static bool IsMatch(string s, string p)
{
int slen = s.Length;
int plen = p.Length;
if (slen == 0 && plen == 0)
{
return true;
}
bool[,] dp = new bool[slen + 1, plen + 1];
dp[0, 0] = true;
for (int j = 1; j <= plen; j++)
{
//当s为空时,a*b*c*可以匹配
//当判断到下标j-1是*,j-2是b,b对应f,要看之前的能否匹配
//比如a*b*下标依次为ftft,b之前的位t,所以j-1也是true
//即dp[0][j]对应的下标j-1位true
if (j == 1)
{
dp[0, j] = false;
}
if (p[j - 1] == '*')
{
if (j >= 2 && dp[0, j-2])
{
dp[0, j] = true;
}
}
}
//for循环当s长度为1时能否匹配,一直到s长度为slen
for (int i = 1; i <= slen; i++)
{
for (int j = 1; j <= plen; j++)
{
//最简单的两种情况 字符相等或者p的字符是‘.'
if (s[i - 1] == p[j - 1] || p[j - 1] == '.')
{
dp[i, j] = dp[i - 1, j - 1];
}
//p当前字符是*时,要判断*前边一个字符和s当前字符
else if (p[j - 1] == '*')
{
if (j < 2)
{
dp[i, j] = false;
continue;
}
//如果p的*前边字符和s当前字符相等或者p的字符是‘.'
//三种可能
//匹配0个,比如aa aaa*也就是没有*和*之前的字符也可以匹配上(在你(a*)没来之前我们(aa)已经能匹配上了)dp[i][j]=dp[i][j-2]
//匹配1个,比如aab aab* 也就是*和*之前一个字符只匹配s串的当前一个字符就不看*号了 即 dp[i][j]=dp[i][j-1]
//匹配多个,比如aabb aab* b*匹配了bb两个b 那么看aab 和aab*是否能匹配上就行了,即dp[i][j]=dp[i-1][j]
if (p[j - 2] == s[i - 1] || p[j - 2] == '.')
{
dp[i, j] = dp[i - 1, j] || dp[i, j - 1] || dp[i, j - 2];
}
//如果p的*前边字符和s当前字符不相等或者p的字符不是‘.',那就把*和*前边一个字符都不要了呗
//你会发现不管是这种情况还是上边的情况都会有dp[i][j]=dp[i][j-2];所以可以把下边剪枝,不用分开写了
//这里分开写是为了好理解
else if (p[j - 2] != s[i - 1] && p[j - 2] != '.')
{
dp[i, j] = dp[i, j - 2];
}
}
else
{
dp[i, j] = false;
}
}
}
return dp[slen,plen];
}
}<file_sep>//2.两数相加
//给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
//请你将两个数相加,并以相同形式返回一个表示和的链表。
//你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
//示例 1:
//输入:l1 = [2,4,3], l2 = [5, 6, 4]
//输出:[7,0,8]
//解释:342 + 465 = 807.
//示例 2:
//输入:l1 = [0], l2 = [0]
//输出:[0]
//示例 3:
//输入:l1 = [9, 9, 9, 9, 9, 9, 9], l2 = [9, 9, 9, 9]
//输出:[8,9,9,9,0,0,0,1]
//提示:
//每个链表中的节点数在范围[1, 100] 内
//0 <= Node.val <= 9
//题目数据保证列表表示的数字不含前导零
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/add-two-numbers
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//思路
// 1. 逆序表示只需要两个链表合并从头节点开始相加合并即可
namespace ByteDancePopular
{
public partial class Solution
{
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
ListNode node = new ListNode(0);
ListNode head = node;
int incre = 0;
int val = 0;
int sum = 0;
while (l1 != null && l2 != null)
{
sum = l1.val + l2.val + incre;
val = sum >= 10 ? sum - 10 : sum;
incre = sum >= 10 ? 1 : 0;
node.val = val;
l1 = l1.next;
l2 = l2.next;
if (l1 == null && l2 == null)
{
break;
}
else
{
node.next = new ListNode(0);
node = node.next;
}
}
while (l1 == null && l2 != null)
{
sum = l2.val + incre;
val = sum >= 10 ? sum - 10 : sum;
incre = sum >= 10 ? 1 : 0;
node.val = val;
l2 = l2.next;
if (l2 != null)
{
node.next = new ListNode(0);
node = node.next;
}
}
while (l2 == null && l1 != null)
{
sum = l1.val + incre;
val = sum >= 10 ? sum - 10 : sum;
incre = sum >= 10 ? 1 : 0;
node.val = val;
l1 = l1.next;
if (l1 != null)
{
node.next = new ListNode(0);
node = node.next;
}
}
if (incre == 1)
{
node.next = new ListNode(incre);
}
return head;
}
}
}
<file_sep>第一个就是很多人用.Net写程序,会谈到托管这个概念。那么.Net所指的资源托管到底是什么意思,是相对于所有资源,还是只限于某一方面资源?很多人对此不是很了解,其实** .Net **所指的托管只是针对内存这一个方面,并不是对于所有的资源;因此对于Stream,数据库的连接,GDI+的相关对象,还有Com对象等等,这些资源并不是受到.Net管理而统称为非托管资源。而对于内存的释放和回收,系统提供了GC-Garbage Collector,而至于其他资源则需要手动进行释放。
那么第二个概念就是什么是垃圾,通过我以前的文章,会了解到.Net类型分为两大类,一个就是值类型,另一个就是引用类型。前者是分配在栈上,并不需要GC回收;后者是分配在堆上,因此它的内存释放和回收需要通过GC来完成。GC的全称为“Garbage Collector”,顾名思义就是垃圾回收器,那么只有被称为垃圾的对象才能被GC回收。也就是说,**一个引用类型对象所占用的内存需要被** **GC** **回收,需要先成为垃圾。那么.Net** **如何判定一个引用类型对象是垃圾呢,.Net** **的判断很简单,只要判定此对象或者其包含的子对象没有任何引用是有效的,那么系统就认为它是垃圾。**
明确了这两个基本概念,接下来说说GC的运作方式以及其的功能。内存的释放和回收需要伴随着程序的运行,因此系统为GC安排了独立的线程。那么GC的工作大致是,查询内存中对象是否成为垃圾,然后对垃圾进行释放和回收。那么对于GC对于内存回收采取了一定的优先算法进行轮循回收内存资源。其次,**对于内存中的垃圾分为两种,一种是需要调用对象的析构函数,另一种是不需要调用的。****GC** **对于前者的回收需要通过两步完成,第一步是调用对象的析构函数,第二步是回收内存,但是要注意这两步不是在GC** **一次轮循完成,即需要两次轮循;相对于后者,则只是回收内存而已。**
那么对于程序资源来说,我们应该做些什么,以及如何去做,才能使程序效率最高,同时占用资源能尽快的释放。前面也说了,资源分为两种,托管的内存资源,这是不需要我们操心的,系统已经为我们进行管理了;那么对于非托管的资源,这里再重申一下,就是Stream,数据库的连接,GDI+的相关对象,还有Com对象等等这些资源,需要我们手动去释放。
如何去释放,应该把这些操作放到哪里比较好呢。.Net提供了三种方法,也是最常见的三种,大致如下:
<!--[if !supportLists]-->1. <!--[endif]-->析构函数;
<!--[if !supportLists]-->2. <!--[endif]-->继承IDisposable接口,实现Dispose方法;
<!--[if !supportLists]-->3. <!--[endif]-->提供Close方法。
**经过前面的介绍,可以知道析构函数只能被GC** **来调用的,那么无法确定它什么时候被调用,因此用它作为资源的释放并不是很合理,因为资源释放不及时;但是为了防止资源泄漏,毕竟它会被GC** **调用,因此析构函数可以作为一个补救方法。而Close** **与Dispose** **这两种方法的区别在于,调用完了对象的Close** **方法后,此对象有可能被重新进行使用;而Dispose** **方法来说,此对象所占有的资源需要被标记为无用了,也就是此对象被销毁了,不能再被使用。**例如,常见SqlConnection这个类,当调用完Close方法后,可以通过Open重新打开数据库连接,当彻底不用这个对象了就可以调用Dispose方法来标记此对象无用,等待GC回收。明白了这两种方法的意思后,大家在往自己的类中添加的接口时候,不要歪曲了这两者意思。
GC为了提高回收的效 率使用了Generation的概念,原理是这样的,第一次回收之前创建的对象属于Generation 0,之后,每次回收时这个Generation的号码就会向后挪一,也就是说,第二次回收时原来的Generation 0变成了Generation 1,而在第一次回收后和第二次回收前创建的对象将属于Generation 0。GC会先试着在属于Generation 0的对象中回收,因为这些是最新的,所以最有可能会被回收,比如一些函数中的局部变量在退出函数时就没有引用了(可被回收)。如果在Generation 0中回收了足够的内存,那么GC就不会再接着回收了,如果回收的还不够,那么GC就试着在Genera
在C#中,资源分为托管资源和非托管资源两种。GC在回收无用对象资源时,可以自动回收托管资源(比如托管内存),但对于非托管资源(比如Socket、文件、数据库连接)必须在程序中显式释放。
托管资源的回收首先需要GC识别无用对象,然后回收其资源。一般无用对象是指通过当前的系统根对象和调用堆栈对象不可达的对象。对象有一个重要的特点导致无用对象判断的复杂性:对象间的相互引用!如果没有相互引用,就可以通过“引用计数”这种简单高效的方式实现无用对象的判断,并实现实时回收。正是由于相互引用的存在导致GC需要设计更为复杂的算法,这样带来的最大问题在于丧失了资源回收的实时性,而变成一种不确定的方式。
**对于非托管资源的释放,C#提供了两种方式:**
1.Finalizer:写法貌似C++的析构函数,本质上却相差甚远。Finalizer是对象被GC回收之前调用的终结器,初衷是在这里释放非托管资源,但由于GC运行时机的不确定性,通常会导致非托管资源释放不及时。另外,Finalizer可能还会有意想不到的副作用,比如:被回收的对象已经没有被其他可用对象所引用,但Finalizer内部却把它重新变成可用,这就破坏了GC垃圾收集过程的原子性,增大了GC开销。
2.Dispose Pattern:C#提供using关键字支持Dispose Pattern进行资源释放。这样能通过确定的方式释放非托管资源,而且using结构提供了异常安全性。所以,一般建议采用Dispose Pattern,并在Finalizer中辅以检查,如果忘记显式Dispose对象则在Finalizer中释放资源。
可以说,GC为程序带来安全方便的同时也付出了不小的代价:一则丧失了托管资源回收的实时性,这在实时系统和资源受限系统中是致命的;二则没有把C#托管资源和非托管资源的管理统一起来,造成概念割裂。C++的定位之一是底层开发能力,所以不难理解GC并没有成为C++的语言特性。虽然我们在C++0x和各种第三方库都能看到GC的身影,但GC对于C++来讲并不是那么重要,至多是一个有益的补充。C++足以傲视C,并和C# GC一较高下的是它的RAII。以上介绍C#托管资源和非托管资源
首先:谈谈托管,什么叫托管,我的理解就是托付C#运行环境帮我们去管理,在这个运行环境中可以帮助我们开辟内存和释放内存,开辟内存一般用new,内存是随机分配的,释放主要靠的是GC也就是垃圾回收机制。哪么有两个大问题
**1.GC可以回收任何对象吗?**
**2.GC什么时候来回收对象?回收那些对象?**
对于第一个问题,GC可以回收任何对象吗?我是这样理解的,首先要明白一点,C#在强大也管不到非托管代码?哪么什么是非托管代码呢?比如stream(文件),connection(数据库连接),COM(组件)等等。。哪么这些对象是需要进行连接的,比如说我们写这样一句话FileStream fs = new FileStream(“d://a.txt”,FileMode.Open);实际上已经创建了和d://a.txt的连接,如果重复两次就会报错。哪么fs这个对象叫做非托管对象,也就是说C#
不能自动去释放和d://a.txt的连接。哪么对于非托管的代码怎么办,一会我来说。
对于第二个问题,GC什么时候来回收,回收什么对象?我想后面的就不用我说了,当然是回收托管对象了。但是GC什么时候回收?是这样的:GC是随机的,没有人知道他什么时候来,哪么我写了一个例子,证明这一点
private void button1_Click(object sender, EventArgs e)
{
AA a = new AA();
AA b = new AA();
AA c = new AA();
AA d = new AA();
}
public class AA{}
在讲这个例子之前,要明白什么被称之为垃圾,**垃圾就是一个内存区域,没有被任何引用指向,或者不再会被用到。**哪么在第一次点击按钮的时候会生成4个对象,第二次点击按钮的时候也会生成4个对象,但是第一次生成的4个对象就已经是垃圾了,因为,第一次生成的4个对象随着button1_Click函数的结束而不会再被调用(**或者说不能再被调用**),哪么这个时候GC就会来回收吗?不是的!我说了GC是随机的,哪么你只管点你的,不一会GC就会来回收的(**这里我们可以认为,内存中存在一定数量的垃圾之后,GC会来**),要证明GC来过我们把AA类改成
public class AA
{
~AA()
{
MessageBox.Show("析构函数被执行了");
}
}
要明白,GC清理垃圾,实际上是调用析构函数,但是这些代码是托管代码(因为里面没有涉及到Steam,Connection等。。)所以在析构函数中,我们可以只写一个MsgBox来证明刚的想法;这个时候,运行你的程序,一直点击按钮,不一会就会出现一大堆的“析构函数被执行了”…
好了,然后让我们看看能不能改变GC这种为所欲为的天性,答案是可以的,我们可以通过调用GC.Collect();来强制GC进行垃圾回收,哪么button1_Click修改如下
private void button1_Click(object sender, EventArgs e)
{
AA a = new AA();
AA b = new AA();
AA c = new AA();
AA d = new AA();
GC.Collect();
}
哪么在点击第一次按钮的时候,生成四个对象,然后强制垃圾回收,这个时候,会回收吗?当然不会,因为,这四个对象还在执行中(方法还没结束),当点第二次按钮的时候,会出现四次"析构函数被执行了",这是在释放第一次点击按钮的四个对象,然后以后每次点击都会出现四次"析构函数被执行了",哪么最后一次的对象什么时候释放的,在关闭程序的时候释放(因为关闭程序要释放所有的内存)。
好了,现在来谈谈非托管代码,刚才说过,非托管代码不能由垃圾回收释放,我们把AA类改成如下
public class AA
{
FileStream fs = new FileStream("D://a.txt",FileMode.Open);
~AA()
{
MessageBox.Show("析构函数被执行了");
}
}
private void button1_Click(object sender, EventArgs e)
{
AA a = new AA();
}
如果是这样一种情况,哪么第二次点击的时候就会报错,原因是一个文件只能创建一个连接。哪么一定要释放掉第一个资源,才可以进行第二次的连接。哪么首先我们想到用GC.Collect(),来强制释放闲置的资源,修改代码如下:
private void button1_Click(object sender, EventArgs e)
{
GC.Collect();
AA a = new AA();
}
哪么可以看到,第二次点按钮的时候,确实出现了“析构函数被执行了“,但是程序仍然错了,原因前面我说过,因为Stream不是托管代码,所以C#不能帮我们回收,哪怎么办?
自己写一个Dispose方法;去释放我们的内存。代码如下:
public class AA:IDisposable
{
FileStream fs = new FileStream("D://a.txt",FileMode.Open);
~AA()
{
MessageBox.Show("析构函数被执行了");
}
\#region IDisposable 成员
public void Dispose()
{
fs.Dispose();
MessageBox.Show("dispose执行了");
}
\#endregion
}
好了,我们看到了,继承IDisposable接口以后会有一个Dispose方法(当然了,你不想继承也可以,但是接口给我们提供一种规则,你不愿意遵守这个规则,就永远无法融入整个团队,你的代码只有你一个人能看懂),好了闲话不说,这样一来我们的button1_Click改为private void button1_Click(object sender, EventArgs e)
{
AA a = new AA();
a.Dispose();
}
我们每次点击之后,都会发现执行了“dispose执行了”,在关闭程序的时候仍然执行了“析构函数被执行了”这意味了,GC还是工作了,哪么如果程序改为:
private void button1_Click(object sender, EventArgs e)
{
AA a = new AA();
a.Dispose();
GC.Collect();
}
每次都既有“dispose执行了又有”“析构函数被执行了”,这意味着GC又来捣乱了,哪么像这样包含Stream connection的对象,就不用GC来清理了,只需要我们加上最后一句话**GC.SuppressFinalize(this)****来告诉GC,让它不用再调用对象的析构函数中。**那么改写后的AA的dispose方法如下:
public void Dispose()
{
fs.Dispose();
MessageBox.Show("dispose执行了");
**GC.SuppressFinalize(this);**
}
**什么是GC**
GC如其名,就是垃圾收集,当然这里仅就内存而言。Garbage Collector(垃圾收集器,在不至于混淆的情况下也成为GC)以应用程序的root为基础,遍历应用程序在Heap上动态分配的所有对象[2],通过识别它们是否被引用来确定哪些对象是已经死亡的、哪些仍需要被使用。已经不再被应用程序的root或者别的对象所引用的对象就是已经死亡的对象,即所谓的垃圾,需要被回收。这就是GC工作的原理。为了实现这个原理,GC有多种算法。比较常见的算法有Reference Counting,Mark Sweep,Copy Colle[C# string 是不可变的,指什么不可变](https://www.cnblogs.com/maijin/p/6914747.html)ction等等。目前主流的虚拟系统.NET CLR,Java VM和Rotor都是采用的Mark Sweep算法。
# [C# string 是不可变的,指什么不可变](https://www.cnblogs.com/maijin/p/6914747.html)
```
String 表示文本,即一系列 Unicode 字符。
字符串是 Unicode 字符的有序集合,用于表示文本。String 对象是 System.Char 对象的有序集合,用于表示字符串。String 对象的值是该有序集合的内容,并且该值是不可变的。
String 对象称为不可变的(只读),因为一旦创建了该对象,就不能修改该对象的值。看来似乎修改了 String 对象的方法实际上是返回一个包含修改内容的新 String 对象。
StringBuilder 类 表示可变字符字符串。无法继承此类。
此类表示值为可变字符序列的类似字符串的对象。之所以说值是可变的,是因为在通过追加、移除、替换或插入字符而创建它后可以对它进行修改。
大多数修改此类的实例的方法都返回对同一实例的引用。由于返回的是对实例的引用,因此可以调用该引用的方法或属性。如果想要编写将连续操作依次连接起来的单个语句,这将很方便。
StringBuilder 的容量是实例在任何给定时间可存储的最大字符数,并且大于或等于实例值的字符串表示形式的长度。容量可通过 Capacity 属性或 EnsureCapacity 方法来增加或减少,但它不能小于 Length 属性的值。
如果在初始化 StringBuilder 的实例时没有指定容量或最大容量,则使用特定于实现的默认值。
```<file_sep> # Unity纹理压缩格式
## 手游开发(Android/IOS)中,我会使用3个级别的压缩程度:高清晰无压缩、中清晰中压缩、低清晰高压缩;4种压缩方法:RGBA32, RGBA16+Dithering,ETC1+Alpha,PVRTC4。一般足够应付大部分的需求了。 高清晰无压缩 - RGBA32

Unity RGBA32 - 高清晰无压缩.png
RGBA32等同于原图了,优点是清晰、与原图一致,缺点是内存占用十分大;对于一些美术要求最好清晰度的图片,是首选。
要注意一些png图片,在硬盘中占用几KB,怎么在Unity中显示却变大?因为Unity显示的是Texture大小,是实际运行时占用内存的大小,而png却是一种压缩显示格式;可以这样理解,png类似于zip格式,是一个压缩文件,只不过在运行时会自动解压解析罢了。
## 中清晰中压缩 - RGBA16 + Dithering RGBA16+Dithering

Unity RGBA16,不抖动处理的渐变图片惨不忍睹
既然叫RGBA16,自然就是RGBA32的阉割版。
对于一些采用渐变的图片,从RGBA32转换成RGBA16,能明显的看出颜色的层叠变化,如上图。

采用Floyd Steinberg抖动处理后,除非放大,否则肉眼基本看不出区别
RGBA16的优点,内存占用是RGBA32的1/2;搭配上Dithering抖动,在原尺寸下看清晰度一模一样;缺点,Unity原生不支持Dithering抖动,需要自己做工具对图片做处理;对于需要放大、拉伸的图片,Dithering抖动的支持不好,会有非常明显的颗粒感。
## 如何进行Dithering抖动?

Texture Packer工具中Image Format选择RGBA4444,Dithering选择FloydSteinberg在我的项目中,TexturePacker具有非常重要的作用,像UI的图集生成,预先生成好正方形的IOS PVRTC4图集和非正方形的Android ETC1图集、 缩放原图50%等工作都由TexturePacker完成。
同样,对图像进行抖动处理,也是预先在TexturePacker使用FloydSteinberg算法进行图像抖动,再在Unity中导入使用。
TexturePacker提供命令行工具,可以做成自动化的工具。具体方法这里不详述。
### RGB16

Unity RGB16
而RGB16,是主要针对一些,不带透明通道,同时长宽又不是2的次方的图片;对于这些图片,使用RGB16可以降低一半的内存,但是效果会略逊于RGB32。
当然了,RGB16其实也是可以搭配抖动,也能提升显示效果;但同样的Dithering抖动对拉伸放大是不友好的。
## 低清晰高压缩 - ETC1+Alpha/PVRTC4 很多初学者都会疑惑,为什么游戏开发中经常看到一些图片,需要设置成2的次方?因为像ETC1、PVRTC4等这类在内存中无需解压、直接被GPU支持的格式,占用内存极低,而且性能效率也是最好的。 但是,相对RGBA32,还是能肉眼看出质量有所下降的。
### ETC1 ETC1+Alpha一般应用在Android版的UI图集中,ETC1不带透明通道,所以需要外挂一张同样是ETC1格式的Alpha通道图。方法是,在原RGBA32的原图中,提取RGB生成第一张ETC1,再提取A通道,填充另一张ETC1的R通道;游戏运行时,Shader将两张ETC1图片进行混合。
生成Alpha通道图的方法可参考:
http://blog.csdn.net/u010153703/article/details/45502895
要配合ETC1+Alpha,还需要Shader支持,这里提供参考直接修改NGUI的Unlit/Transparent With Colored的Shader。

Paste_Image.png
### PVRTC4 PVRTC4在Unity中是直接支持的,不过要注意的细节是,它必须是二次方正方形;也就是说,长宽在二次方的同时,还必须要相等。
# 几种纹理格式的对比
| 格式 | 内存占用 | 质量 | 透明 | 二次方大小 | 建议使用场合 |
| ----------------------- | -------- | ----- | ---- | -------------------------- | -------------------------------------------------- |
| RGBA32 | 1 | ★★★★★ | 有 | 无需 | 清晰度要求极高 |
| RGBA16+Dithering | 1/2 | ★★★★ | 有 | 无需 | UI、头像、卡牌、不会进行拉伸放大 |
| RGBA16 | 1/2 | ★★★ | 有 | 无需 | UI、头像、卡牌,不带渐变,颜色不丰富,需要拉伸放大 |
| RGB16+Dithering | 1/2 | ★★★★ | 无 | 无需 | UI、头像、卡牌、不透明、不会进行拉伸放大 |
| RGB16 | 1/2 | ★★★ | 无 | 无需 | UI、头像、卡牌、不透明、不渐变,不会进行拉伸放大 |
| RGB(ETC1) + Alpha(ETC1) | 1/4 | ★★★ | 有 | 需要二次方,长宽可不一样 | 尽可能默认使用,在质量不满足时再考虑使用上边的格式 |
| RGB(ETC1) | 1/8 | ★★★ | 无 | 需要二次方,长宽可不一样 | 尽可能默认使用,在质量不满足时再考虑使用上边的格式 |
| PVRTC4 | 1/8 | ★★ | 无 | 需要二次方正方形,长宽一样 | 尽可能默认使用,在质量不满足时再考虑使用上边的格式 |
- 内存占用,相对于RGBA32做比较
- 质量星级,更多是本人感受,仅供参考
------
在项目中,尽可能是使用ETC1和PVRTV4等GPU直接支持的图片格式,不仅内存占用低、性能也更好;当出现质量不及格时,再逐步的提升压缩格式,来满足需要。<file_sep>//#### [97. 交错字符串](https://leetcode-cn.com/problems/interleaving-string/)
//给定三个字符串 `s1`、`s2`、`s3`,请你帮忙验证 `s3` 是否是由 `s1` 和 `s2` **交错** 组成的。
//两个字符串 `s` 和 `t` **交错** 的定义与过程如下,其中每个字符串都会被分割成若干 **非空** 子字符串:
//- `s = s1 + s2 + ... + sn`
//- `t = t1 + t2 + ... + tm`
//- `|n - m| <= 1`
//- **交错** 是 `s1 + t1 + s2 + t2 + s3 + t3 + ...` 或者 `t1 + s1 + t2 + s2 + t3 + s3 + ...`
//**提示:**`a + b` 意味着字符串 `a` 和 `b` 连接。
//**示例 1:**
//
//```
//输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
//输出:true
//```
//**示例 2:**
//```
//输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
//输出:false
//```
//**示例 3:**
//```
//输入:s1 = "", s2 = "", s3 = ""
//输出:true
//```
//**提示:**
//- `0 <= s1.length, s2.length <= 100`
//- `0 <= s3.length <= 200`
//- `s1`、`s2`、和 `s3` 都由小写英文字母组成
//### 题解
//输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
//输出:true
//| S2\S1| 0 | a1 | a2 | b | c | c |
//| ---- | ---- | ---- | ------- | -------- | ------------ | ------------- |
//| 0 | T | T(a) | T(aa) | F | | |
//| d 1 | F | F(ad)| T(aad) | T(aadb) | F | |
//| b 2 | |F(adb)| T(aadb) | T(aadbb) | T(aadbbc) | F |
//| b | | | F | F | T(aadbbcb) | T(aadbbcbc) |
//| c | | | | | T(aadbbcbc) | F |
//| a | | | | | T(aadbbcbca) | T(aadbbcbcac) |
// 即 DP[i,j] 是基于 dp[i-1,j] 或 dp[i, j-1]的基础上进行计算
// DP[n,m] = new bool[n,m]
// DP[0,0] = T
// DP[0,1] = s1[0] == s3[0]? T:F
// DP[1,0] = s2[0] == s3[0]? T:F
// DP[1,1] = (DP[0,1] && s3[2] == s2[1])|(DP[1,0] && s3[2] == s1[2])
// aad
// DP[2,1] = (DP[1,1] && s3[2+1 -1] == s2[2]) || DP[2,0] && s3[2+1-1] == S1[1]
// DP[i,j] = DP[i-1,j]
namespace ByteDancePopular
{
public partial class Solution
{
public void IsInterleaveUnitTest()
{
string s1 = "aabcc";
string s2 = "dbbca";
string s3 = "aadbbcbcac";
IsInterleave(s1, s2, s3);
}
public bool IsInterleave(string s1, string s2, string s3)
{
int m = s1.Length;
int n = s2.Length;
if (s3.Length != n+m)
{
return false;
}
else
{
if (m ==0)
{
return string.Equals(s2, s3);
}
if (n == 0)
{
return string.Equals(s1, s3);
}
}
bool[,] dp = new bool[n+1, m+1];
dp[0, 0] = true;
dp[0, 1] = s3[0] == s1[0];
dp[1, 0] = s3[0] == s2[0];
for (int i = 1; i <=m; ++i)
{
dp[0, i] = dp[0, i - 1] && s3[i - 1] == s1[i-1];
}
for (int i = 1; i <= n; ++i)
{
dp[i, 0] = dp[i-1, 0] && s3[i - 1] == s2[i - 1];
}
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= m; ++j)
{
dp[i, j] = (dp[i - 1, j] && s3[i + j - 1] == s2[i - 1]) || (dp[i, j - 1] && s3[i + j - 1]==s1[j-1]);
}
}
return dp[n, m];
}
}
}<file_sep>---
layout: post
title: "C++ Inline函数与宏定义的区别"
subtitle: " \"面试小记\""
date: 2020-11-15 09:44:09
author: "Mas9uerade"
header-img: "img/IMG_2616.jpg"
tags:
- C
- C++
---
> “面试知识点整理”
### Inline函数
内联函数和普通函数相比可以加快程序运行的速度,因为不需要中断调用,在编译的时候内联函数可以直接呗镶嵌到目标代码中。内联函数要做参数类型检查,这是内联函数跟宏相比的优势。
inline是指嵌入代码,就是在调用函数的地方不是跳转,而是把代码直接写到那里去。对于短小的代码来说,inline可以带来一定的效率提升,而且和C时代的宏函数相比,inline更安全可靠。可是这个是以增加空间消耗为代价的。至于是否需要inline函数就需要根据你的实际情况取舍了。
**inline一般只用于如下情况:
(1)一个函数不断被重复调用。
(2)函数只有简单的几行,且函数不包含for、while、switch语句。**
●一般来说,我们写小程序没有必要定义成inline,但是如果要完成一个工程项目,当一个简单函数被调用多次时,则应该考虑用inline。
● 宏在C语言里极其重要,而在C++里用得就少多了。关于宏的第一规则是:绝不应该去使用它,除非你不得不这样做。几乎每个宏都表明了程序设计语言里或者程序里或者程序员的一个缺陷,因为它将在编译器看到程序的正文之前重新摆布这些正文。宏也许是许多程序设计工具的麻烦。所以,如果你使用了宏,你就应该准备着只能从各种工具(如排错系统、交叉引用系统、轮廓程序等)中得到较少的服务。(--pass:宏还是很方便的,使用时要小心,并不是说宏一无是处,存在自然有其合理性)
**宏是在代码处不加任何验证的简单替代,而内联函数是将代码直接插入调用处,而减少了普通函数调用时的资源消耗。**
**宏不是函数,只是在编译前(编译预处理阶段)将程序中有关字符串替换成宏体。**
**inline函数是函数,但在编译中不单独产生代码,而是将有关代码嵌入到调用处。**
inline函数是C++引入的机制,目的是解决使用宏定义的一些缺点。
**1.为什么要引入内联函数(内联函数的作用)**
**用它替代宏定义,消除宏定义的缺点。宏定义使用预处理器实现,做一些简单的字符替换因此不能进行参数有效性的检测。另外它的返回值不能被强制转换为可转换的合适类型,且C++中引入了类及类的访问控制,在涉及到类的保护成员和私有成员就不能用宏定义来操作。**
2.inline相比宏定义有哪些优越处
(1)**inline函数代码是被放到符号表中,使用时像宏一样展开,没有调用的开销效率很高;**
(2)i**nline函数是真正的函数,所以要进行一系列的数据类型检查;**
(3)**inline函数作为类的成员函数,可以使用类的保护成员及私有成员;**
3.inline函数使用的场合
(1)**使用宏定义的地方都可以使用inline函数;**
(2)**作为类成员接口函数来读写类的私有成员或者保护成员;**
4.为什么不能把所有的函数写成inline函数
内联函数以代码复杂为代价,它以省去函数调用的开销来提高执行效率。所以**一方面如果内联函数体内代码执行时间相比函数调用开销较大没有太大的意义;** **另一方面每一处内联函数的调用都要复制代码,消耗更多的内存空间**, 因此以下情况不宜使用内联函数。
(1)**函数体内的代码比较长,将导致内存消耗代价;**
(2)**函数体内有循环,函数执行时间要比函数调用开销大;**
另外类的构造与析构函数不要写成内联函数。
5.内联函数与宏定义区别
**(1)内联函数在编译时展开,宏在预编译时展开;**
**(2)内联函数直接嵌入到目标代码中,宏是简单的做文本替换;**
**(3)内联函数有类型检测、语法判断等功能,而宏没有;**
**(4)inline函数是函数,宏不是;**
**(5)宏定义时要注意书写(参数要括起来)否则容易出现歧义,内联函数不会产生歧义;**
inline的使用是有所限制的,inline只适合函数体内代码简单的涵数使用,不能包含复杂的结构控制语句例如while、switch,并且不能内联函数本身不能是直接递归函数(自己内部还调用自己的函数)。
补充:
inline函数仅仅是一个建议,对编译器的建议,所以最后能否真正内联,看编译器的意思,它如果认为函数不复杂,能在调用点展开,就会真正内联,并不是说声明了内联就会内联,声明内联只是一个建议而已。
其次,因为内联函数要在调用点展开,所以编译器必须随处可见内联函数的定义,要不然,就成了非内联函数的调用了。所以,这要求每个调用了内联函数的文件都出现了该内联函数的定义。
因此,将内联函数放在头文件里实现是合适的,省却你为每个文件实现一次的麻烦。而所以声明跟定义要一致,其实是指,如果在每个文件里都实现一次该内联函数的话,那么,最好保证每个定义都是一样的,否则,将会引起未定义的行为,即是说,如果不是每个文件里的定义都一样,那么,编译器展开的是哪一个,那要看具体的编译器而定。所以,最好将内联函数定义放在头文件中。
而类中的成员函数缺省都是内联的,如果在类定义时就在类内给出函数,那当然最好。如果在类中未给出成员函数定义,而又想内联该函数的话,那在类外要加上inline,否则就认为不是内联的。
为了方便,将内联函数直接声明时就定义,放在头文件中。这样其它文件包含了该头文件,就在每个文件都出现了内联函数的定义。就可以内联了。<file_sep>//1191. K 次串联后最大子数组之和
//给你一个整数数组 arr 和一个整数 k。
//首先,我们要对该数组进行修改,即把原数组 arr 重复 k 次。
//举个例子,如果 arr = [1, 2] 且 k = 3,那么修改后的数组就是 [1, 2, 1, 2, 1, 2]。
//然后,请你返回修改后的数组中的最大的子数组之和。
//注意,子数组长度可以是 0,在这种情况下它的总和也是 0。
//由于 结果可能会很大,所以需要 模(mod) 10^9 + 7 后再返回。
//示例 1:
//输入:arr = [1,2], k = 3
//输出:9
//示例 2:
//输入:arr = [1, -2, 1], k = 5
//输出:2
//示例 3:
//输入:arr = [-1, -2], k = 7
//输出:0
//提示:
//1 <= arr.length <= 10 ^ 5
//1 <= k <= 10 ^ 5
//- 10 ^ 4 <= arr[i] <= 10 ^ 4
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/k-concatenation-maximum-sum
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//思路
// 1. 求出单个数组的最大子数组的值
// 2. 求出数组值的和
// 3. DP求最大值
using System;
using System.Collections.Generic;
namespace ByteDancePopular
{
public partial class Solution
{
private static int InArray = 1, OutArray = 2;
public int KConcatenationMaxSum(int[] arr, int k)
{
int mod = (int) Math.Pow(10, 9) + 7;
int sum = 0;
for (int i = 0; i< arr.Length; ++i)
{
sum = (sum + arr[i]) % mod;
}
sum = Math.Max(0, sum);
List<int> list = new List<int>();
list.AddRange(arr);
list.AddRange(arr);
int left = 0, right = 0;
int[] dp = new int[list.Count];
int[] cost = new int[list.Count];
int[] status = new int[list.Count];
dp[0] = list[0] > 0? list[0] :0;
status[0] = list[0]> 0 ? InArray:OutArray;
for (int i = 1; i < list.Count; ++i)
{
//正数/0,考虑接入最大子数组
if (list[i] >= 0)
{
if (status[i-1] == OutArray)
{
//考虑是否续接
if (cost[i-1] + dp[i-1] + list[i] >= dp[i-1] && cost[i - 1] + dp[i - 1] + list[i] >= list[i])
{
//续接
status[i] = InArray;
cost[i] = 0;
dp[i] = (cost[i - 1] + dp[i - 1] + list[i])% mod;
}
//不续接
else
{
// 1. 延续之前的DP值
if (dp[i-1] > cost[i-1] + dp[i-1] + list[i] && dp[i-1] > list[i])
{
status[i] = OutArray;
cost[i] = (list[i] + cost[i-1])% mod;
dp[i] = (dp[i - 1]) % mod;
}
// 2. 使用当前的数
else if (list[i] >= dp[i-1] && list[i] > dp[i-1] + cost[i-1] + list[i])
{
status[i] = InArray;
dp[i] = list[i] % mod;
cost[i] = 0;
}
}
}
else
{
//已经连接上了
status[i] = InArray;
cost[i] = 0;
dp[i] = (dp[i - 1] + list[i]) % mod;
}
}
//负数的情况
else
{
if (status[i-1] == InArray)
{
//断链
status[i] = OutArray;
dp[i] = dp[i - 1];
cost[i] = list[i];
}
//已断链的情况下
else
{
status[i] = OutArray;
dp[i] = dp[i - 1];
cost[i] = (cost[i - 1] + list[i]) % mod;
}
}
}
int max1 = dp[arr.Length - 1];
int max2 = dp[dp.Length-1];
int k2max = 0;
if (k >= 2)
{
k2max = Math.Max(0, Math.Max(max2, ((k - 2) * sum + max2) % mod));
}
int k1max = 0;
if (k >= 1)
{
k1max = Math.Max(0, Math.Max(((k - 1) * sum + max1) % mod, max1));
}
return Math.Max(Math.Max(k1max, k2max), k * sum % mod);
}
}
}<file_sep>//329. 矩阵中的最长递增路径
//给定一个整数矩阵,找出最长递增路径的长度。
//对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
//示例 1:
//输入: nums =
//[
// [9, 9, 4],
// [6,6,8],
// [2,1,1]
//]
//输出: 4
//解释: 最长递增路径为[1, 2, 6, 9]。
//示例 2:
//输入: nums =
//[
// [3, 4, 5],
// [3,2,6],
// [2,2,1]
//]
//输出: 4
//解释: 最长递增路径是[3, 4, 5, 6]。注意不允许在对角线方向上移动。
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
using System;
using System.Collections.Generic;
/// <summary>
/// 思路 dfs + 记忆化
/// 因为是递增的路线,所以如果可以连接上已经走过的点,则可以直接使用该值
/// </summary>
namespace ByteDancePopular
{
public partial class Solution
{
int[][] dir = new int[4][] { new int[2] { -1, 0 }, new int[2] { 1, 0 }, new int[2] { 0, -1 }, new int[2] { 0, 1 } };
int rows, cols;
public int LongestIncreasingPath(int[][] matrix)
{
rows = matrix.Length;
cols = matrix[0].Length;
int[][] memory = new int[rows][];
for (int i = 0; i < rows; ++i)
{
memory[i] = new int[cols];
}
int ans = 0;
for (int i = 0; i <rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
ans = Math.Max(ans, DfsLongestIncreasePath(memory, matrix, i, j));
}
}
return ans;
}
private int DfsLongestIncreasePath(int[][] memory, int[][] matrix, int i, int j)
{
if (memory[i][j] != 0)
{
return memory[i][j];
}
memory[i][j]++;
for (int k = 0; k < dir.Length; ++k)
{
int newRow = i + dir[k][0], newColumn = j + dir[k][1];
if (newRow >= 0 && newRow < matrix.Length && newColumn >= 0 && newColumn < cols && matrix[newRow][newColumn] > matrix[i][j])
{
memory[i][j] = Math.Max(memory[i][j], DfsLongestIncreasePath(memory, matrix, newRow, newColumn) + 1);
}
}
return memory[i][j];
}
}
}<file_sep>---
layout: post
title: "Python学习1-环境,函数传参,类"
subtitle: " \"Python学习\""
date: 2018-04-14 21:21:00
author: "Mas9uerade"
header-img: "img/watchdog2_sf.jpg"
tags:
- Python
---
> “上周简单地学习了Python的基础语法和API,整理一下加深理解和印象”
## Python的环境搭建
其实,之前因为工作需要,使用python做过简单的数据分析处理脚本,但是在windows平台上单纯的用notepad++和cmd进行代码编写效率是比较低的,因此这次选择了[PyCharm](https://www.jetbrains.com/pycharm/)这个IDE作为编译和调试的环境,界面类似Android Studio,因此这次上手还是很快的。
注意事项:
1. python npm的功能直接集成到了IDE内,安装各类模块/第三方库都很方便;
2. 需要对每个工程都设置一遍Python的运行环境。
## Python的函数传参
Python作为解释性语言,与其他编译型语言最大的不同点,或者说最初接触python需要注意的地方就是python的函数传参。
参考[Python 的函数是怎么传递参数的?](https://www.zhihu.com/question/20591688)
1. __Python中有可变对象(比如列表List)和不可变对象(比如字符串),在参数传递时分为两种情况:
a.对于不可变对象作为函数参数,相当于C系语言的值传递;
b.对于可变对象作为函数参数,相当于C系语言的引用传递。__
2. __在Python中,对于不可变对象,调用自身的任意方法,并不会改变对象自身的内容,这些方法会创建新的对象并返回,保证了不可变对象本身是永远不可变的。__
这里先用了一个交换函数作为例子,交换失败的swap_error为例,传入了a,b,之后交换了值,但由于x,y均为不可变对象,因此传入x,y时实际上new了两个新的对象,然后赋上了原值,所以return后,x,y值未交换。
所以要交换值就不用函数,直接x,y = y,x更方便
```python
def swap_error(a,b):
a,b = b,a
return
def swap_suc(a,b):
return b,a
x = 1
y = 2
print(x,y)
swap_error(x,y)
print(x,y)
x,y = swap_suc(x,y)
print(x,y)
```
## Python的Class
### 1. 多态,继承
下面的例子,是python class多态的体现,子类的函数覆盖父类函数,跟其他语言没什么本质上的区别
```python
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary): #构造函数
self.name = name
self.salary = salary
Employee.empCount += 1
print("offer ", self.name, " with salary :", self.salary)
def __del__(self): #析构函数
print(self.name, "has been fired")
Employee.empCount -=1;
def displayCount(self):
print("Total Employee %d" % Employee.empCount);
def displayEmployee(self):
print("name : ", self.name, " Salary: ", self.salary);
class Boss(Employee): #继承与多态
def __init__(self, name):
self.name = name
self.salary = 1000000000
Employee.empCount += 1
print("offer ", self.name, " with salary :", self.salary )
def displayEmployee(self):
print("name : ", self.name, " Salary: Salary of Boss is Screct");
# cindy = Employee("Cindy", 1000)
# cindy.displayEmployee()
# roger = Boss("Roger")
# roger.displayEmployee()
```
在这里就想到了Python的函数重载Overload问题,[为什么 Python 不支持函数重载?其他函数大部分都支持的?](https://www.zhihu.com/question/20053359),其中高赞回答的解释:
__函数重载主要是为了解决两个问题:
a.可变参数类型。 (这点对python来说根本不需要使用重载,之后再谈)
b.可变参数个数。 (对那些缺少的参数设定为缺省参数来解决问题)
python在这两个问题上的表现使得它不需要再去使用函数重载来解决这些问题。___
### Python的操作符重载
既然提到了重载,就可以说一下Python的操作符重载与内置对象的重载
```Python
class Number:
def __init__(self,start):
self.data = start
def __sub__(self,other):
return Number(self.data + other)
print("Operator Overload")
X = Number(5)
print(X.data)
Y = X -2
print(Y.data)
```
在类中,对内置对象(例如,整数和列表)所能做的事,几乎都有相应的特殊名称的重载方法。
| 方法 | 重载 | 调用 |
| --------- | -------- | ----------------------------------------- |
| \_\_init\_\_ | 构造函数 | 对象建立:X = Class(args) |
| \_\_del\_\_|析构函数 |X对象收回 |
| \_\_add\_\_ | 运算符+ | 如果没有_iadd_,X+Y,X+=Y |
| \_\_or\_\_| 运算符\|(位OR)|如果没有_ior_,X\|Y,X\|=Y|
| \_\_repr\_\_, \_\_str\_\_|打印、转换|print(X)、repr(X),str(X)|
| \_\_call\_\_|函数调用|X(\*arg,\*\*karg)|
| \_\_getattr\_\_ |点号运算|X.undefined|
| \_\_setattr\_\_ |属性赋值语句|X.any = value|
| \_\_delatrr\_\_ | 属性删除|del X.any|
|\_\_getattribute\_\_| 属性获取| X.any|
| \_\_getitem\_\_ |索引运算 |X[key],X[i:j],没\_\_iter\_\_时的for循环和其他迭代器|
| \_\_setitem\_\_ |索引赋值语句| X[key] = value,X[i:j] = sequence|
| \_\_delitem\_\_ |索引和分片删除| del X[key],del X[i:j]|
| \_\_len\_\_ |长度| len(X),如果没有\_\_bool\_\_,真值测试|
| \_\_bool\_\_ |布尔测试| bool(X),真测试|
| \_\_lt\_\_,\_\_gt\_\_| 特定的比较| X < Y,X > Y(less than, greater than)|
| \_\_le\_\_,\_\_ge\_\_,| |X<=Y,X >= Y(less or equal, greater or equal)|
| \_\_eq\_\_,\_\_ne\_\_ | |X == Y,X != Y (equal, neagtive equal)|
| \_\_radd\_\_ |右侧加法| Other+X|
| \_\_iadd\_\_ |实地(增强的)加法 |X += Y (or else \_\_add\_\_)|
| \_\_iter\_\_,\_\_next\_\_| 迭代环境| I = iter(X),next(I)|
| \_\_contains\_\_ |成员关系测试| item in X (任何可迭代的)|
| \_\_index\_\_ |整数值| hex(X),bin(X),oct(X),O[X],O[X:]|
| \_\_enter\_\_,\_\_exit\_\_| 环境管理器| with obj as var:|
| \_\_get\_\_,\_\_set\_\_| 描述符属性| X.attr,X.attr = value,del X.attr|
| \_\_new\_\_ |创建| 在\_\_init\_\_之前创建对象|
```python
print("get/set方式")
class Indexer:
def __getitem__(self,index):
return index**2 #平方
X = Indexer()
print(X[2])
for i in range(5):
print(X[i])
L = [5,6,7,8,9]
print( L[2:4]) #[7, 8]
print(L[1:]) #[6, 7, 8, 9]
print( L[:-1]) #[5, 6, 7, 8]
print( L[::2]) #[5, 7, 9]
class stepper:
def __getitem__(self, i):
return self.data[i]
P = stepper()
P.data = 'Spam'
print(P[1])
for item in P:
print(item)
```
### python的数组
```pyhon
# python的数组的元素删除有两种方式一种是M.pop(),另外一种是del M[i],两种用法遍历时的 for 用不了
M = [0,1,2,3,5,3,2,1]
for num in M:
if num > 2:
print(num)
print("前",M)
M.remove(num)
print("后",M)
print(M)
M = [0,1,2,3,5,3,2,1]
i = 0
for num in M:
if num > 2:
print(i, num)
print("前",M)
del M[i]
print("后",M)
i-= 1
i+= 1
print(M)
#所以可以使用lambda表达式进行过滤
Lam = filter(lambda x: x> 2, M)
print(Lam)
print(Lam)
a = [0,1,2,3,5,3,2,1]
a = filter(lambda x: x <= 2, a)
print(a)
a = list(a)
print(a)
for x in a:
print(x)
```
|
2d2fae85176824e7986779b4f41dc8541492d5fd
|
[
"Markdown",
"C#",
"C++"
] | 108
|
Markdown
|
Mas9uerade/mas9uerade.github.io
|
9cc273313fc1360daff57fe16dd1a60fe910259d
|
4b0ee4ad342011deed023a5ad79e765ea3ab7150
|
refs/heads/master
|
<repo_name>bcpiotr/malePsotyV1<file_sep>/README.md
# malePsotyV1
To jest moj obecny, pierwszy komercyjny projekt.
Obecnie wprowadzane sa zmiany do projektu graficznego, wiec teraz stworzony jest tylko zarys kodu (aby potwierdzic u klienta ustalony uklad strony).
W zalozeniu projekt to:
- one page z linkami odsylajacymi do poszczegolnych sekcji
- w pelni kompatybilny do urzadzen mobilnych
- elementy CMS (opcja dodawnia news'ow, zmiany poszczegolnych ofert i obrazow w sliderze i galerii), mini admin panel dla klienta
Projekt w fazie poczatkowej
<file_sep>/js/script.js
document.addEventListener("DOMContentLoaded",function(){
console.log('dziala');
// bxslider
$('#sliderMain').bxSlider({
auto: true,
autoControls: true
});
//bx gallery
$('#gallerySlider').bxSlider({
pagerCustom: '#bx-pager'
});
});
|
cee71f95fb43a93e3c31f7edb497f1bafaaf1eec
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
bcpiotr/malePsotyV1
|
d270ef672748ea4026004fae2185dc9d05434860
|
9d867a33e2823f5059ba93d267b3ec27f20ff0ea
|
refs/heads/main
|
<repo_name>aftaba/Spoonacular-Drupal-Module<file_sep>/src/Form/SpoonacularAPIForm.php
<?php
/**
* @file
* Contains Drupal\recipe_nutrition\Form\SettingsForm.
*/
namespace Drupal\recipe_nutrition\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Class SettingsForm.
*
* @package Drupal\recipe_nutrition\Form
*/
class SpoonacularAPIForm extends ConfigFormBase {
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'recipe_nutrition.settings',
];
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'spoonacular_api_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('recipe_nutrition.settings');
$form['spoonacular_api_key'] = array(
'#type' => 'textfield',
'#title' => $this->t('Enter Spoonacular API key'),
'#default_value' => $config->get('spoonacular_api_key'),
);
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
$this->config('recipe_nutrition.settings')
->set('spoonacular_api_key', $form_state->getValue('spoonacular_api_key'))
->save();
}
}
|
d4e2070f32703a342a9a4b3c4d4b283b211af12d
|
[
"PHP"
] | 1
|
PHP
|
aftaba/Spoonacular-Drupal-Module
|
1330a348313394f1f509839f1aa67685b6751b7f
|
2c4fcc2b75de52d6275c882cf26840431f4f5856
|
refs/heads/master
|
<repo_name>Dauflo/4JVA<file_sep>/src/main/java/com/dab/household/entity/UserOrder.java
package com.dab.household.entity;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Entity()
public class UserOrder extends BaseEntity implements Serializable {
@ManyToOne
private Cart cart;
@ManyToOne
private Item item;
@NotNull
private Long quantity;
public UserOrder() {
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
}
<file_sep>/src/main/java/com/dab/household/utils/PasswordEncryption.java
package com.dab.household.utils;
import org.mindrot.jbcrypt.BCrypt;
public class PasswordEncryption {
public static String encryption(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}
public static boolean checkPassword(String candidate, String hashed) {
return BCrypt.checkpw(candidate, hashed);
}
}
<file_sep>/src/main/java/com/dab/household/dao/ItemDao.java
package com.dab.household.dao;
import com.dab.household.entity.Item;
import javax.ejb.Local;
import java.util.List;
@Local
public interface ItemDao {
Item addItem(Item item);
List<Item> findItemsByTitle(String title);
Item findItemById(Long id);
List<Item> findAll();
}
<file_sep>/src/main/java/com/dab/household/beans/OldCartDetailBean.java
package com.dab.household.beans;
import com.dab.household.entity.Cart;
import com.dab.household.entity.UserOrder;
import com.dab.household.service.CartService;
import com.dab.household.service.OrderService;
import com.dab.household.utils.Pager;
import com.ocpsoft.pretty.faces.annotation.URLMapping;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@ManagedBean
@URLMapping(id = "oldCartDetail", pattern = "/auth/detail/#{cartId}/#{page}", viewId = "/jsf/auth/oldCartDetail.xhtml")
public class OldCartDetailBean {
@EJB
private CartService cartService;
@EJB
private OrderService orderService;
private Cart cart;
private Long cartId;
private Long page;
public OldCartDetailBean() {
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
this.cartId = Long.parseLong(req.getParameter("cartId"));
this.page = Long.parseLong(req.getParameter("page"));
}
public Cart getCart() {
cart = cartService.findOneById(cartId);
return cart;
}
public List<Object> getOrders() {
return Pager.getList(orderService.getFromCart(cart), this.page);
}
public List<Integer> getPager() {
return Pager.getPageList(orderService.getFromCart(cart));
}
}
<file_sep>/src/main/java/com/dab/household/service/ItemService.java
package com.dab.household.service;
import com.dab.household.dao.ItemDao;
import com.dab.household.entity.Item;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import java.util.List;
@Stateless
public class ItemService {
@EJB
private ItemDao itemDao;
public Item addItem(Item item) {
return itemDao.addItem(item);
}
public List<Item> findItemsByTitle(String title) {
return itemDao.findItemsByTitle(title);
}
public Item findItemById(Long id) {
return itemDao.findItemById(id);
}
public List<Item> findAll() {
return itemDao.findAll();
}
}
<file_sep>/src/main/java/com/dab/household/dao/jpa/JpaCartDao.java
package com.dab.household.dao.jpa;
import com.dab.household.dao.CartDao;
import com.dab.household.entity.Cart;
import com.dab.household.entity.User;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;
@Stateless
public class JpaCartDao implements CartDao {
@PersistenceContext
private EntityManager em;
@Override
public Cart addCart(Cart cart) {
em.persist(cart);
return cart;
}
@Override
public Cart getOneById(Long id) {
return em.find(Cart.class, id);
}
@Override
public List<Cart> getAllCarts() {
List<Cart> carts;
try {
carts = em.createQuery("SELECT c FROM Cart c").getResultList();
} catch (Exception e) {
carts = new ArrayList<>();
}
return carts;
}
@Override
public List<Cart> getUserCarts(User user) {
List<Cart> carts;
try {
carts = em.createQuery("SELECT c from Cart c WHERE c.user = :user")
.setParameter("user", user)
.getResultList();
} catch (Exception e) {
carts = new ArrayList<>();
}
return carts;
}
}
<file_sep>/src/main/java/com/dab/household/service/UserService.java
package com.dab.household.service;
import com.dab.household.dao.UserDao;
import com.dab.household.entity.User;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import java.util.List;
@Stateless
public class UserService {
@EJB
private UserDao userDao;
public User addUser(User user) {
return userDao.addUser(user);
}
public User findUserByUsername(String username) {
return userDao.findUserByUsername(username);
}
public User updateUser(User user) {
return userDao.updateUser(user);
}
public List<User> findAll() {
return userDao.findAll();
}
}
<file_sep>/src/main/java/com/dab/household/utils/CartUtils.java
package com.dab.household.utils;
import com.dab.household.entity.Cart;
import com.dab.household.entity.Item;
import com.dab.household.entity.UserOrder;
import java.util.List;
public class CartUtils {
public static Cart generateCart(List<Item> items) {
Cart cart = new Cart();
for (Item item : items) {
if (cart.getUserOrders().size() == 0) {
UserOrder userOrder = new UserOrder();
userOrder.setItem(item);
userOrder.setQuantity(1L);
userOrder.setCart(cart);
cart.addOrder(userOrder);
} else {
boolean found = false;
List<UserOrder> userOrderList = cart.getUserOrders();
for (UserOrder userOrder : userOrderList) {
if (userOrder.getItem().getId() == item.getId()) {
userOrder.setQuantity(userOrder.getQuantity() + 1);
found = true;
break;
}
}
if (!found) {
UserOrder userOrder = new UserOrder();
userOrder.setItem(item);
userOrder.setCart(cart);
userOrder.setQuantity(1L);
cart.addOrder(userOrder);
}
}
}
return cart;
}
}
<file_sep>/src/main/java/com/dab/household/beans/ItemDescription.java
package com.dab.household.beans;
import com.dab.household.entity.Item;
import com.dab.household.service.ItemService;
import com.ocpsoft.pretty.faces.annotation.URLMapping;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
@ManagedBean
@URLMapping(id = "itemDescription", pattern = "/description/#{id}", viewId = "/jsf/itemDescription.xhtml")
public class ItemDescription {
@EJB
private ItemService itemService;
private Long id;
public ItemDescription() {
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
this.id = Long.parseLong(req.getParameter("id"));
}
public Item getItem() {
return itemService.findItemById(this.id);
}
}
<file_sep>/src/main/java/com/dab/household/entity/Item.java
package com.dab.household.entity;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
@Entity
public class Item extends BaseEntity implements Serializable {
@NotNull
private String title;
@NotNull
private String description;
@NotNull
private Float price;
@OneToMany(fetch = FetchType.EAGER)
private List<UserOrder> userOrders;
public Item() {
}
public Item(String title, String description, Float price) {
this.title = title;
this.description = description;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public List<UserOrder> getUserOrders() {
return userOrders;
}
public void setUserOrders(List<UserOrder> userOrders) {
this.userOrders = userOrders;
}
}
<file_sep>/src/main/java/com/dab/household/beans/UpdateUserBean.java
package com.dab.household.beans;
import com.dab.household.entity.User;
import com.dab.household.service.UserService;
import com.ocpsoft.pretty.faces.annotation.URLMapping;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import java.io.IOException;
@ManagedBean
@URLMapping(id = "update", pattern = "/auth/update", viewId = "/jsf/auth/update.xhtml")
public class UpdateUserBean {
@EJB
private UserService userService;
private User user;
public UpdateUserBean() {
user = (User) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
}
public void update() {
userService.updateUser(user);
}
public User getUser() {
return user;
}
public void updatePassword() {
try {
FacesContext.getCurrentInstance().getExternalContext()
.redirect("update/password");
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/com/dab/household/dao/jpa/JpaOrderDao.java
package com.dab.household.dao.jpa;
import com.dab.household.dao.OrderDao;
import com.dab.household.dao.UserDao;
import com.dab.household.entity.Cart;
import com.dab.household.entity.UserOrder;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;
@Stateless
public class JpaOrderDao implements OrderDao {
@PersistenceContext
private EntityManager em;
@Override
public UserOrder addOder(UserOrder userOrder) {
em.persist(userOrder);
return userOrder;
}
@Override
public UserOrder findOneById(Long id) {
return em.find(UserOrder.class, id);
}
@Override
public List<UserOrder> getAllOrders() {
List<UserOrder> userOrders;
try {
userOrders = em.createQuery("SELECT o FROM UserOrder o").getResultList();
} catch (Exception e) {
userOrders = new ArrayList<>();
}
return userOrders;
}
@Override
public List<UserOrder> getFromCart(Cart cart) {
List<UserOrder> userOrders;
try {
userOrders = em.createQuery("SELECT o FROM UserOrder o WHERE o.cart = :cart")
.setParameter("cart", cart)
.getResultList();
} catch (Exception e) {
userOrders = new ArrayList<>();
}
return userOrders;
}
}
<file_sep>/src/main/java/com/dab/household/beans/OldCartBean.java
package com.dab.household.beans;
import com.dab.household.entity.Cart;
import com.dab.household.entity.User;
import com.dab.household.service.CartService;
import com.dab.household.utils.Pager;
import com.ocpsoft.pretty.faces.annotation.URLMapping;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@ManagedBean
@URLMapping(id = "oldCart", pattern = "/auth/history/#{id}", viewId = "/jsf/auth/oldCart.xhtml")
public class OldCartBean {
@EJB
private CartService cartService;
private List<Cart> oldCarts;
private User user;
private Long id;
public OldCartBean() {
user = (User) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
this.id = Long.parseLong(req.getParameter("id"));
}
public List<Object> getOldCarts() {
oldCarts = cartService.getUserCarts(user);
return Pager.getList(oldCarts, this.id);
}
public List<Integer> getPager() {
return Pager.getPageList(oldCarts);
}
}
<file_sep>/src/main/java/com/dab/household/service/CartService.java
package com.dab.household.service;
import com.dab.household.dao.CartDao;
import com.dab.household.entity.Cart;
import com.dab.household.entity.User;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import java.util.List;
@Stateless
public class CartService {
@EJB
private CartDao cartDao;
public Cart addCart(Cart cart) {
return cartDao.addCart(cart);
}
public Cart findOneById(Long id) {
return cartDao.getOneById(id);
}
public List<Cart> getAllCarts() {
return cartDao.getAllCarts();
}
public List<Cart> getUserCarts(User user) {
return cartDao.getUserCarts(user);
}
}
|
6f41413edca69cfa7e6f0ebb0705d43b13b3d224
|
[
"Java"
] | 14
|
Java
|
Dauflo/4JVA
|
dae43e7fb03e447b29bd88355d5ff228bfef6458
|
1828eda7c8985f587f9b3496a55312d19945d622
|
refs/heads/master
|
<file_sep><?php
header('Content-Type: application/json; charset=UTF-8');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
$response = array();
$server_url = 'http://127.0.0.1:8000';
if (isset($_GET['id'])) {
$id = $_GET['id'];
$mysqli = new mysqli('127.0.0.1:3306','root','','student_profile');
mysqli_set_charset($mysqli,'utf8mb4');
$query = "Select student_info.*,student_father.*,student_mother.* from student_info left join student_father on
student_info.s_f_id = student_father.s_f_id left join student_mother on
student_info.s_m_id = student_mother.s_m_id where student_info.s_id=$id";
try{
$data = $mysqli->query($query);
}catch (mysqli_sql_exception $e){
$response = array(
"status" => "error",
"error" => true,
"message" => "Error fetching info!"
);
echo json_encode($response);
exit();
}
if( $data->fetch_array() != null){
$response = array(
"status" => "success",
"error" => false,
"message" => "Fetched info successfully",
"data" => $data->fetch_array()
);
}
else{
$response = array(
"status" => "error",
"error" => true,
"message" => "Error fetching info!"
);
}
}else {
$response = array(
"status" => "error",
"error" => true,
"message" => "Error fetching info!"
);
}
echo json_encode($response);
?><file_sep><?php
header('Content-Type: application/json; charset=UTF-8');
$response = array();
$server_url = 'http://127.0.0.1:8000';
$post = (array)json_decode(file_get_contents("php://input"));
if (isset($post["id"])) {
$id = $post["id"];
$uno = $post['uno'];
$startingyear = $post['startingyear'];
$mmSName = $post['mmSName'];
$enSName = $post['enSName'];
$nrc = $post['nrc'];
$nationaity = $post['nationality'];
$religion = $post['religion'];
$hometown = $post['hometown'];
$township = $post['township'];
// //$division = $post['division'];
//$citizenship = $post['citizenship'];
$dateOfBirth = $post['dateOfBirth'];
$bloodtype = $post['bloodtype'];
$phoneNo = $post['phoneNo'];
$lastRollNo = $post['lastRollNo'];
$matriRollNo = $post['matriRollNo'];
$matriYear = $post['matriYear'];
$matriexamdept = $post['matriexamdept'];
// //$address = $post['address'];
$f_mmFName = $post['mmFName'];
$f_enFName = $post['enFName'];
$f_nationaity = $post['f_nationality'];
$f_religion = $post['f_religion'];
$f_hometown = $post['f_hometown'];
$f_township = $post['f_township'];
$f_phoneNo = $post['f_phoneNo'];
$f_nrc = $post['f_nrc'];
$f_job = $post['f_job'];
$f_position = $post['f_position'];
$f_department= $post['f_department'];
$f_address= $post['f_address'];
$m_mmMName = $post['mmMName'];
$m_enMName = $post['enMName'];
$m_nationality = $post['m_nationality'];
$m_religion = $post['m_religion'];
$m_hometown = $post['m_hometown'];
$m_township = $post['m_township'];
$m_phoneNo = $post['m_phoneNo'];
$m_nrc = $post['m_nrc'];
$m_job = $post['m_job'];
$m_position = $post['m_position'];
$m_department= $post['m_department'];
$m_address= $post['m_address'];
$m_id = $post['m_id'];
$f_id= $post['f_id'];
//$address = $post['address'];
$mysqli = mysqli_connect('127.0.0.1:3306','root','','student_profile');
mysqli_set_charset($mysqli,'utf8mb4');
$query = " Update student_info
SET student_info.enSName = '$enSName',
student_info.mmSName = '$mmSName',
student_info.enSName = '$enSName',
student_info.nationality = '$nationaity',
student_info.religion = '$religion',
student_info.hometown = '$hometown',
student_info.township = '$township',
student_info.nrc = '$nrc',
student_info.dateOfBirth = '$dateOfBirth',
student_info.bloodtype = '$bloodtype',
student_info.lastRollNo = '$lastRollNo',
student_info.matriRollNo = '$matriRollNo',
student_info.matriYear = '$matriYear',
student_info.matriexamdept = '$matriexamdept'
where student_info.s_id='$id';";
$query.= " Update student_father
SET student_father.enFName = '$f_enFName',
student_father.mmFName = '$f_mmFName',
student_father.nationality= '$f_nationaity',
student_father.religion = '$f_religion',
student_father.hometown ='$f_hometown',
student_father.township = '$f_township',
student_father.nrc = '$f_nrc',
student_father.job = '$f_job',
student_father.position = '$f_position',
student_father.department= '$f_department',
student_father.f_address= '$f_address'
where student_father.s_f_id='$f_id';
";
$query.= " Update student_mother
SET student_mother.enMName = '$m_enMName',
student_mother.mmMName = '$m_mmMName',
student_mother.nationality= '$m_nationality',
student_mother.religion = '$m_religion',
student_mother.hometown ='$m_hometown',
student_mother.township = '$m_township',
student_mother.nrc = '$m_nrc',
student_mother.job = '$m_job',
student_mother.position = '$m_position',
student_mother.department= '$m_department',
student_mother.m_address= '$m_address'
where student_mother.s_m_id='$m_id';
";
if( mysqli_multi_query($mysqli,$query)){
$response = array(
"status" => "success",
"error" => false,
"message" => "Info Updated successfully",
);
}
else{
http_response_code(404);
$response = array(
"status" => "error",
"error" => true,
"message" => "Error Updating info!"
);
}
}else {
http_response_code(404);
$response = array(
"status" => "error",
"error" => true,
"message" => "Error updating info! No ID Specified",
);
}
echo json_encode($response);
?><?php
|
96ba5fff9ac721bf0839f9c43c33692453b8ff34
|
[
"PHP"
] | 2
|
PHP
|
TunNandaAung/student-profile
|
bde30a82e5dbbf7b4c183c13286d3b58932daa5c
|
ac4041a95201a73d3d37acfa82960eaef4911ade
|
refs/heads/master
|
<file_sep>#include <iostream>
#include <random>
#include <ctime>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
void subSquare();
void magicSquare();
void division();
int randRange(int min, int max); // Random Integer x, such that min <= x < max
int getInt(string prompt); //Safely aquire int from stdin
#ifdef Important Functions Below
void instruction();
void mainMenu();
void yesOrNo();
void oneTwoThree();
void transferToMainMenu();
void menuSection();
void end();
void ready();
void results();
#endif //End of Important Functions
int main()
{
srand(time(0));
cout << "My name is Program for Arithmetic for Understanding and Learning," << endl
<< "but you can call me Paul." << endl << endl;
char option; //Selection from main menu
do
{
cout << "Which game will you play, little epsilon?" << endl;
cout << "\tA) Arcade: Most Divisions (1 Player, Division)" << endl
<< "\tB) Versus: Subtract a Square (2 Players, Multiplicaton, Subtraction)" << endl
<< "\tC) Puzzle: Magic Square (1 Player, Addition)" << endl
<< "\tD) Quit" << endl
//<< "\tE) Summon Programmer" << endl
;
string options;
cin >> options;
option = options[0];
switch(option)
{
case 'C':
magicSquare();
break;
case 'B':
subSquare();
break;
case 'A':
division();
break;
case 'D':
cout << "Good bye" << endl;
break;
}
}
while(option != 'D');
}
void subSquare()
{
cout << endl;
cout << "Instructions:" << endl
<< "\tThis game is called \"subtract a square.\" The goal of the game" << endl
<< "\tis to move last. There is a certain number, called the total." << endl
<< "\tI, Paul, shall select the total. Then, little epsilons, one of" << endl
<< "\tyou shall select a number, called the move. You can select any number" << endl
<< "\tbesides 0 (and no decimals or fractions.) You will then" << endl
<< "\tmultiply the move by itself, making a square number. Note: If your" << endl
<< "\tsquare is greater than the total, then you will have to pick a new" << endl
<< "\t move. You will then subtract the total by the square. You will take" << endl
<< "\tturns doing this. Whoever gets it to 0 will win!" << endl
<< "\tIf you want to quit, type 0." << endl
<< endl << "\tDon't worry, I will walk you through the game, little epsilons." << endl << endl;
string name[2]; //Store the names in an array
cin.ignore();
cout << "First little epsilon, what is your name? ";
getline(cin, name[0]);
cout << "Second little epsilon, what is your name? ";
getline(cin, name[1]);
int level;
do
{
level = getInt("Little epsilons, what difficulty will you play? (1 or more)(start with 1) ");
}
while(level < 1);
int total = randRange(pow(10, level-1), pow(10, level)); //level is number of digits
int turn = 0; //Index of name array, a.k.a., switches between 0 and 1
while (total != 0)
{
cout << "The total is " << total << endl;
cout << name[turn] << " it is your turn." << endl;
cout << name[turn] << " pick a move." << endl;
while(true)
{
int move;
move = getInt(name[turn] + ": ");
if (move == 0)
{
cout << "Are you sure you want to quit (y/n)? ";
string ans;
cin >> ans;
if (ans[0] == 'y') return;
else continue;
}
if (move * move > total)
{
cout << "Sorry, but with move " << move << ", you square would be " << endl
<< move << " x " << move << " = " << move * move
<< ", which is more than the total, " << total << "." << endl;
cout << "Pick another." << endl;
continue;
}
int square;
do
{
cout << "Now, " << move << " x " << move << " is what?" << endl;
square = getInt(name[turn] + ": ");
if (move * move != square) cout << "That is wrong!" << endl;
else break;
}
while(true);
cout << "Yes!" << endl;
int newTotal; //Temporary total until user gets newTotal correct
do
{
cout << "And " << total << " - " << square << " is what?" << endl;
newTotal = getInt(name[turn] + ": ");
if (total - square != newTotal) cout << "That is wrong!" << endl;
else break;
}
while(true);
cout << "Yes!" << endl;
total = newTotal;
break;
}
turn = (turn + 1) % 2;
}
int loser = turn;
int winner = (loser + 1) % 2; //Other player
cout << name[winner] << ", you have WON! Congratulations." << endl;
cout << "Better luck next time " << name[loser] << ". :(" << endl;
}
int win[8][3] = //Rows, Columns, and Diagonals
{
{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{0, 3, 6},
{1, 4, 7},
{2, 5, 8},
{0, 4, 8},
{6, 4, 2}
};
char choices[9] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J'}; //Indexed cell names
void magicSquare()
{
string name;
cin.ignore();
cout << "What is your name, little epsilon? ";
getline(cin, name);
int level; //Determines size of magic constant
do
{
level = getInt("What level will you play little epsilon? (1 or more) ");
}
while(level < 1);
int magic = 3 * randRange(5*level, 5*(level+1)); //Random number from 15 * level to 15 * level + 15, that is divisible by 3
int width = ceil(log10(magic)); //Guaranteed to be at least as many as the digits in magic, for formatting purposes
cout << "Instructions: " << endl
<< "\tIn this game, you try and make the rows," << endl
<< "\tcolumns, and diagonals add up to" << endl
<< "\ta special number called the magic constat." << endl
<< "\tAlso, you may not use the same" << endl
<< "\tnumber more than once. The magic constant" << endl
<< "\tfor you is \"" << magic << ".\" Change the boxes" << endl
<< "\tso that each row, column, and diagonal," << endl
<< "\tadd up to \"" << magic << ".\" It will then quiz you" << endl
<< "\tto see if you are right. Answer the addition problems honestly." << endl
;
cout << endl << "Do not worry, little epsilon. I, paul, will walk you through it." << endl << endl;
int square[9] = {0};
while(true)
{
cout << endl;
for (int i=0; i < 9; i++) //Display the Square Loop
{
cout << choices[i] << setw(width) << square[i];
if ((i+1)%3 == 0) //End of row
{
cout << endl;
}
else
{
cout << "|";
}
}
cout << "Magic Constant: " << magic << endl << endl;
cout << "Which square would you like to change? (Z:Check square, 0:Quit) ";
string moves;
cin >> moves;
char movec = moves[0];
for (int i=0; i < 9; i++)
{
if (choices[i] == movec)
{
int n;
do
{
n = getInt(name + ", what would you like to change that box to? ");
if (n < 0 || n > magic) //This also makes sure cells don't violate cell width
{
cout << "That can not possibly be right; try again." << endl;
}
else break;
}
while(true);
square[i] = n;
break;
}
}
if (movec == 'Z')
{
bool dup = false;
for (int i=0; i < 9; i++)
{
for (int j=0; j < 9; j++)
{
if (i != j && square[i] == square[j])
{
cout << endl;
cout << "Sorry, but you have " << square[i] << " at least twice. You must change them to be different." << endl;
dup = true;
break;
}
}
if (dup) break;
}
if (dup) continue;
bool won = true;
for (int i=0; i < 8; i++)
{
int s;
do
{
cout << "What is " << square[win[i][0]] << " + " << square[win[i][1]] << " + " << square[win[i][2]] << "? ";
s = getInt(name + ": ");
if (s != (square[win[i][0]] + square[win[i][1]] + square[win[i][2]]))
{
cout << "Sorry, that is not right. Try again." << endl;
cout << "What is " << square[win[i][0]] << " + " << square[win[i][1]] << " + " << square[win[i][2]] << "? ";
}
else break;
}
while(true);
cout << "Right!" << endl;
if (s!=magic)
{
cout << s << " is not the magic constant, " << magic << ", though. You will have to change something." << endl;
won = false;
break;
}
}
if (won) break;
}
if (movec=='0')
{
cout << "Are you sure you want to quit (y/n)? ";
string ans;
cin >> ans;
if (ans[0] == 'y') break;
}
}
cout << "Since these are all the magic constant, you have won, " << name << "!" << endl;
}
void division()
{
cout << endl;
cout << "Instructions" << endl
<< "\tIn this game, you are trying to get as many points as you can." << endl
<< "\tI, paul, shall pick a number called the total. Each turn, you" << endl
<< "\tshall pick a number, called the move. The total must be divisible" << endl
<< "\tby the move. You will then divide the total by the move. Each turn," << endl
<< "\tyou get one point. You may not divide by 1, as this would allow you" << endl
<< "\tto go on forever. No decimals, fractions, or negatives either." << endl
<< "\tWhen you get to one, the game is over. Type 0 to quit." << endl
<< endl << "\tTry and get the high score, little epsilon!" << endl << endl;
string name;
cin.ignore();
cout << "What is your name, little epsilon? ";
getline(cin, name);
int level; //Number of digits == level + 1
do
{
level = getInt("What level will you play little epsilon? (1 or more) ");
}
while(level < 1);
int total = randRange(pow(10, level), pow(10, level+1));
int score = 0;
while(total!=1)
{
cout << "Your score is " << score << "." << endl;
cout << "The total is " << total << "." << endl;
cout << "Pick a number that you can divide into " << total << "." << endl;
int div = getInt(name + ": ");
if (div == 0)
{
cout << "Are you sure you want to quit (y/n)? ";
string ans;
cin >> ans;
if (ans[0] == 'y') return;
else continue;
}
if (div == 1)
{
cout << "1 is cheating." << endl;
cout << "Try again." << endl;
}
if (not (total % div == 0))
{
cout << div << " is not divisible by " << total << endl;
cout << "Try again." << endl;
continue;
}
if (div < 0)
{
cout << "Smart kid, but no negatives. Sorry." << endl;
cout << "Try again." << endl;
continue;
}
int newTotal; //temporary variable for the new total until user gets it right
while(true)
{
cout << "Now, what is " << total << "/" << div << "?" << endl;
newTotal = getInt(name + ": ");
if (newTotal != total / div)
{
cout << "That is wrong, try again." << endl;
}
else break;
}
total = newTotal;
score++;
}
cout << "That is it. Your score is " << score << ", " << name << "." << endl;
ifstream file(to_string(level), ios::in);
int highscore;
bool newscore = false;
if (file.is_open())
{
file >> highscore;
cout << "The high score for level " << level << " was " << highscore << endl;
if (highscore >= score)
{
cout << "Sorry, you did not beat it this time." << endl;
}
else
{
cout << "You got the high score!" << endl;
}
file.close();
}
else
{
cout << "There was no previous high score for level " << level << ", so the high score is yours!" << endl;
newscore=true;
}
if (newscore)
{
ofstream newfile(to_string(level), ios::out);
newfile << score;
newfile.close();
}
}
int randRange(int min, int max)
{
return (rand() % (max-min))+min;
}
// Based on http://stackoverflow.com/a/10349885/1172541, thanks to chris
int getInt(string prompt)
{
int num;
while (cout << prompt && !(cin >> num))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Sorry, that is not a number." << endl;
cout << "You may now try again." << endl;
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return num;
}
#ifdef Important Functions Defined Here
string instruction()
{
cout >> "In this game you do arithmetic." << endl;
cout >> "And arithmetic is fun!" << endl:
return 0;
}
void mainMenu()
{
switch(option)
case 1:
Add
break;
case 2:
Subtract
break;
case 3:
Multiply
break;
case 4:
Divide and Conqueror
break;
case:
case case case return case;
}
void yesOrNo(bool yesOrNo)
{
return yesOrNo;
}
array oneTwoThree()
{
return 1;
return 2;
return 3;
}
void transferToMainMenu(mainMenu)
{
'(transfer mainMenu)
}
void end()
{
print "Sorry, game over"
}
void ready()
{
main :: IO()
main = do
a <- readLine
b <- readLine
return $ a + b
}
void results()
{
system.out.println("The result is you win!");
}
#endif //End of important functions
|
c33021f6259c6fcd88bd939cd47588d4ec331b9e
|
[
"C++"
] | 1
|
C++
|
TheKing42/Final
|
8a0a8116fc6c7748b411ea25e1daf3ac68a50824
|
1caddbb070a7daa0b6a8bc787c2274698594f61a
|
refs/heads/master
|
<file_sep>import matplotlib.pyplot as plt
from pylab import * # for plotting commands
import numpy as numpy
import math
#<NAME>
#This program solves a wave-like form of the Navier Stokes Equation under a set of assumptions.
#Equation details: -Incompressible form, newtonian fluid
c=0.5
nMax=20 #Number of time steps we want to tak
iMax=20 #This dictates the number of i's starting at 0
uTemp=[]
dt=.1
dx = (2.0-0) / (iMax) #since the index STARTS at 1, we dont need to add 1 to the denominator like usual
u = numpy.ones(iMax) #Set some ones
#setting u = 2 between 0.5 and 1 because of the initial conditions
u[.5/dx : 1/dx+1]=2
# for n in range(0, nMax, dt): #This for loop is moving forward in time
for n in range (nMax):
uTemp=u
print uTemp
for i in range(1,iMax):
#Calculate and store values into list
# u[i]= ( -uTemp[i] ) * ( dt/dx ) * ( uTemp[i] - uTemp[i-1] ) + uTemp[i]
u[i]= ( -c ) * ( dt/dx ) * ( uTemp[i] - uTemp[i-1] ) + uTemp[i]
print u
plt.plot(linspace(0,2,iMax),u)
plt.axis((0, 2 , 0, 2) )
plt.show()
|
c2f51702a245d0e2556631ce67d1b21dd05b59b2
|
[
"Python"
] | 1
|
Python
|
flnguyen/CFD
|
34ab5b53b7348f43499344772f3548143b334023
|
cfcc6a1ab617a60354443b3c9acff082d04cf0fc
|
refs/heads/master
|
<file_sep>import React from 'react';
import Footer from './Footer';
import Header from './Header';
import ListItem from './ListItem';
import ListsList from './ListsList';
import NewList from './NewList';
import TodoItem from './TodoItem';
import TodoList from './TodoList';
import TodoService from './../services/TodoService';
export default class Main extends React.Component {
constructor(props) {
super(props);
var self = this;
self.todoService = new TodoService();
self.state = {
lists: [],
selectedListId: null,
selectedListTodos: []
};
}
setLists = (lists) => {
this.setState({
lists
});
}
addNewList = (newList) => {
var lists = this.state.lists;
lists.push(<ListItem key={newList._id} value={newList.name} id={newList._id} click={this.selectList.bind(this)} />);
this.selectList(newList._id);
this.setState({
lists
});
}
selectList = (selectedListId) => {
this.todoService.getTodos(selectedListId).then((res) => {
const dataList = res.map((data) =>
<TodoItem key={data._id} value={data.text} id={data._id} isComplete={data.isComplete} description={data.description} />
);
this.setState({
selectedListId,
selectedListTodos: dataList
});
});
}
addTodo = (newTodo) => {
var todos = this.state.selectedListTodos;
todos.push(<TodoItem key={newTodo._id} value={newTodo.text} id={newTodo._id} description={newTodo.description} />);
this.setState({
selectedListTodos: todos
});
}
render() {
return (
<div>
<Header />
<p>Selected List: {this.state.selectedListId}</p>
<NewList addNewList={this.addNewList.bind(this)} />
<ListsList
selectList={this.selectList.bind(this)}
setLists={this.setLists.bind(this)}
lists={this.state.lists} />
<hr/>
<TodoList
todos={this.state.selectedListTodos}
listId={this.state.selectedListId}
addTodo={this.addTodo.bind(this)} />
<hr />
<Footer />
</div>
);
}
}
<file_sep>import AjaxService from './AjaxService';
export default class ListService {
constructor() {
this.ajax = new AjaxService();
}
createNewList = (newListName) => {
const body = {
name: newListName
}
return new Promise((resolve, reject) => {
var url = 'http://localhost:8080/api/list';
this.ajax.ajaxPost(url, body).then((res) => {
resolve(res.json());
});
});
}
getLists = () => {
return new Promise((resolve, reject) => {
var url = 'http://localhost:8080/api/list';
this.ajax.ajaxGet(url).then((res) => {
resolve(res.json());
});
});
}
}<file_sep>to run api: nodemon server/server.js
to run front-end: webpack --watch<file_sep>import React from 'react';
import TodoService from './../services/TodoService';
export default class TodoItem extends React.Component {
constructor(props) {
super(props);
this.todoService = new TodoService();
this.state = {
isComplete: this.props.isComplete
};
}
markDone = () => {
this.todoService.markAsDone(this.props.id).then((res) => {
this.setState({
isComplete: res.data.isComplete
})
});
}
render() {
return (
<li>
{this.props.value}
{ this.props.description && this.props.description.length
? <em> - {this.props.description} </em>
: ''
}
{ this.state.isComplete
? ''
: <button onClick={this.markDone.bind(this)}>Mark Done</button>
}
</li>
);
}
}<file_sep>import React from 'react';
import ListService from './../services/ListService';
export default class NewList extends React.Component {
constructor(props) {
super(props);
this.listService = new ListService();
this.state = {
newListName: ''
};
}
changeName = (event) => {
this.setState({
newListName: event.target.value
});
}
submit = (event) => {
event.preventDefault();
this.listService.createNewList(this.state.newListName).then((res) => {
this.props.addNewList(res.data);
this.setState({
newListName: ''
});
});
}
render() {
return (
<div>
<h3>Create a new Todo List</h3>
<input type="text" placeholder="New List Name" value={this.state.newListName} onChange={this.changeName.bind(this)} />
<button onClick={this.submit.bind(this)}>Submit</button>
</div>
);
}
}
<file_sep>// server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Todo = require('./models/todo');
var List = require('./models/list');
var routes = require('./routes');
var cors = require('cors');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
mongoose.connect('mongodb://127.0.0.1:27017/react_todo');
var port = process.env.PORT || 8080;
var router = express.Router();
app.use('/api', routes);
app.listen(port);
console.log('API running on port ' + port);<file_sep>import React from 'react';
import TodoService from './../services/TodoService';
export default class TodoList extends React.Component {
constructor(props) {
super(props);
this.todoService = new TodoService();
this.state = {
newTodo: '',
newDescription: ''
}
}
updateName = (event) => {
this.setState({
newTodo: event.target.value
});
};
updateDescription = (event) => {
this.setState({
newDescription: event.target.value
});
}
submit = (event) => {
event.preventDefault();
if(!this.state.newTodo.length) {
return;
}
this.todoService.postTodo(this.state.newTodo, this.state.newDescription, this.props.listId).then((res) => {
this.props.addTodo(res.data);
this.setState({
newTodo: '',
newDescription: '',
isComplete: false
});
});
};
render() {
return (
<div>
{this.props.listId ?
<div>
<input type="text" placeholder="New Todo" value={this.state.newTodo} onChange={this.updateName.bind(this)} />
<input type="text" placeholder="Description (optional)" value={this.state.newDescription} onChange={this.updateDescription.bind(this)} />
<button onClick={this.submit.bind(this)}>Submit</button>
</div> : ''}
{this.props.todos.length || !this.props.listId ? '' : <div><em>No todo items for this list. Please add one.</em></div>}
{this.props.todos}
</div>
);
}
}<file_sep>import AjaxService from './AjaxService';
export default class TodoService {
constructor() {
this.ajax = new AjaxService();
}
getTodos = (listId) => {
return new Promise((resolve, reject) => {
const url = 'http://localhost:8080/api/todo/' + listId;
this.ajax.ajaxGet(url).then((res) => {
resolve(res.json());
});
});
}
postTodo = (text, description, list_id) => {
return new Promise((resolve, reject) => {
const url = 'http://localhost:8080/api/todo';
const body = {
text,
description,
list_id
};
this.ajax.ajaxPost(url, body).then((res) => {
resolve(res.json());
});
});
}
markAsDone = (todo_id) => {
return new Promise((resolve, reject) => {
const url = 'http://localhost:8080/api/todo/markDone';
const body = {
todo_id
};
this.ajax.ajaxPost(url, body).then((res) => {
resolve(res.json());
});
});
}
}<file_sep>import React from 'react';
export default class Footer extends React.Component {
render() {
return (
<footer>
<span>© <NAME> 2017</span>
<span>|</span>
<span>
<a href="http://www.chrisperko.net/">ChrisPerko.NET</a>
</span>
</footer>
);
}
}
<file_sep>var express = require('express');
var listController = require('./controllers/listController');
var todoController = require('./controllers/todoController');
const routes = express();
routes.post('/list', listController.post);
routes.get('/list', listController.getAll);
routes.post('/todo', todoController.post);
routes.post('/todo/markDone', todoController.markDone);
routes.get('/todo/:list_id', todoController.get);
routes.put('/todo/:todo_id', todoController.update);
routes.delete('/todo/:todo_id', todoController.delete);
module.exports = routes;
|
6dcd83a1db58de6193ce3fe21444a322f228c1c0
|
[
"JavaScript",
"Markdown"
] | 10
|
JavaScript
|
BaronVonPerko/react-todo
|
d8cf4f715dec88fdd79768db85c2006fc2961719
|
8f399b1463350b75ce13f712d0f797dfebd37629
|
refs/heads/main
|
<file_sep>#ifndef TRAIN_H
#define TRAIN_H
#include "face.hpp"
#include <QThread>
#include <QMessageBox>
#include <vector>
#include <iostream>
#include <stdio.h>
#include <QDebug>
#include <opencv2\opencv.hpp>
#include <opencv2\core.hpp>
#include <opencv2\highgui.hpp>
#include <opencv2\imgproc.hpp>
#include <math.h>
#include <fstream>
#include <sstream>
using namespace std;
using namespace cv;
#define SEPARATOR ';'
class TrainThread:public QThread
{
Q_OBJECT
signals:
void sigFinished();
void sigFailed();
public:
explicit TrainThread(QObject *parent = nullptr);
~TrainThread();
void run();
void train();
void read_csv(const string &, vector<Mat> &, vector<int> &, char);
};
#endif // TRAIN_H
<file_sep>#ifndef ADMIWIDGET_H
#define ADMIWIDGET_H
#include "basewidget.h"
#include "facetrainwidget.h"
#include "recordwidget.h"
#include "settingwidget.h"
#include <QWidget>
namespace Ui {
class AdmiWidget;
}
class AdmiWidget : public BaseWidget
{
Q_OBJECT
public:
explicit AdmiWidget(QWidget *parent = nullptr);
~AdmiWidget();
void setSqlDatabase(QSqlDatabase db);
private slots:
void on_pushButton_setting_clicked();
void on_pushButton_face_clicked();
void on_pushButton_record_clicked();
void on_pushButton_exit_clicked();
protected:
void paintEvent(QPaintEvent *event);
public:
SettingWidget *mSettingWidget;
RecordWidget *mRecordWidget;
FaceTrainWidget *mFaceTrainWidget;
private:
Ui::AdmiWidget *ui;
};
#endif // ADMIWIDGET_H
<file_sep>#include "sqlitesingleton.h"
#include <QMessageBox>
#include <QSqlError>
#include <QSqlQuery>
#include <constants.h>
sqliteSingleton* sqliteSingleton::m_pInstance = NULL;
sqliteSingleton::Garbo m_Garbo;
QMutex sqliteSingleton::m_mutex;
sqliteSingleton::sqliteSingleton(QObject *parent)
{
}
void sqliteSingleton::initDB(QString db_type)
{
qDebug() << "初始化数据库";
if(db_type == "QSQLITE"){
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("myface.dat");
if (!db.open()) {
QSqlError lastError = db.lastError();
QMessageBox::warning(0, QObject::tr("Database Error"),
"数据库打开失败," + lastError.driverText());
return ;
}
}else if(db_type == "QMYSQL"){
db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName(HOST);
db.setDatabaseName(DATABASE); //这里输入你的数据库名
db.setUserName(USER);
db.setPassword(<PASSWORD>); //这里输入你的密码
db.setPort(PORT);
if (!db.open()) {
QSqlError lastError = db.lastError();
QMessageBox::warning(0, QObject::tr("Database Error"),
"数据库打开失败," + lastError.driverText());
return ;
}
}
}
void sqliteSingleton::createTable()
{
QSqlQuery query(db);
bool ret = query.exec("create table admi_info (id varchar(40) primary key, password varchar(20))");
qDebug() << "创建管理员信息表格admi_info" << ret;
ret = query.exec("create table stu_info (id varchar(40) primary key, name varchar(20))");
qDebug() << "创建学生信息表格stu_info" << ret;
ret = query.exec("create table record_info (id int primary key, stuId int, name varchar(20), clockDate varchar(40),clockTime varchar(40), isValid varchar(80))");
qDebug() << "创建打卡记录表格record_info" << ret;
insertAdmiTable("1", "654321");
insertStuTable("2016117249", "shenjun");
insertRecordTable("17310520301", "fangjun", "", "", "无效");
}
void sqliteSingleton::insertAdmiTable(QString id, QString pwd)
{
QSqlQuery query(db);
bool ret = query.exec(tr("insert into admi_info values('%1', '%2')").arg(id).arg(pwd));
qDebug() << "insertAdmiTable" << ret;
}
void sqliteSingleton::insertStuTable(QString id, QString name)
{
QSqlQuery query(db);
bool ret = query.exec(tr("insert into stu_info values('%1', '%2')").arg(id).arg(name));
qDebug() << "insertStuTable" << ret;
}
void sqliteSingleton::insertRecordTable(QString stu_id, QString name,
QString clock_date, QString clock_time, QString valid)
{
QSqlQuery query(db);
bool ret = query.exec(tr("insert into record_info(stuId, name, clockDate, clockTime, isValid) "
"values('%1', '%2', '%3', '%4','%5')")
.arg(stu_id)
.arg(name)
.arg(clock_date)
.arg(clock_time)
.arg(valid));
qDebug() << "insertRecordTable" << ret;
}
QString sqliteSingleton::getStudentName(QString id)
{
QString name;
QSqlQuery query(db);
bool ret = query.exec(tr("select * from stu_info where id='%1'").arg(id));
qDebug() << "getStudentName" << ret;
while (query.next()) {
name = query.value("name").toString();
qDebug()<<name;
}
return name;
}
QList<QString> sqliteSingleton::getAdmiPassword()
{
QList<QString> pwdList;
QSqlQuery query(db);
bool ret = query.exec(tr("select * from admi_info"));
qDebug() << "getAdmiPassword" << ret;
while (query.next()) {
pwdList.append(query.value("password").toString());
}
return pwdList;
}
<file_sep>#include "camerathread.h"
#include <QDateTime>
#include <QDebug>
#include <QImage>
#include "constants.h"
CameraThread::CameraThread()
{
g_rng(12345);
}
int CameraThread::Predict(Mat src_image)
{
Mat face_test;
int predict = 0;
//截取的ROI人脸尺寸调整
if (src_image.rows >= 120)
{
//改变图像大小,使用双线性差值
::resize(src_image, face_test, Size(92, 112));
}
//判断是否正确检测ROI
if (!face_test.empty())
{
//测试图像应该是灰度图
predict = model->predict(face_test);
}
cout << predict << endl;
return predict;
}
void CameraThread::run()
{
isWork = true;
//装载人脸识别分类器
cascade.load(HAARCASCADE_FRONTALFACE_ALT2.toStdString());
model = face::FisherFaceRecognizer::create();
model->read(MyFaceFisherModel_XML.toStdString());// opencv2用load加载训练好的模型
cap.open(0);
while (true) {
msleep(10);
// cap.open(0);
if(!isWork){
break;
}
try {
qDebug()<<"读取摄像头";
cap>>frame;//摄像头读取头像
} catch (exception ex) {
qDebug() << "摄像头读取异常";
}
try {
QDateTime startTime= QDateTime::currentDateTime();
FaceRecognition();
qDebug()<<"FaceRecognition time=" << startTime.msecsTo(QDateTime::currentDateTime()) /1000.0;
} catch (exception ex) {
qDebug() << "识别异常";
QImage tempImage = QImage((const unsigned char*)(frame.data),
frame.cols, frame.rows, frame.step,
QImage::Format_RGB888);
emit sigFaceResult(tempImage);
}
}
cap.release();
}
void CameraThread::FaceRecognition()
{
vector<Rect> faces(0);//建立用于存放人脸的向量容器
cvtColor(frame, gray, CV_RGB2GRAY);//测试图像必须为灰度图
cascade.detectMultiScale(gray, faces, 1.1, 4,
CV_HAAR_DO_ROUGH_SEARCH,
Size(30, 30),
Size(500, 500));
Mat* pImage_roi = new Mat[faces.size()]; //数组存所有的脸
Mat face;
Point text_lb;//文本写在的位置
//框出人脸
string str="NONE";
QString result="";
for (size_t i = 0; i < faces.size(); i++)
{
pImage_roi[i] = gray(faces[i]); //将所有的脸部保存起来
text_lb = Point(faces[i].x, faces[i].y);
if (pImage_roi[i].empty())
continue;
qDebug()<<"预测结果:"<<Predict(pImage_roi[i]);
result = QString::number(Predict(pImage_roi[i]));
str = result.toStdString();
Scalar color = Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255));//所取的颜色任意值
rectangle(frame, Point(faces[i].x, faces[i].y), Point(faces[i].x + faces[i].width, faces[i].y + faces[i].height), color, 1, 8);//放入缓存
putText(frame, str, text_lb, FONT_HERSHEY_COMPLEX, 1, Scalar(0, 0, 255));//添加文字
}
delete[]pImage_roi;
Mat temp;
cvtColor(frame, temp, CV_BGR2RGB);//BGR convert to RGB
// QImage tempImage = QImage((const unsigned char*)(temp.data),
// temp.cols, temp.rows, temp.step,
// QImage::Format_RGB888);
QImage tempImage(temp.data, temp.cols, temp.rows, temp.step1() , QImage::Format_RGB888);
emit sigFaceResult(tempImage);
msleep(10);
emit sigIDResult(result);
qDebug()<<"sigIDResult";
}
<file_sep>#ifndef FACEATTENDANCE_H
#define FACEATTENDANCE_H
#include <QMainWindow>
#include <iostream>
#include<opencv2\opencv.hpp>
#include<opencv2\core\core.hpp>
#include <fstream>
#include <sstream>
#include<math.h>
#include <QLabel>
#include <QTimer>
#include "admiwidget.h"
#include "basemainwindow.h"
#include "camerathread.h"
#include "face.hpp"
#include <QList>
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include "constants.h"
#include "showresultdialog.h"
using namespace std;
using namespace cv;
namespace Ui {
class FaceAttendance;
}
class FaceAttendance : public BaseMainWindow
{
Q_OBJECT
public:
explicit FaceAttendance(QWidget *parent = nullptr);
~FaceAttendance();
void initWidget();
QPixmap PixmapToRound(const QPixmap &src, int radius);
void appendLog(const QString &text);
bool isTimeValid(QString time);
private slots:
void on_pushButton_break_clicked();
void slotShowImage(QImage image);
void slotShowIDResult(QString id);
void showTime();
void on_pushButton_cam_clicked();
void on_pushButton_admi_clicked();
void slotSetTimePeriod(QString b_time, QString e_time);
private:
Ui::FaceAttendance *ui;
QTimer *mUpdateTimeTimer;
CameraThread *mCameraThread;
QLabel *label_date_time;
AdmiWidget *mAdmiWidget;
QSqlDatabase db;
ShowResultDialog *mShowResultDialog;
QString mBeginTime;
QString mEndTime;
};
#endif // FACEATTENDANCE_H
<file_sep>#ifndef BASEWIDGET_H
#define BASEWIDGET_H
#include <QWidget>
class BaseWidget: public QWidget
{
Q_OBJECT
public:
explicit BaseWidget(QWidget *parent = nullptr);
protected:
void mousePressEvent(QMouseEvent *ev);
void mouseMoveEvent(QMouseEvent *ev);
void mouseReleaseEvent(QMouseEvent *ev);
private:
QPoint posMouseOrigin; //鼠标原始位置
};
#endif // BASEWIDGET_H
<file_sep>#ifndef CONSTANTS_H
#define CONSTANTS_H
#include <QString>
const QString PROJECT_PATH = ".";
const QString ATT_FACES_PATH = PROJECT_PATH + "\\att_faces";
const QString AT_TXT_PATH = ATT_FACES_PATH + "\\at.txt";
const QString HAARCASCADE_FRONTALFACE_ALT2 = PROJECT_PATH + "\\tools\\haarcascade_frontalface_alt2.xml";
const QString MyFacePCAModel_XML = PROJECT_PATH + "\\tools\\MyFacePCAModel.xml";
const QString MyFaceFisherModel_XML = PROJECT_PATH + "\\tools\\MyFaceFisherModel.xml";
const QString MyFaceLBPHModel_XML = PROJECT_PATH + "\\tools\\MyFaceLBPHModel.xml";
const int MAX_CAP_IMAGE_NUM = 10; //最大采集图片数量
const int MAX_PROGRESS = MAX_CAP_IMAGE_NUM + 20;
//数据库配置
const QString HOST = "sh-cynosdbmysql-grp-3ychwa2k.sql.tencentcdb.com";
const QString USER = "root";
const QString PASSWORD = "<PASSWORD>";
const QString DATABASE = "Face";
const int PORT= 29718;
#endif // CONSTANTS_H
<file_sep>#include "basewidget.h"
BaseWidget::BaseWidget(QWidget *parent):
QWidget(parent)
{
// this->setWindowFlags(Qt::FramelessWindowHint);//去掉标题栏
// this->setWindowOpacity(0.9);//设置透明
}
void BaseWidget::mousePressEvent(QMouseEvent *ev)
{
this->posMouseOrigin = QCursor::pos(); //cursor是一个光标类
}
void BaseWidget::mouseMoveEvent(QMouseEvent *ev)
{
QPoint ptMouseNow = QCursor::pos();
QPoint ptDelta = ptMouseNow - this->posMouseOrigin;
move(this->pos() + ptDelta);
posMouseOrigin = ptMouseNow;
}
void BaseWidget::mouseReleaseEvent(QMouseEvent *ev)
{
}
<file_sep>#include "basemainwindow.h"
BaseMainWindow::BaseMainWindow(QWidget *parent):
QMainWindow(parent)
{
// this->setWindowFlags(Qt::FramelessWindowHint);//去掉标题栏
// this->setWindowOpacity(0.9);//设置透明
}
void BaseMainWindow::mousePressEvent(QMouseEvent *ev)
{
this->posMouseOrigin = QCursor::pos(); //cursor是一个光标类
}
void BaseMainWindow::mouseMoveEvent(QMouseEvent *ev)
{
QPoint ptMouseNow = QCursor::pos();
QPoint ptDelta = ptMouseNow - this->posMouseOrigin;
move(this->pos() + ptDelta);
posMouseOrigin = ptMouseNow;
}
void BaseMainWindow::mouseReleaseEvent(QMouseEvent *ev)
{
}
<file_sep>#include "recordwidget.h"
#include "ui_recordwidget.h"
#include <QDebug>
#include <QDir>
#include <QFileDialog>
#include <QFileDialog>
#include <QMessageBox>
#include <QSqlRecord>
#include "constants.h"
#include "sqlitesingleton.h"
RecordWidget::RecordWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::RecordWidget)
{
ui->setupUi(this);
}
RecordWidget::~RecordWidget()
{
delete ui;
}
void RecordWidget::setSqlDatabase(QSqlDatabase db)
{
this->db = db;
mSQLModel = new QSqlTableModel(this, this->db);
mSQLModel->setTable("record_info");
mSQLModel->setHeaderData(0,Qt::Horizontal,tr("序号"));
mSQLModel->setHeaderData(1,Qt::Horizontal,tr("学号"));
mSQLModel->setHeaderData(2,Qt::Horizontal,tr("姓名"));
mSQLModel->setHeaderData(3,Qt::Horizontal,tr("打卡日期"));
mSQLModel->setHeaderData(4,Qt::Horizontal,tr("打卡时间"));
mSQLModel->setHeaderData(5,Qt::Horizontal,tr("是否有效"));
mSQLModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
ui->tableView->setModel(mSQLModel);
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);//设置单元格不可编辑
ui->tableView->horizontalHeader()->setStretchLastSection(true);//设置最后一列填充后面表格
ui->tableView->setColumnHidden(0,true);//设置第0列隐藏
ui->tableView->setColumnWidth(3,200);//设置列宽,界面看起来更舒适
mSQLModel->select(); //选取整个表的所有行
}
void RecordWidget::on_pushButton_search_clicked()
{
QString idFilter="";
QString timeFilter="";
idFilter = tr("stuId = '%1'").arg(ui->lineEditID->text().toInt());
mSQLModel->setFilter(idFilter);
timeFilter = tr("clockDate = '%1'").arg(ui->dateEditTime->text());
qDebug()<< idFilter << timeFilter;
mSQLModel->setFilter(timeFilter);
mSQLModel->select(); //显示结果
}
void RecordWidget::on_pushButtonExport_clicked()
{
QDir dir;
QString fileName = QFileDialog::getSaveFileName(this,
tr("Open Excel"),
"",
tr("Excel Files (*.csv)"));
if (!fileName.isNull())
{
//fileName是文件名
qDebug()<<fileName;
QFile file(fileName); // 以上两行用时间戳作为文件名
if(file.open(QFile::WriteOnly | QFile::Truncate)) // 打开文件
{
QTextStream out(&file); // 输入流
int row = mSQLModel->rowCount();
int col = mSQLModel->columnCount();
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
QString value = mSQLModel->record(i).value(j).toString() + ",";
out << value;
}
out << "\n";
}
}
file.close();
QMessageBox::information(NULL, "提示", "导出成功!\n导出路径:" +fileName);
}
}
<file_sep>#ifndef FACETRAINWIDGET_H
#define FACETRAINWIDGET_H
#include <QWidget>
#include <QList>
#include <QStandardItemModel>
#include <QTimer>
#include "trainthread.h"
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
namespace Ui {
class FaceTrainWidget;
}
class FaceTrainWidget : public QWidget
{
Q_OBJECT
public:
explicit FaceTrainWidget(QWidget *parent = nullptr);
~FaceTrainWidget();
QList<QString> getAllFileFolder(QString dirPath);
void updateTableData();
bool DeleteFileOrFolder(const QString &strPath);
void CreateCSV();
private slots:
void on_pushButton_add_clicked();
void on_pushButton_del_clicked();
void on_pushButton_find_clicked();
void on_pushButton_cap_clicked();
void showImage();
void slotTrainFinished();
void slotTrainFailed();
private:
Ui::FaceTrainWidget *ui;
QTimer *mCapTimer; //拍照定时器
QImage *image;
VideoCapture cap;
Mat frame,myFace,frame_gray;//图像,人脸,灰度图像
CascadeClassifier cascada;
vector<Rect> faces;//vector容器存检测到的faces
int pic_num;
TrainThread *mTrainThread;
};
#endif // FACETRAINWIDGET_H
<file_sep>#ifndef CAMERATHREAD_H
#define CAMERATHREAD_H
#include <QThread>
#include <iostream>
#include<opencv2\opencv.hpp>
#include<opencv2\core\core.hpp>
#include <fstream>
#include <sstream>
#include<math.h>
#include <QImage>
#include "face.hpp"
using namespace std;
using namespace cv;
class CameraThread : public QThread
{
Q_OBJECT
public:
CameraThread();
int Predict(Mat src_image);
void run();//任务处理线程
void FaceRecognition();
signals:
void sigFaceResult(QImage image);
void sigIDResult(QString id);
public:
bool isWork;
private:
RNG g_rng;
Ptr<face::FaceRecognizer> model;
VideoCapture cap;
CascadeClassifier cascade;//分类器--人脸检测所用
Mat frame;//摄像头读入一帧图像
Mat gray;//灰度处理后图像
};
#endif // CAMERATHREAD_H
<file_sep>#include "showresultdialog.h"
#include "ui_showresultdialog.h"
#include <QPainter>
ShowResultDialog::ShowResultDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ShowResultDialog)
{
ui->setupUi(this);
this->setWindowFlags(Qt::FramelessWindowHint);//去掉标题栏
this->setWindowOpacity(0.9);//设置透明
isOk = false;
}
ShowResultDialog::~ShowResultDialog()
{
delete ui;
}
bool ShowResultDialog::getIsOk()
{
return isOk;
}
void ShowResultDialog::setID(QString id)
{
ui->lineEdit_id->setText(id);
}
QString ShowResultDialog::getID()
{
return ui->lineEdit_id->text();
}
void ShowResultDialog::setName(QString name)
{
ui->lineEdit_name->setText(name);
}
QString ShowResultDialog::getName()
{
return ui->lineEdit_name->text();
}
void ShowResultDialog::setTime(QString time)
{
ui->lineEdit_time->setText(time);
}
QString ShowResultDialog::getTime()
{
return ui->lineEdit_time->text();
}
void ShowResultDialog::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawPixmap(rect(), QPixmap(":/images/bg2.jpg"), QRect());
}
void ShowResultDialog::on_pushButton_cancel_clicked()
{
isOk = false;
close();
}
void ShowResultDialog::on_pushButton_sure_clicked()
{
isOk = true;
close();
}
<file_sep>#ifndef RECORDWIDGET_H
#define RECORDWIDGET_H
#include <QSqlTableModel>
#include <QWidget>
namespace Ui {
class RecordWidget;
}
class RecordWidget : public QWidget
{
Q_OBJECT
public:
explicit RecordWidget(QWidget *parent = nullptr);
~RecordWidget();
void setSqlDatabase(QSqlDatabase db);
private slots:
void on_pushButton_search_clicked();
void on_pushButtonExport_clicked();
private:
Ui::RecordWidget *ui;
QSqlDatabase db;
QSqlTableModel *mSQLModel;
};
#endif // RECORDWIDGET_H
<file_sep># FaceRecognition
人脸识别打卡系统
- 使用技术: qt + opencv + mysql/sqlite
- 使用说明: /docs/人脸识别打卡系统使用说明.pdf
- 联系方式:
- IT项目交流群-2群: 946286053
- IT项目交流群-1群: 245022761<file_sep>#include "admiwidget.h"
#include "ui_admiwidget.h"
#include <QDebug>
#include <QPainter>
AdmiWidget::AdmiWidget(QWidget *parent) :
BaseWidget(parent),
ui(new Ui::AdmiWidget)
{
ui->setupUi(this);
mSettingWidget = new SettingWidget(this);
mRecordWidget = new RecordWidget(this);
mFaceTrainWidget = new FaceTrainWidget(this);
ui->stackedWidget->addWidget(mSettingWidget);
ui->stackedWidget->addWidget(mRecordWidget);
ui->stackedWidget->addWidget(mFaceTrainWidget);
ui->stackedWidget->setCurrentWidget(mSettingWidget);
}
AdmiWidget::~AdmiWidget()
{
delete ui;
}
void AdmiWidget::setSqlDatabase(QSqlDatabase db)
{
mRecordWidget->setSqlDatabase(db);
}
void AdmiWidget::on_pushButton_setting_clicked()
{
qDebug()<<"切换设置页面";
ui->stackedWidget->setCurrentWidget(mSettingWidget);
}
void AdmiWidget::on_pushButton_face_clicked()
{
qDebug()<<"切换人脸录入界面";
ui->stackedWidget->setCurrentWidget(mFaceTrainWidget);
}
void AdmiWidget::on_pushButton_record_clicked()
{
qDebug()<<"切换打卡记录界面";
ui->stackedWidget->setCurrentWidget(mRecordWidget);
}
void AdmiWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
// painter.drawPixmap(rect(), QPixmap(":/images/bg.jpg"), QRect());
}
void AdmiWidget::on_pushButton_exit_clicked()
{
this->close();
}
<file_sep>#include "faceattendance.h"
#include "ui_faceattendance.h"
#include "passworddialog.h"
#include "admiwidget.h"
#include "sqlitesingleton.h"
#include <QDateTime>
#include <QInputDialog>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include <QBitmap>
#include <QPainter>
#include <QMessageBox>
#include <QDateTime>
#include <QDateTime>
FaceAttendance::FaceAttendance(QWidget *parent) :
BaseMainWindow(parent),
ui(new Ui::FaceAttendance)
{
ui->setupUi(this);
initWidget();
mUpdateTimeTimer = new QTimer(this);
connect(mUpdateTimeTimer, SIGNAL(timeout()), this, SLOT(showTime()));
mUpdateTimeTimer->start(1000);
mCameraThread = new CameraThread();
connect(mCameraThread, &CameraThread::sigFaceResult, this, &FaceAttendance::slotShowImage);
connect(mCameraThread, &CameraThread::sigIDResult, this, &FaceAttendance::slotShowIDResult);
connect(mAdmiWidget->mSettingWidget, &SettingWidget::sigTimePeriod, this, &FaceAttendance::slotSetTimePeriod);
appendLog("初始化系统");
}
FaceAttendance::~FaceAttendance()
{
mCameraThread->isWork = false;
mCameraThread->wait();
delete ui;
}
void FaceAttendance::initWidget()
{
mShowResultDialog = nullptr;
mAdmiWidget = new AdmiWidget();
this->setWindowIcon(QIcon(":/images/face5.png"));
label_date_time = new QLabel(this);
label_date_time->setStyleSheet("color: rgb(255, 255, 255);");
ui->statusBar->addWidget(label_date_time);
sqliteSingleton::getInstance()->initDB("QSQLITE");
sqliteSingleton::getInstance()->createTable();
mAdmiWidget->setSqlDatabase(sqliteSingleton::getInstance()->db);
}
void FaceAttendance::slotShowImage(QImage image)
{
try {
QPixmap mmp = QPixmap::fromImage(image);
mmp = mmp.scaled(ui->label_face->size());
mmp = PixmapToRound(mmp, 148);
ui->label_face->setScaledContents(true);
ui->label_face->setPixmap(mmp);
ui->label_face->show();
} catch (exception ex) {
qDebug() << "图片显示异常";
}
if(mCameraThread->isWork == false){
ui->label_face->setPixmap(QPixmap());
ui->label_face->clear();
}
}
void FaceAttendance::slotShowIDResult(QString id)
{
qDebug()<< "slotShowIDResult";
QString name = sqliteSingleton::getInstance()->getStudentName(id);
//数据库中有
if(!name.isEmpty()){
mCameraThread->isWork = false;
if(mShowResultDialog == nullptr)
mShowResultDialog = new ShowResultDialog();
mShowResultDialog->setID(id);
mShowResultDialog->setName(name);
QDateTime local(QDateTime::currentDateTime());
mShowResultDialog->setTime(local.toString("yyyy-MM-dd hh:mm:ss"));
mShowResultDialog->exec();
if(mShowResultDialog->getIsOk()){
bool isValid = isTimeValid(local.toString("hh:mm:ss"));
if(isValid){
sqliteSingleton::getInstance()->insertRecordTable(id, name,
local.toString("yyyy-MM-dd"),
local.toString("hh:mm:ss"),
"有效");
appendLog(name + "在规定时间完成打卡");
}else{
sqliteSingleton::getInstance()->insertRecordTable(id, name,
local.toString("yyyy-MM-dd"),
local.toString("hh:mm:ss"),
"无效");
appendLog(name + "在非规定时间打卡");
}
}
delete mShowResultDialog;
mShowResultDialog = nullptr;
mCameraThread->isWork = true;
mCameraThread->start();
}
}
void FaceAttendance::showTime()
{
QDateTime local(QDateTime::currentDateTime());
label_date_time->setText(local.toString("yyyy年MM月dd日 hh:mm:ss"));
}
/**
* @brief 退出系统
*/
void FaceAttendance::on_pushButton_break_clicked()
{
mCameraThread->isWork=false;
this->close();
}
QPixmap FaceAttendance::PixmapToRound(const QPixmap &src, int radius)
{
if (src.isNull()) {
return QPixmap();
}
QSize size(2*radius, 2*radius);
QBitmap mask(size);
QPainter painter(&mask);
painter.setRenderHint(QPainter::Antialiasing);
painter.setRenderHint(QPainter::SmoothPixmapTransform);
painter.fillRect(0, 0, size.width(), size.height(), Qt::white);
painter.setBrush(QColor(0, 0, 0));
painter.drawRoundedRect(0, 0, size.width(), size.height(), 150, 150);
QPixmap image = src.scaled(size);
image.setMask(mask);
return image;
}
void FaceAttendance::appendLog(const QString &text)
{
QDateTime local(QDateTime::currentDateTime());
QString localTime = local.toString("yyyy-MM-dd hh:mm:ss ");
ui->textBrowserLog->append(localTime + text);
}
bool FaceAttendance::isTimeValid(QString time)
{
if(mBeginTime.isEmpty() || mEndTime.isEmpty()){
return true;
}
qDebug()<<"打开时间="<<time;
qDebug()<<mBeginTime<<mEndTime;
if(time > mBeginTime && time < mEndTime){
return true;
}
return false;
}
void FaceAttendance::on_pushButton_cam_clicked()
{
static bool isOpen=false;
if(isOpen){
mCameraThread->isWork = false;
isOpen = false;
ui->pushButton_cam->setStyleSheet(
"border-image: url(:/images/cam-off.png);");
ui->label_face->setPixmap(QPixmap());
ui->label_face->clear();
}else{
mCameraThread->start();
isOpen = true;
ui->pushButton_cam->setStyleSheet(
"border-image: url(:/images/cam-on.png);");
}
}
void FaceAttendance::on_pushButton_admi_clicked()
{
PasswordDialog tPasswordDialog;
// tPasswordDialog.setPassword(getAdmiPassword());
tPasswordDialog.setPassword(sqliteSingleton::getInstance()->getAdmiPassword());
tPasswordDialog.exec();
if(tPasswordDialog.getIsOk()){
mAdmiWidget->setWindowModality(Qt::ApplicationModal);//设置模态
mAdmiWidget->show();
}
}
void FaceAttendance::slotSetTimePeriod(QString b_time, QString e_time)
{
appendLog(tr("设置打卡时间段: %1 ~ %2").arg(b_time).arg(e_time));
mBeginTime = b_time;
mEndTime = e_time;
}
<file_sep>#ifndef PASSWORDDIALOG_H
#define PASSWORDDIALOG_H
#include <QDialog>
namespace Ui {
class PasswordDialog;
}
class PasswordDialog : public QDialog
{
Q_OBJECT
public:
explicit PasswordDialog(QWidget *parent = nullptr);
~PasswordDialog();
bool getIsOk();
void setPassword(QList<QString> pwd);
protected:
void paintEvent(QPaintEvent *event);
private slots:
void on_num0_clicked();
void on_num1_clicked();
void on_num2_clicked();
void on_num3_clicked();
void on_num4_clicked();
void on_num5_clicked();
void on_num6_clicked();
void on_num7_clicked();
void on_num8_clicked();
void on_num9_clicked();
void on_delbt_clicked();
void on_endbt_clicked();
private:
Ui::PasswordDialog *ui;
bool isOk; //密码输入是否正确
QList<QString> mPwdList;
};
#endif // PASSWORDDIALOG_H
<file_sep>#ifndef SHOWRESULTDIALOG_H
#define SHOWRESULTDIALOG_H
#include <QDialog>
namespace Ui {
class ShowResultDialog;
}
class ShowResultDialog : public QDialog
{
Q_OBJECT
public:
explicit ShowResultDialog(QWidget *parent = nullptr);
~ShowResultDialog();
bool getIsOk();
void setID(QString id);
QString getID();
void setName(QString name);
QString getName();
void setTime(QString time);
QString getTime();
protected:
void paintEvent(QPaintEvent *event);
private slots:
void on_pushButton_cancel_clicked();
void on_pushButton_sure_clicked();
private:
Ui::ShowResultDialog *ui;
bool isOk;
};
#endif // SHOWRESULTDIALOG_H
<file_sep>#ifndef SQLITESINGLETON_H
#define SQLITESINGLETON_H
#include <QMutexLocker>
#include <QSharedPointer>
#include <QObject>
#include <QMutex>
#include <QDebug>
#include <QSqlDatabase>
class sqliteSingleton: public QObject
{
Q_OBJECT
public:
static sqliteSingleton *getInstance()
{
if(m_pInstance == NULL)
{
QMutexLocker mlocker(&m_mutex);
if(m_pInstance == NULL)
{
m_pInstance = new sqliteSingleton();
}
}
return m_pInstance;
}
void initDB(QString db_type);
void createTable();
void insertAdmiTable(QString id, QString pwd);
void insertStuTable(QString id, QString name);
void insertRecordTable(QString stu_id, QString name,QString clock_date, QString clock_time, QString valid);
QString getStudentName(QString id);
QList<QString> getAdmiPassword();
private:
explicit sqliteSingleton(QObject *parent = 0);//构造函数
sqliteSingleton(const sqliteSingleton &,QObject *parent = 0): QObject(parent) {}//拷贝构造函数
sqliteSingleton& operator =(const sqliteSingleton&){return *this;}//赋值操作符重写
static sqliteSingleton* m_pInstance;//定义单例指针
static QMutex m_mutex;//互斥锁
public:
QSqlDatabase db;
public:
class Garbo //专门用来析构m_pInstance指针的类
{
public:
~Garbo()
{
if(m_pInstance != NULL)
{
delete m_pInstance;
m_pInstance = NULL;
qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<"m_pInstance 被析构";
}
}
};
static Garbo m_garbo;
};
#endif // SQLITESINGLETON_H
<file_sep>#include "faceattendance.h"
#include <QApplication>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include "constants.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString fileName = QCoreApplication::applicationDirPath();
qDebug()<<fileName;
qDebug() << QDir::toNativeSeparators(fileName);
FaceAttendance w;
w.show();
return a.exec();
}
<file_sep>#include "facetrainwidget.h"
#include "ui_facetrainwidget.h"
#include "constants.h"
#include "sqlitesingleton.h"
#include <QDir>
#include <QMessageBox>
#include <QDebug>
#include <QSqlQuery>
#include <QStandardItemModel>
FaceTrainWidget::FaceTrainWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::FaceTrainWidget)
{
ui->setupUi(this);
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);//设置选中模式为选中行
ui->tableWidget->setSelectionMode( QAbstractItemView::SingleSelection);//设置选中单个
// ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
updateTableData();
mCapTimer = new QTimer;
connect(mCapTimer, SIGNAL(timeout()), this, SLOT(showImage()));//时间到后启动opencam时间
mTrainThread = new TrainThread(this);//训练线程
connect(mTrainThread, SIGNAL(sigFinished()), this, SLOT(slotTrainFinished()));
connect(mTrainThread, SIGNAL(sigFailed()), this, SLOT(slotTrainFailed()));
//装载人脸识别分类器
cascada.load(HAARCASCADE_FRONTALFACE_ALT2.toStdString());
}
FaceTrainWidget::~FaceTrainWidget()
{
if ( mTrainThread->isRunning() )
{
mTrainThread->wait();
}
delete ui;
}
QList<QString> FaceTrainWidget::getAllFileFolder(QString dirPath)
{
QList<QString> folderList;
QDir dir(dirPath);
dir.setFilter(QDir::Dirs);
foreach(QFileInfo fullDir, dir.entryInfoList())
{
if(fullDir.fileName() == "." || fullDir.fileName() == "..") continue;
folderList.append(fullDir.fileName());
}
return folderList;
}
void FaceTrainWidget::updateTableData()
{
QList<QString> list = getAllFileFolder(ATT_FACES_PATH);
qDebug()<<list;
int row = 0;
ui->tableWidget->setRowCount(list.length());
foreach (QString id, list) {
qDebug()<<id;
QTableWidgetItem *item;
item = new QTableWidgetItem(id);
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); //文本对齐格式
ui->tableWidget->setItem(row,0,item); //为单元格设置Item
item = new QTableWidgetItem(ATT_FACES_PATH + "\\" + id);
item->setToolTip(ATT_FACES_PATH + "\\" + id);
ui->tableWidget->setItem(row,1,item); //为单元格设置Item
row ++;
}
}
bool FaceTrainWidget::DeleteFileOrFolder(const QString &strPath)
{
if (strPath.isEmpty() || !QDir().exists(strPath))//是否传入了空的路径||路径是否存在
return false;
QFileInfo FileInfo(strPath);
if (FileInfo.isFile())//如果是文件
QFile::remove(strPath);
else if (FileInfo.isDir())//如果是文件夹
{
QDir qDir(strPath);
qDir.removeRecursively();
}
return true;
}
void FaceTrainWidget::CreateCSV()
{
QList<QString> list = getAllFileFolder(ATT_FACES_PATH);
qDebug()<<list;
DeleteFileOrFolder(AT_TXT_PATH);
QFile file(AT_TXT_PATH);
file.open(QIODevice::ReadWrite | QIODevice::Text); //打开文件,不存在则创建
QString img_type = ".jpg";
foreach (QString id, list) {
// if(id[0] == "s" ){
// img_type = ".pgm";
// }else{
// img_type = ".jpg";
// }
for(int i=1;i<=MAX_CAP_IMAGE_NUM;i++) {
QString str= ATT_FACES_PATH + "\\" + id
+ "/" + QString::number(i)+ img_type + ";"+id;
//写入文件需要字符串为QByteArray格式
file.write(str.toUtf8() + "\n");
}
}
file.close();
}
void FaceTrainWidget::on_pushButton_add_clicked()
{
// pic_num = 0;
QString id = ui->lineEdit_num->text();
QString name = ui->lineEdit_name->text();
if(id.isEmpty()){
QMessageBox::information(NULL, "提示", "请输入学号!");
return;
}
if(name.isEmpty()){
QMessageBox::information(NULL, "提示", "请输入姓名!");
return;
}
QList<QString> list = getAllFileFolder(ATT_FACES_PATH);
qDebug()<<list;
if(list.contains(id)){
QMessageBox::warning(NULL, "提示", "该学号已经存在!");
return;
}
QString distPath = ATT_FACES_PATH + "//"+ id;
qDebug()<<distPath;
QDir dir;
bool res = dir.mkpath(distPath);
if(res){
sqliteSingleton::getInstance()->insertStuTable(id,name);
QMessageBox::information(NULL, "提示", "添加成功");
}
else{
QMessageBox::warning(NULL, "提示", "添加失败");
}
updateTableData();
}
void FaceTrainWidget::on_pushButton_del_clicked()
{
QModelIndex index = ui->tableWidget->selectionModel()->currentIndex();
int row = index.row();
if(row <=-1){
QMessageBox::information(NULL, "提示", "请选中一行!");
return;
}
qDebug()<<row;
QString id = ui->tableWidget->item(row,0)->text();
QString path = ui->tableWidget->item(row,1)->text();
QString sql = QString ("delete from staff_info where id='%1'").arg(id);
QSqlQuery query(sql);
bool del_ret = DeleteFileOrFolder(path);
if(del_ret){
QMessageBox::information(NULL, "提示", "已删除学号:"+id);
}else{
QMessageBox::warning(NULL, "提示", "删除失败!");
}
updateTableData();
}
void FaceTrainWidget::on_pushButton_find_clicked()
{
updateTableData();
}
void FaceTrainWidget::on_pushButton_cap_clicked()
{
QModelIndex index = ui->tableWidget->selectionModel()->currentIndex();
int row = index.row();
if(row <=-1){
QMessageBox::information(NULL, "提示", "请选中一行!");
return;
}
pic_num = 0;
cap.open(0);
mCapTimer->start(1000);
ui->progressBarTrain->setMaximum(MAX_PROGRESS);
ui->progressBarTrain->setValue(0);
}
void FaceTrainWidget::showImage()
{
// cap.open(0);
Mat temp;//临时保存RGB图像
cap>>frame;//摄像头读取头像
cvtColor(frame, frame_gray, COLOR_BGR2GRAY);//转灰度化,减少运算
cascada.detectMultiScale(frame_gray, faces, 1.1, 4,
CV_HAAR_DO_ROUGH_SEARCH,
Size(70, 70),
Size(1000, 1000));
ui->label_tip->setText("检测到人脸个数=" + QString::number(faces.size()));
qDebug()<<"检测到人脸个数:" + QString::number(faces.size());
//识别到的脸用矩形圈出
for (int i = 0; i < faces.size(); i++)
{
rectangle(frame, faces[i], Scalar(255, 0, 0), 2, 8, 0);
}
cvtColor(frame, temp, CV_BGR2RGB);//BGR convert to RGB
QImage Qtemp = QImage((const unsigned char*)(temp.data),
temp.cols, temp.rows, temp.step,
QImage::Format_RGB888);
ui->label_face->setScaledContents(true);
ui->label_face->setPixmap(QPixmap::fromImage(Qtemp));
//当只有一个人脸时,开始拍照
if (faces.size() == 1)
{
pic_num ++;
ui->label_tip->setText("已经采集头像第" + QString::number(pic_num) + "张");
Mat faceROI = frame_gray(faces[0]);//在灰度图中将圈出的脸所在区域裁剪出
::resize(faceROI, myFace, Size(92, 112));//将兴趣域size为92*112
//在 faces[0].tl()的左上角上面写序号
putText(frame, to_string(pic_num), faces[0].tl(), 3, 1.2, (0, 0, 225), 2, 0);
Mat temp;//临时保存RGB图像
cvtColor(frame, temp, CV_BGR2RGB);//BGR convert to RGB
QImage Qtemp = QImage((const unsigned char*)(temp.data),
temp.cols, temp.rows, temp.step,
QImage::Format_RGB888);
//图片的存放位置
QModelIndex index = ui->tableWidget->selectionModel()->currentIndex();
int row = index.row();
QString image_path = ui->tableWidget->item(row,1)->text() +
"\\" + QString::number(pic_num) + ".jpg";
image_path = QDir::toNativeSeparators(image_path);
string filename = image_path.toStdString();
imwrite(filename, myFace);//存在当前目录下
ui->progressBarTrain->setValue(pic_num);
if(pic_num >= MAX_CAP_IMAGE_NUM){
ui->label_tip->setText("采集完毕,生成训练文件");
mCapTimer->stop();
cap.release();
//生成训练文件
CreateCSV();
//训练
this->setEnabled(false);
mTrainThread->start();
}
}
}
void FaceTrainWidget::slotTrainFinished()
{
this->setEnabled(true);
ui->label_tip->setText("训练完成");
ui->progressBarTrain->setValue(MAX_PROGRESS);
QMessageBox::information(NULL, "提示", "训练完成!");
}
void FaceTrainWidget::slotTrainFailed()
{
this->setEnabled(true);
QMessageBox::information(NULL, "提示", "训练失败!");
}
<file_sep>#include "settingwidget.h"
#include "ui_settingwidget.h"
#include <QMessageBox>
#include <QPainter>
SettingWidget::SettingWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::SettingWidget)
{
ui->setupUi(this);
}
SettingWidget::~SettingWidget()
{
delete ui;
}
void SettingWidget::on_pushButton_save_clicked()
{
QString begin_time = ui->timeEdit_begin->text();
QString end_time = ui->timeEdit_end->text();
if(end_time > begin_time){
emit sigTimePeriod(begin_time, end_time);
QMessageBox::information(NULL, "提示", "设置成功!");
}else{
QMessageBox::information(NULL, "提示", "结束时间必须大于开始时间!");
}
}
<file_sep>#include "trainthread.h"
#include <QDebug>
#include <QDir>
#include "constants.h"
TrainThread::TrainThread(QObject *parent):QThread(parent)
{
}
TrainThread::~TrainThread()
{
}
void TrainThread::run()
{
qDebug()<<"启动训练线程";
sleep(2);
try {
train();
emit sigFinished();
} catch (exception ex) {
emit sigFailed();
}
}
void TrainThread::train()
{
//读取你的CSV文件路径.
string fn_csv = AT_TXT_PATH.toStdString();
// 2个容器来存放图像数据和对应的标签
vector<Mat> images;
vector<int> labels;
try
{
read_csv(fn_csv, images, labels,SEPARATOR); //从csv文件中批量读取训练数据
}
catch (cv::Exception& e)
{
cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
exit(1);
}
qDebug()<<"训练1------------------------------";
// 如果没有读取到足够图片,也退出.
if (images.size() <= 1) {
string error_message = "至少需要2张图片才能运行,请添加更多的图片到您的数据集";
CV_Error(CV_StsError, error_message);
}
for (int i = 0; i < images.size(); i++)
{
//cout<<images.size();
if (images[i].size() != Size(92, 112))
{
cout << i << endl;
cout << images[i].size() << endl;
}
}
qDebug()<<"训练2------------------------------";
// 下面的几行代码仅仅是从你的数据集中移除最后一张图片,作为测试图片
Mat testSample = images[images.size() - 1];
int testLabel = labels[labels.size() - 1];
images.pop_back();//删除最后一张照片,此照片作为测试图片
labels.pop_back();//删除最有一张照片的labels
//调用其中的成员函数train()来完成分类器的训练
qDebug()<<"训练3------------------------------";
Ptr<face::BasicFaceRecognizer> model = face::EigenFaceRecognizer::create();
model->train(images, labels);
qDebug()<<"训练4------------------------------";
model->save(MyFacePCAModel_XML.toStdString());//保存路径可自己设置,但注意用“\\”
qDebug()<<"训练5------------------------------";
Ptr<face::BasicFaceRecognizer> model1 = face::FisherFaceRecognizer::create();
model1->train(images, labels);
model1->save(MyFaceFisherModel_XML.toStdString());
qDebug()<<"训练6------------------------------";
Ptr<face::LBPHFaceRecognizer> model2 = face::LBPHFaceRecognizer::create();
model2->train(images, labels);
model2->save(MyFaceLBPHModel_XML.toStdString());
qDebug()<<"训练7------------------------------";
// 下面对测试图像进行预测,predictedLabel是预测标签结果
//注意predict()入口参数必须为单通道灰度图像,如果图像类型不符,需要先进行转换
//predict()函数返回一个整形变量作为识别标签
int predictedLabel = model->predict(testSample);//加载分类器
qDebug()<<"训练8------------------------------";
int predictedLabel1 = model1->predict(testSample);
qDebug()<<"训练9------------------------------";
int predictedLabel2 = model2->predict(testSample);
qDebug()<<"训练10------------------------------";
string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
string result_message1 = format("Predicted class = %d / Actual class = %d.", predictedLabel1, testLabel);
string result_message2 = format("Predicted class = %d / Actual class = %d.", predictedLabel2, testLabel);
cout << result_message << endl;
cout << result_message1 << endl;
cout << result_message2 << endl;
qDebug()<<"训练完成";
}
/**
* @brief 使用CSV文件去读图像和标签
* @param filename
* @param images
* @param labels
* @param separator
*/
void TrainThread::read_csv(const string& filename, vector<Mat>& images,
vector<int>& labels, char separator = ';')
{
std::ifstream file(filename.c_str(), ifstream::in);//c_str()函数可用可不用,无需返回一个标准C类型的字符串
if (!file)
{
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
string line, path, classlabel;
while (getline(file, line)) //从文本文件中读取一行字符,未指定限定符默认限定符为“/n”
{
stringstream liness(line);//这里采用stringstream主要作用是做字符串的分割
getline(liness, path, separator);//读入图片文件路径以分好作为限定符
getline(liness, classlabel);//读入图片标签,默认限定符
if (!path.empty() && !classlabel.empty()) //如果读取成功,则将图片和对应标签压入对应容器中
{
images.push_back(imread(path, 0));
labels.push_back(atoi(classlabel.c_str()));
}
}
}
<file_sep>#include "passworddialog.h"
#include "ui_passworddialog.h"
#include <QMessageBox>
#include <QPainter>
PasswordDialog::PasswordDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::PasswordDialog)
{
ui->setupUi(this);
isOk = false;
this->setWindowIcon(QIcon(":/images/face5.png"));
}
PasswordDialog::~PasswordDialog()
{
delete ui;
}
bool PasswordDialog::getIsOk()
{
return isOk;
}
void PasswordDialog::setPassword(QList<QString> pwd)
{
mPwdList = pwd;
}
void PasswordDialog::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
// painter.drawPixmap(rect(), QPixmap(":/images/bg2.jpg"), QRect());
}
void PasswordDialog::on_num0_clicked()
{
QString text = ui->pressedit->text();
text.append("0");
ui->pressedit->setText(text);
}
void PasswordDialog::on_num1_clicked()
{
QString text = ui->pressedit->text();
text.append("1");
ui->pressedit->setText(text);
}
void PasswordDialog::on_num2_clicked()
{
QString text = ui->pressedit->text();
text.append("2");
ui->pressedit->setText(text);
}
void PasswordDialog::on_num3_clicked()
{
QString text = ui->pressedit->text();
text.append("3");
ui->pressedit->setText(text);
}
void PasswordDialog::on_num4_clicked()
{
QString text = ui->pressedit->text();
text.append("4");
ui->pressedit->setText(text);
}
void PasswordDialog::on_num5_clicked()
{
QString text = ui->pressedit->text();
text.append("5");
ui->pressedit->setText(text);
}
void PasswordDialog::on_num6_clicked()
{
QString text = ui->pressedit->text();
text.append("6");
ui->pressedit->setText(text);
}
void PasswordDialog::on_num7_clicked()
{
QString text = ui->pressedit->text();
text.append("7");
ui->pressedit->setText(text);
}
void PasswordDialog::on_num8_clicked()
{
QString text = ui->pressedit->text();
text.append("8");
ui->pressedit->setText(text);
}
void PasswordDialog::on_num9_clicked()
{
QString text = ui->pressedit->text();
text.append("9");
ui->pressedit->setText(text);
}
void PasswordDialog::on_delbt_clicked()
{
QString text = ui->pressedit->text();
text.remove(text.size()-1, 1);//删除最后一个字符
ui->pressedit->setText(text);
}
void PasswordDialog::on_endbt_clicked()
{
QString text = ui->pressedit->text();
if(mPwdList.contains(text)){
isOk = true;
this->close();
}else{
isOk = false;
QMessageBox::information(this, "提示", "密码验证失败");
}
}
<file_sep>#ifndef BASEMAINWINDOW_H
#define BASEMAINWINDOW_H
#include <QMainWindow>
class BaseMainWindow: public QMainWindow
{
Q_OBJECT
public:
explicit BaseMainWindow(QWidget *parent = nullptr);
protected:
void mousePressEvent(QMouseEvent *ev);
void mouseMoveEvent(QMouseEvent *ev);
void mouseReleaseEvent(QMouseEvent *ev);
private:
QPoint posMouseOrigin; //鼠标原始位置
};
#endif // BASEMAINWINDOW_H
|
ac2a3089001ff6369d5371daf605f5e116efd710
|
[
"Markdown",
"C",
"C++"
] | 26
|
C++
|
0000duck/FaceRecognition
|
5f332e64d29769a879a856dcf593899470033de2
|
38c07e639518e7a3304b79aff6b3488dcab951d1
|
refs/heads/master
|
<file_sep>using System.Data.Entity;
using System.Data.SqlClient;
using System.Configuration;
namespace SendCollectionToStoredProcedureExample
{
public class BaseContext: DbContext
{
protected string connectionName;
public BaseContext(string connName = "BaseConnection")
: base(connName)
{
connectionName = connName;
}
public BaseContext setDatabase(string databaseName)
{
var connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
//change the database before creating the new connection
builder.InitialCatalog = databaseName;
string sqlConnectionString = builder.ConnectionString;
return new BaseContext(sqlConnectionString);
}
}
}
<file_sep># SendCollectionToStoredProcedureExample
Example for blog : Send Collection To Stored Procedure (Chinese)
<file_sep>using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace SendCollectionToStoredProcedureExample
{
class Program
{
static async Task Main(string[] args)
{
MainAsync().Wait();
}
static async Task MainAsync()
{
var context = new BaseContext();
var db = context.setDatabase("duran");
var parameters = new SqlParameter[]
{
new SqlParameter("@playerDataType", SqlDbType.Structured)
{
Value = GetDataTable(),
TypeName = "PlayerDataType"
},
};
var sql = "dbo.usp_PlayerData_GetPlayerData @playerDataType";
var result = await db.Database.SqlQuery<PlayerData>(sql, parameters).ToArrayAsync();
foreach (var item in result)
{
Console.WriteLine($"{item.Id}:{item.Name}");
}
}
private static DataTable GetDataTable()
{
var playerDataType = new DataTable();
playerDataType.Columns.Add("Id", typeof(Guid));
playerDataType.Rows.Add(Guid.NewGuid());
playerDataType.Rows.Add(Guid.NewGuid());
return playerDataType;
}
}
class PlayerData
{
public Guid Id { get; set; }
public string Name { get; set; }
}
}
|
2ed2cfe71cccca1b79b892554a0d9c4f5562ea36
|
[
"Markdown",
"C#"
] | 3
|
C#
|
matsurigoto/SendCollectionToStoredProcedureExample
|
03cf5e5c4cc33c8695615a39d66449257ece1868
|
49a8d63623f0a48601eb692f2c8632907e60cf5e
|
refs/heads/master
|
<repo_name>elijahsciam/ancient-chinese<file_sep>/src/app/pie/pie.component.ts
import { Component, OnInit } from '@angular/core';
import laozi from 'src/texts/laozi';
import dufu from 'src/texts/dufu';
const dictionary = require('./dict/parser.js');
@Component({
selector: 'app-pie',
templateUrl: './pie.component.html',
styleUrls: ['./pie.component.css'],
})
export class PieComponent implements OnInit {
currentText: any;
errorMessage: any;
selectedTitle: any;
selectedAuthor: any;
printText(event: any) {
const author = this.selectedAuthor;
if (author.data[this.selectedTitle] === undefined) {
this.errorMessage = 'Please select another number';
}
this.currentText = author.data[this.selectedTitle].body;
this.errorMessage = '';
event.preventDefault();
}
selectAuthor(event: any) {
const target = event.target.value;
if (target === 'dufu') {
this.selectedAuthor = dufu;
}
if (target === 'laozi') {
this.selectedAuthor = laozi;
}
}
selectTitle(event: any) {
const target = event.target.value;
this.selectedTitle = parseInt(target);
}
ngOnInit(): void {
console.log(dictionary);
}
}
<file_sep>/src/texts/laozi.ts
let laozi: any;
export default laozi = {
data: [
{
title: 1,
body: [
'道可道',
'非常道',
'名可名',
'非常名',
'无名天地之始',
'有名万物之母',
'故常无',
'欲以观其妙',
'常有',
'欲以观其徼',
'此两者',
'同出而异名',
'同谓之玄',
'玄之又玄',
'众妙之门',
],
},
{
title: 2,
body: [
'天下皆知美之为美',
'斯恶已',
'皆知善之为善',
'斯不善已',
'有无相生',
'难易相成',
'长短相形',
'高下相盈',
'音声相和',
'前后相随',
'恒也',
'是以圣人处无为之事',
'行不言之教',
'万物作而弗始',
'生而弗有',
'为而弗恃',
'功成而不居',
'夫唯弗居',
'是以不去',
],
},
{
title: 3,
body: [
'不尚贤',
'使民不争',
'不贵难得之货',
'使民不为盗',
'不见可欲',
'使民心不乱',
'是以圣人之治',
'虚其心',
'实其腹',
'弱其志',
'强其骨',
'常使民无知无欲',
'使夫智者不敢为也',
'为无为',
'则无不治',
],
},
{
title: 4,
body: [
'道冲',
'而用之或不盈',
'渊兮',
'似万物之宗',
'湛兮',
'似或存',
'吾不知谁之子',
'象帝之先',
],
},
{
title: 5,
body: [
'天地不仁',
'以万物为刍狗',
'圣人不仁',
'以百姓为刍狗',
'天地之间',
'其犹橐龠乎',
'虚而不屈',
'动而愈出',
'多言数穷',
'不如守中',
],
},
{
title: 6,
body: [
'谷神不死',
'是谓玄牝',
'玄牝之门',
'是谓天地根',
'绵绵若存',
'用之不勤',
],
},
{
title: 7,
body: [
'天长地久',
'天地所以能长且久者',
'以其不自生',
'故能长生',
'是以圣人后其身而身先',
'外其身而身存',
'非以其无私邪',
'故能成其私',
],
},
{
title: 8,
body: [
'上善若水',
'水善利万物而不争',
'处众人之所恶',
'故几于道',
'居善地',
'心善渊',
'与善仁',
'言善信',
'政善治',
'事善能',
'动善时',
'夫唯不争',
'故无尤',
],
},
{
title: 9,
body: [
'持而盈之',
'不如其已',
'揣而锐之',
'不可长保',
'金玉满堂',
'莫之能守',
'富贵而骄',
'自遗其咎',
'功遂身退',
'天之道也',
],
},
{
title: 10,
body: [
'载营魄抱一',
'能无离乎',
'专气致柔',
'能如婴儿乎',
'涤除玄鉴',
'能如疵乎',
'爱国治民',
'能无为乎',
'天门开阖',
'能为雌乎',
'明白四达',
'能无知乎',
],
},
{
title: 11,
body: [
'三十辐',
'共一毂',
'当其无',
'有车之用',
'埏埴以为器',
'当其无',
'有器之用',
'凿户牖以为室',
'当其无',
'有室之用',
'故有之以为利',
'无之以为用',
],
},
{
title: 12,
body: [
'五色令人目盲',
'五音令人耳聋',
'五味令人口爽',
'驰骋畋猎',
'令人心发狂',
'难得之货',
'令人行妨',
'是以圣人为腹不为目',
'故去彼取此',
],
},
{
title: 13,
body: [
'宠辱若惊',
'贵大患若身',
'何谓宠辱若惊',
'宠为下',
'得之若惊',
'失之若惊',
'是谓宠辱若惊',
'何谓贵大患若身',
'吾所以有大患者',
'为吾有身',
'及吾无身',
'吾有何患',
'故贵以身为天下',
'若可寄天下',
'爱以身为天下',
'若可托天下',
],
},
{
title: 14,
body: [
'视之不见',
'名曰夷',
'听之不闻',
'名曰希',
'搏之不得',
'名曰微',
'此三者不可致诘',
'故混而为一',
'其上不□',
'其下不昧',
'绳绳兮不可名',
'复归于物',
'是谓无状之状',
'无物之象',
'是谓惚恍',
'迎之不见其首',
'随之不见其后',
'执古之道',
'以御今之有',
'能知古始',
'是谓道纪',
],
},
{
title: 15,
body: [
'古之善为道者',
'微妙玄通',
'深不可识',
'夫唯不可识',
'故强为之容:豫兮若冬涉川',
'犹兮若畏四邻',
'俨兮其若客',
'涣兮其若凌释',
'敦兮其若朴',
'旷兮其若谷',
'混兮其若浊',
'澹兮其若海',
'□兮若无止',
'孰能浊以静之徐清',
'孰能安以动之徐生',
'保此道者',
'不欲盈',
'夫唯不盈',
'故能蔽而新成',
],
},
{
title: 16,
body: [
'致虚极',
'守静笃',
'万物并作',
'吾以观复',
'夫物芸芸',
'各复归其根',
'归根曰静',
'静曰复命',
'复命曰常',
'知常曰明',
'不知常',
'妄作凶',
'知常容',
'容乃公',
'公乃全',
'全乃天',
'天乃道',
'道乃久',
'没身不殆',
],
},
{
title: 17,
body: [
'太上',
'不知有之',
'其次',
'亲而誉之',
'其次',
'畏之',
'其次',
'侮之',
'信不足焉',
'有不信焉',
'悠兮其贵言',
'功成事遂',
'百姓皆谓:',
'我自然',
],
},
{
title: 18,
body: [
'大道废',
'有仁义',
'智慧出',
'有大伪',
'六亲不和',
'有孝慈',
'国家昏乱',
'有忠臣',
],
},
{
title: 19,
body: [
'绝圣弃智',
'民利百倍',
'绝仁弃义',
'民复孝慈',
'绝巧弃利',
'盗贼无有',
'此三者以为文',
'不足',
'故令有所属:见素抱朴',
'少思寡欲',
'绝学无忧',
],
},
{
title: 20,
body: [
'唯之与阿',
'相去几何',
'美之与恶',
'相去若何',
'人之所畏',
'不可不畏',
'荒兮',
'其未央哉!众人熙熙',
'如享太牢',
'如春登台',
'我独泊兮',
'其未兆',
'沌沌兮',
'如婴儿之未孩',
'累累兮',
'若无所归',
'众人皆有馀',
'而我独若遗',
'我愚人之心也哉!俗人昭昭',
'我独昏昏',
'俗人察察',
'我独闷闷',
'众人皆有以',
'而我独顽且鄙',
'我独异于人',
'而贵食母',
],
},
{
title: 21,
body: [
'孔德之容',
'惟道是从',
'道之为物',
'惟恍惟惚',
'惚兮恍兮',
'其中有象',
'恍兮惚兮',
'其中有物',
'窈兮冥兮',
'其中有精',
'其精甚真',
'其中有信',
'自今及古',
'其名不去',
'以阅众甫',
'吾何以知众甫之状哉',
'以此',
],
},
{
title: 22,
body: [
'曲则全',
'枉则直',
'洼则盈',
'敝则新',
'少则多',
'多则惑',
'是以圣人抱一为天下式',
'不自见',
'故明',
'不自是',
'故彰',
'不自伐',
'故有功',
'不自矜',
'故长',
'夫唯不争',
'故天下莫能与之争',
'古之所谓',
'曲则全',
'者',
'岂虚言哉!诚全而归之',
],
},
{
title: 23,
body: [
'希言自然',
'故飘风不终朝',
'骤雨不终日',
'孰为此者',
'天地',
'天地尚不能久',
'而况于人乎',
'故从事于道者',
'同于道',
'德者',
'同于德',
'失者',
'同于失',
'同于道者',
'道亦乐得之',
'同于德者',
'德亦乐得之',
'同于失者',
'失亦乐得之',
'信不足焉',
'有不信焉',
],
},
{
title: 24,
body: [
'企者不立',
'跨者不行',
'自见者不明',
'自是者不彰',
'自伐者无功',
'自矜者不长',
'其在道也',
'曰:馀食赘形',
'物或恶之',
'故有道者不处',
],
},
{
title: 25,
body: [
'有物混成',
'先天地生',
'寂兮寥兮',
'独立而不改',
'周行而不殆',
'可以为天地母',
'吾不知其名',
'强字之曰道',
'强为之名曰大',
'大曰逝',
'逝曰远',
'远曰反',
'故道大',
'天大',
'地大',
'人亦大',
'域中有四大',
'而人居其一焉',
'人法地',
'地法天',
'天法道',
'道法自然',
],
},
{
title: 26,
body: [
'重为轻根',
'静为躁君',
'是以君子终日行不离辎重',
'虽有荣观',
'燕处超然',
'奈何万乘之主',
'而以身轻天下',
'轻则失根',
'躁则失君',
],
},
{
title: 27,
body: [
'善行无辙迹',
'善言无瑕谪',
'善数不用筹策',
'善闭无关楗而不可开',
'善结无绳约而不可解',
'是以圣人常善救人',
'故无弃人',
'常善救物',
'故无弃物',
'是谓袭明',
'故善人者',
'不善人之师',
'不善人者',
'善人之资',
'不贵其师',
'不爱其资',
'虽智大迷',
'是谓要妙',
],
},
{
title: 28,
body: [
'知其雄',
'守其雌',
'为天下溪',
'为天下溪',
'常德不离',
'复归于婴儿',
'知其白',
'守其辱',
'为天下谷',
'为天下谷',
'常德乃足',
'复归于朴',
'知其白',
'守其黑',
'为天下式',
'为天下式',
'常德不忒',
'复归于无极',
'朴散则为器',
'圣人用之',
'则为官长',
'故大智不割',
],
},
{
title: 29,
body: [
'将欲取天下而为之',
'吾见其不得已',
'天下神器',
'不可为也',
'不可执也',
'为者败之',
'执者失之',
'是以圣人无为',
'故无败',
'无执',
'故无失',
'夫物或行或随',
'或嘘或吹',
'或强或羸',
'或载或隳',
'是以圣人去甚',
'去奢',
'去泰',
],
},
{
title: 30,
body: [
'以道佐人主者',
'不以兵强天下',
'其事好远',
'师之所处',
'荆棘生焉',
'大军之后',
'必有凶年',
'善有果而已',
'不以取强',
'果而勿矜',
'果而勿伐',
'果而勿骄',
'果而不得已',
'果而勿强',
'物壮则老',
'是谓不道',
'不道早已',
],
},
{
title: 31,
body: [
'夫兵者',
'不祥之器',
'物或恶之',
'故有道者不处',
'君子居则贵左',
'用兵则贵右',
'兵者不祥之器',
'非君子之器',
'不得已而用之',
'恬淡为上',
'胜而不美',
'而美之者',
'是乐杀人',
'夫乐杀人者',
'则不可得志于天下矣',
'吉事尚左',
'凶事尚右',
'偏将军居左',
'上将军居右',
'言以丧礼处之',
'杀人之众',
'以悲哀泣之',
'战胜以丧礼处之',
],
},
{
title: 32,
body: [
'道常无名朴',
'虽小',
'天下莫能臣',
'侯王若能守之',
'万物将自宾',
'天地相合',
'以降甘露',
'民莫之令而自均',
'始制有名',
'名亦既有',
'夫亦将知止',
'知止可以不殆',
'譬道之在天下',
'犹川谷之于江海',
],
},
{
title: 33,
body: [
'知人者智',
'自知者明',
'胜人者有力',
'自胜者强',
'知足者富',
'强行者有志',
'不失其所者久',
'死而不亡者寿',
],
},
{
title: 34,
body: [
'大道泛兮',
'其可左右',
'万物恃之以生而不辞',
'功成而不有',
'衣养万物而不为主',
'可名于小',
'万物归焉而不为主',
'可名为大',
'以其终不自为大',
'故能成其大',
],
},
{
title: 35,
body: [
'执大象',
'天下往',
'往而不害',
'安平泰',
'乐与饵',
'过客止',
'道之出口',
'淡乎其无味',
'视之不足见',
'听之不足闻',
'用之不足既',
],
},
{
title: 36,
body: [
'将欲歙之',
'必故张之',
'将欲弱之',
'必故强之',
'将欲废之',
'必故兴之',
'将欲取之',
'必故与之',
'是谓微明',
'柔弱胜刚强',
'鱼不可脱于渊',
'国之利器不可以示人',
],
},
{
title: 37,
body: [
'道常无为而无不为',
'侯王若能守之',
'万物将自化',
'化而欲作',
'吾将镇之以无名之朴',
'镇之以无名之朴',
'夫将不欲',
'不欲以静',
'天下将自正',
],
},
{
title: 38,
body: [
'上德不德',
'是以有德',
'下德不失德',
'是以无德',
'上德无为而无以为',
'下德无为而有以为',
'上仁为之而无以为',
'上义为之而有以为',
'上礼为之而莫之应',
'则攘臂而扔之',
'故失道而后德',
'失德而后仁',
'失仁而后义',
'失义而后礼',
'夫礼者',
'忠信之薄',
'而乱之首',
'前识者',
'道之华',
'而愚之始',
'是以大丈夫处其厚',
'不居其薄',
'处其实',
'不居其华',
'故去彼取此',
],
},
{
title: 39,
body: [
'昔之得一者:天得一以清',
'地得一以宁',
'神得一以灵',
'谷得一以生',
'侯得一以为天下正',
'其致之也',
'谓天无以清',
'将恐裂',
'地无以宁',
'将恐废',
'神无以灵',
'将恐歇',
'谷无以盈',
'将恐竭',
'万物无以生',
'将恐灭',
'侯王无以正',
'将恐蹶',
'故贵以贱为本',
'高以下为基',
'是以侯王自称孤、寡、不谷',
'此非以贱为本邪',
'非乎',
'故致誉无誉',
'是故不欲□□如玉',
'珞珞如石',
],
},
{
title: 40,
body: ['反者道之动', '弱者道之用', '天下万物生于有', '有生于无'],
},
{
title: 41,
body: [
'上士闻道',
'勤而行之',
'中士闻道',
'若存若亡',
'下士闻道',
'大笑之',
'不笑不足以为道',
'故建言有之:明道若昧',
'进道若退',
'夷道若□',
'上德若谷',
'广德若不足',
'建德若偷',
'质真若渝',
'大白若辱',
'大方无隅',
'大器晚成',
'大音希声',
'大象无形',
'道隐无名',
'夫唯道',
'善贷且成',
],
},
{
title: 42,
body: [
'道生一',
'一生二',
'二生三',
'三生万物',
'万物负阴而抱阳',
'冲气以为和',
'人之所恶',
'唯孤、寡、不谷',
'而王公以为称',
'故物或损之而益',
'或益之而损',
'人之所教',
'我亦教之',
'强梁者不得其死',
'吾将以为教父',
],
},
{
title: 43,
body: [
'天下之至柔',
'驰骋天下之至坚',
'无有入无间',
'吾是以知无为之有益',
'不言之教',
'无为之益',
'天下希及之',
],
},
{
title: 44,
body: [
'名与身孰亲',
'身与货孰多',
'得与亡孰病',
'甚爱必大费',
'多藏必厚亡',
'故知足不辱',
'知止不殆',
'可以长久',
],
},
{
title: 45,
body: [
'大成若缺',
'其用不弊',
'大盈若冲',
'其用不穷',
'大直若屈',
'大巧若拙',
'大辩若讷',
'静胜躁',
'寒胜热',
'清静为天下正',
],
},
{
title: 46,
body: [
'天下有道',
'却走马以粪',
'天下无道',
'戎马生于郊',
'祸莫大于不知足',
'咎莫大于欲得',
'故知足之足',
'常足矣',
],
},
{
title: 47,
body: [
'不出户',
'知天下',
'不窥牖',
'见天道',
'其出弥远',
'其知弥少',
'是以圣人不行而知',
'不见而明',
'不为而成',
],
},
{
title: 48,
body: [
'为学日益',
'为道日损',
'损之又损',
'以至于无为',
'无为而无不为',
'取天下常以无事',
'及其有事',
'不足以取天下',
],
},
{
title: 49,
body: [
'圣人常无心',
'以百姓心为心',
'善者',
'吾善之',
'不善者',
'吾亦善之',
'德善',
'信者',
'吾信之',
'不信者',
'吾亦信之',
'德信',
'圣人在天下',
'歙歙焉',
'为天下浑其心',
'百姓皆注其耳目',
'圣人皆孩之',
],
},
{
title: 50,
body: [
'出生入死',
'生之徒',
'十有三',
'死之徒',
'十有三',
'人之生',
'动之于死地',
'亦十有三',
'夫何故',
'以其生之厚',
'盖闻善摄生者',
'路行不遇兕虎',
'入军不被甲兵',
'兕无所投其角',
'虎无所用其爪',
'兵无所容其刃',
'夫何故',
'以其无死地',
],
},
{
title: 51,
body: [
'道生之',
'德畜之',
'物形之',
'势成之',
'是以万物莫不尊道而贵德',
'道之尊',
'德之贵',
'夫莫之命而常自然',
'故道生之',
'德畜之',
'长之育之',
'成之熟之',
'养之覆之',
'生而不有',
'为而不恃',
'长而不宰',
'是谓玄德',
],
},
{
title: 52,
body: [
'天下有始',
'以为天下母',
'既得其母',
'以知其子',
'复守其母',
'没身不殆',
'塞其兑',
'闭其门',
'终身不勤',
'开其兑',
'济其事',
'终身不救',
'见小曰明',
'守柔曰强',
'用其光',
'复归其明',
'无遗身殃',
'是为袭常',
],
},
{
title: 53,
body: [
'使我介然有知',
'行于大道',
'唯施是畏',
'大道甚夷',
'而人好径',
'朝甚除',
'田甚芜',
'仓甚虚',
'服文采',
'带利剑',
'厌饮食',
'财货有馀',
'是为盗夸',
'非道也哉!',
],
},
{
title: 54,
body: [
'善建者不拔',
'善抱者不脱',
'子孙以祭祀不辍',
'修之于身',
'其德乃真',
'修之于家',
'其德乃馀',
'修之于乡',
'其德乃长',
'修之于邦',
'其德乃丰',
'修之于天下',
'其德乃普',
'故以身观身',
'以家观家',
'以乡观乡',
'以邦观邦',
'以天下观天下',
'吾何以知天下然哉',
'以此',
],
},
{
title: 55,
body: [
'含',
'德',
'之厚',
'比于赤子',
'毒虫不螫',
'猛兽不据',
'攫鸟不搏',
'骨弱筋柔而握固',
'未知牝牡之合而□作',
'精之至也',
'终日号而不嗄',
'和之至也',
'知和曰',
'常',
'知常曰',
'明',
'益生曰祥',
'心使气曰强',
'物壮则老',
'谓之不道',
'不道早已',
],
},
{
title: 56,
body: [
'知者不言',
'言者不知',
'挫其锐',
'解其纷',
'和其光',
'同其尘',
'是谓',
'玄同',
'故不可得而亲',
'不可得而疏',
'不可得而利',
'不可得而害',
'不可得而贵',
'不可得而贱',
'故为天下贵',
],
},
{
title: 57,
body: [
'以正治国',
'以奇用兵',
'以无事取天下',
'吾何以知其然哉',
'以此:天下多忌讳',
'而民弥贫',
'人多利器',
'国家滋昏',
'人多伎巧',
'奇物滋起',
'法令滋彰',
'盗贼多有',
'故圣人云:',
'我无为',
'而民自化',
'我好静',
'而民自正',
'我无事',
'而民自富',
'我无欲',
'而民自朴',
],
},
{
title: 58,
body: [
'其政闷闷',
'其民淳淳',
'其政察察',
'其民缺缺',
'是以圣人方而不割',
'廉而不刿',
'直而不肆',
'光而不耀',
'祸兮福之所倚',
'福兮祸之所伏',
'孰知其极',
'其无正也',
'正复为奇',
'善复为妖',
'人之迷',
'其日固久',
],
},
{
title: 59,
body: [
'治人事天',
'莫若啬',
'夫为啬',
'是谓早服',
'早服谓之重积德',
'重积德则无不克',
'无不克则莫知其极',
'莫知其极',
'可以有国',
'有国之母',
'可以长久',
'是谓深根固柢',
'长生久视之道',
],
},
{
title: 60,
body: [
'治大国',
'若烹小鲜',
'以道莅天下',
'其鬼不神',
'非其鬼不神',
'其神不伤人',
'非其神不伤人',
'圣人亦不伤人',
'夫两不相伤',
'故德交归焉',
],
},
{
title: 61,
body: [
'大邦者下流',
'天下之牝',
'天下之交也',
'牝常以静胜牡',
'以静为下',
'故大邦以下小邦',
'则取小邦',
'小邦以下大邦',
'则取大邦',
'故或下以取',
'或下而取',
'大邦不过欲兼畜人',
'小邦不过欲入事人',
'夫两者各得所欲',
'大者宜为下',
],
},
{
title: 62,
body: [
'道者万物之奥',
'善人之宝',
'不善人之所保',
'美言可以市尊',
'美行可以加人',
'人之不善',
'何弃之有',
'故立天子',
'置三公',
'虽有拱璧以先驷马',
'不如坐进此道',
'古之所以贵此道者何',
'不曰:求以得',
'有罪以免邪',
'故为天下贵',
],
},
{
title: 63,
body: [
'为无为',
'事无事',
'味无味',
'图难于其易',
'为大于其细',
'天下难事',
'必作于易',
'天下大事',
'必作于细',
'是以圣人终不为大',
'故能成其大',
'夫轻诺必寡信',
'多易必多难',
'是以圣人犹难之',
'故终无难矣',
],
},
{
title: 64,
body: [
'其安易持',
'其未兆易谋',
'其脆易泮',
'其微易散',
'为之于未有',
'治之于未乱',
'合抱之木',
'生于毫末',
'九层之台',
'起于累土',
'千里之行',
'始于足下',
'民之从事',
'常于几成而败之',
'慎终如始',
'则无败事',
],
},
{
title: 65,
body: [
'古之善为道者',
'非以明民',
'将以愚之',
'民之难治',
'以其智多',
'故以智治国',
'国之贼',
'不以智治国',
'国之福',
'知此两者亦稽式',
'常知稽式',
'是谓',
'玄德',
'玄德',
'深矣',
'远矣',
'与物反矣',
'然后乃至大顺',
],
},
{
title: 66,
body: [
'江海之所以能为百谷王者',
'以其善下之',
'故能为百谷王',
'是以圣人欲上民',
'必以言下之',
'欲先民',
'必以身后之',
'是以圣人处上而民不重',
'处前而民不害',
'是以天下乐推而不厌',
'以其不争',
'故天下莫能与之争',
],
},
{
title: 67,
body: [
'天下皆谓我道大',
'似不肖',
'夫唯大',
'故似不肖',
'若肖',
'久矣其细也夫!我有三宝',
'持而保之',
'一曰慈',
'二曰俭',
'三曰不敢为天下先',
'慈故能勇',
'俭故能广',
'不敢为天下先',
'故能成器长',
'今舍慈且勇',
'舍俭且广',
'舍后且先',
'死矣!夫慈以战则胜',
'以守则固',
'天将救之',
'以慈卫之',
],
},
{
title: 68,
body: [
'善为士者',
'不武',
'善战者',
'不怒',
'善胜敌者',
'不与',
'善用人者',
'为之下',
'是谓不争之德',
'是谓用人之力',
'是谓配天古之极',
],
},
{
title: 69,
body: [
'用兵有言:',
'吾不敢为主',
'而为客',
'不敢进寸',
'而退尺',
'是谓行无行',
'攘无臂',
'扔无敌',
'执无兵',
'祸莫大于轻敌',
'轻敌几丧吾宝',
'故抗兵相若',
'哀者胜矣',
],
},
{
title: 70,
body: [
'吾言甚易知',
'甚易行',
'天下莫能知',
'莫能行',
'言有宗',
'事有君',
'夫唯无知',
'是以不我知',
'知我者希',
'则我者贵',
'是以圣人被褐而怀玉',
],
},
{
title: 71,
body: [
'知不知',
'尚矣',
'不知知',
'病也',
'圣人不病',
'以其病病',
'夫唯病病',
'是以不病',
],
},
{
title: 72,
body: [
'民不畏威',
'则大威至',
'无狎其所居',
'无厌其所生',
'夫唯不厌',
'是以不厌',
'是以圣人自知不自见',
'自爱不自贵',
'故去彼取此',
],
},
{
title: 73,
body: [
'勇于敢则杀',
'勇于不敢则活',
'此两者',
'或利或害',
'天之所恶',
'孰知其故',
'天之道',
'不争而善胜',
'不言而善应',
'不召而自来',
'□然而善谋',
'天网恢恢',
'疏而不失',
],
},
{
title: 74,
body: [
'民不畏死',
'奈何以死惧之',
'若使民常畏死',
'而为奇者',
'吾得执而杀之',
'孰敢',
'常有司杀者杀',
'夫代司杀者杀',
'是谓代大匠□',
'夫代大匠□者',
'希有不伤其手矣',
],
},
{
title: 75,
body: [
'民之饥',
'以其上食税之多',
'是以饥',
'民之难治',
'以其上之有为',
'是以难治',
'民之轻死',
'以其上求生之厚',
'是以轻死',
'夫唯无以生为者',
'是贤于贵生',
],
},
{
title: 76,
body: [
'人之生也柔弱',
'其死也坚强',
'草木之生也柔脆',
'其死也枯槁',
'故坚强者死之徒',
'柔弱者生之徒',
'是以兵强则灭',
'木强则折',
'强大处下',
'柔弱处上',
],
},
{
title: 77,
body: [
'天之道',
'其犹张弓欤',
'高者抑之',
'下者举之',
'有馀者损之',
'不足者补之',
'天之道',
'损有馀而补不足',
'人之道',
'则不然',
'损不足以奉有馀',
'孰能有馀以奉天下',
'唯有道者',
'是以圣人为而不恃',
'功成而不处',
'其不欲见贤',
],
},
{
title: 78,
body: [
'天下莫柔弱于水',
'而攻坚强者莫之能胜',
'以其无以易之',
'弱之胜强',
'柔之胜刚',
'天下莫不知',
'莫能行',
'是以圣人云:',
'受国之垢',
'是谓社稷主',
'受国不祥',
'是为天下王',
'正言若反',
],
},
{
title: 79,
body: [
'和大怨',
'必有馀怨',
'报怨以德',
'安可以为善',
'是以圣人执左契',
'而不责于人',
'有德司契',
'无德司彻',
'天道无亲',
'常与善人',
],
},
{
title: 80,
body: [
'小国寡民',
'使有什伯之器而不用',
'使民重死而不远徙',
'虽有舟舆',
'无所乘之',
'虽有甲兵',
'无所陈之',
'使民复结绳而用之',
'甘其食',
'美其服',
'安其居',
'乐其俗',
'邻国相望',
'鸡犬之声相闻',
'民至老死',
'不相往来',
],
},
{
title: 81,
body: [
'信言不美',
'美言不信',
'善者不辩',
'辩者不善',
'知者不博',
'博者不知',
'圣人不积',
'既以为人己愈有',
'既以与人己愈多',
'天之道',
'利而不害',
'圣人之道',
'为而不争',
],
},
],
};
<file_sep>/src/texts/dufu.ts
let dufu: any;
export default dufu = {
data: [
{
title: '奉赠韦左丞丈二十二韵',
body: [
'纨袴不饿死',
'儒冠多误身',
'丈人试静听',
'贱子请具陈',
'甫昔少年日',
'早充观国宾',
'读书破万卷',
'下笔如有神',
'赋料扬雄敌',
'诗看子建亲',
'李邕求识面',
'王翰愿卜邻',
'自谓颇挺出',
'立登要路津',
'致君尧舜上',
'再使风俗淳',
'此意竟萧条',
'行歌非隐沦',
'骑驴三十载',
'旅食京华春',
'朝扣富儿门',
'暮随肥马尘',
'残杯与冷炙',
'到处潜悲辛',
'主上顷见征',
'欻然欲求伸',
'青冥却垂翅',
'蹭蹬无纵鳞',
'甚愧丈人厚',
'甚知丈人真',
'每于百僚上',
'猥诵佳句新',
'窃效贡公喜',
'难甘原宪贫',
'焉能心怏怏',
'只是走踆踆',
'今欲东入海',
'即将西去秦',
'尚怜终南山',
'回首清渭滨',
'常拟报一饭',
'况怀辞大臣',
'白鸥没浩荡',
'万里谁能驯',
],
},
{
title: '送高三十五书记',
body: [
'崆峒小麦熟',
'且愿休王师',
'请公问主将',
'焉用穷荒为',
'饥鹰未饱肉',
'侧翅随人飞',
'高生跨鞍马',
'有似幽并儿',
'脱身簿尉中',
'始与捶楚辞',
'借问今何官',
'触热向武威',
'答云一书记',
'所愧国士知',
'人实不易知',
'更须慎其仪',
'十年出幕府',
'自可持旌麾',
'此行既特达',
'足以慰所思',
'男儿功名遂',
'亦在老大时',
'常恨结欢浅',
'各在天一涯',
'又如参与商',
'惨惨中肠悲',
'惊风吹鸿鹄',
'不得相追随',
'黄尘翳沙漠',
'念子何当归',
'边城有馀力',
'早寄从军诗',
],
},
{
title: '赠李白',
body: [
'二年客东都',
'所历厌机巧',
'野人对膻腥',
'蔬食常不饱',
'岂无青精饭',
'使我颜色好',
'苦乏大药资',
'山林迹如扫',
'李侯金闺彦',
'脱身事幽讨',
'亦有梁宋游',
'方期拾瑶草',
],
},
{
title: '游龙门奉先寺(龙门即伊阙一名阙口在河南府北四十里)',
body: [
'已从招提游',
'更宿招提境',
'阴壑生虚籁',
'月林散清影',
'天阙象纬逼',
'云卧衣裳冷',
'欲觉闻晨钟',
'令人发深省',
],
},
{
title: '望岳',
body: [
'岱宗夫如何',
'齐鲁青未了',
'造化钟神秀',
'阴阳割昏晓',
'荡胸生曾云',
'决眦入归鸟',
'会当凌绝顶',
'一览众山小',
],
},
{
title: '陪李北海宴历下亭',
body: [
'东藩驻皂盖',
'北渚凌青荷',
'海内此亭古',
'济南名士多',
'云山已发兴',
'玉佩仍当歌',
'修竹不受暑',
'交流空涌波',
'蕴真惬所遇',
'落日将如何',
'贵贱俱物役',
'从公难重过',
],
},
{
title: '同李太守登历下古城员外新亭,亭对鹊湖',
body: [
'新亭结构罢',
'隐见清湖阴',
'迹籍台观旧',
'气溟海岳深',
'圆荷想自昔',
'遗堞感至今',
'芳宴此时具',
'哀丝千古心',
'主称寿尊客',
'筵秩宴北林',
'不阻蓬荜兴',
'得兼梁甫吟',
],
},
{
title: '玄都坛歌,寄元逸人',
body: [
'故人昔隐东蒙峰',
'已佩含景苍精龙',
'故人今居子午谷',
'独在阴崖结茅屋',
'屋前太古玄都坛',
'青石漠漠常风寒',
'子规夜啼山竹裂',
'王母昼下云旗翻',
'知君此计成长往',
'芝草琅玕日应长',
'铁锁高垂不可攀',
'致身福地何萧爽',
],
},
{
title: '今夕行(自齐赵西归至咸阳作)',
body: [
'今夕何夕岁云徂',
'更长烛明不可孤',
'咸阳客舍一事无',
'相与博塞为欢娱',
'冯陵大叫呼五白',
'袒跣不肯成枭卢',
'英雄有时亦如此',
'邂逅岂即非良图',
'君莫笑刘毅从来布衣愿',
'家无儋石输百万',
],
},
{
title: '贫交行',
body: [
'翻手作云覆手雨',
'纷纷轻薄何须数',
'君不见管鲍贫时交',
'此道今人弃如土',
],
},
{
title: '兵车行',
body: [
'车辚辚',
'马萧萧',
'行人弓箭各在腰',
'耶娘妻子走相送',
'尘埃不见咸阳桥',
'牵衣顿足阑道哭',
'哭声直上干云霄',
'道傍过者问行人',
'行人但云点行频',
'或从十五北防河',
'便至四十西营田',
'去时里正与裹头',
'归来头白还戍边',
'边亭流血成海水',
'武皇开边意未已',
'君不闻汉家山东二百州',
'千村万落生荆杞',
'纵有健妇把锄犁',
'禾生陇亩无东西',
'况复秦兵耐苦战',
'被驱不异犬与鸡',
'长者虽有问',
'役夫敢申恨',
'且如今年冬',
'未休关西卒',
'县官急索租',
'租税从何出',
'信知生男恶',
'反是生女好',
'生女犹是嫁比邻',
'生男埋没随百草',
'君不见青海头',
'古来白骨无人收',
'新鬼烦冤旧鬼哭',
'天阴雨湿声啾啾',
],
},
{
title: '高都护骢马行(高仙芝开元末为安西副都护)',
body: [
'安西都护胡青骢',
'声价欻然来向东',
'此马临阵久无敌',
'与人一心成大功',
'功成惠养随所致',
'飘飘远自流沙至',
'雄姿未受伏枥恩',
'猛气犹思战场利',
'腕促蹄高如踣铁',
'交河几蹴曾冰裂',
'五花散作云满身',
'万里方看汗流血',
'长安壮儿不敢骑',
'走过掣电倾城知',
'青丝络头为君老',
'何由却出横门道',
],
},
{
title: '天育骠骑歌(天育,厩名,未详所出)',
body: [
'吾闻天子之马走千里',
'今之画图无乃是',
'是何意态雄且杰',
'骏尾萧梢朔风起',
'毛为绿缥两耳黄',
'眼有紫焰双瞳方',
'矫矫龙性合变化',
'卓立天骨森开张',
'伊昔太仆张景顺',
'监牧攻驹阅清峻',
'遂令大奴守天育',
'别养骥子怜神俊',
'当时四十万匹马',
'张公叹其材尽下',
'故独写真传世人',
'见之座右久更新',
'年多物化空形影',
'呜呼健步无由骋',
'如今岂无騕褭与骅骝',
'时无王良伯乐死即休',
],
},
{
title: '白丝行',
body: [
'缫丝须长不须白',
'越罗蜀锦金粟尺',
'象床玉手乱殷红',
'万草千花动凝碧',
'已悲素质随时染',
'裂下鸣机色相射',
'美人细意熨帖平',
'裁缝灭尽针线迹',
'春天衣著为君舞',
'蛱蝶飞来黄鹂语',
'落絮游丝亦有情',
'随风照日宜轻举',
'香汗轻尘污颜色',
'开新合故置何许',
'君不见才士汲引难',
'恐惧弃捐忍羁旅',
],
},
{
title: '秋雨叹三首',
body: [
'雨中百草秋烂死',
'阶下决明颜色鲜',
'著叶满枝翠羽盖',
'开花无数黄金钱',
'凉风萧萧吹汝急',
'恐汝后时难独立',
'堂上书生空白头',
'临风三嗅馨香泣',
'阑风长雨秋纷纷',
'四海八荒同一云',
'去马来牛不复辨',
'浊泾清渭何当分',
'禾头生耳黍穗黑',
'农夫田妇无消息',
'城中斗米换衾裯',
'相许宁论两相直',
'长安布衣谁比数',
'反锁衡门守环堵',
'老夫不出长蓬蒿',
'稚子无忧走风雨',
'雨声飕飕催早寒',
'胡雁翅湿高飞难',
'秋来未曾见白日',
'泥污后土何时干',
],
},
{
title: '叹庭前甘菊花',
body: [
'檐前甘菊移时晚',
'青蕊重阳不堪摘',
'明日萧条醉尽醒',
'残花烂熳开何益',
'篱边野外多众芳',
'采撷细琐升中堂',
'念兹空长大枝叶',
'结根失所缠风霜',
],
},
{
title: '醉时歌(赠广文馆博士郑虔)',
body: [
'诸公衮衮登台省',
'广文先生官独冷',
'甲第纷纷厌粱肉',
'广文先生饭不足',
'先生有道出羲皇',
'先生有才过屈宋',
'德尊一代常轗轲',
'名垂万古知何用',
'杜陵野客人更嗤',
'被褐短窄鬓如丝',
'日籴太仓五升米',
'时赴郑老同襟期',
'得钱即相觅',
'沽酒不复疑',
'忘形到尔汝',
'痛饮真吾师',
'清夜沈沈动春酌',
'灯前细雨檐花落',
'但觉高歌有鬼神',
'焉知饿死填沟壑',
'相如逸才亲涤器',
'子云识字终投阁',
'先生早赋归去来',
'石田茅屋荒苍苔',
'儒术于我何有哉',
'孔丘盗跖俱尘埃',
'不须闻此意惨怆',
'生前相遇且衔杯',
],
},
{
title: '醉歌行',
body: [
'陆机二十作文赋',
'汝更小年能缀文',
'总角草书又神速',
'世上儿子徒纷纷',
'骅骝作驹已汗血',
'鸷鸟举翮连青云',
'词源倒流三峡水',
'笔阵独扫千人军',
'只今年才十六七',
'射策君门期第一',
'旧穿杨叶真自知',
'暂蹶霜蹄未为失',
'偶然擢秀非难取',
'会是排风有毛质',
'汝身已见唾成珠',
'汝伯何由发如漆',
'春光澹沱秦东亭',
'渚蒲牙白水荇青',
'风吹客衣日杲杲',
'树搅离思花冥冥',
'酒尽沙头双玉瓶',
'众宾皆醉我独醒',
'乃知贫贱别更苦',
'吞声踯躅涕泪零',
],
},
{
title: '赠卫八处士',
body: [
'人生不相见',
'动如参与商',
'今夕复何夕',
'共此灯烛光',
'少壮能几时',
'鬓发各已苍',
'访旧半为鬼',
'惊呼热中肠',
'焉知二十载',
'重上君子堂',
'昔别君未婚',
'儿女忽成行',
'怡然敬父执',
'问我来何方',
'问答乃未已',
'儿女罗酒浆',
'夜雨翦春韭',
'新炊间黄粱',
'主称会面难',
'一举累十觞',
'十觞亦不醉',
'感子故意长',
'明日隔山岳',
'世事两茫茫',
],
},
{
title: '苦雨奉寄陇西公兼呈王征士',
body: [
'今秋乃淫雨',
'仲月来寒风',
'群木水光下',
'万象云气中',
'所思碍行潦',
'九里信不通',
'悄悄素浐路',
'迢迢天汉东',
'愿腾六尺马',
'背若孤征鸿',
'划见公子面',
'超然欢笑同',
'奋飞既胡越',
'局促伤樊笼',
'一饭四五起',
'凭轩心力穷',
'嘉蔬没混浊',
'时菊碎榛丛',
'鹰隼亦屈猛',
'乌鸢何所蒙',
'式瞻北邻居',
'取适南巷翁',
'挂席钓川涨',
'焉知清兴终',
],
},
{
title: '同诸公登慈恩寺塔',
body: [
'高标跨苍天',
'烈风无时休',
'自非旷士怀',
'登兹翻百忧',
'方知象教力',
'足可追冥搜',
'仰穿龙蛇窟',
'始出枝撑幽',
'七星在北户',
'河汉声西流',
'羲和鞭白日',
'少昊行清秋',
'秦山忽破碎',
'泾渭不可求',
'俯视但一气',
'焉能辨皇州',
'回首叫虞舜',
'苍梧云正愁',
'惜哉瑶池饮',
'日晏昆仑丘',
'黄鹄去不息',
'哀鸣何所投',
'君看随阳雁',
'各有稻粱谋',
],
},
{
title: '示从孙济(济字应物,官给事中、京兆尹)',
body: [
'平明跨驴出',
'未知适谁门',
'权门多噂eR',
'且复寻诸孙',
'诸孙贫无事',
'宅舍如荒村',
'堂前自生竹',
'堂后自生萱',
'萱草秋已死',
'竹枝霜不蕃',
'淘米少汲水',
'汲多井水浑',
'刈葵莫放手',
'放手伤葵根',
'阿翁懒惰久',
'觉儿行步奔',
'所来为宗族',
'亦不为盘飧',
'小人利口实',
'薄俗难可论',
'勿受外嫌猜',
'同姓古所敦',
],
},
{
title: '九日寄岑参(参,南阳人)',
body: [
'出门复入门',
'两脚但如旧',
'所向泥活活',
'思君令人瘦',
'沉吟坐西轩',
'饮食错昏昼',
'寸步曲江头',
'难为一相就',
'吁嗟呼苍生',
'稼穑不可救',
'安得诛云师',
'畴能补天漏',
'大明韬日月',
'旷野号禽兽',
'君子强逶迤',
'小人困驰骤',
'维南有崇山',
'恐与川浸溜',
'是节东篱菊',
'纷披为谁秀',
'岑生多新诗',
'性亦嗜醇酎',
'采采黄金花',
'何由满衣袖',
],
},
{
title: '送孔巢父谢病归游江东,兼呈李白',
body: [
'巢父掉头不肯住',
'东将入海随烟雾',
'诗卷长留天地间',
'钓竿欲拂珊瑚树',
'深山大泽龙蛇远',
'春寒野阴风景暮',
'蓬莱织女回云车',
'指点虚无是征路',
'自是君身有仙骨',
'世人那得知其故',
'惜君只欲苦死留',
'富贵何如草头露',
'蔡侯静者意有馀',
'清夜置酒临前除',
'罢琴惆怅月照席',
'几岁寄我空中书',
'南寻禹穴见李白',
'道甫问信今何如',
],
},
{
title: '饮中八仙歌',
body: [
'知章骑马似乘船',
'眼花落井水底眠',
'汝阳三斗始朝天',
'道逢麹车口流涎',
'恨不移封向酒泉',
'左相日兴费万钱',
'饮如长鲸吸百川',
'衔杯乐圣称世贤',
'宗之潇洒美少年',
'举觞白眼望青天',
'皎如玉树临风前',
'苏晋长斋绣佛前',
'醉中往往爱逃禅',
'李白一斗诗百篇',
'长安市上酒家眠',
'天子呼来不上船',
'自称臣是酒中仙',
'张旭三杯草圣传',
'脱帽露顶王公前',
'挥毫落纸如云烟',
'焦遂五斗方卓然',
'高谈雄辨惊四筵',
],
},
{
title: '曲江三章,章五句',
body: [
'曲江萧条秋气高',
'菱荷枯折随风涛',
'游子空嗟垂二毛',
'白石素沙亦相荡',
'哀鸿独叫求其曹',
'即事非今亦非古',
'长歌激越梢林莽',
'比屋豪华固难数',
'吾人甘作心似灰',
'弟侄何伤泪如雨',
'自断此生休问天',
'杜曲幸有桑麻田',
'故将移住南山边',
'短衣匹马随李广',
'看射猛虎终残年',
],
},
{
title: '丽人行',
body: [
'三月三日天气新',
'长安水边多丽人',
'态浓意远淑且真',
'肌理细腻骨肉匀',
'绣罗衣裳照暮春',
'蹙金孔雀银麒麟',
'头上何所有',
'翠微zc叶垂鬓唇',
'背后何所见',
'珠压腰衱稳称身',
'就中云幕椒房亲',
'赐名大国虢与秦',
'紫驼之峰出翠釜',
'水精之盘行素鳞',
'犀箸厌饫久未下',
'銮刀缕切空纷纶',
'黄门飞鞚不动尘',
'御厨络绎送八珍',
'箫鼓哀吟感鬼神',
'宾从杂遝实要津',
'后来鞍马何逡巡',
'当轩下马入锦茵',
'杨花雪落覆白蘋',
'青鸟飞去衔红巾',
'炙手可热势绝伦',
'慎莫近前丞相嗔',
],
},
{
title: '乐游园歌',
body: [
'乐游古园崒森爽',
'烟绵碧草萋萋长',
'公子华筵势最高',
'秦川对酒平如掌',
'长生木瓢示真率',
'更调鞍马狂欢赏',
'青春波浪芙蓉园',
'白日雷霆夹城仗',
'阊阖晴开昳荡荡',
'曲江翠幕排银榜',
'拂水低徊舞袖翻',
'缘云清切歌声上',
'却忆年年人醉时',
'只今未醉已先悲',
'数茎白发那抛得',
'百罚深杯亦不辞',
'圣朝亦知贱士丑',
'一物自荷皇天慈',
'此身饮罢无归处',
'独立苍茫自咏诗',
],
},
{
title: '渼陂行(陂在鄠县西五里,周一十四里)',
body: [
'岑参兄弟皆好奇',
'携我远来游渼陂',
'天地黤惨忽异色',
'波涛万顷堆琉璃',
'琉璃汗漫泛舟入',
'事殊兴极忧思集',
'鼍作鲸吞不复知',
'恶风白浪何嗟及',
'主人锦帆相为开',
'舟子喜甚无氛埃',
'凫鹥散乱棹讴发',
'丝管啁啾空翠来',
'沈竿续蔓深莫测',
'菱叶荷花静如拭',
'宛在中流渤澥清',
'下归无极终南黑',
'半陂已南纯浸山',
'动影袅窕冲融间',
'船舷暝戛云际寺',
'水面月出蓝田关',
'此时骊龙亦吐珠',
'冯夷击鼓群龙趋',
'湘妃汉女出歌舞',
'金支翠旗光有无',
'咫尺但愁雷雨至',
'苍茫不晓神灵意',
'少壮几时奈老何',
'向来哀乐何其多',
],
},
{
title: '渼陂西南台',
body: [
'高台面苍陂',
'六月风日冷',
'蒹葭离披去',
'天水相与永',
'怀新目似击',
'接要心已领',
'仿像识鲛人',
'空蒙辨鱼艇',
'错磨终南翠',
'颠倒白阁影',
'崷崒增光辉',
'乘陵惜俄顷',
'劳生愧严郑',
'外物慕张邴',
'世复轻骅骝',
'吾甘杂蛙黾',
'知归俗可忽',
'取适事莫并',
'身退岂待官',
'老来苦便静',
'况资菱芡足',
'庶结茅茨迥',
'从此具扁舟',
'弥年逐清景',
],
},
{
title: '戏简郑广文虔,兼呈苏司业源明',
body: [
'广文到官舍',
'系马堂阶下',
'醉则骑马归',
'颇遭官长骂',
'才名四十年',
'坐客寒无毡',
'赖有苏司业',
'时时与酒钱',
],
},
{
title: '夏日李公见访',
body: [
'远林暑气薄',
'公子过我游',
'贫居类村坞',
'僻近城南楼',
'旁舍颇淳朴',
'所愿亦易求',
'隔屋唤西家',
'借问有酒不',
'墙头过浊醪',
'展席俯长流',
'清风左右至',
'客意已惊秋',
'巢多众鸟斗',
'叶密鸣蝉稠',
'苦道此物聒',
'孰谓吾庐幽',
'水花晚色静',
'庶足充淹留',
'预恐尊中尽',
'更起为君谋',
],
},
{
title: '奉同郭给事汤东灵湫作(骊山温汤之东有龙湫)',
body: [
'东山气鸿濛',
'宫殿居上头',
'君来必十月',
'树羽临九州',
'阴火煮玉泉',
'喷薄涨岩幽',
'有时浴赤日',
'光抱空中楼',
'阆风入辙迹',
'旷原延冥搜',
'沸天万乘动',
'观水百丈湫',
'幽灵斯可佳',
'王命官属休',
'初闻龙用壮',
'擘石摧林丘',
'中夜窟宅改',
'移因风雨秋',
'倒悬瑶池影',
'屈注苍江流',
'味如甘露浆',
'挥弄滑且柔',
'翠旗澹偃蹇',
'云车纷少留',
'箫鼓荡四溟',
'异香泱漭浮',
'鲛人献微绡',
'曾祝沈豪牛',
'百祥奔盛明',
'古先莫能俦',
'坡陀金虾蟆',
'出见盖有由',
'至尊顾之笑',
'王母不肯收',
'复归虚无底',
'化作长黄虬',
'飘飘青琐郎',
'文彩珊瑚钩',
'浩歌渌水曲',
'清绝听者愁',
],
},
{
title: '夜听许十损诵诗爱而有作',
body: [
'许生五台宾',
'业白出石壁',
'余亦师粲可',
'身犹缚禅寂',
'何阶子方便',
'谬引为匹敌',
'离索晚相逢',
'包蒙欣有击',
'诵诗浑游衍',
'四座皆辟易',
'应手看捶钩',
'清心听鸣镝',
'精微穿溟涬',
'飞动摧霹雳',
'陶谢不枝梧',
'风骚共推激',
'紫燕自超诣',
'翠驳谁剪剔',
'君意人莫知',
'人间夜寥阒',
],
},
{
title: '桥陵诗三十韵,因呈县内诸官',
body: [
'先帝昔晏驾',
'兹山朝百灵',
'崇冈拥象设',
'沃野开天庭',
'即事壮重险',
'论功超五丁',
'坡陀因厚地',
'却略罗峻屏',
'云阙虚冉冉',
'风松肃泠泠',
'石门霜露白',
'玉殿莓苔青',
'宫女晚知曙',
'祠官朝见星',
'空梁簇画戟',
'阴井敲铜瓶',
'中使日夜继',
'惟王心不宁',
'岂徒恤备享',
'尚谓求无形',
'孝理敦国政',
'神凝推道经',
'瑞芝产庙柱',
'好鸟鸣岩扃',
'高岳前嵂崒',
'洪河左滢濙',
'金城蓄峻址',
'沙苑交回汀',
'永与奥区固',
'川原纷眇冥',
'居然赤县立',
'台榭争岧亭',
'官属果称是',
'声华真可听',
'王刘美竹润',
'裴李春兰馨',
'郑氏才振古',
'啖侯笔不停',
'遣辞必中律',
'利物常发硎',
'绮绣相展转',
'琳琅愈青荧',
'侧闻鲁恭化',
'秉德崔瑗铭',
'太史候凫影',
'王乔随鹤翎',
'朝仪限霄汉',
'容思回林坰',
'轗轲辞下杜',
'飘飖陵浊泾',
'诸生旧短褐',
'旅泛一浮萍',
'荒岁儿女瘦',
'暮途涕泗零',
'主人念老马',
'廨署容秋萤',
'流寓理岂惬',
'穷愁醉未醒',
'何当摆俗累',
'浩荡乘沧溟',
],
},
{
title: '沙苑行',
body: [
'君不见左辅白沙如白水',
'缭以周墙百馀里',
'龙媒昔是渥洼生',
'汗血今称献于此',
'苑中騋牝三千匹',
'丰草青青寒不死',
'食之豪健西域无',
'每岁攻驹冠边鄙',
'王有虎臣司苑门',
'入门天厩皆云屯',
'骕骦一骨独当御',
'春秋二时归至尊',
'至尊内外马盈亿',
'伏枥在坰空大存',
'逸群绝足信殊杰',
'倜傥权奇难具论',
'累累塠阜藏奔突',
'往往坡陀纵超越',
'角壮翻同麋鹿游',
'浮深簸荡鼋鼍窟',
'泉出巨鱼长比人',
'丹砂作尾黄金鳞',
'岂知异物同精气',
'虽未成龙亦有神',
],
},
{
title: '骢马行',
body: [
'邓公马癖人共知',
'初得花骢大宛种',
'夙昔传闻思一见',
'牵来左右神皆竦',
'雄姿逸态何崷崒',
'顾影骄嘶自矜宠',
'隅目青荧夹镜悬',
'肉骏碨礌连钱动',
'朝来久试华轩下',
'未觉千金满高价',
'赤汗微生白雪毛',
'银鞍却覆香罗帕',
'卿家旧赐公取之',
'天厩真龙此其亚',
'昼洗须腾泾渭深',
'朝趋可刷幽并夜',
'吾闻良骥老始成',
'此马数年人更惊',
'岂有四蹄疾于鸟',
'不与八骏俱先鸣',
'时俗造次那得致',
'云雾晦冥方降精',
'近闻下诏喧都邑',
'肯使骐驎地上行',
],
},
{
title: '去矣行',
body: [
'君不见鞲上鹰',
'一饱则飞掣',
'焉能作堂上燕',
'衔泥附炎热',
'野人旷荡无靦颜',
'岂可久在王侯间',
'未试囊中餐玉法',
'明朝且入蓝田山',
],
},
{
title: '自京赴奉先县咏怀五百字',
body: [
'杜陵有布衣',
'老大意转拙',
'许身一何愚',
'窃比稷与契',
'居然成濩落',
'白首甘契阔',
'盖棺事则已',
'此志常觊豁',
'穷年忧黎元',
'叹息肠内热',
'取笑同学翁',
'浩歌弥激烈',
'非无江海志',
'萧洒送日月',
'生逢尧舜君',
'不忍便永诀',
'当今廊庙具',
'构厦岂云缺',
'葵藿倾太阳',
'物性固莫夺',
'顾惟蝼蚁辈',
'但自求其穴',
'胡为慕大鲸',
'辄拟偃溟渤',
'以兹悟生理',
'独耻事干谒',
'兀兀遂至今',
'忍为尘埃没',
'终愧巢与由',
'未能易其节',
'沈饮聊自适',
'放歌颇愁绝',
'岁暮百草零',
'疾风高冈裂',
'天衢阴峥嵘',
'客子中夜发',
'霜严衣带断',
'指直不得结',
'凌晨过骊山',
'御榻在嵽嵲',
'蚩尤塞寒空',
'蹴蹋崖谷滑',
'瑶池气郁律',
'羽林相摩戛',
'君臣留欢娱',
'乐动殷樛嶱',
'赐浴皆长缨',
'与宴非短褐',
'彤庭所分帛',
'本自寒女出',
'鞭挞其夫家',
'聚敛贡城阙',
'圣人筐篚恩',
'实欲邦国活',
'臣如忽至理',
'君岂弃此物',
'多士盈朝廷',
'仁者宜战栗',
'况闻内金盘',
'尽在卫霍室',
'中堂舞神仙',
'烟雾散玉质',
'暖客貂鼠裘',
'悲管逐清瑟',
'劝客驼蹄羹',
'霜橙压香橘',
'朱门酒肉臭',
'路有冻死骨',
'荣枯咫尺异',
'惆怅难再述',
'北辕就泾渭',
'官渡又改辙',
'群冰从西下',
'极目高崒兀',
'疑是崆峒来',
'恐触天柱折',
'河梁幸未坼',
'枝撑声窸窣',
'行旅相攀援',
'川广不可越',
'老妻寄异县',
'十口隔风雪',
'谁能久不顾',
'庶往共饥渴',
'入门闻号咷',
'幼子饥已卒',
'吾宁舍一哀',
'里巷亦呜咽',
'所愧为人父',
'无食致夭折',
'岂知秋未登',
'贫窭有仓卒',
'生常免租税',
'名不隶征伐',
'抚迹犹酸辛',
'平人固骚屑',
'默思失业徒',
'因念远戍卒',
'忧端齐终南',
'澒洞不可掇',
],
},
{
title: '奉先刘少府新画山水障歌',
body: [
'堂上不合生枫树',
'怪底江山起烟雾',
'闻君扫却赤县图',
'乘兴遣画沧洲趣',
'画师亦无数',
'好手不可遇',
'对此融心神',
'知君重毫素',
'岂但祁岳与郑虔',
'笔迹远过杨契丹',
'得非悬圃裂',
'无乃潇湘翻',
'悄然坐我天姥下',
'耳边已似闻清猿',
'反思前夜风雨急',
'乃是蒲城鬼神入',
'元气淋漓障犹湿',
'真宰上诉天应泣',
'野亭春还杂花远',
'渔翁暝蹋孤舟立',
'沧浪水深青溟阔',
'欹岸侧岛秋毫末',
'不见湘妃鼓瑟时',
'至今斑竹临江活',
'刘侯天机精',
'爱画入骨髓',
'自有两儿郎',
'挥洒亦莫比',
'大儿聪明到',
'能添老树巅崖里',
'小儿心孔开',
'貌得山僧及童子',
'若耶溪',
'云门寺',
'吾独胡为在泥滓',
'青鞋布袜从此始',
],
},
{
title: '白水县崔少府十九翁高斋三十韵',
body: [
'客从南县来',
'浩荡无与适',
'旅食白日长',
'况当朱炎赫',
'高斋坐林杪',
'信宿游衍阒',
'清晨陪跻攀',
'傲睨俯峭壁',
'崇冈相枕带',
'旷野怀咫尺',
'始知贤主人',
'赠此遣愁寂',
'危阶根青冥',
'曾冰生淅沥',
'上有无心云',
'下有欲落石',
'泉声闻复急',
'动静随所击',
'鸟呼藏其身',
'有似惧弹射',
'吏隐道性情',
'兹焉其窟宅',
'白水见舅氏',
'诸翁乃仙伯',
'杖藜长松阴',
'作尉穷谷僻',
'为我炊雕胡',
'逍遥展良觌',
'坐久风颇愁',
'晚来山更碧',
'相对十丈蛟',
'欻翻盘涡坼',
'何得空里雷',
'殷殷寻地脉',
'烟氛蔼崷崒',
'魍魉森惨戚',
'昆仑崆峒颠',
'回首如不隔',
'前轩颓反照',
'巉绝华岳赤',
'兵气涨林峦',
'川光杂锋镝',
'知是相公军',
'铁马云雾积',
'玉觞淡无味',
'胡羯岂强敌',
'长歌激屋梁',
'泪下流衽席',
'人生半哀乐',
'天地有顺逆',
'慨彼万国夫',
'休明备征狄',
'猛将纷填委',
'庙谋蓄长策',
'东郊何时开',
'带甲且来释',
'欲告清宴罢',
'难拒幽明迫',
'三叹酒食旁',
'何由似平昔',
],
},
{
title: '三川观水涨二十韵',
body: [
'我经华原来',
'不复见平陆',
'北上唯土山',
'连山走穷谷',
'火云无时出',
'飞电常在目',
'自多穷岫雨',
'行潦相豗蹙',
'蓊匌川气黄',
'群流会空曲',
'清晨望高浪',
'忽谓阴崖踣',
'恐泥窜蛟龙',
'登危聚麋鹿',
'枯查卷拔树',
'礧磈共充塞',
'声吹鬼神下',
'势阅人代速',
'不有万穴归',
'何以尊四渎',
'及观泉源涨',
'反惧江海覆',
'漂沙坼岸去',
'漱壑松柏秃',
'乘陵破山门',
'回斡裂地轴',
'交洛赴洪河',
'及关岂信宿',
'应沈数州没',
'如听万室哭',
'秽浊殊未清',
'风涛怒犹蓄',
'何时通舟车',
'阴气不黪黩',
'浮生有荡汩',
'吾道正羁束',
'人寰难容身',
'石壁滑侧足',
'云雷此不已',
'艰险路更跼',
'普天无川梁',
'欲济愿水缩',
'因悲中林士',
'未脱众鱼腹',
'举头向苍天',
'安得骑鸿鹄',
],
},
{
title: '悲陈陶',
body: [
'孟冬十郡良家子',
'血作陈陶泽中水',
'野旷天清无战声',
'四万义军同日死',
'群胡归来血洗箭',
'仍唱胡歌饮都市',
'都人回面向北啼',
'日夜更望官军至',
],
},
{
title: '悲青坂',
body: [
'我军青坂在东门',
'天寒饮马太白窟',
'黄头奚儿日向西',
'数骑弯弓敢驰突',
'山雪河冰野萧瑟',
'青是烽烟白人骨',
'焉得附书与我军',
'忍待明年莫仓卒',
],
},
{
title: '哀江头',
body: [
'少陵野老吞声哭',
'春日潜行曲江曲',
'江头宫殿锁千门',
'细柳新蒲为谁绿',
'忆昔霓旌下南苑',
'苑中万物生颜色',
'昭阳殿里第一人',
'同辇随君侍君侧',
'辇前才人带弓箭',
'白马嚼啮黄金勒',
'翻身向天仰射云',
'一箭正坠双飞翼',
'明眸皓齿今何在',
'血污游魂归不得',
'清渭东流剑阁深',
'去住彼此无消息',
'人生有情泪沾臆',
'江水江花岂终极',
'黄昏胡骑尘满城',
'欲往城南忘南北',
],
},
{
title: '哀王孙',
body: [
'长安城头头白乌',
'夜飞延秋门上呼',
'又向人家啄大屋',
'屋底达官走避胡',
'金鞭断折九马死',
'骨肉不待同驰驱',
'腰下宝玦青珊瑚',
'可怜王孙泣路隅',
'问之不肯道姓名',
'但道困苦乞为奴',
'已经百日窜荆棘',
'身上无有完肌肤',
'高帝子孙尽隆准',
'龙种自与常人殊',
'豺狼在邑龙在野',
'王孙善保千金躯',
'不敢长语临交衢',
'且为王孙立斯须',
'昨夜东风吹血腥',
'东来橐驼满旧都',
'朔方健儿好身手',
'昔何勇锐今何愚',
'窃闻天子已传位',
'圣德北服南单于',
'花门kO面请雪耻',
'慎勿出口他人狙',
'哀哉王孙慎勿疏',
'五陵佳气无时无',
],
},
{
title: '大云寺赞公房四首',
body: [
'心在水精域',
'衣沾春雨时',
'洞门尽徐步',
'深院果幽期',
'到扉开复闭',
'撞钟斋及兹',
'醍醐长发性',
'饮食过扶衰',
'把臂有多日',
'开怀无愧辞',
'黄鹂度结构',
'紫鸽下罘罳',
'愚意会所适',
'花边行自迟',
'汤休起我病',
'微笑索题诗',
'细软青丝履',
'光明白氎巾',
'深藏供老宿',
'取用及吾身',
'自顾转无趣',
'交情何尚新',
'道林才不世',
'惠远德过人',
'雨泻暮檐竹',
'风吹青井芹',
'天阴对图画',
'最觉润龙鳞',
'灯影照无睡',
'心清闻妙香',
'夜深殿突兀',
'风动金锒铛',
'天黑闭春院',
'地清栖暗芳',
'玉绳回断绝',
'铁凤森翱翔',
'梵放时出寺',
'钟残仍殷床',
'明朝在沃野',
'苦见尘沙黄',
'童儿汲井华',
'惯捷瓶上手',
'沾洒不濡地',
'扫除似无帚',
'明霞烂复阁',
'霁雾搴高牖',
'侧塞被径花',
'飘飖委墀柳',
'艰难世事迫',
'隐遁佳期后',
'晤语契深心',
'那能总箝口',
'奉辞还杖策',
'暂别终回首',
'泱泱泥污人',
'听听国多狗',
'既未免羁绊',
'时来憩奔走',
'近公如白雪',
'执热烦何有',
],
},
{
title: '苏端、薛复筵简薛华醉歌',
body: [
'文章有神交有道',
'端复得之名誉早',
'爱客满堂尽豪翰',
'开筵上日思芳草',
'安得健步移远梅',
'乱插繁花向晴昊',
'千里犹残旧冰雪',
'百壶且试开怀抱',
'垂老恶闻战鼓悲',
'急觞为缓忧心捣',
'少年努力纵谈笑',
'看我形容已枯槁',
'坐中薛华善醉歌',
'歌辞自作风格老',
'近来海内为长句',
'汝与山东李白好',
'何刘沈谢力未工',
'才兼鲍昭愁绝倒',
'诸生颇尽新知乐',
'万事终伤不自保',
'气酣日落西风来',
'愿吹野水添金杯',
'如渑之酒常快意',
'亦知穷愁安在哉',
'忽忆雨时秋井塌',
'古人白骨生青苔',
'如何不饮令心哀',
],
},
{
title: '晦日寻崔戢、李封',
body: [
'朝光入瓮牖',
'尸寝惊敝裘',
'起行视天宇',
'春气渐和柔',
'兴来不暇懒',
'今晨梳我头',
'出门无所待',
'徒步觉自由',
'杖藜复恣意',
'免值公与侯',
'晚定崔李交',
'会心真罕俦',
'每过得酒倾',
'二宅可淹留',
'喜结仁里欢',
'况因令节求',
'李生园欲荒',
'旧竹颇修修',
'引客看扫除',
'随时成献酬',
'崔侯初筵色',
'已畏空尊愁',
'未知天下士',
'至性有此不',
'草牙既青出',
'蜂声亦暖游',
'思见农器陈',
'何当甲兵休',
'上古葛天民',
'不贻黄屋忧',
'至今阮籍等',
'熟醉为身谋',
'威凤高其翔',
'长鲸吞九洲',
'地轴为之翻',
'百川皆乱流',
'当歌欲一放',
'泪下恐莫收',
'浊醪有妙理',
'庶用慰沈浮',
],
},
{
title: '雨过苏端(端置酒)',
body: [
'鸡鸣风雨交',
'久旱云亦好',
'杖藜入春泥',
'无食起我早',
'诸家忆所历',
'一饭迹便扫',
'苏侯得数过',
'欢喜每倾倒',
'也复可怜人',
'呼儿具梨枣',
'浊醪必在眼',
'尽醉摅怀抱',
'红稠屋角花',
'碧委墙隅草',
'亲宾纵谈谑',
'喧闹畏衰老',
'况蒙霈泽垂',
'粮粒或自保',
'妻孥隔军垒',
'拨弃不拟道',
],
},
{
title: '喜晴(一作喜雨)',
body: [
'皇天久不雨',
'既雨晴亦佳',
'出郭眺西郊',
'肃肃春增华',
'青荧陵陂麦',
'窈窕桃李花',
'春夏各有实',
'我饥岂无涯',
'干戈虽横放',
'惨澹斗龙蛇',
'甘泽不犹愈',
'且耕今未赊',
'丈夫则带甲',
'妇女终在家',
'力难及黍稷',
'得种菜与麻',
'千载商山芝',
'往者东门瓜',
'其人骨已朽',
'此道谁疵瑕',
'英贤遇轗轲',
'远引蟠泥沙',
'顾惭昧所适',
'回首白日斜',
'汉阴有鹿门',
'沧海有灵查',
'焉能学众口',
'咄咄空咨嗟',
],
},
{
title: '送率府程录事还乡',
body: [
'鄙夫行衰谢',
'抱病昏妄集',
'常时往还人',
'记一不识十',
'程侯晚相遇',
'与语才杰立',
'熏然耳目开',
'颇觉聪明入',
'千载得鲍叔',
'末契有所及',
'意钟老柏青',
'义动修蛇蛰',
'若人可数见',
'慰我垂白泣',
'告别无淹晷',
'百忧复相袭',
'内愧突不黔',
'庶羞以赒给',
'素丝挈长鱼',
'碧酒随玉粒',
'途穷见交态',
'世梗悲路涩',
'东风吹春冰',
'泱莽后土湿',
'念君惜羽翮',
'既饱更思戢',
'莫作翻云鹘',
'闻呼向禽急',
],
},
{
title: '述怀一首(此已下自贼中窜归凤翔作)',
body: [
'去年潼关破',
'妻子隔绝久',
'今夏草木长',
'脱身得西走',
'麻鞋见天子',
'衣袖露两肘',
'朝廷愍生还',
'亲故伤老丑',
'涕泪授拾遗',
'流离主恩厚',
'柴门虽得去',
'未忍即开口',
'寄书问三川',
'不知家在否',
'比闻同罹祸',
'杀戮到鸡狗',
'山中漏茅屋',
'谁复依户牖',
'摧颓苍松根',
'地冷骨未朽',
'几人全性命',
'尽室岂相偶',
'嶔岑猛虎场',
'郁结回我首',
'自寄一封书',
'今已十月后',
'反畏消息来',
'寸心亦何有',
'汉运初中兴',
'生平老耽酒',
'沉思欢会处',
'恐作穷独叟',
],
},
{
title: '送长孙九侍御赴武威判官',
body: [
'骢马新凿蹄',
'银鞍被来好',
'绣衣黄白郎',
'骑向交河道',
'问君适万里',
'取别何草草',
'天子忧凉州',
'严程到须早',
'去秋群胡反',
'不得无电扫',
'此行收遗甿',
'风俗方再造',
'族父领元戎',
'名声国中老',
'夺我同官良',
'飘摇按城堡',
'使我不能餐',
'令我恶怀抱',
'若人才思阔',
'溟涨浸绝岛',
'尊前失诗流',
'塞上得国宝',
'皇天悲送远',
'云雨白浩浩',
'东郊尚烽火',
'朝野色枯槁',
'西极柱亦倾',
'如何正穹昊',
],
},
{
title: '送樊二十三侍御赴汉中判官',
body: [
'威弧不能弦',
'自尔无宁岁',
'川谷血横流',
'豺狼沸相噬',
'天子从北来',
'长驱振凋敝',
'顿兵岐梁下',
'却跨沙漠裔',
'二京陷未收',
'四极我得制',
'萧索汉水清',
'缅通淮湖税',
'使者纷星散',
'王纲尚旒缀',
'南伯从事贤',
'君行立谈际',
'生知七曜历',
'手画三军势',
'冰雪净聪明',
'雷霆走精锐',
'幕府辍谏官',
'朝廷无此例',
'至尊方旰食',
'仗尔布嘉惠',
'补阙暮征入',
'柱史晨征憩',
'正当艰难时',
'实藉长久计',
'回风吹独树',
'白日照执袂',
'恸哭苍烟根',
'山门万重闭',
'居人莽牢落',
'游子方迢递',
'裴回悲生离',
'局促老一世',
'陶唐歌遗民',
'后汉更列帝',
'恨无匡复姿',
'聊欲从此逝',
],
},
{
title: '送从弟亚赴安西判官',
body: [
'南风作秋声',
'杀气薄炎炽',
'盛夏鹰隼击',
'时危异人至',
'令弟草中来',
'苍然请论事',
'诏书引上殿',
'奋舌动天意',
'兵法五十家',
'尔腹为箧笥',
'应对如转丸',
'疏通略文字',
'经纶皆新语',
'足以正神器',
'宗庙尚为灰',
'君臣俱下泪',
'崆峒地无轴',
'青海天轩轾',
'西极最疮痍',
'连山暗烽燧',
'帝曰大布衣',
'藉卿佐元帅',
'坐看清流沙',
'所以子奉使',
'归当再前席',
'适远非历试',
'须存武威郡',
'为画长久利',
'孤峰石戴驿',
'快马金缠辔',
'黄羊饫不膻',
'芦酒多还醉',
'踊跃常人情',
'惨澹苦士志',
'安边敌何有',
'反正计始遂',
'吾闻驾鼓车',
'不合用骐骥',
'龙吟回其头',
'夹辅待所致',
],
},
{
title: '送韦十六评事充同谷郡防御判官',
body: [
'昔没贼中时',
'潜与子同游',
'今归行在所',
'王事有去留',
'逼侧兵马间',
'主忧急良筹',
'子虽躯干小',
'老气横九州',
'挺身艰难际',
'张目视寇雠',
'朝廷壮其节',
'奉诏令参谋',
'銮舆驻凤翔',
'同谷为咽喉',
'西扼弱水道',
'南镇枹罕陬',
'此邦承平日',
'剽劫吏所羞',
'况乃胡未灭',
'控带莽悠悠',
'府中韦使君',
'道足示怀柔',
'令侄才俊茂',
'二美又何求',
'受词太白脚',
'走马仇池头',
'古色沙土裂',
'积阴雪云稠',
'羌父豪猪靴',
'羌儿青兕裘',
'吹角向月窟',
'苍山旌旆愁',
'鸟惊出死树',
'龙怒拔老湫',
'古来无人境',
'今代横戈矛',
'伤哉文儒士',
'愤激驰林丘',
'中原正格斗',
'后会何缘由',
'百年赋命定',
'岂料沉与浮',
'且复恋良友',
'握手步道周',
'论兵远壑净',
'亦可纵冥搜',
'题诗得秀句',
'札翰时相投',
],
},
{
title: '塞芦子(芦子关属夏州,北去塞门镇一十八里)',
body: [
'五城何迢迢',
'迢迢隔河水',
'边兵尽东征',
'城内空荆杞',
'思明割怀卫',
'秀岩西未已',
'回略大荒来',
'崤函盖虚尔',
'延州秦北户',
'关防犹可倚',
'焉得一万人',
'疾驱塞芦子',
'岐有薛大夫',
'旁制山贼起',
'近闻昆戎徒',
'为退三百里',
'芦关扼两寇',
'深意实在此',
'谁能叫帝阍',
'胡行速如鬼',
],
},
{
title: '彭衙行(郃阳县西北有彭衙城)',
body: [
'忆昔避贼初',
'北走经险艰',
'夜深彭衙道',
'月照白水山',
'尽室久徒步',
'逢人多厚颜',
'参差谷鸟吟',
'不见游子还',
'痴女饥咬我',
'啼畏虎狼闻',
'怀中掩其口',
'反侧声愈嗔',
'小儿强解事',
'故索苦李餐',
'一旬半雷雨',
'泥泞相牵攀',
'既无御雨备',
'径滑衣又寒',
'有时经契阔',
'竟日数里间',
'野果充糇粮',
'卑枝成屋椽',
'早行石上水',
'暮宿天边烟',
'少留周家洼',
'欲出芦子关',
'故人有孙宰',
'高义薄曾云',
'延客已曛黑',
'张灯启重门',
'暖汤濯我足',
'翦纸招我魂',
'从此出妻孥',
'相视涕阑干',
'众雏烂熳睡',
'唤起沾盘餐',
'誓将与夫子',
'永结为弟昆',
'遂空所坐堂',
'安居奉我欢',
'谁肯艰难际',
'豁达露心肝',
'别来岁月周',
'胡羯仍构患',
'何当有翅翎',
'飞去堕尔前',
],
},
{
title: '北征',
body: [
'皇帝二载秋',
'闰八月初吉',
'杜子将北征',
'苍茫问家室',
'维时遭艰虞',
'朝野少暇日',
'顾惭恩私被',
'诏许归蓬荜',
'拜辞诣阙下',
'怵惕久未出',
'虽乏谏诤姿',
'恐君有遗失',
'君诚中兴主',
'经纬固密勿',
'东胡反未已',
'臣甫愤所切',
'挥涕恋行在',
'道途犹恍惚',
'乾坤含疮痍',
'忧虞何时毕',
'靡靡逾阡陌',
'人烟眇萧瑟',
'所遇多被伤',
'呻吟更流血',
'回首凤翔县',
'旌旗晚明灭',
'前登寒山重',
'屡得饮马窟',
'邠郊入地底',
'泾水中荡潏',
'猛虎立我前',
'苍崖吼时裂',
'菊垂今秋花',
'石戴古车辙',
'青云动高兴',
'幽事亦可悦',
'山果多琐细',
'罗生杂橡栗',
'或红如丹砂',
'或黑如点漆',
'雨露之所濡',
'甘苦齐结实',
'缅思桃源内',
'益叹身世拙',
'坡陀望鄜畤',
'岩谷互出没',
'我行已水滨',
'我仆犹木末',
'鸱鸟鸣黄桑',
'野鼠拱乱穴',
'夜深经战场',
'寒月照白骨',
'潼关百万师',
'往者散何卒',
'遂令半秦民',
'残害为异物',
'况我堕胡尘',
'及归尽华发',
'经年至茅屋',
'妻子衣百结',
'恸哭松声回',
'悲泉共幽咽',
'平生所娇儿',
'颜色白胜雪',
'见耶背面啼',
'垢腻脚不袜',
'床前两小女',
'补绽才过膝',
'海图坼波涛',
'旧绣移曲折',
'天吴及紫凤',
'颠倒在裋褐',
'老夫情怀恶',
'呕泄卧数日',
'那无囊中帛',
'救汝寒凛栗',
'粉黛亦解苞',
'衾裯稍罗列',
'瘦妻面复光',
'痴女头自栉',
'学母无不为',
'晓妆随手抹',
'移时施朱铅',
'狼藉画眉阔',
'生还对童稚',
'似欲忘饥渴',
'问事竞挽须',
'谁能即嗔喝',
'翻思在贼愁',
'甘受杂乱聒',
'新归且慰意',
'生理焉能说',
'至尊尚蒙尘',
'几日休练卒',
'仰观天色改',
'坐觉祆气豁',
'阴风西北来',
'惨澹随回鹘',
'其王愿助顺',
'其俗善驰突',
'送兵五千人',
'驱马一万匹',
'此辈少为贵',
'四方服勇决',
'所用皆鹰腾',
'破敌过箭疾',
'圣心颇虚伫',
'时议气欲夺',
'伊洛指掌收',
'西京不足拔',
'官军请深入',
'蓄锐何俱发',
'此举开青徐',
'旋瞻略恒碣',
'昊天积霜露',
'正气有肃杀',
'祸转亡胡岁',
'势成擒胡月',
'胡命其能久',
'皇纲未宜绝',
'忆昨狼狈初',
'事与古先别',
'奸臣竟菹醢',
'同恶随荡析',
'不闻夏殷衰',
'中自诛褒妲',
'周汉获再兴',
'宣光果明哲',
'桓桓陈将军',
'仗钺奋忠烈',
'微尔人尽非',
'于今国犹活',
'凄凉大同殿',
'寂寞白兽闼',
'都人望翠华',
'佳气向金阙',
'园陵固有神',
'扫洒数不缺',
'煌煌太宗业',
'树立甚宏达',
],
},
{
title: '得舍弟消息',
body: [
'风吹紫荆树',
'色与春庭暮',
'花落辞故枝',
'风回返无处',
'骨肉恩书重',
'漂泊难相遇',
'犹有泪成河',
'经天复东注',
],
},
{
title: '徒步归行',
body: [
'明公壮年值时危',
'经济实藉英雄姿',
'国之社稷今若是',
'武定祸乱非公谁',
'凤翔千官且饱饭',
'衣马不复能轻肥',
'青袍朝士最困者',
'白头拾遗徒步归',
'人生交契无老少',
'论交何必先同调',
'妻子山中哭向天',
'须公枥上追风骠',
],
},
{
title: '玉华宫',
body: [
'溪回松风长',
'苍鼠窜古瓦',
'不知何王殿',
'遗构绝壁下',
'阴房鬼火青',
'坏道哀湍泻',
'万籁真笙竽',
'秋色正萧洒',
'美人为黄土',
'况乃粉黛假',
'当时侍金舆',
'故物独石马',
'忧来藉草坐',
'浩歌泪盈把',
'冉冉征途间',
'谁是长年者',
],
},
{
title: '九成宫',
body: [
'苍山入百里',
'崖断如杵臼',
'曾宫凭风回',
'岌嶪土囊口',
'立神扶栋梁',
'凿翠开户牖',
'其阳产灵芝',
'其阴宿牛斗',
'纷披长松倒',
'揭gG怪石走',
'哀猿啼一声',
'客泪迸林薮',
'荒哉隋家帝',
'制此今颓朽',
'向使国不亡',
'焉为巨唐有',
'虽无新增修',
'尚置官居守',
'巡非瑶水远',
'迹是雕墙后',
'我行属时危',
'仰望嗟叹久',
'天王守太白',
'驻马更搔首',
],
},
{
title: '羌村',
body: [
'峥嵘赤云西',
'日脚下平地',
'柴门鸟雀噪',
'归客千里至',
'妻孥怪我在',
'惊定还拭泪',
'世乱遭飘荡',
'生还偶然遂',
'邻人满墙头',
'感叹亦歔欷',
'夜阑更秉烛',
'相对如梦寐',
'晚岁迫偷生',
'还家少欢趣',
'娇儿不离膝',
'畏我复却去',
'忆昔好追凉',
'故绕池边树',
'萧萧北风劲',
'抚事煎百虑',
'赖知禾黍收',
'已觉糟床注',
'如今足斟酌',
'且用慰迟暮',
'群鸡正乱叫',
'客至鸡斗争',
'驱鸡上树木',
'始闻叩柴荆',
'父老四五人',
'问我久远行',
'手中各有携',
'倾榼浊复清',
'苦辞酒味薄',
'黍地无人耕',
'兵革既未息',
'儿童尽东征',
'请为父老歌',
'艰难愧深情',
'歌罢仰天叹',
'四座泪纵横',
],
},
{
title: '逼仄行,赠毕曜(一作bX々行,一作赠毕四曜)',
body: [
'逼仄何逼仄',
'我居巷南子巷北',
'可恨邻里间',
'十日不一见颜色',
'自从官马送还官',
'行路难行涩如棘',
'我贫无乘非无足',
'昔者相过今不得',
'实不是爱微躯',
'又非关足无力',
'徒步翻愁官长怒',
'此心炯炯君应识',
'晓来急雨春风颠',
'睡美不闻钟鼓传',
'东家蹇驴许借我',
'泥滑不敢骑朝天',
'已令请急会通籍',
'男儿信命绝可怜',
'焉能终日心拳拳',
'忆君诵诗神凛然',
'辛夷始花亦已落',
'况我与子非壮年',
'街头酒价常苦贵',
'方外酒徒稀醉眠',
'速宜相就饮一斗',
'恰有三百青铜钱',
],
},
{
title: '送李校书二十六韵',
body: [
'代北有豪鹰',
'生子毛尽赤',
'渥洼骐骥儿',
'尤异是龙脊',
'李舟名父子',
'清峻流辈伯',
'人间好少年',
'不必须白晰',
'十五富文史',
'十八足宾客',
'十九授校书',
'二十声辉赫',
'众中每一见',
'使我潜动魄',
'自恐二男儿',
'辛勤养无益',
'乾元元年春',
'万姓始安宅',
'舟也衣彩衣',
'告我欲远适',
'倚门固有望',
'敛衽就行役',
'南登吟白华',
'已见楚山碧',
'蔼蔼咸阳都',
'冠盖日云积',
'何时太夫人',
'堂上会亲戚',
'汝翁草明光',
'天子正前席',
'归期岂烂漫',
'别意终感激',
'顾我蓬屋姿',
'谬通金闺籍',
'小来习性懒',
'晚节慵转剧',
'每愁悔吝作',
'如觉天地窄',
'羡君齿发新',
'行己能夕惕',
'临岐意颇切',
'对酒不能吃',
'回身视绿野',
'惨澹如荒泽',
'老雁春忍饥',
'哀号待枯麦',
'时哉高飞燕',
'绚练新羽翮',
'长云湿褒斜',
'汉水饶巨石',
'无令轩车迟',
'衰疾悲夙昔',
],
},
{
title: '洗兵马(收京后作)',
body: [
'中兴诸将收山东',
'捷书日报清昼同',
'河广传闻一苇过',
'胡危命在破竹中',
'祗残邺城不日得',
'独任朔方无限功',
'京师皆骑汗血马',
'回纥喂肉葡萄宫',
'已喜皇威清海岱',
'常思仙仗过崆峒',
'三年笛里关山月',
'万国兵前草木风',
'成王功大心转小',
'郭相谋深古来少',
'司徒清鉴悬明镜',
'尚书气与秋天杳',
'二三豪俊为时出',
'整顿乾坤济时了',
'东走无复忆鲈鱼',
'南飞觉有安巢鸟',
'青春复随冠冕入',
'紫禁正耐烟花绕',
'鹤禁通霄凤辇备',
'鸡鸣问寝龙楼晓',
'攀龙附凤势莫当',
'天下尽化为侯王',
'汝等岂知蒙帝力',
'时来不得夸身强',
'关中既留萧丞相',
'幕下复用张子房',
'张公一生江海客',
'身长九尺须眉苍',
'征起适遇风云会',
'扶颠始知筹策良',
'青袍白马更何有',
'后汉今周喜再昌',
'寸地尺天皆入贡',
'奇祥异瑞争来送',
'不知何国致白环',
'复道诸山得银瓮',
'隐士休歌紫芝曲',
'词人解撰河清颂',
'田家望望惜雨干',
'布谷处处催春种',
'淇上健儿归莫懒',
'城南思妇愁多梦',
'安得壮士挽天河',
'净洗甲兵长不用',
],
},
{
title: '留花门',
body: [
'北门天骄子',
'饱肉气勇决',
'高秋马肥健',
'挟矢射汉月',
'自古以为患',
'诗人厌薄伐',
'修德使其来',
'羁縻固不绝',
'胡为倾国至',
'出入暗金阙',
'中原有驱除',
'隐忍用此物',
'公主歌黄鹄',
'君王指白日',
'连云屯左辅',
'百里见积雪',
'长戟鸟休飞',
'哀笳曙幽咽',
'田家最恐惧',
'麦倒桑枝折',
'沙苑临清渭',
'泉香草丰洁',
'渡河不用船',
'千骑常撇烈',
'胡尘逾太行',
'杂种抵京室',
'花门既须留',
'原野转萧瑟',
],
},
{
title: '病后遇王倚饮,赠歌',
body: [
'麟角凤觜世莫识',
'煎胶续弦奇自见',
'尚看王生抱此怀',
'在于甫也何由羡',
'且遇王生慰畴昔',
'素知贱子甘贫贱',
'酷见冻馁不足耻',
'多病沈年苦无健',
'王生怪我颜色恶',
'答云伏枕艰难遍',
'疟疠三秋孰可忍',
'寒热百日相交战',
'头白眼暗坐有胝',
'肉黄皮皱命如线',
'惟生哀我未平复',
'为我力致美肴膳',
'遣人向市赊香粳',
'唤妇出房亲自馔',
'长安冬菹酸且绿',
'金城土酥静如练',
'兼求富豪且割鲜',
'密沽斗酒谐终宴',
'故人情义晚谁似',
'令我手脚轻欲漩',
'老马为驹信不虚',
'当时得意况深眷',
'但使残年饱吃饭',
'只愿无事常相见',
],
},
{
title: '湖城东遇孟云卿,复归刘颢宅宿宴,饮散因为醉歌',
body: [
'疾风吹尘暗河县',
'行子隔手不相见',
'湖城城南一开眼',
'驻马偶识云卿面',
'向非刘颢为地主',
'懒回鞭辔成高宴',
'刘侯叹我携客来',
'置酒张灯促华馔',
'且将款曲终今夕',
'休语艰难尚酣战',
'照室红炉促曙光',
'萦窗素月垂文练',
'天开地裂长安陌',
'寒尽春生洛阳殿',
'岂知驱车复同轨',
'可惜刻漏随更箭',
'人生会合不可常',
'庭树鸡鸣泪如线',
],
},
{
title: '阌乡姜七少府设脍,戏赠长歌',
body: [
'姜侯设脍当严冬',
'昨日今日皆天风',
'河冻未渔不易得',
'凿冰恐侵河伯宫',
'饔人受鱼鲛人手',
'洗鱼磨刀鱼眼红',
'无声细下飞碎雪',
'有骨已剁觜春葱',
'偏劝腹腴愧年少',
'软炊香饭缘老翁',
'落砧何曾白纸湿',
'放箸未觉金盘空',
'新欢便饱姜侯德',
'清觞异味情屡极',
'东归贪路自觉难',
'欲别上马身无力',
'可怜为人好心事',
'于我见子真颜色',
'不恨我衰子贵时',
'怅望且为今相忆',
],
},
{
title: '戏赠阌乡秦少公短歌',
body: [
'去年行宫当太白',
'朝回君是同舍客',
'同心不减骨肉亲',
'每语见许文章伯',
'今日时清两京道',
'相逢苦觉人情好',
'昨夜邀欢乐更无',
'多才依旧能潦倒',
],
},
{
title: '李鄠县丈人胡马行',
body: [
'丈人骏马名胡骝',
'前年避胡过金牛',
'回鞭却走见天子',
'朝饮汉水暮灵州',
'自矜胡骝奇绝代',
'乘出千人万人爱',
'一闻说尽急难材',
'转益愁向驽骀辈',
'头上锐耳批秋竹',
'脚下高蹄削寒玉',
'始知神龙别有种',
'不比俗马空多肉',
'洛阳大道时再清',
'累日喜得俱东行',
'凤臆龙鬐未易识',
'侧身注目长风生',
],
},
{
title: '义鹘',
body: [
'阴崖有苍鹰',
'养子黑柏颠',
'白蛇登其巢',
'吞噬恣朝餐',
'雄飞远求食',
'雌者鸣辛酸',
'力强不可制',
'黄口无半存',
'其父从西归',
'翻身入长烟',
'斯须领健鹘',
'痛愤寄所宣',
'斗上捩孤影',
'噭哮来九天',
'修鳞脱远枝',
'巨颡坼老拳',
'高空得蹭蹬',
'短草辞蜿蜒',
'折尾能一掉',
'饱肠皆已穿',
'生虽灭众雏',
'死亦垂千年',
'物情有报复',
'快意贵目前',
'兹实鸷鸟最',
'急难心炯然',
'功成失所往',
'用舍何其贤',
'近经潏水湄',
'此事樵夫传',
'飘萧觉素发',
'凛欲冲儒冠',
'人生许与分',
'只在顾盼间',
'聊为义鹘行',
'用激壮士肝',
],
},
{
title: '画鹘行(一作画雕)',
body: [
'高堂见生鹘',
'飒爽动秋骨',
'初惊无拘挛',
'何得立突兀',
'乃知画师妙',
'功刮造化窟',
'写作神骏姿',
'充君眼中物',
'乌鹊满樛枝',
'轩然恐其出',
'侧脑看青霄',
'宁为众禽没',
'长翮如刀剑',
'人寰可超越',
'乾坤空峥嵘',
'粉墨且萧瑟',
'缅思云沙际',
'自有烟雾质',
'吾今意何伤',
'顾步独纡郁',
],
},
{
title: '瘦马行(一作老马)',
body: [
'东郊瘦马使我伤',
'骨骼硉兀如堵墙',
'绊之欲动转欹侧',
'此岂有意仍腾骧',
'细看六印带官字',
'众道三军遗路旁',
'皮干剥落杂泥滓',
'毛暗萧条连雪霜',
'去岁奔波逐馀寇',
'骅骝不惯不得将',
'士卒多骑内厩马',
'惆怅恐是病乘黄',
'当时历块误一蹶',
'委弃非汝能周防',
'见人惨澹若哀诉',
'失主错莫无晶光',
'天寒远放雁为伴',
'日暮不收乌啄疮',
'谁家且养愿终惠',
'更试明年春草长',
],
},
{
title: '新安吏',
body: [
'客行新安道',
'喧呼闻点兵',
'借问新安吏',
'县小更无丁',
'府帖昨夜下',
'次选中男行',
'中男绝短小',
'何以守王城',
'肥男有母送',
'瘦男独伶俜',
'白水暮东流',
'青山犹哭声',
'莫自使眼枯',
'收汝泪纵横',
'眼枯即见骨',
'天地终无情',
'我军取相州',
'日夕望其平',
'岂意贼难料',
'归军星散营',
'就粮近故垒',
'练卒依旧京',
'掘壕不到水',
'牧马役亦轻',
'况乃王师顺',
'抚养甚分明',
'送行勿泣血',
'仆射如父兄',
],
},
{
title: '潼关吏',
body: [
'士卒何草草',
'筑城潼关道',
'大城铁不如',
'小城万丈馀',
'借问潼关吏',
'修关还备胡',
'要我下马行',
'为我指山隅',
'连云列战格',
'飞鸟不能逾',
'胡来但自守',
'岂复忧西都',
'丈人视要处',
'窄狭容单车',
'艰难奋长戟',
'万古用一夫',
'哀哉桃林战',
'百万化为鱼',
'请嘱防关将',
'慎勿学哥舒',
],
},
{
title: '石壕吏(陕县有石壕镇)',
body: [
'暮投石壕村',
'有吏夜捉人',
'老翁逾墙走',
'老妇出门看',
'吏呼一何怒',
'妇啼一何苦',
'听妇前致词',
'三男邺城戍',
'一男附书至',
'二男新战死',
'存者且偷生',
'死者长已矣',
'室中更无人',
'惟有乳下孙',
'有孙母未去',
'出入无完裙',
'老妪力虽衰',
'请从吏夜归',
'急应河阳役',
'犹得备晨炊',
'夜久语声绝',
'如闻泣幽咽',
'天明登前途',
'独与老翁别',
],
},
{
title: '新婚别',
body: [
'兔丝附蓬麻',
'引蔓故不长',
'嫁女与征夫',
'不如弃路旁',
'结发为妻子',
'席不暖君床',
'暮婚晨告别',
'无乃太匆忙',
'君行虽不远',
'守边赴河阳',
'妾身未分明',
'何以拜姑嫜',
'父母养我时',
'日夜令我藏',
'生女有所归',
'鸡狗亦得将',
'君今往死地',
'沈痛迫中肠',
'誓欲随君去',
'形势反苍黄',
'勿为新婚念',
'努力事戎行',
'妇人在军中',
'兵气恐不扬',
'自嗟贫家女',
'久致罗襦裳',
'罗襦不复施',
'对君洗红妆',
'仰视百鸟飞',
'大小必双翔',
'人事多错迕',
'与君永相望',
],
},
{
title: '垂老别',
body: [
'四郊未宁静',
'垂老不得安',
'子孙阵亡尽',
'焉用身独完',
'投杖出门去',
'同行为辛酸',
'幸有牙齿存',
'所悲骨髓干',
'男儿既介胄',
'长揖别上官',
'老妻卧路啼',
'岁暮衣裳单',
'孰知是死别',
'且复伤其寒',
'此去必不归',
'还闻劝加餐',
'土门壁甚坚',
'杏园度亦难',
'势异邺城下',
'纵死时犹宽',
'人生有离合',
'岂择衰老端',
'忆昔少壮日',
'迟回竟长叹',
'万国尽征戍',
'烽火被冈峦',
'积尸草木腥',
'流血川原丹',
'何乡为乐土',
'安敢尚盘桓',
'弃绝蓬室居',
'塌然摧肺肝',
],
},
{
title: '无家别',
body: [
'寂寞天宝后',
'园庐但蒿藜',
'我里百馀家',
'世乱各东西',
'存者无消息',
'死者为尘泥',
'贱子因阵败',
'归来寻旧蹊',
'人行见空巷',
'日瘦气惨凄',
'但对狐与狸',
'竖毛怒我啼',
'四邻何所有',
'一二老寡妻',
'宿鸟恋本枝',
'安辞且穷栖',
'方春独荷锄',
'日暮还灌畦',
'县吏知我至',
'召令习鼓鞞',
'虽从本州役',
'内顾无所携',
'近行止一身',
'远去终转迷',
'家乡既荡尽',
'远近理亦齐',
'永痛长病母',
'五年委沟谿',
'生我不得力',
'终身两酸嘶',
'人生无家别',
'何以为烝黎',
],
},
{
title: '夏日叹',
body: [
'夏日出东北',
'陵天经中街',
'朱光彻厚地',
'郁蒸何由开',
'上苍久无雷',
'无乃号令乖',
'雨降不濡物',
'良田起黄埃',
'飞鸟苦热死',
'池鱼涸其泥',
'万人尚流冗',
'举目唯蒿莱',
'至今大河北',
'化作虎与豺',
'浩荡想幽蓟',
'王师安在哉',
'对食不能餐',
'我心殊未谐',
'眇然贞观初',
'难与数子偕',
],
},
{
title: '夏夜叹',
body: [
'永日不可暮',
'炎蒸毒我肠',
'安得万里风',
'飘飖吹我裳',
'昊天出华月',
'茂林延疏光',
'仲夏苦夜短',
'开轩纳微凉',
'虚明见纤毫',
'羽虫亦飞扬',
'物情无巨细',
'自适固其常',
'念彼荷戈士',
'穷年守边疆',
'何由一洗濯',
'执热互相望',
'竟夕击刁斗',
'喧声连万方',
'青紫虽被体',
'不如早还乡',
'北城悲笳发',
'鹳鹤号且翔',
'况复烦促倦',
'激烈思时康',
],
},
{
title: '立秋后题',
body: [
'日月不相饶',
'节序昨夜隔',
'玄蝉无停号',
'秋燕已如客',
'平生独往愿',
'惆怅年半百',
'罢官亦由人',
'何事拘形役',
],
},
{
title: '贻阮隐居',
body: [
'陈留风俗衰',
'人物世不数',
'塞上得阮生',
'迥继先父祖',
'贫知静者性',
'自益毛发古',
'车马入邻家',
'蓬蒿翳环堵',
'清诗近道要',
'识子用心苦',
'寻我草径微',
'褰裳蹋寒雨',
'更议居远村',
'避喧甘猛虎',
'足明箕颍客',
'荣贵如粪土',
],
},
{
title: '遣兴三首',
body: [
'下马古战场',
'四顾但茫然',
'风悲浮云去',
'黄叶坠我前',
'朽骨穴蝼蚁',
'又为蔓草缠',
'故老行叹息',
'今人尚开边',
'汉虏互胜负',
'封疆不常全',
'安得廉耻将',
'三军同晏眠',
'高秋登塞山',
'南望马邑州',
'降虏东击胡',
'壮健尽不留',
'穹庐莽牢落',
'上有行云愁',
'老弱哭道路',
'愿闻甲兵休',
'邺中事反覆',
'死人积如丘',
'诸将已茅土',
'载驱谁与谋',
'丰年孰云迟',
'甘泽不在早',
'耕田秋雨足',
'禾黍已映道',
'春苗九月交',
'颜色同日老',
'劝汝衡门士',
'忽悲尚枯槁',
'时来展材力',
'先后无丑好',
'但讶鹿皮翁',
'忘机对芳草',
],
},
{
title: '昔游',
body: [
'昔谒华盖君',
'深求洞宫脚',
'玉棺已上天',
'白日亦寂寞',
'暮升艮岑顶',
'巾几犹未却',
'弟子四五人',
'入来泪俱落',
'余时游名山',
'发轫在远壑',
'良觌违夙愿',
'含凄向寥廓',
'林昏罢幽磬',
'竟夜伏石阁',
'王乔下天坛',
'微月映皓鹤',
'晨溪向虚駃',
'归径行已昨',
'岂辞青鞋胝',
'怅望金匕药',
'东蒙赴旧隐',
'尚忆同志乐',
'休事董先生',
'于今独萧索',
'胡为客关塞',
'道意久衰薄',
'妻子亦何人',
'丹砂负前诺',
'虽悲鬒发变',
'未忧筋力弱',
'扶藜望清秋',
'有兴入庐霍',
],
},
{
title: '幽人',
body: [
'孤云亦群游',
'神物有所归',
'麟凤在赤霄',
'何当一来仪',
'往与惠荀辈',
'中年沧洲期',
'天高无消息',
'弃我忽若遗',
'内惧非道流',
'幽人见瑕疵',
'洪涛隐语笑',
'鼓枻蓬莱池',
'崔嵬扶桑日',
'照耀珊瑚枝',
'风帆倚翠盖',
'暮把东皇衣',
'咽漱元和津',
'所思烟霞微',
'知名未足称',
'局促商山芝',
'五湖复浩荡',
'岁暮有馀悲',
],
},
{
title: '佳人',
body: [
'绝代有佳人',
'幽居在空谷',
'自云良家子',
'零落依草木',
'关中昔丧败',
'兄弟遭杀戮',
'官高何足论',
'不得收骨肉',
'世情恶衰歇',
'万事随转烛',
'夫婿轻薄儿',
'新人已如玉',
'合昏尚知时',
'鸳鸯不独宿',
'但见新人笑',
'那闻旧人哭',
'在山泉水清',
'出山泉水浊',
'侍婢卖珠回',
'牵萝补茅屋',
'摘花不插发',
'采柏动盈掬',
'天寒翠袖薄',
'日暮倚修竹',
],
},
{
title: '赤谷西崦人家',
body: [
'跻险不自喧',
'出郊已清目',
'溪回日气暖',
'径转山田熟',
'鸟雀依茅茨',
'藩篱带松菊',
'如行武陵暮',
'欲问桃花宿',
],
},
{
title: '西枝村寻置草堂地,夜宿赞公土室二首',
body: [
'出郭眄细岑',
'披榛得微路',
'溪行一流水',
'曲折方屡渡',
'赞公汤休徒',
'好静心迹素',
'昨枉霞上作',
'盛论岩中趣',
'怡然共携手',
'恣意同远步',
'扪萝涩先登',
'陟巘眩反顾',
'要求阳冈暖',
'苦陟阴岭沍',
'惆怅老大藤',
'沈吟屈蟠树',
'卜居意未展',
'杖策回且暮',
'层巅馀落日',
'早蔓已多露',
'天寒鸟已归',
'月出人更静',
'土室延白光',
'松门耿疏影',
'跻攀倦日短',
'语乐寄夜永',
'明燃林中薪',
'暗汲石底井',
'大师京国旧',
'德业天机秉',
'从来支许游',
'兴趣江湖迥',
'数奇谪关塞',
'道广存箕颍',
'何知戎马间',
'复接尘事屏',
'幽寻岂一路',
'远色有诸岭',
'晨光稍曚曨',
'更越西南顶',
],
},
{
title: '寄赞上人',
body: [
'一昨陪锡杖',
'卜邻南山幽',
'年侵腰脚衰',
'未便阴崖秋',
'重冈北面起',
'竟日阳光留',
'茅屋买兼土',
'斯焉心所求',
'近闻西枝西',
'有谷杉黍稠',
'亭午颇和暖',
'石田又足收',
'当期塞雨干',
'宿昔齿疾瘳',
'裴回虎穴上',
'面势龙泓头',
'柴荆具茶茗',
'径路通林丘',
'与子成二老',
'来往亦风流',
],
},
{
title: '太平寺泉眼',
body: [
'招提凭高冈',
'疏散连草莽',
'出泉枯柳根',
'汲引岁月古',
'石间见海眼',
'天畔萦水府',
'广深丈尺间',
'宴息敢轻侮',
'青白二小蛇',
'幽姿可时睹',
'如丝气或上',
'烂熳为云雨',
'山头到山下',
'凿井不尽土',
'取供十方僧',
'香美胜牛乳',
'北风起寒文',
'弱藻舒翠缕',
'明涵客衣净',
'细荡林影趣',
'何当宅下流',
'馀润通药圃',
'三春湿黄精',
'一食生毛羽',
],
},
{
title: '梦李白二首',
body: [
'死别已吞声',
'生别常恻恻',
'江南瘴疠地',
'逐客无消息',
'故人入我梦',
'明我长相忆',
'恐非平生魂',
'路远不可测',
'魂来枫叶青',
'魂返关塞黑',
'君今在罗网',
'何以有羽翼',
'落月满屋梁',
'犹疑照颜色',
'水深波浪阔',
'无使皎龙得',
'浮云终日行',
'游子久不至',
'三夜频梦君',
'情亲见君意',
'告归常局促',
'苦道来不易',
'江湖多风波',
'舟楫恐失坠',
'出门搔白首',
'若负平生志',
'冠盖满京华',
'斯人独憔悴',
'孰云网恢恢',
'将老身反累',
'千秋万岁名',
'寂寞身后事',
],
},
{
title: '有怀台州郑十八司户(虔)',
body: [
'天台隔三江',
'风浪无晨暮',
'郑公纵得归',
'老病不识路',
'昔如水上鸥',
'今如罝中兔',
'性命由他人',
'悲辛但狂顾',
'山鬼独一脚',
'蝮蛇长如树',
'呼号傍孤城',
'岁月谁与度',
'从来御魑魅',
'多为才名误',
'夫子嵇阮流',
'更被时俗恶',
'海隅微小吏',
'眼暗发垂素',
'黄帽映青袍',
'非供折腰具',
'平生一杯酒',
'见我故人遇',
'相望无所成',
'乾坤莽回互',
],
},
{
title: '遣兴五首',
body: [
'蛰龙三冬卧',
'老鹤万里心',
'昔时贤俊人',
'未遇犹视今',
'嵇康不得死',
'孔明有知音',
'又如垄底松',
'用舍在所寻',
'大哉霜雪干',
'岁久为枯林',
'昔者庞德公',
'未曾入州府',
'襄阳耆旧间',
'处士节独苦',
'岂无济时策',
'终竟畏罗罟',
'林茂鸟有归',
'水深鱼知聚',
'举家依鹿门',
'刘表焉得取',
'我今日夜忧',
'诸弟各异方',
'不知死与生',
'何况道路长',
'避寇一分散',
'饥寒永相望',
'岂无柴门归',
'欲出畏虎狼',
'仰看云中雁',
'禽鸟亦有行',
'蓬生非无根',
'漂荡随高风',
'天寒落万里',
'不复归本丛',
'客子念故宅',
'三年门巷空',
'怅望但烽火',
'戎车满关东',
'生涯能几何',
'常在羁旅中',
'昔在洛阳时',
'亲友相追攀',
'送客东郊道',
'遨游宿南山',
'烟尘阻长河',
'树羽成皋间',
'回首载酒地',
'岂无一日还',
'丈夫贵壮健',
'惨戚非朱颜',
],
},
{
title: '遣兴五首',
body: [
'朔风飘胡雁',
'惨澹带砂砾',
'长林何萧萧',
'秋草萋更碧',
'北里富熏天',
'高楼夜吹笛',
'焉知南邻客',
'九月犹絺绤',
'长陵锐头儿',
'出猎待明发',
'騂弓金爪镝',
'白马蹴微雪',
'未知所驰逐',
'但见暮光灭',
'归来悬两狼',
'门户有旌节',
'漆有用而割',
'膏以明自煎',
'兰摧白露下',
'桂折秋风前',
'府中罗旧尹',
'沙道尚依然',
'赫赫萧京兆',
'今为时所怜',
'猛虎凭其威',
'往往遭急缚',
'雷吼徒咆哮',
'枝撑已在脚',
'忽看皮寝处',
'无复睛闪烁',
'人有甚于斯',
'足以劝元恶',
'朝逢富家葬',
'前后皆辉光',
'共指亲戚大',
'缌麻百夫行',
'送者各有死',
'不须羡其强',
'君看束练去',
'亦得归山冈',
],
},
{
title: '遣兴五首',
body: [
'天用莫如龙',
'有时系扶桑',
'顿辔海徒涌',
'神人身更长',
'性命苟不存',
'英雄徒自强',
'吞声勿复道',
'真宰意茫茫',
'地用莫如马',
'无良复谁记',
'此日千里鸣',
'追风可君意',
'君看渥洼种',
'态与驽骀异',
'不杂蹄啮间',
'逍遥有能事',
'陶潜避俗翁',
'未必能达道',
'观其著诗集',
'颇亦恨枯槁',
'达生岂是足',
'默识盖不早',
'有子贤与愚',
'何其挂怀抱',
'贺公雅吴语',
'在位常清狂',
'上疏乞骸骨',
'黄冠归故乡',
'爽气不可致',
'斯人今则亡',
'山阴一茅宇',
'江海日凄凉',
'吾怜孟浩然',
'裋褐即长夜',
'赋诗何必多',
'往往凌鲍谢',
'清江空旧鱼',
'春雨馀甘蔗',
'每望东南云',
'令人几悲吒',
],
},
{
title: '前出塞九首',
body: [
'戚戚去故里',
'悠悠赴交河',
'公家有程期',
'亡命婴祸罗',
'君已富土境',
'开边一何多',
'弃绝父母恩',
'吞声行负戈',
'出门日已远',
'不受徒旅欺',
'骨肉恩岂断',
'男儿死无时',
'走马脱辔头',
'手中挑青丝',
'捷下万仞冈',
'俯身试搴旗',
'磨刀呜咽水',
'水赤刃伤手',
'欲轻肠断声',
'心绪乱已久',
'丈夫誓许国',
'愤惋复何有',
'功名图骐驎',
'战骨当速朽',
'送徒既有长',
'远戍亦有身',
'生死向前去',
'不劳吏怒嗔',
'路逢相识人',
'附书与六亲',
'哀哉两决绝',
'不复同苦辛',
'迢迢万馀里',
'领我赴三军',
'军中异苦乐',
'主将宁尽闻',
'隔河见胡骑',
'倏忽数百群',
'我始为奴仆',
'几时树功勋',
'挽弓当挽强',
'用箭当用长',
'射人先射马',
'擒贼先擒王',
'杀人亦有限',
'列国自有疆',
'苟能制侵陵',
'岂在多杀伤',
'驱马天雨雪',
'军行入高山',
'径危抱寒石',
'指落曾冰间',
'已去汉月远',
'何时筑城还',
'浮云暮南征',
'可望不可攀',
'单于寇我垒',
'百里风尘昏',
'雄剑四五动',
'彼军为我奔',
'虏其名王归',
'系颈授辕门',
'潜身备行列',
'一胜何足论',
'从军十年馀',
'能无分寸功',
'众人贵苟得',
'欲语羞雷同',
'中原有斗争',
'况在狄与戎',
'丈夫四方志',
'安可辞固穷',
],
},
{
title: '后出塞五首',
body: [
'男儿生世间',
'及壮当封侯',
'战伐有功业',
'焉能守旧丘',
'召募赴蓟门',
'军动不可留',
'千金买马鞭',
'百金装刀头',
'闾里送我行',
'亲戚拥道周',
'斑白居上列',
'酒酣进庶羞',
'少年别有赠',
'含笑看吴钩',
'朝进东门营',
'暮上河阳桥',
'落日照大旗',
'马鸣风萧萧',
'平沙列万幕',
'部伍各见招',
'中天悬明月',
'令严夜寂寥',
'悲笳数声动',
'壮士惨不骄',
'借问大将谁',
'恐是霍嫖姚',
'古人重守边',
'今人重高勋',
'岂知英雄主',
'出师亘长云',
'六合已一家',
'四夷且孤军',
'遂使貔虎士',
'奋身勇所闻',
'拔剑击大荒',
'日收胡马群',
'誓开玄冥北',
'持以奉吾君',
'献凯日继踵',
'两蕃静无虞',
'渔阳豪侠地',
'击鼓吹笙竽',
'云帆转辽海',
'粳稻来东吴',
'越罗与楚练',
'照耀舆台躯',
'主将位益崇',
'气骄凌上都',
'边人不敢议',
'议者死路衢',
'我本良家子',
'出师亦多门',
'将骄益愁思',
'身贵不足论',
'跃马二十年',
'恐辜明主恩',
'坐见幽州骑',
'长驱河洛昏',
'中夜间道归',
'故里但空村',
'恶名幸脱免',
'穷老无儿孙',
],
},
{
title: '别赞上人',
body: [
'百川日东流',
'客去亦不息',
'我生苦漂荡',
'何时有终极',
'赞公释门老',
'放逐来上国',
'还为世尘婴',
'颇带憔悴色',
'杨枝晨在手',
'豆子雨已熟',
'是身如浮云',
'安可限南北',
'异县逢旧友',
'初忻写胸臆',
'天长关塞寒',
'岁暮饥冻逼',
'野风吹征衣',
'欲别向曛黑',
'马嘶思故枥',
'归鸟尽敛翼',
'古来聚散地',
'宿昔长荆棘',
'相看俱衰年',
'出处各努力',
],
},
{
title: '万丈潭',
body: [
'青溪合冥莫',
'神物有显晦',
'龙依积水蟠',
'窟压万丈内',
'跼步凌垠堮',
'侧身下烟霭',
'前临洪涛宽',
'却立苍石大',
'山色一径尽',
'崖绝两壁对',
'削成根虚无',
'倒影垂澹瀩',
'黑如湾澴底',
'清见光炯碎',
'孤云倒来深',
'飞鸟不在外',
'高萝成帷幄',
'寒木累旌旆',
'远川曲通流',
'嵌窦潜泄濑',
'造幽无人境',
'发兴自我辈',
'告归遗恨多',
'将老斯游最',
'闭藏修鳞蛰',
'出入巨石碍',
'何事暑天过',
'快意风雨会',
],
},
{
title: '两当县吴十侍御江上宅',
body: [
'寒城朝烟澹',
'山谷落叶赤',
'阴风千里来',
'吹汝江上宅',
'鹍鸡号枉渚',
'日色傍阡陌',
'借问持斧翁',
'几年长沙客',
'哀哀失木狖',
'矫矫避弓翮',
'亦知故乡乐',
'未敢思夙昔',
'昔在凤翔都',
'共通金闺籍',
'天子犹蒙尘',
'东郊暗长戟',
'兵家忌间谍',
'此辈常接迹',
'台中领举劾',
'君必慎剖析',
'不忍杀无辜',
'所以分白黑',
'上官权许与',
'失意见迁斥',
'仲尼甘旅人',
'向子识损益',
'朝廷非不知',
'闭口休叹息',
'余时忝诤臣',
'丹陛实咫尺',
'相看受狼狈',
'至死难塞责',
'行迈心多违',
'出门无与适',
'于公负明义',
'惆怅头更白',
],
},
{
title: '发秦州(乾元二年自秦州赴同谷县纪行)',
body: [
'我衰更懒拙',
'生事不自谋',
'无食问乐土',
'无衣思南州',
'汉源十月交',
'天气凉如秋',
'草木未黄落',
'况闻山水幽',
'栗亭名更佳',
'下有良田畴',
'充肠多薯蓣',
'崖蜜亦易求',
'密竹复冬笋',
'清池可方舟',
'虽伤旅寓远',
'庶遂平生游',
'此邦俯要冲',
'实恐人事稠',
'应接非本性',
'登临未销忧',
'谿谷无异石',
'塞田始微收',
'岂复慰老夫',
'惘然难久留',
'日色隐孤戍',
'乌啼满城头',
'中宵驱车去',
'饮马寒塘流',
'磊落星月高',
'苍茫云雾浮',
'大哉乾坤内',
'吾道长悠悠',
],
},
{
title: '赤谷',
body: [
'天寒霜雪繁',
'游子有所之',
'岂但岁月暮',
'重来未有期',
'晨发赤谷亭',
'险艰方自兹',
'乱石无改辙',
'我车已载脂',
'山深苦多风',
'落日童稚饥',
'悄然村墟迥',
'烟火何由追',
'贫病转零落',
'故乡不可思',
'常恐死道路',
'永为高人嗤',
],
},
{
title: '铁堂峡(铁堂山在天水县东五里,峡有铁堂庄)',
body: [
'山风吹游子',
'缥缈乘险绝',
'峡形藏堂隍',
'壁色立积铁',
'径摩穹苍蟠',
'石与厚地裂',
'修纤无垠竹',
'嵌空太始雪',
'威迟哀壑底',
'徒旅惨不悦',
'水寒长冰横',
'我马骨正折',
'生涯抵弧矢',
'盗贼殊未灭',
'飘蓬逾三年',
'回首肝肺热',
],
},
{
title: '盐井(盐井在成州长道县,有盐官故城)',
body: [
'卤中草木白',
'青者官盐烟',
'官作既有程',
'煮盐烟在川',
'汲井岁榾榾',
'出车日连连',
'自公斗三百',
'转致斛六千',
'君子慎止足',
'小人苦喧阗',
'我何良叹嗟',
'物理固自然',
],
},
{
title: '寒硖',
body: [
'行迈日悄悄',
'山谷势多端',
'云门转绝岸',
'积阻霾天寒',
'寒硖不可度',
'我实衣裳单',
'况当仲冬交',
'溯沿增波澜',
'野人寻烟语',
'行子傍水餐',
'此生免荷殳',
'未敢辞路难',
],
},
{
title: '法镜寺',
body: [
'身危适他州',
'勉强终劳苦',
'神伤山行深',
'愁破崖寺古',
'婵娟碧鲜净',
'萧摵寒箨聚',
'回回山根水',
'冉冉松上雨',
'泄云蒙清晨',
'初日翳复吐',
'朱甍半光炯',
'户牖粲可数',
'拄策忘前期',
'出萝已亭午',
'冥冥子规叫',
'微径不复取',
],
},
{
title: '青阳峡',
body: [
'塞外苦厌山',
'南行道弥恶',
'冈峦相经亘',
'云水气参错',
'林迥硖角来',
'天窄壁面削',
'溪西五里石',
'奋怒向我落',
'仰看日车侧',
'俯恐坤轴弱',
'魑魅啸有风',
'霜霰浩漠漠',
'昨忆逾陇坂',
'高秋视吴岳',
'东笑莲华卑',
'北知崆峒薄',
'超然侔壮观',
'已谓殷寥廓',
'突兀犹趁人',
'及兹叹冥莫',
],
},
{
title: '龙门镇(龙门镇在成县东后改府城镇)',
body: [
'细泉兼轻冰',
'沮洳栈道湿',
'不辞辛苦行',
'迫此短景急',
'石门雪云隘',
'古镇峰峦集',
'旌竿暮惨澹',
'风水白刃涩',
'胡马屯成皋',
'防虞此何及',
'嗟尔远戍人',
'山寒夜中泣',
],
},
{
title: '石龛',
body: [
'熊罴哮我东',
'虎豹号我西',
'我后鬼长啸',
'我前狨又啼',
'天寒昏无日',
'山远道路迷',
'驱车石龛下',
'仲冬见虹霓',
'伐竹者谁子',
'悲歌上云梯',
'为官采美箭',
'五岁供梁齐',
'苦云直簳尽',
'无以充提携',
'奈何渔阳骑',
'飒飒惊烝黎',
],
},
{
title: '积草岭(同谷县界)',
body: [
'连峰积长阴',
'白日递隐见',
'飕飕林响交',
'惨惨石状变',
'山分积草岭',
'路异明水县',
'旅泊吾道穷',
'衰年岁时倦',
'卜居尚百里',
'休驾投诸彦',
'邑有佳主人',
'情如已会面',
'来书语绝妙',
'远客惊深眷',
'食蕨不愿馀',
'茅茨眼中见',
],
},
{
title: '泥功山(贞元五年于同谷西境泥公山权置行成州)',
body: [
'朝行青泥上',
'暮在青泥中',
'泥泞非一时',
'版筑劳人功',
'不畏道途永',
'乃将汩没同',
'白马为铁骊',
'小儿成老翁',
'哀猿透却坠',
'死鹿力所穷',
'寄语北来人',
'后来莫匆匆',
],
},
{
title: '凤凰台',
body: [
'亭亭凤凰台',
'北对西康州',
'西伯今寂寞',
'凤声亦悠悠',
'山峻路绝踪',
'石林气高浮',
'安得万丈梯',
'为君上上头',
'恐有无母雏',
'饥寒日啾啾',
'我能剖心出',
'饮啄慰孤愁',
'心以当竹实',
'炯然无外求',
'血以当醴泉',
'岂徒比清流',
'所贵王者瑞',
'敢辞微命休',
'坐看彩翮长',
'举意八极周',
'自天衔瑞图',
'飞下十二楼',
'图以奉至尊',
'凤以垂鸿猷',
'再光中兴业',
'一洗苍生忧',
'深衷正为此',
'群盗何淹留',
],
},
{
title: '乾元中寓居同谷县,作歌七首',
body: [
'有客有客字子美',
'白头乱发垂过耳',
'岁拾橡栗随狙公',
'天寒日暮山谷里',
'中原无书归不得',
'手脚冻皴皮肉死',
'呜呼一歌兮歌已哀',
'悲风为我从天来',
'长镵长镵白木柄',
'我生托子以为命',
'黄精无苗山雪盛',
'短衣数挽不掩胫',
'此时与子空归来',
'男呻女吟四壁静',
'呜呼二歌兮歌始放',
'邻里为我色惆怅',
'有弟有弟在远方',
'三人各瘦何人强',
'生别展转不相见',
'胡尘暗天道路长',
'东飞鴐鹅后鹙鶬',
'安得送我置汝旁',
'呜呼三歌兮歌三发',
'汝归何处收兄骨',
'有妹有妹在钟离',
'良人早殁诸孤痴',
'长淮浪高蛟龙怒',
'十年不见来何时',
'扁舟欲往箭满眼',
'杳杳南国多旌旗',
'呜呼四歌兮歌四奏',
'林猿为我啼清昼',
'四山多风溪水急',
'寒雨飒飒枯树湿',
'黄蒿古城云不开',
'白狐跳梁黄狐立',
'我生何为在穷谷',
'中夜起坐万感集',
'呜呼五歌兮歌正长',
'魂招不来归故乡',
'南有龙兮在山湫',
'古木巃嵸枝相樛',
'木叶黄落龙正蛰',
'蝮蛇东来水上游',
'我行怪此安敢出',
'拔剑欲斩且复休',
'呜呼六歌兮歌思迟',
'溪壑为我回春姿',
'男儿生不成名身已老',
'三年饥走荒山道',
'长安卿相多少年',
'富贵应须致身早',
'山中儒生旧相识',
'但话宿昔伤怀抱',
'呜呼七歌兮悄终曲',
'仰视皇天白日速',
],
},
{
title: '发同谷县(乾元二年十二月一日自陇右赴剑南纪行)',
body: [
'贤有不黔突',
'圣有不暖席',
'况我饥愚人',
'焉能尚安宅',
'始来兹山中',
'休驾喜地僻',
'奈何迫物累',
'一岁四行役',
'忡忡去绝境',
'杳杳更远适',
'停骖龙潭云',
'回首白崖石',
'临岐别数子',
'握手泪再滴',
'交情无旧深',
'穷老多惨戚',
'平生懒拙意',
'偶值栖遁迹',
'去住与愿违',
'仰惭林间翮',
],
},
{
title: '木皮岭',
body: [
'首路栗亭西',
'尚想凤凰村',
'季冬携童稚',
'辛苦赴蜀门',
'南登木皮岭',
'艰险不易论',
'汗流被我体',
'祁寒为之暄',
'远岫争辅佐',
'千岩自崩奔',
'始知五岳外',
'别有他山尊',
'仰干塞大明',
'俯入裂厚坤',
'再闻虎豹斗',
'屡跼风水昏',
'高有废阁道',
'摧折如短辕',
'下有冬青林',
'石上走长根',
'西崖特秀发',
'焕若灵芝繁',
'润聚金碧气',
'清无沙土痕',
'忆观昆仑图',
'目击悬圃存',
'对此欲何适',
'默伤垂老魂',
],
},
{
title: '白沙渡(属剑州)',
body: [
'畏途随长江',
'渡口下绝岸',
'差池上舟楫',
'杳窕入云汉',
'天寒荒野外',
'日暮中流半',
'我马向北嘶',
'山猿饮相唤',
'水清石礧礧',
'沙白滩漫漫',
'迥然洗愁辛',
'多病一疏散',
'高壁抵嶔崟',
'洪涛越凌乱',
'临风独回首',
'揽辔复三叹',
],
},
{
title: '水会渡',
body: [
'山行有常程',
'中夜尚未安',
'微月没已久',
'崖倾路何难',
'大江动我前',
'汹若溟渤宽',
'篙师暗理楫',
'歌笑轻波澜',
'霜浓木石滑',
'风急手足寒',
'入舟已千忧',
'陟巘仍万盘',
'迥眺积水外',
'始知众星乾',
'远游令人瘦',
'衰疾惭加餐',
],
},
{
title: '飞仙阁',
body: [
'土门山行窄',
'微径缘秋毫',
'栈云阑干峻',
'梯石结构牢',
'万壑欹疏林',
'积阴带奔涛',
'寒日外澹泊',
'长风中怒号',
'歇鞍在地底',
'始觉所历高',
'往来杂坐卧',
'人马同疲劳',
'浮生有定分',
'饥饱岂可逃',
'叹息谓妻子',
'我何随汝曹',
],
},
{
title: '五盘(七盘岭在广元县北一名五盘栈道盘曲有五重)',
body: [
'五盘虽云险',
'山色佳有馀',
'仰凌栈道细',
'俯映江木疏',
'地僻无网罟',
'水清反多鱼',
'好鸟不妄飞',
'野人半巢居',
'喜见淳朴俗',
'坦然心神舒',
'东郊尚格斗',
'巨猾何时除',
'故乡有弟妹',
'流落随丘墟',
'成都万事好',
'岂若归吾庐',
],
},
{
title: '龙门阁',
body: [
'清江下龙门',
'绝壁无尺土',
'长风驾高浪',
'浩浩自太古',
'危途中萦盘',
'仰望垂线缕',
'滑石欹谁凿',
'浮梁袅相拄',
'目眩陨杂花',
'头风吹过雨',
'百年不敢料',
'一坠那得取',
'饱闻经瞿塘',
'足见度大庾',
'终身历艰险',
'恐惧从此数',
],
},
{
title: '石柜阁',
body: [
'季冬日已长',
'山晚半天赤',
'蜀道多早花',
'江间饶奇石',
'石柜曾波上',
'临虚荡高壁',
'清晖回群鸥',
'暝色带远客',
'羁栖负幽意',
'感叹向绝迹',
'信甘孱懦婴',
'不独冻馁迫',
'优游谢康乐',
'放浪陶彭泽',
'吾衰未自安',
'谢尔性所适',
],
},
{
title: '桔柏渡(在昭化县)',
body: [
'青冥寒江渡',
'驾竹为长桥',
'竿湿烟漠漠',
'江永风萧萧',
'连笮动袅娜',
'征衣飒飘飖',
'急流鸨鹢散',
'绝岸鼋鼍骄',
'西辕自兹异',
'东逝不可要',
'高通荆门路',
'阔会沧海潮',
'孤光隐顾眄',
'游子怅寂寥',
'无以洗心胸',
'前登但山椒',
],
},
{
title: '剑门',
body: [
'惟天有设险',
'剑门天下壮',
'连山抱西南',
'石角皆北向',
'两崖崇墉倚',
'刻画城郭状',
'一夫怒临关',
'百万未可傍',
'珠玉走中原',
'岷峨气凄怆',
'三皇五帝前',
'鸡犬各相放',
'后王尚柔远',
'职贡道已丧',
'至今英雄人',
'高视见霸王',
'并吞与割据',
'极力不相让',
'吾将罪真宰',
'意欲铲叠嶂',
'恐此复偶然',
'临风默惆怅',
],
},
{
title: '鹿头山(山上有关,在德阳县治北)',
body: [
'鹿头何亭亭',
'是日慰饥渴',
'连山西南断',
'俯见千里豁',
'游子出京华',
'剑门不可越',
'及兹险阻尽',
'始喜原野阔',
'殊方昔三分',
'霸气曾间发',
'天下今一家',
'云端失双阙',
'悠然想扬马',
'继起名硉兀',
'有文令人伤',
'何处埋尔骨',
'纡馀脂膏地',
'惨澹豪侠窟',
'仗钺非老臣',
'宣风岂专达',
'冀公柱石姿',
'论道邦国活',
'斯人亦何幸',
'公镇逾岁月',
],
},
{
title: '成都府',
body: [
'翳翳桑榆日',
'照我征衣裳',
'我行山川异',
'忽在天一方',
'但逢新人民',
'未卜见故乡',
'大江东流去',
'游子去日长',
'曾城填华屋',
'季冬树木苍',
'喧然名都会',
'吹箫间笙簧',
'信美无与适',
'侧身望川梁',
'鸟雀夜各归',
'中原杳茫茫',
'初月出不高',
'众星尚争光',
'自古有羁旅',
'我何苦哀伤',
],
},
{
title: '石笋行',
body: [
'君不见益州城西门',
'陌上石笋双高蹲',
'古来相传是海眼',
'苔藓蚀尽波涛痕',
'雨多往往得瑟瑟',
'此事恍惚难明论',
'恐是昔时卿相墓',
'立石为表今仍存',
'惜哉俗态好蒙蔽',
'亦如小臣媚至尊',
'政化错迕失大体',
'坐看倾危受厚恩',
'嗟尔石笋擅虚名',
'后来未识犹骏奔',
'安得壮士掷天外',
'使人不疑见本根',
],
},
{
title: '石犀行',
body: [
'君不见秦时蜀太守',
'刻石立作三犀牛',
'自古虽有厌胜法',
'天生江水向东流',
'蜀人矜夸一千载',
'泛溢不近张仪楼',
'今年灌口损户口',
'此事或恐为神羞',
'终藉堤防出众力',
'高拥木石当清秋',
'先王作法皆正道',
'鬼怪何得参人谋',
'嗟尔三犀不经济',
'缺讹只与长川逝',
'但见元气常调和',
'自免洪涛恣凋瘵',
'安得壮士提天纲',
'再平水土犀奔茫',
],
},
{
title: '杜鹃行',
body: [
'君不见昔日蜀天子',
'化作杜鹃似老乌',
'寄巢生子不自啄',
'群鸟至今与哺雏',
'虽同君臣有旧礼',
'骨肉满眼身羁孤',
'业工窜伏深树里',
'四月五月偏号呼',
'其声哀痛口流血',
'所诉何事常区区',
'尔岂摧残始发愤',
'羞带羽翮伤形愚',
'苍天变化谁料得',
'万事反覆何所无',
'万事反覆何所无',
'岂忆当殿群臣趋',
],
},
{
title: '赠蜀僧闾丘师兄',
body: [
'大师铜梁秀',
'籍籍名家孙',
'呜呼先博士',
'炳灵精气奔',
'惟昔武皇后',
'临轩御乾坤',
'多士尽儒冠',
'墨客蔼云屯',
'当时上紫殿',
'不独卿相尊',
'世传闾丘笔',
'峻极逾昆仑',
'凤藏丹霄暮',
'龙去白水浑',
'青荧雪岭东',
'碑碣旧制存',
'斯文散都邑',
'高价越玙璠',
'晚看作者意',
'妙绝与谁论',
'吾祖诗冠古',
'同年蒙主恩',
'豫章夹日月',
'岁久空深根',
'小子思疏阔',
'岂能达词门',
'穷愁一挥泪',
'相遇即诸昆',
'我住锦官城',
'兄居祇树园',
'地近慰旅愁',
'往来当丘樊',
'天涯歇滞雨',
'粳稻卧不翻',
'漂然薄游倦',
'始与道侣敦',
'景晏步修廊',
'而无车马喧',
'夜阑接软语',
'落月如金盆',
'漠漠世界黑',
'驱车争夺繁',
'惟有摩尼珠',
'可照浊水源',
],
},
{
title: '泛溪',
body: [
'落景下高堂',
'进舟泛回溪',
'谁谓筑居小',
'未尽乔木西',
'远郊信荒僻',
'秋色有馀凄',
'练练峰上雪',
'纤纤云表霓',
'童戏左右岸',
'罟弋毕提携',
'翻倒荷芰乱',
'指挥径路迷',
'得鱼已割鳞',
'采藕不洗泥',
'人情逐鲜美',
'物贱事已睽',
'吾村霭暝姿',
'异舍鸡亦栖',
'萧条欲何适',
'出处无可齐',
'衣上见新月',
'霜中登故畦',
'浊醪自初熟',
'东城多鼓鼙',
],
},
{
title: '题壁画马歌(一作题壁上韦偃画歌。偃京兆人善画马)',
body: [
'韦侯别我有所适',
'知我怜君画无敌',
'戏拈秃笔扫骅骝',
'欻见骐驎出东壁',
'一匹龁草一匹嘶',
'坐看千里当霜蹄',
'时危安得真致此',
'与人同生亦同死',
],
},
{
title: '戏题画山水图歌(一本题下有王宰二字。宰,蜀人)',
body: [
'十日画一水',
'五日画一石',
'能事不受相促迫',
'王宰始肯留真迹',
'壮哉昆仑方壶图',
'挂君高堂之素壁',
'巴陵洞庭日本东',
'赤岸水与银河通',
'中有云气随飞龙',
'舟人渔子入浦溆',
'山木尽亚洪涛风',
'尤工远势古莫比',
'咫尺应须论万里',
'焉得并州快剪刀',
'翦取吴松半江水',
],
},
{
title: '题李尊师松树障子歌',
body: [
'老夫清晨梳白头',
'玄都道士来相访',
'握发呼儿延入户',
'手提新画青松障',
'障子松林静杳冥',
'凭轩忽若无丹青',
'阴崖却承霜雪干',
'偃盖反走虬龙形',
'老夫平生好奇古',
'对此兴与精灵聚',
'已知仙客意相亲',
'更觉良工心独苦',
'松下丈人巾屦同',
'偶坐似是商山翁',
'怅望聊歌紫芝曲',
'时危惨澹来悲风',
],
},
{
title: '戏为双松图歌(韦偃画)',
body: [
'天下几人画古松',
'毕宏已老韦偃少',
'绝笔长风起纤末',
'满堂动色嗟神妙',
'两株惨裂苔藓皮',
'屈铁交错回高枝',
'白摧朽骨龙虎死',
'黑入太阴雷雨垂',
'松根胡僧憩寂寞',
'庞眉皓首无住著',
'偏袒右肩露双脚',
'叶里松子僧前落',
'韦侯韦侯数相见',
'我有一匹好东绢',
'重之不减锦绣段',
'已令拂拭光凌乱',
'请公放笔为直干',
],
},
{
title: '投简成、华两县诸子',
body: [
'赤县官曹拥材杰',
'软裘快马当冰雪',
'长安苦寒谁独悲',
'杜陵野老骨欲折',
'南山豆苗早荒秽',
'青门瓜地新冻裂',
'乡里儿童项领成',
'朝廷故旧礼数绝',
'自然弃掷与时异',
'况乃疏顽临事拙',
'饥卧动即向一旬',
'敝裘何啻联百结',
'君不见空墙日色晚',
'此老无声泪垂血',
],
},
{
title: '徐卿二子歌',
body: [
'君不见徐卿二子生绝奇',
'感应吉梦相追随',
'孔子释氏亲抱送',
'并是天上麒麟儿',
'大儿九龄色清澈',
'秋水为神玉为骨',
'小儿五岁气食牛',
'满堂宾客皆回头',
'吾知徐公百不忧',
'积善衮衮生公侯',
'丈夫生儿有如此二雏者',
'名位岂肯卑微休',
],
},
{
title: '病柏',
body: [
'有柏生崇冈',
'童童状车盖',
'偃蹙龙虎姿',
'主当风云会',
'神明依正直',
'故老多再拜',
'岂知千年根',
'中路颜色坏',
'出非不得地',
'蟠据亦高大',
'岁寒忽无凭',
'日夜柯叶改',
'丹凤领九雏',
'哀鸣翔其外',
'鸱鸮志意满',
'养子穿穴内',
'客从何乡来',
'伫立久吁怪',
'静求元精理',
'浩荡难倚赖',
],
},
{
title: '病橘',
body: [
'群橘少生意',
'虽多亦奚为',
'惜哉结实小',
'酸涩如棠梨',
'剖之尽蠹虫',
'采掇爽其宜',
'纷然不适口',
'岂只存其皮',
'萧萧半死叶',
'未忍别故枝',
'玄冬霜雪积',
'况乃回风吹',
'尝闻蓬莱殿',
'罗列潇湘姿',
'此物岁不稔',
'玉食失光辉',
'寇盗尚凭陵',
'当君减膳时',
'汝病是天意',
'吾谂罪有司',
'忆昔南海使',
'奔腾献荔支',
'百马死山谷',
'到今耆旧悲',
],
},
{
title: '枯棕',
body: [
'蜀门多棕榈',
'高者十八九',
'其皮割剥甚',
'虽众亦易朽',
'徒布如云叶',
'青黄岁寒后',
'交横集斧斤',
'凋丧先蒲柳',
'伤时苦军乏',
'一物官尽取',
'嗟尔江汉人',
'生成复何有',
'有同枯棕木',
'使我沈叹久',
'死者即已休',
'生者何自守',
'啾啾黄雀啅',
'侧见寒蓬走',
'念尔形影干',
'摧残没藜莠',
],
},
{
title: '枯楠',
body: [
'楩楠枯峥嵘',
'乡党皆莫记',
'不知几百岁',
'惨惨无生意',
'上枝摩皇天',
'下根蟠厚地',
'巨围雷霆坼',
'万孔虫蚁萃',
'冻雨落流胶',
'冲风夺佳气',
'白鹄遂不来',
'天鸡为愁思',
'犹含栋梁具',
'无复霄汉志',
'良工古昔少',
'识者出涕泪',
'种榆水中央',
'成长何容易',
'截承金露盘',
'袅袅不自畏',
],
},
{
title: '丽春',
body: [
'百草竞春华',
'丽春应最胜',
'少须好颜色',
'多漫枝条剩',
'纷纷桃李枝',
'处处总能移',
'如何贵此重',
'却怕有人知',
],
},
{
title: '丈人山(山在青城县北,黄帝封青城山为五岳丈人)',
body: [
'自为青城客',
'不唾青城地',
'为爱丈人山',
'丹梯近幽意',
'丈人祠西佳气浓',
'缘云拟住最高峰',
'扫除白发黄精在',
'君看他时冰雪容',
],
},
{
title: '百忧集行(王筠诗百忧俱集断人肠)',
body: [
'忆年十五心尚孩',
'健如黄犊走复来',
'庭前八月梨枣熟',
'一日上树能千回',
'即今倏忽已五十',
'坐卧只多少行立',
'强将笑语供主人',
'悲见生涯百忧集',
'入门依旧四壁空',
'老妻睹我颜色同',
'痴儿未知父子礼',
'叫怒索饭啼门东',
],
},
{
title: '戏作花卿歌',
body: [
'成都猛将有花卿',
'学语小儿知姓名',
'用如快鹘风火生',
'见贼唯多身始轻',
'绵州副使著柘黄',
'我卿扫除即日平',
'子章髑髅血模糊',
'手提掷还崔大夫',
'李侯重有此节度',
'人道我卿绝世无',
'既称绝世无',
'天子何不唤取守京都',
],
},
{
title: '入奏行,赠西山检察使窦侍御',
body: [
'窦侍御',
'骥之子',
'凤之雏',
'年未三十忠义俱',
'骨鲠绝代无',
'炯如一段清冰出万壑',
'置在迎风寒露之玉壶',
'蔗浆归厨金碗冻',
'洗涤烦热足以宁君躯',
'政用疏通合典则',
'戚联豪贵耽文儒',
'兵革未息人未苏',
'天子亦念西南隅',
'吐蕃凭陵气颇粗',
'窦氏检察应时须',
'运粮绳桥壮士喜',
'斩木火井穷猿呼',
'八州刺史思一战',
'三城守边却可图',
'此行入奏计未小',
'密奉圣旨恩宜殊',
'绣衣春当霄汉立',
'彩服日向庭闱趋',
'省郎京尹必俯拾',
'江花未落还成都',
'江花未落还成都',
'肯访浣花老翁无',
'为君酤酒满眼酤',
'与奴白饭马青刍',
],
},
{
title: '楠树为风雨所拔叹',
body: [
'倚江楠树草堂前',
'故老相传二百年',
'诛茅卜居总为此',
'五月仿佛闻寒蝉',
'东南飘风动地至',
'江翻石走流云气',
'干排雷雨犹力争',
'根断泉源岂天意',
'沧波老树性所爱',
'浦上童童一青盖',
'野客频留惧雪霜',
'行人不过听竽籁',
'虎倒龙颠委榛棘',
'泪痕血点垂胸臆',
'我有新诗何处吟',
'草堂自此无颜色',
],
},
{
title: '茅屋为秋风所破歌',
body: [
'八月秋高风怒号',
'卷我屋上三重茅',
'茅飞度江洒江郊',
'高者挂罥长林梢',
'下者飘转沉塘坳',
'南村群童欺我老无力',
'忍能对面为盗贼',
'公然抱茅入竹去',
'唇焦口燥呼不得',
'归来倚杖自叹息',
'俄顷风定云墨色',
'秋天漠漠向昏黑',
'布衾多年冷似铁',
'骄儿恶卧踏里裂',
'床床屋漏无干处',
'雨脚如麻未断绝',
'自经丧乱少睡眠',
'长夜沾湿何由彻',
'安得广厦千万间',
'大庇天下寒士俱欢颜',
'风雨不动安如山',
'呜呼何时眼前突兀见此屋',
'吾庐独破受冻死亦足',
],
},
{
title: '大雨',
body: [
'西蜀冬不雪',
'春农尚嗷嗷',
'上天回哀眷',
'朱夏云郁陶',
'执热乃沸鼎',
'纤絺成缊袍',
'风雷飒万里',
'霈泽施蓬蒿',
'敢辞茅苇漏',
'已喜黍豆高',
'三日无行人',
'二江声怒号',
'流恶邑里清',
'矧兹远江皋',
'荒庭步鹳鹤',
'隐几望波涛',
'沉疴聚药饵',
'顿忘所进劳',
'则知润物功',
'可以贷不毛',
'阴色静陇亩',
'劝耕自官曹',
'四邻耒耜出',
'何必吾家操',
],
},
{
title: '溪涨',
body: [
'当时浣花桥',
'溪水才尺馀',
'白石明可把',
'水中有行车',
'秋夏忽泛溢',
'岂惟入吾庐',
'蛟龙亦狼狈',
'况是鳖与鱼',
'兹晨已半落',
'归路跬步疏',
'马嘶未敢动',
'前有深填淤',
'青青屋东麻',
'散乱床上书',
'不意远山雨',
'夜来复何如',
'我游都市间',
'晚憩必村墟',
'乃知久行客',
'终日思其居',
],
},
{
title: '戏赠友二首',
body: [
'元年建巳月',
'郎有焦校书',
'自夸足膂力',
'能骑生马驹',
'一朝被马踏',
'唇裂版齿无',
'壮心不肯已',
'欲得东擒胡',
'元年建巳月',
'官有王司直',
'马惊折左臂',
'骨折面如墨',
'驽骀漫深泥',
'何不避雨色',
'劝君休叹恨',
'未必不为福',
],
},
{
title: '遭田父泥饮美严中丞',
body: [
'步屟随春风',
'村村自花柳',
'田翁逼社日',
'邀我尝春酒',
'酒酣夸新尹',
'畜眼未见有',
'回头指大男',
'渠是弓弩手',
'名在飞骑籍',
'长番岁时久',
'前日放营农',
'辛苦救衰朽',
'差科死则已',
'誓不举家走',
'今年大作社',
'拾遗能住否',
'叫妇开大瓶',
'盆中为吾取',
'感此气扬扬',
'须知风化首',
'语多虽杂乱',
'说尹终在口',
'朝来偶然出',
'自卯将及酉',
'久客惜人情',
'如何拒邻叟',
'高声索果栗',
'欲起时被肘',
'指挥过无礼',
'未觉村野丑',
'月出遮我留',
'仍嗔问升斗',
],
},
{
title: '喜雨',
body: [
'春旱天地昏',
'日色赤如血',
'农事都已休',
'兵戈况骚屑',
'巴人困军须',
'恸哭厚土热',
'沧江夜来雨',
'真宰罪一雪',
'谷根小苏息',
'沴气终不灭',
'何由见宁岁',
'解我忧思结',
'峥嵘群山云',
'交会未断绝',
'安得鞭雷公',
'滂沱洗吴越',
],
},
{
title: '渔阳',
body: [
'渔阳突骑犹精锐',
'赫赫雍王都节制',
'猛将飘然恐后时',
'本朝不入非高计',
'禄山北筑雄武城',
'旧防败走归其营',
'系书请问燕耆旧',
'今日何须十万兵',
],
},
{
title: '天边行',
body: [
'天边老人归未得',
'日暮东临大江哭',
'陇右河源不种田',
'胡骑羌兵入巴蜀',
'洪涛滔天风拔木',
'前飞秃鹙后鸿鹄',
'九度附书向洛阳',
'十年骨肉无消息',
],
},
{
title: '大麦行',
body: [
'大麦干枯小麦黄',
'妇女行泣夫走藏',
'东至集壁西梁洋',
'问谁腰镰胡与羌',
'岂无蜀兵三千人',
'部领辛苦江山长',
'安得如鸟有羽翅',
'托身白云还故乡',
],
},
{
title: '苦战行',
body: [
'苦战身死马将军',
'自云伏波之子孙',
'干戈未定失壮士',
'使我叹恨伤精魂',
'去年江南讨狂贼',
'临江把臂难再得',
'别时孤云今不飞',
'时独看云泪横臆',
],
},
{
title: '去秋行',
body: [
'去秋涪江木落时',
'臂枪走马谁家儿',
'到今不知白骨处',
'部曲有去皆无归',
'遂州城中汉节在',
'遂州城外巴人稀',
'战场冤魂每夜哭',
'空令野营猛士悲',
],
},
{
title: '述古三首',
body: [
'赤骥顿长缨',
'非无万里姿',
'悲鸣泪至地',
'为问驭者谁',
'凤凰从东来',
'何意复高飞',
'竹花不结实',
'念子忍朝饥',
'古时君臣合',
'可以物理推',
'贤人识定分',
'进退固其宜',
'市人日中集',
'于利竞锥刀',
'置膏烈火上',
'哀哀自煎熬',
'农人望岁稔',
'相率除蓬蒿',
'所务谷为本',
'邪赢无乃劳',
'舜举十六相',
'身尊道何高',
'秦时任商鞅',
'法令如牛毛',
'汉光得天下',
'祚永固有开',
'岂惟高祖圣',
'功自萧曹来',
'经纶中兴业',
'何代无长才',
'吾慕寇邓勋',
'济时信良哉',
'耿贾亦宗臣',
'羽翼共裴回',
'休运终四百',
'图画在云台',
],
},
{
title: '观打鱼歌',
body: [
'绵州江水之东津',
'鲂鱼鱍鱍色胜银',
'渔人漾舟沈大网',
'截江一拥数百鳞',
'众鱼常才尽却弃',
'赤鲤腾出如有神',
'潜龙无声老蛟怒',
'回风飒飒吹沙尘',
'饔子左右挥双刀',
'脍飞金盘白雪高',
'徐州秃尾不足忆',
'汉阴槎头远遁逃',
'鲂鱼肥美知第一',
'既饱欢娱亦萧瑟',
'君不见朝来割素鬐',
'咫尺波涛永相失',
],
},
{
title: '又观打鱼',
body: [
'苍江鱼子清晨集',
'设网提纲万鱼急',
'能者操舟疾若风',
'撑突波涛挺叉入',
'小鱼脱漏不可记',
'半死半生犹戢戢',
'大鱼伤损皆垂头',
'屈强泥沙有时立',
'东津观鱼已再来',
'主人罢鲙还倾杯',
'日暮蛟龙改窟穴',
'山根鳣鲔随云雷',
'干戈兵革斗未止',
'凤凰麒麟安在哉',
'吾徒胡为纵此乐',
'暴殄天物圣所哀',
],
},
{
title: '越王楼歌(太宗子越王贞为绵州刺史,作台于州城西北)',
body: [
'绵州州府何磊落',
'显庆年中越王作',
'孤城西北起高楼',
'碧瓦朱甍照城郭',
'楼下长江百丈清',
'山头落日半轮明',
'君王旧迹今人赏',
'转见千秋万古情',
],
},
{
title: '海棕行',
body: [
'左绵公馆清江濆',
'海棕一株高入云',
'龙鳞犀甲相错落',
'苍棱白皮十抱文',
'自是众木乱纷纷',
'海棕焉知身出群',
'移栽北辰不可得',
'时有西域胡僧识',
],
},
{
title: '姜楚公画角鹰歌',
body: [
'楚公画鹰鹰戴角',
'杀气森森到幽朔',
'观者贪愁掣臂飞',
'画师不是无心学',
'此鹰写真在左绵',
'却嗟真骨遂虚传',
'梁间燕雀休惊怕',
'亦未抟空上九天',
],
},
{
title: '相逢歌赠严二别驾(一作严别驾相逢歌)',
body: [
'我行入东川',
'十步一回首',
'成都乱罢气萧飒',
'浣花草堂亦何有',
'梓中豪俊大者谁',
'本州从事知名久',
'把臂开尊饮我酒',
'酒酣击剑蛟龙吼',
'乌帽拂尘青螺粟',
'紫衣将炙绯衣走',
'铜盘烧蜡光吐日',
'夜如何其初促膝',
'黄昏始扣主人门',
'谁谓俄顷胶在漆',
'万事尽付形骸外',
'百年未见欢娱毕',
'神倾意豁真佳士',
'久客多忧今愈疾',
'高视乾坤又可愁',
'一躯交态同悠悠',
'垂老遇君未恨晚',
'似君须向古人求',
],
},
{
title: '光禄坂行',
body: [
'山行落日下绝壁',
'西望千山万山赤',
'树枝有鸟乱鸣时',
'暝色无人独归客',
'马惊不忧深谷坠',
'草动只怕长弓射',
'安得更似开元中',
'道路即今多拥隔',
],
},
{
title: '冬到金华山观,因得故拾遗陈公学堂遗迹',
body: [
'涪右众山内',
'金华紫崔嵬',
'上有蔚蓝天',
'垂光抱琼台',
'系舟接绝壁',
'杖策穷萦回',
'四顾俯层巅',
'澹然川谷开',
'雪岭日色死',
'霜鸿有馀哀',
'焚香玉女跪',
'雾里仙人来',
'陈公读书堂',
'石柱仄青苔',
'悲风为我起',
'激烈伤雄才',
],
},
{
title: '陈拾遗故宅(宅在射洪县东七里东武山下)',
body: [
'拾遗平昔居',
'大屋尚修椽',
'悠扬荒山日',
'惨澹故园烟',
'位下曷足伤',
'所贵者圣贤',
'有才继骚雅',
'哲匠不比肩',
'公生扬马后',
'名与日月悬',
'同游英俊人',
'多秉辅佐权',
'彦昭超玉价',
'郭振起通泉',
'到今素壁滑',
'洒翰银钩连',
'盛事会一时',
'此堂岂千年',
'终古立忠义',
'感遇有遗编',
],
},
{
title: '谒文公上方',
body: [
'野寺隐乔木',
'山僧高下居',
'石门日色异',
'绛气横扶疏',
'窈窕入风磴',
'长芦纷卷舒',
'庭前猛虎卧',
'遂得文公庐',
'俯视万家邑',
'烟尘对阶除',
'吾师雨花外',
'不下十年馀',
'长者自布金',
'禅龛只晏如',
'大珠脱玷翳',
'白月当空虚',
'甫也南北人',
'芜蔓少耘锄',
'久遭诗酒污',
'何事忝簪裾',
'王侯与蝼蚁',
'同尽随丘墟',
'愿闻第一义',
'回向心地初',
'金篦刮眼膜',
'价重百车渠',
'无生有汲引',
'兹理傥吹嘘',
],
},
{
title: '奉赠射洪李四丈(明甫)',
body: [
'丈人屋上乌',
'人好乌亦好',
'人生意气豁',
'不在相逢早',
'南京乱初定',
'所向邑枯槁',
'游子无根株',
'茅斋付秋草',
'东征下月峡',
'挂席穷海岛',
'万里须十金',
'妻孥未相保',
'苍茫风尘际',
'蹭蹬骐驎老',
'志士怀感伤',
'心胸已倾倒',
],
},
{
title: '早发射洪县南途中作',
body: [
'将老忧贫窭',
'筋力岂能及',
'征途乃侵星',
'得使诸病入',
'鄙人寡道气',
'在困无独立',
'俶装逐徒旅',
'达曙凌险涩',
'寒日出雾迟',
'清江转山急',
'仆夫行不进',
'驽马若维絷',
'汀洲稍疏散',
'风景开怏悒',
'空慰所尚怀',
'终非曩游集',
'衰颜偶一破',
'胜事难屡挹',
'茫然阮籍途',
'更洒杨朱泣',
],
},
{
title: '通泉驿南去通泉县十五里山水作',
body: [
'溪行衣自湿',
'亭午气始散',
'冬温蚊蚋在',
'人远凫鸭乱',
'登顿生曾阴',
'欹倾出高岸',
'驿楼衰柳侧',
'县郭轻烟畔',
'一川何绮丽',
'尽目穷壮观',
'山色远寂寞',
'江光夕滋漫',
'伤时愧孔父',
'去国同王粲',
'我生苦飘零',
'所历有嗟叹',
],
},
{
title: '过郭代公故宅',
body: [
'豪俊初未遇',
'其迹或脱略',
'代公尉通泉',
'放意何自若',
'及夫登衮冕',
'直气森喷薄',
'磊落见异人',
'岂伊常情度',
'定策神龙后',
'宫中翕清廓',
'俄顷辨尊亲',
'指挥存顾托',
'群公有惭色',
'王室无削弱',
'迥出名臣上',
'丹青照台阁',
'我行得遗迹',
'池馆皆疏凿',
'壮公临事断',
'顾步涕横落',
'高咏宝剑篇',
'神交付冥漠',
],
},
{
title: '观薛稷少保书画壁',
body: [
'少保有古风',
'得之陕郊篇',
'惜哉功名忤',
'但见书画传',
'我游梓州东',
'遗迹涪江边',
'画藏青莲界',
'书入金榜悬',
'仰看垂露姿',
'不崩亦不骞',
'郁郁三大字',
'蛟龙岌相缠',
'又挥西方变',
'发地扶屋椽',
'惨澹壁飞动',
'到今色未填',
'此行叠壮观',
'郭薛俱才贤',
'不知百载后',
'谁复来通泉',
],
},
{
title: '通泉县署屋壁后薛少保画鹤',
body: [
'薛公十一鹤',
'皆写青田真',
'画色久欲尽',
'苍然犹出尘',
'低昂各有意',
'磊落如长人',
'佳此志气远',
'岂惟粉墨新',
'万里不以力',
'群游森会神',
'威迟白凤态',
'非是仓庚邻',
'高堂未倾覆',
'常得慰嘉宾',
'曝露墙壁外',
'终嗟风雨频',
'赤霄有真骨',
'耻饮洿池津',
'冥冥任所往',
'脱略谁能驯',
],
},
{
title: '陪王侍御同登东山最高顶宴姚通泉,晚携酒泛江',
body: [
'姚公美政谁与俦',
'不减昔时陈太丘',
'邑中上客有柱史',
'多暇日陪骢马游',
'东山高顶罗珍羞',
'下顾城郭销我忧',
'清江白日落欲尽',
'复携美人登彩舟',
'笛声愤怨哀中流',
'妙舞逶迤夜未休',
'灯前往往大鱼出',
'听曲低昂如有求',
'三更风起寒浪涌',
'取乐喧呼觉船重',
'满空星河光破碎',
'四座宾客色不动',
'请公临深莫相违',
'回船罢酒上马归',
'人生欢会岂有极',
'无使霜过沾人衣',
],
},
{
title: '春日戏题恼郝使君兄',
body: [
'使君意气凌青霄',
'忆昨欢娱常见招',
'细马时鸣金騕褭',
'佳人屡出董娇饶',
'东流江水西飞燕',
'可惜春光不相见',
'愿携王赵两红颜',
'再骋肌肤如素练',
'通泉百里近梓州',
'请公一来开我愁',
'舞处重看花满面',
'尊前还有锦缠头',
],
},
{
title: '短歌行,赠王郎司直',
body: [
'王郎酒酣拔剑斫地歌莫哀',
'我能拔尔抑塞磊落之奇才',
'豫章翻风白日动',
'鲸鱼跋浪沧溟开',
'且脱佩剑休裴回',
'西得诸侯棹锦水',
'欲向何门趿珠履',
'仲宣楼头春色深',
'青眼高歌望吾子',
'眼中之人吾老矣',
],
},
{
title: '短歌行,送祁录事归合州,因寄苏使君',
body: [
'前者途中一相见',
'人事经年记君面',
'后生相动何寂寥',
'君有长才不贫贱',
'君今起柁春江流',
'余亦沙边具小舟',
'幸为达书贤府主',
'江花未尽会江楼',
],
},
{
title: '陪章留后惠义寺饯嘉州崔都督赴州',
body: [
'中军待上客',
'令肃事有恒',
'前驱入宝地',
'祖帐飘金绳',
'南陌既留欢',
'兹山亦深登',
'清闻树杪磬',
'远谒云端僧',
'回策匪新岸',
'所攀仍旧藤',
'耳激洞门飙',
'目存寒谷冰',
'出尘閟轨躅',
'毕景遗炎蒸',
'永愿坐长夏',
'将衰栖大乘',
'羁旅惜宴会',
'艰难怀友朋',
'劳生共几何',
'离恨兼相仍',
],
},
{
title: '将适吴楚,留别章使君留后,兼幕府诸公,得柳字',
body: [
'我来入蜀门',
'岁月亦已久',
'岂惟长儿童',
'自觉成老丑',
'常恐性坦率',
'失身为杯酒',
'近辞痛饮徒',
'折节万夫后',
'昔如纵壑鱼',
'今如丧家狗',
'既无游方恋',
'行止复何有',
'相逢半新故',
'取别随薄厚',
'不意青草湖',
'扁舟落吾手',
'眷眷章梓州',
'开筵俯高柳',
'楼前出骑马',
'帐下罗宾友',
'健儿簸红旗',
'此乐或难朽',
'日车隐昆仑',
'鸟雀噪户牖',
'波涛未足畏',
'三峡徒雷吼',
'所忧盗贼多',
'重见衣冠走',
'中原消息断',
'黄屋今安否',
'终作适荆蛮',
'安排用庄叟',
'随云拜东皇',
'挂席上南斗',
'有使即寄书',
'无使长回首',
],
},
{
title: '山寺(得开字,章留后同游)',
body: [
'野寺根石壁',
'诸龛遍崔嵬',
'前佛不复辨',
'百身一莓苔',
'虽有古殿存',
'世尊亦尘埃',
'如闻龙象泣',
'足令信者哀',
'使君骑紫马',
'捧拥从西来',
'树羽静千里',
'临江久裴回',
'山僧衣蓝缕',
'告诉栋梁摧',
'公为顾宾徒',
'咄嗟檀施开',
'吾知多罗树',
'却倚莲华台',
'诸天必欢喜',
'鬼物无嫌猜',
'以兹抚士卒',
'孰曰非周才',
'穷子失净处',
'高人忧祸胎',
'岁晏风破肉',
'荒林寒可回',
'思量入道苦',
'自哂同婴孩',
],
},
{
title: '棕拂子',
body: [
'棕拂且薄陋',
'岂知身效能',
'不堪代白羽',
'有足除苍蝇',
'荧荧金错刀',
'擢擢朱丝绳',
'非独颜色好',
'亦用顾盼称',
'吾老抱疾病',
'家贫卧炎蒸',
'咂肤倦扑灭',
'赖尔甘服膺',
'物微世竞弃',
'义在谁肯征',
'三岁清秋至',
'未敢阙缄藤',
],
},
{
title: '桃竹杖引,赠章留后(竹兼可为簟,名桃笙)',
body: [
'江心蟠石生桃竹',
'苍波喷浸尺度足',
'斩根削皮如紫玉',
'江妃水仙惜不得',
'梓潼使君开一束',
'满堂宾客皆叹息',
'怜我老病赠两茎',
'出入爪甲铿有声',
'老夫复欲东南征',
'乘涛鼓枻白帝城',
'路幽必为鬼神夺',
'拔剑或与蛟龙争',
'重为告曰:杖兮杖兮',
'尔之生也甚正直',
'慎勿见水踊跃学变化为龙',
'使我不得尔之扶持',
'灭迹于君山湖上之青峰',
'噫',
'风尘澒洞兮豺虎咬人',
'忽失双杖兮吾将曷从',
],
},
{
title: '寄题江外草堂(梓州作,寄成都故居)',
body: [
'我生性放诞',
'雅欲逃自然',
'嗜酒爱风竹',
'卜居必林泉',
'遭乱到蜀江',
'卧疴遣所便',
'诛茅初一亩',
'广地方连延',
'经营上元始',
'断手宝应年',
'敢谋土木丽',
'自觉面势坚',
'台亭随高下',
'敞豁当清川',
'虽有会心侣',
'数能同钓船',
'干戈未偃息',
'安得酣歌眠',
'蛟龙无定窟',
'黄鹄摩苍天',
'古来达士志',
'宁受外物牵',
'顾惟鲁钝姿',
'岂识悔吝先',
'偶携老妻去',
'惨澹凌风烟',
'事迹无固必',
'幽贞愧双全',
'尚念四小松',
'蔓草易拘缠',
'霜骨不甚长',
'永为邻里怜',
],
},
{
title: '韦讽录事宅观曹将军画马图',
body: [
'国初已来画鞍马',
'神妙独数江都王',
'将军得名三十载',
'人间又见真乘黄',
'曾貌先帝照夜白',
'龙池十日飞霹雳',
'内府殷红马脑碗',
'婕妤传诏才人索',
'碗赐将军拜舞归',
'轻纨细绮相追飞',
'贵戚权门得笔迹',
'始觉屏障生光辉',
'昔日太宗拳毛騧',
'近时郭家师子花',
'今之新图有二马',
'复令识者久叹嗟',
'此皆骑战一敌万',
'缟素漠漠开风沙',
'其馀七匹亦殊绝',
'迥若寒空动烟雪',
'霜蹄蹴踏长楸间',
'马官厮养森成列',
'可怜九马争神骏',
'顾视清高气深稳',
'借问苦心爱者谁',
'后有韦讽前支遁',
'忆昔巡幸新丰宫',
'翠华拂天来向东',
'腾骧磊落三万匹',
'皆与此图筋骨同',
'自从献宝朝河宗',
'无复射蛟江水中',
'君不见金粟堆前松柏里',
'龙媒去尽鸟呼风',
],
},
{
title: '送韦讽上阆州录事参军',
body: [
'国步犹艰难',
'兵革未衰息',
'万方哀嗷嗷',
'十载供军食',
'庶官务割剥',
'不暇忧反侧',
'诛求何多门',
'贤者贵为德',
'韦生富春秋',
'洞彻有清识',
'操持纪纲地',
'喜见朱丝直',
'当令豪夺吏',
'自此无颜色',
'必若救疮痍',
'先应去蟊贼',
'挥泪临大江',
'高天意凄恻',
'行行树佳政',
'慰我深相忆',
],
},
{
title: '丹青引,赠曹将军霸',
body: [
'将军魏武之子孙',
'于今为庶为清门',
'英雄割据虽已矣',
'文彩风流犹尚存',
'学书初学卫夫人',
'但恨无过王右军',
'丹青不知老将至',
'富贵于我如浮云',
'开元之中常引见',
'承恩数上南熏殿',
'凌烟功臣少颜色',
'将军下笔开生面',
'良相头上进贤冠',
'猛将腰间大羽箭',
'褒公鄂公毛发动',
'英姿飒爽来酣战',
'先帝天马玉花骢',
'画工如山貌不同',
'是日牵来赤墀下',
'迥立阊阖生长风',
'诏谓将军拂绢素',
'意匠惨澹经营中',
'斯须九重真龙出',
'一洗万古凡马空',
'玉花却在御榻上',
'榻上庭前屹相向',
'至尊含笑催赐金',
'圉人太仆皆惆怅',
'弟子韩幹早入室',
'亦能画马穷殊相',
'幹惟画肉不画骨',
'忍使骅骝气凋丧',
'将军画善盖有神',
'必逢佳士亦写真',
'即今飘泊干戈际',
'屡貌寻常行路人',
'途穷反遭俗眼白',
'世上未有如公贫',
'但看古来盛名下',
'终日坎壈缠其身',
],
},
{
title: '阆州东楼筵,奉送十一舅往青城县,得昏字',
body: [
'曾城有高楼',
'制古丹雘存',
'迢迢百馀尺',
'豁达开四门',
'虽有车马客',
'而无人世喧',
'游目俯大江',
'列筵慰别魂',
'是时秋冬交',
'节往颜色昏',
'天寒鸟兽休',
'霜露在草根',
'今我送舅氏',
'万感集清尊',
'岂伊山川间',
'回首盗贼繁',
'高贤意不暇',
'王命久崩奔',
'临风欲恸哭',
'声出已复吞',
],
},
{
title: '严氏溪放歌行(溪在阆州东百馀里)',
body: [
'天下甲马未尽销',
'岂免沟壑常漂漂',
'剑南岁月不可度',
'边头公卿仍独骄',
'费心姑息是一役',
'肥肉大酒徒相要',
'呜呼古人已粪土',
'独觉志士甘渔樵',
'况我飘转无定所',
'终日戚戚忍羁旅',
'秋宿霜溪素月高',
'喜得与子长夜语',
'东游西还力实倦',
'从此将身更何许',
'知子松根长茯苓',
'迟暮有意来同煮',
],
},
{
title: '南池(在阆中县东南,即彭道将鱼池)',
body: [
'峥嵘巴阆间',
'所向尽山谷',
'安知有苍池',
'万顷浸坤轴',
'呀然阆城南',
'枕带巴江腹',
'芰荷入异县',
'粳稻共比屋',
'皇天不无意',
'美利戒止足',
'高田失西成',
'此物颇丰熟',
'清源多众鱼',
'远岸富乔木',
'独叹枫香林',
'春时好颜色',
'南有汉王祠',
'终朝走巫祝',
'歌舞散灵衣',
'荒哉旧风俗',
'高堂亦明王',
'魂魄犹正直',
'不应空陂上',
'缥缈亲酒食',
'淫祀自古昔',
'非唯一川渎',
'干戈浩茫茫',
'地僻伤极目',
'平生江海兴',
'遭乱身局促',
'驻马问渔舟',
'踌躇慰羁束',
],
},
{
title: '发阆中',
body: [
'前有毒蛇后猛虎',
'溪行尽日无村坞',
'江风萧萧云拂地',
'山木惨惨天欲雨',
'女病妻忧归意速',
'秋花锦石谁复数',
'别家三月一得书',
'避地何时免愁苦',
],
},
{
title: '寄韩谏议',
body: [
'今我不乐思岳阳',
'身欲奋飞病在床',
'美人娟娟隔秋水',
'濯足洞庭望八荒',
'鸿飞冥冥日月白',
'青枫叶赤天雨霜',
'玉京群帝集北斗',
'或骑骐驎翳凤凰',
'芙蓉旌旗烟雾乐',
'影动倒景摇潇湘',
'星宫之君醉琼浆',
'羽人稀少不在旁',
'似闻昨者赤松子',
'恐是汉代韩张良',
'昔随刘氏定长安',
'帷幄未改神惨伤',
'国家成败吾岂敢',
'色难腥腐餐风香',
'周南留滞古所惜',
'南极老人应寿昌',
'美人胡为隔秋水',
'焉得置之贡玉堂',
],
},
{
title: '忆昔二首',
body: [
'忆昔先皇巡朔方',
'千乘万骑入咸阳',
'阴山骄子汗血马',
'长驱东胡胡走藏',
'邺城反覆不足怪',
'关中小儿坏纪纲',
'张后不乐上为忙',
'至今今上犹拨乱',
'劳身焦思补四方',
'我昔近侍叨奉引',
'出兵整肃不可当',
'为留猛士守未央',
'致使岐雍防西羌',
'犬戎直来坐御林',
'百官跣足随天王',
'愿见北地傅介子',
'老儒不用尚书郎',
'忆昔开元全盛日',
'小邑犹藏万家室',
'稻米流脂粟米白',
'公私仓廪俱丰实',
'九州道路无豺虎',
'远行不劳吉日出',
'齐纨鲁缟车班班',
'男耕女桑不相失',
'宫中圣人奏云门',
'天下朋友皆胶漆',
'百馀年间未灾变',
'叔孙礼乐萧何律',
'岂闻一绢直万钱',
'有田种谷今流血',
'洛阳宫殿烧焚尽',
'宗庙新除狐兔穴',
'伤心不忍问耆旧',
'复恐初从乱离说',
'小臣鲁钝无所能',
'朝廷记识蒙禄秩',
'周宣中兴望我皇',
'洒血江汉身衰疾',
],
},
{
title: '冬狩行(时梓州刺史章彝兼侍御史留后东川)',
body: [
'君不见东川节度兵马雄',
'校猎亦似观成功',
'夜发猛士三千人',
'清晨合围步骤同',
'禽兽已毙十七八',
'杀声落日回苍穹',
'幕前生致九青兕',
'骆驼pI峞垂玄熊',
'东西南北百里间',
'仿佛蹴踏寒山空',
'有鸟名鸲鹆',
'力不能高飞逐走蓬',
'肉味不足登鼎俎',
'何为见羁虞罗中',
'春蒐冬狩侯得同',
'使君五马一马骢',
'况今摄行大将权',
'号令颇有前贤风',
'飘然时危一老翁',
'十年厌见旌旗红',
'喜君士卒甚整肃',
'为我回辔擒西戎',
'草中狐兔尽何益',
'天子不在咸阳宫',
'朝廷虽无幽王祸',
'得不哀痛尘再蒙',
'呜呼',
'得不哀痛尘再蒙',
],
},
{
title: '自平',
body: [
'自平宫中吕太一',
'收珠南海千馀日',
'近供生犀翡翠稀',
'复恐征戎干戈密',
'蛮溪豪族小动摇',
'世封刺史非时朝',
'蓬莱殿前诸主将',
'才如伏波不得骄',
],
},
{
title: '释闷',
body: [
'四海十年不解兵',
'犬戎也复临咸京',
'失道非关出襄野',
'扬鞭忽是过胡城',
'豺狼塞路人断绝',
'烽火照夜尸纵横',
'天子亦应厌奔走',
'群公固合思升平',
'但恐诛求不改辙',
'闻道嬖孽能全生',
'江边老翁错料事',
'眼暗不见风尘清',
],
},
{
title: '赠别贺兰铦',
body: [
'黄雀饱野粟',
'群飞动荆榛',
'今君抱何恨',
'寂寞向时人',
'老骥倦骧首',
'苍鹰愁易驯',
'高贤世未识',
'固合婴饥贫',
'国步初返正',
'乾坤尚风尘',
'悲歌鬓发白',
'远赴湘吴春',
'我恋岷下芋',
'君思千里莼',
'生离与死别',
'自古鼻酸辛',
],
},
{
title: '别唐十五诫,因寄礼部贾侍郎(贾至)',
body: [
'九载一相逢',
'百年能几何',
'复为万里别',
'送子山之阿',
'白鹤久同林',
'潜鱼本同河',
'未知栖集期',
'衰老强高歌',
'歌罢两凄恻',
'六龙忽蹉跎',
'相视发皓白',
'况难驻羲和',
'胡星坠燕地',
'汉将仍横戈',
'萧条四海内',
'人少豺虎多',
'少人慎莫投',
'多虎信所过',
'饥有易子食',
'兽犹畏虞罗',
'子负经济才',
'天门郁嵯峨',
'飘摇适东周',
'来往若崩波',
'南宫吾故人',
'白马金盘陀',
'雄笔映千古',
'见贤心靡他',
'念子善师事',
'岁寒守旧柯',
'为吾谢贾公',
'病肺卧江沱',
],
},
{
title: '阆山歌',
body: [
'阆州城东灵山白',
'阆州城北玉台碧',
'松浮欲尽不尽云',
'江动将崩未崩石',
'那知根无鬼神会',
'已觉气与嵩华敌',
'中原格斗且未归',
'应结茅斋看青壁',
],
},
{
title: '阆水歌',
body: [
'嘉陵江色何所似',
'石黛碧玉相因依',
'正怜日破浪花出',
'更复春从沙际归',
'巴童荡桨欹侧过',
'水鸡衔鱼来去飞',
'阆中胜事可肠断',
'阆州城南天下稀',
],
},
{
title: '草堂',
body: [
'昔我去草堂',
'蛮夷塞成都',
'今我归草堂',
'成都适无虞',
'请陈初乱时',
'反复乃须臾',
'大将赴朝廷',
'群小起异图',
'中宵斩白马',
'盟歃气已粗',
'西取邛南兵',
'北断剑阁隅',
'布衣数十人',
'亦拥专城居',
'其势不两大',
'始闻蕃汉殊',
'西卒却倒戈',
'贼臣互相诛',
'焉知肘腋祸',
'自及枭獍徒',
'义士皆痛愤',
'纪纲乱相逾',
'一国实三公',
'万人欲为鱼',
'唱和作威福',
'孰肯辨无辜',
'眼前列杻械',
'背后吹笙竽',
'谈笑行杀戮',
'溅血满长衢',
'到今用钺地',
'风雨闻号呼',
'鬼妾与鬼马',
'色悲充尔娱',
'国家法令在',
'此又足惊吁',
'贱子且奔走',
'三年望东吴',
'弧矢暗江海',
'难为游五湖',
'不忍竟舍此',
'复来薙榛芜',
'入门四松在',
'步屟万竹疏',
'旧犬喜我归',
'低徊入衣裾',
'邻舍喜我归',
'酤酒携胡芦',
'大官喜我来',
'遣骑问所须',
'城郭喜我来',
'宾客隘村墟',
'天下尚未宁',
'健儿胜腐儒',
'飘摇风尘际',
'何地置老夫',
'于时见疣赘',
'骨髓幸未枯',
'饮啄愧残生',
'食薇不敢馀',
],
},
{
title: '四松',
body: [
'四松初移时',
'大抵三尺强',
'别来忽三载',
'离立如人长',
'会看根不拔',
'莫计枝凋伤',
'幽色幸秀发',
'疏柯亦昂藏',
'所插小藩篱',
'本亦有堤防',
'终然掁拨损',
'得吝千叶黄',
'敢为故林主',
'黎庶犹未康',
'避贼今始归',
'春草满空堂',
'览物叹衰谢',
'及兹慰凄凉',
'清风为我起',
'洒面若微霜',
'足以送老姿',
'聊待偃盖张',
'我生无根带',
'配尔亦茫茫',
'有情且赋诗',
'事迹可两忘',
'勿矜千载后',
'惨澹蟠穹苍',
],
},
{
title: '水槛',
body: [
'苍江多风飙',
'云雨昼夜飞',
'茅轩驾巨浪',
'焉得不低垂',
'游子久在外',
'门户无人持',
'高岸尚如谷',
'何伤浮柱欹',
'扶颠有劝诫',
'恐贻识者嗤',
'既殊大厦倾',
'可以一木支',
'临川视万里',
'何必阑槛为',
'人生感故物',
'慷慨有馀悲',
],
},
{
title: '破船',
body: [
'平生江海心',
'宿昔具扁舟',
'岂惟青溪上',
'日傍柴门游',
'苍皇避乱兵',
'缅邈怀旧丘',
'邻人亦已非',
'野竹独修修',
'船舷不重扣',
'埋没已经秋',
'仰看西飞翼',
'下愧东逝流',
'故者或可掘',
'新者亦易求',
'所悲数奔窜',
'白屋难久留',
],
},
{
title: '营屋',
body: [
'我有阴江竹',
'能令朱夏寒',
'阴通积水内',
'高入浮云端',
'甚疑鬼物凭',
'不顾翦伐残',
'东偏若面势',
'户牖永可安',
'爱惜已六载',
'兹晨去千竿',
'萧萧见白日',
'汹汹开奔湍',
'度堂匪华丽',
'养拙异考槃',
'草茅虽薙葺',
'衰疾方少宽',
'洗然顺所适',
'此足代加餐',
'寂无斤斧响',
'庶遂憩息欢',
],
},
{
title: '除草',
body: [
'草有害于人',
'曾何生阻修',
'其毒甚蜂虿',
'其多弥道周',
'清晨步前林',
'江色未散忧',
'芒刺在我眼',
'焉能待高秋',
'霜露一沾凝',
'蕙叶亦难留',
'荷锄先童稚',
'日入仍讨求',
'转致水中央',
'岂无双钓舟',
'顽根易滋蔓',
'敢使依旧丘',
'自兹藩篱旷',
'更觉松竹幽',
'芟夷不可阙',
'疾恶信如雠',
],
},
{
title: '扬旗',
body: [
'江雨飒长夏',
'府中有馀清',
'我公会宾客',
'肃肃有异声',
'初筵阅军装',
'罗列照广庭',
'庭空六马入',
'駊騀扬旗旌',
'回回偃飞盖',
'熠熠迸流星',
'来缠风飙急',
'去擘山岳倾',
'材归俯身尽',
'妙取略地平',
'虹霓就掌握',
'舒卷随人轻',
'三州陷犬戎',
'但见西岭青',
'公来练猛士',
'欲夺天边城',
'此堂不易升',
'庸蜀日已宁',
'吾徒且加餐',
'休适蛮与荆',
],
},
{
title: '太子张舍人遗织成褥段',
body: [
'客从西北来',
'遗我翠织成',
'开缄风涛涌',
'中有掉尾鲸',
'逶迤罗水族',
'琐细不足名',
'客云充君褥',
'承君终宴荣',
'空堂魑魅走',
'高枕形神清',
'领客珍重意',
'顾我非公卿',
'留之惧不祥',
'施之混柴荆',
'服饰定尊卑',
'大哉万古程',
'今我一贱老',
'裋褐更无营',
'煌煌珠宫物',
'寝处祸所婴',
'叹息当路子',
'干戈尚纵横',
'掌握有权柄',
'衣马自肥轻',
'李鼎死岐阳',
'实以骄贵盈',
'来瑱赐自尽',
'气豪直阻兵',
'皆闻黄金多',
'坐见悔吝生',
'奈何田舍翁',
'受此厚贶情',
'锦鲸卷还客',
'始觉心和平',
'振我粗席尘',
'愧客茹藜羹',
],
},
{
title: '莫相疑行',
body: [
'男儿生无所成头皓白',
'牙齿欲落真可惜',
'忆献三赋蓬莱宫',
'自怪一日声辉赫',
'集贤学士如堵墙',
'观我落笔中书堂',
'往时文彩动人主',
'此日饥寒趋路旁',
'晚将末契托年少',
'当面输心背面笑',
'寄谢悠悠世上儿',
'不争好恶莫相疑',
],
},
{
title: '别蔡十四著作',
body: [
'贾生恸哭后',
'寥落无其人',
'安知蔡夫子',
'高义迈等伦',
'献书谒皇帝',
'志已清风尘',
'流涕洒丹极',
'万乘为酸辛',
'天地则创痍',
'朝廷当正臣',
'异才复间出',
'周道日惟新',
'使蜀见知己',
'别颜始一伸',
'主人薨城府',
'扶榇归咸秦',
'巴道此相逢',
'会我病江滨',
'忆念凤翔都',
'聚散俄十春',
'我衰不足道',
'但愿子意陈',
'稍令社稷安',
'自契鱼水亲',
'我虽消渴甚',
'敢忘帝力勤',
'尚思未朽骨',
'复睹耕桑民',
'积水驾三峡',
'浮龙倚长津',
'扬舲洪涛间',
'仗子济物身',
'鞍马下秦塞',
'王城通北辰',
'玄甲聚不散',
'兵久食恐贫',
'穷谷无粟帛',
'使者来相因',
'若凭南辕吏',
'书札到天垠',
],
},
{
title: '杜鹃',
body: [
'西川有杜鹃',
'东川无杜鹃',
'涪万无杜鹃',
'云安有杜鹃',
'我昔游锦城',
'结庐锦水边',
'有竹一顷馀',
'乔木上参天',
'杜鹃暮春至',
'哀哀叫其间',
'我见常再拜',
'重是古帝魂',
'生子百鸟巢',
'百鸟不敢嗔',
'仍为喂其子',
'礼若奉至尊',
'鸿雁及羔羊',
'有礼太古前',
'行飞与跪乳',
'识序如知恩',
'圣贤古法则',
'付与后世传',
'君看禽鸟情',
'犹解事杜鹃',
'今忽暮春间',
'值我病经年',
'身病不能拜',
'泪下如迸泉',
],
},
{
title: '客居',
body: [
'客居所居堂',
'前江后山根',
'下堑万寻岸',
'苍涛郁飞翻',
'葱青众木梢',
'邪竖杂石痕',
'子规昼夜啼',
'壮士敛精魂',
'峡开四千里',
'水合数百源',
'人虎相半居',
'相伤终两存',
'蜀麻久不来',
'吴盐拥荆门',
'西南失大将',
'商旅自星奔',
'今又降元戎',
'已闻动行轩',
'舟子候利涉',
'亦凭节制尊',
'我在路中央',
'生理不得论',
'卧愁病脚废',
'徐步视小园',
'短畦带碧草',
'怅望思王孙',
'凤随其皇去',
'篱雀暮喧繁',
'览物想故国',
'十年别荒村',
'日暮归几翼',
'北林空自昏',
'安得覆八溟',
'为君洗乾坤',
'稷契易为力',
'犬戎何足吞',
'儒生老无成',
'臣子忧四番',
'箧中有旧笔',
'情至时复援',
],
},
{
title: '客堂',
body: [
'忆昨离少城',
'而今异楚蜀',
'舍舟复深山',
'窅窕一林麓',
'栖泊云安县',
'消中内相毒',
'旧疾甘载来',
'衰年得无足',
'死为殊方鬼',
'头白免短促',
'老马终望云',
'南雁意在北',
'别家长儿女',
'欲起惭筋力',
'客堂序节改',
'具物对羁束',
'石暄蕨芽紫',
'渚秀芦笋绿',
'巴莺纷未稀',
'徼麦早向熟',
'悠悠日动江',
'漠漠春辞木',
'台郎选才俊',
'自顾亦已极',
'前辈声名人',
'埋没何所得',
'居然绾章绂',
'受性本幽独',
'平生憩息地',
'必种数竿竹',
'事业只浊醪',
'营葺但草屋',
'上公有记者',
'累奏资薄禄',
'主忧岂济时',
'身远弥旷职',
'循文庙算正',
'献可天衢直',
'尚想趋朝廷',
'毫发裨社稷',
'形骸今若是',
'进退委行色',
],
},
{
title: '石研诗',
body: [
'平公今诗伯',
'秀发吾所羡',
'奉使三峡中',
'长啸得石研',
'巨璞禹凿馀',
'异状君独见',
'其滑乃波涛',
'其光或雷电',
'联坳各尽墨',
'多水递隐现',
'挥洒容数人',
'十手可对面',
'比公头上冠',
'贞质未为贱',
'当公赋佳句',
'况得终清宴',
'公含起草姿',
'不远明光殿',
'致于丹青地',
'知汝随顾眄',
],
},
{
title: '水阁朝霁,奉简严云安(一作云安严明府)',
body: [
'东城抱春岑',
'江阁邻石面',
'崔嵬晨云白',
'朝旭射芳甸',
'雨槛卧花丛',
'风床展书卷',
'钩帘宿鹭起',
'丸药流莺啭',
'呼婢取酒壶',
'续儿诵文选',
'晚交严明府',
'矧此数相见',
],
},
{
title: '赠郑十八贲(云安令)',
body: [
'温温士君子',
'令我怀抱尽',
'灵芝冠众芳',
'安得阙亲近',
'遭乱意不归',
'窜身迹非隐',
'细人尚姑息',
'吾子色愈谨',
'高怀见物理',
'识者安肯哂',
'卑飞欲何待',
'捷径应未忍',
'示我百篇文',
'诗家一标准',
'羁离交屈宋',
'牢落值颜闵',
'水陆迷畏途',
'药饵驻修轸',
'古人日以远',
'青史字不泯',
'步趾咏唐虞',
'追随饭葵堇',
'数杯资好事',
'异味烦县尹',
'心虽在朝谒',
'力与愿矛盾',
'抱病排金门',
'衰容岂为敏',
],
},
{
title: '三韵三篇',
body: [
'高马勿唾面',
'长鱼无损鳞',
'辱马马毛焦',
'困鱼鱼有神',
'君看磊落士',
'不肯易其身',
'荡荡万斛船',
'影若扬白虹',
'起樯必椎牛',
'挂席集众功',
'自非风动天',
'莫置大水中',
'烈士恶多门',
'小人自同调',
'名利苟可取',
'杀身傍权要',
'何当官曹清',
'尔辈堪一笑',
],
},
{
title: '青丝(青丝白马,用侯景事,以比仆固怀恩)',
body: [
'青丝白马谁家子',
'粗豪且逐风尘起',
'不闻汉主放妃嫔',
'近静潼关扫蜂蚁',
'殿前兵马破汝时',
'十月即为齑粉期',
'未如面缚归金阙',
'万一皇恩下玉墀',
],
},
{
title: '近闻',
body: [
'近闻犬戎远遁逃',
'牧马不敢侵临洮',
'渭水逶迤白日净',
'陇山萧瑟秋云高',
'崆峒五原亦无事',
'北庭数有关中使',
'似闻赞普更求亲',
'舅甥和好应难弃',
],
},
{
title: '蚕谷行',
body: [
'天下郡国向万城',
'无有一城无甲兵',
'焉得铸甲作农器',
'一寸荒田牛得耕',
'牛尽耕',
'蚕亦成',
'不劳烈士泪滂沱',
'男谷女丝行复歌',
],
},
{
title: '折槛行',
body: [
'呜呼房魏不复见',
'秦王学士时难羡',
'青衿胄子困泥涂',
'白马将军若雷电',
'千载少似朱云人',
'至今折槛空嶙峋',
'娄公不语宋公语',
'尚忆先皇容直臣',
],
},
{
title: '引水',
body: [
'月峡瞿塘云作顶',
'乱石峥嵘俗无井',
'云安酤水奴仆悲',
'鱼复移居心力省',
'白帝城西万竹蟠',
'接筒引水喉不干',
'人生留滞生理难',
'斗水何直百忧宽',
],
},
{
title: '古柏行',
body: [
'孔明庙前有老柏',
'柯如青铜根如石',
'霜皮溜雨四十围',
'黛色参天二千尺',
'君臣已与时际会',
'树木犹为人爱惜',
'云来气接巫峡长',
'月出寒通雪山白',
'忆昨路绕锦亭东',
'先主武侯同閟宫',
'崔嵬枝干郊原古',
'窈窕丹青户牖空',
'落落盘踞虽得地',
'冥冥孤高多烈风',
'扶持自是神明力',
'正直原因造化功',
'大厦如倾要梁栋',
'万牛回首丘山重',
'不露文章世已惊',
'未辞翦伐谁能送',
'苦心岂免容蝼蚁',
'香叶终经宿鸾凤',
'志士幽人莫怨嗟',
'古来材大难为用',
],
},
{
title: '缚鸡行',
body: [
'小奴缚鸡向市卖',
'鸡被缚急相喧争',
'家中厌鸡食虫蚁',
'不知鸡卖还遭烹',
'虫鸡于人何厚薄',
'吾叱奴人解其缚',
'鸡虫得失无了时',
'注目寒江倚山阁',
],
},
{
title: '负薪行',
body: [
'夔州处女发半华',
'四十五十无夫家',
'更遭丧乱嫁不售',
'一生抱恨堪咨嗟',
'土风坐男使女立',
'应当门户女出入',
'十犹八九负薪归',
'卖薪得钱应供给',
'至老双鬟只垂颈',
'野花山叶银钗并',
'筋力登危集市门',
'死生射利兼盐井',
'面妆首饰杂啼痕',
'地褊衣寒困石根',
'若道巫山女粗丑',
'何得此有昭君村',
],
},
{
title: '最能行',
body: [
'峡中丈夫绝轻死',
'少在公门多在水',
'富豪有钱驾大舸',
'贫穷取给行艓子',
'小儿学问止论语',
'大儿结束随商旅',
'欹帆侧柁入波涛',
'撇漩捎濆无险阻',
'朝发白帝暮江陵',
'顷来目击信有征',
'瞿塘漫天虎须怒',
'归州长年行最能',
'此乡之人气量窄',
'误竞南风疏北客',
'若道土无英俊才',
'何得山有屈原宅',
],
},
{
title: '寄裴施州(裴冕坐李辅国贬施州刺史)',
body: [
'廊庙之具裴施州',
'宿昔一逢无此流',
'金钟大镛在东序',
'冰壶玉衡悬清秋',
'自从相遇感多病',
'三岁为客宽边愁',
'尧有四岳明至理',
'汉二千石真分忧',
'几度寄书白盐北',
'苦寒赠我青羔裘',
'霜雪回光避锦袖',
'龙蛇动箧蟠银钩',
'紫衣使者辞复命',
'再拜故人谢佳政',
'将老已失子孙忧',
'后来况接才华盛',
],
},
{
title: '郑典设自施州归',
body: [
'吾怜荥阳秀',
'冒暑初有适',
'名贤慎所出',
'不肯妄行役',
'旅兹殊俗远',
'竟以屡空迫',
'南谒裴施州',
'气合无险僻',
'攀援悬根木',
'登顿入天石',
'青山自一川',
'城郭洗忧戚',
'听子话此邦',
'令我心悦怿',
'其俗则纯朴',
'不知有主客',
'温温诸侯门',
'礼亦如古昔',
'敕厨倍常羞',
'杯盘颇狼藉',
'时虽属丧乱',
'事贵赏匹敌',
'中宵惬良会',
'裴郑非远戚',
'群书一万卷',
'博涉供务隙',
'他日辱银钩',
'森疏见矛戟',
'倒屣喜旋归',
'画地求所历',
'乃闻风土质',
'又重田畴辟',
'刺史似寇恂',
'列郡宜竞惜',
'北风吹瘴疠',
'羸老思散策',
'渚拂蒹葭塞',
'峤穿萝茑幂',
'此身仗儿仆',
'高兴潜有激',
'孟冬方首路',
'强饭取崖壁',
'叹尔疲驽骀',
'汗沟血不赤',
'终然备外饰',
'驾驭何所益',
'我有平肩舆',
'前途犹准的',
'翩翩入鸟道',
'庶脱蹉跌厄',
],
},
{
title: '柴门',
body: [
'孤舟登瀼西',
'回首望两崖',
'东城干旱天',
'其气如焚柴',
'长影没窈窕',
'馀光散唅呀',
'大江蟠嵌根',
'归海成一家',
'下冲割坤轴',
'竦壁攒镆铘',
'萧飒洒秋色',
'氛昏霾日车',
'峡门自此始',
'最窄容浮查',
'禹功翊造化',
'疏凿就欹斜',
'巨渠决太古',
'众水为长蛇',
'风烟渺吴蜀',
'舟楫通盐麻',
'我今远游子',
'飘转混泥沙',
'万物附本性',
'约身不愿奢',
'茅栋盖一床',
'清池有馀花',
'浊醪与脱粟',
'在眼无咨嗟',
'山荒人民少',
'地僻日夕佳',
'贫病固其常',
'富贵任生涯',
'老于干戈际',
'宅幸蓬荜遮',
'石乱上云气',
'杉清延月华',
'赏妍又分外',
'理惬夫何夸',
'足了垂白年',
'敢居高士差',
'书此豁平昔',
'回首犹暮霞',
],
},
{
title: '贻华阳柳少府',
body: [
'系马乔木间',
'问人野寺门',
'柳侯披衣笑',
'见我颜色温',
'并坐石下堂',
'俯视大江奔',
'火云洗月露',
'绝壁上朝暾',
'自非晓相访',
'触热生病根',
'南方六七月',
'出入异中原',
'老少多暍死',
'汗逾水浆翻',
'俊才得之子',
'筋力不辞烦',
'指挥当世事',
'语及戎马存',
'涕泪溅我裳',
'悲气排帝阍',
'郁陶抱长策',
'义仗知者论',
'吾衰卧江汉',
'但愧识玙璠',
'文章一小技',
'于道未为尊',
'起予幸斑白',
'因是托子孙',
'俱客古信州',
'结庐依毁垣',
'相去四五里',
'径微山叶繁',
'时危挹佳士',
'况免军旅喧',
'醉从赵女舞',
'歌鼓秦人盆',
'子壮顾我伤',
'我欢兼泪痕',
'馀生如过鸟',
'故里今空村',
],
},
{
title: '雷',
body: [
'大旱山岳燋',
'密云复无雨',
'南方瘴疠地',
'罹此农事苦',
'封内必舞雩',
'峡中喧击鼓',
'真龙竟寂寞',
'土梗空俯偻',
'吁嗟公私病',
'税敛缺不补',
'故老仰面啼',
'疮痍向谁数',
'暴尪或前闻',
'鞭巫非稽古',
'请先偃甲兵',
'处分听人主',
'万邦但各业',
'一物休尽取',
'水旱其数然',
'尧汤免亲睹',
'上天铄金石',
'群盗乱豺虎',
'二者存一端',
'愆阳不犹愈',
'昨宵殷其雷',
'风过齐万弩',
'复吹霾翳散',
'虚觉神灵聚',
'气暍肠胃融',
'汗滋衣裳污',
'吾衰尤拙计',
'失望筑场圃',
],
},
{
title: '火',
body: [
'楚山经月火',
'大旱则斯举',
'旧俗烧蛟龙',
'惊惶致雷雨',
'爆嵌魑魅泣',
'崩冻岚阴昈',
'罗落沸百泓',
'根源皆万古',
'青林一灰烬',
'云气无处所',
'入夜殊赫然',
'新秋照牛女',
'风吹巨焰作',
'河棹腾烟柱',
'势俗焚昆仑',
'光弥焮洲渚',
'腥至焦长蛇',
'声吼缠猛虎',
'神物已高飞',
'不见石与土',
'尔宁要谤讟',
'凭此近荧侮',
'薄关长吏忧',
'甚昧至精主',
'远迁谁扑灭',
'将恐及环堵',
'流汗卧江亭',
'更深气如缕',
],
},
{
title: '七月三日亭午已后较热退晚加小凉稳睡…呈元二十一曹长',
body: [
'今兹商用事',
'馀热亦已末',
'衰年旅炎方',
'生意从此活',
'亭午减汗流',
'北邻耐人聒',
'晚风爽乌匼',
'筋力苏摧折',
'闭目逾十旬',
'大江不止渴',
'退藏恨雨师',
'健步闻旱魃',
'园蔬抱金玉',
'无以供采掇',
'密云虽聚散',
'徂暑终衰歇',
'前圣慎焚巫',
'武王亲救暍',
'阴阳相主客',
'时序递回斡',
'洒落唯清秋',
'昏霾一空阔',
'萧萧紫塞雁',
'南向欲行列',
'欻思红颜日',
'霜露冻阶闼',
'胡马挟雕弓',
'鸣弦不虚发',
'长鈚逐狡兔',
'突羽当满月',
'惆怅白头吟',
'萧条游侠窟',
'临轩望山阁',
'缥缈安可越',
'高人炼丹砂',
'未念将朽骨',
'少壮迹颇疏',
'欢乐曾倏忽',
'杖藜风尘际',
'老丑难翦拂',
'吾子得神仙',
'本是池中物',
'贱夫美一睡',
'烦促婴词笔',
],
},
{
title: '牵牛织女',
body: [
'牵牛出河西',
'织女处其东',
'万古永相望',
'七夕谁见同',
'神光意难候',
'此事终蒙胧',
'飒然精灵合',
'何必秋遂通',
'亭亭新妆立',
'龙驾具曾空',
'世人亦为尔',
'祈请走儿童',
'称家随丰俭',
'白屋达公宫',
'膳夫翊堂殿',
'鸣玉凄房栊',
'曝衣遍天下',
'曳月扬微风',
'蛛丝小人态',
'曲缀瓜果中',
'初筵裛重露',
'日出甘所终',
'嗟汝未嫁女',
'秉心郁忡忡',
'防身动如律',
'竭力机杼中',
'虽无姑舅事',
'敢昧织作功',
'明明君臣契',
'咫尺或未容',
'义无弃礼法',
'恩始夫妇恭',
'小大有佳期',
'戒之在至公',
'方圆苟龃龉',
'丈夫多英雄',
],
},
{
title: '毒热寄简崔评事十六弟',
body: [
'大暑运金气',
'荆扬不知秋',
'林下有塌翼',
'水中无行舟',
'千室但扫地',
'闭关人事休',
'老夫转不乐',
'旅次兼百忧',
'蝮蛇暮偃蹇',
'空床难暗投',
'炎宵恶明烛',
'况乃怀旧丘',
'开襟仰内弟',
'执热露白头',
'束带负芒刺',
'接居成阻修',
'何当清霜飞',
'会子临江楼',
'载闻大易义',
'讽兴诗家流',
'蕴藉异时辈',
'检身非苟求',
'皇皇使臣体',
'信是德业优',
'楚材择杞梓',
'汉苑归骅骝',
'短章达我心',
'理为识者筹',
],
},
{
title: '殿中杨监见示张旭草书图',
body: [
'斯人已云亡',
'草圣秘难得',
'及兹烦见示',
'满目一凄恻',
'悲风生微绡',
'万里起古色',
'锵锵鸣玉动',
'落落群松直',
'连山蟠其间',
'溟涨与笔力',
'有练实先书',
'临池真尽墨',
'俊拔为之主',
'暮年思转极',
'未知张王后',
'谁并百代则',
'呜呼东吴精',
'逸气感清识',
'杨公拂箧笥',
'舒卷忘寝食',
'念昔挥毫端',
'不独观酒德',
],
},
{
title: '杨监又出画鹰十二扇',
body: [
'近时冯绍正',
'能画鸷鸟样',
'明公出此图',
'无乃传其状',
'殊姿各独立',
'清绝心有向',
'疾禁千里马',
'气敌万人将',
'忆昔骊山宫',
'冬移含元仗',
'天寒大羽猎',
'此物神俱王',
'当时无凡材',
'百中皆用壮',
'粉墨形似间',
'识者一惆怅',
'干戈少暇日',
'真骨老崖嶂',
'为君除狡兔',
'会是翻鞲上',
],
},
{
title: '送殿中杨监赴蜀见相公(杜鸿渐镇蜀,辟杨炎为判官)',
body: [
'去水绝还波',
'泄云无定姿',
'人生在世间',
'聚散亦暂时',
'离别重相逢',
'偶然岂定期',
'送子清秋暮',
'风物长年悲',
'豪俊贵勋业',
'邦家频出师',
'相公镇梁益',
'军事无孑遗',
'解榻再见今',
'用才复择谁',
'况子已高位',
'为郡得固辞',
'难拒供给费',
'慎哀渔夺私',
'干戈未甚息',
'纪纲正所持',
'泛舟巨石横',
'登陆草露滋',
'山门日易久',
'当念居者思',
],
},
{
title: '赠李十五丈别(李秘书文嶷)',
body: [
'峡人鸟兽居',
'其室附层颠',
'下临不测江',
'中有万里船',
'多病纷倚薄',
'少留改岁年',
'绝域谁慰怀',
'开颜喜名贤',
'孤陋忝末亲',
'等级敢比肩',
'人生意颇合',
'相与襟袂连',
'一日两遣仆',
'三日一共筵',
'扬论展寸心',
'壮笔过飞泉',
'玄成美价存',
'子山旧业传',
'不闻八尺躯',
'常受众目怜',
'且为辛苦行',
'盖被生事牵',
'北回白帝棹',
'南入黔阳天',
'汧公制方隅',
'迥出诸侯先',
'封内如太古',
'时危独萧然',
'清高金茎露',
'正直朱丝弦',
'昔在尧四岳',
'今之黄颍川',
'于迈恨不同',
'所思无由宣',
'山深水增波',
'解榻秋露悬',
'客游虽云久',
'主要月再圆',
'晨集风渚亭',
'醉操云峤篇',
'丈夫贵知己',
'欢罢念归旋',
],
},
{
title: '西阁曝日',
body: [
'凛冽倦玄冬',
'负暄嗜飞阁',
'羲和流德泽',
'颛顼愧倚薄',
'毛发具自和',
'肌肤潜沃若',
'太阳信深仁',
'衰气欻有托',
'欹倾烦注眼',
'容易收病脚',
'流离木杪猿',
'翩跹山颠鹤',
'用知苦聚散',
'哀乐日已作',
'即事会赋诗',
'人生忽如昨',
'古来遭丧乱',
'贤圣尽萧索',
'胡为将暮年',
'忧世心力弱',
],
},
{
title: '课伐木',
body: [
'长夏无所为',
'客居课奴仆',
'清晨饭其腹',
'持斧入白谷',
'青冥曾巅后',
'十里斩阴木',
'人肩四根已',
'亭午下山麓',
'尚闻丁丁声',
'功课日各足',
'苍皮成委积',
'素节相照烛',
'藉汝跨小篱',
'当仗苦虚竹',
'空荒咆熊罴',
'乳兽待人肉',
'不示知禁情',
'岂惟干戈哭',
'城中贤府主',
'处贵如白屋',
'萧萧理体净',
'蜂虿不敢毒',
'虎穴连里闾',
'堤防旧风俗',
'泊舟沧江岸',
'久客慎所触',
'舍西崖峤壮',
'雷雨蔚含蓄',
'墙宇资屡修',
'衰年怯幽独',
'尔曹轻执热',
'为我忍烦促',
'秋光近青岑',
'季月当泛菊',
'报之以微寒',
'共给酒一斛',
],
},
{
title: '园人送瓜',
body: [
'江间虽炎瘴',
'瓜熟亦不早',
'柏公镇夔国',
'滞务兹一扫',
'食新先战士',
'共少及溪老',
'倾筐蒲鸽青',
'满眼颜色好',
'竹竿接嵌窦',
'引注来鸟道',
'沈浮乱水玉',
'爱惜如芝草',
'落刃嚼冰霜',
'开怀慰枯槁',
'许以秋蒂除',
'仍看小童抱',
'东陵迹芜绝',
'楚汉休征讨',
'园人非故侯',
'种此何草草',
],
},
{
title: '信行远修水筒(引水筒)',
body: [
'汝性不茹荤',
'清静仆夫内',
'秉心识本源',
'于事少滞碍',
'云端水筒坼',
'林表山石碎',
'触热藉子修',
'通流与厨会',
'往来四十里',
'荒险崖谷大',
'日曛惊未餐',
'貌赤愧相对',
'浮瓜供老病',
'裂饼尝所爱',
'于斯答恭谨',
'足以殊殿最',
'讵要方士符',
'何假将军盖',
'行诸直如笔',
'用意崎岖外',
],
},
{
title: '槐叶冷淘',
body: [
'青青高槐叶',
'采掇付中厨',
'新面来近市',
'汁滓宛相俱',
'入鼎资过熟',
'加餐愁欲无',
'碧鲜俱照箸',
'香饭兼苞芦',
'经齿冷于雪',
'劝人投此珠',
'愿随金騕褭',
'走置锦屠苏',
'路远思恐泥',
'兴深终不渝',
'献芹则小小',
'荐藻明区区',
'万里露寒殿',
'开冰清玉壶',
'君王纳凉晚',
'此味亦时须',
],
},
{
title: '行官张望补稻畦水归',
body: [
'东屯大江北',
'百顷平若案',
'六月青稻多',
'千畦碧泉乱',
'插秧适云已',
'引溜加溉灌',
'更仆往方塘',
'决渠当断岸',
'公私各地著',
'浸润无天旱',
'主守问家臣',
'分明见溪伴',
'芊芊炯翠羽',
'剡剡生银汉',
'鸥鸟镜里来',
'关山云边看',
'秋菰成黑米',
'精凿传白粲',
'玉粒足晨炊',
'红鲜任霞散',
'终然添旅食',
'作苦期壮观',
'遗穗及众多',
'我仓戒滋蔓',
],
},
{
title: '催宗文树鸡栅',
body: [
'吾衰怯行迈',
'旅次展崩迫',
'愈风传乌鸡',
'秋卵方漫吃',
'自春生成者',
'随母向百翮',
'驱趁制不禁',
'喧呼山腰宅',
'课奴杀青竹',
'终日憎赤帻',
'蹋藉盘案翻',
'塞蹊使之隔',
'墙东有隙地',
'可以树高栅',
'避热时来归',
'问儿所为迹',
'织笼曹其内',
'令人不得掷',
'稀间可突过',
'觜爪还污席',
'我宽蝼蚁遭',
'彼免狐貉厄',
'应宜各长幼',
'自此均勍敌',
'笼栅念有修',
'近身见损益',
'明明领处分',
'一一当剖析',
'不昧风雨晨',
'乱离减忧戚',
'其流则凡鸟',
'其气心匪石',
'倚赖穷岁晏',
'拨烦去冰释',
'未似尸乡翁',
'拘留盖阡陌',
],
},
{
title: '园官送菜',
body: [
'清晨蒙菜把',
'常荷地主恩',
'守者愆实数',
'略有其名存',
'苦苣刺如针',
'马齿叶亦繁',
'青青嘉蔬色',
'埋没在中园',
'园吏未足怪',
'世事固堪论',
'呜呼战伐久',
'荆棘暗长原',
'乃知苦苣辈',
'倾夺蕙草根',
'小人塞道路',
'为态何喧喧',
'又如马齿盛',
'气拥葵荏昏',
'点染不易虞',
'丝麻杂罗纨',
'一经器物内',
'永挂粗刺痕',
'志士采紫芝',
'放歌避戎轩',
'畦丁负笼至',
'感动百虑端',
],
},
{
title: '上后园山脚',
body: [
'朱夏热所婴',
'清旭步北林',
'小园背高冈',
'挽葛上崎崟',
'旷望延驻目',
'飘摇散疏襟',
'潜鳞恨水壮',
'去翼依云深',
'勿谓地无疆',
'劣于山有阴',
'石榞遍天下',
'水陆兼浮沈',
'自我登陇首',
'十年经碧岑',
'剑门来巫峡',
'薄倚浩至今',
'故园暗戎马',
'骨肉失追寻',
'时危无消息',
'老去多归心',
'志士惜白日',
'久客藉黄金',
'敢为苏门啸',
'庶作梁父吟',
],
},
{
title: '驱竖子摘苍耳(即卷耳)',
body: [
'江上秋已分',
'林中瘴犹剧',
'畦丁告劳苦',
'无以供日夕',
'蓬莠独不焦',
'野蔬暗泉石',
'卷耳况疗风',
'童儿且时摘',
'侵星驱之去',
'烂熳任远适',
'放筐亭午际',
'洗剥相蒙幂',
'登床半生熟',
'下箸还小益',
'加点瓜薤间',
'依稀橘奴迹',
'乱世诛求急',
'黎民糠籺窄',
'饱食复何心',
'荒哉膏粱客',
'富家厨肉臭',
'战地骸骨白',
'寄语恶少年',
'黄金且休掷',
],
},
{
title: '秋行官张望督促东渚耗稻向毕清晨遣女奴阿稽竖子…往问',
body: [
'东渚雨今足',
'伫闻粳稻香',
'上天无偏颇',
'蒲稗各自长',
'人情见非类',
'田家戒其荒',
'功夫竞搰搰',
'除草置岸旁',
'谷者命之本',
'客居安可忘',
'青春具所务',
'勤垦免乱常',
'吴牛力容易',
'并驱动莫当',
'丰苗亦已穊',
'云水照方塘',
'有生固蔓延',
'静一资堤防',
'督领不无人',
'提携颇在纲',
'荆扬风土暖',
'肃肃候微霜',
'尚恐主守疏',
'用心未甚臧',
'清朝遣婢仆',
'寄语逾崇冈',
'西成聚必散',
'不独陵我仓',
'岂要仁里誉',
'感此乱世忙',
'北风吹蒹葭',
'蟋蟀近中堂',
'荏苒百工休',
'郁纡迟暮伤',
],
},
{
title: '阻雨不得归瀼西甘林',
body: [
'三伏适已过',
'骄阳化为霖',
'欲归瀼西宅',
'阻此江浦深',
'坏舟百版坼',
'峻岸复万寻',
'篙工初一弃',
'恐泥劳寸心',
'伫立东城隅',
'怅望高飞禽',
'草堂乱悬圃',
'不隔昆仑岑',
'昏浑衣裳外',
'旷绝同层阴',
'园甘长成时',
'三寸如黄金',
'诸侯旧上计',
'厥贡倾千林',
'邦人不足重',
'所迫豪吏侵',
'客居暂封殖',
'日夜偶瑶琴',
'虚徐五株态',
'侧塞烦胸襟',
'焉得辍两足',
'杖藜出岖嶔',
'条流数翠实',
'偃息归碧浔',
'拂拭乌皮几',
'喜闻樵牧音',
'令儿快搔背',
'脱我头上簪',
],
},
{
title: '雨',
body: [
'峡云行清晓',
'烟雾相裴回',
'风吹苍江树',
'雨洒石壁来',
'凄凄生馀寒',
'殷殷兼出雷',
'白谷变气候',
'朱炎安在哉',
'高鸟湿不下',
'居人门未开',
'楚宫久已灭',
'幽佩为谁哀',
'侍臣书王梦',
'赋有冠古才',
'冥冥翠龙驾',
'多自巫山台',
],
},
{
title: '雨二首',
body: [
'青山澹无姿',
'白露谁能数',
'片片水上云',
'萧萧沙中雨',
'殊俗状巢居',
'曾台俯风渚',
'佳客适万里',
'沈思情延伫',
'挂帆远色外',
'惊浪满吴楚',
'久阴蛟螭出',
'寇盗复几许',
'空山中宵阴',
'微冷先枕席',
'回风起清曙',
'万象萋已碧',
'落落出岫云',
'浑浑倚天石',
'日假何道行',
'雨含长江白',
'连樯荆州船',
'有士荷矛戟',
'南防草镇惨',
'沾湿赴远役',
'群盗下辟山',
'总戎备强敌',
'水深云光廓',
'鸣橹各有适',
'渔艇息悠悠',
'夷歌负樵客',
'留滞一老翁',
'书时记朝夕',
],
},
{
title: '晚登瀼上堂',
body: [
'故跻瀼岸高',
'颇免崖石拥',
'开襟野堂豁',
'系马林花动',
'雉堞粉如云',
'山田麦无垄',
'春气晚更生',
'江流静犹涌',
'四序婴我怀',
'群盗久相踵',
'黎民困逆节',
'天子渴垂拱',
'所思注东北',
'深峡转修耸',
'衰老自成病',
'郎官未为冗',
'凄其望吕葛',
'不复梦周孔',
'济世数向时',
'斯人各枯冢',
'楚星南天黑',
'蜀月西雾重',
'安得随鸟翎',
'迫此惧将恐',
],
},
{
title: '又上后园山脚',
body: [
'昔我游山东',
'忆戏东岳阳',
'穷秋立日观',
'矫首望八荒',
'朱崖著毫发',
'碧海吹衣裳',
'蓐收困用事',
'玄冥蔚强梁',
'逝水自朝宗',
'镇名各其方',
'平原独憔悴',
'农力废耕桑',
'非关风露凋',
'曾是戍役伤',
'于时国用富',
'足以守边疆',
'朝廷任猛将',
'远夺戎虏场',
'到今事反覆',
'故老泪万行',
'龟蒙不复见',
'况乃怀旧乡',
'肺萎属久战',
'骨出热中肠',
'忧来杖匣剑',
'更上林北冈',
'瘴毒猿鸟落',
'峡干南日黄',
'秋风亦已起',
'江汉始如汤',
'登高欲有往',
'荡析川无梁',
'哀彼远征人',
'去家死路旁',
'不及祖父茔',
'累累冢相当',
],
},
{
title: '雨',
body: [
'山雨不作泥',
'江云薄为雾',
'晴飞半岭鹤',
'风乱平沙树',
'明灭洲景微',
'隐见岩姿露',
'拘闷出门游',
'旷绝经目趣',
'消中日伏枕',
'卧久尘及屦',
'岂无平肩舆',
'莫辨望乡路',
'兵戈浩未息',
'蛇虺反相顾',
'悠悠边月破',
'郁郁流年度',
'针灸阻朋曹',
'糠籺对童孺',
'一命须屈色',
'新知渐成故',
'穷荒益自卑',
'飘泊欲谁诉',
'尪羸愁应接',
'俄顷恐违迕',
'浮俗何万端',
'幽人有独步',
'庞公竟独往',
'尚子终罕遇',
'宿留洞庭秋',
'天寒潇湘素',
'杖策可入舟',
'送此齿发暮',
],
},
{
title: '甘林',
body: [
'舍舟越西冈',
'入林解我衣',
'青刍适马性',
'好鸟知人归',
'晨光映远岫',
'夕露见日晞',
'迟暮少寝食',
'清旷喜荆扉',
'经过倦俗态',
'在野无所违',
'试问甘藜藿',
'未肯羡轻肥',
'喧静不同科',
'出处各天机',
'勿矜朱门是',
'陋此白屋非',
'明朝步邻里',
'长老可以依',
'时危赋敛数',
'脱粟为尔挥',
'相携行豆田',
'秋花霭菲菲',
'子实不得吃',
'货市送王畿',
'尽添军旅用',
'迫此公家威',
'主人长跪问',
'戎马何时稀',
'我衰易悲伤',
'屈指数贼围',
'劝其死王命',
'慎莫远奋飞',
],
},
{
title: '雨',
body: [
'行云递崇高',
'飞雨霭而至',
'潺潺石间溜',
'汩汩松上驶',
'亢阳乘秋热',
'百谷皆已弃',
'皇天德泽降',
'焦卷有生意',
'前雨伤卒暴',
'今雨喜容易',
'不可无雷霆',
'间作鼓增气',
'佳声达中宵',
'所望时一致',
'清霜九月天',
'仿佛见滞穗',
'郊扉及我私',
'我圃日苍翠',
'恨无抱瓮力',
'庶减临江费',
],
},
{
title: '种莴苣',
body: [
'阴阳一错乱',
'骄蹇不复理',
'枯旱于其中',
'炎方惨如毁',
'植物半蹉跎',
'嘉生将已矣',
'云雷欻奔命',
'师伯集所使',
'指麾赤白日',
'澒洞青光起',
'雨声先已风',
'散足尽西靡',
'山泉落沧江',
'霹雳犹在耳',
'终朝纡飒沓',
'信宿罢潇洒',
'堂下可以畦',
'呼童对经始',
'苣兮蔬之常',
'随事艺其子',
'破块数席间',
'荷锄功易止',
'两旬不甲坼',
'空惜埋泥滓',
'野苋迷汝来',
'宗生实于此',
'此辈岂无秋',
'亦蒙寒露委',
'翻然出地速',
'滋蔓户庭毁',
'因知邪干正',
'掩抑至没齿',
'贤良虽得禄',
'守道不封己',
'拥塞败芝兰',
'众多盛荆杞',
'中园陷萧艾',
'老圃永为耻',
'登于白玉盘',
'藉以如霞绮',
'苋也无所施',
'胡颜入筐篚',
],
},
{
title: '暇日小园散病,将种秋菜,督勒耕牛,兼书触目',
body: [
'不爱入州府',
'畏人嫌我真',
'及乎归茅宇',
'旁舍未曾嗔',
'老病忌拘束',
'应接丧精神',
'江村意自放',
'林木心所欣',
'秋耕属地湿',
'山雨近甚匀',
'冬菁饭之半',
'牛力晚来新',
'深耕种数亩',
'未甚后四邻',
'嘉蔬既不一',
'名数颇具陈',
'荆巫非苦寒',
'采撷接青春',
'飞来两白鹤',
'暮啄泥中芹',
'雄者左翮垂',
'损伤已露筋',
'一步再流血',
'尚经矰缴勤',
'三步六号叫',
'志屈悲哀频',
'鸾皇不相待',
'侧颈诉高旻',
'杖藜俯沙渚',
'为汝鼻酸辛',
],
},
{
title: '八哀诗。赠司空王公思礼',
body: [
'司空出东夷',
'童稚刷劲翮',
'追随燕蓟儿',
'颖锐物不隔',
'服事哥舒翰',
'意无流沙碛',
'未甚拔行间',
'犬戎大充斥',
'短小精悍姿',
'屹然强寇敌',
'贯穿百万众',
'出入由咫尺',
'马鞍悬将首',
'甲外控鸣镝',
'洗剑青海水',
'刻铭天山石',
'九曲非外蕃',
'其王转深壁',
'飞兔不近驾',
'鸷鸟资远击',
'晓达兵家流',
'饱闻春秋癖',
'胸襟日沈静',
'肃肃自有适',
'潼关初溃散',
'万乘犹辟易',
'偏裨无所施',
'元帅见手格',
'太子入朔方',
'至尊狩梁益',
'胡马缠伊洛',
'中原气甚逆',
'肃宗登宝位',
'塞望势敦迫',
'公时徒步至',
'请罪将厚责',
'际会清河公',
'间道传玉册',
'天王拜跪毕',
'谠议果冰释',
'翠华卷飞雪',
'熊虎亘阡陌',
'屯兵凤凰山',
'帐殿泾渭辟',
'金城贼咽喉',
'诏镇雄所搤',
'禁暴清无双',
'爽气春淅沥',
'巷有从公歌',
'野多青青麦',
'及夫哭庙后',
'复领太原役',
'恐惧禄位高',
'怅望王土窄',
'不得见清时',
'呜呼就窀穸',
'永系五湖舟',
'悲甚田横客',
'千秋汾晋间',
'事与云水白',
'昔观文苑传',
'岂述廉蔺绩',
'嗟嗟邓大夫',
'士卒终倒戟',
],
},
{
title: '八哀诗。故司徒李公光弼',
body: [
'司徒天宝末',
'北收晋阳甲',
'胡骑攻吾城',
'愁寂意不惬',
'人安若泰山',
'蓟北断右胁',
'朔方气乃苏',
'黎首见帝业',
'二宫泣西郊',
'九庙起颓压',
'未散河阳卒',
'思明伪臣妾',
'复自碣石来',
'火焚乾坤猎',
'高视笑禄山',
'公又大献捷',
'异王册崇勋',
'小敌信所怯',
'拥兵镇河汴',
'千里初妥帖',
'青蝇纷营营',
'风雨秋一叶',
'内省未入朝',
'死泪终映睫',
'大屋去高栋',
'长城扫遗堞',
'平生白羽扇',
'零落蛟龙匣',
'雅望与英姿',
'恻怆槐里接',
'三军晦光彩',
'烈士痛稠叠',
'直笔在史臣',
'将来洗箱箧',
'吾思哭孤冢',
'南纪阻归楫',
'扶颠永萧条',
'未济失利涉',
'疲苶竟何人',
'洒涕巴东峡',
],
},
{
title: '八哀诗。赠左仆射郑国公严公武',
body: [
'郑公瑚琏器',
'华岳金天晶',
'昔在童子日',
'已闻老成名',
'嶷然大贤后',
'复见秀骨清',
'开口取将相',
'小心事友生',
'阅书百纸尽',
'落笔四座惊',
'历职匪父任',
'嫉邪常力争',
'汉仪尚整肃',
'胡骑忽纵横',
'飞传自河陇',
'逢人问公卿',
'不知万乘出',
'雪涕风悲鸣',
'受词剑阁道',
'谒帝萧关城',
'寂寞云台仗',
'飘飖沙塞旌',
'江山少使者',
'笳鼓凝皇情',
'壮士血相视',
'忠臣气不平',
'密论贞观体',
'挥发岐阳征',
'感激动四极',
'联翩收二京',
'西郊牛酒再',
'原庙丹青明',
'匡汲俄宠辱',
'卫霍竟哀荣',
'四登会府地',
'三掌华阳兵',
'京兆空柳色',
'尚书无履声',
'群乌自朝夕',
'白马休横行',
'诸葛蜀人爱',
'文翁儒化成',
'公来雪山重',
'公去雪山轻',
'记室得何逊',
'韬钤延子荆',
'四郊失壁垒',
'虚馆开逢迎',
'堂上指图画',
'军中吹玉笙',
'岂无成都酒',
'忧国只细倾',
'时观锦水钓',
'问俗终相并',
'意待犬戎灭',
'人藏红粟盈',
'以兹报主愿',
'庶或裨世程',
'炯炯一心在',
'沉沉二竖婴',
'颜回竟短折',
'贾谊徒忠贞',
'飞旐出江汉',
'孤舟轻荆衡',
'虚无马融笛',
'怅望龙骧茔',
'空馀老宾客',
'身上愧簪缨',
],
},
{
title: '八哀诗。赠太子太师汝阳郡王琎',
body: [
'汝阳让帝子',
'眉宇真天人',
'虬须似太宗',
'色映塞外春',
'往者开元中',
'主恩视遇频',
'出入独非时',
'礼异见群臣',
'爱其谨洁极',
'倍此骨肉亲',
'从容听朝后',
'或在风雪晨',
'忽思格猛兽',
'苑囿腾清尘',
'羽旗动若一',
'万马肃駪駪',
'诏王来射雁',
'拜命已挺身',
'箭出飞鞚内',
'上又回翠麟',
'翻然紫塞翮',
'下拂明月轮',
'胡人虽获多',
'天笑不为新',
'王每中一物',
'手自与金银',
'袖中谏猎书',
'扣马久上陈',
'竟无衔橛虞',
'圣聪矧多仁',
'官免供给费',
'水有在藻鳞',
'匪唯帝老大',
'皆是王忠勤',
'晚年务置醴',
'门引申白宾',
'道大容无能',
'永怀侍芳茵',
'好学尚贞烈',
'义形必沾巾',
'挥翰绮绣扬',
'篇什若有神',
'川广不可溯',
'墓久狐兔邻',
'宛彼汉中郡',
'文雅见天伦',
'何以开我悲',
'泛舟俱远津',
'温温昔风味',
'少壮已书绅',
'旧游易磨灭',
'衰谢增酸辛',
],
},
{
title: '八哀诗。赠秘书监江夏李公邕',
body: [
'长啸宇宙间',
'高才日陵替',
'古人不可见',
'前辈复谁继',
'忆昔李公存',
'词林有根柢',
'声华当健笔',
'洒落富清制',
'风流散金石',
'追琢山岳锐',
'情穷造化理',
'学贯天人际',
'干谒走其门',
'碑版照四裔',
'各满深望还',
'森然起凡例',
'萧萧白杨路',
'洞彻宝珠惠',
'龙宫塔庙涌',
'浩劫浮云卫',
'宗儒俎豆事',
'故吏去思计',
'眄睐已皆虚',
'跋涉曾不泥',
'向来映当时',
'岂独劝后世',
'丰屋珊瑚钩',
'骐驎织成罽',
'紫骝随剑几',
'义取无虚岁',
'分宅脱骖间',
'感激怀未济',
'众归赒给美',
'摆落多藏秽',
'独步四十年',
'风听九皋唳',
'呜呼江夏姿',
'竟掩宣尼袂',
'往者武后朝',
'引用多宠嬖',
'否臧太常议',
'面折二张势',
'衰俗凛生风',
'排荡秋旻霁',
'忠贞负冤恨',
'宫阙深旒缀',
'放逐早联翩',
'低垂困炎厉',
'日斜鵩鸟入',
'魂断苍梧帝',
'荣枯走不暇',
'星驾无安税',
'几分汉廷竹',
'夙拥文侯篲',
'终悲洛阳狱',
'事近小臣敝',
'祸阶初负谤',
'易力何深哜',
'伊昔临淄亭',
'酒酣托末契',
'重叙东都别',
'朝阴改轩砌',
'论文到崔苏',
'指尽流水逝',
'近伏盈川雄',
'未甘特进丽',
'是非张相国',
'相扼一危脆',
'争名古岂然',
'键捷欻不闭',
'例及吾家诗',
'旷怀扫氛翳',
'慷慨嗣真作',
'咨嗟玉山桂',
'钟律俨高悬',
'鲲鲸喷迢递',
'坡陀青州血',
'芜没汶阳瘗',
'哀赠竟萧条',
'恩波延揭厉',
'子孙存如线',
'旧客舟凝滞',
'君臣尚论兵',
'将帅接燕蓟',
'朗吟六公篇',
'忧来豁蒙蔽',
],
},
{
title: '八哀诗。故秘书少监武功苏公源明',
body: [
'武功少也孤',
'徒步客徐兖',
'读书东岳中',
'十载考坟典',
'时下莱芜郭',
'忍饥浮云巘',
'负米晚为身',
'每食脸必泫',
'夜字照爇薪',
'垢衣生碧藓',
'庶以勤苦志',
'报兹劬劳显',
'学蔚醇儒姿',
'文包旧史善',
'洒落辞幽人',
'归来潜京辇',
'射君东堂策',
'宗匠集精选',
'制可题未干',
'乙科已大阐',
'文章日自负',
'吏禄亦累践',
'晨趋阊阖内',
'足蹋宿昔趼',
'一麾出守还',
'黄屋朔风卷',
'不暇陪八骏',
'虏庭悲所遣',
'平生满尊酒',
'断此朋知展',
'忧愤病二秋',
'有恨石可转',
'肃宗复社稷',
'得无逆顺辨',
'范晔顾其儿',
'李斯忆黄犬',
'秘书茂松意',
'溟涨本末浅',
'青荧芙蓉剑',
'犀兕岂独剸',
'反为后辈亵',
'予实苦怀缅',
'煌煌斋房芝',
'事绝万手搴',
'垂之俟来者',
'正始征劝勉',
'不要悬黄金',
'胡为投乳rP',
'结交三十载',
'吾与谁游衍',
'荥阳复冥莫',
'罪罟已横罥',
'呜呼子逝日',
'始泰则终蹇',
'长安米万钱',
'凋丧尽馀喘',
'战伐何当解',
'归帆阻清沔',
'尚缠漳水疾',
'永负蒿里饯',
],
},
{
title: '八哀诗。故著作郎贬台州司户荥阳郑公虔',
body: [
'鶢鶋至鲁门',
'不识钟鼓飨',
'孔翠望赤霄',
'愁思雕笼养',
'荥阳冠众儒',
'早闻名公赏',
'地崇士大夫',
'况乃气精爽',
'天然生知姿',
'学立游夏上',
'神农极阙漏',
'黄石愧师长',
'药纂西极名',
'兵流指诸掌',
'贯穿无遗恨',
'荟蕞何技痒',
'圭臬星经奥',
'虫篆丹青广',
'子云窥未遍',
'方朔谐太枉',
'神翰顾不一',
'体变钟兼两',
'文传天下口',
'大字犹在榜',
'昔献书画图',
'新诗亦俱往',
'沧洲动玉陛',
'宣鹤误一响',
'三绝自御题',
'四方尤所仰',
'嗜酒益疏放',
'弹琴视天壤',
'形骸实土木',
'亲近唯几杖',
'未曾寄官曹',
'突兀倚书幌',
'晚就芸香阁',
'胡尘昏坱莽',
'反覆归圣朝',
'点染无涤荡',
'老蒙台州掾',
'泛泛浙江桨',
'覆穿四明雪',
'饥拾楢溪橡',
'空闻紫芝歌',
'不见杏坛丈',
'天长眺东南',
'秋色馀魍魉',
'别离惨至今',
'斑白徒怀曩',
'春深秦山秀',
'叶坠清渭朗',
'剧谈王侯门',
'野税林下鞅',
'操纸终夕酣',
'时物集遐想',
'词场竟疏阔',
'平昔滥吹奖',
'百年见存殁',
'牢落吾安放',
'萧条阮咸在',
'出处同世网',
'他日访江楼',
'含凄述飘荡',
],
},
{
title: '八哀诗。故右仆射相国张公九龄',
body: [
'相国生南纪',
'金璞无留矿',
'仙鹤下人间',
'独立霜毛整',
'矫然江海思',
'复与云路永',
'寂寞想土阶',
'未遑等箕颍',
'上君白玉堂',
'倚君金华省',
'碣石岁峥嵘',
'天地日蛙黾',
'退食吟大庭',
'何心记榛梗',
'骨惊畏曩哲',
'鬒变负人境',
'虽蒙换蝉冠',
'右地恧多幸',
'敢忘二疏归',
'痛迫苏耽井',
'紫绶映暮年',
'荆州谢所领',
'庾公兴不浅',
'黄霸镇每静',
'宾客引调同',
'讽咏在务屏',
'诗罢地有馀',
'篇终语清省',
'一阳发阴管',
'淑气含公鼎',
'乃知君子心',
'用才文章境',
'散帙起翠螭',
'倚薄巫庐并',
'绮丽玄晖拥',
'笺诔任昉骋',
'自我一家则',
'未缺只字警',
'千秋沧海南',
'名系朱鸟影',
'归老守故林',
'恋阙悄延颈',
'波涛良史笔',
'芜绝大庾岭',
'向时礼数隔',
'制作难上请',
'再读徐孺碑',
'犹思理烟艇',
],
},
{
title: '写怀二首',
body: [
'劳生共乾坤',
'何处异风俗',
'冉冉自趋竞',
'行行见羁束',
'无贵贱不悲',
'无富贫亦足',
'万古一骸骨',
'邻家递歌哭',
'鄙夫到巫峡',
'三岁如转烛',
'全命甘留滞',
'忘情任荣辱',
'朝班及暮齿',
'日给还脱粟',
'编蓬石城东',
'采药山北谷',
'用心霜雪间',
'不必条蔓绿',
'非关故安排',
'曾是顺幽独',
'达士如弦直',
'小人似钩曲',
'曲直我不知',
'负暄候樵牧',
'夜深坐南轩',
'明月照我膝',
'惊风翻河汉',
'梁栋已出日',
'群生各一宿',
'飞动自俦匹',
'吾亦驱其儿',
'营营为私实',
'天寒行旅稀',
'岁暮日月疾',
'荣名忽中人',
'世乱如虮虱',
'古者三皇前',
'满腹志愿毕',
'胡为有结绳',
'陷此胶与漆',
'祸首燧人氏',
'厉阶董狐笔',
'君看灯烛张',
'转使飞蛾密',
'放神八极外',
'俯仰俱萧瑟',
'终契如往还',
'得匪合仙术',
],
},
{
title: '可叹',
body: [
'天上浮云如白衣',
'斯须改变如苍狗',
'古往今来共一时',
'人生万事无不有',
'近者抉眼去其夫',
'河东女儿身姓柳',
'丈夫正色动引经',
'酆城客子王季友',
'群书万卷常暗诵',
'孝经一通看在手',
'贫穷老瘦家卖屐',
'好事就之为携酒',
'豫章太守高帝孙',
'引为宾客敬颇久',
'闻道三年未曾语',
'小心恐惧闭其口',
'太守得之更不疑',
'人生反覆看亦丑',
'明月无瑕岂容易',
'紫气郁郁犹冲斗',
'时危可仗真豪俊',
'二人得置君侧否',
'太守顷者领山南',
'邦人思之比父母',
'王生早曾拜颜色',
'高山之外皆培塿',
'用为羲和天为成',
'用平水土地为厚',
'王也论道阻江湖',
'李也丞疑旷前后',
'死为星辰终不灭',
'致君尧舜焉肯朽',
'吾辈碌碌饱饭行',
'风后力牧长回首',
],
},
{
title: '观公孙大娘弟子舞剑器行',
body: [
'昔有佳人公孙氏',
'一舞剑气动四方',
'观者如山色沮丧',
'天地为之久低昂',
'z8如羿射九日落',
'矫如群帝骖龙翔',
'来如雷霆收震怒',
'罢如江海凝清光',
'绛唇珠袖两寂寞',
'况有弟子传芬芳',
'临颍美人在白帝',
'妙舞此曲神扬扬',
'与余问答既有以',
'感时抚事增惋伤',
'先帝侍女八千人',
'公孙剑器初第一',
'五十年间似反掌',
'风尘倾动昏王室',
'梨园子弟散如烟',
'女乐馀姿映寒日',
'金粟堆南木已拱',
'瞿唐石城草萧瑟',
'玳筵急管曲复终',
'乐极哀来月东出',
'老夫不知其所往',
'足茧荒山转愁疾',
],
},
{
title: '往在',
body: [
'往在西京日',
'胡来满彤宫',
'中宵焚九庙',
'云汉为之红',
'解瓦飞十里',
'繐帷纷曾空',
'疚心惜木主',
'一一灰悲风',
'合昏排铁骑',
'清旭散锦eL',
'贼臣表逆节',
'相贺以成功',
'是时妃嫔戮',
'连为粪土丛',
'当宁陷玉座',
'白间剥画虫',
'不知二圣处',
'私泣百岁翁',
'车驾既云还',
'楹桷欻穹崇',
'故老复涕泗',
'祠官树椅桐',
'宏壮不如初',
'已见帝力雄',
'前春礼郊庙',
'祀事亲圣躬',
'微躯忝近臣',
'景从陪群公',
'登阶捧玉册',
'峨冕耿金钟',
'侍祠恧先露',
'掖垣迩濯龙',
'天子惟孝孙',
'五云起九重',
'镜奁换粉黛',
'翠羽犹葱胧',
'前者厌羯胡',
'后来遭犬戎',
'俎豆腐膻肉',
'罘罳行角弓',
'安得自西极',
'申命空山东',
'尽驱诣阙下',
'士庶塞关中',
'主将晓逆顺',
'元元归始终',
'一朝自罪己',
'万里车书通',
'锋镝供锄犁',
'征戍听所从',
'冗官各复业',
'土著还力农',
'君臣节俭足',
'朝野欢呼同',
'中兴似国初',
'继体如太宗',
'端拱纳谏诤',
'和风日冲融',
'赤墀樱桃枝',
'隐映银丝笼',
'千春荐陵寝',
'永永垂无穷',
'京都不再火',
'泾渭开愁容',
'归号故松柏',
'老去苦飘蓬',
],
},
{
title: '昔游',
body: [
'昔者与高李',
'晚登单父台',
'寒芜际碣石',
'万里风云来',
'桑柘叶如雨',
'飞藿去裴回',
'清霜大泽冻',
'禽兽有馀哀',
'是时仓廪实',
'洞达寰区开',
'猛士思灭胡',
'将帅望三台',
'君王无所惜',
'驾驭英雄材',
'幽燕盛用武',
'供给亦劳哉',
'吴门转粟帛',
'泛海陵蓬莱',
'肉食三十万',
'猎射起黄埃',
'隔河忆长眺',
'青岁已摧颓',
'不及少年日',
'无复故人杯',
'赋诗独流涕',
'乱世想贤才',
'有能市骏骨',
'莫恨少龙媒',
'商山议得失',
'蜀主脱嫌猜',
'吕尚封国邑',
'傅说已盐梅',
'景晏楚山深',
'水鹤去低回',
'庞公任本性',
'携子卧苍苔',
],
},
{
title: '壮游',
body: [
'往昔十四五',
'出游翰墨场',
'斯文崔魏徒',
'以我似班扬',
'七龄思即壮',
'开口咏凤凰',
'九龄书大字',
'有作成一囊',
'性豪业嗜酒',
'嫉恶怀刚肠',
'脱略小时辈',
'结交皆老苍',
'饮酣视八极',
'俗物都茫茫',
'东下姑苏台',
'已具浮海航',
'到今有遗恨',
'不得穷扶桑',
'王谢风流远',
'阖庐丘墓荒',
'剑池石壁仄',
'长洲荷芰香',
'嵯峨阊门北',
'清庙映回塘',
'每趋吴太伯',
'抚事泪浪浪',
'枕戈忆勾践',
'渡浙想秦皇',
'蒸鱼闻匕首',
'除道哂要章',
'越女天下白',
'鉴湖五月凉',
'剡溪蕴秀异',
'欲罢不能忘',
'归帆拂天姥',
'中岁贡旧乡',
'气劘屈贾垒',
'目短曹刘墙',
'忤下考功第',
'独辞京尹堂',
'放荡齐赵间',
'裘马颇清狂',
'春歌丛台上',
'冬猎青丘旁',
'呼鹰皂枥林',
'逐兽云雪冈',
'射飞曾纵鞚',
'引臂落鹙鶬',
'苏侯据鞍喜',
'忽如携葛强',
'快意八九年',
'西归到咸阳',
'许与必词伯',
'赏游实贤王',
'曳裾置醴地',
'奏赋入明光',
'天子废食召',
'群公会轩裳',
'脱身无所爱',
'痛饮信行藏',
'黑貂不免敝',
'斑鬓兀称觞',
'杜曲晚耆旧',
'四郊多白杨',
'坐深乡党敬',
'日觉死生忙',
'朱门任倾夺',
'赤族迭罹殃',
'国马竭粟豆',
'官鸡输稻粱',
'举隅见烦费',
'引古惜兴亡',
'河朔风尘起',
'岷山行幸长',
'两宫各警跸',
'万里遥相望',
'崆峒杀气黑',
'少海旌旗黄',
'禹功亦命子',
'涿鹿亲戎行',
'翠华拥英岳',
'螭虎啖豺狼',
'爪牙一不中',
'胡兵更陆梁',
'大军载草草',
'凋瘵满膏肓',
'备员窃补衮',
'忧愤心飞扬',
'上感九庙焚',
'下悯万民疮',
'斯时伏青蒲',
'廷争守御床',
'君辱敢爱死',
'赫怒幸无伤',
'圣哲体仁恕',
'宇县复小康',
'哭庙灰烬中',
'鼻酸朝未央',
'小臣议论绝',
'老病客殊方',
'郁郁苦不展',
'羽翮困低昂',
'秋风动哀壑',
'碧蕙捐微芳',
'之推避赏从',
'渔父濯沧浪',
'荣华敌勋业',
'岁暮有严霜',
'吾观鸱夷子',
'才格出寻常',
'群凶逆未定',
'侧伫英俊翔',
],
},
{
title: '遣怀',
body: [
'昔我游宋中',
'惟梁孝王都',
'名今陈留亚',
'剧则贝魏俱',
'邑中九万家',
'高栋照通衢',
'舟车半天下',
'主客多欢娱',
'白刃雠不义',
'黄金倾有无',
'杀人红尘里',
'报答在斯须',
'忆与高李辈',
'论交入酒垆',
'两公壮藻思',
'得我色敷腴',
'气酣登吹台',
'怀古视平芜',
'芒砀云一去',
'雁鹜空相呼',
'先帝正好武',
'寰海未凋枯',
'猛将收西域',
'长戟破林胡',
'百万攻一城',
'献捷不云输',
'组练弃如泥',
'尺土负百夫',
'拓境功未已',
'元和辞大炉',
'乱离朋友尽',
'合沓岁月徂',
'吾衰将焉托',
'存殁再呜呼',
'萧条益堪愧',
'独在天一隅',
'乘黄已去矣',
'凡马徒区区',
'不复见颜鲍',
'系舟卧荆巫',
'临餐吐更食',
'常恐违抚孤',
],
},
{
title: '同元使君舂陵行',
body: [
'遭乱发尽白',
'转衰病相婴',
'沈绵盗贼际',
'狼狈江汉行',
'叹时药力薄',
'为客羸瘵成',
'吾人诗家秀',
'博采世上名',
'粲粲元道州',
'前圣畏后生',
'观乎舂陵作',
'欻见俊哲情',
'复览贼退篇',
'结也实国桢',
'贾谊昔流恸',
'匡衡常引经',
'道州忧黎庶',
'词气浩纵横',
'两章对秋月',
'一字偕华星',
'致君唐虞际',
'纯朴忆大庭',
'何时降玺书',
'用尔为丹青',
'狱讼永衰息',
'岂唯偃甲兵',
'凄恻念诛求',
'薄敛近休明',
'乃知正人意',
'不苟飞长缨',
'凉飙振南岳',
'之子宠若惊',
'色阻金印大',
'兴含沧浪清',
'我多长卿病',
'日夕思朝廷',
'肺枯渴太甚',
'漂泊公孙城',
'呼儿具纸笔',
'隐几临轩楹',
'作诗呻吟内',
'墨澹字欹倾',
'感彼危苦词',
'庶几知者听',
],
},
{
title: '李潮八分小篆歌',
body: [
'苍颉鸟迹既茫昧',
'字体变化如浮云',
'陈仓石鼓又已讹',
'大小二篆生八分',
'秦有李斯汉蔡邕',
'中间作者寂不闻',
'峄山之碑野火焚',
'枣木传刻肥失真',
'苦县光和尚骨立',
'书贵瘦硬方通神',
'惜哉李蔡不复得',
'吾甥李潮下笔亲',
'尚书韩择木',
'骑曹蔡有邻',
'开元已来数八分',
'潮也奄有二子成三人',
'况潮小篆逼秦相',
'快剑长戟森相向',
'八分一字直百金',
'蛟龙盘拏肉屈强',
'吴郡张颠夸草书',
'草书非古空雄壮',
'岂如吾甥不流宕',
'丞相中郎丈人行',
'巴东逢李潮',
'逾月求我歌',
'我今衰老才力薄',
'潮乎潮乎奈汝何',
],
},
{
title: '览柏中允兼子侄数人除官制词因述父子兄弟四美载歌丝纶',
body: [
'纷然丧乱际',
'见此忠孝门',
'蜀中寇亦甚',
'柏氏功弥存',
'深诚补王室',
'戮力自元昆',
'三止锦江沸',
'独清玉垒昏',
'高名入竹帛',
'新渥照乾坤',
'子弟先卒伍',
'芝兰叠玙璠',
'同心注师律',
'洒血在戎轩',
'丝纶实具载',
'绂冕已殊恩',
'奉公举骨肉',
'诛叛经寒温',
'金甲雪犹冻',
'朱旗尘不翻',
'每闻战场说',
'欻激懦气奔',
'圣主国多盗',
'贤臣官则尊',
'方当节钺用',
'必绝祲沴根',
'吾病日回首',
'云台谁再论',
'作歌挹盛事',
'推毂期孤鶱',
],
},
{
title: '听杨氏歌',
body: [
'佳人绝代歌',
'独立发皓齿',
'满堂惨不乐',
'响下清虚里',
'江城带素月',
'况乃清夜起',
'老夫悲暮年',
'壮士泪如水',
'玉杯久寂寞',
'金管迷宫徵',
'勿云听者疲',
'愚智心尽死',
'古来杰出士',
'岂待一知己',
'吾闻昔秦青',
'倾侧天下耳',
],
},
{
title: '荆南兵马使太常卿赵公大食刀歌',
body: [
'太常楼船声嗷嘈',
'问兵刮寇趋下牢',
'牧出令奔飞百艘',
'猛蛟突兽纷腾逃',
'白帝寒城驻锦袍',
'玄冬示我胡国刀',
'壮士短衣头虎毛',
'凭轩拔鞘天为高',
'翻风转日木怒号',
'冰翼雪澹伤哀猱',
'镌错碧罂鸊鹈膏',
'铓锷已莹虚秋涛',
'鬼物撇捩辞坑壕',
'苍水使者扪赤绦',
'龙伯国人罢钓鳌',
'芮公回首颜色劳',
'分阃救世用贤豪',
'赵公玉立高歌起',
'揽环结佩相终始',
'万岁持之护天子',
'得君乱丝与君理',
'蜀江如线如针水',
'荆岑弹丸心未已',
'贼臣恶子休干纪',
'魑魅魍魉徒为耳',
'妖腰乱领敢欣喜',
'用之不高亦不庳',
'不似长剑须天倚',
'吁嗟光禄英雄弭',
'大食宝刀聊可比',
'丹青宛转麒麟里',
'光芒六合无泥滓',
],
},
{
title: '王兵马使二角鹰',
body: [
'悲台萧飒石巃嵸',
'哀壑杈桠浩呼汹',
'中有万里之长江',
'回风滔日孤光动',
'角鹰翻倒壮士臂',
'将军玉帐轩翠气',
'二鹰猛脑徐侯穟',
'目如愁胡视天地',
'杉鸡竹兔不自惜',
'溪虎野羊俱辟易',
'鞲上锋棱十二翮',
'将军勇锐与之敌',
'将军树勋起安西',
'昆仑虞泉入马蹄',
'白羽曾肉三狻猊',
'敢决岂不与之齐',
'荆南芮公得将军',
'亦如角鹰下翔云',
'恶鸟飞飞啄金屋',
'安得尔辈开其群',
'驱出六合枭鸾分',
],
},
{
title: '狄明府(博济。一作寄狄明府)',
body: [
'梁公曾孙我姨弟',
'不见十年官济济',
'大贤之后竟陵迟',
'浩荡古今同一体',
'比看叔伯四十人',
'有才无命百寮底',
'今者兄弟一百人',
'几人卓绝秉周礼',
'在汝更用文章为',
'长兄白眉复天启',
'汝门请从曾翁说',
'太后当朝多巧诋',
'狄公执政在末年',
'浊河终不污清济',
'国嗣初将付诸武',
'公独廷诤守丹陛',
'禁中决册请房陵',
'前朝长老皆流涕',
'太宗社稷一朝正',
'汉官威仪重昭洗',
'时危始识不世才',
'谁谓荼苦甘如荠',
'汝曹又宜列土食',
'身使门户多旌棨',
'胡为漂泊岷汉间',
'干谒王侯颇历抵',
'况乃山高水有波',
'秋风萧萧露泥泥',
'虎之饥',
'下巉岩',
'蛟之横',
'出清泚',
'早归来',
'黄土泥衣眼易眯',
],
},
{
title: '秋风二首',
body: [
'秋风淅淅吹巫山',
'上牢下牢修水关',
'吴樯楚柁牵百丈',
'暖向神都寒未还',
'要路何日罢长戟',
'战自青羌连百蛮',
'中巴不曾消息好',
'暝传戍鼓长云间',
'秋风淅淅吹我衣',
'东流之外西日微',
'天清小城捣练急',
'石古细路行人稀',
'不知明月为谁好',
'早晚孤帆他夜归',
'会将白发倚庭树',
'故园池台今是非',
],
},
{
title: '久雨期王将军不至',
body: [
'天雨萧萧滞茅屋',
'空山无以慰幽独',
'锐头将军来何迟',
'令我心中苦不足',
'数看黄雾乱玄云',
'时听严风折乔木',
'泉源泠泠杂猿狖',
'泥泞漠漠饥鸿鹄',
'岁暮穷阴耿未已',
'人生会面难再得',
'忆尔腰下铁丝箭',
'射杀林中雪色鹿',
'前者坐皮因问毛',
'知子历险人马劳',
'异兽如飞星宿落',
'应弦不碍苍山高',
'安得突骑只五千',
'崒然眉骨皆尔曹',
'走平乱世相催促',
'一豁明主正郁陶',
'忆昔范增碎玉斗',
'未使吴兵著白袍',
'昏昏阊阖闭氛祲',
'十月荆南雷怒号',
],
},
{
title: '别李秘书始兴寺所居',
body: [
'不见秘书心若失',
'及见秘书失心疾',
'安为动主理信然',
'我独觉子神充实',
'重闻西方止观经',
'老身古寺风泠泠',
'妻儿待我且归去',
'他日杖藜来细听',
],
},
{
title: '虎牙行(虎牙在荆门之北,江水峻急)',
body: [
'秋风欻吸吹南国',
'天地惨惨无颜色',
'洞庭扬波江汉回',
'虎牙铜柱皆倾侧',
'巫峡阴岑朔漠气',
'峰峦窈窕谿谷黑',
'杜鹃不来猿狖寒',
'山鬼幽忧雪霜逼',
'楚老长嗟忆炎瘴',
'三尺角弓两斛力',
'壁立石城横塞起',
'金错旌竿满云直',
'渔阳突骑猎青丘',
'犬戎锁甲闻丹极',
'八荒十年防盗贼',
'征戍诛求寡妻哭',
'远客中宵泪沾臆',
],
},
{
title: '锦树行(因篇内有锦树二字摘以为题非正赋锦树也)',
body: [
'今日苦短昨日休',
'岁云暮矣增离忧',
'霜凋碧树待锦树',
'万壑东逝无停留',
'荒戍之城石色古',
'东郭老人住青丘',
'飞书白帝营斗粟',
'琴瑟几杖柴门幽',
'青草萋萋尽枯死',
'天马跂足随牦牛',
'自古圣贤多薄命',
'奸雄恶少皆封侯',
'故国三年一消息',
'终南渭水寒悠悠',
'五陵豪贵反颠倒',
'乡里小儿狐白裘',
'生男堕地要膂力',
'一生富贵倾邦国',
'莫愁父母少黄金',
'天下风尘儿亦得',
],
},
{
title: '赤霄行',
body: [
'孔雀未知牛有角',
'渴饮寒泉逢牴触',
'赤霄悬圃须往来',
'翠尾金花不辞辱',
'江中淘河吓飞燕',
'衔泥却落羞华屋',
'皇孙犹曾莲勺困',
'卫庄见贬伤其足',
'老翁慎莫怪少年',
'葛亮贵和书有篇',
'丈夫垂名动万年',
'记忆细故非高贤',
],
},
{
title: '前苦寒行二首',
body: [
'汉时长安雪一丈',
'牛马毛寒缩如猬',
'楚江巫峡冰入怀',
'虎豹哀号又堪记',
'秦城老翁荆扬客',
'惯习炎蒸岁絺绤',
'玄冥祝融气或交',
'手持白羽未敢释',
'去年白帝雪在山',
'今年白帝雪在地',
'冻埋蛟龙南浦缩',
'寒刮肌肤北风利',
'楚人四时皆麻衣',
'楚天万里无晶辉',
'三足之乌足恐断',
'羲和送将何所归',
],
},
{
title: '后苦寒行二首',
body: [
'南纪巫庐瘴不绝',
'太古以来无尺雪',
'蛮夷长老怨苦寒',
'昆仑天关冻应折',
'玄猿口噤不能啸',
'白鹄翅垂眼流血',
'安得春泥补地裂',
'晚来江门失大木',
'猛风中夜吹白屋',
'天兵斩断青海戎',
'杀气南行动地轴',
'不尔苦寒何太酷',
'巴东之峡生凌澌',
'彼苍回轩人得知',
],
},
{
title: '晚晴',
body: [
'高唐暮冬雪壮哉',
'旧瘴无复似尘埃',
'崖沉谷没白皑皑',
'江石缺裂青枫摧',
'南天三旬苦雾开',
'赤日照耀从西来',
'六龙寒急光裴回',
'照我衰颜忽落地',
'口虽吟咏心中哀',
'未怪及时少年子',
'扬眉结义黄金台',
'洎乎吾生何飘零',
'支离委绝同死灰',
],
},
{
title: '复阴',
body: [
'方冬合沓玄阴塞',
'昨日晚晴今日黑',
'万里飞蓬映天过',
'孤城树羽扬风直',
'江涛簸岸黄沙走',
'云雪埋山苍兕吼',
'君不见夔子之国杜陵翁',
'牙齿半落左耳聋',
],
},
{
title: '夜归',
body: [
'夜来归来冲虎过',
'山黑家中已眠卧',
'傍见北斗向江低',
'仰看明星当空大',
'庭前把烛嗔两炬',
'峡口惊猿闻一个',
'白头老罢舞复歌',
'杖藜不睡谁能那',
],
},
{
title: '寄柏学士林居',
body: [
'自胡之反持干戈',
'天下学士亦奔波',
'叹彼幽栖载典籍',
'萧然暴露依山阿',
'青山万里静散地',
'白雨一洗空垂萝',
'乱代飘零余到此',
'古人成败子如何',
'荆扬春冬异风土',
'巫峡日夜多云雨',
'赤叶枫林百舌鸣',
'黄泥野岸天鸡舞',
'盗贼纵横甚密迩',
'形神寂寞甘辛苦',
'几时高议排金门',
'各使苍生有环堵',
],
},
{
title: '寄从孙崇简',
body: [
'嵯峨白帝城东西',
'南有龙湫北虎溪',
'吾孙骑曹不骑马',
'业学尸乡多养鸡',
'庞公隐时尽室去',
'武陵春树他人迷',
'与汝林居未相失',
'近身药裹酒长携',
'牧竖樵童亦无赖',
'莫令斩断青云梯',
],
},
{
title: '奉酬薛十二丈判官见赠',
body: [
'忽忽峡中睡',
'悲风方一醒',
'西来有好鸟',
'为我下青冥',
'羽毛净白雪',
'惨澹飞云汀',
'既蒙主人顾',
'举翮唳孤亭',
'持以比佳士',
'及此慰扬舲',
'清文动哀玉',
'见道发新硎',
'欲学鸱夷子',
'待勒燕山铭',
'谁重断蛇剑',
'致君君未听',
'志在麒麟阁',
'无心云母屏',
'卓氏近新寡',
'豪家朱门扃',
'相如才调逸',
'银汉会双星',
'客来洗粉黛',
'日暮拾流萤',
'不是无膏火',
'劝郎勤六经',
'老夫自汲涧',
'野水日泠泠',
'我叹黑头白',
'君看银印青',
'卧病识山鬼',
'为农知地形',
'谁矜坐锦帐',
'苦厌食鱼腥',
'东西两岸坼',
'横水注沧溟',
'碧色忽惆怅',
'风雷搜百灵',
'空中右白虎',
'赤节引娉婷',
'自云帝里女',
'噀雨凤凰翎',
'襄王薄行迹',
'莫学冷如丁',
'千秋一拭泪',
'梦觉有微馨',
'人生相感动',
'金石两青荧',
'丈人但安坐',
'休辨渭与泾',
'龙蛇尚格斗',
'洒血暗郊坰',
'吾闻聪明主',
'治国用轻刑',
'销兵铸农器',
'今古岁方宁',
'文王日俭德',
'俊乂始盈庭',
'荣华贵少壮',
'岂食楚江萍',
],
},
{
title: '醉为马坠,诸公携酒相看',
body: [
'甫也诸侯老宾客',
'罢酒酣歌拓金戟',
'骑马忽忆少年时',
'散蹄迸落瞿塘石',
'白帝城门水云外',
'低身直下八千尺',
'粉堞电转紫游缰',
'东得平冈出天壁',
'江村野堂争入眼',
'垂鞭亸鞚凌紫陌',
'向来皓首惊万人',
'自倚红颜能骑射',
'安知决臆追风足',
'朱汗骖驔犹喷玉',
'不虞一蹶终损伤',
'人生快意多所辱',
'职当忧戚伏衾枕',
'况乃迟暮加烦促',
'明知来问腆我颜',
'杖藜强起依僮仆',
'语尽还成开口笑',
'提携别扫清溪曲',
'酒肉如山又一时',
'初筵哀丝动豪竹',
'共指西日不相贷',
'喧呼且覆杯中渌',
'何必走马来为问',
'君不见嵇康养生遭杀戮',
],
},
{
title: '别李义',
body: [
'神尧十八子',
'十七王其门',
'道国洎舒国',
'督唯亲弟昆',
'中外贵贱殊',
'余亦忝诸孙',
'丈人嗣三叶',
'之子白玉温',
'道国继德业',
'请从丈人论',
'丈人领宗卿',
'肃穆古制敦',
'先朝纳谏诤',
'直气横乾坤',
'子建文笔壮',
'河间经术存',
'尔克富诗礼',
'骨清虑不喧',
'洗然遇知己',
'谈论淮湖奔',
'忆昔初见时',
'小襦绣芳荪',
'长成忽会面',
'慰我久疾魂',
'三峡春冬交',
'江山云雾昏',
'正宜且聚集',
'恨此当离尊',
'莫怪执杯迟',
'我衰涕唾烦',
'重问子何之',
'西上岷江源',
'愿子少干谒',
'蜀都足戎轩',
'误失将帅意',
'不如亲故恩',
'少年早归来',
'梅花已飞翻',
'努力慎风水',
'岂惟数盘飧',
'猛虎卧在岸',
'蛟螭出无痕',
'王子自爱惜',
'老夫困石根',
'生别古所嗟',
'发声为尔吞',
],
},
{
title: '送高司直寻封阆州',
body: [
'丹雀衔书来',
'暮栖何乡树',
'骅骝事天子',
'辛苦在道路',
'司直非冗官',
'荒山甚无趣',
'借问泛舟人',
'胡为入云雾',
'与子姻娅间',
'既亲亦有故',
'万里长江边',
'邂逅一相遇',
'长卿消渴再',
'公干沉绵屡',
'清谈慰老夫',
'开卷得佳句',
'时见文章士',
'欣然澹情素',
'伏枕闻别离',
'畴能忍漂寓',
'良会苦短促',
'溪行水奔注',
'熊罴咆空林',
'游子慎驰骛',
'西谒巴中侯',
'艰险如跬步',
'主人不世才',
'先帝常特顾',
'拔为天军佐',
'崇大王法度',
'淮海生清风',
'南翁尚思慕',
'公宫造广厦',
'木石乃无数',
'初闻伐松柏',
'犹卧天一柱',
'我瘦书不成',
'成字读亦误',
'为我问故人',
'劳心练征戍',
],
},
{
title: '君不见,简苏徯',
body: [
'君不见道边废弃池',
'君不见前者摧折桐',
'百年死树中琴瑟',
'一斛旧水藏蛟龙',
'丈夫盖棺事始定',
'君今幸未成老翁',
'何恨憔悴在山中',
'深山穷谷不可处',
'霹雳魍魉兼狂风',
],
},
{
title: '赠苏四徯',
body: [
'异县昔同游',
'各云厌转蓬',
'别离已五年',
'尚在行李中',
'戎马日衰息',
'乘舆安九重',
'有才何栖栖',
'将老委所穷',
'为郎未为贱',
'其奈疾病攻',
'子何面黧黑',
'不得豁心胸',
'巴蜀倦剽掠',
'下愚成土风',
'幽蓟已削平',
'荒徼尚弯弓',
'斯人脱身来',
'岂非吾道东',
'乾坤虽宽大',
'所适装囊空',
'肉食哂菜色',
'少壮欺老翁',
'况乃主客间',
'古来逼侧同',
'君今下荆扬',
'独帆如飞鸿',
'二州豪侠场',
'人马皆自雄',
'一请甘饥寒',
'再请甘养蒙',
],
},
{
title: '寄薛三郎中(据)',
body: [
'人生无贤愚',
'飘飖若埃尘',
'自非得神仙',
'谁免危其身',
'与子俱白头',
'役役常苦辛',
'虽为尚书郎',
'不及村野人',
'忆昔村野人',
'其乐难具陈',
'蔼蔼桑麻交',
'公侯为等伦',
'天未厌戎马',
'我辈本常贫',
'子尚客荆州',
'我亦滞江滨',
'峡中一卧病',
'疟疠终冬春',
'春复加肺气',
'此病盖有因',
'早岁与苏郑',
'痛饮情相亲',
'二公化为土',
'嗜酒不失真',
'余今委修短',
'岂得恨命屯',
'闻子心甚壮',
'所过信席珍',
'上马不用扶',
'每扶必怒嗔',
'赋诗宾客间',
'挥洒动八垠',
'乃知盖代手',
'才力老益神',
'青草洞庭湖',
'东浮沧海漘',
'君山可避暑',
'况足采白蘋',
'子岂无扁舟',
'往复江汉津',
'我未下瞿塘',
'空念禹功勤',
'听说松门峡',
'吐药揽衣巾',
'高秋却束带',
'鼓枻视青旻',
'凤池日澄碧',
'济济多士新',
'余病不能起',
'健者勿逡巡',
'上有明哲君',
'下有行化臣',
],
},
{
title: '大觉高僧兰若(和尚去冬往湖南)',
body: [
'巫山不见庐山远',
'松林兰若秋风晚',
'一老犹鸣日暮钟',
'诸僧尚乞斋时饭',
'香炉峰色隐晴湖',
'种杏仙家近白榆',
'飞锡去年啼邑子',
'献花何日许门徒',
],
},
{
title: '宿青溪驿奉怀张员外十五兄之绪',
body: [
'漾舟千山内',
'日入泊枉渚',
'我生本飘飘',
'今复在何许',
'石根青枫林',
'猿鸟聚俦侣',
'月明游子静',
'畏虎不得语',
'中夜怀友朋',
'乾坤此深阻',
'浩荡前后间',
'佳期付荆楚',
],
},
{
title: '敬寄族弟唐十八使君',
body: [
'与君陶唐后',
'盛族多其人',
'圣贤冠史籍',
'枝派罗源津',
'在今气磊落',
'巧伪莫敢亲',
'介立实吾弟',
'济时肯杀身',
'物白讳受玷',
'行高无污真',
'得罪永泰末',
'放之五溪滨',
'鸾凤有铩翮',
'先儒曾抱麟',
'雷霆霹长松',
'骨大却生筋',
'一失不足伤',
'念子孰自珍',
'泊舟楚宫岸',
'恋阙浩酸辛',
'除名配清江',
'厥土巫峡邻',
'登陆将首途',
'笔札枉所申',
'归朝跼病肺',
'叙旧思重陈',
'春风洪涛壮',
'谷转颇弥旬',
'我能泛中流',
'搪突鼍獭瞋',
'长年已省柁',
'慰此贞良臣',
],
},
{
title: '忆昔行',
body: [
'忆昔北寻小有洞',
'洪河怒涛过轻舸',
'辛勤不见华盖君',
'艮岑青辉惨么麽',
'千崖无人万壑静',
'三步回头五步坐',
'秋山眼冷魂未归',
'仙赏心违泪交堕',
'弟子谁依白茅室',
'卢老独启青铜锁',
'巾拂香馀捣药尘',
'阶除灰死烧丹火',
'悬圃沧洲莽空阔',
'金节羽衣飘婀娜',
'落日初霞闪馀映',
'倏忽东西无不可',
'松风涧水声合时',
'青兕黄熊啼向我',
'徒然咨嗟抚遗迹',
'至今梦想仍犹佐',
'秘诀隐文须内教',
'晚岁何功使愿果',
'更讨衡阳董炼师',
'南浮早鼓潇湘柁',
],
},
{
title: '魏将军歌',
body: [
'将军昔著从事衫',
'铁马驰突重两衔',
'披坚执锐略西极',
'昆仑月窟东崭岩',
'君门羽林万猛士',
'恶若哮虎子所监',
'五年起家列霜戟',
'一日过海收风帆',
'平生流辈徒蠢蠢',
'长安少年气欲尽',
'魏侯骨耸精爽紧',
'华岳峰尖见秋隼',
'星躔宝校金盘陀',
'夜骑天驷超天河',
'欃枪荧惑不敢动',
'翠蕤云旓相荡摩',
'吾为子起歌都护',
'酒阑插剑肝胆露',
'钩陈苍苍风玄武',
'万岁千秋奉明主',
'临江节士安足数',
],
},
{
title: '北风',
body: [
'北风破南极',
'朱凤日威垂',
'洞庭秋欲雪',
'鸿雁将安归',
'十年杀气盛',
'六合人烟稀',
'吾慕汉初老',
'时清犹茹芝',
],
},
{
title: '客从',
body: [
'客从南溟来',
'遗我泉客珠',
'珠中有隐字',
'欲辨不成书',
'缄之箧笥久',
'以俟公家须',
'开视化为血',
'哀今征敛无',
],
},
{
title: '白马',
body: [
'白马东北来',
'空鞍贯双箭',
'可怜马上郎',
'意气今谁见',
'近时主将戮',
'中夜商於战',
'丧乱死多门',
'呜呼泪如霰',
],
},
{
title: '白凫行',
body: [
'君不见黄鹄高于五尺童',
'化为白凫似老翁',
'故畦遗穗已荡尽',
'天寒岁暮波涛中',
'鳞介腥膻素不食',
'终日忍饥西复东',
'鲁门鶢鶋亦蹭蹬',
'闻道如今犹避风',
],
},
{
title: '朱凤行',
body: [
'君不见潇湘之山衡山高',
'山巅朱凤声嗷嗷',
'侧身长顾求其群',
'翅垂口噤心甚劳',
'下愍百鸟在罗网',
'黄雀最小犹难逃',
'愿分竹实及蝼蚁',
'尽使鸱枭相怒号',
],
},
{
title: '惜别行,送向卿进奉端午御衣之上都',
body: [
'肃宗昔在灵武城',
'指挥猛将收咸京',
'向公泣血洒行殿',
'佐佑卿相乾坤平',
'逆胡冥寞随烟烬',
'卿家兄弟功名震',
'麒麟图画鸿雁行',
'紫极出入黄金印',
'尚书勋业超千古',
'雄镇荆州继吾祖',
'裁缝云雾成御衣',
'拜跪题封向端午',
'向卿将命寸心赤',
'青山落日江潮白',
'卿到朝廷说老翁',
'漂零已是沧浪客',
],
},
{
title: '醉歌行,赠公安颜少府请顾八题壁',
body: [
'神仙中人不易得',
'颜氏之子才孤标',
'天马长鸣待驾驭',
'秋鹰整翮当云霄',
'君不见东吴顾文学',
'君不见西汉杜陵老',
'诗家笔势君不嫌',
'词翰升堂为君扫',
'是日霜风冻七泽',
'乌蛮落照衔赤壁',
'酒酣耳热忘头白',
'感君意气无所惜',
'一为歌行歌主客',
],
},
{
title: '夜闻觱篥',
body: [
'夜闻觱篥沧江上',
'衰年侧耳情所向',
'邻舟一听多感伤',
'塞曲三更欻悲壮',
'积雪飞霜此夜寒',
'孤灯急管复风湍',
'君知天地干戈满',
'不见江湖行路难',
],
},
{
title: '发刘郎浦(浦在石首县,昭烈纳吴女处)',
body: [
'挂帆早发刘郎浦',
'疾风飒飒昏亭午',
'舟中无日不沙尘',
'岸上空村尽豺虎',
'十日北风风未回',
'客行岁晚晚相催',
'白头厌伴渔人宿',
'黄帽青鞋归去来',
],
},
{
title: '别董颋',
body: [
'穷冬急风水',
'逆浪开帆难',
'士子甘旨阙',
'不知道里寒',
'有求彼乐土',
'南适小长安',
'到我舟楫去',
'觉君衣裳单',
'素闻赵公节',
'兼尽宾主欢',
'已结门庐望',
'无令霜雪残',
'老夫缆亦解',
'脱粟朝未餐',
'飘荡兵甲际',
'几时怀抱宽',
'汉阳颇宁静',
'岘首试考槃',
'当念著白帽',
'采薇青云端',
],
},
{
title: '送重表侄王砅评事使南海',
body: [
'我之曾祖姑',
'尔之高祖母',
'尔祖未显时',
'归为尚书妇',
'隋朝大业末',
'房杜俱交友',
'长者来在门',
'荒年自糊口',
'家贫无供给',
'客位但箕帚',
'俄顷羞颇珍',
'寂寥人散后',
'入怪鬓发空',
'吁嗟为之久',
'自陈翦髻鬟',
'鬻市充杯酒',
'上云天下乱',
'宜与英俊厚',
'向窃窥数公',
'经纶亦俱有',
'次问最少年',
'虬髯十八九',
'子等成大名',
'皆因此人手',
'下云风云合',
'龙虎一吟吼',
'愿展丈夫雄',
'得辞儿女丑',
'秦王时在坐',
'真气惊户牖',
'及乎贞观初',
'尚书践台斗',
'夫人常肩舆',
'上殿称万寿',
'六宫师柔顺',
'法则化妃后',
'至尊均嫂叔',
'盛事垂不朽',
'凤雏无凡毛',
'五色非尔曹',
'往者胡作逆',
'乾坤沸嗷嗷',
'吾客左冯翊',
'尔家同遁逃',
'争夺至徒步',
'块独委蓬蒿',
'逗留热尔肠',
'十里却呼号',
'自下所骑马',
'右持腰间刀',
'左牵紫游缰',
'飞走使我高',
'苟活到今日',
'寸心铭佩牢',
'乱离又聚散',
'宿昔恨滔滔',
'水花笑白首',
'春草随青袍',
'廷评近要津',
'节制收英髦',
'北驱汉阳传',
'南泛上泷舠',
'家声肯坠地',
'利器当秋毫',
'番禺亲贤领',
'筹运神功操',
'大夫出卢宋',
'宝贝休脂膏',
'洞主降接武',
'海胡舶千艘',
'我欲就丹砂',
'跋涉觉身劳',
'安能陷粪土',
'有志乘鲸鳌',
'或骖鸾腾天',
'聊作鹤鸣皋',
],
},
{
title: '咏怀二首',
body: [
'人生贵是男',
'丈夫重天机',
'未达善一身',
'得志行所为',
'嗟余竟轗轲',
'将老逢艰危',
'胡雏逼神器',
'逆节同所归',
'河雒化为血',
'公侯草间啼',
'西京复陷没',
'翠盖蒙尘飞',
'万姓悲赤子',
'两宫弃紫微',
'倏忽向二纪',
'奸雄多是非',
'本朝再树立',
'未及贞观时',
'日给在军储',
'上官督有司',
'高贤迫形势',
'岂暇相扶持',
'疲苶苟怀策',
'栖屑无所施',
'先王实罪己',
'愁痛正为兹',
'岁月不我与',
'蹉跎病于斯',
'夜看丰城气',
'回首蛟龙池',
'齿发已自料',
'意深陈苦词',
'邦危坏法则',
'圣远益愁慕',
'飘飖桂水游',
'怅望苍梧暮',
'潜鱼不衔钩',
'走鹿无反顾',
'皦皦幽旷心',
'拳拳异平素',
'衣食相拘阂',
'朋知限流寓',
'风涛上春沙',
'千里侵江树',
'逆行少吉日',
'时节空复度',
'井灶任尘埃',
'舟航烦数具',
'牵缠加老病',
'琐细隘俗务',
'万古一死生',
'胡为足名数',
'多忧污桃源',
'拙计泥铜柱',
'未辞炎瘴毒',
'摆落跋涉惧',
'虎狼窥中原',
'焉得所历住',
'葛洪及许靖',
'避世常此路',
'贤愚诚等差',
'自爱各驰骛',
'羸瘠且如何',
'魄夺针灸屡',
'拥滞僮仆慵',
'稽留篙师怒',
'终当挂帆席',
'天意难告诉',
'南为祝融客',
'勉强亲杖屦',
'结托老人星',
'罗浮展衰步',
],
},
{
title: '送顾八分文学适洪吉州',
body: [
'中郎石经后',
'八分盖憔悴',
'顾侯运炉锤',
'笔力破馀地',
'昔在开元中',
'韩蔡同赑屃',
'玄宗妙其书',
'是以数子至',
'御札早流传',
'揄扬非造次',
'三人并入直',
'恩泽各不二',
'顾于韩蔡内',
'辨眼工小字',
'分日示诸王',
'钩深法更秘',
'文学与我游',
'萧疏外声利',
'追随二十载',
'浩荡长安醉',
'高歌卿相宅',
'文翰飞省寺',
'视我扬马间',
'白首不相弃',
'骅骝入穷巷',
'必脱黄金辔',
'一论朋友难',
'迟暮敢失坠',
'古来事反覆',
'相见横涕泗',
'向者玉珂人',
'谁是青云器',
'才尽伤形体',
'病渴污官位',
'故旧独依然',
'时危话颠踬',
'我甘多病老',
'子负忧世志',
'胡为困衣食',
'颜色少称遂',
'远作辛苦行',
'顺从众多意',
'舟楫无根蒂',
'蛟鼍好为祟',
'况兼水贼繁',
'特戒风飙驶',
'崩腾戎马际',
'往往杀长吏',
'子干东诸侯',
'劝勉防纵恣',
'邦以民为本',
'鱼饥费香饵',
'请哀疮痍深',
'告诉皇华使',
'使臣精所择',
'进德知历试',
'恻隐诛求情',
'固应贤愚异',
'列士恶苟得',
'俊杰思自致',
'赠子猛虎行',
'出郊载酸鼻',
],
},
{
title: '上水遣怀',
body: [
'我衰太平时',
'身病戎马后',
'蹭蹬多拙为',
'安得不皓首',
'驱驰四海内',
'童稚日糊口',
'但遇新少年',
'少逢旧亲友',
'低颜下色地',
'故人知善诱',
'后生血气豪',
'举动见老丑',
'穷迫挫曩怀',
'常如中风走',
'一纪出西蜀',
'于今向南斗',
'孤舟乱春华',
'暮齿依蒲柳',
'冥冥九疑葬',
'圣者骨亦朽',
'蹉跎陶唐人',
'鞭挞日月久',
'中间屈贾辈',
'谗毁竟自取',
'郁没二悲魂',
'萧条犹在否',
'崷崒清湘石',
'逆行杂林薮',
'篙工密逞巧',
'气若酣杯酒',
'歌讴互激远',
'回斡明受授',
'善知应触类',
'各藉颖脱手',
'古来经济才',
'何事独罕有',
'苍苍众色晚',
'熊挂玄蛇吼',
'黄罴在树颠',
'正为群虎守',
'羸骸将何适',
'履险颜益厚',
'庶与达者论',
'吞声混瑕垢',
],
},
{
title: '遣遇',
body: [
'磬折辞主人',
'开帆驾洪涛',
'春水满南国',
'朱崖云日高',
'舟子废寝食',
'飘风争所操',
'我行匪利涉',
'谢尔从者劳',
'石间采蕨女',
'鬻菜输官曹',
'丈夫死百役',
'暮返空村号',
'闻见事略同',
'刻剥及锥刀',
'贵人岂不仁',
'视汝如莠蒿',
'索钱多门户',
'丧乱纷嗷嗷',
'奈何黠吏徒',
'渔夺成逋逃',
'自喜遂生理',
'花时甘缊袍',
],
},
{
title: '解忧',
body: [
'减米散同舟',
'路难思共济',
'向来云涛盘',
'众力亦不细',
'呀坑瞥眼过',
'飞橹本无蒂',
'得失瞬息间',
'致远宜恐泥',
'百虑视安危',
'分明曩贤计',
'兹理庶可广',
'拳拳期勿替',
],
},
{
title: '宿凿石浦(浦在湘潭县西)',
body: [
'早宿宾从劳',
'仲春江山丽',
'飘风过无时',
'舟楫敢不系',
'回塘澹暮色',
'日没众星嘒',
'缺月殊未生',
'青灯死分翳',
'穷途多俊异',
'乱世少恩惠',
'鄙夫亦放荡',
'草草频卒岁',
'斯文忧患馀',
'圣哲垂彖系',
],
},
{
title: '早行',
body: [
'歌哭俱在晓',
'行迈有期程',
'孤舟似昨日',
'闻见同一声',
'飞鸟数求食',
'潜鱼亦独惊',
'前王作网罟',
'设法害生成',
'碧藻非不茂',
'高帆终日征',
'干戈未揖让',
'崩迫开其情',
],
},
{
title: '过津口',
body: [
'南岳自兹近',
'湘流东逝深',
'和风引桂楫',
'春日涨云岑',
'回首过津口',
'而多枫树林',
'白鱼困密网',
'黄鸟喧嘉音',
'物微限通塞',
'恻隐仁者心',
'瓮馀不尽酒',
'膝有无声琴',
'圣贤两寂寞',
'眇眇独开襟',
],
},
{
title: '次空灵岸',
body: [
'沄沄逆素浪',
'落落展清眺',
'幸有舟楫迟',
'得尽所历妙',
'空灵霞石峻',
'枫栝隐奔峭',
'青春犹无私',
'白日亦偏照',
'可使营吾居',
'终焉托长啸',
'毒瘴未足忧',
'兵戈满边徼',
'向者留遗恨',
'耻为达人诮',
'回帆觊赏延',
'佳处领其要',
],
},
{
title: '宿花石戍(长沙有渌口、花石二戍)',
body: [
'午辞空灵岑',
'夕得花石戍',
'岸疏开辟水',
'木杂今古树',
'地蒸南风盛',
'春热西日暮',
'四序本平分',
'气候何回互',
'茫茫天造间',
'理乱岂恒数',
'系舟盘藤轮',
'策杖古樵路',
'罢人不在村',
'野圃泉自注',
'柴扉虽芜没',
'农器尚牢固',
'山东残逆气',
'吴楚守王度',
'谁能扣君门',
'下令减征赋',
],
},
{
title: '早发',
body: [
'有求常百虑',
'斯文亦吾病',
'以兹朋故多',
'穷老驱驰并',
'早行篙师怠',
'席挂风不正',
'昔人戒垂堂',
'今则奚奔命',
'涛翻黑蛟跃',
'日出黄雾映',
'烦促瘴岂侵',
'颓倚睡未醒',
'仆夫问盥栉',
'暮颜靦青镜',
'随意簪葛巾',
'仰惭林花盛',
'侧闻夜来寇',
'幸喜囊中净',
'艰危作远客',
'干请伤直性',
'薇蕨饿首阳',
'粟马资历聘',
'贱子欲适从',
'疑误此二柄',
],
},
{
title: '次晚洲',
body: [
'参错云石稠',
'坡陀风涛壮',
'晚洲适知名',
'秀色固异状',
'棹经垂猿把',
'身在度鸟上',
'摆浪散帙妨',
'危沙折花当',
'羁离暂愉悦',
'羸老反惆怅',
'中原未解兵',
'吾得终疏放',
],
},
{
title: '望岳',
body: [
'南岳配朱鸟',
'秩礼自百王',
'欻吸领地灵',
'鸿洞半炎方',
'邦家用祀典',
'在德非馨香',
'巡守何寂寥',
'有虞今则亡',
'洎吾隘世网',
'行迈越潇湘',
'渴日绝壁出',
'漾舟清光旁',
'祝融五峰尊',
'峰峰次低昂',
'紫盖独不朝',
'争长嶪相望',
'恭闻魏夫人',
'群仙夹翱翔',
'有时五峰气',
'散风如飞霜',
'牵迫限修途',
'未暇杖崇冈',
'归来觊命驾',
'沐浴休玉堂',
'三叹问府主',
'曷以赞我皇',
'牲璧忍衰俗',
'神其思降祥',
],
},
{
title: '湘江宴饯裴二端公赴道州',
body: [
'白日照舟师',
'朱旗散广川',
'群公饯南伯',
'肃肃秩初筵',
'鄙人奉末眷',
'佩服自早年',
'义均骨肉地',
'怀抱罄所宣',
'盛名富事业',
'无取愧高贤',
'不以丧乱婴',
'保爱金石坚',
'计拙百僚下',
'气苏君子前',
'会合苦不久',
'哀乐本相缠',
'交游飒向尽',
'宿昔浩茫然',
'促觞激百虑',
'掩抑泪潺湲',
'热云集曛黑',
'缺月未生天',
'白团为我破',
'华烛蟠长烟',
'鸹鹖催明星',
'解袂从此旋',
'上请减兵甲',
'下请安井田',
'永念病渴老',
'附书远山巅',
],
},
{
title: '清明',
body: [
'著处繁花务是日',
'长沙千人万人出',
'渡头翠柳艳明眉',
'争道朱蹄骄啮膝',
'此都好游湘西寺',
'诸将亦自军中至',
'马援征行在眼前',
'葛强亲近同心事',
'金镫下山红粉晚',
'牙樯捩柁青楼远',
'古时丧乱皆可知',
'人世悲欢暂相遣',
'弟侄虽存不得书',
'干戈未息苦离居',
'逢迎少壮非吾道',
'况乃今朝更祓除',
],
},
{
title: '风雨看舟前落花,戏为新句',
body: [
'江上人家桃树枝',
'春寒细雨出疏篱',
'影遭碧水潜勾引',
'风妒红花却倒吹',
'吹花困癫傍舟楫',
'水光风力俱相怯',
'赤憎轻薄遮入怀',
'珍重分明不来接',
'湿久飞迟半日高',
'萦沙惹草细于毛',
'蜜蜂蝴蝶生情性',
'偷眼蜻蜓避百劳',
],
},
{
title: '岳麓山道林二寺行',
body: [
'玉泉之南麓山殊',
'道林林壑争盘纡',
'寺门高开洞庭野',
'殿脚插入赤沙湖',
'五月寒风冷佛骨',
'六时天乐朝香炉',
'地灵步步雪山草',
'僧宝人人沧海珠',
'塔劫宫墙壮丽敌',
'香厨松道清凉俱',
'莲花交响共命鸟',
'金榜双回三足乌',
'方丈涉海费时节',
'悬圃寻河知有无',
'暮年且喜经行近',
'春日兼蒙暄暖扶',
'飘然斑白身奚适',
'傍此烟霞茅可诛',
'桃源人家易制度',
'橘洲田土仍膏腴',
'潭府邑中甚淳古',
'太守庭内不喧呼',
'昔遭衰世皆晦迹',
'今幸乐国养微躯',
'依止老宿亦未晚',
'富贵功名焉足图',
'久为野客寻幽惯',
'细学何颙免兴孤',
'一重一掩吾肺腑',
'山鸟山花吾友于',
'宋公放逐曾题壁',
'物色分留与老夫',
],
},
{
title: '奉送魏六丈佑少府之交广',
body: [
'贤豪赞经纶',
'功成空名垂',
'子孙不振耀',
'历代皆有之',
'郑公四叶孙',
'长大常苦饥',
'众中见毛骨',
'犹是麒麟儿',
'磊落贞观事',
'致君朴直词',
'家声盖六合',
'行色何其微',
'遇我苍梧阴',
'忽惊会面稀',
'议论有馀地',
'公侯来未迟',
'虚思黄金贵',
'自笑青云期',
'长卿久病渴',
'武帝元同时',
'季子黑貂敝',
'得无妻嫂欺',
'尚为诸侯客',
'独屈州县卑',
'南游炎海甸',
'浩荡从此辞',
'穷途仗神道',
'世乱轻土宜',
'解帆岁云暮',
'可与春风归',
'出入朱门家',
'华屋刻蛟螭',
'玉食亚王者',
'乐张游子悲',
'侍婢艳倾城',
'绡绮轻雾霏',
'掌中琥珀钟',
'行酒双逶迤',
'新欢继明烛',
'梁栋星辰飞',
'两情顾盼合',
'珠碧赠于斯',
'上贵见肝胆',
'下贵不相疑',
'心事披写间',
'气酣达所为',
'错挥铁如意',
'莫避珊瑚枝',
'始兼逸迈兴',
'终慎宾主仪',
'戎马暗天宇',
'呜呼生别离',
],
},
{
title: '别张十三建封',
body: [
'尝读唐实录',
'国家草昧初',
'刘裴建首义',
'龙见尚踌躇',
'秦王拨乱姿',
'一剑总兵符',
'汾晋为丰沛',
'暴隋竟涤除',
'宗臣则庙食',
'后祀何疏芜',
'彭城英雄种',
'宜膺将相图',
'尔惟外曾孙',
'倜傥汗血驹',
'眼中万少年',
'用意尽崎岖',
'相逢长沙亭',
'乍问绪业馀',
'乃吾故人子',
'童丱联居诸',
'挥手洒衰泪',
'仰看八尺躯',
'内外名家流',
'风神荡江湖',
'范云堪晚友',
'嵇绍自不孤',
'择材征南幕',
'湖落回鲸鱼',
'载感贾生恸',
'复闻乐毅书',
'主忧急盗贼',
'师老荒京都',
'旧丘岂税驾',
'大厦倾宜扶',
'君臣各有分',
'管葛本时须',
'虽当霰雪严',
'未觉栝柏枯',
'高义在云台',
'嘶鸣望天衢',
'羽人扫碧海',
'功业竟何如',
],
},
{
title: '暮秋枉裴道州手札,率尔遣兴,寄近呈苏涣侍御',
body: [
'久客多枉友朋书',
'素书一月凡一束',
'虚名但蒙寒温问',
'泛爱不救沟壑辱',
'齿落未是无心人',
'舌存耻作穷途哭',
'道州手札适复至',
'纸长要自三过读',
'盈把那须沧海珠',
'入怀本倚昆山玉',
'拨弃潭州百斛酒',
'芜没潇岸千株菊',
'使我昼立烦儿孙',
'令我夜坐费灯烛',
'忆子初尉永嘉去',
'红颜白面花映肉',
'军符侯印取岂迟',
'紫燕騄耳行甚速',
'圣朝尚飞战斗尘',
'济世宜引英俊人',
'黎元愁痛会苏息',
'夷狄跋扈徒逡巡',
'授钺筑坛闻意旨',
'颓纲漏网期弥纶',
'郭钦上书见大计',
'刘毅答诏惊群臣',
'他日更仆语不浅',
'明公论兵气益振',
'倾壶箫管黑白发',
'舞剑霜雪吹青春',
'宴筵曾语苏季子',
'后来杰出云孙比',
'茅斋定王城郭门',
'药物楚老渔商市',
'市北肩舆每联袂',
'郭南抱瓮亦隐几',
'无数将军西第成',
'早作丞相东山起',
'鸟雀苦肥秋粟菽',
'蛟龙欲蛰寒沙水',
'天下鼓角何时休',
'阵前部曲终日死',
'附书与裴因示苏',
'此生已愧须人扶',
'致君尧舜付公等',
'早据要路思捐躯',
],
},
{
title: '奉赠李八丈判官(曛)',
body: [
'我丈时英特',
'宗枝神尧后',
'珊瑚市则无',
'騄骥人得有',
'早年见标格',
'秀气冲星斗',
'事业富清机',
'官曹正独守',
'顷来树嘉政',
'皆已传众口',
'艰难体贵安',
'冗长吾敢取',
'区区犹历试',
'炯炯更持久',
'讨论实解颐',
'操割纷应手',
'箧书积讽谏',
'宫阙限奔走',
'入幕未展材',
'秉钧孰为偶',
'所亲问淹泊',
'泛爱惜衰朽',
'垂白乱南翁',
'委身希北叟',
'真成穷辙鲋',
'或似丧家狗',
'秋枯洞庭石',
'风飒长沙柳',
'高兴激荆衡',
'知音为回首',
],
},
{
title: '岁晏行',
body: [
'岁云暮矣多北风',
'潇湘洞庭白雪中',
'渔父天寒网罟冻',
'莫徭射雁鸣桑弓',
'去年米贵阙军食',
'今年米贱大伤农',
'高马达官厌酒肉',
'此辈杼轴茅茨空',
'楚人重鱼不重鸟',
'汝休枉杀南飞鸿',
'况闻处处鬻男女',
'割慈忍爱还租庸',
'往日用钱捉私铸',
'今许铅锡和青铜',
'刻泥为之最易得',
'好恶不合长相蒙',
'万国城头吹画角',
'此曲哀怨何时终',
],
},
{
title: '追酬故高蜀州人日见寄',
body: [
'自蒙蜀州人日作',
'不意清诗久零落',
'今晨散帙眼忽开',
'迸泪幽吟事如昨',
'呜呼壮士多慷慨',
'合沓高名动寥廓',
'叹我凄凄求友篇',
'感时郁郁匡君略',
'锦里春光空烂熳',
'瑶墀侍臣已冥莫',
'潇湘水国傍鼋鼍',
'鄠杜秋天失雕鹗',
'东西南北更谁论',
'白首扁舟病独存',
'遥拱北辰缠寇盗',
'欲倾东海洗乾坤',
'边塞西蕃最充斥',
'衣冠南渡多崩奔',
'鼓瑟至今悲帝子',
'曳裾何处觅王门',
'文章曹植波澜阔',
'服食刘安德业尊',
'长笛谁能乱愁思',
'昭州词翰与招魂',
],
},
{
title: '苏大侍御访江浦,赋八韵记异',
body: [
'庞公不浪出',
'苏氏今有之',
'再闻诵新作',
'突过黄初诗',
'乾坤几反覆',
'扬马宜同时',
'今晨清镜中',
'胜食斋房芝',
'余发喜却变',
'白间生黑丝',
'昨夜舟火灭',
'湘娥帘外悲',
'百灵未敢散',
'风破寒江迟',
],
},
{
title: '题衡山县文宣王庙新学堂,呈陆宰',
body: [
'旄头彗紫微',
'无复俎豆事',
'金甲相排荡',
'青衿一憔悴',
'呜呼已十年',
'儒服弊于地',
'征夫不遑息',
'学者沦素志',
'我行洞庭野',
'欻得文翁肆',
'侁侁胄子行',
'若舞风雩至',
'周室宜中兴',
'孔门未应弃',
'是以资雅才',
'涣然立新意',
'衡山虽小邑',
'首唱恢大义',
'因见县尹心',
'根源旧宫閟',
'讲堂非曩构',
'大屋加涂墍',
'下可容百人',
'墙隅亦深邃',
'何必三千徒',
'始压戎马气',
'林木在庭户',
'密干叠苍翠',
'有井朱夏时',
'辘轳冻阶戺',
'耳闻读书声',
'杀伐灾仿佛',
'故国延归望',
'衰颜减愁思',
'南纪改波澜',
'西河共风味',
'采诗倦跋涉',
'载笔尚可记',
'高歌激宇宙',
'凡百慎失坠',
],
},
{
title: '入衡州',
body: [
'兵革自久远',
'兴衰看帝王',
'汉仪甚照耀',
'胡马何猖狂',
'老将一失律',
'清边生战场',
'君臣忍瑕垢',
'河岳空金汤',
'重镇如割据',
'轻权绝纪纲',
'军州体不一',
'宽猛性所将',
'嗟彼苦节士',
'素于圆凿方',
'寡妻从为郡',
'兀者安堵墙',
'凋弊惜邦本',
'哀矜存事常',
'旌麾非其任',
'府库实过防',
'恕己独在此',
'多忧增内伤',
'偏裨限酒肉',
'卒伍单衣裳',
'元恶迷是似',
'聚谋泄康庄',
'竟流帐下血',
'大降湖南殃',
'烈火发中夜',
'高烟焦上苍',
'至今分粟帛',
'杀气吹沅湘',
'福善理颠倒',
'明征天莽茫',
'销魂避飞镝',
'累足穿豺狼',
'隐忍枳棘刺',
'迁延胝趼疮',
'远归儿侍侧',
'犹乳女在旁',
'久客幸脱免',
'暮年惭激昂',
'萧条向水陆',
'汩没随鱼商',
'报主身已老',
'入朝病见妨',
'悠悠委薄俗',
'郁郁回刚肠',
'参错走洲渚',
'舂容转林篁',
'片帆左郴岸',
'通郭前衡阳',
'华表云鸟埤',
'名园花草香',
'旗亭壮邑屋',
'烽橹蟠城隍',
'中有古刺史',
'盛才冠岩廊',
'扶颠待柱石',
'独坐飞风霜',
'昨者间琼树',
'高谈随羽觞',
'无论再缱绻',
'已是安苍黄',
'剧孟七国畏',
'马卿四赋良',
'门阑苏生在',
'勇锐白起强',
'问罪富形势',
'凯歌悬否臧',
'氛埃期必扫',
'蚊蚋焉能当',
'橘井旧地宅',
'仙山引舟航',
'此行厌暑雨',
'厥土闻清凉',
'诸舅剖符近',
'开缄书札光',
'频繁命屡及',
'磊落字百行',
'江总外家养',
'谢安乘兴长',
'下流匪珠玉',
'择木羞鸾皇',
'我师嵇叔夜',
'世贤张子房',
'柴荆寄乐土',
'鹏路观翱翔',
],
},
{
title: '舟中苦热遣怀,奉呈阳中丞通简台省诸公',
body: [
'愧为湖外客',
'看此戎马乱',
'中夜混黎氓',
'脱身亦奔窜',
'平生方寸心',
'反掌帐下难',
'呜呼杀贤良',
'不叱白刃散',
'吾非丈夫特',
'没齿埋冰炭',
'耻以风病辞',
'胡然泊湘岸',
'入舟虽苦热',
'垢腻可溉灌',
'痛彼道边人',
'形骸改昏旦',
'中丞连帅职',
'封内权得按',
'身当问罪先',
'县实诸侯半',
'士卒既辑睦',
'启行促精悍',
'似闻上游兵',
'稍逼长沙馆',
'怜好彼克修',
'天机自明断',
'南图卷云水',
'北拱戴霄汉',
'美名光史臣',
'长策何壮观',
'驱驰数公子',
'咸愿同伐叛',
'声节哀有馀',
'夫何激衰懦',
'偏裨表三上',
'卤莽同一贯',
'始谋谁其间',
'回首增愤惋',
'宗英李端公',
'守职甚昭焕',
'变通迫胁地',
'谋画焉得算',
'王室不肯微',
'凶徒略无惮',
'此流须卒斩',
'神器资强干',
'扣寂豁烦襟',
'皇天照嗟叹',
],
},
{
title: '聂耒阳以仆阻水书致酒肉疗饥荒江诗得代怀…泊于方田',
body: [
'耒阳驰尺素',
'见访荒江眇',
'义士烈女家',
'风流吾贤绍',
'昨见狄相孙',
'许公人伦表',
'前期翰林后',
'屈迹县邑小',
'知我碍湍涛',
'半旬获浩溔',
'麾下杀元戎',
'湖边有飞旐',
'孤舟增郁郁',
'僻路殊悄悄',
'侧惊猿猱捷',
'仰羡鹳鹤矫',
'礼过宰肥羊',
'愁当置清醥',
'人非西喻蜀',
'兴在北坑赵',
'方行郴岸静',
'未话长沙扰',
'崔师乞已至',
'澧卒用矜少',
'问罪消息真',
'开颜憩亭沼',
],
},
{
title: '冬日洛城北谒玄元皇帝庙',
body: [
'配极玄都閟',
'凭虚禁御长',
'守祧严具礼',
'掌节镇非常',
'碧瓦初寒外',
'金茎一气旁',
'山河扶绣户',
'日月近雕梁',
'仙李盘根大',
'猗兰奕叶光',
'世家遗旧史',
'道德付今王',
'画手看前辈',
'吴生远擅场',
'森罗移地轴',
'妙绝动宫墙',
'五圣联龙衮',
'千官列雁行',
'冕旒俱秀发',
'旌旆尽飞扬',
'翠柏深留景',
'红梨迥得霜',
'风筝吹玉柱',
'露井冻银床',
'身退卑周室',
'经传拱汉皇',
'谷神如不死',
'养拙更何乡',
],
},
{
title: '赠韦左丞丈(济。天宝七年以韦济为河南尹迁尚书左丞)',
body: [
'左辖频虚位',
'今年得旧儒',
'相门韦氏在',
'经术汉臣须',
'时议归前烈',
'天伦恨莫俱',
'鴒原荒宿草',
'凤沼接亨衢',
'有客虽安命',
'衰容岂壮夫',
'家人忧几杖',
'甲子混泥途',
'不谓矜馀力',
'还来谒大巫',
'岁寒仍顾遇',
'日暮且踟蹰',
'老骥思千里',
'饥鹰待一呼',
'君能微感激',
'亦足慰榛芜',
],
},
{
title: '投赠哥舒开府二十韵',
body: [
'今代麒麟阁',
'何人第一功',
'君王自神武',
'驾驭必英雄',
'开府当朝杰',
'论兵迈古风',
'先锋百胜在',
'略地两隅空',
'青海无传箭',
'天山早挂弓',
'廉颇仍走敌',
'魏绛已和戎',
'每惜河湟弃',
'新兼节制通',
'智谋垂睿想',
'出入冠诸公',
'日月低秦树',
'乾坤绕汉宫',
'胡人愁逐北',
'宛马又从东',
'受命边沙远',
'归来御席同',
'轩墀曾宠鹤',
'畋猎旧非熊',
'茅土加名数',
'山河誓始终',
'策行遗战伐',
'契合动昭融',
'勋业青冥上',
'交亲气概中',
'未为珠履客',
'已见白头翁',
'壮节初题柱',
'生涯独转蓬',
'几年春草歇',
'今日暮途穷',
'军事留孙楚',
'行间识吕蒙',
'防身一长剑',
'将欲倚崆峒',
],
},
{
title: '上韦左相二十韵(见素)',
body: [
'凤历轩辕纪',
'龙飞四十春',
'八荒开寿域',
'一气转洪钧',
'霖雨思贤佐',
'丹青忆老臣',
'应图求骏马',
'惊代得麒麟',
'沙汰江河浊',
'调和鼎鼐新',
'韦贤初相汉',
'范叔已归秦',
'盛业今如此',
'传经固绝伦',
'豫樟深出地',
'沧海阔无津',
'北斗司喉舌',
'东方领搢绅',
'持衡留藻鉴',
'听履上星辰',
'独步才超古',
'馀波德照邻',
'聪明过管辂',
'尺牍倒陈遵',
'岂是池中物',
'由来席上珍',
'庙堂知至理',
'风俗尽还淳',
'才杰俱登用',
'愚蒙但隐沦',
'长卿多病久',
'子夏索居频',
'回首驱流俗',
'生涯似众人',
'巫咸不可问',
'邹鲁莫容身',
'感激时将晚',
'苍茫兴有神',
'为公歌此曲',
'涕泪在衣巾',
],
},
{
title: '奉赠太常张卿二十韵(均)',
body: [
'方丈三韩外',
'昆仑万国西',
'建标天地阔',
'诣绝古今迷',
'气得神仙迥',
'恩承雨露低',
'相门清议众',
'儒术大名齐',
'轩冕罗天阙',
'琳琅识介珪',
'伶官诗必诵',
'夔乐典犹稽',
'健笔凌鹦鹉',
'铦锋莹鸊鹈',
'友于皆挺拔',
'公望各端倪',
'通籍逾青琐',
'亨衢照紫泥',
'灵虬传夕箭',
'归马散霜蹄',
'能事闻重译',
'嘉谟及远黎',
'弼谐方一展',
'斑序更何跻',
'适越空颠踬',
'游梁竟惨凄',
'谬知终画虎',
'微分是醯鸡',
'萍泛无休日',
'桃阴想旧蹊',
'吹嘘人所羡',
'腾跃事仍睽',
'碧海真难涉',
'青云不可梯',
'顾深惭锻炼',
'才小辱提携',
'槛束哀猿叫',
'枝惊夜鹊栖',
'几时陪羽猎',
'应指钓璜溪',
],
},
{
title: '敬赠郑谏议十韵',
body: [
'谏官非不达',
'诗义早知名',
'破的由来事',
'先锋孰敢争',
'思飘云物外',
'律中鬼神惊',
'毫发无遗恨',
'波澜独老成',
'野人宁得所',
'天意薄浮生',
'多病休儒服',
'冥搜信客旌',
'筑居仙缥缈',
'旅食岁峥嵘',
'使者求颜阖',
'诸公厌祢衡',
'将期一诺重',
'欻使寸心倾',
'君见途穷哭',
'宜忧阮步兵',
],
},
{
title: '奉赠鲜于京兆二十韵(鲜于仲通,天宝末为京兆尹)',
body: [
'王国称多士',
'贤良复几人',
'异才应间出',
'爽气必殊伦',
'始见张京兆',
'宜居汉近臣',
'骅骝开道路',
'雕鹗离风尘',
'侯伯知何等',
'文章实致身',
'奋飞超等级',
'容易失沈沦',
'脱略磻溪钓',
'操持郢匠斤',
'云霄今已逼',
'台衮更谁亲',
'凤穴雏皆好',
'龙门客又新',
'义声纷感激',
'败绩自逡巡',
'途远欲何向',
'天高难重陈',
'学诗犹孺子',
'乡赋念嘉宾',
'不得同晁错',
'吁嗟后郄诜',
'计疏疑翰墨',
'时过忆松筠',
'献纳纡皇眷',
'中间谒紫宸',
'且随诸彦集',
'方觊薄才伸',
'破胆遭前政',
'阴谋独秉钧',
'微生沾忌刻',
'万事益酸辛',
'交合丹青地',
'恩倾雨露辰',
'有儒愁饿死',
'早晚报平津',
],
},
{
title: '赠特进汝阳王二十韵',
body: [
'特进群公表',
'天人夙德升',
'霜蹄千里骏',
'风翮九霄鹏',
'服礼求毫发',
'惟忠忘寝兴',
'圣情常有眷',
'朝退若无凭',
'仙醴来浮蚁',
'奇毛或赐鹰',
'清关尘不杂',
'中使日相乘',
'晚节嬉游简',
'平居孝义称',
'自多亲棣萼',
'谁敢问山陵',
'学业醇儒富',
'辞华哲匠能',
'笔飞鸾耸立',
'章罢凤鶱腾',
'精理通谈笑',
'忘形向友朋',
'寸长堪缱绻',
'一诺岂骄矜',
'已忝归曹植',
'何知对李膺',
'招要恩屡至',
'崇重力难胜',
'披雾初欢夕',
'高秋爽气澄',
'尊罍临极浦',
'凫雁宿张灯',
'花月穷游宴',
'炎天避郁蒸',
'研寒金井水',
'檐动玉壶冰',
'瓢饮唯三径',
'岩栖在百层',
'且持蠡测海',
'况挹酒如渑',
'鸿宝宁全秘',
'丹梯庶可凌',
'淮王门有客',
'终不愧孙登',
],
},
{
title: '郑驸马宅宴洞中',
body: [
'主家阴洞细烟雾',
'留客夏簟清琅玕',
'春酒杯浓琥珀薄',
'冰浆碗碧玛瑙寒',
'误疑茅堂过江麓',
'已入风磴霾云端',
'自是秦楼压郑谷',
'时闻杂佩声珊珊',
],
},
{
title: '李监宅',
body: [
'尚觉王孙贵',
'豪家意颇浓',
'屏开金孔雀',
'褥隐绣芙蓉',
'且食双鱼美',
'谁看异味重',
'门阑多喜色',
'女婿近乘龙',
],
},
{
title: '重题郑氏东亭(在新安界)',
body: [
'华亭入翠微',
'秋日乱清晖',
'崩石欹山树',
'清涟曳水衣',
'紫鳞冲岸跃',
'苍隼护巢归',
'向晚寻征路',
'残云傍马飞',
],
},
{
title: '题张氏隐居二首',
body: [
'春山无伴独相求',
'伐木丁丁山更幽',
'涧道馀寒历冰雪',
'石门斜日到林丘',
'不贪夜识金银气',
'远害朝看麋鹿游',
'乘兴杳然迷出处',
'对君疑是泛虚舟',
'之子时相见',
'邀人晚兴留',
'霁潭鳣发发',
'春草鹿呦呦',
'杜酒偏劳劝',
'张梨不外求',
'前村山路险',
'归醉每无愁',
],
},
{
title: '天宝初南曹小司寇舅于我太夫人堂下累土为山…而作是诗',
body: [
'一匮功盈尺',
'三峰意出群',
'望中疑在野',
'幽处欲生云',
'慈竹春阴覆',
'香炉晓势分',
'惟南将献寿',
'佳气日氛氲',
],
},
{
title: '龙门(即伊阙)',
body: [
'龙门横野断',
'驿树出城来',
'气色皇居近',
'金银佛寺开',
'往还时屡改',
'川水日悠哉',
'相阅征途上',
'生涯尽几回',
],
},
{
title: '奉寄河南韦尹丈人',
body: [
'有客传河尹',
'逢人问孔融',
'青囊仍隐逸',
'章甫尚西东',
'鼎食分门户',
'词场继国风',
'尊荣瞻地绝',
'疏放忆途穷',
'浊酒寻陶令',
'丹砂访葛洪',
'江湖漂短褐',
'霜雪满飞蓬',
'牢落乾坤大',
'周流道术空',
'谬惭知蓟子',
'真怯笑扬雄',
'盘错神明惧',
'讴歌德义丰',
'尸乡馀土室',
'难说祝鸡翁',
],
},
{
title: '赠李白',
body: [
'秋来相顾尚飘蓬',
'未就丹砂愧葛洪',
'痛饮狂歌空度日',
'飞扬跋扈为谁雄',
],
},
{
title: '与任城许主簿游南池(池在济宁州境)',
body: [
'秋水通沟洫',
'城隅进小船',
'晚凉看洗马',
'森木乱鸣蝉',
'菱熟经时雨',
'蒲荒八月天',
'晨朝降白露',
'遥忆旧青毡',
],
},
{
title: '登兖州城楼',
body: [
'东郡趋庭日',
'南楼纵目初',
'浮云连海岳',
'平野入青徐',
'孤嶂秦碑在',
'荒城鲁殿馀',
'从来多古意',
'临眺独踌躇',
],
},
{
title: '刘九法曹、郑瑕丘石门宴集',
body: [
'秋水清无底',
'萧然静客心',
'掾曹乘逸兴',
'鞍马去相寻',
'能吏逢联璧',
'华筵直一金',
'晚来横吹好',
'泓下亦龙吟',
],
},
{
title: '暂如临邑,至gh山湖亭奉怀李员外率尔成兴',
body: [
'野亭逼湖水',
'歇马高林间',
'鼍吼风奔浪',
'鱼跳日映山',
'暂游阻词伯',
'却望怀青关',
'霭霭生云雾',
'唯应促驾还',
],
},
{
title: '对雨书怀,走邀许十一簿公',
body: [
'东岳云峰起',
'溶溶满太虚',
'震雷翻幕燕',
'骤雨落河鱼',
'座对贤人酒',
'门听长者车',
'相邀愧泥泞',
'骑马到阶除',
],
},
{
title: '巳上人茅斋',
body: [
'巳公茅屋下',
'可以赋新诗',
'枕簟入林僻',
'茶瓜留客迟',
'江莲摇白羽',
'天棘梦青丝',
'空忝许询辈',
'难酬支遁词',
],
},
{
title: '房兵曹胡马诗',
body: [
'胡马大宛名',
'锋棱瘦骨成',
'竹批双耳峻',
'风入四蹄轻',
'所向无空阔',
'真堪托死生',
'骁腾有如此',
'万里可横行',
],
},
{
title: '画鹰',
body: [
'素练风霜起',
'苍鹰画作殊',
'�身思狡兔',
'侧目似愁胡',
'绦镟光堪擿',
'轩楹势可呼',
'何当击凡鸟',
'毛血洒平芜',
],
},
{
title: '与李十二白同寻范十隐居(李白集有寻鲁城北范居士诗)',
body: [
'李侯有佳句',
'往往似阴铿',
'余亦东蒙客',
'怜君如弟兄',
'醉眠秋共被',
'携手日同行',
'更想幽期处',
'还寻北郭生',
'入门高兴发',
'侍立小童清',
'落景闻寒杵',
'屯云对古城',
'向来吟橘颂',
'谁欲讨莼羹',
'不愿论簪笏',
'悠悠沧海情',
],
},
{
title: '临邑舍弟书至苦雨黄河泛溢堤防之患簿领所忧…用宽其意',
body: [
'二仪积风雨',
'百谷漏波涛',
'闻道洪河坼',
'遥连沧海高',
'职思忧悄悄',
'郡国诉嗷嗷',
'舍弟卑栖邑',
'防川领簿曹',
'尺书前日至',
'版筑不时操',
'难假鼋鼍力',
'空瞻乌鹊毛',
'燕南吹畎亩',
'济上没蓬蒿',
'螺蚌满近郭',
'蛟螭乘九皋',
'徐关深水府',
'碣石小秋毫',
'白屋留孤树',
'青天矢万艘',
'吾衰同泛梗',
'利涉想蟠桃',
'倚赖天涯钓',
'犹能掣巨鳌',
],
},
{
title: '过宋员外之问旧庄',
body: [
'宋公旧池馆',
'零落守阳阿',
'枉道祗从入',
'吟诗许更过',
'淹留问耆老',
'寂寞向山河',
'更识将军树',
'悲风日暮多',
],
},
{
title: '夜宴左氏庄',
body: [
'风林纤月落',
'衣露净琴张',
'暗水流花径',
'春星带草堂',
'检书烧烛短',
'看剑引杯长',
'诗罢闻吴咏',
'扁舟意不忘',
],
},
{
title: '送蔡希曾都尉还陇右,因寄高三十五书记',
body: [
'蔡子勇成癖',
'弯弓西射胡',
'健儿宁斗死',
'壮士耻为儒',
'官是先锋得',
'材缘挑战须',
'身轻一鸟过',
'枪急万人呼',
'云幕随开府',
'春城赴上都',
'马头金狎帢',
'驼背锦模糊',
'咫尺云山路',
'归飞青海隅',
'上公犹宠锡',
'突将且前驱',
'汉使黄河远',
'凉州白麦枯',
'因君问消息',
'好在阮元瑜',
],
},
{
title: '春日忆李白',
body: [
'白也诗无敌',
'飘然思不群',
'清新庾开府',
'俊逸鲍参军',
'渭北春天树',
'江东日暮云',
'何时一尊酒',
'重与细论文',
],
},
{
title: '赠陈二补阙',
body: [
'世儒多汩没',
'夫子独声名',
'献纳开东观',
'君王问长卿',
'皂雕寒始急',
'天马老能行',
'自到青冥里',
'休看白发生',
],
},
{
title: '寄高三十五书记(適)',
body: [
'叹惜高生老',
'新诗日又多',
'美名人不及',
'佳句法如何',
'主将收才子',
'崆峒足凯歌',
'闻君已朱绂',
'且得慰蹉跎',
],
},
{
title: '送裴二虬作尉永嘉',
body: [
'孤屿亭何处',
'天涯水气中',
'故人官就此',
'绝境兴谁同',
'隐吏逢梅福',
'游山忆谢公',
'扁舟吾已就',
'把钓待秋风',
],
},
{
title: '城西陂泛舟(即渼陂)',
body: [
'青蛾皓齿在楼船',
'横笛短箫悲远天',
'春风自信牙樯动',
'迟日徐看锦缆牵',
'鱼吹细浪摇歌扇',
'燕蹴飞花落舞筵',
'不有小舟能荡桨',
'百壶那送酒如泉',
],
},
{
title: '赠田九判官(梁丘)',
body: [
'崆峒使节上青霄',
'河陇降王款圣朝',
'宛马总肥春苜蓿',
'将军只数汉嫖姚',
'陈留阮瑀谁争长',
'京兆田郎早见招',
'麾下赖君才并入',
'独能无意向渔樵',
],
},
{
title: '赠献纳使起居田舍人(澄)',
body: [
'献纳司存雨露边',
'地分清切任才贤',
'舍人退食收封事',
'宫女开函近御筵',
'晓漏追飞青琐闼',
'晴窗点检白云篇',
'扬雄更有河东赋',
'唯待吹嘘送上天',
],
},
{
title: '送韦书记赴安西',
body: [
'夫子欻通贵',
'云泥相望悬',
'白头无藉在',
'朱绂有哀怜',
'书记赴三捷',
'公车留二年',
'欲浮江海去',
'此别意苍然',
],
},
{
title: '陪郑广文游何将军山林十首(山林在韦曲西塔陂)',
body: [
'不识南塘路',
'今知第五桥',
'名园依绿水',
'野竹上青霄',
'谷口旧相得',
'濠梁同见招',
'平生为幽兴',
'未惜马蹄遥',
'百顷风潭上',
'千重夏木清',
'卑枝低结子',
'接叶暗巢莺',
'鲜鲫银丝脍',
'香芹碧涧羹',
'翻疑柁楼底',
'晚饭越中行',
'万里戎王子',
'何年别月支',
'异花开绝域',
'滋蔓匝清池',
'汉使徒空到',
'神农竟不知',
'露翻兼雨打',
'开坼日离披',
'旁舍连高竹',
'疏篱带晚花',
'碾涡深没马',
'藤蔓曲藏蛇',
'词赋工无益',
'山林迹未赊',
'尽捻书籍卖',
'来问尔东家',
'剩水沧江破',
'残山碣石开',
'绿垂风折笋',
'红绽雨肥梅',
'银甲弹筝用',
'金鱼换酒来',
'兴移无洒扫',
'随意坐莓苔',
'风磴吹阴雪',
'云门吼瀑泉',
'酒醒思卧簟',
'衣冷欲装绵',
'野老来看客',
'河鱼不取钱',
'只疑淳朴处',
'自有一山川',
'棘树寒云色',
'茵蔯春藕香',
'脆添生菜美',
'阴益食单凉',
'野鹤清晨出',
'山精白日藏',
'石林蟠水府',
'百里独苍苍',
'忆过杨柳渚',
'走马定昆池',
'醉把青荷叶',
'狂遗白接z5',
'刺船思郢客',
'解水乞吴儿',
'坐对秦山晚',
'江湖兴颇随',
'床上书连屋',
'阶前树拂云',
'将军不好武',
'稚子总能文',
'醒酒微风入',
'听诗静夜分',
'絺衣挂萝薜',
'凉月白纷纷',
'幽意忽不惬',
'归期无奈何',
'出门流水注',
'回首白云多',
'自笑灯前舞',
'谁怜醉后歌',
'祗应与朋好',
'风雨亦来过',
],
},
{
title: '重过何氏五首',
body: [
'问讯东桥竹',
'将军有报书',
'倒衣还命驾',
'高枕乃吾庐',
'花妥莺捎蝶',
'溪喧獭趁鱼',
'重来休沐地',
'真作野人居',
'山雨尊仍在',
'沙沈榻未移',
'犬迎曾宿客',
'鸦护落巢儿',
'云薄翠微寺',
'天清黄子陂',
'向来幽兴极',
'步屣过东篱',
'落日平台上',
'春风啜茗时',
'石阑斜点笔',
'桐叶坐题诗',
'翡翠鸣衣桁',
'蜻蜓立钓丝',
'自今幽兴熟',
'来往亦无期',
'颇怪朝参懒',
'应耽野趣长',
'雨抛金锁甲',
'苔卧绿沈枪',
'手自移蒲柳',
'家才足稻粱',
'看君用幽意',
'白日到羲皇',
'到此应常宿',
'相留可判年',
'蹉跎暮容色',
'怅望好林泉',
'何路沾微禄',
'归山买薄田',
'斯游恐不遂',
'把酒意茫然',
],
},
{
title: '冬日有怀李白',
body: [
'寂寞书斋里',
'终朝独尔思',
'更寻嘉树传',
'不忘角弓诗',
'短褐风霜入',
'还丹日月迟',
'未因乘兴去',
'空有鹿门期',
],
},
{
title: '杜位宅守岁',
body: [
'守岁阿戎家',
'椒盘已颂花',
'盍簪喧枥马',
'列炬散林鸦',
'四十明朝过',
'飞腾暮景斜',
'谁能更拘束',
'烂醉是生涯',
],
},
{
title: '与鄠县源大少府宴渼陂(得寒字)',
body: [
'应为西陂好',
'金钱罄一餐',
'饭抄云子白',
'瓜嚼水精寒',
'无计回船下',
'空愁避酒难',
'主人情烂熳',
'持答翠琅玕',
],
},
{
title: '崔驸马山亭宴集(京城东有崔惠童驸马山池)',
body: [
'萧史幽栖地',
'林间蹋凤毛',
'洑流何处入',
'乱石闭门高',
'客醉挥金碗',
'诗成得绣袍',
'清秋多宴会',
'终日困香醪',
],
},
{
title: '九日杨奉先会白水崔明府',
body: [
'今日潘怀县',
'同时陆浚仪',
'坐开桑落酒',
'来把菊花枝',
'天宇清霜净',
'公堂宿雾披',
'晚酣留客舞',
'凫舄共差池',
],
},
{
title: '赠翰林张四学士',
body: [
'翰林逼华盖',
'鲸力破沧溟',
'天上张公子',
'宫中汉客星',
'赋诗拾翠殿',
'佐酒望云亭',
'紫诰仍兼绾',
'黄麻似六经',
'内分金带赤',
'恩与荔枝青',
'无复随高凤',
'空馀泣聚萤',
'此生任春草',
'垂老独漂萍',
'倘忆山阳会',
'悲歌在一听',
],
},
{
title: '送张二十参军赴蜀州,因呈杨五侍御',
body: [
'好去张公子',
'通家别恨添',
'两行秦树直',
'万点蜀山尖',
'御史新骢马',
'参军旧紫髯',
'皇华吾善处',
'于汝定无嫌',
],
},
{
title: '陪诸贵公子丈八沟携妓纳凉,晚际遇雨二首',
body: [
'落日放船好',
'轻风生浪迟',
'竹深留客处',
'荷净纳凉时',
'公子调冰水',
'佳人雪藕丝',
'片云头上黑',
'应是雨催诗',
'雨来沾席上',
'风急打船头',
'越女红裙湿',
'燕姬翠黛愁',
'缆侵堤柳系',
'幔宛浪花浮',
'归路翻萧飒',
'陂塘五月秋',
],
},
{
title: '白水明府舅宅喜雨(得过字)',
body: [
'吾舅政如此',
'古人谁复过',
'碧山晴又湿',
'白水雨偏多',
'精祷既不昧',
'欢娱将谓何',
'汤年旱颇甚',
'今日醉弦歌',
],
},
{
title: '陪李金吾花下饮',
body: [
'胜地初相引',
'余行得自娱',
'见轻吹鸟毳',
'随意数花须',
'细草称偏坐',
'香醪懒再酤',
'醉归应犯夜',
'可怕李金吾',
],
},
{
title: '赠高式颜',
body: [
'昔别是何处',
'相逢皆老夫',
'故人还寂寞',
'削迹共艰虞',
'自失论文友',
'空知卖酒垆',
'平生飞动意',
'见尔不能无',
],
},
{
title: '赠比部萧郎中十兄(甫从姑子也)',
body: [
'有美生人杰',
'由来积德门',
'汉朝丞相系',
'梁日帝王孙',
'蕴藉为郎久',
'魁梧秉哲尊',
'词华倾后辈',
'风雅蔼孤鶱',
'宅相荣姻戚',
'儿童惠讨论',
'见知真自幼',
'谋拙丑诸昆',
'漂荡云天阔',
'沈埋日月奔',
'致君时已晚',
'怀古意空存',
'中散山阳锻',
'愚公野谷村',
'宁纡长者辙',
'归老任乾坤',
],
},
{
title: '九日曲江',
body: [
'缀席茱萸好',
'浮舟菡萏衰',
'季秋时欲半',
'九日意兼悲',
'江水清源曲',
'荆门此路疑',
'晚来高兴尽',
'摇荡菊花期',
],
},
{
title: '承沈八丈东美除膳部员外,阻雨未遂驰贺,奉寄此诗',
body: [
'今日西京掾',
'多除内省郎',
'通家惟沈氏',
'谒帝似冯唐',
'诗律群公问',
'儒门旧史长',
'清秋便寓直',
'列宿顿辉光',
'未暇申宴慰',
'含情空激扬',
'司存何所比',
'膳部默凄伤',
'贫贱人事略',
'经过霖潦妨',
'礼同诸父长',
'恩岂布衣忘',
'天路牵骐骥',
'云台引栋梁',
'徒怀贡公喜',
'飒飒鬓毛苍',
],
},
{
title: '奉留赠集贤院崔、于二学士(国辅、休烈)',
body: [
'昭代将垂白',
'途穷乃叫阍',
'气冲星象表',
'词感帝王尊',
'天老书题目',
'春官验讨论',
'倚风遗鶂路',
'随水到龙门',
'竟与蛟螭杂',
'空闻燕雀喧',
'青冥犹契阔',
'陵厉不飞翻',
'儒术诚难起',
'家声庶已存',
'故山多药物',
'胜概忆桃源',
'欲整还乡旆',
'长怀禁掖垣',
'谬称三赋在',
'难述二公恩',
],
},
{
title: '故武卫将军挽歌三首',
body: [
'严警当寒夜',
'前军落大星',
'壮夫思感决',
'哀诏惜精灵',
'王者今无战',
'书生已勒铭',
'封侯意疏阔',
'编简为谁青',
'舞剑过人绝',
'鸣弓射兽能',
'铦锋行惬顺',
'猛噬失蹻腾',
'赤羽千夫膳',
'黄河十月冰',
'横行沙漠外',
'神速至今称',
'哀挽青门去',
'新阡绛水遥',
'路人纷雨泣',
'天意飒风飘',
'部曲精仍锐',
'匈奴气不骄',
'无由睹雄略',
'大树日萧萧',
],
},
{
title: '官定后戏赠(时免河西尉,为右卫率府兵曹)',
body: [
'不作河西尉',
'凄凉为折腰',
'老夫怕趋走',
'率府且逍遥',
'耽酒须微禄',
'狂歌托圣朝',
'故山归兴尽',
'回首向风飙',
],
},
{
title: '九日蓝田崔氏庄',
body: [
'老去悲秋强自宽',
'兴来今日尽君欢',
'羞将短发还吹帽',
'笑倩旁人为正冠',
'蓝水远从千涧落',
'玉山高并两峰寒',
'明年此会知谁健',
'醉把茱萸子细看',
],
},
{
title: '崔氏东山草堂',
body: [
'爱汝玉山草堂静',
'高秋爽气相鲜新',
'有时自发钟磬响',
'落日更见渔樵人',
'盘剥白鸦谷口栗',
'饭煮青泥坊底芹',
'何为西庄王给事',
'柴门空闭锁松筠',
],
},
{
title: '对雪',
body: [
'战哭多新鬼',
'愁吟独老翁',
'乱云低薄暮',
'急雪舞回风',
'瓢弃尊无绿',
'炉存火似红',
'数州消息断',
'愁坐正书空',
],
},
{
title: '月夜',
body: [
'今夜鄜州月',
'闺中只独看',
'遥怜小儿女',
'未解忆长安',
'香雾云鬟湿',
'清辉玉臂寒',
'何时倚虚幌',
'双照泪痕干',
],
},
{
title: '遣兴',
body: [
'骥子好男儿',
'前年学语时',
'问知人客姓',
'诵得老夫诗',
'世乱怜渠小',
'家贫仰母慈',
'鹿门携不遂',
'雁足系难期',
'天地军麾满',
'山河战角悲',
'傥归免相失',
'见日敢辞迟',
],
},
{
title: '元日寄韦氏妹',
body: [
'近闻韦氏妹',
'迎在汉钟离',
'郎伯殊方镇',
'京华旧国移',
'春城回北斗',
'郢树发南枝',
'不见朝正使',
'啼痕满面垂',
],
},
{
title: '春望',
body: [
'国破山河在',
'城春草木深',
'感时花溅泪',
'恨别鸟惊心',
'烽火连三月',
'家书抵万金',
'白头搔更短',
'浑欲不胜簪',
],
},
{
title: '忆幼子(字骥子,时隔绝在鄜州)',
body: [
'骥子春犹隔',
'莺歌暖正繁',
'别离惊节换',
'聪慧与谁论',
'涧水空山道',
'柴门老树村',
'忆渠愁只睡',
'炙背俯晴轩',
],
},
{
title: '一百五日夜对月',
body: [
'无家对寒食',
'有泪如金波',
'斫却月中桂',
'清光应更多',
'仳离放红蕊',
'想像嚬青蛾',
'牛女漫愁思',
'秋期犹渡河',
],
},
{
title: '喜达行在所三首(原注:自京窜至凤翔)',
body: [
'西忆岐阳信',
'无人遂却回',
'眼穿当落日',
'心死著寒灰',
'雾树行相引',
'莲峰望忽开',
'所亲惊老瘦',
'辛苦贼中来',
'愁思胡笳夕',
'凄凉汉苑春',
'生还今日事',
'间道暂时人',
'司隶章初睹',
'南阳气已新',
'喜心翻倒极',
'呜咽泪沾巾',
'死去凭谁报',
'归来始自怜',
'犹瞻太白雪',
'喜遇武功天',
'影静千官里',
'心苏七校前',
'今朝汉社稷',
'新数中兴年',
],
},
{
title: '得家书',
body: [
'去凭游客寄',
'来为附家书',
'今日知消息',
'他乡且旧居',
'熊儿幸无恙',
'骥子最怜渠',
'临老羁孤极',
'伤时会合疏',
'二毛趋帐殿',
'一命侍鸾舆',
'北阙妖氛满',
'西郊白露初',
'凉风新过雁',
'秋雨欲生鱼',
'农事空山里',
'眷言终荷锄',
],
},
{
title: '奉赠严八阁老',
body: [
'扈圣登黄阁',
'明公独妙年',
'蛟龙得云雨',
'雕鹗在秋天',
'客礼容疏放',
'官曹可接联',
'新诗句句好',
'应任老夫传',
],
},
{
title: '奉送郭中丞兼太仆卿充陇右节度使三十韵(郭英乂)',
body: [
'诏发西山将',
'秋屯陇右兵',
'凄凉馀部曲',
'燀赫旧家声',
'雕鹗乘时去',
'骅骝顾主鸣',
'艰难须上策',
'容易即前程',
'斜日当轩盖',
'高风卷旆旌',
'松悲天水冷',
'沙乱雪山清',
'和虏犹怀惠',
'防边不敢惊',
'古来于异域',
'镇静示专征',
'燕蓟奔封豕',
'周秦触骇鲸',
'中原何惨黩',
'馀孽尚纵横',
'箭入昭阳殿',
'笳吟细柳营',
'内人红袖泣',
'王子白衣行',
'宸极祅星动',
'园陵杀气平',
'空馀金碗出',
'无复穗帷轻',
'毁庙天飞雨',
'焚宫火彻明',
'罘罳朝共落',
'棆桷夜同倾',
'三月师逾整',
'群胡势就烹',
'疮痍亲接战',
'勇决冠垂成',
'妙誉期元宰',
'殊恩且列卿',
'几时回节钺',
'戮力扫欃枪',
'圭窦三千士',
'云梯七十城',
'耻非齐说客',
'只似鲁诸生',
'通籍微班忝',
'周行独坐荣',
'随肩趋漏刻',
'短发寄簪缨',
'径欲依刘表',
'还疑厌祢衡',
'渐衰那此别',
'忍泪独含情',
'废邑狐狸语',
'空村虎豹争',
'人频坠涂炭',
'公岂忘精诚',
'元帅调新律',
'前军压旧京',
'安边仍扈从',
'莫作后功名',
],
},
{
title: '送杨六判官使西蕃',
body: [
'送远秋风落',
'西征海气寒',
'帝京氛祲满',
'人世别离难',
'绝域遥怀怒',
'和亲愿结欢',
'敕书怜赞普',
'兵甲望长安',
'宣命前程急',
'惟良待士宽',
'子云清自守',
'今日起为官',
'垂泪方投笔',
'伤时即据鞍',
'儒衣山鸟怪',
'汉节野童看',
'边酒排金醆',
'夷歌捧玉盘',
'草轻蕃马健',
'雪重拂庐干',
'慎尔参筹画',
'从兹正羽翰',
'归来权可取',
'九万一朝抟',
],
},
{
title: '月',
body: [
'天上秋期近',
'人间月影清',
'入河蟾不没',
'捣药兔长生',
'只益丹心苦',
'能添白发明',
'干戈知满地',
'休照国西营',
],
},
{
title: '留别贾严二阁老两院补阙(得云字)',
body: [
'田园须暂往',
'戎马惜离群',
'去远留诗别',
'愁多任酒醺',
'一秋常苦雨',
'今日始无云',
'山路时吹角',
'那堪处处闻',
],
},
{
title: '晚行口号',
body: [
'三川不可到',
'归路晚山稠',
'落雁浮寒水',
'饥乌集戍楼',
'市朝今日异',
'丧乱几时休',
'远愧梁江总',
'还家尚黑头',
],
},
{
title: '独酌成诗',
body: [
'灯花何太喜',
'酒绿正相亲',
'醉里从为客',
'诗成觉有神',
'兵戈犹在眼',
'儒术岂谋身',
'共被微官缚',
'低头愧野人',
],
},
{
title: '行次昭陵',
body: [
'旧俗疲庸主',
'群雄问独夫',
'谶归龙凤质',
'威定虎狼都',
'天属尊尧典',
'神功协禹谟',
'风云随绝足',
'日月继高衢',
'文物多师古',
'朝廷半老儒',
'直词宁戮辱',
'贤路不崎岖',
'往者灾犹降',
'苍生喘未苏',
'指麾安率土',
'荡涤抚洪炉',
'壮士悲陵邑',
'幽人拜鼎湖',
'玉衣晨自举',
'铁马汗常趋',
'松柏瞻虚殿',
'尘沙立暝途',
'寂寥开国日',
'流恨满山隅',
],
},
{
title: '重经昭陵',
body: [
'草昧英雄起',
'讴歌历数归',
'风尘三尺剑',
'社稷一戎衣',
'翼亮贞文德',
'丕承戢武威',
'圣图天广大',
'宗祀日光辉',
'陵寝盘空曲',
'熊罴守翠微',
'再窥松柏路',
'还见五云飞',
],
},
{
title: '喜闻官军已临贼境二十韵',
body: [
'胡虏潜京县',
'官军拥贼壕',
'鼎鱼犹假息',
'穴蚁欲何逃',
'帐殿罗玄冕',
'辕门照白袍',
'秦山当警跸',
'汉苑入旌旄',
'路失羊肠险',
'云横雉尾高',
'五原空壁垒',
'八水散风涛',
'今日看天意',
'游魂贷尔曹',
'乞降那更得',
'尚诈莫徒劳',
'元帅归龙种',
'司空握豹韬',
'前军苏武节',
'左将吕虔刀',
'兵气回飞鸟',
'威声没巨鳌',
'戈鋋开雪色',
'弓矢尚秋毫',
'天步艰方尽',
'时和运更遭',
'谁云遗毒螫',
'已是沃腥臊',
'睿想丹墀近',
'神行羽卫牢',
'花门腾绝漠',
'拓羯渡临洮',
'此辈感恩至',
'羸俘何足操',
'锋先衣染血',
'骑突剑吹毛',
'喜觉都城动',
'悲怜子女号',
'家家卖钗钏',
'只待献春醪',
],
},
{
title: '收京三首',
body: [
'仙仗离丹极',
'妖星照玉除',
'须为下殿走',
'不可好楼居',
'暂屈汾阳驾',
'聊飞燕将书',
'依然七庙略',
'更与万方初',
'生意甘衰白',
'天涯正寂寥',
'忽闻哀痛诏',
'又下圣明朝',
'羽翼怀商老',
'文思忆帝尧',
'叨逢罪己日',
'沾洒望青霄',
'汗马收宫阙',
'春城铲贼壕',
'赏应歌杕杜',
'归及荐樱桃',
'杂虏横戈数',
'功臣甲第高',
'万方频送喜',
'无乃圣躬劳',
],
},
{
title: '腊日',
body: [
'腊日常年暖尚遥',
'今年腊日冻全消',
'侵陵雪色还萱草',
'漏泄春光有柳条',
'纵酒欲谋良夜醉',
'还家初散紫宸朝',
'口脂面药随恩泽',
'翠管银罂下九霄',
],
},
{
title: '紫宸殿退朝口号',
body: [
'户外昭容紫袖垂',
'双瞻御座引朝仪',
'香飘合殿春风转',
'花覆千官淑景移',
'昼漏希闻高阁报',
'天颜有喜近臣知',
'宫中每出归东省',
'会送夔龙集凤池',
],
},
{
title: '曲江二首',
body: [
'一片花飞减却春',
'风飘万点正愁人',
'且看欲尽花经眼',
'莫厌伤多酒入唇',
'江上小堂巢翡翠',
'花边高冢卧麒麟',
'细推物理须行乐',
'何用浮名绊此身',
'朝回日日典春衣',
'每日江头尽醉归',
'酒债寻常行处有',
'人生七十古来稀',
'穿花蛱蝶深深见',
'点水蜻蜓款款飞',
'传语风光共流转',
'暂时相赏莫相违',
],
},
{
title: '曲江对酒',
body: [
'苑外江头坐不归',
'水精春殿转霏微',
'桃花细逐杨花落',
'黄鸟时兼白鸟飞',
'纵饮久判人共弃',
'懒朝真与世相违',
'吏情更觉沧洲远',
'老大悲伤未拂衣',
],
},
{
title: '曲江对雨',
body: [
'城上春云覆苑墙',
'江亭晚色静年芳',
'林花著雨燕脂落',
'水荇牵风翠带长',
'龙武新军深驻辇',
'芙蓉别殿谩焚香',
'何时诏此金钱会',
'暂醉佳人锦瑟旁',
],
},
{
title: '奉和贾至舍人早朝大明宫',
body: [
'五夜漏声催晓箭',
'九重春色醉仙桃',
'旌旗日暖龙蛇动',
'宫殿风微燕雀高',
'朝罢香烟携满袖',
'诗成珠玉在挥毫',
'欲知世掌丝纶美',
'池上于今有凤毛',
],
},
{
title: '宣政殿退朝晚出左掖(掖门在两旁如人之臂掖)',
body: [
'天门日射黄金榜',
'春殿晴曛赤羽旗',
'宫草微微承委佩',
'炉烟细细驻游丝',
'云近蓬莱常好色',
'雪残鳷鹊亦多时',
'侍臣缓步归青琐',
'退食从容出每迟',
],
},
{
title: '题省中院壁',
body: [
'掖垣竹埤梧十寻',
'洞门对霤常阴阴',
'落花游丝白日静',
'鸣鸠乳燕青春深',
'腐儒衰晚谬通籍',
'退食迟回违寸心',
'衮职曾无一字补',
'许身愧比双南金',
],
},
{
title: '春宿左省',
body: [
'花隐掖垣暮',
'啾啾栖鸟过',
'星临万户动',
'月傍九霄多',
'不寝听金钥',
'因风想玉珂',
'明朝有封事',
'数问夜如何',
],
},
{
title: '送翰林张司马南海勒碑(相国制文)',
body: [
'冠冕通南极',
'文章落上台',
'诏从三殿去',
'碑到百蛮开',
'野馆浓花发',
'春帆细雨来',
'不知沧海上',
'天遣几时回',
],
},
{
title: '晚出左掖',
body: [
'昼刻传呼浅',
'春旗簇仗齐',
'退朝花底散',
'归院柳边迷',
'楼雪融城湿',
'宫云去殿低',
'避人焚谏草',
'骑马欲鸡栖',
],
},
{
title: '曲江陪郑八丈南史饮',
body: [
'雀啄江头黄柳花',
'��鸂鶒满晴沙',
'自知白发非春事',
'且尽芳尊恋物华',
'近侍即今难浪迹',
'此身那得更无家',
'丈人文力犹强健',
'岂傍青门学种瓜',
],
},
{
title: '送贾阁老出汝州',
body: [
'西掖梧桐树',
'空留一院阴',
'艰难归故里',
'去住损春心',
'宫殿青门隔',
'云山紫逻深',
'人生五马贵',
'莫受二毛侵',
],
},
{
title: '郑驸马池台喜遇郑广文同饮',
body: [
'不谓生戎马',
'何知共酒杯',
'然脐郿坞败',
'握节汉臣回',
'白发千茎雪',
'丹心一寸灰',
'别离经死地',
'披写忽登台',
'重对秦箫发',
'俱过阮宅来',
'留连春夜舞',
'泪落强裴回',
],
},
{
title: '送郑十八虔贬台州司户伤其临老陷贼之故阙…别情见于诗',
body: [
'郑公樗散鬓成丝',
'酒后常称老画师',
'万里伤心严谴日',
'百年垂死中兴时',
'苍惶已就长途往',
'邂逅无端出饯迟',
'便与先生应永诀',
'九重泉路尽交期',
],
},
{
title: '题郑十八著作虔',
body: [
'台州地阔海冥冥',
'云水长和岛屿青',
'乱后故人双别泪',
'春深逐客一浮萍',
'酒酣懒舞谁相拽',
'诗罢能吟不复听',
'第五桥东流恨水',
'皇陂岸北结愁亭',
'贾生对鵩伤王傅',
'苏武看羊陷贼庭',
'可念此翁怀直道',
'也沾新国用轻刑',
'祢衡实恐遭江夏',
'方朔虚传是岁星',
'穷巷悄然车马绝',
'案头干死读书萤',
],
},
{
title: '端午日赐衣',
body: [
'宫衣亦有名',
'端午被恩荣',
'细葛含风软',
'香罗叠雪轻',
'自天题处湿',
'当暑著来清',
'意内称长短',
'终身荷圣情',
],
},
{
title: '赠毕四(曜)',
body: [
'才大今诗伯',
'家贫苦宦卑',
'饥寒奴仆贱',
'颜状老翁为',
'同调嗟谁惜',
'论文笑自知',
'流传江鲍体',
'相顾免无儿',
],
},
{
title: '酬孟云卿',
body: [
'乐极伤头白',
'更长爱烛红',
'相逢难衮衮',
'告别莫匆匆',
'但恐天河落',
'宁辞酒盏空',
'明朝牵世务',
'挥泪各西东',
],
},
{
title: '奉赠王中允(维)',
body: [
'中允声名久',
'如今契阔深',
'共传收庾信',
'不比得陈琳',
'一病缘明主',
'三年独此心',
'穷愁应有作',
'试诵白头吟',
],
},
{
title: '奉陪郑驸马韦曲二首',
body: [
'韦曲花无赖',
'家家恼杀人',
'绿尊虽尽日',
'白发好禁春',
'石角钩衣破',
'藤枝刺眼新',
'何时占丛竹',
'头戴小乌巾',
'野寺垂杨里',
'春畦乱水间',
'美花多映竹',
'好鸟不归山',
'城郭终何事',
'风尘岂驻颜',
'谁能共公子',
'薄暮欲俱还',
],
},
{
title: '奉答岑参补阙见赠',
body: [
'窈窕清禁闼',
'罢朝归不同',
'君随丞相后',
'我往日华东',
'冉冉柳枝碧',
'娟娟花蕊红',
'故人得佳句',
'独赠白头翁',
],
},
{
title: '送许八拾遗归江宁觐省甫昔时尝客游此县…图样志诸篇末',
body: [
'诏许辞中禁',
'慈颜赴北堂',
'圣朝新孝理',
'祖席倍辉光',
'内帛擎偏重',
'宫衣著更香',
'淮阴清夜驿',
'京口渡江航',
'春隔鸡人昼',
'秋期燕子凉',
'赐书夸父老',
'寿酒乐城隍',
'看画曾饥渴',
'追踪恨淼茫',
'虎头金粟影',
'神妙独难忘',
],
},
{
title: '因许八奉寄江宁旻上人',
body: [
'不见旻公三十年',
'封书寄与泪潺湲',
'旧来好事今能否',
'老去新诗谁与传',
'棋局动随寻涧竹',
'袈裟忆上泛湖船',
'闻君话我为官在',
'头白昏昏只醉眠',
],
},
{
title: '至德二载甫自京金光门出问道归凤翔乾元初…有悲往事',
body: [
'此道昔归顺',
'西郊胡正繁',
'至今残破胆',
'应有未招魂',
'近得归京邑',
'移官岂至尊',
'无才日衰老',
'驻马望千门',
],
},
{
title: '寄高三十五詹事',
body: [
'安稳高詹事',
'兵戈久索居',
'时来如宦达',
'岁晚莫情疏',
'天上多鸿雁',
'池中足鲤鱼',
'相看过半百',
'不寄一行书',
],
},
{
title: '路逢襄阳杨少府入城,戏呈杨员外绾',
body: [
'寄语杨员外',
'山寒少茯苓',
'归来稍暄暖',
'当为劚青冥',
'翻动神仙窟',
'封题鸟兽形',
'兼将老藤杖',
'扶汝醉初醒',
],
},
{
title: '题郑县亭子(郑县游春亭在西溪上一名西溪亭)',
body: [
'郑县亭子涧之滨',
'户牖凭高发兴新',
'云断岳莲临大路',
'天晴宫柳暗长春',
'巢边野雀群欺燕',
'花底山蜂远趁人',
'更欲题诗满青竹',
'晚来幽独恐伤神',
],
},
{
title: '早秋苦热,堆案相仍(时任华州司功)',
body: [
'七月六日苦炎热',
'对食暂餐还不能',
'每愁夜中自足蝎',
'况乃秋后转多蝇',
'束带发狂欲大叫',
'簿书何急来相仍',
'南望青松架短壑',
'安得赤脚蹋层冰',
],
},
{
title: '望岳',
body: [
'西岳崚嶒竦处尊',
'诸峰罗立如儿孙',
'安得仙人九节杖',
'拄到玉女洗头盆',
'车箱入谷无归路',
'箭栝通天有一门',
'稍待西风凉冷后',
'高寻白帝问真源',
],
},
{
title: '至日遣兴,奉寄北省旧阁老两院故人二首',
body: [
'去岁兹辰捧御床',
'五更三点入鹓行',
'欲知趋走伤心地',
'正想氛氲满眼香',
'无路从容陪语笑',
'有时颠倒著衣裳',
'何人错忆穷愁日',
'愁日愁随一线长',
'忆昨逍遥供奉班',
'去年今日侍龙颜',
'麒麟不动炉烟上',
'孔雀徐开扇影还',
'玉几由来天北极',
'朱衣只在殿中间',
'孤城此日堪肠断',
'愁对寒云雪满山',
],
},
{
title: '得弟消息二首',
body: [
'近有平阴信',
'遥怜舍弟存',
'侧身千里道',
'寄食一家村',
'烽举新酣战',
'啼垂旧血痕',
'不知临老日',
'招得几人魂',
'汝懦归无计',
'吾衰往未期',
'浪传乌鹊喜',
'深负鶺鴒诗',
'生理何颜面',
'忧端且岁时',
'两京三十口',
'虽在命如丝',
],
},
{
title: '忆弟二首(时归在南陆浑庄)',
body: [
'丧乱闻吾弟',
'饥寒傍济州',
'人稀吾不到',
'兵在见何由',
'忆昨狂催走',
'无时病去忧',
'即今千种恨',
'惟共水东流',
'且喜河南定',
'不问邺城围',
'百战今谁在',
'三年望汝归',
'故园花自发',
'春日鸟还飞',
'断绝人烟久',
'东西消息稀',
],
},
{
title: '得舍弟消息',
body: [
'乱后谁归得',
'他乡胜故乡',
'直为心厄苦',
'久念与存亡',
'汝书犹在壁',
'汝妾已辞房',
'旧犬知愁恨',
'垂头傍我床',
],
},
{
title: '秦州杂诗二十首',
body: [
'满目悲生事',
'因人作远游',
'迟回度陇怯',
'浩荡及关愁',
'水落鱼龙夜',
'山空鸟鼠秋',
'西征问烽火',
'心折此淹留',
'秦州山北寺',
'胜迹隗嚣宫',
'苔藓山门古',
'丹青野殿空',
'月明垂叶露',
'云逐渡溪风',
'清渭无情极',
'愁时独向东',
'州图领同谷',
'驿道出流沙',
'降虏兼千帐',
'居人有万家',
'马骄珠汗落',
'胡舞白蹄斜',
'年少临洮子',
'西来亦自夸',
'鼓角缘边郡',
'川原欲夜时',
'秋听殷地发',
'风散入云悲',
'抱叶寒蝉静',
'归来独鸟迟',
'万方声一概',
'吾道竟何之',
'南使宜天马',
'由来万匹强',
'浮云连阵没',
'秋草遍山长',
'闻说真龙种',
'仍残老骕骦',
'哀鸣思战斗',
'迥立向苍苍',
'城上胡笳奏',
'山边汉节归',
'防河赴沧海',
'奉诏发金微',
'士苦形骸黑',
'旌疏鸟兽稀',
'那闻往来戍',
'恨解邺城围',
'莽莽万重山',
'孤城山谷间',
'无风云出塞',
'不夜月临关',
'属国归何晚',
'楼兰斩未还',
'烟尘独长望',
'衰飒正摧颜',
'闻道寻源使',
'从天此路回',
'牵牛去几许',
'宛马至今来',
'一望幽燕隔',
'何时郡国开',
'东征健儿尽',
'羌笛暮吹哀',
'今日明人眼',
'临池好驿亭',
'丛篁低地碧',
'高柳半天青',
'稠叠多幽事',
'喧呼阅使星',
'老夫如有此',
'不异在郊坰',
'云气接昆仑',
'涔涔塞雨繁',
'羌童看渭水',
'使客向河源',
'烟火军中幕',
'牛羊岭上村',
'所居秋草净',
'正闭小蓬门',
'萧萧古塞冷',
'漠漠秋云低',
'黄鹄翅垂雨',
'苍鹰饥啄泥',
'蓟门谁自北',
'汉将独征西',
'不意书生耳',
'临衰厌鼓鼙',
'山头南郭寺',
'水号北流泉',
'老树空庭得',
'清渠一邑传',
'秋花危石底',
'晚景卧钟边',
'俯仰悲身世',
'溪风为飒然',
'传道东柯谷',
'深藏数十家',
'对门藤盖瓦',
'映竹水穿沙',
'瘦地翻宜粟',
'阳坡可种瓜',
'船人近相报',
'但恐失桃花',
'万古仇池穴',
'潜通小有天',
'神鱼人不见',
'福地语真传',
'近接西南境',
'长怀十九泉',
'何时一茅屋',
'送老白云边',
'未暇泛沧海',
'悠悠兵马间',
'塞门风落木',
'客舍雨连山',
'阮籍行多兴',
'庞公隐不还',
'东柯遂疏懒',
'休镊鬓毛斑',
'东柯好崖谷',
'不与众峰群',
'落日邀双鸟',
'晴天养片云',
'野人矜险绝',
'水竹会平分',
'采药吾将老',
'儿童未遣闻',
'边秋阴易久',
'不复辨晨光',
'檐雨乱淋幔',
'山云低度墙',
'鸬鹚窥浅井',
'蚯蚓上深堂',
'车马何萧索',
'门前百草长',
'地僻秋将尽',
'山高客未归',
'塞云多断续',
'边日少光辉',
'警急烽常报',
'传闻檄屡飞',
'西戎外甥国',
'何得迕天威',
'凤林戈未息',
'鱼海路常难',
'候火云烽峻',
'悬军幕井干',
'风连西极动',
'月过北庭寒',
'故老思飞将',
'何时议筑坛',
'唐尧真自圣',
'野老复何知',
'晒药能无妇',
'应门幸有儿',
'藏书闻禹穴',
'读记忆仇池',
'为报鸳行旧',
'鹪鹩在一枝',
],
},
{
title: '月夜忆舍弟',
body: [
'戍鼓断人行',
'秋边一雁声',
'露从今夜白',
'月是故乡明',
'有弟皆分散',
'无家问死生',
'寄书长不避',
'况乃未休兵',
],
},
{
title: '宿赞公房(京中大云寺主谪此安置)',
body: [
'杖锡何来此',
'秋风已飒然',
'雨荒深院菊',
'霜倒半池莲',
'放逐宁违性',
'虚空不离禅',
'相逢成夜宿',
'陇月向人圆',
],
},
{
title: '东楼',
body: [
'万里流沙道',
'西征过北门',
'但添新战骨',
'不返旧征魂',
'楼角临风迥',
'城阴带水昏',
'传声看驿使',
'送节向河源',
],
},
{
title: '雨晴(一作秋霁)',
body: [
'天水秋云薄',
'从西万里风',
'今朝好晴景',
'久雨不妨农',
'塞柳行疏翠',
'山梨结小红',
'胡笳楼上发',
'一雁入高空',
],
},
{
title: '寓目',
body: [
'一县蒲萄熟',
'秋山苜蓿多',
'关云常带雨',
'塞水不成河',
'羌女轻烽燧',
'胡儿制骆驼',
'自伤迟暮眼',
'丧乱饱经过',
],
},
{
title: '山寺',
body: [
'野寺残僧少',
'山园细路高',
'麝香眠石竹',
'鹦鹉啄金桃',
'乱石通人过',
'悬崖置屋牢',
'上方重阁晚',
'百里见秋毫',
],
},
{
title: '即事',
body: [
'闻道花门破',
'和亲事却非',
'人怜汉公主',
'生得渡河归',
'秋思抛云髻',
'腰支胜宝衣',
'群凶犹索战',
'回首意多违',
],
},
{
title: '遣怀',
body: [
'愁眼看霜露',
'寒城菊自花',
'天风随断柳',
'客泪堕清笳',
'水净楼阴直',
'山昏塞日斜',
'夜来归鸟尽',
'啼杀后栖鸦',
],
},
{
title: '天河',
body: [
'常时任显晦',
'秋至辄分明',
'纵被微云掩',
'终能永夜清',
'含星动双阙',
'伴月照边城',
'牛女年年渡',
'何曾风浪生',
],
},
{
title: '初月',
body: [
'光细弦岂上',
'影斜轮未安',
'微升古塞外',
'已隐暮云端',
'河汉不改色',
'关山空自寒',
'庭前有白露',
'暗满菊花团',
],
},
{
title: '归燕',
body: [
'不独避霜雪',
'其如俦侣稀',
'四时无失序',
'八月自知归',
'春色岂相访',
'众雏还识机',
'故巢傥未毁',
'会傍主人飞',
],
},
{
title: '捣衣',
body: [
'亦知戍不返',
'秋至拭清砧',
'已近苦寒月',
'况经长别心',
'宁辞捣熨倦',
'一寄塞垣深',
'用尽闺中力',
'君听空外音',
],
},
{
title: '促织',
body: [
'促织甚微细',
'哀音何动人',
'草根吟不稳',
'床下夜相亲',
'久客得无泪',
'放妻难及晨',
'悲丝与急管',
'感激异天真',
],
},
{
title: '萤火',
body: [
'幸因腐草出',
'敢近太阳飞',
'未足临书卷',
'时能点客衣',
'随风隔幔小',
'带雨傍林微',
'十月清霜重',
'飘零何处归',
],
},
{
title: '蒹葭',
body: [
'摧折不自守',
'秋风吹若何',
'暂时花戴雪',
'几处叶沉波',
'体弱春风早',
'丛长夜露多',
'江湖后摇落',
'亦恐岁蹉跎',
],
},
{
title: '苦竹',
body: [
'青冥亦自守',
'软弱强扶持',
'味苦夏虫避',
'丛卑春鸟疑',
'轩墀曾不重',
'翦伐欲无辞',
'幸近幽人屋',
'霜根结在兹',
],
},
{
title: '除架',
body: [
'束薪已零落',
'瓠叶转萧疏',
'幸结白花了',
'宁辞青蔓除',
'秋虫声不去',
'暮雀意何如',
'寒事今牢落',
'人生亦有初',
],
},
{
title: '废畦',
body: [
'秋蔬拥霜露',
'岂敢惜凋残',
'暮景数枝叶',
'天风吹汝寒',
'绿沾泥滓尽',
'香与岁时阑',
'生意春如昨',
'悲君白玉盘',
],
},
{
title: '夕烽',
body: [
'夕烽来不近',
'每日报平安',
'塞上传光小',
'云边落点残',
'照秦通警急',
'过陇自艰难',
'闻道蓬莱殿',
'千门立马看',
],
},
{
title: '秋笛',
body: [
'清商欲尽奏',
'奏苦血沾衣',
'他日伤心极',
'征人白骨归',
'相逢恐恨过',
'故作发声微',
'不见秋云动',
'悲风稍稍飞',
],
},
{
title: '送远',
body: [
'带甲满天地',
'胡为君远行',
'亲朋尽一哭',
'鞍马去孤城',
'草木岁月晚',
'关河霜雪清',
'别离已昨日',
'因见古人情',
],
},
{
title: '观兵',
body: [
'北庭送壮士',
'貔虎数尤多',
'精锐旧无敌',
'边隅今若何',
'妖氛拥白马',
'元帅待雕戈',
'莫守邺城下',
'斩鲸辽海波',
],
},
{
title: '不归',
body: [
'河间尚征伐',
'汝骨在空城',
'从弟人皆有',
'终身恨不平',
'数金怜俊迈',
'总角爱聪明',
'面上三年土',
'春风草又生',
],
},
{
title: '天末怀李白',
body: [
'凉风起天末',
'君子意如何',
'鸿雁几时到',
'江湖秋水多',
'文章憎命达',
'魑魅喜人过',
'应共冤魂语',
'投诗赠汨罗',
],
},
{
title: '独立',
body: [
'空外一鸷鸟',
'河间双白鸥',
'飘飖搏击便',
'容易往来游',
'草露亦多湿',
'蛛丝仍未收',
'天机近人事',
'独立万端忧',
],
},
{
title: '日暮',
body: [
'日落风亦起',
'城头鸟尾讹',
'黄云高未动',
'白水已扬波',
'羌妇语还哭',
'胡儿行且歌',
'将军别换马',
'夜出拥雕戈',
],
},
{
title: '空囊',
body: [
'翠柏苦犹食',
'晨霞高可餐',
'世人共卤莽',
'吾道属艰难',
'不爨井晨冻',
'无衣床夜寒',
'囊空恐羞涩',
'留得一钱看',
],
},
{
title: '病马',
body: [
'乘尔亦已久',
'天寒关塞深',
'尘中老尽力',
'岁晚病伤心',
'毛骨岂殊众',
'驯良犹至今',
'物微意不浅',
'感动一沉吟',
],
},
{
title: '蕃剑',
body: [
'致此自僻远',
'又非珠玉装',
'如何有奇怪',
'每夜吐光芒',
'虎气必腾踔',
'龙身宁久藏',
'风尘苦未息',
'持汝奉明王',
],
},
{
title: '铜瓶',
body: [
'乱后碧井废',
'时清瑶殿深',
'铜瓶未失水',
'百丈有哀音',
'侧想美人意',
'应非寒甃沉',
'蛟龙半缺落',
'犹得折黄金',
],
},
{
title: '观安西兵过赴关中待命二首',
body: [
'四镇富精锐',
'摧锋皆绝伦',
'还闻献士卒',
'足以静风尘',
'老马夜知道',
'苍鹰饥著人',
'临危经久战',
'用急始如神',
'奇兵不在众',
'万马救中原',
'谈笑无河北',
'心肝奉至尊',
'孤云随杀气',
'飞鸟避辕门',
'竟日留欢乐',
'城池未觉喧',
],
},
{
title: '送人从军',
body: [
'弱水应无地',
'阳关已近天',
'今君渡沙碛',
'累月断人烟',
'好武宁论命',
'封侯不计年',
'马寒防失道',
'雪没锦鞍鞯',
],
},
{
title: '野望',
body: [
'清秋望不极',
'迢递起曾阴',
'远水兼天净',
'孤城隐雾深',
'叶稀风更落',
'山迥日初沈',
'独鹤归何晚',
'昏鸦已满林',
],
},
{
title: '示侄佐(佐草堂在东柯谷)',
body: [
'多病秋风落',
'君来慰眼前',
'自闻茅屋趣',
'只想竹林眠',
'满谷山云起',
'侵篱涧水悬',
'嗣宗诸子侄',
'早觉仲容贤',
],
},
{
title: '佐还山后寄三首',
body: [
'山晚浮云合',
'归时恐路迷',
'涧寒人欲到',
'村黑鸟应栖',
'野客茅茨小',
'田家树木低',
'旧谙疏懒叔',
'须汝故相携',
'白露黄粱熟',
'分张素有期',
'已应舂得细',
'颇觉寄来迟',
'味岂同金菊',
'香宜配绿葵',
'老人他日爱',
'正想滑流匙',
'几道泉浇圃',
'交横落慢坡',
'葳蕤秋叶少',
'隐映野云多',
'隔沼连香芰',
'通林带女萝',
'甚闻霜薤白',
'重惠意如何',
],
},
{
title: '从人觅小胡孙许寄',
body: [
'人说南州路',
'山猿树树悬',
'举家闻若骇',
'为寄小如拳',
'预哂愁胡面',
'初调见马鞭',
'许求聪慧者',
'童稚捧应癫',
],
},
{
title: '秋日阮隐居致薤三十束',
body: [
'隐者柴门内',
'畦蔬绕舍秋',
'盈筐承露薤',
'不待致书求',
'束比青刍色',
'圆齐玉箸头',
'衰年关鬲冷',
'味暖并无忧',
],
},
{
title: '秦州见敕目薛三璩授司议郎毕四曜除监察与二…凡三十韵',
body: [
'大雅何寥阔',
'斯人尚典刑',
'交期余潦倒',
'材力尔精灵',
'二子声同日',
'诸生困一经',
'文章开穾奥',
'迁擢润朝廷',
'旧好何由展',
'新诗更忆听',
'别来头并白',
'相见眼终青',
'伊昔贫皆甚',
'同忧心不宁',
'栖遑分半菽',
'浩荡逐流萍',
'俗态犹猜忌',
'妖氛忽杳冥',
'独惭投汉阁',
'俱议哭秦庭',
'还蜀只无补',
'囚梁亦固扃',
'华夷相混合',
'宇宙一膻腥',
'帝力收三统',
'天威总四溟',
'旧都俄望幸',
'清庙肃惟馨',
'杂种虽高垒',
'长驱甚建瓴',
'焚香淑景殿',
'涨水望云亭',
'法驾初还日',
'群公若会星',
'宫臣仍点染',
'柱史正零丁',
'官忝趋栖凤',
'朝回叹聚萤',
'唤人看騕褭',
'不嫁惜娉婷',
'掘剑知埋狱',
'提刀见发硎',
'侏儒应共饱',
'渔父忌偏醒',
'旅泊穷清渭',
'长吟望浊泾',
'羽书还似急',
'烽火未全停',
'师老资残寇',
'戎生及近坰',
'忠臣辞愤激',
'烈士涕飘零',
'上将盈边鄙',
'元勋溢鼎铭',
'仰思调玉烛',
'谁定握青萍',
'陇俗轻鹦鹉',
'原情类鶺鴒',
'秋风动关塞',
'高卧想仪形',
],
},
{
title: '寄彭州高三十五使君適、虢州岑二十七长史参三十韵',
body: [
'故人何寂寞',
'今我独凄凉',
'老去才难尽',
'秋来兴甚长',
'物情尤可见',
'辞客未能忘',
'海内知名士',
'云端各异方',
'高岑殊缓步',
'沈鲍得同行',
'意惬关飞动',
'篇终接混茫',
'举天悲富骆',
'近代惜卢王',
'似尔官仍贵',
'前贤命可伤',
'诸侯非弃掷',
'半刺已翱翔',
'诗好几时见',
'书成无信将',
'男儿行处是',
'客子斗身强',
'羁旅推贤圣',
'沈绵抵咎殃',
'三年犹疟疾',
'一鬼不销亡',
'隔日搜脂髓',
'增寒抱雪霜',
'徒然潜隙地',
'有靦屡鲜妆',
'何太龙钟极',
'于今出处妨',
'无钱居帝里',
'尽室在边疆',
'刘表虽遗恨',
'庞公至死藏',
'心微傍鱼鸟',
'肉瘦怯豺狼',
'陇草萧萧白',
'洮云片片黄',
'彭门剑阁外',
'虢略鼎湖旁',
'荆玉簪头冷',
'巴笺染翰光',
'乌麻蒸续晒',
'丹橘露应尝',
'岂异神仙宅',
'俱兼山水乡',
'竹斋烧药灶',
'花屿读书床',
'更得清新否',
'遥知对属忙',
'旧官宁改汉',
'淳俗本归唐',
'济世宜公等',
'安贫亦士常',
'蚩尤终戮辱',
'胡羯漫猖狂',
'会待袄氛静',
'论文暂裹粮',
],
},
{
title: '寄岳州贾司马六丈、巴州严八使君两阁老五十韵',
body: [
'衡岳啼猿里',
'巴州鸟道边',
'故人俱不利',
'谪宦两悠然',
'开辟乾坤正',
'荣枯雨露偏',
'长沙才子远',
'钓濑客星悬',
'忆昨趋行殿',
'殷忧捧御筵',
'讨胡愁李广',
'奉使待张骞',
'无复云台仗',
'虚修水战船',
'苍茫城七十',
'流落剑三千',
'画角吹秦晋',
'旄头俯涧瀍',
'小儒轻董卓',
'有识笑苻坚',
'浪作禽填海',
'那将血射天',
'万方思助顺',
'一鼓气无前',
'阴散陈仓北',
'晴熏太白巅',
'乱麻尸积卫',
'破竹势临燕',
'法驾还双阙',
'王师下八川',
'此时沾奉引',
'佳气拂周旋',
'貔虎开金甲',
'麒麟受玉鞭',
'侍臣谙入仗',
'厩马解登仙',
'花动朱楼雪',
'城凝碧树烟',
'衣冠心惨怆',
'故老泪潺湲',
'哭庙悲风急',
'朝正霁景鲜',
'月分梁汉米',
'春得水衡钱',
'内蕊繁于缬',
'宫莎软胜绵',
'恩荣同拜手',
'出入最随肩',
'晚著华堂醉',
'寒重绣被眠',
'辔齐兼秉烛',
'书枉满怀笺',
'每觉升元辅',
'深期列大贤',
'秉钧方咫尺',
'铩翮再联翩',
'禁掖朋从改',
'微班性命全',
'青蒲甘受戮',
'白发竟谁怜',
'弟子贫原宪',
'诸生老伏虔',
'师资谦未达',
'乡党敬何先',
'旧好肠堪断',
'新愁眼欲穿',
'翠干危栈竹',
'红腻小湖莲',
'贾笔论孤愤',
'严诗赋几篇',
'定知深意苦',
'莫使众人传',
'贝锦无停织',
'朱丝有断弦',
'浦鸥防碎首',
'霜鹘不空拳',
'地僻昏炎瘴',
'山稠隘石泉',
'且将棋度日',
'应用酒为年',
'典郡终微眇',
'治中实弃捐',
'安排求傲吏',
'比兴展归田',
'去去才难得',
'苍苍理又玄',
'古人称逝矣',
'吾道卜终焉',
'陇外翻投迹',
'渔阳复控弦',
'笑为妻子累',
'甘与岁时迁',
'亲故行稀少',
'兵戈动接联',
'他乡饶梦寐',
'失侣自屯邅',
'多病加淹泊',
'长吟阻静便',
'如公尽雄俊',
'志在必腾鶱',
],
},
{
title: '寄张十二山人彪三十韵',
body: [
'独卧嵩阳客',
'三违颍水春',
'艰难随老母',
'惨澹向时人',
'谢氏寻山屐',
'陶公漉酒巾',
'群凶弥宇宙',
'此物在风尘',
'历下辞姜被',
'关西得孟邻',
'早通交契密',
'晚接道流新',
'静者心多妙',
'先生艺绝伦',
'草书何太苦',
'诗兴不无神',
'曹植休前辈',
'张芝更后身',
'数篇吟可老',
'一字买堪贫',
'将恐曾防寇',
'深潜托所亲',
'宁闻倚门夕',
'尽力洁飧晨',
'疏懒为名误',
'驱驰丧我真',
'索居犹寂寞',
'相遇益悲辛',
'流转依边徼',
'逢迎念席珍',
'时来故旧少',
'乱后别离频',
'世祖修高庙',
'文公赏从臣',
'商山犹入楚',
'源水不离秦',
'存想青龙秘',
'骑行白鹿驯',
'耕岩非谷口',
'结草即河滨',
'肘后符应验',
'囊中药未陈',
'旅怀殊不惬',
'良觌渺无因',
'自古皆悲恨',
'浮生有屈伸',
'此邦今尚武',
'何处且依仁',
'鼓角凌天籁',
'关山信月轮',
'官场罗镇碛',
'贼火近洮岷',
'萧索论兵地',
'苍茫斗将辰',
'大军多处所',
'馀孽尚纷纶',
'高兴知笼鸟',
'斯文起获麟',
'穷秋正摇落',
'回首望松筠',
],
},
{
title: '寄李十二白二十韵',
body: [
'昔年有狂客',
'号尔谪仙人',
'笔落惊风雨',
'诗成泣鬼神',
'声名从此大',
'汩没一朝伸',
'文彩承殊渥',
'流传必绝伦',
'龙舟移棹晚',
'兽锦夺袍新',
'白日来深殿',
'青云满后尘',
'乞归优诏许',
'遇我宿心亲',
'未负幽栖志',
'兼全宠辱身',
'剧谈怜野逸',
'嗜酒见天真',
'醉舞梁园夜',
'行歌泗水春',
'才高心不展',
'道屈善无邻',
'处士祢衡俊',
'诸生原宪贫',
'稻粱求未足',
'薏苡谤何频',
'五岭炎蒸地',
'三危放逐臣',
'几年遭鵩鸟',
'独泣向麒麟',
'苏武先还汉',
'黄公岂事秦',
'楚筵辞醴日',
'梁狱上书辰',
'已用当时法',
'谁将此义陈',
'老吟秋月下',
'病起暮江滨',
'莫怪恩波隔',
'乘槎与问津',
],
},
{
title: '蜀相(诸葛亮祠在昭烈庙西)',
body: [
'丞相祠堂何处寻',
'锦官城外柏森森',
'映阶碧草自春色',
'隔叶黄鹂空好音',
'三顾频烦天下计',
'两朝开济老臣心',
'出师未捷身先死',
'长使英雄泪满襟',
],
},
{
title: '卜居',
body: [
'浣花流水水西头',
'主人为卜林塘幽',
'已知出郭少尘事',
'更有澄江销客愁',
'无数蜻蜓齐上下',
'一双鸂鶒对沉浮',
'东行万里堪乘兴',
'须向山阴上小舟',
],
},
{
title: '一室',
body: [
'一室他乡远',
'空林暮景悬',
'正愁闻塞笛',
'独立见江船',
'巴蜀来多病',
'荆蛮去几年',
'应同王粲宅',
'留井岘山前',
],
},
{
title: '梅雨',
body: [
'南京西浦道',
'四月熟黄梅',
'湛湛长江去',
'冥冥细雨来',
'茅茨疏易湿',
'云雾密难开',
'竟日蛟龙喜',
'盘涡与岸回',
],
},
{
title: '为农',
body: [
'锦里烟尘外',
'江村八九家',
'圆荷浮小叶',
'细麦落轻花',
'卜宅从兹老',
'为农去国赊',
'远惭句漏令',
'不得问丹砂',
],
},
{
title: '有客(一作宾至)',
body: [
'幽栖地僻经过少',
'老病人扶再拜难',
'岂有文章惊海内',
'漫劳车马驻江干',
'竟日淹留佳客坐',
'百年粗粝腐儒餐',
'不嫌野外无供给',
'乘兴还来看药栏',
],
},
{
title: '狂夫',
body: [
'万里桥西一草堂',
'百花潭水即沧浪',
'风含翠筱娟娟静',
'雨裛红蕖冉冉香',
'厚禄故人书断绝',
'恒饥稚子色凄凉',
'欲填沟壑唯疏放',
'自笑狂夫老更狂',
],
},
{
title: '宾至(一作有客)',
body: [
'患气经时久',
'临江卜宅新',
'喧卑方避俗',
'疏快颇宜人',
'有客过茅宇',
'呼儿正葛巾',
'自锄稀菜甲',
'小摘为情亲',
],
},
{
title: '王十五司马弟出郭相访,兼遗营茅屋赀',
body: [
'客里何迁次',
'江边正寂寥',
'肯来寻一老',
'愁破是今朝',
'忧我营茅栋',
'携钱过野桥',
'他乡唯表弟',
'还往莫辞遥',
],
},
{
title: '堂成',
body: [
'背郭堂成荫白茅',
'缘江路熟俯青郊',
'桤林碍日吟风叶',
'笼竹和烟滴露梢',
'暂止飞乌将数子',
'频来语燕定新巢',
'旁人错比扬雄宅',
'懒惰无心作解嘲',
],
},
{
title: '田舍',
body: [
'田舍清江曲',
'柴门古道旁',
'草深迷市井',
'地僻懒衣裳',
'榉柳枝枝弱',
'枇杷树树香',
'鸬鹚西日照',
'晒翅满鱼梁',
],
},
{
title: '进艇',
body: [
'南京久客耕南亩',
'北望伤神坐北窗',
'昼引老妻乘小艇',
'晴看稚子浴清江',
'俱飞蛱蝶元相逐',
'并蒂芙蓉本自双',
'茗饮蔗浆携所有',
'瓷罂无谢玉为缸',
],
},
{
title: '西郊',
body: [
'时出碧鸡坊',
'西郊向草堂',
'市桥官柳细',
'江路野梅香',
'傍架齐书帙',
'看题减药囊',
'无人觉来往',
'疏懒意何长',
],
},
{
title: '所思',
body: [
'苦忆荆州醉司马',
'谪官樽俎定常开',
'九江日落醒何处',
'一柱观头眠几回',
'可怜怀抱向人尽',
'欲问平安无使来',
'故凭锦水将双泪',
'好过瞿塘滟滪堆',
],
},
{
title: '江村',
body: [
'清江一曲抱村流',
'长夏江村事事幽',
'自去自来堂上燕',
'相亲相近水中鸥',
'老妻画纸为棋局',
'稚子敲针作钓钩',
'多病所须唯药物',
'微躯此外更何求',
],
},
{
title: '江涨',
body: [
'江涨柴门外',
'儿童报急流',
'下床高数尺',
'倚杖没中洲',
'细动迎风燕',
'轻摇逐浪鸥',
'渔人萦小楫',
'容易拔船头',
],
},
{
title: '野老',
body: [
'野老篱前江岸回',
'柴门不正逐江开',
'渔人网集澄潭下',
'贾客船随返照来',
'长路关心悲剑阁',
'片云何意傍琴台',
'王师未报收东郡',
'城阙秋生画角哀',
],
},
{
title: '云山',
body: [
'京洛云山外',
'音书静不来',
'神交作赋客',
'力尽望乡台',
'衰疾江边卧',
'亲朋日暮回',
'白鸥元水宿',
'何事有馀哀',
],
},
{
title: '遣兴',
body: [
'干戈犹未定',
'弟妹各何之',
'拭泪沾襟血',
'梳头满面丝',
'地卑荒野大',
'天远暮江迟',
'衰疾那能久',
'应无见汝时',
],
},
{
title: '北邻',
body: [
'明府岂辞满',
'藏身方告劳',
'青钱买野竹',
'白帻岸江皋',
'爱酒晋山简',
'能诗何水曹',
'时来访老疾',
'步屟到蓬蒿',
],
},
{
title: '南邻',
body: [
'锦里先生乌角巾',
'园收芋粟不全贫',
'惯看宾客儿童喜',
'得食阶除鸟雀驯',
'秋水才深四五尺',
'野航恰受两三人',
'白沙翠竹江村暮',
'相对柴门月色新',
],
},
{
title: '出郭',
body: [
'霜露晚凄凄',
'高天逐望低',
'远烟盐井上',
'斜景雪峰西',
'故国犹兵马',
'他乡亦鼓鼙',
'江城今夜客',
'还与旧乌啼',
],
},
{
title: '过南邻朱山人水亭',
body: [
'相近竹参差',
'相过人不知',
'幽花欹满树',
'小水细通池',
'归客村非远',
'残樽席更移',
'看君多道气',
'从此数追随',
],
},
{
title: '恨别',
body: [
'洛城一别四千里',
'胡骑长驱五六年',
'草木变衰行剑外',
'兵戈阻绝老江边',
'思家步月清宵立',
'忆弟看云白日眠',
'闻道河阳近乘胜',
'司徒急为破幽燕',
],
},
{
title: '寄贺兰铦',
body: [
'朝野欢娱后',
'乾坤震荡中',
'相随万里日',
'总作白头翁',
'岁晚仍分袂',
'江边更转蓬',
'勿云俱异域',
'饮啄几回同',
],
},
{
title: '寄杨五桂州谭(因州参军段子之任)',
body: [
'五岭皆炎热',
'宜人独桂林',
'梅花万里外',
'雪片一冬深',
'闻此宽相忆',
'为邦复好音',
'江边送孙楚',
'远附白头吟',
],
},
{
title: '逢唐兴刘主簿弟',
body: [
'分手开元末',
'连年绝尺书',
'江山且相见',
'戎马未安居',
'剑外官人冷',
'关中驿骑疏',
'轻舟下吴会',
'主簿意何如',
],
},
{
title: '和裴迪登新津寺寄王侍郎',
body: [
'何限倚山木',
'吟诗秋叶黄',
'蝉声集古寺',
'鸟影度寒塘',
'风物悲游子',
'登临忆侍郎',
'老夫贪佛日',
'随意宿僧房',
],
},
{
title: '敬简王明府(甫尝为唐兴县宰王潜作客馆记疑即王明府)',
body: [
'叶县郎官宰',
'周南太史公',
'神仙才有数',
'流落意无穷',
'骥病思偏秣',
'鹰愁怕苦笼',
'看君用高义',
'耻与万人同',
],
},
{
title: '重简王明府',
body: [
'甲子西南异',
'冬来只薄寒',
'江云何夜尽',
'蜀雨几时干',
'行李须相问',
'穷愁岂有宽',
'君听鸿雁响',
'恐致稻粱难',
],
},
{
title: '建都十二韵',
body: [
'苍生未苏息',
'胡马半乾坤',
'议在云台上',
'谁扶黄屋尊',
'建都分魏阙',
'下韶辟荆门',
'恐失东人望',
'其如西极存',
'时危当雪耻',
'计大岂轻论',
'虽倚三阶正',
'终愁万国翻',
'牵裾恨不死',
'漏网荷殊恩',
'永负汉庭哭',
'遥怜湘水魂',
'穷冬客江剑',
'随事有田园',
'风断青蒲节',
'霜埋翠竹根',
'衣冠空穰穰',
'关辅久昏昏',
'愿枉长安日',
'光辉照北原',
],
},
{
title: '岁暮',
body: [
'岁暮远为客',
'边隅还用兵',
'烟尘犯雪岭',
'鼓角动江城',
'天地日流血',
'朝廷谁请缨',
'济时敢爱死',
'寂寞壮心惊',
],
},
{
title: '和裴迪登蜀州东亭送客逢早梅相忆见寄',
body: [
'东阁官梅动诗兴',
'还如何逊在扬州',
'此时对雪遥相忆',
'送客逢春可自由',
'幸不折来伤岁暮',
'若为看去乱乡愁',
'江边一树垂垂发',
'朝夕催人自白头',
],
},
{
title: '寄赠王十将军承俊',
body: [
'将军胆气雄',
'臂悬两角弓',
'缠结青骢马',
'出入锦城中',
'时危未授钺',
'势屈难为功',
'宾客满堂上',
'何人高义同',
],
},
{
title: '暮登四安寺钟楼寄裴十(迪)',
body: [
'暮倚高楼对雪峰',
'僧来不语自鸣钟',
'孤城返照红将敛',
'近市浮烟翠且重',
'多病独愁常阒寂',
'故人相见未从容',
'知君苦思缘诗瘦',
'大向交游万事慵',
],
},
{
title: '散愁二首',
body: [
'久客宜旋旆',
'兴王未息戈',
'蜀星阴见少',
'江雨夜闻多',
'百万传深入',
'寰区望匪它',
'司徒下燕赵',
'收取旧山河',
'闻道并州镇',
'尚书训士齐',
'几时通蓟北',
'当日报关西',
'恋阙丹心破',
'沾衣皓首啼',
'老魂招不得',
'归路恐长迷',
],
},
{
title: '奉酬李都督表丈早春作',
body: [
'力疾坐清晓',
'来时悲早春',
'转添愁伴客',
'更觉老随人',
'红入桃花嫩',
'青归柳叶新',
'望乡应未已',
'四海尚风尘',
],
},
{
title: '客至(喜崔明府相过)',
body: [
'舍南舍北皆春水',
'但见群鸥日日来',
'花径不曾缘客扫',
'蓬门今始为君开',
'盘餐市远无兼味',
'樽酒家贫只旧醅',
'肯与邻翁相对饮',
'隔篱呼取尽馀杯',
],
},
{
title: '遣意二首',
body: [
'啭枝黄鸟近',
'泛渚白鸥轻',
'一径野花落',
'孤村春水生',
'衰年催酿黍',
'细雨更移橙',
'渐喜交游绝',
'幽居不用名',
'檐影微微落',
'津流脉脉斜',
'野船明细火',
'宿雁聚圆沙',
'云掩初弦月',
'香传小树花',
'邻人有美酒',
'稚子夜能赊',
],
},
{
title: '漫成二首',
body: [
'野日荒荒白',
'春流泯泯清',
'渚蒲随地有',
'村径逐门成',
'只作披衣惯',
'常从漉酒生',
'眼前无俗物',
'多病也身轻',
'江皋已仲春',
'花下复清晨',
'仰面贪看鸟',
'回头错应人',
'读书难字过',
'对酒满壶频',
'近识峨眉老',
'知予懒是真',
],
},
{
title: '春夜喜雨',
body: [
'好雨知时节',
'当春乃发生',
'随风潜入夜',
'润物细无声',
'野径云俱黑',
'江船火独明',
'晓看红湿处',
'花重锦官城',
],
},
{
title: '春水',
body: [
'三月桃花浪',
'江流复旧痕',
'朝来没沙尾',
'碧色动柴门',
'接缕垂芳饵',
'连筒灌小园',
'已添无数鸟',
'争浴故相喧',
],
},
{
title: '春水生二绝',
body: [
'二月六夜春水生',
'门前小滩浑欲平',
'鸬鹚鸂鶒莫漫喜',
'吾与汝曹俱眼明',
'一夜水高二尺强',
'数日不可更禁当',
'南市津头有船卖',
'无钱即买系篱旁',
],
},
{
title: '江亭',
body: [
'坦腹江亭暖',
'长吟野望时',
'水流心不竞',
'云在意俱迟',
'寂寂春将晚',
'欣欣物自私',
'故林归未得',
'排闷强裁诗',
],
},
{
title: '村夜',
body: [
'萧萧风色暮',
'江头人不行',
'村舂雨外急',
'邻火夜深明',
'胡羯何多难',
'渔樵寄此生',
'中原有兄弟',
'万里正含情',
],
},
{
title: '早起',
body: [
'春来常早起',
'幽事颇相关',
'帖石防隤岸',
'开林出远山',
'一丘藏曲折',
'缓步有跻攀',
'童仆来城市',
'瓶中得酒还',
],
},
{
title: '可惜',
body: [
'花飞有底急',
'老去愿春迟',
'可惜欢娱地',
'都非少壮时',
'宽心应是酒',
'遣兴莫过诗',
'此意陶潜解',
'吾生后汝期',
],
},
{
title: '落日',
body: [
'落日在帘钩',
'溪边春事幽',
'芳菲缘岸圃',
'樵爨倚滩舟',
'啅雀争枝坠',
'飞虫满院游',
'浊醪谁造汝',
'一酌散千忧',
],
},
{
title: '独酌',
body: [
'步屦深林晚',
'开樽独酌迟',
'仰蜂黏落絮',
'行蚁上枯梨',
'薄劣惭真隐',
'幽偏得自怡',
'本无轩冕意',
'不是傲当时',
],
},
{
title: '徐步',
body: [
'整履步青芜',
'荒庭日欲晡',
'芹泥随燕觜',
'花蕊上蜂须',
'把酒从衣湿',
'吟诗信杖扶',
'敢论才见忌',
'实有醉如愚',
],
},
{
title: '寒食',
body: [
'寒食江村路',
'风花高下飞',
'汀烟轻冉冉',
'竹日静晖晖',
'田父要皆去',
'邻家闹不违',
'地偏相识尽',
'鸡犬亦忘归',
],
},
{
title: '高楠',
body: [
'楠树色冥冥',
'江边一盖青',
'近根开药圃',
'接叶制茅亭',
'落景阴犹合',
'微风韵可听',
'寻常绝醉困',
'卧此片时醒',
],
},
{
title: '恶树',
body: [
'独绕虚斋径',
'常持小斧柯',
'幽阴成颇杂',
'恶木剪还多',
'枸杞因吾有',
'鸡栖奈汝何',
'方知不材者',
'生长漫婆娑',
],
},
{
title: '石镜',
body: [
'蜀王将此镜',
'送死置空山',
'冥寞怜香骨',
'提携近玉颜',
'众妃无复叹',
'千骑亦虚还',
'独有伤心石',
'埋轮月宇间',
],
},
{
title: '琴台(司马相如宅在州西笮桥,北有琴台)',
body: [
'茂陵多病后',
'尚爱卓文君',
'酒肆人间世',
'琴台日暮云',
'野花留宝靥',
'蔓草见罗裙',
'归凤求皇意',
'寥寥不复闻',
],
},
{
title: '闻斛斯六官未归',
body: [
'故人南郡去',
'去索作碑钱',
'本卖文为活',
'翻令室倒悬',
'荆扉深蔓草',
'土锉冷疏烟',
'老罢休无赖',
'归来省醉眠',
],
},
{
title: '游修觉寺',
body: [
'野寺江天豁',
'山扉花竹幽',
'诗应有神助',
'吾得及春游',
'径石相萦带',
'川云自去留',
'禅枝宿众鸟',
'漂转暮归愁',
],
},
{
title: '后游',
body: [
'寺忆新游处',
'桥怜再渡时',
'江山如有待',
'花柳更无私',
'野润烟光薄',
'沙暄日色迟',
'客愁全为减',
'舍此复何之',
],
},
{
title: '题新津北桥楼(得郊字)',
body: [
'望极春城上',
'开筵近鸟巢',
'白花檐外朵',
'青柳槛前梢',
'池水观为政',
'厨烟觉远庖',
'西川供客眼',
'唯有此江郊',
],
},
{
title: '江涨',
body: [
'江发蛮夷涨',
'山添雨雪流',
'大声吹地转',
'高浪蹴天浮',
'鱼鳖为人得',
'蛟龙不自谋',
'轻帆好去便',
'吾道付沧洲',
],
},
{
title: '晚晴',
body: [
'村晚惊风度',
'庭幽过雨沾',
'夕阳薰细草',
'江色映疏帘',
'书乱谁能帙',
'怀干可自添',
'时闻有馀论',
'未怪老夫潜',
],
},
{
title: '朝雨',
body: [
'凉气晚萧萧',
'江云乱眼飘',
'风鸳藏近渚',
'雨燕集深条',
'黄绮终辞汉',
'巢由不见尧',
'草堂樽酒在',
'幸得过清朝',
],
},
{
title: '江上值水如海势,聊短述',
body: [
'为人性僻耽佳句',
'语不惊人死不休',
'老去诗篇浑漫兴',
'春来花鸟莫深愁',
'新添水槛供垂钓',
'故著浮槎替入舟',
'焉得思如陶谢手',
'令渠述作与同游',
],
},
{
title: '送裴五赴东川',
body: [
'故人亦流落',
'高义动乾坤',
'何日通燕塞',
'相看老蜀门',
'东行应暂别',
'北望苦销魂',
'凛凛悲秋意',
'非君谁与论',
],
},
{
title: '赴青城县出成都,寄陶、王二少尹',
body: [
'老耻妻孥笑',
'贫嗟出入劳',
'客情投异县',
'诗态忆吾曹',
'东郭沧江合',
'西山白雪高',
'文章差底病',
'回首兴滔滔',
],
},
{
title: '因崔五侍御寄高彭州(適)',
body: ['百年已过半', '秋至转饥寒', '为问彭州牧', '何时救急难'],
},
{
title: '野望因过常少仙',
body: [
'野桥齐度马',
'秋望转悠哉',
'竹覆青城合',
'江从灌口来',
'入村樵径引',
'尝果栗皱开',
'落尽高天日',
'幽人未遣回',
],
},
{
title: '寄杜位(位京中宅近西曲江,诗尾有述)',
body: [
'近闻宽法离新州',
'想见怀归尚百忧',
'逐客虽皆万里去',
'悲君已是十年流',
'干戈况复尘随眼',
'鬓发还应雪满头',
'玉垒题书心绪乱',
'何时更得曲江游',
],
},
{
title: '奉简高三十五使君',
body: [
'当代论才子',
'如公复几人',
'骅骝开道路',
'鹰隼出风尘',
'行色秋将晚',
'交情老更亲',
'天涯喜相见',
'披豁对吾真',
],
},
{
title: '送韩十四江东觐省',
body: [
'兵戈不见老莱衣',
'叹息人间万事非',
'我已无家寻弟妹',
'君今何处访庭闱',
'黄牛峡静滩声转',
'白马江寒树影稀',
'此别应须各努力',
'故乡犹恐未同归',
],
},
{
title: '酬高使君相赠',
body: [
'古寺僧牢落',
'空房客寓居',
'故人供禄米',
'邻舍与园蔬',
'双树容听法',
'三车肯载书',
'草玄吾岂敢',
'赋或似相如',
],
},
{
title: '草堂即事',
body: [
'荒村建子月',
'独树老夫家',
'雾里江船渡',
'风前径竹斜',
'寒鱼依密藻',
'宿鹭起圆沙',
'蜀酒禁愁得',
'无钱何处赊',
],
},
{
title: '魏十四侍御就弊庐相别',
body: [
'有客骑骢马',
'江边问草堂',
'远寻留药价',
'惜别到文场',
'入幕旌旗动',
'归轩锦绣香',
'时应念衰疾',
'书疏及沧浪',
],
},
{
title: '徐九少尹见过',
body: [
'晚景孤村僻',
'行军数骑来',
'交新徒有喜',
'礼厚愧无才',
'赏静怜云竹',
'忘归步月台',
'何当看花蕊',
'欲发照江梅',
],
},
{
title: '范二员外邈、吴十侍御郁特枉驾阙展待,聊寄此',
body: [
'暂往比邻去',
'空闻二妙归',
'幽栖诚简略',
'衰白已光辉',
'野外贫家远',
'村中好客稀',
'论文或不愧',
'肯重款柴扉',
],
},
{
title: '王十七侍御抡许携酒至草堂奉寄…请邀高三十五使君同到',
body: [
'老夫卧稳朝慵起',
'白屋寒多暖始开',
'江鹳巧当幽径浴',
'邻鸡还过短墙来',
'绣衣屡许携家酝',
'皂盖能忘折野梅',
'戏假霜威促山简',
'须成一醉习池回',
],
},
{
title: '王竟携酒,高亦同过,共用寒字',
body: [
'卧病荒郊远',
'通行小径难',
'故人能领客',
'携酒重相看',
'自愧无鲑菜',
'空烦卸马鞍',
'移樽劝山简',
'头白恐风寒',
],
},
{
title: '陪李七司马皂江上观造竹桥即日成往来之…简李公二首',
body: [
'伐竹为桥结构同',
'褰裳不涉往来通',
'天寒白鹤归华表',
'日落青龙见水中',
'顾我老非题柱客',
'知君才是济川功',
'合欢却笑千年事',
'驱石何时到海东',
'把烛成桥夜',
'回舟坐客时',
'天高云去尽',
'江迥月来迟',
'衰谢多扶病',
'招邀屡有期',
'异方乘此兴',
'乐罢不无悲',
],
},
{
title: '李司马桥了承高使君自成都回',
body: [
'向来江上手纷纷',
'三日成功事出群',
'已传童子骑青竹',
'总拟桥东待使君',
],
},
{
title: '少年行二首',
body: [
'莫笑田家老瓦盆',
'自从盛酒长儿孙',
'倾银注瓦惊人眼',
'共醉终同卧竹根',
'巢燕养雏浑去尽',
'江花结子已无多',
'黄衫年少来宜数',
'不见堂前东逝波',
],
},
{
title: '野人送朱樱',
body: [
'西蜀樱桃也自红',
'野人相赠满筠笼',
'数回细写愁仍破',
'万颗匀圆讶许同',
'忆昨赐沾门下省',
'退朝擎出大明宫',
'金盘玉箸无消息',
'此日尝新任转蓬',
],
},
{
title: '即事',
body: ['百宝装腰带', '真珠络臂鞲', '笑时花近眼', '舞罢锦缠头'],
},
{
title: '赠花卿',
body: [
'锦城丝管日纷纷',
'半入江风半入云',
'此曲只应天上有',
'人间能得几回闻',
],
},
{
title: '少年行',
body: [
'马上谁家薄媚郎',
'临阶下马坐人床',
'不通姓字粗豪甚',
'指点银瓶索酒尝',
],
},
{
title: '观李固请司马弟山水图三首',
body: [
'简易高人意',
'匡床竹火炉',
'寒天留远客',
'碧海挂新图',
'虽对连山好',
'贪看绝岛孤',
'群仙不愁思',
'冉冉下蓬壶',
'方丈浑连水',
'天台总映云',
'人间长见画',
'老去恨空闻',
'范蠡舟偏小',
'王乔鹤不群',
'此生随万物',
'何路出尘氛',
'高浪垂翻屋',
'崩崖欲压床',
'野桥分子细',
'沙岸绕微茫',
'红浸珊瑚短',
'青悬薜荔长',
'浮查并坐得',
'仙老暂相将',
],
},
{
title: '题桃树',
body: [
'小径升堂旧不斜',
'五株桃树亦从遮',
'高秋总喂贫人实',
'来岁还舒满眼花',
'帘户每宜通乳燕',
'儿童莫信打慈鸦',
'寡妻群盗非今日',
'天下车书正一家',
],
},
{
title: '萧八明府堤处觅桃栽',
body: [
'奉乞桃栽一百根',
'春前为送浣花村',
'河阳县里虽无数',
'濯锦江边未满园',
],
},
{
title: '从韦二明府续处觅绵竹',
body: [
'华轩蔼蔼他年到',
'绵竹亭亭出县高',
'江上舍前无此物',
'幸分苍翠拂波涛',
],
},
{
title: '凭何十一少府邕觅桤木栽',
body: [
'草堂堑西无树林',
'非子谁复见幽心',
'饱闻桤木三年大',
'与致溪边十亩阴',
],
},
{
title: '凭韦少府班觅松树子',
body: [
'落落出群非榉柳',
'青青不朽岂杨梅',
'欲存老盖千年意',
'为觅霜根数寸栽',
],
},
{
title: '又于韦处乞大邑瓷碗',
body: [
'大邑烧瓷轻且坚',
'扣如哀玉锦城传',
'君家白碗胜霜雪',
'急送茅斋也可怜',
],
},
{
title: '诣徐卿觅果栽',
body: [
'草堂少花今欲栽',
'不问绿李与黄梅',
'石笋街中却归去',
'果园坊里为求来',
],
},
{
title: '赠别何邕',
body: [
'生死论交地',
'何由见一人',
'悲君随燕雀',
'薄宦走风尘',
'绵谷元通汉',
'沱江不向秦',
'五陵花满眼',
'传语故乡春',
],
},
{
title: '赠别郑炼赴襄阳',
body: [
'戎马交驰际',
'柴门老病身',
'把君诗过日',
'念此别惊神',
'地阔峨眉晚',
'天高岘首春',
'为于耆旧内',
'试觅姓庞人',
],
},
{
title: '重赠郑炼',
body: [
'郑子将行罢使臣',
'囊无一物献尊亲',
'江山路远羁离日',
'裘马谁为感激人',
],
},
{
title: '奉和严中丞西城晚眺十韵',
body: [
'汲黯匡君切',
'廉颇出将频',
'直词才不世',
'雄略动如神',
'政简移风速',
'诗清立意新',
'层城临暇景',
'绝域望馀春',
'旗尾蛟龙会',
'楼头燕雀驯',
'地平江动蜀',
'天阔树浮秦',
'帝念深分阃',
'军须远算缗',
'花罗封蛱蝶',
'瑞锦送麒麟',
'辞第输高义',
'观图忆古人',
'征南多兴绪',
'事业闇相亲',
],
},
{
title: '严中丞枉驾见过',
body: [
'元戎小队出郊坰',
'问柳寻花到野亭',
'川合东西瞻使节',
'地分南北任流萍',
'扁舟不独如张翰',
'白帽还应似管宁',
'寂寞江天云雾里',
'何人道有少微星',
],
},
{
title: '广州段功曹到得杨五长史谭书功曹却归聊寄此诗',
body: [
'卫青开幕府',
'杨仆将楼船',
'汉节梅花外',
'春城海水边',
'铜梁书远及',
'珠浦使将旋',
'贫病他乡老',
'烦君万里传',
],
},
{
title: '得广州张判官叔卿书,使还,以诗代意',
body: [
'乡关胡骑远',
'宇宙蜀城偏',
'忽得炎州信',
'遥从月峡传',
'云深骠骑幕',
'夜隔孝廉船',
'却寄双愁眼',
'相思泪点悬',
],
},
{
title: '送段功曹归广州',
body: [
'南海春天外',
'功曹几月程',
'峡云笼树小',
'湖日落船明',
'交趾丹砂重',
'韶州白葛轻',
'幸君因旅客',
'时寄锦官城',
],
},
{
title: '绝句漫兴九首',
body: [
'眼见客愁愁不醒',
'无赖春色到江亭',
'即遣花开深造次',
'便觉莺语太丁宁',
'手种桃李非无主',
'野老墙低还似家',
'恰似春风相欺得',
'夜来吹折数枝花',
'熟知茅斋绝低小',
'江上燕子故来频',
'衔泥点污琴书内',
'更接飞虫打著人',
'二月已破三月来',
'渐老逢春能几回',
'莫思身外无穷事',
'且尽生前有限杯',
'肠断春江欲尽头',
'杖藜徐步立芳洲',
'颠狂柳絮随风去',
'轻薄桃花逐水流',
'懒慢无堪不出村',
'呼儿日在掩柴门',
'苍苔浊酒林中静',
'碧水春风野外昏',
'糁径杨花铺白毡',
'点溪荷叶叠青钱',
'笋根稚子无人见',
'沙上凫雏傍母眠',
'舍西柔桑叶可拈',
'江畔细麦复纤纤',
'人生几何春已夏',
'不放香醪如蜜甜',
'隔户杨柳弱袅袅',
'恰似十五女儿腰',
'谁谓朝来不作意',
'狂风挽断最长条',
],
},
{
title: '江畔独步寻花七绝句',
body: [
'江上被花恼不彻',
'无处告诉只颠狂',
'走觅南邻爱酒伴',
'经旬出饮独空床',
'稠花乱蕊畏江滨',
'行步欹危实怕春',
'诗酒尚堪驱使在',
'未须料理白头人',
'江深竹静两三家',
'多事红花映白花',
'报答春光知有处',
'应须美酒送生涯',
'东望少城花满烟',
'百花高楼更可怜',
'谁能载酒开金盏',
'唤取佳人舞绣筵',
'黄师塔前江水东',
'春光懒困倚微风',
'桃花一簇开无主',
'可爱深红爱浅红',
'黄四娘家花满蹊',
'千朵万朵压枝低',
'留连戏蝶时时舞',
'自在娇莺恰恰啼',
'不是爱花即肯死',
'只恐花尽老相催',
'繁枝容易纷纷落',
'嫩叶商量细细开',
],
},
{
title: '三绝句',
body: [
'楸树馨香倚钓矶',
'斩新花蕊未应飞',
'不如醉里风吹尽',
'可忍醒时雨打稀',
'门外鸬鹚去不来',
'沙头忽见眼相猜',
'自今已后知人意',
'一日须来一百回',
'无数春笋满林生',
'柴门密掩断人行',
'会须上番看成竹',
'客至从嗔不出迎',
],
},
{
title: '戏为六绝句',
body: [
'庾信文章老更成',
'凌云健笔意纵横',
'今人嗤点流传赋',
'不觉前贤畏后生',
'杨王卢骆当时体',
'轻薄为文哂未休',
'尔曹身与名俱灭',
'不废江河万古流',
'纵使卢王操翰墨',
'劣于汉魏近风骚',
'龙文虎脊皆君驭',
'历块过都见尔曹',
'才力应难夸数公',
'凡今谁是出群雄',
'或看翡翠兰苕上',
'未掣鲸鱼碧海中',
'不薄今人爱古人',
'清词丽句必为邻',
'窃攀屈宋宜方驾',
'恐与齐梁作后尘',
'未及前贤更勿疑',
'递相祖述复先谁',
'别裁伪体亲风雅',
'转益多师是汝师',
],
},
{
title: '江头四咏。丁香',
body: [
'丁香体柔弱',
'乱结枝犹垫',
'细叶带浮毛',
'疏花披素艳',
'深栽小斋后',
'庶近幽人占',
'晚堕兰麝中',
'休怀粉身念',
],
},
{
title: '江头四咏。栀子',
body: [
'栀子比众木',
'人间诚未多',
'于身色有用',
'与道气伤和',
'红取风霜实',
'青看雨露柯',
'无情移得汝',
'贵在映江波',
],
},
{
title: '江头四咏。鸂鶒',
body: [
'故使笼宽织',
'须知动损毛',
'看云莫怅望',
'失水任呼号',
'六翮曾经剪',
'孤飞卒未高',
'且无鹰隼虑',
'留滞莫辞劳',
],
},
{
title: '江头四咏。花鸭',
body: [
'花鸭无泥滓',
'阶前每缓行',
'羽毛知独立',
'黑白太分明',
'不觉群心妒',
'休牵众眼惊',
'稻粱沾汝在',
'作意莫先鸣',
],
},
{
title: '畏人',
body: [
'早花随处发',
'春鸟异方啼',
'万里清江上',
'三年落日低',
'畏人成小筑',
'褊性合幽栖',
'门径从榛草',
'无心走马蹄',
],
},
{
title: '远游',
body: [
'贱子何人记',
'迷芳著处家',
'竹风连野色',
'江沫拥春沙',
'种药扶衰病',
'吟诗解叹嗟',
'似闻胡骑走',
'失喜问京华',
],
},
{
title: '野望',
body: [
'西山白雪三奇戍',
'南浦清江万里桥',
'海内风尘诸弟隔',
'天涯涕泪一身遥',
'唯将迟暮供多病',
'未有涓埃答圣朝',
'跨马出郊时极目',
'不堪人事日萧条',
],
},
{
title: '官池春雁二首',
body: [
'自古稻粱多不足',
'至今鸂鶒乱为群',
'且休怅望看春水',
'更恐归飞隔暮云',
'青春欲尽急还乡',
'紫塞宁论尚有霜',
'翅在云天终不远',
'力微矰缴绝须防',
],
},
{
title: '水槛遣心二首',
body: [
'去郭轩楹敞',
'无村眺望赊',
'澄江平少岸',
'幽树晚多花',
'细雨鱼儿出',
'微风燕子斜',
'城中十万户',
'此地两三家',
'蜀天常夜雨',
'江槛已朝晴',
'叶润林塘密',
'衣干枕席清',
'不堪祗老病',
'何得尚浮名',
'浅把涓涓酒',
'深凭送此生',
],
},
{
title: '屏迹三首',
body: [
'用拙存吾道',
'幽居近物情',
'桑麻深雨露',
'燕雀半生成',
'村鼓时时急',
'渔舟个个轻',
'杖藜从白首',
'心迹喜双清',
'晚起家何事',
'无营地转幽',
'竹光团野色',
'舍影漾江流',
'失学从儿懒',
'长贫任妇愁',
'百年浑得醉',
'一月不梳头',
'衰颜甘屏迹',
'幽事供高卧',
'鸟下竹根行',
'龟开萍叶过',
'年荒酒价乏',
'日并园蔬课',
'犹酌甘泉歌',
'歌长击樽破',
],
},
{
title: '奉酬严公寄题野亭之作',
body: [
'拾遗曾奏数行书',
'懒性从来水竹居',
'奉引滥骑沙苑马',
'幽栖真钓锦江鱼',
'谢安不倦登临费',
'阮籍焉知礼法疏',
'枉沐旌麾出城府',
'草茅无径欲教锄',
],
},
{
title: '中丞严公雨中垂寄见忆一绝,奉答二绝',
body: [
'雨映行宫辱赠诗',
'元戎肯赴野人期',
'江边老病虽无力',
'强拟晴天理钓丝',
'何日雨晴云出溪',
'白沙青石先无泥',
'只须伐竹开荒径',
'倚杖穿花听马嘶',
],
},
{
title: '谢严中丞送青城山道士乳酒一瓶',
body: [
'山瓶乳酒下青云',
'气味浓香幸见分',
'鸣鞭走送怜渔父',
'洗盏开尝对马军',
],
},
{
title: '严公仲夏枉驾草堂,兼携酒馔(得寒字)',
body: [
'竹里行厨洗玉盘',
'花边立马簇金鞍',
'非关使者征求急',
'自识将军礼数宽',
'百年地辟柴门迥',
'五月江深草阁寒',
'看弄渔舟移白日',
'老农何有罄交欢',
],
},
{
title: '严公厅宴,同咏蜀道画图(得空字)',
body: [
'日临公馆静',
'画满地图雄',
'剑阁星桥北',
'松州雪岭东',
'华夷山不断',
'吴蜀水相通',
'兴与烟霞会',
'清樽幸不空',
],
},
{
title: '奉送严公入朝十韵',
body: [
'鼎湖瞻望远',
'象阙宪章新',
'四海犹多难',
'中原忆旧臣',
'与时安反侧',
'自昔有经纶',
'感激张天步',
'从容静塞尘',
'南图回羽翮',
'北极捧星辰',
'漏鼓还思昼',
'宫莺罢啭春',
'空留玉帐术',
'愁杀锦城人',
'阁道通丹地',
'江潭隐白蘋',
'此生那老蜀',
'不死会归秦',
'公若登台辅',
'临危莫爱身',
],
},
{
title: '送严侍郎到绵州,同登杜使君江楼(得心字)',
body: [
'野兴每难尽',
'江楼延赏心',
'归朝送使节',
'落景惜登临',
'稍稍烟集渚',
'微微风动襟',
'重船依浅濑',
'轻鸟度层阴',
'槛峻背幽谷',
'窗虚交茂林',
'灯光散远近',
'月彩静高深',
'城拥朝来客',
'天横醉后参',
'穷途衰谢意',
'苦调短长吟',
'此会共能几',
'诸孙贤至今',
'不劳朱户闭',
'自待白河沉',
],
},
{
title: '奉济驿重送严公四韵',
body: [
'远送从此别',
'青山空复情',
'几时杯重把',
'昨夜月同行',
'列郡讴歌惜',
'三朝出入荣',
'江村独归处',
'寂寞养残生',
],
},
{
title: '送梓州李使君之任(原注故陈拾遗射洪人也篇末有云)',
body: [
'籍甚黄丞相',
'能名自颍川',
'近看除刺史',
'还喜得吾贤',
'五马何时到',
'双鱼会早传',
'老思筇竹杖',
'冬要锦衾眠',
'不作临岐恨',
'惟听举最先',
'火云挥汗日',
'山驿醒心泉',
'遇害陈公殒',
'于今蜀道怜',
'君行射洪县',
'为我一潸然',
],
},
{
title: '巴西驿亭观江涨,呈窦使君(一作窦十五使君)',
body: [
'宿雨南江涨',
'波涛乱远峰',
'孤亭凌喷薄',
'万井逼舂容',
'霄汉愁高鸟',
'泥沙困老龙',
'天边同客舍',
'携我豁心胸',
],
},
{
title: '九日登梓州城',
body: [
'伊昔黄花酒',
'如今白发翁',
'追欢筋力异',
'望远岁时同',
'弟妹悲歌里',
'朝廷醉眼中',
'兵戈与关塞',
'此日意无穷',
],
},
{
title: '九日奉寄严大夫',
body: [
'九日应愁思',
'经时冒险艰',
'不眠持汉节',
'何路出巴山',
'小驿香醪嫩',
'重岩细菊斑',
'遥知簇鞍马',
'回首白云间',
],
},
{
title: '黄草',
body: [
'黄草峡西船不归',
'赤甲山下行人稀',
'秦中驿使无消息',
'蜀道兵戈有是非',
'万里秋风吹锦水',
'谁家别泪湿罗衣',
'莫愁剑阁终堪据',
'闻道松州已被围',
],
},
{
title: '怀旧',
body: [
'地下苏司业',
'情亲独有君',
'那因丧乱后',
'便有死生分',
'老罢知明镜',
'悲来望白云',
'自从失词伯',
'不复更论文',
],
},
{
title: '所思(得台州郑司户虔消息)',
body: [
'郑老身仍窜',
'台州信所传',
'为农山涧曲',
'卧病海云边',
'世已疏儒素',
'人犹乞酒钱',
'徒劳望牛斗',
'无计劚龙泉',
],
},
{
title: '不见(近无李白消息)',
body: [
'不见李生久',
'佯狂真可哀',
'世人皆欲杀',
'吾意独怜才',
'敏捷诗千首',
'飘零酒一杯',
'匡山读书处',
'头白好归来',
],
},
{
title: '题玄武禅师屋壁(屋在中江大雄山)',
body: [
'何年顾虎头',
'满壁画瀛州',
'赤日石林气',
'青天江海流',
'锡飞常近鹤',
'杯度不惊鸥',
'似得庐山路',
'真随惠远游',
],
},
{
title: '客夜',
body: [
'客睡何曾著',
'秋天不肯明',
'卷帘残月影',
'高枕远江声',
'计拙无衣食',
'途穷仗友生',
'老妻书数纸',
'应悉未归情',
],
},
{
title: '客亭',
body: [
'秋窗犹曙色',
'落木更天风',
'日出寒山外',
'江流宿雾中',
'圣朝无弃物',
'老病已成翁',
'多少残生事',
'飘零似转蓬',
],
},
{
title: '秋尽',
body: [
'秋尽东行且未回',
'茅斋寄在少城隈',
'篱边老却陶潜菊',
'江上徒逢袁绍杯',
'雪岭独看西日落',
'剑门犹阻北人来',
'不辞万里长为客',
'怀抱何时得好开',
],
},
{
title: '陪王侍御宴通泉东山野亭',
body: [
'江水东流去',
'清樽日复斜',
'异方同宴赏',
'何处是京华',
'亭景临山水',
'村烟对浦沙',
'狂歌过于胜',
'得醉即为家',
],
},
{
title: '野望',
body: [
'金华山北涪水西',
'仲冬风日始凄凄',
'山连越巂蟠三蜀',
'水散巴渝下五溪',
'独鹤不知何事舞',
'饥乌似欲向人啼',
'射洪春酒寒仍绿',
'目极伤神谁为携',
],
},
{
title: '闻官军收河南河北',
body: [
'剑外忽传收蓟北',
'初闻涕泪满衣裳',
'却看妻子愁何在',
'漫卷诗书喜欲狂',
'白日放歌须纵酒',
'青春作伴好还乡',
'即从巴峡穿巫峡',
'便下襄阳向洛阳',
],
},
{
title: '涪江泛舟送韦班归京(得山字)',
body: [
'追饯同舟日',
'伤春一水间',
'飘零为客久',
'衰老羡君还',
'花远重重树',
'云轻处处山',
'天涯故人少',
'更益鬓毛斑',
],
},
{
title: '春日梓州登楼二首',
body: [
'行路难如此',
'登楼望欲迷',
'身无却少壮',
'迹有但羁栖',
'江水流城郭',
'春风入鼓鼙',
'双双新燕子',
'依旧已衔泥',
'天畔登楼眼',
'随春入故园',
'战场今始定',
'移柳更能存',
'厌蜀交游冷',
'思吴胜事繁',
'应须理舟楫',
'长啸下荆门',
],
},
{
title: '郪城西原送李判官兄、武判官弟赴成都府',
body: [
'凭高送所亲',
'久坐惜芳辰',
'远水非无浪',
'他山自有春',
'野花随处发',
'官柳著行新',
'天际伤愁别',
'离筵何太频',
],
},
{
title: '泛江送魏十八仓曹还京,因寄岑中允参、范郎中季明',
body: [
'迟日深春水',
'轻舟送别筵',
'帝乡愁绪外',
'春色泪痕边',
'见酒须相忆',
'将诗莫浪传',
'若逢岑与范',
'为报各衰年',
],
},
{
title: '送路六侍御入朝',
body: [
'童稚情亲四十年',
'中间消息两茫然',
'更为后会知何地',
'忽漫相逢是别筵',
'不分桃花红胜锦',
'生憎柳絮白于绵',
'剑南春色还无赖',
'触忤愁人到酒边',
],
},
{
title: '泛江送客',
body: [
'二月频送客',
'东津江欲平',
'烟花山际重',
'舟楫浪前轻',
'泪逐劝杯下',
'愁连吹笛生',
'离筵不隔日',
'那得易为情',
],
},
{
title: '上牛头寺(牛头山在郪县西南,下有长乐寺)',
body: [
'青山意不尽',
'衮衮上牛头',
'无复能拘碍',
'真成浪出游',
'花浓春寺静',
'竹细野池幽',
'何处莺啼切',
'移时独未休',
],
},
{
title: '望牛头寺',
body: [
'牛头见鹤林',
'梯迳绕幽深',
'春色浮山外',
'天河宿殿阴',
'传灯无白日',
'布地有黄金',
'休作狂歌老',
'回看不住心',
],
},
{
title: '上兜率寺',
body: [
'兜率知名寺',
'真如会法堂',
'江山有巴蜀',
'栋宇自齐梁',
'庾信哀虽久',
'何颙好不忘',
'白牛车远近',
'且欲上慈航',
],
},
{
title: '望兜率寺',
body: [
'树密当山径',
'江深隔寺门',
'霏霏云气重',
'闪闪浪花翻',
'不复知天大',
'空馀见佛尊',
'时应清盥罢',
'随喜给孤园',
],
},
{
title: '甘园',
body: [
'春日清江岸',
'千甘二顷园',
'青云羞叶密',
'白雪避花繁',
'结子随边使',
'开筒近至尊',
'后于桃李熟',
'终得献金门',
],
},
{
title: '数陪李梓州泛江,有女乐在诸舫,戏为艳曲二首赠李',
body: [
'上客回空骑',
'佳人满近船',
'江清歌扇底',
'野旷舞衣前',
'玉袖凌风并',
'金壶隐浪偏',
'竞将明媚色',
'偷眼艳阳天',
'白日移歌袖',
'清霄近笛床',
'翠眉萦度曲',
'云鬓俨分行',
'立马千山暮',
'回舟一水香',
'使君自有妇',
'莫学野鸳鸯',
],
},
{
title: '登牛头山亭子',
body: [
'路出双林外',
'亭窥万井中',
'江城孤照日',
'山谷远含风',
'兵革身将老',
'关河信不通',
'犹残数行泪',
'忍对百花丛',
],
},
{
title: '陪李梓州、王阆州、苏遂州、李果州四使君登惠义寺',
body: [
'春日无人境',
'虚空不住天',
'莺花随世界',
'楼阁寄山巅',
'迟暮身何得',
'登临意惘然',
'谁能解金印',
'潇洒共安禅',
],
},
{
title: '送何侍御归朝(李梓州泛舟筵上作)',
body: [
'舟楫诸侯饯',
'车舆使者归',
'山花相映发',
'水鸟自孤飞',
'春日垂霜鬓',
'天隅把绣衣',
'故人从此去',
'寥落寸心违',
],
},
{
title: '江亭送眉州辛别驾升之(得芜字)',
body: [
'柳影含云幕',
'江波近酒壶',
'异方惊会面',
'终宴惜征途',
'沙晚低风蝶',
'天晴喜浴凫',
'别离伤老大',
'意绪日荒芜',
],
},
{
title: '涪城县香积寺官阁',
body: [
'寺下春江深不流',
'山腰官阁迥添愁',
'含风翠壁孤云细',
'背日丹枫万木稠',
'小院回廊春寂寂',
'浴凫飞鹭晚悠悠',
'诸天合在藤萝外',
'昏黑应须到上头',
],
},
{
title: '戏题寄上汉中王三首',
body: [
'西汉亲王子',
'成都老客星',
'百年双白鬓',
'一别五秋萤',
'忍断杯中物',
'祗看座右铭',
'不能随皂盖',
'自醉逐浮萍',
'策杖时能出',
'王门异昔游',
'已知嗟不起',
'未许醉相留',
'蜀酒浓无敌',
'江鱼美可求',
'终思一酩酊',
'净扫雁池头',
'群盗无归路',
'衰颜会远方',
'尚怜诗警策',
'犹记酒颠狂',
'鲁卫弥尊重',
'徐陈略丧亡',
'空馀枚叟在',
'应念早升堂',
],
},
{
title: '陪章留后侍御宴南楼(得风字)',
body: [
'绝域长夏晚',
'兹楼清宴同',
'朝廷烧栈北',
'鼓角满天东',
'屡食将军第',
'仍骑御史骢',
'本无丹灶术',
'那免白头翁',
'寇盗狂歌外',
'形骸痛饮中',
'野云低渡水',
'檐雨细随风',
'出号江城黑',
'题诗蜡炬红',
'此身醒复醉',
'不拟哭途穷',
],
},
{
title: '台上(得凉字)',
body: [
'改席台能迥',
'留门月复光',
'云行遗暑湿',
'山谷进风凉',
'老去一杯足',
'谁怜屡舞长',
'何须把官烛',
'似恼鬓毛苍',
],
},
{
title: '送王十五判官扶侍还黔中(得开字)',
body: [
'大家东征逐子回',
'风生洲渚锦帆开',
'青青竹笋迎船出',
'日日江鱼入馔来',
'离别不堪无限意',
'艰危深仗济时才',
'黔阳信使应稀少',
'莫怪频频劝酒杯',
],
},
{
title: '倦夜(吴曾《漫录》云:顾陶《类编》题作倦秋夜)',
body: [
'竹凉侵卧内',
'野月满庭隅',
'重露成涓滴',
'稀星乍有无',
'暗飞萤自照',
'水宿鸟相呼',
'万事干戈里',
'空悲清夜徂',
],
},
{
title: '悲秋',
body: [
'凉风动万里',
'群盗尚纵横',
'家远传书日',
'秋来为客情',
'愁窥高鸟过',
'老逐众人行',
'始欲投三峡',
'何由见两京',
],
},
{
title: '对雨',
body: [
'莽莽天涯雨',
'江边独立时',
'不愁巴道路',
'恐湿汉旌旗',
'雪岭防秋急',
'绳桥战胜迟',
'西戎甥舅礼',
'未敢背恩私',
],
},
{
title: '警急(时高公適领西川节度)',
body: [
'才名旧楚将',
'妙略拥兵机',
'玉垒虽传檄',
'松州会解围',
'和亲知拙计',
'公主漫无归',
'青海今谁得',
'西戎实饱飞',
],
},
{
title: '王命',
body: [
'汉北豺狼满',
'巴西道路难',
'血埋诸将甲',
'骨断使臣鞍',
'牢落新烧栈',
'苍茫旧筑坛',
'深怀喻蜀意',
'恸哭望王官',
],
},
{
title: '征夫',
body: [
'十室几人在',
'千山空自多',
'路衢唯见哭',
'城市不闻歌',
'漂梗无安地',
'衔枚有荷戈',
'官军未通蜀',
'吾道竟如何',
],
},
{
title: '有感五首',
body: [
'将帅蒙恩泽',
'兵戈有岁年',
'至今劳圣主',
'可以报皇天',
'白骨新交战',
'云台旧拓边',
'乘槎断消息',
'无处觅张骞',
'幽蓟馀蛇豕',
'乾坤尚虎狼',
'诸侯春不贡',
'使者日相望',
'慎勿吞青海',
'无劳问越裳',
'大君先息战',
'归马华山阳',
'洛下舟车入',
'天中贡赋均',
'日闻红粟腐',
'寒待翠华春',
'莫取金汤固',
'长令宇宙新',
'不过行俭德',
'盗贼本王臣',
'丹桂风霜急',
'青梧日夜凋',
'由来强干地',
'未有不臣朝',
'受钺亲贤往',
'卑宫制诏遥',
'终依古封建',
'岂独听箫韶',
'盗灭人还乱',
'兵残将自疑',
'登坛名绝假',
'报主尔何迟',
'领郡辄无色',
'之官皆有词',
'愿闻哀痛诏',
'端拱问疮痍',
],
},
{
title: '送元二适江左',
body: [
'乱后今相见',
'秋深复远行',
'风尘为客日',
'江海送君情',
'晋室丹阳尹',
'公孙白帝城',
'经过自爱惜',
'取次莫论兵',
],
},
{
title: '章梓州水亭',
body: [
'城晚通云雾',
'亭深到芰荷',
'吏人桥外少',
'秋水席边多',
'近属淮王至',
'高门蓟子过',
'荆州爱山简',
'吾醉亦长歌',
],
},
{
title: '玩月呈汉中王',
body: [
'夜深露气清',
'江月满江城',
'浮客转危坐',
'归舟应独行',
'关山同一照',
'乌鹊自多惊',
'欲得淮王术',
'风吹晕已生',
],
},
{
title: '戏作寄上汉中王二首',
body: [
'云里不闻双雁过',
'掌中贪见一珠新',
'秋风袅袅吹江汉',
'只在他乡何处人',
'谢安舟楫风还起',
'梁苑池台雪欲飞',
'杳杳东山携汉妓',
'泠泠修竹待王归',
],
},
{
title: '投简梓州幕府,兼简韦十郎官',
body: [
'幕下郎官安稳无',
'从来不奉一行书',
'固知贫病人须弃',
'能使韦郎迹也疏',
],
},
{
title: '登高',
body: [
'风急天高猿啸哀',
'渚清沙白鸟飞回',
'无边落木萧萧下',
'不尽长江衮衮来',
'万里悲秋常作客',
'百年多病独登台',
'艰难苦恨繁霜鬓',
'潦倒新停浊酒杯',
],
},
{
title: '九日',
body: [
'去年登高郪县北',
'今日重在涪江滨',
'苦遭白发不相放',
'羞见黄花无数新',
'世乱郁郁久为客',
'路难悠悠常傍人',
'酒阑却忆十年事',
'肠断骊山清路尘',
],
},
{
title: '遣愤',
body: [
'闻道花门将',
'论功未尽归',
'自从收帝里',
'谁复总戎机',
'蜂虿终怀毒',
'雷霆可震威',
'莫令鞭血地',
'再湿汉臣衣',
],
},
{
title: '章梓州橘亭饯成都窦少尹(得凉字)',
body: [
'秋日野亭千橘香',
'玉盘锦席高云凉',
'主人送客何所作',
'行酒赋诗殊未央',
'衰老应为难离别',
'贤声此去有辉光',
'预传籍籍新京尹',
'青史无劳数赵张',
],
},
{
title: '送陵州路使君赴任',
body: [
'王室比多难',
'高官皆武臣',
'幽燕通使者',
'岳牧用词人',
'国待贤良急',
'君当拔擢新',
'佩刀成气象',
'行盖出风尘',
'战伐乾坤破',
'疮痍府库贫',
'众僚宜洁白',
'万役但平均',
'霄汉瞻佳士',
'泥途任此身',
'秋天正摇落',
'回首大江滨',
],
},
{
title: '薄暮',
body: [
'江水长流地',
'山云薄暮时',
'寒花隐乱草',
'宿鸟择深枝',
'旧国见何日',
'高秋心苦悲',
'人生不再好',
'鬓发白成丝',
],
},
{
title: '西山三首(即岷山,捍阻羌夷,全蜀巨障)',
body: [
'彝界荒山顶',
'蕃州积雪边',
'筑城依白帝',
'转粟上青天',
'蜀将分旗鼓',
'羌兵助井泉',
'西戎背和好',
'杀气日相缠',
'辛苦三城戍',
'长防万里秋',
'烟尘侵火井',
'雨雪闭松州',
'风动将军幕',
'天寒使者裘',
'漫山贼营垒',
'回首得无忧',
'子弟犹深入',
'关城未解围',
'蚕崖铁马瘦',
'灌口米船稀',
'辩士安边策',
'元戎决胜威',
'今朝乌鹊喜',
'欲报凯歌归',
],
},
{
title: '薄游',
body: [
'淅淅风生砌',
'团团日隐墙',
'遥空秋雁灭',
'半岭暮云长',
'病叶多先坠',
'寒花只暂香',
'巴城添泪眼',
'今夜复清光',
],
},
{
title: '赠韦赞善别',
body: [
'扶病送君发',
'自怜犹不归',
'只应尽客泪',
'复作掩荆扉',
'江汉故人少',
'音书从此稀',
'往还二十载',
'岁晚寸心违',
],
},
{
title: '送李卿晔(晔,淮安忠公琇之子,时以罪贬岭南)',
body: [
'王子思归日',
'长安已乱兵',
'沾衣问行在',
'走马向承明',
'暮景巴蜀僻',
'春风江汉清',
'晋山虽自弃',
'魏阙尚含情',
],
},
{
title: '绝句',
body: ['江边踏青罢', '回首见旌旗', '风起春城暮', '高楼鼓角悲'],
},
{
title: '城上(一作空城)',
body: [
'草满巴西绿',
'空城白日长',
'风吹花片片',
'春动水茫茫',
'八骏随天子',
'群臣从武皇',
'遥闻出巡守',
'早晚遍遐荒',
],
},
{
title: '舍弟占归草堂检校聊示此诗',
body: [
'久客应吾道',
'相随独尔来',
'孰知江路近',
'频为草堂回',
'鹅鸭宜长数',
'柴荆莫浪开',
'东林竹影薄',
'腊月更须栽',
],
},
{
title: '伤春五首(巴阆僻远伤春罢始知春前已收宫阙)',
body: [
'天下兵虽满',
'春光日自浓',
'西京疲百战',
'北阙任群凶',
'关塞三千里',
'烟花一万重',
'蒙尘清路急',
'御宿且谁供',
'殷复前王道',
'周迁旧国容',
'蓬莱足云气',
'应合总从龙',
'莺入新年语',
'花开满故枝',
'天青风卷幔',
'草碧水通池',
'牢落官军速',
'萧条万事危',
'鬓毛元自白',
'泪点向来垂',
'不是无兄弟',
'其如有别离',
'巴山春色静',
'北望转逶迤',
'日月还相斗',
'星辰屡合围',
'不成诛执法',
'焉得变危机',
'大角缠兵气',
'钩陈出帝畿',
'烟尘昏御道',
'耆旧把天衣',
'行在诸军阙',
'来朝大将稀',
'贤多隐屠钓',
'王肯载同归',
'再有朝廷乱',
'难知消息真',
'近传王在洛',
'复道使归秦',
'夺马悲公主',
'登车泣贵嫔',
'萧关迷北上',
'沧海欲东巡',
'敢料安危体',
'犹多老大臣',
'岂无嵇绍血',
'沾洒属车尘',
'闻说初东幸',
'孤儿却走多',
'难分太仓粟',
'竞弃鲁阳戈',
'胡虏登前殿',
'王公出御河',
'得无中夜舞',
'谁忆大风歌',
'春色生烽燧',
'幽人泣薜萝',
'君臣重修德',
'犹足见时和',
],
},
{
title: '王阆州筵奉酬十一舅惜别之作',
body: [
'万壑树声满',
'千崖秋气高',
'浮舟出郡郭',
'别酒寄江涛',
'良会不复久',
'此生何太劳',
'穷愁但有骨',
'群盗尚如毛',
'吾舅惜分手',
'使君寒赠袍',
'沙头暮黄鹄',
'失侣自哀号',
],
},
{
title: '放船',
body: [
'送客苍溪县',
'山寒雨不开',
'直愁骑马滑',
'故作泛舟回',
'青惜峰峦过',
'黄知橘柚来',
'江流大自在',
'坐稳兴悠哉',
],
},
{
title: '奉待严大夫',
body: [
'殊方又喜故人来',
'重镇还须济世才',
'常怪偏裨终日待',
'不知旌节隔年回',
'欲辞巴徼啼莺合',
'远下荆门去鹢催',
'身老时危思会面',
'一生襟抱向谁开',
],
},
{
title: '奉寄高常侍(一作寄高三十五大夫)',
body: [
'汶上相逢年颇多',
'飞腾无那故人何',
'总戎楚蜀应全未',
'方驾曹刘不啻过',
'今日朝廷须汲黯',
'中原将帅忆廉颇',
'天涯春色催迟暮',
'别泪遥添锦水波',
],
},
{
title: '奉寄章十侍御',
body: [
'淮海维扬一俊人',
'金章紫绶照青春',
'指麾能事回天地',
'训练强兵动鬼神',
'湘西不得归关羽',
'河内犹宜借寇恂',
'朝觐从容问幽仄',
'勿云江汉有垂纶',
],
},
{
title: '将赴荆南,寄别李剑州',
body: [
'使君高义驱今古',
'寥落三年坐剑州',
'但见文翁能化俗',
'焉知李广未封侯',
'路经滟滪双蓬鬓',
'天入沧浪一钓舟',
'戎马相逢更何日',
'春风回首仲宣楼',
],
},
{
title: '奉寄别马巴州(时甫除京兆功曹在东川)',
body: [
'勋业终归马伏波',
'功曹非复汉萧何',
'扁舟系缆沙边久',
'南国浮云水上多',
'独把鱼竿终远去',
'难随鸟翼一相过',
'知君未爱春湖色',
'兴在骊驹白玉珂',
],
},
{
title: '泛江',
body: [
'方舟不用楫',
'极目总无波',
'长日容杯酒',
'深江净绮罗',
'乱离还奏乐',
'飘泊且听歌',
'故国流清渭',
'如今花正多',
],
},
{
title: '陪王使君晦日泛江就黄家亭子二首',
body: [
'山豁何时断',
'江平不肯流',
'稍知花改岸',
'始验鸟随舟',
'结束多红粉',
'欢娱恨白头',
'非君爱人客',
'晦日更添愁',
'有径金沙软',
'无人碧草芳',
'野畦连蛱蝶',
'江槛俯鸳鸯',
'日晚烟花乱',
'风生锦绣香',
'不须吹急管',
'衰老易悲伤',
],
},
{
title: '南征',
body: [
'春岸桃花水',
'云帆枫树林',
'偷生长避地',
'适远更沾襟',
'老病南征日',
'君恩北望心',
'百年歌自苦',
'未见有知音',
],
},
{
title: '久客',
body: [
'羁旅知交态',
'淹留见俗情',
'衰颜聊自哂',
'小吏最相轻',
'去国哀王粲',
'伤时哭贾生',
'狐狸何足道',
'豺虎正纵横',
],
},
{
title: '春远',
body: [
'肃肃花絮晚',
'菲菲红素轻',
'日长唯鸟雀',
'春远独柴荆',
'数有关中乱',
'何曾剑外清',
'故乡归不得',
'地入亚夫营',
],
},
{
title: '暮寒',
body: [
'雾隐平郊树',
'风含广岸波',
'沉沉春色静',
'惨惨暮寒多',
'戍鼓犹长击',
'林莺遂不歌',
'忽思高宴会',
'朱袖拂云和',
],
},
{
title: '双燕',
body: [
'旅食惊双燕',
'衔泥入此堂',
'应同避燥湿',
'且复过炎凉',
'养子风尘际',
'来时道路长',
'今秋天地在',
'吾亦离殊方',
],
},
{
title: '百舌',
body: [
'百舌来何处',
'重重只报春',
'知音兼众语',
'整翮岂多身',
'花密藏难见',
'枝高听转新',
'过时如发口',
'君侧有谗人',
],
},
{
title: '地隅',
body: [
'江汉山重阻',
'风云地一隅',
'年年非故物',
'处处是穷途',
'丧乱秦公子',
'悲凉楚大夫',
'平生心已折',
'行路日荒芜',
],
},
{
title: '游子',
body: [
'巴蜀愁谁语',
'吴门兴杳然',
'九江春草外',
'三峡暮帆前',
'厌就成都卜',
'休为吏部眠',
'蓬莱如可到',
'衰白问群仙',
],
},
{
title: '归梦',
body: [
'道路时通塞',
'江山日寂寥',
'偷生唯一老',
'伐叛已三朝',
'雨急青枫暮',
'云深黑水遥',
'梦归归未得',
'不用楚辞招',
],
},
{
title: '江亭王阆州筵饯萧遂州',
body: [
'离亭非旧国',
'春色是他乡',
'老畏歌声断',
'愁随舞曲长',
'二天开宠饯',
'五马烂生光',
'川路风烟接',
'俱宜下凤凰',
],
},
{
title: '绝句二首',
body: [
'迟日江山丽',
'春风花草香',
'泥融飞燕子',
'沙暖睡鸳鸯',
'江碧鸟逾白',
'山青花欲燃',
'今春看又过',
'何日是归年',
],
},
{
title: '滕王亭子',
body: [
'君王台榭枕巴山',
'万丈丹梯尚可攀',
'春日莺啼修竹里',
'仙家犬吠白云间',
'清江锦石伤心丽',
'嫩蕊浓花满目班',
'人到于今歌出牧',
'来游此地不知还',
],
},
{
title: '玉台观(滕王造)',
body: [
'中天积翠玉台遥',
'上帝高居绛节朝',
'遂有冯夷来击鼓',
'始知嬴女善吹箫',
'江光隐见鼋鼍窟',
'石势参差乌鹊桥',
'更肯红颜生羽翼',
'便应黄发老渔樵',
],
},
{
title: '滕王亭子',
body: [
'寂寞春山路',
'君王不复行',
'古墙犹竹色',
'虚阁自松声',
'鸟雀荒村暮',
'云霞过客情',
'尚思歌吹入',
'千骑把霓旌',
],
},
{
title: '玉台观',
body: [
'浩劫因王造',
'平台访古游',
'彩云萧史驻',
'文字鲁恭留',
'宫阙通群帝',
'乾坤到十洲',
'人传有笙鹤',
'时过此山头',
],
},
{
title: '渡江',
body: [
'春江不可渡',
'二月已风涛',
'舟楫欹斜疾',
'鱼龙偃卧高',
'渚花兼素锦',
'汀草乱青袍',
'戏问垂纶客',
'悠悠见汝曹',
],
},
{
title: '喜雨',
body: [
'南国旱无雨',
'今朝江出云',
'入空才漠漠',
'洒迥已纷纷',
'巢燕高飞尽',
'林花润色分',
'晚来声不绝',
'应得夜深闻',
],
},
{
title: '送韦郎司直归成都',
body: [
'窜身来蜀地',
'同病得韦郎',
'天下干戈满',
'江边岁月长',
'别筵花欲暮',
'春日鬓俱苍',
'为问南溪竹',
'抽梢合过墙',
],
},
{
title: '将赴成都草堂途中有作,先寄严郑公五首',
body: [
'得归茅屋赴成都',
'直为文翁再剖符',
'但使闾阎还揖让',
'敢论松竹久荒芜',
'鱼知丙穴由来美',
'酒忆郫筒不用酤',
'五马旧曾谙小径',
'几回书札待潜夫',
'处处青江带白蘋',
'故园犹得见残春',
'雪山斥候无兵马',
'锦里逢迎有主人',
'休怪儿童延俗客',
'不教鹅鸭恼比邻',
'习池未觉风流尽',
'况复荆州赏更新',
'竹寒沙碧浣花溪',
'菱刺藤梢咫尺迷',
'过客径须愁出入',
'居人不自解东西',
'书签药裹封蛛网',
'野店山桥送马蹄',
'岂藉荒庭春草色',
'先判一饮醉如泥',
'常苦沙崩损药栏',
'也从江槛落风湍',
'新松恨不高千尺',
'恶竹应须斩万竿',
'生理只凭黄阁老',
'衰颜欲付紫金丹',
'三年奔走空皮骨',
'信有人间行路难',
'锦官城西生事微',
'乌皮几在还思归',
'昔去为忧乱兵入',
'今来已恐邻人非',
'侧身天地更怀古',
'回首风尘甘息机',
'共说总戎云鸟阵',
'不妨游子芰荷衣',
],
},
{
title: '别房太尉墓(在阆州)',
body: [
'他乡复行役',
'驻马别孤坟',
'近泪无干土',
'低空有断云',
'对棋陪谢傅',
'把剑觅徐君',
'唯见林花落',
'莺啼送客闻',
],
},
{
title: '自阆州领妻子却赴蜀山行三首',
body: [
'汩汩避群盗',
'悠悠经十年',
'不成向南国',
'复作游西川',
'物役水虚照',
'魂伤山寂然',
'我生无倚著',
'尽室畏途边',
'长林偃风色',
'回复意犹迷',
'衫裛翠微润',
'马衔青草嘶',
'栈悬斜避石',
'桥断却寻溪',
'何日干戈尽',
'飘飘愧老妻',
'行色递隐见',
'人烟时有无',
'仆夫穿竹语',
'稚子入云呼',
'转石惊魑魅',
'抨弓落狖鼯',
'真供一笑乐',
'似欲慰穷途',
],
},
{
title: '山馆(一作移居公安山馆,编入江陵诗后)',
body: [
'南国昼多雾',
'北风天正寒',
'路危行木杪',
'身远宿云端',
'山鬼吹灯灭',
'厨人语夜阑',
'鸡鸣问前馆',
'世乱敢求安',
],
},
{
title: '行次盐亭县聊题四韵奉简严遂州蓬州两使君咨议诸昆季',
body: [
'马首见盐亭',
'高山拥县青',
'云溪花淡淡',
'春郭水泠泠',
'全蜀多名士',
'严家聚德星',
'长歌意无极',
'好为老夫听',
],
},
{
title: '倚杖(盐亭县作)',
body: [
'看花虽郭内',
'倚杖即溪边',
'山县早休市',
'江桥春聚船',
'狎鸥轻白浪',
'归雁喜青天',
'物色兼生意',
'凄凉忆去年',
],
},
{
title: '陪王汉州留杜绵州泛房公西湖(房琯刺汉州时所凿)',
body: [
'旧相恩追后',
'春池赏不稀',
'阙庭分未到',
'舟楫有光辉',
'豉化莼丝熟',
'刀鸣鲙缕飞',
'使君双皂盖',
'滩浅正相依',
],
},
{
title: '舟前小鹅儿(汉州城西北角官池作官池即房公湖)',
body: [
'鹅儿黄似酒',
'对酒爱新鹅',
'引颈嗔船逼',
'无行乱眼多',
'翅开遭宿雨',
'力小困沧波',
'客散层城暮',
'狐狸奈若何',
],
},
{
title: '得房公池鹅',
body: [
'房相西亭鹅一群',
'眠沙泛浦白于云',
'凤凰池上应回首',
'为报笼随王右军',
],
},
{
title: '答杨梓州',
body: [
'闷到房公池水头',
'坐逢杨子镇东州',
'却向青溪不相见',
'回船应载阿戎游',
],
},
{
title: '登楼',
body: [
'花近高楼伤客心',
'万方多难此登临',
'锦江春色来天地',
'玉垒浮云变古今',
'北极朝廷终不改',
'西山寇盗莫相侵',
'可怜后主还祠庙',
'日暮聊为梁甫吟',
],
},
{
title: '春归',
body: [
'苔径临江竹',
'茅檐覆地花',
'别来频甲子',
'倏忽又春华',
'倚杖看孤石',
'倾壶就浅沙',
'远鸥浮水静',
'轻燕受风斜',
'世路虽多梗',
'吾生亦有涯',
'此身醒复醉',
'乘兴即为家',
],
},
{
title: '归雁',
body: ['东来万里客', '乱定几年归', '肠断江城雁', '高高正北飞'],
},
{
title: '赠王二十四侍御契四十韵(王契,字佐卿,京兆人)',
body: [
'往往虽相见',
'飘飘愧此身',
'不关轻绂冕',
'俱是避风尘',
'一别星桥夜',
'三移斗柄春',
'败亡非赤壁',
'奔走为黄巾',
'子去何潇洒',
'余藏异隐沦',
'书成无过雁',
'衣故有悬鹑',
'恐惧行装数',
'伶俜卧疾频',
'晓莺工迸泪',
'秋月解伤神',
'会面嗟黧黑',
'含凄话苦辛',
'接舆还入楚',
'王粲不归秦',
'锦里残丹灶',
'花溪得钓纶',
'消中只自惜',
'晚起索谁亲',
'伏柱闻周史',
'乘槎有汉臣',
'鸳鸿不易狎',
'龙虎未宜驯',
'客则挂冠至',
'交非倾盖新',
'由来意气合',
'直取性情真',
'浪迹同生死',
'无心耻贱贫',
'偶然存蔗芋',
'幸各对松筠',
'粗饭依他日',
'穷愁怪此辰',
'女长裁褐稳',
'男大卷书匀',
'漰口江如练',
'蚕崖雪似银',
'名园当翠巘',
'野棹没青蘋',
'屡喜王侯宅',
'时邀江海人',
'追随不觉晚',
'款曲动弥旬',
'但使芝兰秀',
'何烦栋宇邻',
'山阳无俗物',
'郑驿正留宾',
'出入并鞍马',
'光辉参席珍',
'重游先主庙',
'更历少城闉',
'石镜通幽魄',
'琴台隐绛唇',
'送终惟粪土',
'结爱独荆榛',
'置酒高林下',
'观棋积水滨',
'区区甘累趼',
'稍稍息劳筋',
'网聚粘圆鲫',
'丝繁煮细莼',
'长歌敲柳瘿',
'小睡凭藤轮',
'农月须知课',
'田家敢忘勤',
'浮生难去食',
'良会惜清晨',
'列国兵戈暗',
'今王德教淳',
'要闻除猰貐',
'休作画麒麟',
'洗眼看轻薄',
'虚怀任屈伸',
'莫令胶漆地',
'万古重雷陈',
],
},
{
title: '寄董卿嘉荣十韵',
body: [
'闻道君牙帐',
'防秋近赤霄',
'下临千雪岭',
'却背五绳桥',
'海内久戎服',
'京师今晏朝',
'犬羊曾烂熳',
'宫阙尚萧条',
'猛将宜尝胆',
'龙泉必在腰',
'黄图遭污辱',
'月窟可焚烧',
'会取干戈利',
'无令斥候骄',
'居然双捕虏',
'自是一嫖姚',
'落日思轻骑',
'高天忆射雕',
'云台画形像',
'皆为扫氛妖',
],
},
{
title: '寄司马山人十二韵',
body: [
'关内昔分袂',
'天边今转蓬',
'驱驰不可说',
'谈笑偶然同',
'道术曾留意',
'先生早击蒙',
'家家迎蓟子',
'处处识壶公',
'长啸峨嵋北',
'潜行玉垒东',
'有时骑猛虎',
'虚室使仙童',
'发少何劳白',
'颜衰肯更红',
'望云悲轗轲',
'毕景羡冲融',
'丧乱形仍役',
'凄凉信不通',
'悬旌要路口',
'倚剑短亭中',
'永作殊方客',
'残生一老翁',
'相哀骨可换',
'亦遣驭清风',
],
},
{
title: '黄河二首',
body: [
'黄河北岸海西军',
'椎鼓鸣钟天下闻',
'铁马长鸣不知数',
'胡人高鼻动成群',
'黄河西岸是吾蜀',
'欲须供给家无粟',
'愿驱众庶戴君王',
'混一车书弃金玉',
],
},
{
title: '寄李十四员外布十二韵',
body: [
'名参汉望苑',
'职述景题舆',
'巫峡将之郡',
'荆门好附书',
'远行无自苦',
'内热比何如',
'正是炎天阔',
'那堪野馆疏',
'黄牛平驾浪',
'画鹢上凌虚',
'试待盘涡歇',
'方期解缆初',
'闷能过小径',
'自为摘嘉蔬',
'渚柳元幽僻',
'村花不扫除',
'宿阴繁素柰',
'过雨乱红蕖',
'寂寂夏先晚',
'泠泠风有馀',
'江清心可莹',
'竹冷发堪梳',
'直作移巾几',
'秋帆发弊庐',
],
},
{
title: '归来',
body: [
'客里有所过',
'归来知路难',
'开门野鼠走',
'散帙壁鱼干',
'洗杓开新酝',
'低头拭小盘',
'凭谁给麹蘖',
'细酌老江干',
],
},
{
title: '王录事许修草堂赀不到,聊小诘',
body: ['为嗔王录事', '不寄草堂赀', '昨属愁春雨', '能忘欲漏时'],
},
{
title: '寄邛州崔录事',
body: [
'邛州崔录事',
'闻在果园坊',
'久待无消息',
'终朝有底忙',
'应愁江树远',
'怯见野亭荒',
'浩荡风尘外',
'谁知酒熟香',
],
},
{
title: '过故斛斯校书庄二首',
body: [
'此老已云殁',
'邻人嗟亦休',
'竟无宣室召',
'徒有茂陵求',
'妻子寄他食',
'园林非昔游',
'空馀繐帷在',
'淅淅野风秋',
'燕入非旁舍',
'鸥归只故池',
'断桥无复板',
'卧柳自生枝',
'遂有山阳作',
'多惭鲍叔知',
'素交零落尽',
'白首泪双垂',
],
},
{
title: '立秋雨院中有作',
body: [
'山云行绝塞',
'大火复西流',
'飞雨动华屋',
'萧萧梁栋秋',
'穷途愧知己',
'暮齿借前筹',
'已费清晨谒',
'那成长者谋',
'解衣开北户',
'高枕对南楼',
'树湿风凉进',
'江喧水气浮',
'礼宽心有适',
'节爽病微瘳',
'主将归调鼎',
'吾还访旧丘',
],
},
{
title: '奉和严大夫军城早秋',
body: [
'秋风褭褭动高旌',
'玉帐分弓射虏营',
'已收滴博云间戍',
'更夺蓬婆雪外城',
],
},
{
title: '院中晚晴怀西郭茅舍',
body: [
'幕府秋风日夜清',
'澹云疏雨过高城',
'叶心朱实看时落',
'阶面青苔先自生',
'复有楼台衔暮景',
'不劳钟鼓报新晴',
'浣花溪里花饶笑',
'肯信吾兼吏隐名',
],
},
{
title: '到村',
body: [
'碧涧虽多雨',
'秋沙先少泥',
'蛟龙引子过',
'荷芰逐花低',
'老去参戎幕',
'归来散马蹄',
'稻粱须就列',
'榛草即相迷',
'蓄积思江汉',
'疏顽惑町畦',
'稍酬知己分',
'还入故林栖',
],
},
{
title: '宿府',
body: [
'清秋幕府井梧寒',
'独宿江城蜡炬残',
'永夜角声悲自语',
'中天月色好谁看',
'风尘荏苒音书绝',
'关塞萧条行路难',
'已忍伶俜十年事',
'强移栖息一枝安',
],
},
{
title: '遣闷奉呈严公二十韵',
body: [
'白水鱼竿客',
'清秋鹤发翁',
'胡为来幕下',
'只合在舟中',
'黄卷真如律',
'青袍也自公',
'老妻忧坐痹',
'幼女问头风',
'平地专欹倒',
'分曹失异同',
'礼甘衰力就',
'义忝上官通',
'畴昔论诗早',
'光辉仗钺雄',
'宽容存性拙',
'剪拂念途穷',
'露裛思藤架',
'烟霏想桂丛',
'信然龟触网',
'直作鸟窥笼',
'西岭纡村北',
'南江绕舍东',
'竹皮寒旧翠',
'椒实雨新红',
'浪簸船应坼',
'杯干瓮即空',
'藩篱生野径',
'斤斧任樵童',
'束缚酬知己',
'蹉跎效小忠',
'周防期稍稍',
'太简遂匆匆',
'晓入朱扉启',
'昏归画角终',
'不成寻别业',
'未敢息微躬',
'乌鹊愁银汉',
'驽骀怕锦幪',
'会希全物色',
'时放倚梧桐',
],
},
{
title: '送舍弟频赴齐州三首',
body: [
'岷岭南蛮北',
'徐关东海西',
'此行何日到',
'送汝万行啼',
'绝域惟高枕',
'清风独杖藜',
'危时暂相见',
'衰白意都迷',
'风尘暗不开',
'汝去几时来',
'兄弟分离苦',
'形容老病催',
'江通一柱观',
'日落望乡台',
'客意长东北',
'齐州安在哉',
'诸姑今海畔',
'两弟亦山东',
'去傍干戈觅',
'来看道路通',
'短衣防战地',
'匹马逐秋风',
'莫作俱流落',
'长瞻碣石鸿',
],
},
{
title: '严郑公阶下新松(得沾字)',
body: [
'弱质岂自负',
'移根方尔瞻',
'细声闻玉帐',
'疏翠近珠帘',
'未见紫烟集',
'虚蒙清露沾',
'何当一百丈',
'欹盖拥高檐',
],
},
{
title: '严郑公宅同咏竹(得香字)',
body: [
'绿竹半含箨',
'新梢才出墙',
'色侵书帙晚',
'阴过酒樽凉',
'雨洗娟娟净',
'风吹细细香',
'但令无剪伐',
'会见拂云长',
],
},
{
title: '奉观严郑公厅事岷山沱江画图十韵(得忘字)',
body: [
'沱水流中座',
'岷山到此堂',
'白波吹粉壁',
'青嶂插雕梁',
'直讶杉松冷',
'兼疑菱荇香',
'雪云虚点缀',
'沙草得微茫',
'岭雁随毫末',
'川蜺饮练光',
'霏红洲蕊乱',
'拂黛石萝长',
'暗谷非关雨',
'丹枫不为霜',
'秋成玄圃外',
'景物洞庭旁',
'绘事功殊绝',
'幽襟兴激昂',
'从来谢太傅',
'丘壑道难忘',
],
},
{
title: '晚秋陪严郑公摩诃池泛舟(得溪字。池在张仪子城内)',
body: [
'湍驶风醒酒',
'船回雾起堤',
'高城秋自落',
'杂树晚相迷',
'坐触鸳鸯起',
'巢倾翡翠低',
'莫须惊白鹭',
'为伴宿清溪',
],
},
{
title: '初冬',
body: [
'垂老戎衣窄',
'归休寒色深',
'渔舟上急水',
'猎火著高林',
'日有习池醉',
'愁来梁甫吟',
'干戈未偃息',
'出处遂何心',
],
},
{
title: '至后',
body: [
'冬至至后日初长',
'远在剑南思洛阳',
'青袍白马有何意',
'金谷铜驼非故乡',
'梅花欲开不自觉',
'棣萼一别永相望',
'愁极本凭诗遣兴',
'诗成吟咏转凄凉',
],
},
{
title: '正月三日归溪上有作,简院内诸公',
body: [
'野外堂依竹',
'篱边水向城',
'蚁浮仍腊味',
'鸥泛已春声',
'药许邻人劚',
'书从稚子擎',
'白头趋幕府',
'深觉负平生',
],
},
{
title: '弊庐遣兴,奉寄严公',
body: [
'野水平桥路',
'春沙映竹村',
'风轻粉蝶喜',
'花暖蜜蜂喧',
'把酒宜深酌',
'题诗好细论',
'府中瞻暇日',
'江上忆词源',
'迹忝朝廷旧',
'情依节制尊',
'还思长者辙',
'恐避席为门',
],
},
{
title: '春日江村五首',
body: [
'农务村村急',
'春流岸岸深',
'乾坤万里眼',
'时序百年心',
'茅屋还堪赋',
'桃源自可寻',
'艰难贱生理',
'飘泊到如今',
'迢递来三蜀',
'蹉跎有六年',
'客身逢故旧',
'发兴自林泉',
'过懒从衣结',
'频游任履穿',
'藩篱无限景',
'恣意买江天',
'种竹交加翠',
'栽桃烂熳红',
'经心石镜月',
'到面雪山风',
'赤管随王命',
'银章付老翁',
'岂知牙齿落',
'名玷荐贤中',
'扶病垂朱绂',
'归休步紫苔',
'郊扉存晚计',
'幕府愧群材',
'燕外晴丝卷',
'鸥边水叶开',
'邻家送鱼鳖',
'问我数能来',
'群盗哀王粲',
'中年召贾生',
'登楼初有作',
'前席竟为荣',
'宅入先贤传',
'才高处士名',
'异时怀二子',
'春日复含情',
],
},
{
title: '绝句六首',
body: [
'日出篱东水',
'云生舍北泥',
'竹高鸣翡翠',
'沙僻舞鹍鸡',
'蔼蔼花蕊乱',
'飞飞蜂蝶多',
'幽栖身懒动',
'客至欲如何',
'凿井交棕叶',
'开渠断竹根',
'扁舟轻褭缆',
'小径曲通村',
'急雨捎溪足',
'斜晖转树腰',
'隔巢黄鸟并',
'翻藻白鱼跳',
'舍下笋穿壁',
'庭中藤刺檐',
'地晴丝冉冉',
'江白草纤纤',
'江动月移石',
'溪虚云傍花',
'鸟栖知故道',
'帆过宿谁家',
],
},
{
title: '绝句四首',
body: [
'堂西长笋别开门',
'堑北行椒却背村',
'梅熟许同朱老吃',
'松高拟对阮生论',
'欲作鱼梁云复湍',
'因惊四月雨声寒',
'青溪先有蛟龙窟',
'竹石如山不敢安',
'两个黄鹂鸣翠柳',
'一行白鹭上青天',
'窗含西岭千秋雪',
'门泊东吴万里船',
'药条药甲润青青',
'色过棕亭入草亭',
'苗满空山惭取誉',
'根居隙地怯成形',
],
},
{
title: '哭严仆射归榇',
body: [
'素幔随流水',
'归舟返旧京',
'老亲如宿昔',
'部曲异平生',
'风送蛟龙雨',
'天长骠骑营',
'一哀三峡暮',
'遗后见君情',
],
},
{
title: '宴戎州杨使君东楼',
body: [
'胜绝惊身老',
'情忘发兴奇',
'座从歌妓密',
'乐任主人为',
'重碧拈春酒',
'轻红擘荔枝',
'楼高欲愁思',
'横笛未休吹',
],
},
{
title: '渝州候严六侍御不到,先下峡',
body: [
'闻道乘骢发',
'沙边待至今',
'不知云雨散',
'虚费短长吟',
'山带乌蛮阔',
'江连白帝深',
'船经一柱观',
'留眼共登临',
],
},
{
title: '拨闷(一作赠严二别驾)',
body: [
'闻道云安麹米春',
'才倾一盏即醺人',
'乘舟取醉非难事',
'下峡消愁定几巡',
'长年三老遥怜汝',
'棙柁开头捷有神',
'已办青钱防雇直',
'当令美味入吾唇',
],
},
{
title: '闻高常侍亡(忠州作)',
body: [
'归朝不相见',
'蜀使忽传亡',
'虚历金华省',
'何殊地下郎',
'致君丹槛折',
'哭友白云长',
'独步诗名在',
'只令故旧伤',
],
},
{
title: '宴忠州使君侄宅',
body: [
'出守吾家侄',
'殊方此日欢',
'自须游阮巷',
'不是怕湖滩',
'乐助长歌逸',
'杯饶旅思宽',
'昔曾如意舞',
'牵率强为看',
],
},
{
title: '禹庙(此忠州临江县禹祠也)',
body: [
'禹庙空山里',
'秋风落日斜',
'荒庭垂橘柚',
'古屋画龙蛇',
'云气生虚壁',
'江声走白沙',
'早知乘四载',
'疏凿控三巴',
],
},
{
title: '题忠州龙兴寺所居院壁',
body: [
'忠州三峡内',
'井邑聚云根',
'小市常争米',
'孤城早闭门',
'空看过客泪',
'莫觅主人恩',
'淹泊仍愁虎',
'深居赖独园',
],
},
{
title: '旅夜书怀',
body: [
'细草微风岸',
'危樯独夜舟',
'星垂平野阔',
'月涌大江流',
'名岂文章著',
'官因老病休',
'飘飘何所似',
'天地一沙鸥',
],
},
{
title: '别常征君',
body: [
'儿扶犹杖策',
'卧病一秋强',
'白发少新洗',
'寒衣宽总长',
'故人忧见及',
'此别泪相忘',
'各逐萍流转',
'来书细作行',
],
},
{
title: '三绝句',
body: [
'前年渝州杀刺史',
'今年开州杀刺史',
'群盗相随剧虎狼',
'食人更肯留妻子',
'二十一家同入蜀',
'惟残一人出骆谷',
'自说二女啮臂时',
'回头却向秦云哭',
'殿前兵马虽骁雄',
'纵暴略与羌浑同',
'闻道杀人汉水上',
'妇女多在官军中',
],
},
{
title: '十二月一日三首',
body: [
'今朝腊月春意动',
'云安县前江可怜',
'一声何处送书雁',
'百丈谁家上水船',
'未将梅蕊惊愁眼',
'要取楸花媚远天',
'明光起草人所羡',
'肺病几时朝日边',
'寒轻市上山烟碧',
'日满楼前江雾黄',
'负盐出井此溪女',
'打鼓发船何郡郎',
'新亭举目风景切',
'茂陵著书消渴长',
'春花不愁不烂漫',
'楚客唯听棹相将',
'即看燕子入山扉',
'岂有黄鹂历翠微',
'短短桃花临水岸',
'轻轻柳絮点人衣',
'春来准拟开怀久',
'老去亲知见面稀',
'他日一杯难强进',
'重嗟筋力故山违',
],
},
{
title: '又雪',
body: [
'南雪不到地',
'青崖沾未消',
'微微向日薄',
'脉脉去人遥',
'冬热鸳鸯病',
'峡深豺虎骄',
'愁边有江水',
'焉得北之朝',
],
},
{
title: '奉汉中王手札',
body: [
'国有乾坤大',
'王今叔父尊',
'剖符来蜀道',
'归盖取荆门',
'峡险通舟过',
'水长注海奔',
'主人留上客',
'避暑得名园',
'前后缄书报',
'分明馔玉恩',
'天云浮绝壁',
'风竹在华轩',
'已觉良宵永',
'何看骇浪翻',
'入期朱邸雪',
'朝傍紫微垣',
'枚乘文章老',
'河间礼乐存',
'悲秋宋玉宅',
'失路武陵源',
'淹薄俱崖口',
'东西异石根',
'夷音迷咫尺',
'鬼物傍黄昏',
'犬马诚为恋',
'狐狸不足论',
'从容草奏罢',
'宿昔奉清樽',
],
},
{
title: '赠崔十三评事公辅',
body: [
'飘飘西极马',
'来自渥洼池',
'飒飁定山桂',
'低徊风雨枝',
'我闻龙正直',
'道屈尔何为',
'且有元戎命',
'悲歌识者谁',
'官联辞冗长',
'行路洗欹危',
'脱剑主人赠',
'去帆春色随',
'阴沉铁凤阙',
'教练羽林儿',
'天子朝侵早',
'云台仗数移',
'分军应供给',
'百姓日支离',
'黠吏因封己',
'公才或守雌',
'燕王买骏骨',
'渭老得熊罴',
'活国名公在',
'拜坛群寇疑',
'冰壶动瑶碧',
'野水失蛟螭',
'入幕诸彦集',
'渴贤高选宜',
'骞腾坐可致',
'九万起于斯',
'复进出矛戟',
'昭然开鼎彝',
'会看之子贵',
'叹及老夫衰',
'岂但江曾决',
'还思雾一披',
'暗尘生古镜',
'拂匣照西施',
'舅氏多人物',
'无惭困翮垂',
],
},
{
title: '长江二首',
body: [
'众水会涪万',
'瞿塘争一门',
'朝宗人共挹',
'盗贼尔谁尊',
'孤石隐如马',
'高萝垂饮猿',
'归心异波浪',
'何事即飞翻',
'浩浩终不息',
'乃知东极临',
'众流归海意',
'万国奉君心',
'色借潇湘阔',
'声驱滟滪深',
'未辞添雾雨',
'接上遇衣襟',
],
},
{
title: '承闻故房相公灵榇自阆州启殡归葬东都有作二首',
body: [
'远闻房太守',
'归葬陆浑山',
'一德兴王后',
'孤魂久客间',
'孔明多故事',
'安石竟崇班',
'他日嘉陵涕',
'仍沾楚水还',
'丹旐飞飞日',
'初传发阆州',
'风尘终不解',
'江汉忽同流',
'剑动新身匣',
'书归故国楼',
'尽哀知有处',
'为客恐长休',
],
},
{
title: '云安九日,郑十八携酒陪诸公宴',
body: [
'寒花开已尽',
'菊蕊独盈枝',
'旧摘人频异',
'轻香酒暂随',
'地偏初衣夹',
'山拥更登危',
'万国皆戎马',
'酣歌泪欲垂',
],
},
{
title: '答郑十七郎一绝',
body: ['雨后过畦润', '花残步屐迟', '把文惊小陆', '好客见当时'],
},
{
title: '将晓二首',
body: [
'石城除击柝',
'铁锁欲开关',
'鼓角悲荒塞',
'星河落曙山',
'巴人常小梗',
'蜀使动无还',
'垂老孤帆色',
'飘飘犯百蛮',
'军吏回官烛',
'舟人自楚歌',
'寒沙蒙薄雾',
'落月去清波',
'壮惜身名晚',
'衰惭应接多',
'归朝日簪笏',
'筋力定如何',
],
},
{
title: '怀锦水居止二首',
body: [
'军旅西征僻',
'风尘战伐多',
'犹闻蜀父老',
'不忘舜讴歌',
'天险终难立',
'柴门岂重过',
'朝朝巫峡水',
'远逗锦江波',
'万里桥南宅',
'百花潭北庄',
'层轩皆面水',
'老树饱经霜',
'雪岭界天白',
'锦城曛日黄',
'惜哉形胜地',
'回首一茫茫',
],
},
{
title: '子规',
body: [
'峡里云安县',
'江楼翼瓦齐',
'两边山木合',
'终日子规啼',
'眇眇春风见',
'萧萧夜色凄',
'客愁那听此',
'故作傍人低',
],
},
{
title: '立春',
body: [
'春日春盘细生菜',
'忽忆两京梅发时',
'盘出高门行白玉',
'菜传纤手送青丝',
'巫峡寒江那对眼',
'杜陵远客不胜悲',
'此身未知归定处',
'呼儿觅纸一题诗',
],
},
{
title: '漫成一绝',
body: [
'江月去人只数尺',
'风灯照夜欲三更',
'沙头宿鹭联拳静',
'船尾跳鱼拨剌鸣',
],
},
{
title: '老病',
body: [
'老病巫山里',
'稽留楚客中',
'药残他日裹',
'花发去年丛',
'夜足沾沙雨',
'春多逆水风',
'合分双赐笔',
'犹作一飘蓬',
],
},
{
title: '南楚',
body: [
'南楚青春异',
'暄寒早早分',
'无名江上草',
'随意岭头云',
'正月蜂相见',
'非时鸟共闻',
'杖藜妨跃马',
'不是故离群',
],
},
{
title: '寄常征君',
body: [
'白水青山空复春',
'征君晚节傍风尘',
'楚妃堂上色殊众',
'海鹤阶前鸣向人',
'万事纠纷犹绝粒',
'一官羁绊实藏身',
'开州入夏知凉冷',
'不似云安毒热新',
],
},
{
title: '寄岑嘉州(州据蜀江外)',
body: [
'不见故人十年馀',
'不道故人无素书',
'愿逢颜色关塞远',
'岂意出守江城居',
'外江三峡且相接',
'斗酒新诗终日疏',
'谢脁每篇堪讽诵',
'冯唐已老听吹嘘',
'泊船秋夜经春草',
'伏枕青枫限玉除',
'眼前所寄选何物',
'赠子云安双鲤鱼',
],
},
{
title: '移居夔州郭',
body: [
'伏枕云安县',
'迁居白帝城',
'春知催柳别',
'江与放船清',
'农事闻人说',
'山光见鸟情',
'禹功饶断石',
'且就土微平',
],
},
{
title: '船下夔州郭宿,雨湿不得上岸,别王十二判官',
body: [
'依沙宿舸船',
'石濑月娟娟',
'风起春灯乱',
'江鸣夜雨悬',
'晨钟云外湿',
'胜地石堂烟',
'柔橹轻鸥外',
'含凄觉汝贤',
],
},
{
title: '雨不绝',
body: [
'鸣雨既过渐细微',
'映空摇飏如丝飞',
'阶前短草泥不乱',
'院里长条风乍稀',
'舞石旋应将乳子',
'行云莫自湿仙衣',
'眼边江舸何匆促',
'未待安流逆浪归',
],
},
{
title: '崔评事弟许相迎不到应虑老夫见泥雨…必愆佳期走笔戏简',
body: [
'江阁要宾许马迎',
'午时起坐自天明',
'浮云不负青春色',
'细雨何孤白帝城',
'身过花间沾湿好',
'醉于马上往来轻',
'虚疑皓首冲泥怯',
'实少银鞍傍险行',
],
},
{
title: '宿江边阁(即后西阁)',
body: [
'暝色延山径',
'高斋次水门',
'薄云岩际宿',
'孤月浪中翻',
'鹳鹤追飞静',
'豺狼得食喧',
'不眠忧战伐',
'无力正乾坤',
],
},
{
title: '夜宿西阁,晓呈元二十一曹长',
body: [
'城暗更筹急',
'楼高雨雪微',
'稍通绡幕霁',
'远带玉绳稀',
'门鹊晨光起',
'墙乌宿处飞',
'寒江流甚细',
'有意待人归',
],
},
{
title: '西阁口号(呈元二十一)',
body: [
'山木抱云稠',
'寒江绕上头',
'雪崖才变石',
'风幔不依楼',
'社稷堪流涕',
'安危在运筹',
'看君话王室',
'感动几销忧',
],
},
{
title: '西阁雨望',
body: [
'楼雨沾云幔',
'山寒著水城',
'径添沙面出',
'湍减石棱生',
'菊蕊凄疏放',
'松林驻远情',
'滂沱朱槛湿',
'万虑傍檐楹',
],
},
{
title: '不离西阁二首',
body: [
'江柳非时发',
'江花冷色频',
'地偏应有瘴',
'腊近已含春',
'失学从愚子',
'无家住老身',
'不知西阁意',
'肯别定留人',
'西阁从人别',
'人今亦故亭',
'江云飘素练',
'石壁断空青',
'沧海先迎日',
'银河倒列星',
'平生耽胜事',
'吁骇始初经',
],
},
{
title: '西阁三度期大昌严明府同宿不到',
body: [
'问子能来宿',
'今疑索故要',
'匣琴虚夜夜',
'手板自朝朝',
'金吼霜钟彻',
'花催腊炬销',
'早凫江槛底',
'双影漫飘飖',
],
},
{
title: '西阁二首',
body: [
'巫山小摇落',
'碧色见松林',
'百鸟各相命',
'孤云无自心',
'层轩俯江壁',
'要路亦高深',
'朱绂犹纱帽',
'新诗近玉琴',
'功名不早立',
'衰病谢知音',
'哀世非王粲',
'终然学越吟',
'懒心似江水',
'日夜向沧洲',
'不道含香贱',
'其如镊白休',
'经过调碧柳',
'萧索倚朱楼',
'毕娶何时竟',
'消中得自由',
'豪华看古往',
'服食寄冥搜',
'诗尽人间兴',
'兼须入海求',
],
},
{
title: '阁夜',
body: [
'岁暮阴阳催短景',
'天涯霜雪霁寒宵',
'五更鼓角声悲壮',
'三峡星河影动摇',
'野哭几家闻战伐',
'夷歌数处起渔樵',
'卧龙跃马终黄土',
'人事依依漫寂寥',
],
},
{
title: '西阁夜',
body: [
'恍惚寒山暮',
'逶迤白雾昏',
'山虚风落石',
'楼静月侵门',
'击柝可怜子',
'无衣何处村',
'时危关百虑',
'盗贼尔犹存',
],
},
{
title: '瀼西寒望',
body: [
'水色含群动',
'朝光切太虚',
'年侵频怅望',
'兴远一萧疏',
'猿挂时相学',
'鸥行炯自如',
'瞿唐春欲至',
'定卜瀼西居',
],
},
{
title: '入宅三首(大历二年春,甫自西阁迁赤甲)',
body: [
'奔峭背赤甲',
'断崖当白盐',
'客居愧迁次',
'春酒渐多添',
'花亚欲移竹',
'鸟窥新卷帘',
'衰年不敢恨',
'胜概欲相兼',
'乱后居难定',
'春归客未还',
'水生鱼复浦',
'云暖麝香山',
'半顶梳头白',
'过眉拄杖斑',
'相看多使者',
'一一问函关',
'宋玉归州宅',
'云通白帝城',
'吾人淹老病',
'旅食岂才名',
'峡口风常急',
'江流气不平',
'只应与儿子',
'飘转任浮生',
],
},
{
title: '赤甲',
body: [
'卜居赤甲迁居新',
'两见巫山楚水春',
'炙背可以献天子',
'美芹由来知野人',
'荆州郑薛寄书近',
'蜀客郗岑非我邻',
'笑接郎中评事饮',
'病从深酌道吾真',
],
},
{
title: '卜居',
body: [
'归羡辽东鹤',
'吟同楚执珪',
'未成游碧海',
'著处觅丹梯',
'云障宽江左',
'春耕破瀼西',
'桃红客若至',
'定似昔人迷',
],
},
{
title: '暮春题瀼西新赁草屋五首',
body: [
'久嗟三峡客',
'再与暮春期',
'百舌欲无语',
'繁花能几时',
'谷虚云气薄',
'波乱日华迟',
'战伐何由定',
'哀伤不在兹',
'此邦千树橘',
'不见比封君',
'养拙干戈际',
'全生麋鹿群',
'畏人江北草',
'旅食瀼西云',
'万里巴渝曲',
'三年实饱闻',
'彩云阴复白',
'锦树晓来青',
'身世双蓬鬓',
'乾坤一草亭',
'哀歌时自短',
'醉舞为谁醒',
'细雨荷锄立',
'江猿吟翠屏',
'壮年学书剑',
'他日委泥沙',
'事主非无禄',
'浮生即有涯',
'高斋依药饵',
'绝域改春华',
'丧乱丹心破',
'王臣未一家',
'欲陈济世策',
'已老尚书郎',
'未息豺虎斗',
'空惭鸳鹭行',
'时危人事急',
'风逆羽毛伤',
'落日悲江汉',
'中宵泪满床',
],
},
{
title: '园',
body: [
'仲夏流多水',
'清晨向小园',
'碧溪摇艇阔',
'朱果烂枝繁',
'始为江山静',
'终防市井喧',
'畦蔬绕茅屋',
'自足媚盘餐',
],
},
{
title: '竖子至',
body: [
'楂梨且缀碧',
'梅杏半传黄',
'小子幽园至',
'轻笼熟柰香',
'山风犹满把',
'野露及新尝',
'欲寄江湖客',
'提携日月长',
],
},
{
title: '示獠奴阿段',
body: [
'山木苍苍落日曛',
'竹竿褭褭细泉分',
'郡人入夜争馀沥',
'竖子寻源独不闻',
'病渴三更回白首',
'传声一注湿青云',
'曾惊陶侃胡奴异',
'怪尔常穿虎豹群',
],
},
{
title: '秋野五首',
body: [
'秋野日疏芜',
'寒江动碧虚',
'系舟蛮井络',
'卜宅楚村墟',
'枣熟从人打',
'葵荒欲自锄',
'盘餐老夫食',
'分减及溪鱼',
'易识浮生理',
'难教一物违',
'水深鱼极乐',
'林茂鸟知归',
'吾老甘贫病',
'荣华有是非',
'秋风吹几杖',
'不厌此山薇',
'礼乐攻吾短',
'山林引兴长',
'掉头纱帽仄',
'曝背竹书光',
'风落收松子',
'天寒割蜜房',
'稀疏小红翠',
'驻屐近微香',
'远岸秋沙白',
'连山晚照红',
'潜鳞输骇浪',
'归翼会高风',
'砧响家家发',
'樵声个个同',
'飞霜任青女',
'赐被隔南宫',
'身许麒麟画',
'年衰鸳鹭群',
'大江秋易盛',
'空峡夜多闻',
'径隐千重石',
'帆留一片云',
'儿童解蛮语',
'不必作参军',
],
},
{
title: '溪上',
body: [
'峡内淹留客',
'溪边四五家',
'古苔生迮地',
'秋竹隐疏花',
'塞俗人无井',
'山田饭有沙',
'西江使船至',
'时复问京华',
],
},
{
title: '树间',
body: [
'岑寂双甘树',
'婆娑一院香',
'交柯低几杖',
'垂实碍衣裳',
'满岁如松碧',
'同时待菊黄',
'几回沾叶露',
'乘月坐胡床',
],
},
{
title: '课小竖鉏斫舍北果林,枝蔓荒秽,净讫移床三首',
body: [
'病枕依茅栋',
'荒鉏净果林',
'背堂资僻远',
'在野兴清深',
'山雉防求敌',
'江猿应独吟',
'泄云高不去',
'隐几亦无心',
'众壑生寒早',
'长林卷雾齐',
'青虫悬就日',
'朱果落封泥',
'薄俗防人面',
'全身学马蹄',
'吟诗坐回首',
'随意葛巾低',
'篱弱门何向',
'沙虚岸只摧',
'日斜鱼更食',
'客散鸟还来',
'寒水光难定',
'秋山响易哀',
'天涯稍曛黑',
'倚杖更裴回',
],
},
{
title: '寒雨朝行视园树',
body: [
'柴门杂树向千株',
'丹橘黄甘此地无',
'江上今朝寒雨歇',
'篱中秀色画屏纡',
'桃蹊李径年虽故',
'栀子红椒艳复殊',
'锁石藤稍元自落',
'倚天松骨见来枯',
'林香出实垂将尽',
'叶蒂辞枝不重苏',
'爱日恩光蒙借贷',
'清霜杀气得忧虞',
'衰颜更觅藜床坐',
'缓步仍须竹杖扶',
'散骑未知云阁处',
'啼猿僻在楚山隅',
],
},
{
title: '季秋江村',
body: [
'乔木村墟古',
'疏篱野蔓悬',
'清琴将暇日',
'白首望霜天',
'登俎黄甘重',
'支床锦石圆',
'远游虽寂寞',
'难见此山川',
],
},
{
title: '小园',
body: [
'由来巫峡水',
'本自楚人家',
'客病留因药',
'春深买为花',
'秋庭风落果',
'瀼岸雨颓沙',
'问俗营寒事',
'将诗待物华',
],
},
{
title: '自瀼西荆扉且移居东屯茅屋四首',
body: [
'白盐危峤北',
'赤甲古城东',
'平地一川稳',
'高山四面同',
'烟霜凄野日',
'粳稻熟天风',
'人事伤蓬转',
'吾将守桂丛',
'东屯复瀼西',
'一种住青溪',
'来往皆茅屋',
'淹留为稻畦',
'市喧宜近利',
'林僻此无蹊',
'若访衰翁语',
'须令剩客迷',
'道北冯都使',
'高斋见一川',
'子能渠细石',
'吾亦沼清泉',
'枕带还相似',
'柴荆即有焉',
'斫畬应费日',
'解缆不知年',
'牢落西江外',
'参差北户间',
'久游巴子国',
'卧病楚人山',
'幽独移佳境',
'清深隔远关',
'寒空见鸳鹭',
'回首忆朝班',
],
},
{
title: '茅堂检校收稻二首',
body: [
'香稻三秋末',
'平田百顷间',
'喜无多屋宇',
'幸不碍云山',
'御夹侵寒气',
'尝新破旅颜',
'红鲜终日有',
'玉粒未吾悭',
'稻米炊能白',
'秋葵煮复新',
'谁云滑易饱',
'老藉软俱匀',
'种幸房州熟',
'苗同伊阙春',
'无劳映渠碗',
'自有色如银',
],
},
{
title: '东屯月夜',
body: [
'抱疾漂萍老',
'防边旧谷屯',
'春农亲异俗',
'岁月在衡门',
'青女霜枫重',
'黄牛峡水喧',
'泥留虎斗迹',
'月挂客愁村',
'乔木澄稀影',
'轻云倚细根',
'数惊闻雀噪',
'暂睡想猿蹲',
'日转东方白',
'风来北斗昏',
'天寒不成寝',
'无梦寄归魂',
],
},
{
title: '东屯北崦',
body: [
'盗贼浮生困',
'诛求异俗贫',
'空村惟见鸟',
'落日未逢人',
'步壑风吹面',
'看松露滴身',
'远山回白首',
'战地有黄尘',
],
},
{
title: '从驿次草堂复至东屯二首',
body: [
'峡内归田客',
'江边借马骑',
'非寻戴安道',
'似向习家池',
'峡险风烟僻',
'天寒橘柚垂',
'筑场看敛积',
'一学楚人为',
'短景难高卧',
'衰年强此身',
'山家蒸栗暖',
'野饭谢麋新',
'世路知交薄',
'门庭畏客频',
'牧童斯在眼',
'田父实为邻',
],
},
{
title: '暂往白帝复还东屯',
body: [
'复作归田去',
'犹残获稻功',
'筑场怜穴蚁',
'拾穗许村童',
'落杵光辉白',
'除芒子粒红',
'加餐可扶老',
'仓庾慰飘蓬',
],
},
{
title: '刈稻了咏怀',
body: [
'稻获空云水',
'川平对石门',
'寒风疏落木',
'旭日散鸡豚',
'野哭初闻战',
'樵歌稍出村',
'无家问消息',
'作客信乾坤',
],
},
{
title: '上白帝城(公孙述僭位于此,自称白帝)',
body: [
'城峻随天壁',
'楼高更女墙',
'江流思夏后',
'风至忆襄王',
'老去闻悲角',
'人扶报夕阳',
'公孙初恃险',
'跃马意何长',
],
},
{
title: '上白帝城二首',
body: [
'江城含变态',
'一上一回新',
'天欲今朝雨',
'山归万古春',
'英雄馀事业',
'衰迈久风尘',
'取醉他乡客',
'相逢故国人',
'兵戈犹拥蜀',
'赋敛强输秦',
'不是烦形胜',
'深惭畏损神',
'白帝空祠庙',
'孤云自往来',
'江山城宛转',
'栋宇客裴回',
'勇略今何在',
'当年亦壮哉',
'后人将酒肉',
'虚殿日尘埃',
'谷鸟鸣还过',
'林花落又开',
'多惭病无力',
'骑马入青苔',
],
},
{
title: '武侯庙(庙在白帝西郊)',
body: ['遗庙丹青落', '空山草木长', '犹闻辞后主', '不复卧南阳'],
},
{
title: '八阵图',
body: ['功盖三分国', '名高八阵图', '江流石不转', '遗恨失吞吴'],
},
{
title: '谒先主庙(刘昭烈庙在奉节县东六里)',
body: [
'惨淡风云会',
'乘时各有人',
'力侔分社稷',
'志屈偃经纶',
'复汉留长策',
'中原仗老臣',
'杂耕心未已',
'欧血事酸辛',
'霸气西南歇',
'雄图历数屯',
'锦江元过楚',
'剑阁复通秦',
'旧俗存祠庙',
'空山立鬼神',
'虚檐交鸟道',
'枯木半龙鳞',
'竹送清溪月',
'苔移玉座春',
'闾阎儿女换',
'歌舞岁时新',
'绝域归舟远',
'荒城系马频',
'如何对摇落',
'况乃久风尘',
'孰与关张并',
'功临耿邓亲',
'应天才不小',
'得士契无邻',
'迟暮堪帷幄',
'飘零且钓缗',
'向来忧国泪',
'寂寞洒衣巾',
],
},
{
title: '白盐山(白盐崖高千馀丈,在州城东十七里)',
body: [
'卓立群峰外',
'蟠根积水边',
'他皆任厚地',
'尔独近高天',
'白榜千家邑',
'清秋万估船',
'词人取佳句',
'刻画竟谁传',
],
},
{
title: '滟滪堆',
body: [
'巨积水中央',
'江寒出水长',
'沈牛答云雨',
'如马戒舟航',
'天意存倾覆',
'神功接混茫',
'干戈连解缆',
'行止忆垂堂',
],
},
{
title: '滟滪',
body: [
'滟滪既没孤根深',
'西来水多愁太阴',
'江天漠漠鸟双去',
'风雨时时龙一吟',
'舟人渔子歌回首',
'估客胡商泪满襟',
'寄语舟航恶年少',
'休翻盐井横黄金',
],
},
{
title: '白帝',
body: [
'白帝城中云出门',
'白帝城下雨翻盆',
'高江急峡雷霆斗',
'翠木苍藤日月昏',
'戎马不如归马逸',
'千家今有百家存',
'哀哀寡妇诛求尽',
'恸哭秋原何处村',
],
},
{
title: '白帝城楼',
body: [
'江度寒山阁',
'城高绝塞楼',
'翠屏宜晚对',
'白谷会深游',
'急急能鸣雁',
'轻轻不下鸥',
'彝陵春色起',
'渐拟放扁舟',
],
},
{
title: '晓望白帝城盐山',
body: [
'徐步移班杖',
'看山仰白头',
'翠深开断壁',
'红远结飞楼',
'日出清江望',
'暄和散旅愁',
'春城见松雪',
'始拟进归舟',
],
},
{
title: '白帝城最高楼',
body: [
'城尖径昃旌旆愁',
'独立缥缈之飞楼',
'峡坼云霾龙虎卧',
'江清日抱鼋鼍游',
'扶桑西枝对断石',
'弱水东影随长流',
'杖藜叹世者谁子',
'泣血迸空回白头',
],
},
{
title: '白帝楼',
body: [
'漠漠虚无里',
'连连睥睨侵',
'楼光去日远',
'峡影入江深',
'腊破思端绮',
'春归待一金',
'去年梅柳意',
'还欲搅边心',
],
},
{
title: '陪诸公上白帝城宴越公堂之作(越公杨素所建)',
body: [
'此堂存古制',
'城上俯江郊',
'落构垂云雨',
'荒阶蔓草茅',
'柱穿蜂溜蜜',
'栈缺燕添巢',
'坐接春杯气',
'心伤艳蕊梢',
'英灵如过隙',
'宴衎愿投胶',
'莫问东流水',
'生涯未即抛',
],
},
{
title: '峡隘',
body: [
'闻说江陵府',
'云沙静眇然',
'白鱼如切玉',
'朱橘不论钱',
'水有远湖树',
'人今何处船',
'青山各在眼',
'却望峡中天',
],
},
{
title: '诸葛庙',
body: [
'久游巴子国',
'屡入武侯祠',
'竹日斜虚寝',
'溪风满薄帷',
'君臣当共济',
'贤圣亦同时',
'翊戴归先主',
'并吞更出师',
'虫蛇穿画壁',
'巫觋醉蛛丝',
'欻忆吟梁父',
'躬耕也未迟',
],
},
{
title: '峡口二首',
body: [
'峡口大江间',
'西南控百蛮',
'城欹连粉堞',
'岸断更青山',
'开辟多天险',
'防隅一水关',
'乱离闻鼓角',
'秋气动衰颜',
'时清关失险',
'世乱戟如林',
'去矣英雄事',
'荒哉割据心',
'芦花留客晚',
'枫树坐猿深',
'疲苶烦亲故',
'诸侯数赐金',
],
},
{
title: '天池',
body: [
'天池马不到',
'岚壁鸟才通',
'百顷青云杪',
'层波白石中',
'郁纡腾秀气',
'萧瑟浸寒空',
'直对巫山出',
'兼疑夏禹功',
'鱼龙开辟有',
'菱芡古今同',
'闻道奔雷黑',
'初看浴日红',
'飘零神女雨',
'断续楚王风',
'欲问支机石',
'如临献宝宫',
'九秋惊雁序',
'万里狎渔翁',
'更是无人处',
'诛茅任薄躬',
],
},
{
title: '瞿塘两崖',
body: [
'三峡传何处',
'双崖壮此门',
'入天犹石色',
'穿水忽云根',
'猱玃须髯古',
'蛟龙窟宅尊',
'羲和冬驭近',
'愁畏日车翻',
],
},
{
title: '夔州歌十绝句',
body: [
'中巴之东巴东山',
'江水开辟流其间',
'白帝高为三峡镇',
'夔州险过百牢关',
'白帝夔州各异城',
'蜀江楚峡混殊名',
'英雄割据非天意',
'霸主并吞在物情',
'群雄竞起问前朝',
'王者无外见今朝',
'比讶渔阳结怨恨',
'元听舜日旧箫韶',
'赤甲白盐俱刺天',
'闾阎缭绕接山巅',
'枫林橘树丹青合',
'复道重楼锦绣悬',
'瀼东瀼西一万家',
'江北江南春冬花',
'背飞鹤子遗琼蕊',
'相趁凫雏入蒋牙',
'东屯稻畦一百顷',
'北有涧水通青苗',
'晴浴狎鸥分处处',
'雨随神女下朝朝',
'蜀麻吴盐自古通',
'万斛之舟行若风',
'长年三老长歌里',
'白昼摊钱高浪中',
'忆昔咸阳都市合',
'山水之图张卖时',
'巫峡曾经宝屏见',
'楚宫犹对碧峰疑',
'武侯祠堂不可忘',
'中有松柏参天长',
'干戈满地客愁破',
'云日如火炎天凉',
'阆风玄圃与蓬壶',
'中有高堂天下无',
'借问夔州压何处',
'峡门江腹拥城隅',
],
},
{
title: '上卿翁请修武侯庙,遗像缺落,时崔卿权夔州',
body: [
'大贤为政即多闻',
'刺史真符不必分',
'尚有西郊诸葛庙',
'卧龙无首对江濆',
],
},
{
title: '偶题',
body: [
'文章千古事',
'得失寸心知',
'作者皆殊列',
'名声岂浪垂',
'骚人嗟不见',
'汉道盛于斯',
'前辈飞腾入',
'馀波绮丽为',
'后贤兼旧列',
'历代各清规',
'法自儒家有',
'心从弱岁疲',
'永怀江左逸',
'多病邺中奇',
'騄骥皆良马',
'骐驎带好儿',
'车轮徒已斫',
'堂构惜仍亏',
'漫作潜夫论',
'虚传幼妇碑',
'缘情慰漂荡',
'抱疾屡迁移',
'经济惭长策',
'飞栖假一枝',
'尘沙傍蜂虿',
'江峡绕蛟螭',
'萧瑟唐虞远',
'联翩楚汉危',
'圣朝兼盗贼',
'异俗更喧卑',
'郁郁星辰剑',
'苍苍云雨池',
'两都开幕府',
'万宇插军麾',
'南海残铜柱',
'东风避月支',
'音书恨乌鹊',
'号怒怪熊罴',
'稼穑分诗兴',
'柴荆学土宜',
'故山迷白阁',
'秋水隐黄陂',
'不敢要佳句',
'愁来赋别离',
],
},
{
title: '秋兴八首',
body: [
'玉露凋伤枫树林',
'巫山巫峡气萧森',
'江间波浪兼天涌',
'塞上风云接地阴',
'丛菊两开他日泪',
'孤舟一系故园心',
'寒衣处处催刀尺',
'白帝城高急暮砧',
'夔府孤城落日斜',
'每依南斗望京华',
'听猿实下三声泪',
'奉使虚随八月查',
'画省香炉违伏枕',
'山楼粉堞隐悲笳',
'请看石上藤萝月',
'已映洲前芦荻花',
'千家山郭静朝晖',
'一日江楼坐翠微',
'信宿渔人还泛泛',
'清秋燕子故飞飞',
'匡衡抗疏功名薄',
'刘向传经心事违',
'同学少年多不贱',
'五陵衣马自轻肥',
'闻道长安似弈棋',
'百年世事不胜悲',
'王侯第宅皆新主',
'文武衣冠异昔时',
'直北关山金鼓振',
'征西车马羽书迟',
'鱼龙寂寞秋江冷',
'故国平居有所思',
'蓬莱宫阙对南山',
'承露金茎霄汉间',
'西望瑶池降王母',
'东来紫气满函关',
'云移雉尾开宫扇',
'日绕龙鳞识圣颜',
'一卧沧江惊岁晚',
'几回青琐照朝班',
'瞿唐峡口曲江头',
'万里风烟接素秋',
'花萼夹城通御气',
'芙蓉小苑入边愁',
'朱帘绣柱围黄鹤',
'锦缆牙樯起白鸥',
'回首可怜歌舞地',
'秦中自古帝王州',
'昆明池水汉时功',
'武帝旌旗在眼中',
'织女机丝虚月夜',
'石鲸鳞甲动秋风',
'波漂菰米沈云黑',
'露冷莲房坠粉红',
'关塞极天唯鸟道',
'江湖满地一渔翁',
'昆吾御宿自逶迤',
'紫阁峰阴入渼陂',
'香稻啄馀鹦鹉粒',
'碧梧栖老凤凰枝',
'佳人拾翠春相问',
'仙侣同舟晚更移',
'彩笔昔游干气象',
'白头吟望苦低垂',
],
},
{
title: '咏怀古迹五首',
body: [
'支离东北风尘际',
'漂泊西南天地间',
'三峡楼台淹日月',
'五溪衣服共云山',
'羯胡事主终无赖',
'词客哀时且未还',
'庾信平生最萧瑟',
'暮年诗赋动江关',
'摇落深知宋玉悲',
'风流儒雅亦吾师',
'怅望千秋一洒泪',
'萧条异代不同时',
'江山故宅空文藻',
'云雨荒台岂梦思',
'最是楚宫俱泯灭',
'舟人指点到今疑',
'群山万壑赴荆门',
'生长明妃尚有村',
'一去紫台连朔漠',
'独留青冢向黄昏',
'画图省识春风面',
'环佩空归月夜魂',
'千载琵琶作胡语',
'分明怨恨曲中论',
'蜀主窥吴幸三峡',
'崩年亦在永安宫',
'翠华想像空山里',
'玉殿虚无野寺中',
'古庙杉松巢水鹤',
'岁时伏腊走村翁',
'武侯祠屋常邻近',
'一体君臣祭祀同',
'诸葛大名垂宇宙',
'宗臣遗像肃清高',
'三分割据纡筹策',
'万古云霄一羽毛',
'伯仲之间见伊吕',
'指挥若定失萧曹',
'福移汉祚难恢复',
'志决身歼军务劳',
],
},
{
title: '诸将五首',
body: [
'汉朝陵墓对南山',
'胡虏千秋尚入关',
'昨日玉鱼蒙葬地',
'早时金碗出人间',
'见愁汗马西戎逼',
'曾闪朱旗北斗殷',
'多少材官守泾渭',
'将军且莫破愁颜',
'韩公本意筑三城',
'拟绝天骄拔汉旌',
'岂谓尽烦回纥马',
'翻然远救朔方兵',
'胡来不觉潼关隘',
'龙起犹闻晋水清',
'独使至尊忧社稷',
'诸君何以答升平',
'洛阳宫殿化为烽',
'休道秦关百二重',
'沧海未全归禹贡',
'蓟门何处尽尧封',
'朝廷衮职虽多预',
'天下军储不自供',
'稍喜临边王相国',
'肯销金甲事春农',
'回首扶桑铜柱标',
'冥冥氛祲未全销',
'越裳翡翠无消息',
'南海明珠久寂寥',
'殊锡曾为大司马',
'总戎皆插侍中貂',
'炎风朔雪天王地',
'只在忠臣翊圣朝',
'锦江春色逐人来',
'巫峡清秋万壑哀',
'正忆往时严仆射',
'共迎中使望乡台',
'主恩前后三持节',
'军令分明数举杯',
'西蜀地形天下险',
'安危须仗出群材',
],
},
{
title: '秋日夔府咏怀奉寄郑监李宾客一百韵',
body: [
'绝塞乌蛮北',
'孤城白帝边',
'飘零仍百里',
'消渴已三年',
'雄剑鸣开匣',
'群书满系船',
'乱离心不展',
'衰谢日萧然',
'筋力妻孥问',
'菁华岁月迁',
'登临多物色',
'陶冶赖诗篇',
'峡束沧江起',
'岩排石树圆',
'拂云霾楚气',
'朝海蹴吴天',
'煮井为盐速',
'烧畬度地偏',
'有时惊叠嶂',
'何处觅平川',
'鸂鶒双双舞',
'猕猿垒垒悬',
'碧萝长似带',
'锦石小如钱',
'春草何曾歇',
'寒花亦可怜',
'猎人吹戍火',
'野店引山泉',
'唤起搔头急',
'扶行几屐穿',
'两京犹薄产',
'四海绝随肩',
'幕府初交辟',
'郎官幸备员',
'瓜时犹旅寓',
'萍泛苦夤缘',
'药饵虚狼藉',
'秋风洒静便',
'开襟驱瘴疠',
'明目扫云烟',
'高宴诸侯礼',
'佳人上客前',
'哀筝伤老大',
'华屋艳神仙',
'南内开元曲',
'常时弟子传',
'法歌声变转',
'满座涕潺湲',
'吊影夔州僻',
'回肠杜曲煎',
'即今龙厩水',
'莫带犬戎膻',
'耿贾扶王室',
'萧曹拱御筵',
'乘威灭蜂虿',
'戮力效鹰鹯',
'旧物森犹在',
'凶徒恶未悛',
'国须行战伐',
'人忆止戈鋋',
'奴仆何知礼',
'恩荣错与权',
'胡星一彗孛',
'黔首遂拘挛',
'哀痛丝纶切',
'烦苛法令蠲',
'业成陈始王',
'兆喜出于畋',
'宫禁经纶密',
'台阶翊戴全',
'熊罴载吕望',
'鸿雁美周宣',
'侧听中兴主',
'长吟不世贤',
'音徽一柱数',
'道里下牢千',
'郑李光时论',
'文章并我先',
'阴何尚清省',
'沈宋欻联翩',
'律比昆仑竹',
'音知燥湿弦',
'风流俱善价',
'惬当久忘筌',
'置驿常如此',
'登龙盖有焉',
'虽云隔礼数',
'不敢坠周旋',
'高视收人表',
'虚心味道玄',
'马来皆汗血',
'鹤唳必青田',
'羽翼商山起',
'蓬莱汉阁连',
'管宁纱帽净',
'江令锦袍鲜',
'东郡时题壁',
'南湖日扣舷',
'远游凌绝境',
'佳句染华笺',
'每欲孤飞去',
'徒为百虑牵',
'生涯已寥落',
'国步乃迍邅',
'衾枕成芜没',
'池塘作弃捐',
'别离忧怛怛',
'伏腊涕涟涟',
'露菊班丰镐',
'秋蔬影涧瀍',
'共谁论昔事',
'几处有新阡',
'富贵空回首',
'喧争懒著鞭',
'兵戈尘漠漠',
'江汉月娟娟',
'局促看秋燕',
'萧疏听晚蝉',
'雕虫蒙记忆',
'烹鲤问沈绵',
'卜羡君平杖',
'偷存子敬毡',
'囊虚把钗钏',
'米尽坼花钿',
'甘子阴凉叶',
'茅斋八九椽',
'阵图沙北岸',
'市暨瀼西巅',
'羁绊心常折',
'栖迟病即痊',
'紫收岷岭芋',
'白种陆池莲',
'色好梨胜颊',
'穰多栗过拳',
'敕厨唯一味',
'求饱或三鳣',
'儿去看鱼笱',
'人来坐马鞯',
'缚柴门窄窄',
'通竹溜涓涓',
'堑抵公畦棱',
'村依野庙壖',
'缺篱将棘拒',
'倒石赖藤缠',
'借问频朝谒',
'何如稳醉眠',
'谁云行不逮',
'自觉坐能坚',
'雾雨银章涩',
'馨香粉署妍',
'紫鸾无近远',
'黄雀任翩翾',
'困学违从众',
'明公各勉旃',
'声华夹宸极',
'早晚到星躔',
'恳谏留匡鼎',
'诸儒引服虔',
'不逢输鲠直',
'会是正陶甄',
'宵旰忧虞轸',
'黎元疾苦骈',
'云台终日画',
'青简为谁编',
'行路难何有',
'招寻兴已专',
'由来具飞楫',
'暂拟控鸣弦',
'身许双峰寺',
'门求七祖禅',
'落帆追宿昔',
'衣褐向真诠',
'安石名高晋',
'昭王客赴燕',
'途中非阮籍',
'查上似张骞',
'披拂云宁在',
'淹留景不延',
'风期终破浪',
'水怪莫飞涎',
'他日辞神女',
'伤春怯杜鹃',
'淡交随聚散',
'泽国绕回旋',
'本自依迦叶',
'何曾藉偓佺',
'炉峰生转盼',
'橘井尚高褰',
'东走穷归鹤',
'南征尽跕鸢',
'晚闻多妙教',
'卒践塞前愆',
'顾凯丹青列',
'头陀琬琰镌',
'众香深黯黯',
'几地肃芊芊',
'勇猛为心极',
'清羸任体孱',
'金篦空刮眼',
'镜象未离铨',
],
},
{
title: '赠李八秘书别三十韵',
body: [
'往时中补右',
'扈跸上元初',
'反气凌行在',
'妖星下直庐',
'六龙瞻汉阙',
'万骑略姚墟',
'玄朔回天步',
'神都忆帝车',
'一戎才汗马',
'百姓免为鱼',
'通籍蟠螭印',
'差肩列凤舆',
'事殊迎代邸',
'喜异赏朱虚',
'寇盗方归顺',
'乾坤欲晏如',
'不才同补衮',
'奉诏许牵裾',
'鸳鹭叨云阁',
'麒麟滞玉除',
'文园多病后',
'中散旧交疏',
'飘泊哀相见',
'平生意有馀',
'风烟巫峡远',
'台榭楚宫虚',
'触目非论故',
'新文尚起予',
'清秋凋碧柳',
'别浦落红蕖',
'消息多旗帜',
'经过叹里闾',
'战连唇齿国',
'军急羽毛书',
'幕府筹频问',
'山家药正锄',
'台星入朝谒',
'使节有吹嘘',
'西蜀灾长弭',
'南翁愤始摅',
'对扬抏士卒',
'干没费仓储',
'势藉兵须用',
'功无礼忽诸',
'御鞍金騕褭',
'宫砚玉蟾蜍',
'拜舞银钩落',
'恩波锦帕舒',
'此行非不济',
'良友昔相于',
'去旆依颜色',
'沿流想疾徐',
'沈绵疲井臼',
'倚薄似樵渔',
'乞米烦佳客',
'钞诗听小胥',
'杜陵斜晚照',
'潏水带寒淤',
'莫话清溪发',
'萧萧白映梳',
],
},
{
title: '寄刘峡州伯华使君四十韵',
body: [
'峡内多云雨',
'秋来尚郁蒸',
'远山朝白帝',
'深水谒彝陵',
'迟暮嗟为客',
'西南喜得朋',
'哀猿更起坐',
'落雁失飞腾',
'伏枕思琼树',
'临轩对玉绳',
'青松寒不落',
'碧海阔逾澄',
'昔岁文为理',
'群公价尽增',
'家声同令闻',
'时论以儒称',
'太后当朝肃',
'多才接迹升',
'翠虚捎魍魉',
'丹极上鹍鹏',
'宴引春壶满',
'恩分夏簟冰',
'雕章五色笔',
'紫殿九华灯',
'学并卢王敏',
'书偕褚薛能',
'老兄真不坠',
'小子独无承',
'近有风流作',
'聊从月继征',
'放蹄知赤骥',
'捩翅服苍鹰',
'卷轴来何晚',
'襟怀庶可凭',
'会期吟讽数',
'益破旅愁凝',
'雕刻初谁料',
'纤毫欲自矜',
'神融蹑飞动',
'战胜洗侵凌',
'妙取筌蹄弃',
'高宜百万层',
'白头遗恨在',
'青竹几人登',
'回首追谈笑',
'劳歌跼寝兴',
'年华纷已矣',
'世故莽相仍',
'刺史诸侯贵',
'郎官列宿应',
'潘生骖阁远',
'黄霸玺书增',
'乳rP号攀石',
'饥鼯诉落藤',
'药囊亲道士',
'灰劫问胡僧',
'凭久乌皮折',
'簪稀白帽棱',
'林居看蚁穴',
'野食行鱼罾',
'筋力交凋丧',
'飘零免战兢',
'皆为百里宰',
'正似六安丞',
'姹女萦新裹',
'丹砂冷旧秤',
'但求椿寿永',
'莫虑杞天崩',
'炼骨调情性',
'张兵挠棘矜',
'养生终自惜',
'伐数必全惩',
'政术甘疏诞',
'词场愧服膺',
'展怀诗诵鲁',
'割爱酒如渑',
'咄咄宁书字',
'冥冥欲避矰',
'江湖多白鸟',
'天地有青蝇',
],
},
{
title: '夔府书怀四十韵',
body: [
'昔罢河西尉',
'初兴蓟北师',
'不才名位晚',
'敢恨省郎迟',
'扈圣崆峒日',
'端居滟滪时',
'萍流仍汲引',
'樗散尚恩慈',
'遂阻云台宿',
'常怀湛露诗',
'翠华森远矣',
'白首飒凄其',
'拙被林泉滞',
'生逢酒赋欺',
'文园终寂寞',
'汉阁自磷缁',
'病隔君臣议',
'惭纡德泽私',
'扬镳惊主辱',
'拔剑拨年衰',
'社稷经纶地',
'风云际会期',
'血流纷在眼',
'涕洒乱交颐',
'四渎楼船泛',
'中原鼓角悲',
'贼壕连白翟',
'战瓦落丹墀',
'先帝严灵寝',
'宗臣切受遗',
'恒山犹突骑',
'辽海竞张旗',
'田父嗟胶漆',
'行人避蒺藜',
'总戎存大体',
'降将饰卑词',
'楚贡何年绝',
'尧封旧俗疑',
'长吁翻北寇',
'一望卷西夷',
'不必陪玄圃',
'超然待具茨',
'凶兵铸农器',
'讲殿辟书帷',
'庙算高难测',
'天忧实在兹',
'形容真潦倒',
'答效莫支持',
'使者分王命',
'群公各典司',
'恐乖均赋敛',
'不似问疮痍',
'万里烦供给',
'孤城最怨思',
'绿林宁小患',
'云梦欲难追',
'即事须尝胆',
'苍生可察眉',
'议堂犹集凤',
'正观是元龟',
'处处喧飞檄',
'家家急竞锥',
'萧车安不定',
'蜀使下何之',
'钓濑疏坟籍',
'耕岩进弈棋',
'地蒸馀破扇',
'冬暖更纤絺',
'豺遘哀登楚',
'麟伤泣象尼',
'衣冠迷适越',
'藻绘忆游睢',
'赏月延秋桂',
'倾阳逐露葵',
'大庭终反朴',
'京观且僵尸',
'高枕虚眠昼',
'哀歌欲和谁',
'南宫载勋业',
'凡百慎交绥',
],
},
{
title: '解闷十二首',
body: [
'草阁柴扉星散居',
'浪翻江黑雨飞初',
'山禽引子哺红果',
'溪友得钱留白鱼',
'商胡离别下扬州',
'忆上西陵故驿楼',
'为问淮南米贵贱',
'老夫乘兴欲东流',
'一辞故国十经秋',
'每见秋瓜忆故丘',
'今日南湖采薇蕨',
'何人为觅郑瓜州',
'沈范早知何水部',
'曹刘不待薛郎中',
'独当省署开文苑',
'兼泛沧浪学钓翁',
'李陵苏武是吾师',
'孟子论文更不疑',
'一饭未曾留俗客',
'数篇今见古人诗',
'复忆襄阳孟浩然',
'清诗句句尽堪传',
'即今耆旧无新语',
'漫钓槎头缩颈鳊',
'陶冶性灵在底物',
'新诗改罢自长吟',
'孰知二谢将能事',
'颇学阴何苦用心',
'不见高人王右丞',
'蓝田丘壑漫寒藤',
'最传秀句寰区满',
'未绝风流相国能',
'先帝贵妃今寂寞',
'荔枝还复入长安',
'炎方每续朱樱献',
'玉座应悲白露团',
'忆过泸戎摘荔枝',
'青峰隐映石逶迤',
'京中旧见无颜色',
'红颗酸甜只自知',
'翠瓜碧李沈玉甃',
'赤梨葡萄寒露成',
'可怜先不异枝蔓',
'此物娟娟长远生',
'侧生野岸及江蒲',
'不熟丹宫满玉壶',
'云壑布衣骀背死',
'劳生重马翠眉须',
],
},
{
title: '复愁十二首',
body: [
'人烟生处僻',
'虎迹过新蹄',
'野鹘翻窥草',
'村船逆上溪',
'钓艇收缗尽',
'昏鸦接翅归',
'月生初学扇',
'云细不成衣',
'万国尚防寇',
'故园今若何',
'昔归相识少',
'早已战场多',
'身觉省郎在',
'家须农事归',
'年深荒草径',
'老恐失柴扉',
'金丝镂箭镞',
'皂尾制旗竿',
'一自风尘起',
'犹嗟行路难',
'胡虏何曾盛',
'干戈不肯休',
'闾阎听小子',
'谈话觅封侯',
'贞观铜牙弩',
'开元锦兽张',
'花门小前好',
'此物弃沙场',
'今日翔麟马',
'先宜驾鼓车',
'无劳问河北',
'诸将觉荣华',
'任转江淮粟',
'休添苑囿兵',
'由来貔虎士',
'不满凤凰城',
'江上亦秋色',
'火云终不移',
'巫山犹锦树',
'南国且黄鹂',
'每恨陶彭泽',
'无钱对菊花',
'如今九日至',
'自觉酒须赊',
'病减诗仍拙',
'吟多意有馀',
'莫看江总老',
'犹被赏时鱼',
],
},
{
title: '承闻河北诸道节度入朝欢喜口号绝句十二首',
body: [
'禄山作逆降天诛',
'更有思明亦已无',
'汹汹人寰犹不定',
'时时斗战欲何须',
'社稷苍生计必安',
'蛮夷杂种错相干',
'周宣汉武今王是',
'孝子忠臣后代看',
'喧喧道路多歌谣',
'河北将军尽入朝',
'始是乾坤王室正',
'却交江汉客魂销',
'不道诸公无表来',
'茫然庶事遣人猜',
'拥兵相学干戈锐',
'使者徒劳百万回',
'鸣玉锵金尽正臣',
'修文偃武不无人',
'兴王会静妖氛气',
'圣寿宜过一万春',
'英雄见事若通神',
'圣哲为心小一身',
'燕赵休矜出佳丽',
'宫闱不拟选才人',
'抱病江天白首郎',
'空山楼阁暮春光',
'衣冠是日朝天子',
'草奏何时入帝乡',
'澶漫山东一百州',
'削成如桉抱青丘',
'苞茅重入归关内',
'王祭还供尽海头',
'东逾辽水北滹沱',
'星象风云喜共和',
'紫气关临天地阔',
'黄金台贮俊贤多',
'渔阳突骑邯郸儿',
'酒酣并辔金鞭垂',
'意气即归双阙舞',
'雄豪复遣五陵知',
'李相将军拥蓟门',
'白头虽老赤心存',
'竟能尽说诸侯入',
'知有从来天子尊',
'十二年来多战场',
'天威已息阵堂堂',
'神灵汉代中兴主',
'功业汾阳异姓王',
],
},
{
title: '喜闻盗贼蕃寇总退口号五首',
body: [
'萧关陇水入官军',
'青海黄河卷塞云',
'北极转愁龙虎气',
'西戎休纵犬羊群',
'赞普多教使入秦',
'数通和好止烟尘',
'朝廷忽用哥舒将',
'杀伐虚悲公主亲',
'崆峒西极过昆仑',
'驼马由来拥国门',
'逆气数年吹路断',
'蕃人闻道渐星奔',
'勃律天西采玉河',
'坚昆碧碗最来多',
'旧随汉使千堆宝',
'少答胡王万匹罗',
'今春喜气满乾坤',
'南北东西拱至尊',
'大历二年调玉烛',
'玄元皇帝圣云孙',
],
},
{
title: '洞房',
body: [
'洞房环佩冷',
'玉殿起秋风',
'秦地应新月',
'龙池满旧宫',
'系舟今夜远',
'清漏往时同',
'万里黄山北',
'园陵白露中',
],
},
{
title: '宿昔',
body: [
'宿昔青门里',
'蓬莱仗数移',
'花娇迎杂树',
'龙喜出平池',
'落日留王母',
'微风倚少儿',
'宫中行乐秘',
'少有外人知',
],
},
{
title: '能画',
body: [
'能画毛延寿',
'投壶郭舍人',
'每蒙天一笑',
'复似物皆春',
'政化平如水',
'皇恩断若神',
'时时用抵戏',
'亦未杂风尘',
],
},
{
title: '斗鸡',
body: [
'斗鸡初赐锦',
'舞马既登床',
'帘下宫人出',
'楼前御柳长',
'仙游终一閟',
'女乐久无香',
'寂寞骊山道',
'清秋草木黄',
],
},
{
title: '鹦鹉(一作翦羽)',
body: [
'鹦鹉含愁思',
'聪明忆别离',
'翠衿浑短尽',
'红觜漫多知',
'未有开笼日',
'空残旧宿枝',
'世人怜复损',
'何用羽毛奇',
],
},
{
title: '历历',
body: [
'历历开元事',
'分明在眼前',
'无端盗贼起',
'忽已岁时迁',
'巫峡西江外',
'秦城北斗边',
'为郎从白首',
'卧病数秋天',
],
},
{
title: '洛阳',
body: [
'洛阳昔陷没',
'胡马犯潼关',
'天子初愁思',
'都人惨别颜',
'清笳去宫阙',
'翠盖出关山',
'故老仍流涕',
'龙髯幸再攀',
],
},
{
title: '骊山',
body: [
'骊山绝望幸',
'花萼罢登临',
'地下无朝烛',
'人间有赐金',
'鼎湖龙去远',
'银海雁飞深',
'万岁蓬莱日',
'长悬旧羽林',
],
},
{
title: '提封',
body: [
'提封汉天下',
'万国尚同心',
'借问悬车守',
'何如俭德临',
'时征俊乂入',
'草窃犬羊侵',
'愿戒兵犹火',
'恩加四海深',
],
},
{
title: '覆舟二首',
body: [
'巫峡盘涡晓',
'黔阳贡物秋',
'丹砂同陨石',
'翠羽共沉舟',
'羁使空斜影',
'龙居閟积流',
'篙工幸不溺',
'俄顷逐轻鸥',
'竹宫时望拜',
'桂馆或求仙',
'姹女临波日',
'神光照夜年',
'徒闻斩蛟剑',
'无复爨犀船',
'使者随秋色',
'迢迢独上天',
],
},
{
title: '垂白(一作白首)',
body: [
'垂白冯唐老',
'清秋宋玉悲',
'江喧长少睡',
'楼迥独移时',
'多难身何补',
'无家病不辞',
'甘从千日醉',
'未许七哀诗',
],
},
{
title: '草阁',
body: [
'草阁临无地',
'柴扉永不关',
'鱼龙回夜水',
'星月动秋山',
'久露清初湿',
'高云薄未还',
'泛舟惭小妇',
'飘泊损红颜',
],
},
{
title: '江月',
body: [
'江月光于水',
'高楼思杀人',
'天边长作客',
'老去一沾巾',
'玉露团清影',
'银河没半轮',
'谁家挑锦字',
'灭烛翠眉颦',
],
},
{
title: '江上',
body: [
'江上日多雨',
'萧萧荆楚秋',
'高风下木叶',
'永夜揽貂裘',
'勋业频看镜',
'行藏独倚楼',
'时危思报主',
'衰谢不能休',
],
},
{
title: '中夜',
body: [
'中夜江山静',
'危楼望北辰',
'长为万里客',
'有愧百年身',
'故国风云气',
'高堂战伐尘',
'胡雏负恩泽',
'嗟尔太平人',
],
},
{
title: '江汉',
body: [
'江汉思归客',
'乾坤一腐儒',
'片云天共远',
'永夜月同孤',
'落日心犹壮',
'秋风病欲疏',
'古来存老马',
'不必取长途',
],
},
{
title: '白露',
body: [
'白露团甘子',
'清晨散马蹄',
'圃开连石树',
'船渡入江溪',
'凭几看鱼乐',
'回鞭急鸟栖',
'渐知秋实美',
'幽径恐多蹊',
],
},
{
title: '孟氏(集有过孟十二仓曹十四主簿兄弟诗)',
body: [
'孟氏好兄弟',
'养亲唯小园',
'承颜胝手足',
'坐客强盘飧',
'负米力葵外',
'读书秋树根',
'卜邻惭近舍',
'训子学谁门',
],
},
{
title: '吾宗(卫仓曹崇简)',
body: [
'吾宗老孙子',
'质朴古人风',
'耕凿安时论',
'衣冠与世同',
'在家常早起',
'忧国愿年丰',
'语及君臣际',
'经书满腹中',
],
},
{
title: '有叹',
body: [
'壮心久零落',
'白首寄人间',
'天下兵常斗',
'江东客未还',
'穷猿号雨雪',
'老马怯关山',
'武德开元际',
'苍生岂重攀',
],
},
{
title: '冬深(一作即日)',
body: [
'花叶随天意',
'江溪共石根',
'早霞随类影',
'寒水各依痕',
'易下杨朱泪',
'难招楚客魂',
'风涛暮不稳',
'舍棹宿谁门',
],
},
{
title: '不寐',
body: [
'瞿塘夜水黑',
'城内改更筹',
'翳翳月沉雾',
'辉辉星近楼',
'气衰甘少寐',
'心弱恨和愁',
'多垒满山谷',
'桃源无处求',
],
},
{
title: '月圆',
body: [
'孤月当楼满',
'寒江动夜扉',
'委波金不定',
'照席绮逾依',
'未缺空山静',
'高悬列宿稀',
'故园松桂发',
'万里共清辉',
],
},
{
title: '中宵',
body: [
'西阁百寻馀',
'中宵步绮疏',
'飞星过水白',
'落月动沙虚',
'择木知幽鸟',
'潜波想巨鱼',
'亲朋满天地',
'兵甲少来书',
],
},
{
title: '遣愁',
body: [
'养拙蓬为户',
'茫茫何所开',
'江通神女馆',
'地隔望乡台',
'渐惜容颜老',
'无由弟妹来',
'兵戈与人事',
'回首一悲哀',
],
},
{
title: '秋清',
body: [
'高秋苏病气',
'白发自能梳',
'药饵憎加减',
'门庭闷扫除',
'杖藜还客拜',
'爱竹遣儿书',
'十月江平稳',
'轻舟进所如',
],
},
{
title: '伤秋',
body: [
'林僻来人少',
'山长去鸟微',
'高秋收画扇',
'久客掩荆扉',
'懒慢头时栉',
'艰难带减围',
'将军犹汗马',
'天子尚戎衣',
'白蒋风飙脆',
'殷柽晓夜稀',
'何年减豺虎',
'似有故园归',
],
},
{
title: '秋峡',
body: [
'江涛万古峡',
'肺气久衰翁',
'不寐防巴虎',
'全生狎楚童',
'衣裳垂素发',
'门巷落丹枫',
'常怪商山老',
'兼存翊赞功',
],
},
{
title: '南极',
body: [
'南极青山众',
'西江白谷分',
'古城疏落木',
'荒戍密寒云',
'岁月蛇常见',
'风飙虎或闻',
'近身皆鸟道',
'殊俗自人群',
'睥睨登哀柝',
'矛弧照夕曛',
'乱离多醉尉',
'愁杀李将军',
],
},
{
title: '摇落',
body: [
'摇落巫山暮',
'寒江东北流',
'烟尘多战鼓',
'风浪少行舟',
'鹅费羲之墨',
'貂馀季子裘',
'长怀报明主',
'卧病复高秋',
],
},
{
title: '耳聋',
body: [
'生年鹖冠子',
'叹世鹿皮翁',
'眼复几时暗',
'耳从前月聋',
'猿鸣秋泪缺',
'雀噪晚愁空',
'黄落惊山树',
'呼儿问朔风',
],
},
{
title: '独坐二首',
body: [
'竟日雨冥冥',
'双崖洗更青',
'水花寒落岸',
'山鸟暮过庭',
'暖老须燕玉',
'充饥忆楚萍',
'胡笳在楼上',
'哀怨不堪听',
'白狗斜临北',
'黄牛更在东',
'峡云常照夜',
'江月会兼风',
'晒药安垂老',
'应门试小童',
'亦知行不逮',
'苦恨耳多聋',
],
},
{
title: '远游',
body: [
'江阔浮高栋',
'云长出断山',
'尘沙连越巂',
'风雨暗荆蛮',
'雁矫衔芦内',
'猿啼失木间',
'弊裘苏季子',
'历国未知还',
],
},
{
title: '夜(一作秋夜客舍)',
body: [
'露下天高秋水清',
'空山独夜旅魂惊',
'疏灯自照孤帆宿',
'新月犹悬双杵鸣',
'南菊再逢人卧病',
'北书不至雁无情',
'步蟾倚杖看牛斗',
'银汉遥应接凤城',
],
},
{
title: '暮春',
body: [
'卧病拥塞在峡中',
'潇湘洞庭虚映空',
'楚天不断四时雨',
'巫峡常吹千里风',
'沙上草阁柳新暗',
'城边野池莲欲红',
'暮春鸳鹭立洲渚',
'挟子翻飞还一丛',
],
},
{
title: '晴二首',
body: [
'久雨巫山暗',
'新晴锦绣文',
'碧知湖外草',
'红见海东云',
'竟日莺相和',
'摩霄鹤数群',
'野花干更落',
'风处急纷纷',
'啼乌争引子',
'鸣鹤不归林',
'下食遭泥去',
'高飞恨久阴',
'雨声冲塞尽',
'日气射江深',
'回首周南客',
'驱驰魏阙心',
],
},
{
title: '雨',
body: [
'始贺天休雨',
'还嗟地出雷',
'骤看浮峡过',
'密作渡江来',
'牛马行无色',
'蛟龙斗不开',
'干戈盛阴气',
'未必自阳台',
],
},
{
title: '月三首',
body: [
'断续巫山雨',
'天河此夜新',
'若无青嶂月',
'愁杀白头人',
'魍魉移深树',
'虾蟆动半轮',
'故园当北斗',
'直指照西秦',
'并照巫山出',
'新窥楚水清',
'羁栖愁里见',
'二十四回明',
'必验升沉体',
'如知进退情',
'不违银汉落',
'亦伴玉绳横',
'万里瞿塘峡',
'春来六上弦',
'时时开暗室',
'故故满青天',
'爽合风襟静',
'高当泪脸悬',
'南飞有乌鹊',
'夜久落江边',
],
},
{
title: '雨',
body: [
'万木云深隐',
'连山雨未开',
'风扉掩不定',
'水鸟过仍回',
'鲛馆如鸣杼',
'樵舟岂伐枚',
'清凉破炎毒',
'衰意欲登台',
],
},
{
title: '晚晴',
body: [
'返照斜初彻',
'浮云薄未归',
'江虹明远饮',
'峡雨落馀飞',
'凫雁终高去',
'熊罴觉自肥',
'秋分客尚在',
'竹露夕微微',
],
},
{
title: '夜雨',
body: [
'小雨夜复密',
'回风吹早秋',
'野凉侵闭户',
'江满带维舟',
'通籍恨多病',
'为郎忝薄游',
'天寒出巫峡',
'醉别仲宣楼',
],
},
{
title: '更题',
body: [
'只应踏初雪',
'骑马发荆州',
'直怕巫山雨',
'真伤白帝秋',
'群公苍玉佩',
'天子翠云裘',
'同舍晨趋侍',
'胡为淹此留',
],
},
{
title: '归',
body: [
'束带还骑马',
'东西却渡船',
'林中才有地',
'峡外绝无天',
'虚白高人静',
'喧卑俗累牵',
'他乡悦迟暮',
'不敢废诗篇',
],
},
{
title: '返照',
body: [
'楚王宫北正黄昏',
'白帝城西过雨痕',
'返照入江翻石壁',
'归云拥树失山村',
'衰年肺病唯高枕',
'绝塞愁时早闭门',
'不可久留豺虎乱',
'南方实有未招魂',
],
},
{
title: '热三首',
body: [
'雷霆空霹雳',
'云雨竟虚无',
'炎赫衣流汗',
'低垂气不苏',
'乞为寒水玉',
'愿作冷秋菰',
'何似儿童岁',
'风凉出舞雩',
'瘴云终不灭',
'泸水复西来',
'闭户人高卧',
'归林鸟却回',
'峡中都似火',
'江上只空雷',
'想见阴宫雪',
'风门飒踏开',
'朱李沈不冷',
'雕胡炊屡新',
'将衰骨尽痛',
'被褐味空频',
'欻翕炎蒸景',
'飘摇征戍人',
'十年可解甲',
'为尔一沾巾',
],
},
{
title: '日暮',
body: [
'牛羊下来久',
'各已闭柴门',
'风月自清夜',
'江山非故园',
'石泉流暗壁',
'草露滴秋根',
'头白灯明里',
'何须花烬繁',
],
},
{
title: '八月十五夜月二首',
body: [
'满目飞明镜',
'归心折大刀',
'转蓬行地远',
'攀桂仰天高',
'水路疑霜雪',
'林栖见羽毛',
'此时瞻白兔',
'直欲数秋毫',
'稍下巫山峡',
'犹衔白帝城',
'气沈全浦暗',
'轮仄半楼明',
'刁斗皆催晓',
'蟾蜍且自倾',
'张弓倚残魄',
'不独汉家营',
],
},
{
title: '十六夜玩月',
body: [
'旧挹金波爽',
'皆传玉露秋',
'关山随地阔',
'河汉近人流',
'谷口樵归唱',
'孤城笛起愁',
'巴童浑不寝',
'半夜有行舟',
],
},
{
title: '十七夜对月',
body: [
'秋月仍圆夜',
'江村独老身',
'卷帘还照客',
'倚杖更随人',
'光射潜虬动',
'明翻宿鸟频',
'茅斋依橘柚',
'清切露华新',
],
},
{
title: '村雨',
body: [
'雨声传两夜',
'寒事飒高秋',
'挈带看朱绂',
'开箱睹黑裘',
'世情只益睡',
'盗贼敢忘忧',
'松菊新沾洗',
'茅斋慰远游',
],
},
{
title: '雨晴',
body: [
'雨时山不改',
'晴罢峡如新',
'天路看殊俗',
'秋江思杀人',
'有猿挥泪尽',
'无犬附书频',
'故国愁眉外',
'长歌欲损神',
],
},
{
title: '晚晴吴郎见过北舍',
body: [
'圃畦新雨润',
'愧子废锄来',
'竹杖交头拄',
'柴扉隔径开',
'欲栖群鸟乱',
'未去小童催',
'明日重阳酒',
'相迎自酦醅',
],
},
{
title: '暝',
body: [
'日下四山阴',
'山庭岚气侵',
'牛羊归径险',
'鸟雀聚枝深',
'正枕当星剑',
'收书动玉琴',
'半扉开烛影',
'欲掩见清砧',
],
},
{
title: '云',
body: [
'龙似瞿唐会',
'江依白帝深',
'终年常起峡',
'每夜必通林',
'收获辞霜渚',
'分明在夕岑',
'高斋非一处',
'秀气豁烦襟',
],
},
{
title: '月',
body: [
'四更山吐月',
'残夜水明楼',
'尘匣元开镜',
'风帘自上钩',
'兔应疑鹤发',
'蟾亦恋貂裘',
'斟酌姮娥寡',
'天寒耐九秋',
],
},
{
title: '雨四首',
body: [
'微雨不滑道',
'断云疏复行',
'紫崖奔处黑',
'白鸟去边明',
'秋日新沾影',
'寒江旧落声',
'柴扉临野碓',
'半得捣香粳',
'江雨旧无时',
'天晴忽散丝',
'暮秋沾物冷',
'今日过云迟',
'上马迥休出',
'看鸥坐不辞',
'高轩当滟滪',
'润色静书帷',
'物色岁将晏',
'天隅人未归',
'朔风鸣淅淅',
'寒雨下霏霏',
'多病久加饭',
'衰容新授衣',
'时危觉凋丧',
'故旧短书稀',
'楚雨石苔滋',
'京华消息迟',
'山寒青兕叫',
'江晚白鸥饥',
'神女花钿落',
'鲛人织杼悲',
'繁忧不自整',
'终日洒如丝',
],
},
{
title: '夜',
body: [
'绝岸风威动',
'寒房烛影微',
'岭猿霜外宿',
'江鸟夜深飞',
'独坐亲雄剑',
'哀歌叹短衣',
'烟尘绕阊阖',
'白首壮心违',
],
},
{
title: '晨雨',
body: [
'小雨晨光内',
'初来叶上闻',
'雾交才洒地',
'风逆旋随云',
'暂起柴荆色',
'轻沾鸟兽群',
'麝香山一半',
'亭午未全分',
],
},
{
title: '返照',
body: [
'返照开巫峡',
'寒空半有无',
'已低鱼复暗',
'不尽白盐孤',
'荻岸如秋水',
'松门似画图',
'牛羊识僮仆',
'既夕应传呼',
],
},
{
title: '向夕',
body: [
'畎亩孤城外',
'江村乱水中',
'深山催短景',
'乔木易高风',
'鹤下云汀近',
'鸡栖草屋同',
'琴书散明烛',
'长夜始堪终',
],
},
{
title: '晓望',
body: [
'白帝更声尽',
'阳台曙色分',
'高峰寒上日',
'叠岭宿霾云',
'地坼江帆隐',
'天清木叶闻',
'荆扉对麋鹿',
'应共尔为群',
],
},
{
title: '雷',
body: [
'巫峡中宵动',
'沧江十月雷',
'龙蛇不成蛰',
'天地划争回',
'却碾空山过',
'深蟠绝壁来',
'何须妒云雨',
'霹雳楚王台',
],
},
{
title: '雨',
body: [
'冥冥甲子雨',
'已度立春时',
'轻箑烦相向',
'纤絺恐自疑',
'烟添才有色',
'风引更如丝',
'直觉巫山暮',
'兼催宋玉悲',
],
},
{
title: '朝二首',
body: [
'清旭楚宫南',
'霜空万岭含',
'野人时独往',
'云木晓相参',
'俊鹘无声过',
'饥乌下食贪',
'病身终不动',
'摇落任江潭',
'浦帆晨初发',
'郊扉冷未开',
'村疏黄叶坠',
'野静白鸥来',
'础润休全湿',
'云晴欲半回',
'巫山冬可怪',
'昨夜有奔雷',
],
},
{
title: '晚',
body: [
'杖藜寻晚巷',
'炙背近墙暄',
'人见幽居僻',
'吾知拙养尊',
'朝廷问府主',
'耕稼学山村',
'归翼飞栖定',
'寒灯亦闭门',
],
},
{
title: '夜二首',
body: [
'白夜月休弦',
'灯花半委眠',
'号山无定鹿',
'落树有惊蝉',
'暂忆江东鲙',
'兼怀雪下船',
'蛮歌犯星起',
'空觉在天边',
'城郭悲笳暮',
'村墟过翼稀',
'甲兵年数久',
'赋敛夜深归',
'暗树依岩落',
'明河绕塞微',
'斗斜人更望',
'月细鹊休飞',
],
},
{
title: '宗武生日',
body: [
'小子何时见',
'高秋此日生',
'自从都邑语',
'已伴老夫名',
'诗是吾家事',
'人传世上情',
'熟精文选理',
'休觅彩衣轻',
'凋瘵筵初秩',
'欹斜坐不成',
'流霞分片片',
'涓滴就徐倾',
],
},
{
title: '又示宗武',
body: [
'觅句新知律',
'摊书解满床',
'试吟青玉案',
'莫羡紫罗囊',
'假日从时饮',
'明年共我长',
'应须饱经术',
'已似爱文章',
'十五男儿志',
'三千弟子行',
'曾参与游夏',
'达者得升堂',
],
},
{
title: '熟食日示宗文、宗武',
body: [
'消渴游江汉',
'羁栖尚甲兵',
'几年逢熟食',
'万里逼清明',
'松柏邛山路',
'风花白帝城',
'汝曹催我老',
'回首泪纵横',
],
},
{
title: '又示两儿',
body: [
'令节成吾老',
'他时见汝心',
'浮生看物变',
'为恨与年深',
'长葛书难得',
'江州涕不禁',
'团圆思弟妹',
'行坐白头吟',
],
},
{
title: '社日两篇',
body: [
'九农成德业',
'百祀发光辉',
'报效神如在',
'馨香旧不违',
'南翁巴曲醉',
'北雁塞声微',
'尚想东方朔',
'诙谐割肉归',
'陈平亦分肉',
'太史竟论功',
'今日江南老',
'他时渭北童',
'欢娱看绝塞',
'涕泪落秋风',
'鸳鹭回金阙',
'谁怜病峡中',
],
},
{
title: '九日五首',
body: [
'重阳独酌杯中酒',
'抱病起登江上台',
'竹叶于人既无分',
'菊花从此不须开',
'殊方日落玄猿哭',
'旧国霜前白雁来',
'弟妹萧条各何往',
'干戈衰谢两相催',
'旧日重阳日',
'传杯不放杯',
'即今蓬鬓改',
'但愧菊花开',
'北阙心长恋',
'西江首独回',
'茱萸赐朝士',
'难得一枝来',
'旧与苏司业',
'兼随郑广文',
'采花香泛泛',
'坐客醉纷纷',
'野树歌还倚',
'秋砧醒却闻',
'欢娱两冥漠',
'西北有孤云',
'故里樊川菊',
'登高素浐源',
'他时一笑后',
'今日几人存',
'巫峡蟠江路',
'终南对国门',
'系舟身万里',
'伏枕泪双痕',
'为客裁乌帽',
'从儿具绿尊',
'佳辰对群盗',
'愁绝更谁论',
],
},
{
title: '九日诸人集于林',
body: [
'九日明朝是',
'相要旧俗非',
'老翁难早出',
'贤客幸知归',
'旧采黄花剩',
'新梳白发微',
'漫看年少乐',
'忍泪已沾衣',
],
},
{
title: '大历二年九月三十日',
body: [
'为客无时了',
'悲秋向夕终',
'瘴馀夔子国',
'霜薄楚王宫',
'草敌虚岚翠',
'花禁冷叶红',
'年年小摇落',
'不与故园同',
],
},
{
title: '十月一日',
body: [
'有瘴非全歇',
'为冬亦不难',
'夜郎溪日暖',
'白帝峡风寒',
'蒸裹如千室',
'焦糟幸一柈',
'兹辰南国重',
'旧俗自相欢',
],
},
{
title: '孟冬',
body: [
'殊俗还多事',
'方冬变所为',
'破甘霜落爪',
'尝稻雪翻匙',
'巫峡寒都薄',
'乌蛮瘴远随',
'终然减滩濑',
'暂喜息蛟螭',
],
},
{
title: '冬至',
body: [
'年年至日长为客',
'忽忽穷愁泥杀人',
'江上形容吾独老',
'天边风俗自相亲',
'杖藜雪后临丹壑',
'鸣玉朝来散紫宸',
'心折此时无一寸',
'路迷何处见三秦',
],
},
{
title: '小至',
body: [
'天时人事日相催',
'冬至阳生春又来',
'刺绣五纹添弱线',
'吹葭六琯动浮灰',
'岸容待腊将舒柳',
'山意冲寒欲放梅',
'云物不殊乡国异',
'教儿且覆掌中杯',
],
},
{
title: '览物(一作峡中览物)',
body: [
'曾为掾吏趋三辅',
'忆在潼关诗兴多',
'巫峡忽如瞻华岳',
'蜀江犹似见黄河',
'舟中得病移衾枕',
'洞口经春长薜萝',
'形胜有馀风土恶',
'几时回首一高歌',
],
},
{
title: '忆郑南玭',
body: [
'郑南伏毒寺',
'潇洒到江心',
'石影衔珠阁',
'泉声带玉琴',
'风杉曾曙倚',
'云峤忆春临',
'万里沧浪外',
'龙蛇只自深',
],
},
{
title: '怀灞上游',
body: [
'怅望东陵道',
'平生灞上游',
'春浓停野骑',
'夜宿敞云楼',
'离别人谁在',
'经过老自休',
'眼前今古意',
'江汉一归舟',
],
},
{
title: '愁(强戏为吴体)',
body: [
'江草日日唤愁生',
'巫峡泠泠非世情',
'盘涡鹭浴底心性',
'独树花发自分明',
'十年戎马暗万国',
'异域宾客老孤城',
'渭水秦山得见否',
'人经罢病虎纵横',
],
},
{
title: '昼梦',
body: [
'二月饶睡昏昏然',
'不独夜短昼分眠',
'桃花气暖眼自醉',
'春渚日落梦相牵',
'故乡门巷荆棘底',
'中原君臣豺虎边',
'安得务农息战斗',
'普天无吏横索钱',
],
},
{
title: '览镜呈柏中丞',
body: [
'渭水流关内',
'终南在日边',
'胆销豺虎窟',
'泪入犬羊天',
'起晚堪从事',
'行迟更学仙',
'镜中衰谢色',
'万一故人怜',
],
},
{
title: '即事',
body: [
'暮春三月巫峡长',
'皛皛行云浮日光',
'雷声忽送千峰雨',
'花气浑如百和香',
'黄莺过水翻回去',
'燕子衔泥湿不妨',
'飞阁卷帘图画里',
'虚无只少对潇湘',
],
},
{
title: '即事(一作天畔)',
body: [
'天畔群山孤草亭',
'江中风浪雨冥冥',
'一双白鱼不受钓',
'三寸黄甘犹自青',
'多病马卿无日起',
'穷途阮籍几时醒',
'未闻细柳散金甲',
'肠断秦川流浊泾',
],
},
{
title: '闷',
body: [
'瘴疠浮三蜀',
'风云暗百蛮',
'卷帘唯白水',
'隐几亦青山',
'猿捷长难见',
'鸥轻故不还',
'无钱从滞客',
'有镜巧催颜',
],
},
{
title: '戏作俳谐体遣闷二首',
body: [
'异俗吁可怪',
'斯人难并居',
'家家养乌鬼',
'顿顿食黄鱼',
'旧识能为态',
'新知已暗疏',
'治生且耕凿',
'只有不关渠',
'西历青羌板',
'南留白帝城',
'於菟侵客恨',
'粔籹作人情',
'瓦卜传神语',
'畬田费火声',
'是非何处定',
'高枕笑浮生',
],
},
{
title: '得舍弟观书自中都已达江陵,今兹暮春月末…情见乎词',
body: [
'尔到江陵府',
'何时到峡州',
'乱难生有别',
'聚集病应瘳',
'飒飒开啼眼',
'朝朝上水楼',
'老身须付托',
'白骨更何忧',
],
},
{
title: '喜观即到,复题短篇二首',
body: [
'巫峡千山暗',
'终南万里春',
'病中吾见弟',
'书到汝为人',
'意答儿童问',
'来经战伐新',
'泊船悲喜后',
'款款话归秦',
'待尔嗔乌鹊',
'抛书示鶺鴒',
'枝间喜不去',
'原上急曾经',
'江阁嫌津柳',
'风帆数驿亭',
'应论十年事',
'愁绝始星星',
],
},
{
title: '舍弟观归蓝田迎新妇,送示两篇',
body: [
'汝去迎妻子',
'高秋念却回',
'即今萤已乱',
'好与雁同来',
'东望西江水',
'南游北户开',
'卜居期静处',
'会有故人杯',
'楚塞难为路',
'蓝田莫滞留',
'衣裳判白露',
'鞍马信清秋',
'满峡重江水',
'开帆八月舟',
'此时同一醉',
'应在仲宣楼',
],
},
{
title: '第五弟丰独在江左,近三四载寂无消息,觅使寄此二首',
body: [
'乱后嗟吾在',
'羁栖见汝难',
'草黄骐骥病',
'沙晚鶺鴒寒',
'楚设关城险',
'吴吞水府宽',
'十年朝夕泪',
'衣袖不曾干',
'闻汝依山寺',
'杭州定越州',
'风尘淹别日',
'江汉失清秋',
'影盖啼猿树',
'魂飘结蜃楼',
'明年下春水',
'东尽白云求',
],
},
{
title: '舍弟观赴蓝田取妻子到江陵,喜寄三首',
body: [
'汝迎妻子达荆州',
'消息真传解我忧',
'鸿雁影来连峡内',
'鶺鴒飞急到沙头',
'峣关险路今虚远',
'禹凿寒江正稳流',
'朱绂即当随彩鹢',
'青春不假报黄牛',
'马度秦关雪正深',
'北来肌骨苦寒侵',
'他乡就我生春色',
'故国移居见客心',
'剩欲提携如意舞',
'喜多行坐白头吟',
'巡檐索共梅花笑',
'冷蕊疏枝半不禁',
'庾信罗含俱有宅',
'春来秋去作谁家',
'短墙若在从残草',
'乔木如存可假花',
'卜筑应同蒋诩径',
'为园须似邵平瓜',
'比年病酒开涓滴',
'弟劝兄酬何怨嗟',
],
},
{
title: '江雨有怀郑典设',
body: [
'春雨暗暗塞峡中',
'早晚来自楚王宫',
'乱波分披已打岸',
'弱云狼藉不禁风',
'宠光蕙叶与多碧',
'点注桃花舒小红',
'谷口子真正忆汝',
'岸高瀼滑限西东',
],
},
{
title: '王十五前阁会',
body: [
'楚岸收新雨',
'春台引细风',
'情人来石上',
'鲜脍出江中',
'邻舍烦书札',
'肩舆强老翁',
'病身虚俊味',
'何幸饫儿童',
],
},
{
title: '寄韦有夏郎中',
body: [
'省郎忧病士',
'书信有柴胡',
'饮子频通汗',
'怀君想报珠',
'亲知天畔少',
'药味峡中无',
'归楫生衣卧',
'春鸥洗翅呼',
'犹闻上急水',
'早作取平途',
'万里皇华使',
'为僚记腐儒',
],
},
{
title: '陪柏中丞观宴将士二首',
body: [
'极乐三军士',
'谁知百战场',
'无私齐绮馔',
'久坐密金章',
'醉客沾鹦鹉',
'佳人指凤凰',
'几时来翠节',
'特地引红妆',
'绣段装檐额',
'金花帖鼓腰',
'一夫先舞剑',
'百戏后歌樵',
'江树城孤远',
'云台使寂寥',
'汉朝频选将',
'应拜霍嫖姚',
],
},
{
title: '七月一日题终明府水楼二首',
body: [
'高栋曾轩已自凉',
'秋风此日洒衣裳',
'翛然欲下阴山雪',
'不去非无汉署香',
'绝辟过云开锦绣',
'疏松夹水奏笙簧',
'看君宜著王乔履',
'真赐还疑出尚方',
'宓子弹琴邑宰日',
'终军弃繻英妙时',
'承家节操尚不泯',
'为政风流今在兹',
'可怜宾客尽倾盖',
'何处老翁来赋诗',
'楚江巫峡半云雨',
'清簟疏帘看弈棋',
],
},
{
title: '季秋苏五弟缨江楼夜宴崔十三评事、韦少府侄三首',
body: [
'峡险江惊急',
'楼高月迥明',
'一时今夕会',
'万里故乡情',
'星落黄姑渚',
'秋辞白帝城',
'老人因酒病',
'坚坐看君倾',
'明月生长好',
'浮云薄渐遮',
'悠悠照边塞',
'悄悄忆京华',
'清动杯中物',
'高随海上查',
'不眠瞻白兔',
'百过落乌纱',
'对月那无酒',
'登楼况有江',
'听歌惊白鬓',
'笑舞拓秋窗',
'尊蚁添相续',
'沙鸥并一双',
'尽怜君醉倒',
'更觉片心降',
],
},
{
title: '九月一日过孟十二仓曹、十四主簿兄弟',
body: [
'藜杖侵寒露',
'蓬门启曙烟',
'力稀经树歇',
'老困拨书眠',
'秋觉追随尽',
'来因孝友偏',
'清谈见滋味',
'尔辈可忘年',
],
},
{
title: '过客相寻',
body: [
'穷老真无事',
'江山已定居',
'地幽忘盥栉',
'客至罢琴书',
'挂壁移筐果',
'呼儿问煮鱼',
'时闻系舟楫',
'及此问吾庐',
],
},
{
title: '孟仓曹步趾领新酒酱二物满器见遗老夫',
body: [
'楚岸通秋屐',
'胡床面夕畦',
'藉糟分汁滓',
'瓮酱落提携',
'饭粝添香味',
'朋来有醉泥',
'理生那免俗',
'方法报山妻',
],
},
{
title: '柳司马至',
body: [
'有使归三峡',
'相过问两京',
'函关犹出将',
'渭水更屯兵',
'设备邯郸道',
'和亲逻些城',
'幽燕唯鸟去',
'商洛少人行',
'衰谢身何补',
'萧条病转婴',
'霜天到宫阙',
'恋主寸心明',
],
},
{
title: '简吴郎司法',
body: [
'有客乘舸自忠州',
'遣骑安置瀼西头',
'古堂本买藉疏豁',
'借汝迁居停宴游',
'云石荧荧高叶曙',
'风江飒飒乱帆秋',
'却为姻娅过逢地',
'许坐曾轩数散愁',
],
},
{
title: '又呈吴郎',
body: [
'堂前扑枣任西邻',
'无食无儿一妇人',
'不为困穷宁有此',
'只缘恐惧转须亲',
'即防远客虽多事',
'使插疏篱却甚真',
'已诉征求贫到骨',
'正思戎马泪盈巾',
],
},
{
title: '覃山人隐居',
body: [
'南极老人自有星',
'北山移文谁勒铭',
'征君已去独松菊',
'哀壑无光留户庭',
'予见乱离不得已',
'子知出处必须经',
'高车驷马带倾覆',
'怅望秋天虚翠屏',
],
},
{
title: '柏学士茅屋',
body: [
'碧山学士焚银鱼',
'白马却走身岩居',
'古人已用三冬足',
'年少今开万卷馀',
'晴云满户团倾盖',
'秋水浮阶溜决渠',
'富贵必从勤苦得',
'男儿须读五车书',
],
},
{
title: '题柏大兄弟山居屋壁二首',
body: [
'叔父朱门贵',
'郎君玉树高',
'山居精典籍',
'文雅涉风骚',
'江汉终吾老',
'云林得尔曹',
'哀弦绕白雪',
'未与俗人操',
'野屋流寒水',
'山篱带薄云',
'静应连虎穴',
'喧已去人群',
'笔架沾窗雨',
'书签映隙曛',
'萧萧千里足',
'个个五花文',
],
},
{
title: '戏寄崔评事表侄、苏五表弟、韦大少府诸侄',
body: [
'隐豹深愁雨',
'潜龙故起云',
'泥多仍径曲',
'心醉阻贤群',
'忍待江山丽',
'还披鲍谢文',
'高楼忆疏豁',
'秋兴坐氛氲',
],
},
{
title: '秋日寄题郑监湖上亭三首',
body: [
'碧草逢春意',
'沅湘万里秋',
'池要山简马',
'月净庾公楼',
'磨灭馀篇翰',
'平生一钓舟',
'高唐寒浪减',
'仿佛识昭丘',
'新作湖边宅',
'远闻宾客过',
'自须开竹径',
'谁道避云萝',
'官序潘生拙',
'才名贾傅多',
'舍舟应转地',
'邻接意如何',
'暂阻蓬莱阁',
'终为江海人',
'挥金应物理',
'拖玉岂吾身',
'羹煮秋莼滑',
'杯迎露菊新',
'赋诗分气象',
'佳句莫频频',
],
},
{
title: '谒真谛寺禅师',
body: [
'兰若山高处',
'烟霞嶂几重',
'冻泉依细石',
'晴雪落长松',
'问法看诗忘',
'观身向酒慵',
'未能割妻子',
'卜宅近前峰',
],
},
{
title: '别崔潩因寄薛据、孟云卿(内弟潩赴湖南幕职)',
body: [
'志士惜妄动',
'知深难固辞',
'如何久磨砺',
'但取不磷缁',
'夙夜听忧主',
'飞腾急济时',
'荆州过薛孟',
'为报欲论诗',
],
},
{
title: '送李八秘书赴杜相公幕',
body: [
'青帘白舫益州来',
'巫峡秋涛天地回',
'石出倒听枫叶下',
'橹摇背指菊花开',
'贪趋相府今晨发',
'恐失佳期后命催',
'南极一星朝北斗',
'五云多处是三台',
],
},
{
title: '巫峡敝庐奉赠侍御四舅别之澧朗',
body: [
'江城秋日落',
'山鬼闭门中',
'行李淹吾舅',
'诛茅问老翁',
'赤眉犹世乱',
'青眼只途穷',
'传语桃源客',
'人今出处同',
],
},
{
title: '奉送十七舅下邵桂',
body: [
'绝域三冬暮',
'浮生一病身',
'感深辞舅氏',
'别后见何人',
'缥缈苍梧帝',
'推迁孟母邻',
'昏昏阻云水',
'侧望苦伤神',
],
},
{
title: '送覃二判官',
body: [
'先帝弓剑远',
'小臣馀此生',
'蹉跎病江汉',
'不复谒承明',
'饯尔白头日',
'永怀丹凤城',
'迟迟恋屈宋',
'渺渺卧荆衡',
'魂断航舸失',
'天寒沙水清',
'肺肝若稍愈',
'亦上赤霄行',
],
},
{
title: '季夏送乡弟韶陪黄门从叔朝谒',
body: [
'令弟尚为苍水使',
'名家莫出杜陵人',
'比来相国兼安蜀',
'归赴朝廷已入秦',
'舍舟策马论兵地',
'拖玉腰金报主身',
'莫度清秋吟蟋蟀',
'早闻黄阁画麒麟',
],
},
{
title: '送十五弟侍御使蜀',
body: [
'喜弟文章进',
'添余别兴牵',
'数杯巫峡酒',
'百丈内江船',
'未息豺狼斗',
'空催犬马年',
'归朝多便道',
'搏击望秋天',
],
},
{
title: '送田四弟将军将夔州柏中丞命起居江陵节度…郡王卫公幕',
body: [
'离筵罢多酒',
'起地发寒塘',
'回首中丞座',
'驰笺异姓王',
'燕辞枫树日',
'雁度麦城霜',
'空醉山翁酒',
'遥怜似葛强',
],
},
{
title: '送王十六判官',
body: [
'客下荆南尽',
'君今复入舟',
'买薪犹白帝',
'鸣橹少沙头',
'衡霍生春早',
'潇湘共海浮',
'荒林庾信宅',
'为仗主人留',
],
},
{
title: '奉送卿二翁统节度镇军还江陵',
body: [
'火旗还锦缆',
'白马出江城',
'嘹唳吟笳发',
'萧条别浦清',
'寒空巫峡曙',
'落日渭阳明',
'留滞嗟衰疾',
'何时见息兵',
],
},
{
title: '送鲜于万州迁巴州(鲜于炅乃仲通子,有父风)',
body: [
'京兆先时杰',
'琳琅照一门',
'朝廷偏注意',
'接近与名藩',
'祖帐排舟数',
'寒江触石喧',
'看君妙为政',
'他日有殊恩',
],
},
{
title: '寄杜位(顷者与位同在故严尚书幕)',
body: [
'寒日经檐短',
'穷猿失木悲',
'峡中为客恨',
'江上忆君时',
'天地身何在',
'风尘病敢辞',
'封书两行泪',
'沾洒裛新诗',
],
},
{
title: '奉寄李十五秘书二首',
body: [
'避暑云安县',
'秋风早下来',
'暂留鱼复浦',
'同过楚王台',
'猿鸟千崖窄',
'江湖万里开',
'竹枝歌未好',
'画舸莫迟回',
'行李千金赠',
'衣冠八尺身',
'飞腾知有策',
'意度不无神',
'班秩兼通贵',
'公侯出异人',
'玄成负文彩',
'世业岂沉沦',
],
},
{
title: '奉送韦中丞之晋赴湖南',
body: [
'宠渥征黄渐',
'权宜借寇频',
'湖南安背水',
'峡内忆行春',
'王室仍多故',
'苍生倚大臣',
'还将徐孺子',
'处处待高人',
],
},
{
title: '送李功曹之荆州充郑侍御判官重赠',
body: [
'曾闻宋玉宅',
'每欲到荆州',
'此地生涯晚',
'遥悲水国秋',
'孤城一柱观',
'落日九江流',
'使者虽光彩',
'青枫远自愁',
],
},
{
title: '送孟十二仓曹赴东京选',
body: [
'君行别老亲',
'此去苦家贫',
'藻镜留连客',
'江山憔悴人',
'秋风楚竹冷',
'夜雪巩梅春',
'朝夕高堂念',
'应宜彩服新',
],
},
{
title: '凭孟仓曹将书觅土娄旧庄',
body: [
'平居丧乱后',
'不到洛阳岑',
'为历云山问',
'无辞荆棘深',
'北风黄叶下',
'南浦白头吟',
'十载江湖客',
'茫茫迟暮心',
],
},
{
title: '别苏徯(赴湖南幕)',
body: [
'故人有游子',
'弃掷傍天隅',
'他日怜才命',
'居然屈壮图',
'十年犹塌翼',
'绝倒为惊吁',
'消渴今如在',
'提携愧老夫',
'岂知台阁旧',
'先拂凤凰雏',
'得实翻苍竹',
'栖枝把翠梧',
'北辰当宇宙',
'南岳据江湖',
'国带风尘色',
'兵张虎豹符',
'数论封内事',
'挥发府中趋',
'赠尔秦人策',
'莫鞭辕下驹',
],
},
{
title: '存殁口号二首',
body: [
'席谦不见近弹棋',
'毕曜仍传旧小诗',
'玉局他年无限笑',
'白杨今日几人悲',
'郑公粉绘随长夜',
'曹霸丹青已白头',
'天下何曾有山水',
'人间不解重骅骝',
],
},
{
title: '奉汉中王手札报韦侍御、萧尊师亡',
body: [
'秋日萧韦逝',
'淮王报峡中',
'少年疑柱史',
'多术怪仙公',
'不但时人惜',
'只应吾道穷',
'一哀侵疾病',
'相识自儿童',
'处处邻家笛',
'飘飘客子蓬',
'强吟怀旧赋',
'已作白头翁',
],
},
{
title: '哭王彭州抡',
body: [
'执友惊沦没',
'斯人已寂寥',
'新文生沈谢',
'异骨降松乔',
'北部初高选',
'东堂早见招',
'蛟龙缠倚剑',
'鸾凤夹吹箫',
'历职汉庭久',
'中年胡马骄',
'兵戈闇两观',
'宠辱事三朝',
'蜀路江干窄',
'彭门地里遥',
'解龟生碧草',
'谏猎阻清霄',
'顷壮戎麾出',
'叨陪幕府要',
'将军临气候',
'猛士塞风飙',
'井漏泉谁汲',
'烽疏火不烧',
'前筹自多暇',
'隐几接终朝',
'翠石俄双表',
'寒松竟后凋',
'赠诗焉敢坠',
'染翰欲无聊',
'再哭经过罢',
'离魂去住销',
'之官方玉折',
'寄葬与萍漂',
'旷望渥洼道',
'霏微河汉桥',
'夫人先即世',
'令子各清标',
'巫峡长云雨',
'秦城近斗杓',
'冯唐毛发白',
'归兴日萧萧',
],
},
{
title: '见萤火',
body: [
'巫山秋夜萤火飞',
'帘疏巧入坐人衣',
'忽惊屋里琴书冷',
'复乱檐边星宿稀',
'却绕井阑添个个',
'偶经花蕊弄辉辉',
'沧江白发愁看汝',
'来岁如今归未归',
],
},
{
title: '吹笛',
body: [
'吹笛秋山风月清',
'谁家巧作断肠声',
'风飘律吕相和切',
'月傍关山几处明',
'胡骑中宵堪北走',
'武陵一曲想南征',
'故园杨柳今摇落',
'何得愁中曲尽生',
],
},
{
title: '孤雁(一作后飞雁)',
body: [
'孤雁不饮啄',
'飞鸣声念群',
'谁怜一片影',
'相失万重云',
'望尽似犹见',
'哀多如更闻',
'野鸦无意绪',
'鸣噪自纷纷',
],
},
{
title: '鸥',
body: [
'江浦寒鸥戏',
'无他亦自饶',
'却思翻玉羽',
'随意点春苗',
'雪暗还须浴',
'风生一任飘',
'几群沧海上',
'清影日萧萧',
],
},
{
title: '猿',
body: [
'袅袅啼虚壁',
'萧萧挂冷枝',
'艰难人不见',
'隐见尔如知',
'惯习元从众',
'全生或用奇',
'前林腾每及',
'父子莫相离',
],
},
{
title: '黄鱼',
body: [
'日见巴东峡',
'黄鱼出浪新',
'脂膏兼饲犬',
'长大不容身',
'筒桶相沿久',
'风雷肯为神',
'泥沙卷涎沫',
'回首怪龙鳞',
],
},
{
title: '白小',
body: [
'白小群分命',
'天然二寸鱼',
'细微沾水族',
'风俗当园蔬',
'入肆银花乱',
'倾箱雪片虚',
'生成犹拾卵',
'尽取义何如',
],
},
{
title: '麂',
body: [
'永与清溪别',
'蒙将玉馔俱',
'无才逐仙隐',
'不敢恨庖厨',
'乱世轻全物',
'微声及祸枢',
'衣冠兼盗贼',
'饕餮用斯须',
],
},
{
title: '鸡',
body: [
'纪德名标五',
'初鸣度必三',
'殊方听有异',
'失次晓无惭',
'问俗人情似',
'充庖尔辈堪',
'气交亭育际',
'巫峡漏司南',
],
},
{
title: '玉腕骝(江陵节度卫公马也)',
body: [
'闻说荆南马',
'尚书玉腕骝',
'顿骖飘赤汗',
'跼蹐顾长楸',
'胡虏三年入',
'乾坤一战收',
'举鞭如有问',
'欲伴习池游',
],
},
{
title: '见王监兵马使说近山有白黑二鹰罗者久取竟未…请余赋诗',
body: [
'雪飞玉立尽清秋',
'不惜奇毛恣远游',
'在野只教心力破',
'千人何事网罗求',
'一生自猎知无敌',
'百中争能耻下鞲',
'鹏碍九天须却避',
'兔藏三穴莫深忧',
'黑鹰不省人间有',
'度海疑从北极来',
'正翮抟风超紫塞',
'立冬几夜宿阳台',
'虞罗自各虚施巧',
'春雁同归必见猜',
'万里寒空只一日',
'金眸玉爪不凡材',
],
},
{
title: '太岁日',
body: [
'楚岸行将老',
'巫山坐复春',
'病多犹是客',
'谋拙竟何人',
'阊阖开黄道',
'衣冠拜紫宸',
'荣光悬日月',
'赐与出金银',
'愁寂鸳行断',
'参差虎穴邻',
'西江元下蜀',
'北斗故临秦',
'散地逾高枕',
'生涯脱要津',
'天边梅柳树',
'相见几回新',
],
},
{
title: '元日示宗武',
body: [
'汝啼吾手战',
'吾笑汝身长',
'处处逢正月',
'迢迢滞远方',
'飘零还柏酒',
'衰病只藜床',
'训喻青衿子',
'名惭白首郎',
'赋诗犹落笔',
'献寿更称觞',
'不见江东弟',
'高歌泪数行',
],
},
{
title: '远怀舍弟颖、观等',
body: [
'阳翟空知处',
'荆南近得书',
'积年仍远别',
'多难不安居',
'江汉春风起',
'冰霜昨夜除',
'云天犹错莫',
'花萼尚萧疏',
'对酒都疑梦',
'吟诗正忆渠',
'旧时元日会',
'乡党羡吾庐',
],
},
{
title: '续得观书,迎就当阳居止,正月中旬定出三峡',
body: [
'自汝到荆府',
'书来数唤吾',
'颂椒添讽咏',
'禁火卜欢娱',
'舟楫因人动',
'形骸用杖扶',
'天旋夔子国',
'春近岳阳湖',
'发日排南喜',
'伤神散北吁',
'飞鸣还接翅',
'行序密衔芦',
'俗薄江山好',
'时危草木苏',
'冯唐虽晚达',
'终觊在皇都',
],
},
{
title: '将别巫峡,赠南卿兄瀼西果园四十亩',
body: [
'苔竹素所好',
'萍蓬无定居',
'远游长儿子',
'几地别林庐',
'杂蕊红相对',
'他时锦不如',
'具舟将出峡',
'巡圃念携锄',
'正月喧莺末',
'兹辰放鹢初',
'雪篱梅可折',
'风榭柳微舒',
'托赠卿家有',
'因歌野兴疏',
'残生逗江汉',
'何处狎樵渔',
],
},
{
title: '送大理封主簿五郎亲事不合却赴通州主簿前阆…亲事遂停',
body: [
'禁脔去东床',
'趋庭赴北堂',
'风波空远涉',
'琴瑟几虚张',
'渥水出骐骥',
'昆山生凤凰',
'两家诚款款',
'中道许苍苍',
'颇谓秦晋匹',
'从来王谢郎',
'青春动才调',
'白首缺辉光',
'玉润终孤立',
'珠明得暗藏',
'馀寒折花卉',
'恨别满江乡',
],
},
{
title: '人日两篇',
body: [
'元日到人日',
'未有不阴时',
'冰雪莺难至',
'春寒花较迟',
'云随白水落',
'风振紫山悲',
'蓬鬓稀疏久',
'无劳比素丝',
'此日此时人共得',
'一谈一笑俗相看',
'尊前柏叶休随酒',
'胜里金花巧耐寒',
'佩剑冲星聊暂拔',
'匣琴流水自须弹',
'早春重引江湖兴',
'直道无忧行路难',
],
},
{
title: '江梅',
body: [
'梅蕊腊前破',
'梅花年后多',
'绝知春意好',
'最奈客愁何',
'雪树元同色',
'江风亦自波',
'故园不可见',
'巫岫郁嵯峨',
],
},
{
title: '庭草',
body: [
'楚草经寒碧',
'逢春入眼浓',
'旧低收叶举',
'新掩卷牙重',
'步履宜轻过',
'开筵得屡供',
'看花随节序',
'不敢强为容',
],
},
{
title: '大历三年春白帝城放船出瞿塘峡久居夔府将适…凡四十韵',
body: [
'老向巴人里',
'今辞楚塞隅',
'入舟翻不乐',
'解缆独长吁',
'窄转深啼狖',
'虚随乱浴凫',
'石苔凌几杖',
'空翠扑肌肤',
'叠壁排霜剑',
'奔泉溅水珠',
'杳冥藤上下',
'浓澹树荣枯',
'神女峰娟妙',
'昭君宅有无',
'曲留明怨惜',
'梦尽失欢娱',
'摆阖盘涡沸',
'欹斜激浪输',
'风雷缠地脉',
'冰雪耀天衢',
'鹿角真走险',
'狼头如跋胡',
'恶滩宁变色',
'高卧负微躯',
'书史全倾挠',
'装囊半压濡',
'生涯临臬兀',
'死地脱斯须',
'不有平川决',
'焉知众壑趋',
'乾坤霾涨海',
'雨露洗春芜',
'鸥鸟牵丝飏',
'骊龙濯锦纡',
'落霞沉绿绮',
'残月坏金枢',
'泥笋苞初荻',
'沙茸出小蒲',
'雁儿争水马',
'燕子逐樯乌',
'绝岛容烟雾',
'环洲纳晓晡',
'前闻辨陶牧',
'转眄拂宜都',
'县郭南畿好',
'津亭北望孤',
'劳心依憩息',
'朗咏划昭苏',
'意遣乐还笑',
'衰迷贤与愚',
'飘萧将素发',
'汩没听洪炉',
'丘壑曾忘返',
'文章敢自诬',
'此生遭圣代',
'谁分哭穷途',
'卧疾淹为客',
'蒙恩早厕儒',
'廷争酬造化',
'朴直乞江湖',
'滟滪险相迫',
'沧浪深可逾',
'浮名寻已已',
'懒计却区区',
'喜近天皇寺',
'先披古画图',
'应经帝子渚',
'同泣舜苍梧',
'朝士兼戎服',
'君王按湛卢',
'旄头初俶扰',
'鹑首丽泥涂',
'甲卒身虽贵',
'书生道固殊',
'出尘皆野鹤',
'历块匪辕驹',
'伊吕终难降',
'韩彭不易呼',
'五云高太甲',
'六月旷抟扶',
'回首黎元病',
'争权将帅诛',
'山林托疲苶',
'未必免崎岖',
],
},
{
title: '巫山县汾州唐使君十八弟宴别兼诸公携酒乐…留于屋壁',
body: [
'卧病巴东久',
'今年强作归',
'故人犹远谪',
'兹日倍多违',
'接宴身兼杖',
'听歌泪满衣',
'诸公不相弃',
'拥别惜光辉',
],
},
{
title: '春夜峡州田侍御长史津亭留宴(得筵字)',
body: [
'北斗三更席',
'西江万里船',
'杖藜登水榭',
'挥翰宿春天',
'白发烦多酒',
'明星惜此筵',
'始知云雨峡',
'忽尽下牢边',
],
},
{
title: '泊松滋江亭',
body: [
'沙帽随鸥鸟',
'扁舟系此亭',
'江湖深更白',
'松竹远微青',
'一柱全应近',
'高唐莫再经',
'今宵南极外',
'甘作老人星',
],
},
{
title: '行次古城店泛江作,不揆鄙拙,奉呈江陵幕府诸公',
body: [
'老年常道路',
'迟日复山川',
'白屋花开里',
'孤城麦秀边',
'济江元自阔',
'下水不劳牵',
'风蝶勤依桨',
'春鸥懒避船',
'王门高德业',
'幕府盛才贤',
'行色兼多病',
'苍茫泛爱前',
],
},
{
title: '乘雨入行军六弟宅',
body: [
'曙角凌云罢',
'春城带雨长',
'水花分堑弱',
'巢燕得泥忙',
'令弟雄军佐',
'凡才污省郎',
'萍漂忍流涕',
'衰飒近中堂',
],
},
{
title: '宴胡侍御书堂(李尚书之芳、郑秘监审同集归字韵)',
body: [
'江湖春欲暮',
'墙宇日犹微',
'暗暗春籍满',
'轻轻花絮飞',
'翰林名有素',
'墨客兴无违',
'今夜文星动',
'吾侪醉不归',
],
},
{
title: '书堂饮既,夜复邀李尚书下马,月下赋绝句',
body: [
'湖水林风相与清',
'残尊下马复同倾',
'久判野鹤如霜鬓',
'遮莫邻鸡下五更',
],
},
{
title: '上巳日徐司录林园宴集',
body: [
'鬓毛垂领白',
'花蕊亚枝红',
'欹倒衰年废',
'招寻令节同',
'薄衣临积水',
'吹面受和风',
'有喜留攀桂',
'无劳问转蓬',
],
},
{
title: '奉送苏州李二十五长史丈之任',
body: [
'星坼台衡地',
'曾为人所怜',
'公侯终必复',
'经术昔相传',
'食德见从事',
'克家何妙年',
'一毛生凤穴',
'三尺献龙泉',
'赤壁浮春暮',
'姑苏落海边',
'客间头最白',
'惆怅此离筵',
],
},
{
title: '暮春江陵送马大卿公,恩命追赴阙下',
body: [
'自古求忠孝',
'名家信有之',
'吾贤富才术',
'此道未磷缁',
'玉府标孤映',
'霜蹄去不疑',
'激扬音韵彻',
'籍甚众多推',
'潘陆应同调',
'孙吴亦异时',
'北辰征事业',
'南纪赴恩私',
'卿月升金掌',
'王春度玉墀',
'熏风行应律',
'湛露即歌诗',
'天意高难问',
'人情老易悲',
'尊前江汉阔',
'后会且深期',
],
},
{
title: '暮春陪李尚书、李中丞过郑监湖亭泛舟(得过字韵)',
body: [
'海内文章伯',
'湖边意绪多',
'玉尊移晚兴',
'桂楫带酣歌',
'春日繁鱼鸟',
'江天足芰荷',
'郑庄宾客地',
'衰白远来过',
],
},
{
title: '奉送蜀州柏二别驾将中丞命赴江陵起居…行军司马佐',
body: [
'中丞问俗画熊频',
'爱弟传书彩鹢新',
'迁转五州防御使',
'起居八座太夫人',
'楚宫腊送荆门水',
'白帝云偷碧海春',
'报与惠连诗不惜',
'知吾斑鬓总如银',
],
},
{
title: '夏日杨长宁宅送崔侍御、常正字入京(得深字韵)',
body: [
'醉酒扬雄宅',
'升堂子贱琴',
'不堪垂老鬓',
'还对欲分襟',
'天地西江远',
'星辰北斗深',
'乌台俯麟阁',
'长夏白头吟',
],
},
{
title: '和江陵宋大少府暮春雨后同诸公及舍弟宴书斋',
body: [
'渥洼汗血种',
'天上麒麟儿',
'才士得神秀',
'书斋闻尔为',
'棣华晴雨好',
'彩服暮春宜',
'朋酒日欢会',
'老夫今始知',
],
},
{
title: '宇文晁尚书之甥崔彧司业之孙尚书之子重泛郑监前湖',
body: [
'郊扉俗远长幽寂',
'野水春来更接连',
'锦席淹留还出浦',
'葛巾欹侧未回船',
'尊当霞绮轻初散',
'棹拂荷珠碎却圆',
'不但习池归酩酊',
'君看郑谷去夤缘',
],
},
{
title: '多病执热奉怀李尚书(之芳)',
body: [
'衰年正苦病侵凌',
'首夏何须气郁蒸',
'大水淼茫炎海接',
'奇峰硉兀火云升',
'思沾道暍黄梅雨',
'敢望宫恩玉井冰',
'不是尚书期不顾',
'山阴野雪兴难乘',
],
},
{
title: '水宿遣兴奉呈群公',
body: [
'鲁钝乃多病',
'逢迎远复迷',
'耳聋须画字',
'发短不胜篦',
'泽国虽勤雨',
'炎天竟浅泥',
'小江还积浪',
'弱缆且长堤',
'归路非关北',
'行舟却向西',
'暮年漂泊恨',
'今夕乱离啼',
'童稚频书札',
'盘餐讵糁藜',
'我行何到此',
'物理直难齐',
'高枕翻星月',
'严城叠鼓鼙',
'风号闻虎豹',
'水宿伴凫鹥',
'异县惊虚往',
'同人惜解携',
'蹉跎长泛鹢',
'展转屡鸣鸡',
'嶷嶷瑚琏器',
'阴阴桃李蹊',
'馀波期救涸',
'费日苦轻赍',
'支策门阑邃',
'肩舆羽翮低',
'自伤甘贱役',
'谁愍强幽栖',
'巨海能无钓',
'浮云亦有梯',
'勋庸思树立',
'语默可端倪',
'赠粟囷应指',
'登桥柱必题',
'丹心老未折',
'时访武陵溪',
],
},
{
title: '奉贺阳城郡王太夫人恩命加邓国太夫人',
body: [
'卫幕衔恩重',
'潘舆送喜频',
'济时瞻上将',
'锡号戴慈亲',
'富贵当如此',
'尊荣迈等伦',
'郡依封土旧',
'国与大名新',
'紫诰鸾回纸',
'清朝燕贺人',
'远传冬笋味',
'更觉彩衣春',
'奕叶班姑史',
'芬芳孟母邻',
'义方兼有训',
'词翰两如神',
'委曲承颜体',
'鶱飞报主身',
'可怜忠与孝',
'双美画骐驎',
],
},
{
title: '江陵望幸',
body: [
'雄都元壮丽',
'望幸欻威神',
'地利西通蜀',
'天文北照秦',
'风烟含越鸟',
'舟楫控吴人',
'未枉周王驾',
'终期汉武巡',
'甲兵分圣旨',
'居守付宗臣',
'早发云台仗',
'恩波起涸鳞',
],
},
{
title: '江边星月二首',
body: [
'骤雨清秋夜',
'金波耿玉绳',
'天河元自白',
'江浦向来澄',
'映物连珠断',
'缘空一镜升',
'馀光隐更漏',
'况乃露华凝',
'江月辞风缆',
'江星别雾船',
'鸡鸣还曙色',
'鹭浴自清川',
'历历竟谁种',
'悠悠何处圆',
'客愁殊未已',
'他夕始相鲜',
],
},
{
title: '舟月对驿近寺',
body: [
'更深不假烛',
'月朗自明船',
'金刹青枫外',
'朱楼白水边',
'城乌啼眇眇',
'野鹭宿娟娟',
'皓首江湖客',
'钩帘独未眠',
],
},
{
title: '舟中',
body: [
'风餐江柳下',
'雨卧驿楼边',
'结缆排鱼网',
'连樯并米船',
'今朝云细薄',
'昨夜月清圆',
'飘泊南庭老',
'只应学水仙',
],
},
{
title: '遣闷',
body: [
'地阔平沙岸',
'舟虚小洞房',
'使尘来驿道',
'城日避乌樯',
'暑雨留蒸湿',
'江风借夕凉',
'行云星隐见',
'叠浪月光芒',
'萤鉴缘帷彻',
'蛛丝罥鬓长',
'哀筝犹凭几',
'鸣笛竟沾裳',
'倚著如秦赘',
'过逢类楚狂',
'气冲看剑匣',
'颖脱抚锥囊',
'妖孽关东臭',
'兵戈陇右创',
'时清疑武略',
'世乱跼文场',
'馀力浮于海',
'端忧问彼苍',
'百年从万事',
'故国耿难忘',
],
},
{
title: '江陵节度阳城郡王新楼成王请严侍御判官赋七字句同作',
body: [
'楼上炎天冰雪生',
'高尽燕雀贺新成',
'碧窗宿雾濛濛湿',
'朱栱浮云细细轻',
'杖钺褰帷瞻具美',
'投壶散帙有馀清',
'自公多暇延参佐',
'江汉风流万古情',
],
},
{
title: '又作此奉卫王',
body: [
'西北楼成雄楚都',
'远开山岳散江湖',
'二仪清浊还高下',
'三伏炎蒸定有无',
'推毂几年唯镇静',
'曳裾终日盛文儒',
'白头授简焉能赋',
'愧似相如为大夫',
],
},
{
title: '舟出江陵南浦,奉寄郑少尹(审)',
body: [
'更欲投何处',
'飘然去此都',
'形骸元土木',
'舟楫复江湖',
'社稷缠妖气',
'干戈送老儒',
'百年同弃物',
'万国尽穷途',
'雨洗平沙静',
'天衔阔岸纡',
'鸣螀随泛梗',
'别燕赴秋菰',
'栖托难高卧',
'饥寒迫向隅',
'寂寥相喣沫',
'浩荡报恩珠',
'溟涨鲸波动',
'衡阳雁影徂',
'南征问悬榻',
'东逝想乘桴',
'滥窃商歌听',
'时忧卞泣诛',
'经过忆郑驿',
'斟酌旅情孤',
],
},
{
title: '江南逢李龟年',
body: [
'岐王宅里寻常见',
'崔九堂前几度闻',
'正是江南好风景',
'落花时节又逢君',
],
},
{
title: '官亭夕坐戏简颜十少府',
body: [
'南国调寒杵',
'西江浸日车',
'客愁连蟋蟀',
'亭古带蒹葭',
'不返青丝鞚',
'虚烧夜烛花',
'老翁须地主',
'细细酌流霞',
],
},
{
title: '秋日荆南述怀三十韵',
body: [
'昔承推奖分',
'愧匪挺生材',
'迟暮宫臣忝',
'艰危衮职陪',
'扬镳随日驭',
'折槛出云台',
'罪戾宽犹活',
'干戈塞未开',
'星霜玄鸟变',
'身世白驹催',
'伏枕因超忽',
'扁舟任往来',
'九钻巴噀火',
'三蛰楚祠雷',
'望帝传应实',
'昭王问不回',
'蛟螭深作横',
'豺虎乱雄猜',
'素业行已矣',
'浮名安在哉',
'琴乌曲怨愤',
'庭鹤舞摧颓',
'秋雨漫湘水',
'阴风过岭梅',
'苦摇求食尾',
'常曝报恩腮',
'结舌防谗柄',
'探肠有祸胎',
'苍茫步兵哭',
'展转仲宣哀',
'饥籍家家米',
'愁征处处杯',
'休为贫士叹',
'任受众人咍',
'得丧初难识',
'荣枯划易该',
'差池分组冕',
'合沓起蒿莱',
'不必伊周地',
'皆知屈宋才',
'汉庭和异域',
'晋史坼中台',
'霸业寻常体',
'忠臣忌讳灾',
'群公纷戮力',
'圣虑窅裴回',
'数见铭钟鼎',
'真宜法斗魁',
'愿闻锋镝铸',
'莫使栋梁摧',
'盘石圭多翦',
'凶门毂少推',
'垂旒资穆穆',
'祝网但恢恢',
'赤雀翻然至',
'黄龙讵假媒',
'贤非梦傅野',
'隐类凿颜坯',
'自古江湖客',
'冥心若死灰',
],
},
{
title: '秋日荆南送石首薛明府辞满告别奉寄薛尚书颂德…三十韵',
body: [
'南征为客久',
'西候别君初',
'岁满归凫舄',
'秋来把雁书',
'荆门留美化',
'姜被就离居',
'闻道和亲入',
'垂名报国馀',
'连枝不日并',
'八座几时除',
'往者胡星孛',
'恭惟汉网疏',
'风尘相澒洞',
'天地一丘墟',
'殿瓦鸳鸯坼',
'宫帘翡翠虚',
'钩陈摧徼道',
'枪櫐失储胥',
'文物陪巡守',
'亲贤病拮据',
'公时呵猰貐',
'首唱却鲸鱼',
'势惬宗萧相',
'材非一范睢',
'尸填太行道',
'血走浚仪渠',
'滏口师仍会',
'函关愤已摅',
'紫微临大角',
'皇极正乘舆',
'赏从频峨冕',
'殊私再直庐',
'岂惟高卫霍',
'曾是接应徐',
'降集翻翔凤',
'追攀绝众狙',
'侍臣双宋玉',
'战策两穰苴',
'鉴澈劳悬镜',
'荒芜已荷锄',
'向来披述作',
'重此忆吹嘘',
'白发甘凋丧',
'青云亦卷舒',
'经纶功不朽',
'跋涉体何如',
'应讶耽湖橘',
'常餐占野蔬',
'十年婴药饵',
'万里狎樵渔',
'扬子淹投阁',
'邹生惜曳裾',
'但惊飞熠耀',
'不记改蟾蜍',
'烟雨封巫峡',
'江淮略孟诸',
'汤池虽险固',
'辽海尚填淤',
'努力输肝胆',
'休烦独起予',
],
},
{
title: '哭李尚书(之芳)',
body: [
'漳滨与蒿里',
'逝水竟同年',
'欲挂留徐剑',
'犹回忆戴船',
'相知成白首',
'此别间黄泉',
'风雨嗟何及',
'江湖涕泫然',
'修文将管辂',
'奉使失张骞',
'史阁行人在',
'诗家秀句传',
'客亭鞍马绝',
'旅榇网虫悬',
'复魄昭丘远',
'归魂素浐偏',
'樵苏封葬地',
'喉舌罢朝天',
'秋色凋春草',
'王孙若个边',
],
},
{
title: '重题',
body: [
'涕泗不能收',
'哭君余白头',
'儿童相识尽',
'宇宙此生浮',
'江雨铭旌湿',
'湖风井径秋',
'还瞻魏太子',
'宾客减应刘',
],
},
{
title: '独坐',
body: [
'悲愁回白首',
'倚杖背孤城',
'江敛洲渚出',
'天虚风物清',
'沧溟服衰谢',
'朱绂负平生',
'仰羡黄昏鸟',
'投林羽翮轻',
],
},
{
title: '暮归',
body: [
'霜黄碧梧白鹤栖',
'城上击柝复乌啼',
'客子入门月皎皎',
'谁家捣练风凄凄',
'南渡桂水阙舟楫',
'北归秦川多鼓鼙',
'年过半百不称意',
'明日看云还杖藜',
],
},
{
title: '移居公安敬赠卫大郎钧',
body: [
'卫侯不易得',
'余病汝知之',
'雅量涵高远',
'清襟照等夷',
'平生感意气',
'少小爱文辞',
'河海由来合',
'风云若有期',
'形容劳宇宙',
'质朴谢轩墀',
'自古幽人泣',
'流年壮士悲',
'水烟通径草',
'秋露接园葵',
'入邑豺狼斗',
'伤弓鸟雀饥',
'白头供宴语',
'乌几伴栖迟',
'交态遭轻薄',
'今朝豁所思',
],
},
{
title: '公安送韦二少府匡赞',
body: [
'逍遥公后世多贤',
'送尔维舟惜此筵',
'念我能书数字至',
'将诗不必万人传',
'时危兵甲黄尘里',
'日短江湖白发前',
'古往今来皆涕泪',
'断肠分手各风烟',
],
},
{
title: '赠虞十五司马',
body: [
'远师虞秘监',
'今喜识玄孙',
'形像丹青逼',
'家声器宇存',
'凄凉怜笔势',
'浩荡问词源',
'爽气金天豁',
'清谈玉露繁',
'伫鸣南岳凤',
'欲化北溟鲲',
'交态知浮俗',
'儒流不异门',
'过逢联客位',
'日夜倒芳尊',
'沙岸风吹叶',
'云江月上轩',
'百年嗟已半',
'四座敢辞喧',
'书籍终相与',
'青山隔故园',
],
},
{
title: '公安县怀古',
body: [
'野旷吕蒙营',
'江深刘备城',
'寒天催日短',
'风浪与云平',
'洒落君臣契',
'飞腾战伐名',
'维舟倚前浦',
'长啸一含情',
],
},
{
title: '公安送李二十九弟晋肃入蜀,余下沔鄂',
body: [
'正解柴桑缆',
'仍看蜀道行',
'樯乌相背发',
'塞雁一行鸣',
'南纪连铜柱',
'西江接锦城',
'凭将百钱卜',
'飘泊问君平',
],
},
{
title: '宴王使君宅题二首',
body: [
'汉主追韩信',
'苍生起谢安',
'吾徒自漂泊',
'世事各艰难',
'逆旅招邀近',
'他乡思绪宽',
'不材甘朽质',
'高卧岂泥蟠',
'泛爱容霜发',
'留欢卜夜闲',
'自吟诗送老',
'相劝酒开颜',
'戎马今何地',
'乡园独旧山',
'江湖堕清月',
'酩酊任扶还',
],
},
{
title: '留别公安太易沙门',
body: [
'隐居欲就庐山远',
'丽藻初逢休上人',
'数问舟航留制作',
'长开箧笥拟心神',
'沙村白雪仍含冻',
'江县红梅已放春',
'先蹋炉峰置兰若',
'徐飞锡杖出风尘',
],
},
{
title: '晓发公安(数月憩息此县)',
body: [
'北城击柝复欲罢',
'东方明星亦不迟',
'邻鸡野哭如昨日',
'物色生态能几时',
'舟楫眇然自此去',
'江湖远适无前期',
'出门转眄已陈迹',
'药饵扶吾随所之',
],
},
{
title: '泊岳阳城下',
body: [
'江国逾千里',
'山城仅百层',
'岸风翻夕浪',
'舟雪洒寒灯',
'留滞才难尽',
'艰危气益增',
'图南未可料',
'变化有鲲鹏',
],
},
{
title: '缆船苦风,戏题四韵,奉简郑十三判官(泛)',
body: [
'楚岸朔风疾',
'天寒鶬鸹呼',
'涨沙霾草树',
'舞雪渡江湖',
'吹帽时时落',
'维舟日日孤',
'因声置驿外',
'为觅酒家垆',
],
},
{
title: '登岳阳楼',
body: [
'昔闻洞庭水',
'今上岳阳楼',
'吴楚东南坼',
'乾坤日夜浮',
'亲朋无一字',
'老病有孤舟',
'戎马关山北',
'凭轩涕泗流',
],
},
{
title: '陪裴使君登岳阳楼',
body: [
'湖阔兼云雾',
'楼孤属晚晴',
'礼加徐孺子',
'诗接谢宣城',
'雪岸丛梅发',
'春泥百草生',
'敢违渔父问',
'从此更南征',
],
},
{
title: '过南岳入洞庭湖',
body: [
'洪波忽争道',
'岸转异江湖',
'鄂渚分云树',
'衡山引舳舻',
'翠牙穿裛桨',
'碧节上寒蒲',
'病渴身何去',
'春生力更无',
'壤童犁雨雪',
'渔屋架泥涂',
'欹侧风帆满',
'微冥水驿孤',
'悠悠回赤壁',
'浩浩略苍梧',
'帝子留遗恨',
'曹公屈壮图',
'圣朝光御极',
'残孽驻艰虞',
'才淑随厮养',
'名贤隐锻炉',
'邵平元入汉',
'张翰后归吴',
'莫怪啼痕数',
'危樯逐夜乌',
],
},
{
title: '宿青草湖(重湖,南青草,北洞庭)',
body: [
'洞庭犹在目',
'青草续为名',
'宿桨依农事',
'邮签报水程',
'寒冰争倚薄',
'云月递微明',
'湖雁双双起',
'人来故北征',
],
},
{
title: '宿白沙驿(初过湖南五里)',
body: [
'水宿仍馀照',
'人烟复此亭',
'驿边沙旧白',
'湖外草新青',
'万象皆春气',
'孤槎自客星',
'随波无限月',
'的的近南溟',
],
},
{
title: '湘夫人祠(即黄陵庙)',
body: [
'肃肃湘妃庙',
'空墙碧水春',
'虫书玉佩藓',
'燕舞翠帷尘',
'晚泊登汀树',
'微馨借渚蘋',
'苍梧恨不尽',
'染泪在丛筠',
],
},
{
title: '祠南夕望',
body: [
'百丈牵江色',
'孤舟泛日斜',
'兴来犹杖屦',
'目断更云沙',
'山鬼迷春竹',
'湘娥倚暮花',
'湖南清绝地',
'万古一长嗟',
],
},
{
title: '登白马潭',
body: [
'水生春缆没',
'日出野船开',
'宿鸟行犹去',
'丛花笑不来',
'人人伤白首',
'处处接金杯',
'莫道新知要',
'南征且未回',
],
},
{
title: '归雁',
body: [
'闻道今春雁',
'南归自广州',
'见花辞涨海',
'避雪到罗浮',
'是物关兵气',
'何时免客愁',
'年年霜露隔',
'不过五湖秋',
],
},
{
title: '野望',
body: [
'纳纳乾坤大',
'行行郡国遥',
'云山兼五岭',
'风壤带三苗',
'野树侵江阔',
'春蒲长雪消',
'扁舟空老去',
'无补圣明朝',
],
},
{
title: '入乔口(长沙北界)',
body: [
'漠漠旧京远',
'迟迟归路赊',
'残年傍水国',
'落日对春华',
'树蜜早蜂乱',
'江泥轻燕斜',
'贾生骨已朽',
'凄恻近长沙',
],
},
{
title: '铜官渚守风(渚在宁乡县)',
body: [
'不夜楚帆落',
'避风湘渚间',
'水耕先浸草',
'春火更烧山',
'早泊云物晦',
'逆行波浪悭',
'飞来双白鹤',
'过去杳难攀',
],
},
{
title: '北风(新康江口信宿方行)',
body: [
'春生南国瘴',
'气待北风苏',
'向晚霾残日',
'初宵鼓大炉',
'爽携卑湿地',
'声拔洞庭湖',
'万里鱼龙伏',
'三更鸟兽呼',
'涤除贪破浪',
'愁绝付摧枯',
'执热沉沉在',
'凌寒往往须',
'且知宽疾肺',
'不敢恨危途',
'再宿烦舟子',
'衰容问仆夫',
'今晨非盛怒',
'便道即长驱',
'隐几看帆席',
'云州涌坐隅',
],
},
{
title: '双枫浦(在浏阳县)',
body: [
'辍棹青枫浦',
'双枫旧已摧',
'自惊衰谢力',
'不道栋梁材',
'浪足浮纱帽',
'皮须截锦苔',
'江边地有主',
'暂借上天回',
],
},
{
title: '奉送王信州崟北归',
body: [
'朝廷防盗贼',
'供给愍诛求',
'下诏选郎署',
'传声能典州',
'苍生今日困',
'天子向时忧',
'井屋有烟起',
'疮痍无血流',
'壤歌唯海甸',
'画角自山楼',
'白发寐常早',
'荒榛农复秋',
'解龟逾卧辙',
'遣骑觅扁舟',
'徐榻不知倦',
'颍川何以酬',
'尘生彤管笔',
'寒腻黑貂裘',
'高义终焉在',
'斯文去矣休',
'别离同雨散',
'行止各云浮',
'林热鸟开口',
'江浑鱼掉头',
'尉佗虽北拜',
'太史尚南留',
'军旅应都息',
'寰区要尽收',
'九重思谏诤',
'八极念怀柔',
'徙倚瞻王室',
'从容仰庙谋',
'故人持雅论',
'绝塞豁穷愁',
'复见陶唐理',
'甘为汗漫游',
],
},
{
title: '江阁卧病走笔寄呈崔、卢两侍御',
body: [
'客子庖厨薄',
'江楼枕席清',
'衰年病只瘦',
'长夏想为情',
'滑忆雕胡饭',
'香闻锦带羹',
'溜匙兼暖腹',
'谁欲致杯罂',
],
},
{
title: '潭州送韦员外牧韶州(迢)',
body: [
'炎海韶州牧',
'风流汉署郎',
'分符先令望',
'同舍有辉光',
'白首多年疾',
'秋天昨夜凉',
'洞庭无过雁',
'书疏莫相忘',
],
},
{
title: '江阁对雨有怀行营裴二端公(裴虬与讨臧玠故有行营)',
body: [
'南纪风涛壮',
'阴晴屡不分',
'野流行地日',
'江入度山云',
'层阁凭雷殷',
'长空水面文',
'雨来铜柱北',
'应洗伏波军',
],
},
{
title: '酬韦韶州见寄',
body: [
'养拙江湖外',
'朝廷记忆疏',
'深惭长者辙',
'重得故人书',
'白发丝难理',
'新诗锦不如',
'虽无南去雁',
'看取北来鱼',
],
},
{
title: '千秋节有感二首(八月二日为明皇千秋节)',
body: [
'自罢千秋节',
'频伤八月来',
'先朝常宴会',
'壮观已尘埃',
'凤纪编生日',
'龙池堑劫灰',
'湘川新涕泪',
'秦树远楼台',
'宝镜群臣得',
'金吾万国回',
'衢尊不重饮',
'白首独馀哀',
'御气云楼敞',
'含风彩仗高',
'仙人张内乐',
'王母献宫桃',
'罗袜红蕖艳',
'金羁白雪毛',
'舞阶衔寿酒',
'走索背秋毫',
'圣主他年贵',
'边心此日劳',
'桂江流向北',
'满眼送波涛',
],
},
{
title: '晚秋长沙蔡五侍御饮筵,送殷六参军归澧州觐省',
body: [
'佳士欣相识',
'慈颜望远游',
'甘从投辖饮',
'肯作置书邮',
'高鸟黄云暮',
'寒蝉碧树秋',
'湖南冬不雪',
'吾病得淹留',
],
},
{
title: '湖中送敬十使君适广陵',
body: [
'相见各头白',
'其如离别何',
'几年一会面',
'今日复悲歌',
'少壮乐难得',
'岁寒心匪他',
'气缠霜匣满',
'冰置玉壶多',
'遭乱实漂泊',
'济时曾琢磨',
'形容吾校老',
'胆力尔谁过',
'秋晚岳增翠',
'风高湖涌波',
'鶱腾访知己',
'淮海莫蹉跎',
],
},
{
title: '长沙送李十一(衔)',
body: [
'与子避地西康州',
'洞庭相逢十二秋',
'远愧尚方曾赐履',
'竟非吾土倦登楼',
'久存胶漆应难并',
'一辱泥涂遂晚收',
'李杜齐名真忝窃',
'朔云寒菊倍离忧',
],
},
{
title: '重送刘十弟判官',
body: [
'分源豕韦派',
'别浦雁宾秋',
'年事推兄忝',
'人才觉弟优',
'经过辨丰剑',
'意气逐吴钩',
'垂翅徒衰老',
'先鞭不滞留',
'本枝凌岁晚',
'高义豁穷愁',
'他日临江待',
'长沙旧驿楼',
],
},
{
title: '奉赠卢五丈参谋(琚)',
body: [
'恭惟同自出',
'妙选异高标',
'入幕知孙楚',
'披襟得郑侨',
'丈人藉才地',
'门阀冠云霄',
'老矣逢迎拙',
'相于契托饶',
'赐钱倾府待',
'争米驻船遥',
'邻好艰难薄',
'氓心杼轴焦',
'客星空伴使',
'寒水不成潮',
'素发干垂领',
'银章破在腰',
'说诗能累夜',
'醉酒或连朝',
'藻翰惟牵率',
'湖山合动摇',
'时清非造次',
'兴尽却萧条',
'天子多恩泽',
'苍生转寂寥',
'休传鹿是马',
'莫信鵩如鸮',
'未解依依袂',
'还斟泛泛瓢',
'流年疲蟋蟀',
'体物幸鹪鹩',
'辜负沧洲愿',
'谁云晚见招',
],
},
{
title: '登舟将适汉阳',
body: [
'春宅弃汝去',
'秋帆催客归',
'庭蔬尚在眼',
'浦浪已吹衣',
'生理飘荡拙',
'有心迟暮违',
'中原戎马盛',
'远道素书稀',
'塞雁与时集',
'樯乌终岁飞',
'鹿门自此往',
'永息汉阴机',
],
},
{
title: '暮秋将归秦,留别湖南幕府亲友',
body: [
'水阔苍梧野',
'天高白帝秋',
'途穷那免哭',
'身老不禁愁',
'大府才能会',
'诸公德业优',
'北归冲雨雪',
'谁悯敝貂裘',
],
},
{
title: '送卢十四弟侍御护韦尚书灵榇归上都二十韵',
body: [
'素幕渡江远',
'朱幡登陆微',
'悲鸣驷马顾',
'失涕万人挥',
'参佐哭辞毕',
'门阑谁送归',
'从公伏事久',
'之子俊才稀',
'长路更执绋',
'此心犹倒衣',
'感恩义不小',
'怀旧礼无违',
'墓待龙骧诏',
'台迎獬豸威',
'深衷见士则',
'雅论在兵机',
'戎狄乘妖气',
'尘沙落禁闱',
'往年朝谒断',
'他日扫除非',
'但促铜壶箭',
'休添玉帐旂',
'动询黄阁老',
'肯虑白登围',
'万姓疮痍合',
'群凶嗜欲肥',
'刺规多谏诤',
'端拱自光辉',
'俭约前王体',
'风流后代希',
'对扬期特达',
'衰朽再芳菲',
'空里愁书字',
'山中疾采薇',
'拨杯要忽罢',
'抱被宿何依',
'眼冷看征盖',
'儿扶立钓矶',
'清霜洞庭叶',
'故就别时飞',
],
},
{
title: '哭李常侍峄二首',
body: [
'一代风流尽',
'修文地下深',
'斯人不重见',
'将老失知音',
'短日行梅岭',
'寒山落桂林',
'长安若个畔',
'犹想映貂金',
'青琐陪双入',
'铜梁阻一辞',
'风尘逢我地',
'江汉哭君时',
'次第寻书札',
'呼儿检赠诗',
'发挥王子表',
'不愧史臣词',
],
},
{
title: '哭韦大夫之晋',
body: [
'凄怆郇瑕色',
'差池弱冠年',
'丈人叨礼数',
'文律早周旋',
'台阁黄图里',
'簪裾紫盖边',
'尊荣真不忝',
'端雅独翛然',
'贡喜音容间',
'冯招病疾缠',
'南过骇仓卒',
'北思悄联绵',
'鵩鸟长沙讳',
'犀牛蜀郡怜',
'素车犹恸哭',
'宝剑谷高悬',
'汉道中兴盛',
'韦经亚相传',
'冲融标世业',
'磊落映时贤',
'城府深朱夏',
'江湖眇霁天',
'绮楼关树顶',
'飞旐泛堂前',
'帟幕疑风燕',
'笳箫急暮蝉',
'兴残虚白室',
'迹断孝廉船',
'童孺交游尽',
'喧卑俗事牵',
'老来多涕泪',
'情在强诗篇',
'谁寄方隅理',
'朝难将帅权',
'春秋褒贬例',
'名器重双全',
],
},
{
title: '舟中夜雪,有怀卢十四侍御弟',
body: [
'朔风吹桂水',
'朔雪夜纷纷',
'暗度南楼月',
'寒深北渚云',
'烛斜初近见',
'舟重竟无闻',
'不识山阴道',
'听鸡更忆君',
],
},
{
title: '对雪',
body: [
'北雪犯长沙',
'胡云冷万家',
'随风且间叶',
'带雨不成花',
'金错囊从罄',
'银壶酒易赊',
'无人竭浮蚁',
'有待至昏鸦',
],
},
{
title: '楼上',
body: [
'天地空搔首',
'频抽白玉簪',
'皇舆三极北',
'身事五湖南',
'恋阙劳肝肺',
'论材愧杞楠',
'乱离难自救',
'终是老湘潭',
],
},
{
title: '冬晚送长孙渐舍人归州',
body: [
'参卿休坐幄',
'荡子不还乡',
'南客潇湘外',
'西戎鄠杜旁',
'衰年倾盖晚',
'费日系舟长',
'会面思来札',
'销魂逐去樯',
'云晴鸥更舞',
'风逆雁无行',
'匣里雌雄剑',
'吹毛任选将',
],
},
{
title: '暮冬送苏四郎徯兵曹适桂州',
body: [
'飘飘苏季子',
'六印佩何迟',
'早作诸侯客',
'兼工古体诗',
'尔贤埋照久',
'余病长年悲',
'卢绾须征日',
'楼兰要斩时',
'岁阳初盛动',
'王化久磷缁',
'为入苍梧庙',
'看云哭九疑',
],
},
{
title: '风疾舟中伏枕书怀三十六韵,奉呈湖南亲友',
body: [
'轩辕休制律',
'虞舜罢弹琴',
'尚错雄鸣管',
'犹伤半死心',
'圣贤名古邈',
'羁旅病年侵',
'舟泊常依震',
'湖平早见参',
'如闻马融笛',
'若倚仲宣襟',
'故国悲寒望',
'群云惨岁阴',
'水乡霾白屋',
'枫岸叠青岑',
'郁郁冬炎瘴',
'濛濛雨滞淫',
'鼓迎非祭鬼',
'弹落似鸮禽',
'兴尽才无闷',
'愁来遽不禁',
'生涯相汩没',
'时物自萧森',
'疑惑尊中弩',
'淹留冠上簪',
'牵裾惊魏帝',
'投阁为刘歆',
'狂走终奚适',
'微才谢所钦',
'吾安藜不糁',
'汝贵玉为琛',
'乌几重重缚',
'鹑衣寸寸针',
'哀伤同庾信',
'述作异陈琳',
'十暑岷山葛',
'三霜楚户砧',
'叨陪锦帐座',
'久放白头吟',
'反朴时难遇',
'忘机陆易沈',
'应过数粒食',
'得近四知金',
'春草封归恨',
'源花费独寻',
'转蓬忧悄悄',
'行药病涔涔',
'瘗夭追潘岳',
'持危觅邓林',
'蹉跎翻学步',
'感激在知音',
'却假苏张舌',
'高夸周宋镡',
'纳流迷浩汗',
'峻址得嶔崟',
'城府开清旭',
'松筠起碧浔',
'披颜争倩倩',
'逸足竞駸駸',
'朗鉴存愚直',
'皇天实照临',
'公孙仍恃险',
'侯景未生擒',
'书信中原阔',
'干戈北斗深',
'畏人千里井',
'问俗九州箴',
'战血流依旧',
'军声动至今',
'葛洪尸定解',
'许靖力还任',
'家事丹砂诀',
'无成涕作霖',
],
},
{
title: '奉赠萧二十使君',
body: [
'昔在严公幕',
'俱为蜀使臣',
'艰危参大府',
'前后间清尘',
'起草鸣先路',
'乘槎动要津',
'王凫聊暂出',
'萧雉只相驯',
'终始任安义',
'荒芜孟母邻',
'联翩匍匐礼',
'意气死生亲',
'张老存家事',
'嵇康有故人',
'食恩惭卤莽',
'镂骨抱酸辛',
'巢许山林志',
'夔龙廊庙珍',
'鹏图仍矫翼',
'熊轼且移轮',
'磊落衣冠地',
'苍茫土木身',
'埙篪鸣自合',
'金石莹逾新',
'重忆罗江外',
'同游锦水滨',
'结欢随过隙',
'怀旧益沾巾',
'旷绝含香舍',
'稽留伏枕辰',
'停骖双阙早',
'回雁五湖春',
'不达长卿病',
'从来原宪贫',
'监河受贷粟',
'一起辙中鳞',
],
},
{
title: '奉送二十三舅录事之摄郴州',
body: [
'贤良归盛族',
'吾舅尽知名',
'徐庶高交友',
'刘牢出外甥',
'泥涂岂珠玉',
'环堵但柴荆',
'衰老悲人世',
'驱驰厌甲兵',
'气春江上别',
'泪血渭阳情',
'舟鹢排风影',
'林乌反哺声',
'永嘉多北至',
'句漏且南征',
'必见公侯复',
'终闻盗贼平',
'郴州颇凉冷',
'橘井尚凄清',
'从役何蛮貊',
'居官志在行',
],
},
{
title: '送魏二十四司直充岭南掌选崔郎中判官兼寄韦韶州',
body: [
'选曹分五岭',
'使者历三湘',
'才美膺推荐',
'君行佐纪纲',
'佳声斯共远',
'雅节在周防',
'明白山涛鉴',
'嫌疑陆贾装',
'故人湖外少',
'春日岭南长',
'凭报韶州牧',
'新诗昨寄将',
],
},
{
title: '送赵十七明府之县',
body: [
'连城为宝重',
'茂宰得才新',
'山雉迎舟楫',
'江花报邑人',
'论交翻恨晚',
'卧病却愁春',
'惠爱南翁悦',
'馀波及老身',
],
},
{
title: '燕子来舟中作',
body: [
'湖南为客动经春',
'燕子衔泥两度新',
'旧入故园常识主',
'如今社日远看人',
'可怜处处巢君室',
'何异飘飘托此身',
'暂语船樯还起去',
'穿花落水益沾巾',
],
},
{
title: '同豆卢峰知字韵',
body: [
'炼金欧冶子',
'喷玉大宛儿',
'符彩高无敌',
'聪明达所为',
'梦兰他日应',
'折桂早年知',
'烂漫通经术',
'光芒刷羽仪',
'谢庭瞻不远',
'潘省会于斯',
'倡和将雏曲',
'田翁号鹿皮',
],
},
{
title: '归雁二首',
body: [
'万里衡阳雁',
'今年又北归',
'双双瞻客上',
'一一背人飞',
'云里相呼疾',
'沙边自宿稀',
'系书元浪语',
'愁寂故山薇',
'欲雪违胡地',
'先花别楚云',
'却过清渭影',
'高起洞庭群',
'塞北春阴暮',
'江南日色曛',
'伤弓流落羽',
'行断不堪闻',
],
},
{
title: '小寒食舟中作',
body: [
'佳辰强饭食犹寒',
'隐几萧条带鹖冠',
'春水船如天上坐',
'老年花似雾中看',
'娟娟戏蝶过闲幔',
'片片轻鸥下急湍',
'云白山青万馀里',
'愁看直北是长安',
],
},
{
title: '清明二首',
body: [
'朝来新火起新烟',
'湖色春光净客船',
'绣羽衔花他自得',
'红颜骑竹我无缘',
'胡童结束还难有',
'楚女腰肢亦可怜',
'不见定王城旧处',
'长怀贾傅井依然',
'虚沾焦举为寒食',
'实藉严君卖卜钱',
'钟鼎山林各天性',
'浊醪粗饭任吾年',
'此身飘泊苦西东',
'右臂偏枯半耳聋',
'寂寂系舟双下泪',
'悠悠伏枕左书空',
'十年蹴踘将雏远',
'万里秋千习俗同',
'旅雁上云归紫塞',
'家人钻火用青枫',
'秦城楼阁烟花里',
'汉主山河锦绣中',
'风水春来洞庭阔',
'白蘋愁杀白头翁',
],
},
{
title: '发潭州(时自潭之衡)',
body: [
'夜醉长沙酒',
'晓行湘水春',
'岸花飞送客',
'樯燕语留人',
'贾傅才未有',
'褚公书绝伦',
'高名前后事',
'回首一伤神',
],
},
{
title: '回棹',
body: [
'宿昔试安命',
'自私犹畏天',
'劳生系一物',
'为客费多年',
'衡岳江湖大',
'蒸池疫疠偏',
'散才婴薄俗',
'有迹负前贤',
'巾拂那关眼',
'瓶罍易满船',
'火云滋垢腻',
'冻雨裛沉绵',
'强饭莼添滑',
'端居茗续煎',
'清思汉水上',
'凉忆岘山巅',
'顺浪翻堪倚',
'回帆又省牵',
'吾家碑不昧',
'王氏井依然',
'几杖将衰齿',
'茅茨寄短椽',
'灌园曾取适',
'游寺可终焉',
'遂性同渔父',
'成名异鲁连',
'篙师烦尔送',
'朱夏及寒泉',
],
},
{
title: '赠韦七赞善',
body: [
'乡里衣冠不乏贤',
'杜陵韦曲未央前',
'尔家最近魁三象',
'时论同归尺五天',
'北走关山开雨雪',
'南游花柳塞云烟',
'洞庭春色悲公子',
'鰕菜忘归范蠡船',
],
},
{
title: '奉酬寇十侍御锡见寄四韵,复寄寇',
body: [
'往别郇瑕地',
'于今四十年',
'来簪御府笔',
'故泊洞庭船',
'诗忆伤心处',
'春深把臂前',
'南瞻按百越',
'黄帽待君偏',
],
},
{
title: '酬郭十五受判官',
body: [
'才微岁老尚虚名',
'卧病江湖春复生',
'药裹关心诗总废',
'花枝照眼句还成',
'只同燕石能星陨',
'自得隋珠觉夜明',
'乔口橘洲风浪促',
'系帆何惜片时程',
],
},
{
title: '衡州送李大夫七丈勉赴广州',
body: [
'斧钺下青冥',
'楼船过洞庭',
'北风随爽气',
'南斗避文星',
'日月笼中鸟',
'乾坤水上萍',
'王孙丈人行',
'垂老见飘零',
],
},
{
title: '哭长孙侍御(一作杜诵诗。以下为杜甫补遗)',
body: [
'道为谋书重',
'名因赋颂雄',
'礼闱曾擢桂',
'宪府旧乘骢',
'流水生涯尽',
'浮云世事空',
'唯馀旧台柏',
'萧瑟九原中',
],
},
{
title: '虢国夫人(一作《张祜集》灵台二首之一)',
body: [
'虢国夫人承主恩',
'平明上马入宫门',
'却嫌脂粉涴颜色',
'澹扫蛾眉朝至尊',
],
},
{
title: '军中醉饮寄沈八、刘叟(一作畅当诗)',
body: [
'酒渴爱江清',
'馀甘漱晚汀',
'软沙欹坐稳',
'冷石醉眠醒',
'野膳随行帐',
'华音发从伶',
'数杯君不见',
'醉已遣沉冥',
],
},
{
title: '杜鹃行(一作司空曙诗)',
body: [
'古时杜宇称望帝',
'魂作杜鹃何微细',
'跳枝窜叶树木中',
'抢佯瞥捩雌随雄',
'毛衣惨黑貌憔悴',
'众鸟安肯相尊崇',
'隳形不敢栖华屋',
'短翮唯愿巢深丛',
'穿皮啄朽觜欲秃',
'苦饥始得食一虫',
'谁言养雏不自哺',
'此语亦足为愚蒙',
'声音咽咽如有谓',
'号啼略与婴儿同',
'口干垂血转迫促',
'似欲上诉于苍穹',
'蜀人闻之皆起立',
'至今斅学效遗风',
'乃知变化不可穷',
'岂知昔日居深宫',
'嫔嫱左右如花红',
],
},
{
title: '闻惠二过东溪特一送(以下七首,吴若本逸诗)',
body: [
'惠子白驹瘦',
'归溪唯病身',
'皇天无老眼',
'空谷滞斯人',
'崖蜜松花熟',
'山杯竹叶新',
'柴门了无事',
'黄绮未称臣',
],
},
{
title: '舟泛洞庭(一作过洞庭湖)',
body: [
'蛟室围青草',
'龙堆拥白沙',
'护江盘古木',
'迎棹舞神鸦',
'破浪南风正',
'收帆畏日斜',
'云山千万叠',
'底处上仙槎',
],
},
{
title: '李盐铁二首(一首题作李监宅,已见第九卷中)',
body: [
'落叶春风起',
'高城烟雾开',
'杂花分户映',
'娇燕入檐回',
'一见能倾产',
'虚怀只爱才',
'盐官虽绊骥',
'名是汉庭来',
],
},
{
title: '长吟',
body: [
'江渚翻鸥戏',
'官桥带柳阴',
'江飞竞渡日',
'草见蹋春心',
'已拨形骸累',
'真为烂漫深',
'赋诗歌句稳',
'不免自长吟',
],
},
{
title: '绝句九首(前六首已见第十三卷中)',
body: [
'闻道巴山里',
'春船正好行',
'都将百年兴',
'一望九江城',
'水槛温江口',
'茅堂石笋西',
'移船先主庙',
'洗药浣沙溪',
'设道春来好',
'狂风大放颠',
'吹花随水去',
'翻却钓鱼船',
],
},
{
title: '瞿唐怀古(以下草堂逸诗拾遗)',
body: [
'西南万壑注',
'勍敌两崖开',
'地与山根裂',
'江从月窟来',
'削成当白帝',
'空曲隐阳台',
'疏凿功虽美',
'陶钧力大哉',
],
},
{
title: '送司马入京',
body: [
'群盗至今日',
'先朝忝从臣',
'叹君能恋主',
'久客羡归秦',
'黄阁长司谏',
'丹墀有故人',
'向来论社稷',
'为话涕沾巾',
],
},
{
title: '惜别行送刘仆射判官(仆射乃其主将刘乃仆射之判官也)',
body: [
'闻道南行市骏马',
'不限匹数军中须',
'襄阳幕府天下异',
'主将俭省忧艰虞',
'只收壮健胜铁甲',
'岂因格斗求龙驹',
'而今西北自反胡',
'骐驎荡尽一匹无',
'龙媒真种在帝都',
'子孙永落西南隅',
'向非戎事备征伐',
'君肯辛苦越江湖',
'江湖凡马多憔悴',
'衣冠往往乘蹇驴',
'梁公富贵于身疏',
'号令明白人安居',
'俸钱时散士子尽',
'府库不为骄豪虚',
'以兹报主寸心赤',
'气却西戎回北狄',
'罗网群马籍马多',
'气在驱驰出金帛',
'刘侯奉使光推择',
'滔滔才略沧溟窄',
'杜陵老翁秋系船',
'扶病相识长沙驿',
'强梳白发提胡卢',
'手把菊花路旁摘',
'九州兵革浩茫茫',
'三叹聚散临重阳',
'当杯对客忍流涕',
'君不觉老夫神内伤',
],
},
{
title: '呀鹘行',
body: [
'病鹘孤飞俗眼丑',
'每夜江边宿衰柳',
'清秋落日已侧身',
'过雁归鸦错回首',
'紧脑雄姿迷所向',
'疏翮稀毛不可状',
'强神迷复皂雕前',
'俊才早在苍鹰上',
'风涛飒飒寒山阴',
'熊罴欲蛰龙蛇深',
'念尔此时有一掷',
'失声溅血非其心',
],
},
{
title: '狂歌行,赠四兄',
body: [
'与兄行年校一岁',
'贤者是兄愚者弟',
'兄将富贵等浮云',
'弟切功名好权势',
'长安秋雨十日泥',
'我曹鞴马听晨鸡',
'公卿朱门未开锁',
'我曹已到肩相齐',
'吾兄睡稳方舒膝',
'不袜不巾蹋晓日',
'男啼女哭莫我知',
'身上须缯腹中实',
'今年思我来嘉州',
'嘉州酒重花绕楼',
'楼头吃酒楼下卧',
'长歌短咏还相酬',
'四时八节还拘礼',
'女拜弟妻男拜弟',
'幅巾鞶带不挂身',
'头脂足垢何曾洗',
'吾兄吾兄巢许伦',
'一生喜怒长任真',
'日斜枕肘寝已熟',
'啾啾唧唧为何人',
],
},
{
title: '逃难',
body: [
'五十头白翁',
'南北逃世难',
'疏布缠枯骨',
'奔走苦不暖',
'已衰病方入',
'四海一涂炭',
'乾坤万里内',
'莫见容身畔',
'妻孥复随我',
'回首共悲叹',
'故国莽丘墟',
'邻里各分散',
'归路从此迷',
'涕尽湘江岸',
],
},
{
title: '寄高適',
body: [
'楚隔乾坤远',
'难招病客魂',
'诗名惟我共',
'世事与谁论',
'北阙更新主',
'南星落故园',
'定知相见日',
'烂漫倒芳尊',
],
},
{
title: '送灵州李判官',
body: [
'犬戎腥四海',
'回首一茫茫',
'血战乾坤赤',
'氛迷日月黄',
'将军专策略',
'幕府盛材良',
'近贺中兴主',
'神兵动朔方',
],
},
{
title: '与严二郎奉礼别',
body: [
'别君谁暖眼',
'将老病缠身',
'出涕同斜日',
'临风看去尘',
'商歌还入夜',
'巴俗自为邻',
'尚愧微躯在',
'遥闻盛礼新',
'山东群盗散',
'阙下受降频',
'诸将归应尽',
'题书报旅人',
],
},
{
title: '巴西驿亭观江涨,呈窦使君二首',
body: [
'转惊波作怒',
'即恐岸随流',
'赖有杯中物',
'还同海上鸥',
'关心小剡县',
'傍眼见扬州',
'为接情人饮',
'朝来减半愁',
'向晚波微绿',
'连空岸脚青',
'日兼春有暮',
'愁与醉无醒',
'漂泊犹杯酒',
'踌躇此驿亭',
'相看万里外',
'同是一浮萍',
],
},
{
title: '遣忧',
body: [
'乱离知又甚',
'消息苦难真',
'受谏无今日',
'临危忆古人',
'纷纷乘白马',
'攘攘著黄巾',
'隋氏留宫室',
'焚烧何太频',
],
},
{
title: '早花',
body: [
'西京安稳未',
'不见一人来',
'腊日巴江曲',
'山花已自开',
'盈盈当雪杏',
'艳艳待春梅',
'直苦风尘暗',
'谁忧容鬓催',
],
},
{
title: '巴山',
body: [
'巴山遇中使',
'云自峡城来',
'盗贼还奔突',
'乘舆恐未回',
'天寒邵伯树',
'地阔望仙台',
'狼狈风尘里',
'群臣安在哉',
],
},
{
title: '收京',
body: [
'复道收京邑',
'兼闻杀犬戎',
'衣冠却扈从',
'车驾已还宫',
'克复成如此',
'安危在数公',
'莫令回首地',
'恸哭起悲风',
],
},
{
title: '巴西闻收宫阙,送班司马入京',
body: [
'闻道收宗庙',
'鸣銮自陕归',
'倾都看黄屋',
'正殿引朱衣',
'剑外春天远',
'巴西敕使稀',
'念君经世乱',
'匹马向王畿',
],
},
{
title: '花底',
body: [
'紫萼扶千蕊',
'黄须照万花',
'忽疑行暮雨',
'何事入朝霞',
'恐是潘安县',
'堪留卫玠车',
'深知好颜色',
'莫作委泥沙',
],
},
{
title: '柳边',
body: [
'只道梅花发',
'那知柳亦新',
'枝枝总到地',
'叶叶自开春',
'紫燕时翻翼',
'黄鹂不露身',
'汉南应老尽',
'霸上远愁人',
],
},
{
title: '送窦九归成都',
body: [
'文章亦不尽',
'窦子才纵横',
'非尔更苦节',
'何人符大名',
'读书云阁观',
'问绢锦官城',
'我有浣花竹',
'题诗须一行',
],
},
{
title: '赠裴南部,闻袁判官自来欲有按问',
body: [
'尘满莱芜甑',
'堂横单父琴',
'人皆知饮水',
'公辈不偷金',
'梁狱书因上',
'秦台镜欲临',
'独醒时所嫉',
'群小谤能深',
'即出黄沙在',
'何须白发侵',
'使君传旧德',
'已见直绳心',
],
},
{
title: '奉使崔都水翁下峡',
body: [
'无数涪江筏',
'鸣桡总发时',
'别离终不久',
'宗族忍相遗',
'白狗黄牛峡',
'朝云暮雨祠',
'所过频问讯',
'到日自题诗',
],
},
{
title: '题郪县郭三十二明府茅屋壁',
body: [
'江头且系船',
'为尔独相怜',
'云散灌坛雨',
'春青彭泽田',
'频惊适小国',
'一拟问高天',
'别后巴东路',
'逢人问几贤',
],
},
{
title: '遣闷戏呈路十九曹长',
body: [
'江浦雷声喧昨夜',
'春城雨色动微寒',
'黄鹂并坐交愁湿',
'白鹭群飞大剧干',
'晚节渐于诗律细',
'谁家数去酒杯宽',
'惟吾最爱清狂客',
'百遍相看意未阑',
],
},
{
title: '随章留后新亭会送诸君',
body: [
'新亭有高会',
'行子得良时',
'日动映江幕',
'风鸣排槛旗',
'绝荤终不改',
'劝酒欲无词',
'已堕岘山泪',
'因题零雨诗',
],
},
{
title: '东津送韦讽摄阆州录事',
body: [
'闻说江山好',
'怜君吏隐兼',
'宠行舟远泛',
'怯别酒频添',
'推荐非承乏',
'操持必去嫌',
'他时如按县',
'不得慢陶潜',
],
},
{
title: '客旧馆',
body: [
'陈迹随人事',
'初秋别此亭',
'重来梨叶赤',
'依旧竹林青',
'风幔何时卷',
'寒砧昨夜声',
'无由出江汉',
'愁绪月冥冥',
],
},
{
title: '阆州奉送二十四舅使自京赴任青城',
body: [
'闻道王乔舄',
'名因太史传',
'如何碧鸡使',
'把诏紫微天',
'秦岭愁回马',
'涪江醉泛船',
'青城漫污杂',
'吾舅意凄然',
],
},
{
title: '愁坐',
body: [
'高斋常见野',
'愁坐更临门',
'十月山寒重',
'孤城月水昏',
'葭萌氐种迥',
'左担犬戎存',
'终日忧奔走',
'归期未敢论',
],
},
{
title: '陪郑公秋晚北池临眺',
body: [
'北池云水阔',
'华馆辟秋风',
'独鹤元依渚',
'衰荷且映空',
'采菱寒刺上',
'蹋藕野泥中',
'素楫分曹往',
'金盘小径通',
'萋萋露草碧',
'片片晚旗红',
'杯酒沾津吏',
'衣裳与钓翁',
'异方初艳菊',
'故里亦高桐',
'摇落关山思',
'淹留战伐功',
'严城殊未掩',
'清宴已知终',
'何补参卿事',
'欢娱到薄躬',
],
},
{
title: '去蜀',
body: [
'五载客蜀郡',
'一年居梓州',
'如何关塞阻',
'转作潇湘游',
'世事已黄发',
'残生随白鸥',
'安危大臣在',
'不必泪长流',
],
},
{
title: '放船',
body: [
'收帆下急水',
'卷幔逐回滩',
'江市戎戎暗',
'山云淰淰寒',
'村荒无径入',
'独鸟怪人看',
'已泊城楼底',
'何曾夜色阑',
],
},
{
title: '哭台州郑司户苏少监',
body: [
'故旧谁怜我',
'平生郑与苏',
'存亡不重见',
'丧乱独前途',
'豪俊何人在',
'文章扫地无',
'羁游万里阔',
'凶问一年俱',
'白首中原上',
'清秋大海隅',
'夜台当北斗',
'泉路著东吴',
'得罪台州去',
'时危弃硕儒',
'移官蓬阁后',
'谷贵没潜夫',
'流恸嗟何及',
'衔冤有是夫',
'道消诗兴废',
'心息酒为徒',
'许与才虽薄',
'追随迹未拘',
'班扬名甚盛',
'嵇阮逸相须',
'会取君臣合',
'宁铨品命殊',
'贤良不必展',
'廊庙偶然趋',
'胜决风尘际',
'功安造化炉',
'从容拘旧学',
'惨澹閟阴符',
'摆落嫌疑久',
'哀伤志力输',
'俗依绵谷异',
'客对雪山孤',
'童稚思诸子',
'交朋列友于',
'情乖清酒送',
'望绝抚坟呼',
'疟病餐巴水',
'疮痍老蜀都',
'飘零迷哭处',
'天地日榛芜',
],
},
{
title: '送王侍御往东川,放生池祖席',
body: [
'东川诗友合',
'此赠怯轻为',
'况复传宗近',
'空然惜别离',
'梅花交近野',
'草色向平池',
'倘忆江边卧',
'归期愿早知',
],
},
{
title: '惠义寺送王少尹赴成都(得峰字)',
body: [
'苒苒谷中寺',
'娟娟林表峰',
'阑干上处远',
'结构坐来重',
'骑马行春径',
'衣冠起晚钟',
'云门青寂寂',
'此别惜相从',
],
},
{
title: '避地',
body: [
'避地岁时晚',
'窜身筋骨劳',
'诗书遂墙壁',
'奴仆且旌旄',
'行在仅闻信',
'此生随所遭',
'神尧旧天下',
'会见出腥臊',
],
},
{
title: '惠义寺园送辛员外',
body: [
'朱樱此日垂朱实',
'郭外谁家负郭田',
'万里相逢贪握手',
'高才却望足离筵',
],
},
{
title: '又送',
body: [
'双峰寂寂对春台',
'万竹青青照客杯',
'细草留连侵坐软',
'残花怅望近人开',
'同舟昨日何由得',
'并马今朝未拟回',
'直到绵州始分首',
'江边树里共谁来',
],
},
{
title: '九日登梓州城',
body: [
'客心惊暮序',
'宾雁下襄州',
'共赏重阳节',
'言寻戏马游',
'湖风秋戍柳',
'江雨暗山楼',
'且酌东篱菊',
'聊祛南国愁',
],
},
{
title: '阙题',
body: ['三月雪连夜', '未应伤物华', '只缘春欲尽', '留著伴梨花'],
},
],
};
<file_sep>/src/app/pie/dict/parser.js
/* eslint-disable no-unused-vars */
const fs = require('fs');
const REGEX_CHINESE = /[\u4e00-\u9fff]|[\u3400-\u4dbf]|[\u{20000}-\u{2a6df}]|[\u{2a700}-\u{2b73f}]|[\u{2b740}-\u{2b81f}]|[\u{2b820}-\u{2ceaf}]|[\uf900-\ufaff]|[\u3300-\u33ff]|[\ufe30-\ufe4f]|[\uf900-\ufaff]|[\u{2f800}-\u{2fa1f}]/u;
const isChinese = (str) => REGEX_CHINESE.test(str);
const readData = (data) => {
let dict = { simplified: {}, traditional: {} };
const lines = data.split('\n');
const chars_pinyin_english = lines.map((line) => {
return line.split('/');
});
const english = chars_pinyin_english.map((word) => {
return word[1];
});
const char_pinyin = chars_pinyin_english.map((word) => {
return word[0];
});
const pinyin = char_pinyin.map((char) => {
let array = char.split('[');
return array[1];
});
const simplifiedChar = char_pinyin.map((char) => {
let array = char.split(' ');
return array[1];
});
const traditionalChar = char_pinyin.map((char) => {
let array = char.split(' ');
return array[0];
});
for (const sChar in simplifiedChar) {
dict.simplified[simplifiedChar[sChar]] = {
pinyin: pinyin[sChar],
english: english[sChar],
};
}
for (const tChar in traditionalChar) {
dict.traditional[traditionalChar[tChar]] = english[tChar];
}
return dict;
};
const dictionary = fs.readFile(
'src/app/pie/dict/cedict_ts.u8',
'utf8',
(err, data) => {
if (err) throw err;
readData(data);
}
);
module.exports = dictionary;
|
140e7ed2edf9ebe602fecb460f5b8a8b1ce6ea8d
|
[
"JavaScript",
"TypeScript"
] | 4
|
TypeScript
|
elijahsciam/ancient-chinese
|
32e45477c6ff4796b5b72276e50abbf048318f1f
|
b59c1d990833c15329592e62735fea7929d99f76
|
refs/heads/master
|
<repo_name>Iced-Tea/star.js<file_sep>/README.md
[](https://badge.fury.io/js/star-correct) [](https://travis-ci.org/Decagon/star.js/branches)
# star.js
[](https://gitter.im/Decagon/star.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
Fixing typos was never easier*. A small javascript npm library to automatically correct typos in messages based on the next message, and it works out of the box, no dependencies. This repository addresses productivity issues, having to manually go back, modify your message, and then resend it. Just type your correction in the next message, followed by a star, and keep your hands on your keyboard. Star.js will fetch the right correction for you.
### Usage:
`starjs.correct(phrase[]);` where `phrase` is a two element array, the first element is the first message, the second is the correction. If there is no corrections to be made (because the correction is too ambigious, or it doesn't need to be corrected) it will return `false`.
### Examples
```
var starjs = require('star-correct');
// Will Output 'I would like to do that today sometime'
console.log(starjs.correct(['I would like to to that today sometime', 'to do*']));
```
Star.js knows when something isn't a correction, even though it is passed in as a correction.
Or, maybe something a little more interesting:
```
var starjs = require('star-correct');
// Will return false, since there is no correction to be made.
console.log(starjs.correct(['I like apples', 'I like oranges, pecans, and strawberries, too.']));
```
#### Examples explained
Star.js is very new, and so most of the features have not been implemented yet. It's meant to replace manual spell checkers, or drop down menus that let you choose a different word. Spell checkers are very good if you have the time, but if you only have one correction to make, they're a bit overkill, especially when you have to use the mouse. All of these examples follow the same syntax as the previous boilerplate example.
Say you're on some sort of internet chat thing, and you type:
*Message:* This is a msg with a tyop in it
*Correction:* typo*
Star.js will replace "tyop" with "typo" because it sounds similar (using soundex) but will not consider msg to be a typo because the replacement does not make sense. Similarly, if I replace a "misspelled" word with another one:
Sometimes, no words are misspelled but instead a context change is needed. If something is typed but contains something incorrect, Star.js can use some of the words in the correction to base its starting position from.
*Message:* My rss isn't working today
*Correction:* rss reader*
*Corrected Message:* My rss reader isn't working today
Here, Star.js uses "rss" as an anchor word, and adds "reader" after it.
(In beta) sometimes, corrections might make a sentence more gramatically correct, but the words have absolutely no relation to any misspellings.
*Message:* He go to store tomorrow
*Correction:* will*
*Corrected Message:* He will go to the store tomorrow
Star.js notices that the word "He" is a null link, and adds the correction to the end, since will is acting as a verb for the proper pronoun "he".
*Message:* Turn left on Main Street, then take a right at 83 Prince Street.
*Correction:* Turn right*
Since the correction begins with "turn" it will go to the first instance of the word "turn" and replace the next word with the next word in the correction. So, the message would read:
*Corrected Message:* Turn right on Main Street, then take a right at 83 Prince Street.
Things can get a bit tricky when working with multiple values that could easily be replaced, such as numbers.
*Message:* I have 34 apples and 83 eggs.
*Correction:* 23*
Here, it is more likely that the user typed "34" instead of "23" because of how close the number keys are on the keyboard compared to the distance from 8 and 3 to 2 and 3.
### Demo
A demo is available at https://decagon.github.io/star.js/ (thanks to @njt1982 for getting the demo working nicely)
### Issues
- punctuation is not preserved if there is more than one punctuation symbol after the word that needs to be replaced
- capitalization is only preserved for the first letter, the rest is ignored
- whitespace is not preserved, but just added (and never subtracted)
- there are, of course a few false positives where star.js can make the new message non-sensical
### Configuring
Just install node with `apt-get install node`, create a new project with `npm init` and just include star.js via `var starjs = require('star-correct');` and you're good to go! See the examples section to see how to get started.
### Browser
I have only tested Star.js in Google Chrome, but it should work with all modern browsers, except possibly IE, since it uses a string function which is not built-in to IE.
### Thanks
- @adamisntdead, for helping publish Star.js to NPM, and making the readme file more readable and attractive
- Stack Overflow (credit in comments) for the levenshtein distance algorthim
<file_sep>/star.js
var starjs = {
correct: function(message) {
// Credit: http://stackoverflow.com/questions/11919065/sort-an-array-by-the-levenshtein-distance-with-best-performance-in-javascript/11958496#11958496
function distance(s, t) {
var d = []; //2d matrix
// Step 1
var n = s.length;
var m = t.length;
if (n == 0) return m;
if (m == 0) return n;
//Create an array of arrays in javascript (a descending loop is quicker)
for (var i = n; i >= 0; i--) d[i] = [];
// Step 2
for (var i = n; i >= 0; i--) d[i][0] = i;
for (var j = m; j >= 0; j--) d[0][j] = j;
// Step 3
for (var i = 1; i <= n; i++) {
var s_i = s.charAt(i - 1);
// Step 4
for (var j = 1; j <= m; j++) {
//Check the jagged ld total so far
if (i == j && d[i][j] > 4) return n;
var t_j = t.charAt(j - 1);
var cost = (s_i == t_j) ? 0 : 1; // Step 5
//Calculate the minimum
var mi = d[i - 1][j] + 1;
var b = d[i][j - 1] + 1;
var c = d[i - 1][j - 1] + cost;
if (b < mi) mi = b;
if (c < mi) mi = c;
d[i][j] = mi; // Step 6
//Damerau transposition
if (i > 1 && j > 1 && s_i == t.charAt(j - 2) && s.charAt(i - 2) == t_j) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
// Step 7
return d[n][m];
}
function isUpperCase(text) {
return (text[0].toUpperCase() == text[0]);
}
if (("/".indexOf(message[0]) > -1) && ("/".indexOf(correction) > -1)) {
return false; // might be a path name
}
wordsOfMessage = message[0].split(" ");
correction = message[1].split("*")[0];
if (wordsOfMessage.length == correction.split(" ").length) {
return correction;
}
if (correction.length == 0) {
return false;
}
correctionMerged = correction;
if (typeof(correction) != "string") {
correctionMerged = correction.join("");
}
if (("!$%().,?;:".indexOf(correction[correction.length - 1]) > -1)) {
if (correctionMerged.length == 1) {
// entire correction is to fix punctuation
wordsOfMessage = wordsOfMessage.join(" ");
wordsOfMessage[wordsOfMessage.length - 1] = correction;
return wordsOfMessage;
}
}
if (correction[correction.length - 1] == ":") {
return false; // a :* face
}
if ((wordsOfMessage.length == 1) && (correction.length == 1) && (wordsOfMessage[0] == correction[0])) {
return false;
}
oldIndex = 0;
oldDistance = 10000;
for (var i = 0; i < wordsOfMessage.length; i++) {
newDistance = distance(wordsOfMessage[i],correction);
if ((newDistance < oldDistance)&&(newDistance != 0)) {
oldDistance = newDistance;
oldIndex = i;
}
}
prevWord = wordsOfMessage[oldIndex];
punctuation = (prevWord.substr(prevWord.length - 1));
if (!("!$%().,?;:".indexOf(punctuation) > -1)) {
punctuation = "";
}
// if the levenstein distance is too far, cancel early
if (oldDistance > 4) { return false; }
// match case
correction = correction.split("");
if (isUpperCase(wordsOfMessage[oldIndex])) {
correction[0] = correction[0].toUpperCase();
} else {
correction[0] = correction[0].toLowerCase();
}
correction = correction.join("");
wordsOfMessage[oldIndex] = correction + punctuation;
return wordsOfMessage.join(" ");
},
soundex: function(str) {
str = str.toString();
str = str.toUpperCase();
str = str.split('');
var firstLetter = str[0];
// convert letters to numeric code
for (var i = 0; i < str.length; i++) {
switch (str[i]) {
case 'B':
case 'F':
case 'P':
case 'V':
str[i] = '1';
break;
case 'C':
case 'G':
case 'J':
case 'K':
case 'Q':
case 'S':
case 'X':
case 'Z':
str[i] = '2';
break;
case 'D':
case 'T':
str[i] = '3';
break;
case 'L':
str[i] = '4';
break;
case 'M':
case 'N':
str[i] = '5';
break;
case 'R':
str[i] = '6';
break;
default:
str[i] = '0';
break;
}
}
// remove duplicates
var output = firstLetter;
for (var i = 1; i < str.length; i++)
if (str[i] != str[i-1] && str[i] != '0')
output += str[i];
// pad with 0's or truncate
output = output + "0000";
return output.substring(0, 4);
}
};
module.exports = starjs;
|
6a4a1c67ce348935885f9de300eb79dfac5302c5
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Iced-Tea/star.js
|
6bcdb9b2eea200b6e96b2adfdd56648f28c8357e
|
6f04da71f2af9ebf3210c10816b4211aa069c7de
|
refs/heads/master
|
<file_sep>package Livraria.Teste;
import java.util.List;
import Livraria.Autor;
import Livraria.Produtos.Ebook;
import Livraria.Produtos.Livro;
import Livraria.Produtos.LivroFisico;
import Livraria.Produtos.Produto;
public class RegistroDeVenda {
public static void main(String[] args) {
// TODO Auto-generated method stub
Autor autor = new Autor();
autor.setNome("<NAME>");
Livro lf = new LivroFisico(autor);
lf.setNome("TDD impresso");
lf.setValor(59.90);
lf.AplicarDescontoPadrao();
Livro book = new Ebook(autor);
book.setNome("TDD digital");
book.setValor(19.90);
CarrinhoDeCompra carrinho = new CarrinhoDeCompra();
carrinho.Adiciona(lf);
carrinho.Adiciona(book);
List<Produto> produtos = carrinho.getProdutos();
for(Produto p :produtos )
{
System.out.println(p);
}
}
}
<file_sep>package Livraria;
public class ErrorException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = 1L;
public ErrorException(String msg)
{
super(msg);
}
}
<file_sep>package Livraria.Produtos;
import Livraria.Autor;
public class MiniLivro extends Livro {
public MiniLivro(Autor autor) {
super(autor);
// TODO Auto-generated constructor stub
}
@Override
public double getValor() {
// TODO Auto-generated method stub
return 0;
}
@Override
public double AplicarDescontoDe(double porcentagem) {
// TODO Auto-generated method stub
if (porcentagem > 0.3) {
// throw new Exception("Desconto não permitido");
}
double desconto = getValor() * porcentagem;
setValor(getValor() - desconto);
System.out.println("aplicando desconto");
return getValor();
}
}
<file_sep>package Livraria.Teste;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import Livraria.Autor;
import Livraria.Produtos.Livro;
import Livraria.Produtos.LivroFisico;
public class CapOne {
public static void main(String[] args) {
// TODO Auto-generated method stub
Autor autor = new Autor();
autor.setNome("renato");
Livro javaOO = new LivroFisico(autor);
javaOO.setNome("JAVA OO");
Livro java8 = new LivroFisico(autor);
java8.setNome("RUBY");
Livro javaP = new LivroFisico(autor);
javaP.setNome("JAVA Patterns");
List<Livro> livros = Arrays.asList(javaOO,java8 , javaP);
// livros.forEach(l-> System.out.println(l.getNome()));
List<Livro> stream = livros.stream().filter(l-> l.getNome().contains("JAVA")).collect(Collectors.toList()); ;
stream.forEach(l-> System.out.println(l.getNome()));
}
}
|
5f03fbcee6e4cc8585d885381bc478a39dde8663
|
[
"Java"
] | 4
|
Java
|
renatocantarino/DesbravandoJavaOO
|
659bb770de4d860d61b7243c7a6907ae9de04ac0
|
11d79d1996f8053e8e87b53e5e317043b76ce61f
|
refs/heads/master
|
<file_sep>#define PIN_ECHO 8 // Echo Pin
#define PIN_TRIG 9 // Trigger Pin
#define DISTANCE_MIN 0 //May want to set to 2 if needed as that is the sensor's actual minimum
#define DISTANCE_MAX 400 //Max effective range of sensor in cm
#define DISTANCE_INVALID -1
double duration, distance; // Duration used to calculate distance
void setup() {
Serial.begin (9600);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
}
void loop() {
//Reset to LOW
digitalWrite(PIN_TRIG, LOW);
delayMicroseconds(2);
//10uS High trigger to tell HC-SR04 to start a 8-cycle sonic burst as stated in datasheet
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
//HC-SR04's result is in a form of a pulse. Time of pulse = time sound takes from emission to receipt
//PulseIn() measures the amount of time a signal remains high
duration = pulseIn(PIN_ECHO, HIGH);
//Calculate the distance (in cm) based on datasheet formula
distance = duration / 58;
//Sensor can return garbage data if out of range so we check against that
if(distance < DISTANCE_MIN || distance > DISTANCE_MAX){
distance = DISTANCE_INVALID;
}
Serial.println(distance);
delay(50);
}
<file_sep># ultrasonic-hc-sr04-usage
Class materials for teaching the use of the HC-SR04 ultrasonic distance sensor with an Arduino Uno
My slides are available on slideshare in the picture link below.
[](http://www.slideshare.net/yeokm1/hcsr04-ultrasonic-sensor-with-arduino)
###Parts Used
1. Arduino Uno R3
2. USB cable
3. HC-SR04 ultrasonic distance sensor
4. Breadboard
5. 4 jumper wires

Fritzing schematic diagram.
##Software/Libraries/References
1. Tested on Arduino IDE 1.6.7
2. [Original reference code and schematic](http://arduinobasics.blogspot.sg/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html)
|
22ea12b216ee773b6f031340168874dc7a48a3f1
|
[
"Markdown",
"C++"
] | 2
|
C++
|
SustainableLivingLab/ultrasonic-hc-sr04-usage
|
f7f7759e147cda62e19685379565773889c58a01
|
7f3753f640d2cfc6b655546db8cf641596ce89f2
|
refs/heads/master
|
<file_sep>import java.util.ArrayList;
public class MainMenu {
public static void main(final String args[]) {
final OliveGardenMenu oliveGardenMenu = new OliveGardenMenu();
final SubwayMenu subwayMenu = new SubwayMenu();
final ArrayList<Menu> menus = new ArrayList<Menu>();
menus.add(oliveGardenMenu);
menus.add(subwayMenu);
final Cashier cashier = new Cashier(menus);
cashier.printMenu();
}
}<file_sep>import java.util.Iterator;
public class SubwayMenu implements Menu {
static final int MAX_ITEMS = 6;
int numberOfItems = 0;
MenuItem[] menuItems;
public SubwayMenu() {
menuItems = new MenuItem[MAX_ITEMS];
addItem("BBQ Rib",
"Tender pork topped with sweet BBQ sauce, crisp lettuce, onions, and tangy pickles.", false, 8.99);
addItem("Tuna",
"Classic tuna sandwich with creamy mayo, topped with your choice of crisp veggies.", false, 7.49);
addItem("Steak & Cheese",
"Steak topped with melty cheese, veggies, and your choice of sauce.", false, 12.49);
addItem("Spicy Italian",
"Pepperoni and Genoa salami, piled with cheese, veggies, and your favorite sauce.",
false, 9.99);
addItem("Black Forest Ham",
"Black forest ham, topped with veggies and tasty vinaigrette.", false, 7.99);
addItem("Meatball Marinara",
"Irresistible marinara topped meatballs, with parmesan cheese, and whatever else you want.",
false, 10.99);
}
public void addItem(String name, String description,
boolean vegetarian, double price)
{
MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
if (numberOfItems >= MAX_ITEMS) {
System.err.println("Sorry, menu is full! Can't add item to menu");
} else {
menuItems[numberOfItems] = menuItem;
numberOfItems = numberOfItems + 1;
}
}
public MenuItem[] getMenuItems() {
return menuItems;
}
public Iterator<MenuItem> createIterator() {
return new SubwayMenuIterator(menuItems);
}
}
|
0646288526f69fa624080989f95f35250db818f4
|
[
"Java"
] | 2
|
Java
|
saintsavon/IteratorPattern
|
5fac4667e3371ebe5ff993cb94bc2897e7d23835
|
05a11ab6f11a7591a6583438b563bc798ed9d1ff
|
refs/heads/master
|
<file_sep># subscan
利用查询啦接口,chinaz,ip138接口,百度云观测接口查询子域名
<file_sep>import socket
socket.setdefaulttimeout(0.5)
with open('eastmoney.com(filtered).txt') as f:
for line in f.readlines():
host = line
ip = socket.gethostbyname(host)
print(host,ip)<file_sep>import requests
import re
import base64
import inspect
import sys
import socket
from time import sleep
from multiprocessing.dummy import Pool as ThreadPool
class SubDomain:
def __init__(self,url):
self.url = url
self.subs_filtered = []
self.subs_filtered_domain = []
self.ports = []
self.headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36',
'Referer':'http://www.baidu.com/',
}
socket.setdefaulttimeout(0.5)
self.subs = self._get_all()
self._save()
#查询啦接口,容易被封,TMD
def chaxunla(self):
print('[+] 正在使用 '+inspect.stack()[0][3]+' 接口')
sub = []
res = requests.get('http://api.chaxun.la/toolsAPI/getDomain/?k={}&action=moreson'.format(self.url),headers=self.headers)
res = res.json()
if "status" in res and res['status']==3:
print('[+] 查询啦接口可能出现问题!')
print('[+] '+res['message'])
else:
while True:
page = 1
res = requests.get('http://api.chaxun.la/toolsAPI/getDomain/?k={}&action=moreson&page={}'.format(self.url,page),headers=self.headers)
res = res.json()
if(res['status']==-2):
break
for i in res['data']:
sub.append(i['domain'])
if len(res['data'<100]):
break
page += 1
sleep(1)
print('[+] '+inspect.stack()[0][3]+' 接口查询完毕: 共 '+str(len(sub))+' 条')
return sub
#chinaz
def chinaz(self):
print('[+] 正在使用 '+inspect.stack()[0][3]+' 接口')
subs = []
res = requests.get('http://tool.chinaz.com/subdomain?domain='+self.url,headers=self.headers)
p = re.compile(r'<span class="col-gray02">[\u4e00-\u9fa5](\d)[\u4e00-\u9fa5]')
#print(res.text)
#获取页数
if len(p.findall(res.text))>=1:
page = int(p.findall(res.text)[0])
#获取子域名
for i in range(1,page+1):
res = requests.get('http://tool.chinaz.com/subdomain?domain={}&page={}'.format(self.url,i),headers=self.headers)
p = re.compile(r'target="_blank">(.*?)</a></div>')
sub = p.findall(res.text)
subs.extend(sub)
sleep(0.5)
if(len(subs)==0):
print('[+] chinaz接口可能出现问题!')
print('[+] '+inspect.stack()[0][3]+' 接口查询完毕: 共 '+str(len(subs))+' 条')
return subs
#ip138接口
def ip138(self):
print('[+] 正在使用 '+inspect.stack()[0][3]+' 接口')
res = requests.get('http://site.ip138.com/{}/domain.htm'.format(self.url),headers=self.headers)
p = re.compile(r'target="_blank">(.*?)</a></p>')
sub = p.findall(res.text)
#print(res.text)
if(len(sub)==0):
print('[+] ip138接口可能出现问题!')
print('[+] '+inspect.stack()[0][3]+' 接口查询完毕: 共 '+str(len(sub))+' 条')
return sub
#fofa api,要钱的
def fofa_api(self):
print('[+] 正在使用 '+inspect.stack()[0][3]+' 接口')
email = '<EMAIL>'
key = '36e9d7c4f23a45a5f0b3e6650157e6f0'
size = 50
s = 'domain=\"{}\"'.format(self.url)
s = base64.b64encode(s.encode())
res = requests.get('https://fofa.so/api/v1/search/all?email={}&key={}&qbase64={}&size={}'.format(email,key,s,size))
res = res.json()
if "error" in res and res["error"]==True:
print('[+] fofa api可能出现问题!')
return res["errmsg"]
else:
return res
#百度云观测接口,暂时只爬取子域名
def baidu(self):
print('[+] 正在使用 '+inspect.stack()[0][3]+' 接口')
sub = []
res = requests.get('http://ce.baidu.com/index/getRelatedSites?site_address='+self.url,headers=self.headers)
res = res.json()
for i in res['data']:
sub.append(i['domain'])
print('[+] '+inspect.stack()[0][3]+' 接口查询完毕: 共 '+str(len(sub))+' 条')
return sub
#汇总并去重,暂时没有fofa api,因为我没钱
def _get_all(self):
subs = []
#sub = self.chaxunla()
#subs.extend(sub)
sub = self.chinaz()
subs.extend(sub)
sub = self.ip138()
subs.extend(sub)
sub = self.baidu()
subs.extend(sub)
#去重
subs = list(set(subs))
print('[+] 去重完毕: 共 '+str(len(subs))+' 条')
return subs
#save the results
def _save(self):
filename = self.url + '.txt'
with open(filename,'w') as f:
for i in self.subs:
f.write(i+'\n')
print('[+] 运行完毕,结果保存至 '+filename)
def filter(self):
print('[+] 正在过滤无法访问的子域名...')
filename = self.url+'(filtered).txt'
scan_pool = ThreadPool(processes = 16)
scan_pool.map(self.is_use,self.subs)
scan_pool.close()
scan_pool.join()
with open(filename,'w',encoding='utf-8') as f:
for i in self.subs_filtered_domain:
f.write(i+'\n')
print('[+] 过滤后还剩: '+str(len(self.subs_filtered)))
print('[+] 结果保存至 '+filename)
def is_use(self,site):
p = re.compile(r'<title>(.*?)</title>')
try:
res = requests.get('http://'+site,timeout=3,headers=self.headers)
#print(res.encoding)
res.encoding='utf-8'
title = p.findall(res.text)[0]
print(site,res.status_code,title)
self.subs_filtered.append(site+'\t'+str(res.status_code)+'\t'+title+'\n')
self.subs_filtered_domain.append(site)
except Exception as e:
print(e)
def scan_port(self):
print('[+] 正在扫描端口...')
filename = self.url+'-ports.txt'
scan_pool = ThreadPool(processes = 16)
scan_pool.map(self.is_open,self.subs_filtered_domain)
scan_pool.close()
scan_pool.join()
print('[+] End!')
def is_open(self,site):
for port in self.ports:
try:
s = socket.socket(2,1)
res = s.connect_ex((site,port))
if res == 0:
print('Site: {} Port {}: OPEN'.format(site,port))
except Exception as e:
print(e)
s.close()
if __name__=='__main__':
if len(sys.argv)==1:
print('[+] 使用方法: python '+sys.argv[0]+' baidu.com')
print('[+] 可选参数:\n[1] -f\n\t加了之后会过滤无法访问的子域名,如果加必须加在末尾')
elif len(sys.argv)==2:
t = SubDomain(sys.argv[1])
elif len(sys.argv)==3 and sys.argv[2]=='-f':
t = SubDomain(sys.argv[1])
print(t.subs)
t.filter()
elif len(sys.argv)==3 and sys.argv[2]=='-p':
t = SubDomain(sys.argv[1])
print(t.subs)
t.filter()
t.scan_port()
else:
print('参数错误!')
|
78b98528d23ceb868283956ff9a8e3434d88c640
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
huyuanzhi2/subscan
|
328bbbb81e4f4b2346553235321dedc12abb0f53
|
be21334e2e395cf516ebc63548f4e17572bd9eea
|
refs/heads/master
|
<repo_name>talbn1/Insurance_queue<file_sep>/src/main/java/com/talbn1/insurancequeue/InsurancequeueApplication.java
package com.talbn1.insurancequeue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class InsurancequeueApplication {
public static void main(String[] args) {
SpringApplication.run(InsurancequeueApplication.class, args);
}
}
<file_sep>/src/test/java/com/talbn1/insurancequeue/InsurancequeueApplicationTests.java
package com.talbn1.insurancequeue;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class InsurancequeueApplicationTests {
@Test
void contextLoads() {
}
}
|
bea8b04f8285d8c9ad1d6371f823dee61740efbe
|
[
"Java"
] | 2
|
Java
|
talbn1/Insurance_queue
|
e647597d6ca7d7cbd5f4fc8c2ba01cd0d6b1bc2f
|
56219a8706646a61b4e9646210fe5d8e8b931f7c
|
refs/heads/master
|
<repo_name>gaodazhu/gk-auto-connector<file_sep>/readme.md
#instroduction
This is a node-webkit project for industrial machine monitor!
It receives messages from auto-collections program!<file_sep>/testleveldwon.js
/**
* Created by gaozhu on 2015/4/10.
*/
leveldown = require("leveldown345");
leveldown("./db");
|
6765142cfa2f8d124aa6141ef799abcff8f92c21
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
gaodazhu/gk-auto-connector
|
427b38df4a738f08c10d532ff0f399bb3daa452a
|
a7e2bf6753fa3e5a26e12279a9fece9fdd3593c8
|
refs/heads/master
|
<file_sep>package xr_algorithm_stack_queue;
import java.util.Stack;
/**
* 用两个栈实现队列的操作
* 先进先出
* @author X.R
*
*/
public class StackToQueueTest {
public static class MyStack{
private Stack<Integer> stack;
public MyStack(){
this.stack = new Stack<Integer>();
}
public void push(int num){
this.stack.push(num);
}
public int pop(){
return this.stack.pop();
}
}
public static class Queue{
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public Queue(){
this.stack1 = new Stack<Integer>();
this.stack2 = new Stack<Integer>();
}
public void add(int num){
stack1.push(num);
}
//返回第一个元素 但不出栈
public int poll(){
if(!this.stack2.isEmpty()&&!this.stack1.isEmpty()){
System.out.println("Error!");
}else if(this.stack2.isEmpty()){
while(!this.stack1.isEmpty()){
this.stack2.push(this.stack1.pop());
}
}
return this.stack2.pop();
}
//进栈
public int peek(){
if(!this.stack2.isEmpty()&&!this.stack1.isEmpty()){
System.out.println("Error!");
}else if(this.stack2.isEmpty()){
while(!this.stack1.isEmpty()){
this.stack2.push(this.stack1.pop());
}
}
return this.stack2.peek();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyStack myStack = new MyStack();
myStack.push(3);
myStack.push(4);
myStack.push(1);
myStack.push(2);
myStack.push(5);
System.out.println("栈为:");
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println("==============");
Queue myQueue = new Queue();
myQueue.add(3);
myQueue.add(4);
myQueue.add(1);
myQueue.add(2);
myQueue.add(5);
System.out.println("队列为:");
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
}
}
<file_sep>package xr_algorithm_stack_queue;
import java.util.Scanner;
import java.util.Stack;
/**
* 设计一个有getMin的功能的栈
*
* 利用两个栈
*
* @author X.R
*
*/
public class GetMinTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyStack1 stack1 = new MyStack1();
stack1.push(3);
System.out.println("当前栈的最小值为:" + stack1.getMin());
stack1.push(4);
System.out.println("当前栈的最小值为:" + stack1.getMin());
stack1.push(1);
System.out.println("当前栈的最小值为:" + stack1.getMin());
System.out.println("当前栈的栈顶为:" + stack1.pop());
System.out.println("当前栈的最小值为:" + stack1.getMin());
System.out.println("*****第二种方法*****");
MyStack2 stack2 = new MyStack2();
stack2.push(3);
System.out.println("当前栈的最小值为:" + stack2.getMin());
stack2.push(4);
System.out.println("当前栈的最小值为:" + stack2.getMin());
stack2.push(1);
System.out.println("当前栈的最小值为:" + stack2.getMin());
System.out.println("当前栈的栈顶为:" + stack2.pop());
System.out.println("当前栈的最小值为:" + stack2.getMin());
}
public static class MyStack1 {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyStack1() {
this.stack1 = new Stack<Integer>();
this.stack2 = new Stack<Integer>();
}
// 进栈
public void push(int num) {
if (this.stack2.isEmpty()) {
this.stack2.push(num);
} else if (num <= this.getMin()) {
this.stack2.push(num);
}
this.stack1.push(num);
}
// 出栈
public int pop() {
if (this.stack1.isEmpty()) {
System.out.println("Error!");
}
int temp = this.stack1.peek();
if (temp == this.getMin()) {
this.stack2.pop();
}
return temp;
}
// 取得最小元素
private int getMin() {
// TODO Auto-generated method stub
if (this.stack2.isEmpty()) {
System.out.println("Error!");
}
return this.stack2.peek();
}
}
public static class MyStack2 {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyStack2() {
this.stack1 = new Stack<Integer>();
this.stack2 = new Stack<Integer>();
}
// 进栈
public void push(int num) {
if (this.stack2.isEmpty()) {
this.stack2.push(num);
} else if (num < this.getMin()) {
this.stack2.push(num);
} else if (num >= this.getMin()) {
int value = this.stack2.peek();
this.stack2.push(value);
}
this.stack1.push(num);
}
// 出栈
public int pop() {
if (this.stack1.isEmpty()) {
System.out.println("Error!");
}
int temp = this.stack1.peek();
if (temp == this.getMin()) {
this.stack2.pop();
}
return temp;
}
// 取得最小元素
private int getMin() {
// TODO Auto-generated method stub
if (this.stack2.isEmpty()) {
System.out.println("Error!");
}
return this.stack2.peek();
}
}
}
|
3149c7dff9162e962442f2ee449deeb6f5f96e4c
|
[
"Java"
] | 2
|
Java
|
IamXiaRui/JavaSE_Demo_Algorithm
|
02ed52924871c33f79c2adb9a615b596a8094475
|
9b50a4174ba32748483cf9600a9a19cbbfae2a35
|
refs/heads/master
|
<repo_name>msaha-finomial/movie-maker<file_sep>/FileDownloader/FileDownloader/AzureKeyVaultClient.cs
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileDownloader
{
public class AzureKeyVaultClient
{
private static async Task<string> GetAzureKeyVaultAccessToken(string authority, string resource, string scope)
{
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(
ConfigurationManager.AppSettings["AADClientId"],
ConfigurationManager.AppSettings["AADClientSecret"]);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
{
return null;
}
return result.AccessToken;
}
public async Task<string> GetToken(string key)
{
string url = "https://abootkakv.vault.azure.net/secrets/";
url = url + key;
// Create KeyVaultClient with vault credentials
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAzureKeyVaultAccessToken));
// Get a SAS token for our storage from Key Vault
var sasToken = await kv.GetSecretAsync(url);
return sasToken.Value;
}
}
}
<file_sep>/README.md
# movie-maker
Open the solution file AudioVideoMaker.sln.
Make AudioVideoMaker project as startup project.
Post in slack channel.
Run the application.<file_sep>/FileDownloader/FileDownloader/BlobStorageClient.cs
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileDownloader
{
public class BlobStorageClient
{
public static string GetPath(string filename)
{
string saveTo = Path.GetDirectoryName(Environment.CurrentDirectory) + @"\temp\"; //Folder to Save
if (!Directory.Exists(saveTo))
{
Directory.CreateDirectory(saveTo);
}
return saveTo + filename;
}
string containerName = "bootcampdocs";
string blobEndpoint = "https://abootkstorage.blob.core.windows.net/";
string blobSecurityToken = "<PASSWORD>";
public async Task<string> UploadImage(byte[] document, string fileName)
{
try
{
AzureKeyVaultClient _client = new AzureKeyVaultClient();
var token = await _client.GetToken(blobSecurityToken);
var creds = new StorageCredentials(token);
var accountWithSas = new CloudStorageAccount(creds, new Uri(blobEndpoint), null, null, null);
var blobClientWithSas = accountWithSas.CreateCloudBlobClient();
var container = blobClientWithSas.GetContainerReference(containerName);
container.CreateIfNotExists();
var blob = container.GetBlockBlobReference(fileName);
blob.Properties.ContentType = @"image\jpeg";
await blob.UploadFromByteArrayAsync(document, 0, document.Length);
return string.Format("{0}/{1}", containerName, fileName);
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<string> DownloadImage(string fileName)
{
try
{
AzureKeyVaultClient _client = new AzureKeyVaultClient();
var token = await _client.GetToken(blobSecurityToken);
var creds = new StorageCredentials(token);
var accountWithSas = new CloudStorageAccount(creds, new Uri(blobEndpoint), null, null, null);
var blobClientWithSas = accountWithSas.CreateCloudBlobClient();
var container = blobClientWithSas.GetContainerReference(containerName);
var blob = container.GetBlockBlobReference(fileName);
blob.Properties.ContentType = @"image\jpeg";
blob.DownloadToFile(GetPath(fileName), FileMode.Create);
return string.Format("{0}/{1}", containerName, fileName);
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<string> UploadVideo(byte[] video, string videoFilename)
{
try
{
AzureKeyVaultClient _client = new AzureKeyVaultClient();
var token = await _client.GetToken(blobSecurityToken);
var creds = new StorageCredentials(token);
var accountWithSas = new CloudStorageAccount(creds, new Uri(blobEndpoint), null, null, null);
var blobClientWithSas = accountWithSas.CreateCloudBlobClient();
var container = blobClientWithSas.GetContainerReference(containerName);
container.CreateIfNotExists();
var blob = container.GetBlockBlobReference(videoFilename);
blob.Properties.ContentType = @"video/x-msvideo";
await blob.UploadFromByteArrayAsync(video, 0, video.Length);
return string.Format("{0}/{1}", containerName, videoFilename);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
<file_sep>/FileDownloader/FileDownloader/Class1.cs
using Microsoft.Azure;
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.RetryPolicies;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileDownloader
{
public class Class1
{
public enum ContainerCategory
{
TenantSpecific,
OCR,
Internal,
Public,
Others
}
public string GetContainerName(ContainerCategory containerCategory)
{
switch (containerCategory)
{
case ContainerCategory.OCR:
string ocrContainerName = CloudConfigurationManager.GetSetting("OcrContainerName");
if (!string.IsNullOrEmpty(ocrContainerName))
{
return ocrContainerName;
}
return "ocr";
default:
string docContainerName = CloudConfigurationManager.GetSetting("DocContainerName");
if (!string.IsNullOrEmpty(docContainerName))
{
return docContainerName;
}
return "docs";
}
}
private static async Task<string> GetAzureKeyVaultAccessToken(string authority, string resource, string scope)
{
string clientId = ConfigurationManager.AppSettings["AADClientId"];
string clientSecret = ConfigurationManager.AppSettings["AADClientSecret"];
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
{
//ErrorAquiringAzureKeyVaultAuthenticationToken(authority, resource);
throw new InvalidOperationException();
}
return result.AccessToken;
}
public string RemoveContainerName(string filePath)
{
int firstIndex = filePath.IndexOf('/');
if (firstIndex > 0)
{
return filePath.Substring(firstIndex + 1);
}
return filePath;
}
public string GetContainerName(string filePath)
{
int firstIndex = filePath.IndexOf('/');
if (firstIndex > 0)
{
return filePath.Substring(0, firstIndex);
}
else
{
return null;
}
}
private async Task<ICloudBlob> DownloadEncryptedBlobReferenceFromServerAsync(string filePath, string blobStorageAccountName, string blobStorageKey, bool isSecondary = false)
{
//LogDownloadInfo("DownloadEncryptedBlobReferenceFromServerAsync");
var creds = new StorageCredentials(blobStorageAccountName, blobStorageKey);
var storageAccount = new CloudStorageAccount(creds, true);
string containerName = GetContainerName(filePath) ?? GetContainerName(ContainerCategory.TenantSpecific);
var resolver = new KeyVaultKeyResolver(GetAzureKeyVaultAccessToken);
var client = storageAccount.CreateCloudBlobClient();
var container = client.GetContainerReference(containerName);
var downloadOptions = new BlobRequestOptions();
downloadOptions.EncryptionPolicy = new BlobEncryptionPolicy(null, resolver);
downloadOptions.RequireEncryption = true;
if (isSecondary)
{
client.DefaultRequestOptions = downloadOptions;
downloadOptions.LocationMode = LocationMode.SecondaryOnly;
//LogDownloadInfo("Blob Location Mode Secondary inside DownloadEncryptedBlobReferenceFromServerAsync ");
}
else
{
downloadOptions.LocationMode = LocationMode.PrimaryOnly;
//LogDownloadInfo("Blob Location Mode Primary inside DownloadEncryptedBlobReferenceFromServerAsync ");
}
ICloudBlob blob = await container.GetBlobReferenceFromServerAsync(RemoveContainerName(filePath), null, downloadOptions, null);
if (isSecondary)
{
//Log Storage Uri
string storageUri = !string.IsNullOrEmpty(blob.StorageUri.SecondaryUri.ToString()) ? blob.StorageUri.SecondaryUri.ToString() : blob.StorageUri.PrimaryUri.ToString();
//LogStorageInfo("Got Blob reference Successfully from location : " + storageUri);
//Log Storage Replication Status
//LogServiceStatus(client);
}
return blob;
}
}
}
<file_sep>/AudioVideoMaker/SlackMessage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace AudioVideoMaker
{
[XmlType(AnonymousType = true)]
[XmlRoot("SlackMessage", Namespace = "http://www.example.com/schemas/TestNamespace/Interface6/Schema.xsd", IsNullable = false)]
[Serializable]
public class SlackMessage
{
[XmlElement]
public string text { get; set; }
[XmlElement]
public string filePath { get; set; }
[XmlElement]
public bool isFile { get; set; }
}
}
<file_sep>/AudioMaker/Azure.SpeechToText/Program.cs
using Microsoft.CognitiveServices.SpeechRecognition;
using System;
using System.IO;
using System.Media;
using System.Threading;
using static Azure.SpeechToText.InputOptions;
namespace Azure.SpeechToText
{
public class Program
{
static String audioSavePath = "";
static string filename = "audio.wav";
private static void initialize()
{
string saveTo = Path.GetDirectoryName(Environment.CurrentDirectory) + @"\audio\"; //Folder to Save
if (!Directory.Exists(saveTo))
{
Directory.CreateDirectory(saveTo);
}
audioSavePath = saveTo + filename;//@"\MSaha" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".wav";
}
static void Main(string[] args)
{
initialize();
string text = "Hi this is Krishna from Finomial Technology pvt. Ltd., I hope you like my demo";
TextToSpeech(text);
Console.Read();
}
private static void TextToSpeech(String text)
{
try
{
var srService = new TextToSpeechService(Constants.Speech_API_Key);
srService.OnAudioAvailable += SaveAudio;
srService.OnError += ErrorHandler;
Authorization auth = new Authorization(Constants.Speech_API_Key);
var authToken = auth.GetAuthorizationTokenAsync().Result;
var inputOptions = new InputOptions()
{
RequestUri = new Uri(Constants.BASE_URI + "synthesize"),
Text = text,
Locale = "en-US",
VoiceName = "Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)",
OutputFormat = AudioOutputFormat.Riff16Khz16BitMonoPcm,
AuthorizationToken = "Bearer " + authToken,
};
srService.Speak(CancellationToken.None, inputOptions).Wait();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
private static void SaveAudio(object sender, GenericEventArgs<Stream> args)
{
Stream readStream = args.EventData;
try
{
FileStream writeStream = File.Create(audioSavePath);
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytestoRead = readStream.Read(buffer, 0, Length);
while (bytestoRead > 0)
{
writeStream.Write(buffer, 0, bytestoRead);
bytestoRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
//Play audio
//SoundPlayer player = new System.Media.SoundPlayer(filename);
//player.PlaySync();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
args.EventData.Dispose();
}
}
private static void ErrorHandler(object sender, GenericEventArgs<Exception> e)
{
Console.WriteLine("Unable to complete the TTS request: [{0}]", e.ToString());
}
}
}
<file_sep>/AudioVideoMaker/QueueDownloader.cs
using FileDownloader;
using Microsoft.ServiceBus.Messaging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace AudioVideoMaker
{
public class QueueDownloader
{
public String GetBody(BrokeredMessage brokeredMessage)
{
Stream stream = brokeredMessage.GetBody<Stream>();
StreamReader reader = new StreamReader(stream);
string s = reader.ReadToEnd();
return s;
}
public async Task<string> DownloadFromQueue()
{
BlobStorageClient blobClient = new BlobStorageClient();
string connectionString = Convert.ToString(ConfigurationManager.AppSettings["ServiceBus.ConnectionString"]);
QueueClient qClient = QueueClient.CreateFromConnectionString(connectionString);
// Continuously process messages sent to the "TestQueue"
StringBuilder sb = new StringBuilder();
BrokeredMessage message = null;
do
{
message = qClient.Receive();
if (message != null)
{
try
{
String msg = message.GetBody<String>();
var slMsg = Newtonsoft.Json.JsonConvert.DeserializeObject<SlackMessage>(msg);
if (!String.IsNullOrEmpty(slMsg.filePath))
{
string fn = Path.GetFileName(slMsg.filePath);
var res = await blobClient.DownloadImage(fn);
Console.WriteLine("File found :" + slMsg.filePath);
}
else if (!String.IsNullOrEmpty(slMsg.text) && !String.IsNullOrWhiteSpace(slMsg.text))
{
Console.WriteLine("Text found :" + slMsg.text);
sb.Append(slMsg.text);
if (!slMsg.text.EndsWith("."))
{
sb.Append(". ");
}
}
message.Complete();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
// Indicate a problem, unlock message in queue
message.Abandon();
}
}
} while (message != null);
string textString = sb.ToString();
return textString;
}
}
}
<file_sep>/AudioMaker/Azure.SpeechToText/AudioGenerator.cs
using Microsoft.CognitiveServices.SpeechRecognition;
using System;
using System.IO;
using System.Media;
using System.Threading;
using static Azure.SpeechToText.InputOptions;
namespace Azure.SpeechToText
{
public class AudioGenerator
{
string audioSavePath = "";
public bool Generate(String text, string path)
{
bool success = false;
try
{
audioSavePath = path;
//initialize();
TextToSpeech(text);
success = true;
}
catch (Exception e)
{
//Console.WriteLine("Error: " + e.Message);
}
return success;
}
//string filename = @"audio.wav";
//private void initialize()
//{
// string saveTo = Path.GetDirectoryName(Environment.CurrentDirectory) + @"\audio\"; //Folder to Save
// if (!Directory.Exists(saveTo))
// {
// Directory.CreateDirectory(saveTo);
// }
// audioSavePath = saveTo + filename;
//}
private void TextToSpeech(String text)
{
try
{
var srService = new TextToSpeechService(Constants.Speech_API_Key);
srService.OnAudioAvailable += SaveAudio;
srService.OnError += ErrorHandler;
Authorization auth = new Authorization(Constants.Speech_API_Key);
var authToken = auth.GetAuthorizationTokenAsync().Result;
var inputOptions = new InputOptions()
{
RequestUri = new Uri(Constants.BASE_URI + "synthesize"),
Text = text,
Locale = "en-US",
VoiceName = "Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)",
OutputFormat = AudioOutputFormat.Riff16Khz16BitMonoPcm,
AuthorizationToken = "Bearer " + authToken,
};
srService.Speak(CancellationToken.None, inputOptions).Wait();
}
catch (Exception ex)
{
//Console.WriteLine("Error: " + ex.Message);
}
}
private void SaveAudio(object sender, GenericEventArgs<Stream> args)
{
Stream readStream = args.EventData;
try
{
FileStream writeStream = File.Create(audioSavePath);
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytestoRead = readStream.Read(buffer, 0, Length);
while (bytestoRead > 0)
{
writeStream.Write(buffer, 0, bytestoRead);
bytestoRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
catch (Exception e)
{
//Console.WriteLine(e.Message);
}
finally
{
args.EventData.Dispose();
}
}
private void ErrorHandler(object sender, GenericEventArgs<Exception> e)
{
//Console.WriteLine("Unable to complete the TTS request: [{0}]", e.ToString());
}
}
}
<file_sep>/VideoConverter/VideoConverter/MovieMaker.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Accord.Video.FFMPEG;
using AForge.Video;
using System.ComponentModel;
using System.Data;
using System.Drawing.Imaging;
//using Accord.Audio.Windows;
//using Microsoft.Xna.Framework.Audio;
//using AForge.Video.DirectShow;
using AForge.Video;
using Accord.Video.FFMPEG;
//using Accord.Controls.Audio;
using System.IO;
using System.IO.IsolatedStorage;
using System.Threading;
using System.Runtime.InteropServices;
using System.Media;
using AviFile;
namespace VideoConverter
{
public class MovieMaker
{
int width = 320;
int height = 240;
int frameRate = 15;
public Bitmap ToBitmap(byte[] byteArrayIn)
{
var ms = new System.IO.MemoryStream(byteArrayIn);
var returnImage = Image.FromStream(ms);
var bitmap = new Bitmap(returnImage);
return bitmap;
}
public Bitmap ReduceBitmap(Bitmap original, int reducedWidth, int reducedHeight)
{
var reduced = new Bitmap(reducedWidth, reducedHeight);
using (var dc = Graphics.FromImage(reduced))
{
// you might want to change properties like
dc.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
dc.DrawImage(original, new Rectangle(0, 0, reducedWidth, reducedHeight), new Rectangle(0, 0, original.Width, original.Height), GraphicsUnit.Pixel);
}
return reduced;
}
/*END OF COPIED CODE BLOCK*/
public void CreateVideoFromImages(String dirFullPath, string outputVideoFullPath, int secsToPlay = 4)
{
try
{
using (var vFWriter = new VideoFileWriter())
{
// create new video file
vFWriter.Open(outputVideoFullPath, width, height, frameRate);
DirectoryInfo d = new DirectoryInfo(dirFullPath);//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.jpg"); //Getting Text files
foreach (FileInfo file in Files)
{
Bitmap bmp = new Bitmap(file.FullName);
for (int i = 0; i < frameRate * secsToPlay; i++)
{
vFWriter.WriteVideoFrame(ReduceBitmap(bmp, width, height));
}
}
vFWriter.Close();
}
}
catch (Exception e)
{
}
}
public bool AudioVideoJoiner(String videoPath, String audioPath)
{
bool success = false;
try
{
AviManager aviManager = new AviManager(videoPath, true);
aviManager.AddAudioStream(audioPath, 0);
aviManager.Close();
success = true;
}
catch(Exception e)
{
success = false;
}
return success;
}
}
}
<file_sep>/AudioVideoMaker/Program.cs
using Azure.SpeechToText;
using FileDownloader;
using Microsoft.ServiceBus.Messaging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using VideoConverter;
namespace AudioVideoMaker
{
class Program
{
const string queueConString = "Endpoint=sb://azureboot.servicebus.windows.net/;SharedAccessKeyName=admin;SharedAccessKey=<KEY>;EntityPath=slack";
public static string GetPath(string filename)
{
string saveTo = Path.GetDirectoryName(Environment.CurrentDirectory) + @"\temp\"; //Folder to Save
Console.WriteLine($"Saving to {saveTo}");
if (!Directory.Exists(saveTo))
{
Directory.CreateDirectory(saveTo);
}
return saveTo + filename;
}
public static void Main(string[] args)
{
string audioPath = GetPath("audio.wav");
string imageFolder = GetPath("");
string outputVideoPath = GetPath($"bootcamp-video-{DateTime.Now.ToString("yyyyMMddHHmmSS")}.avi");
var oQueueDownloader = new QueueDownloader();
String textString = String.Empty;
textString = oQueueDownloader.DownloadFromQueue().GetAwaiter().GetResult();
bool isAudio = false;
if (!String.IsNullOrEmpty(textString))
{
isAudio = true;
AudioGenerator ag = new AudioGenerator();
ag.Generate(textString, audioPath);
}
MovieMaker mm = new MovieMaker();
mm.CreateVideoFromImages(imageFolder, outputVideoPath, 4);
if (isAudio)
{
mm.AudioVideoJoiner(outputVideoPath, audioPath);
}
UploadVideo(outputVideoPath).GetAwaiter().GetResult();
Console.WriteLine("Press any key to continue.");
Console.Read();
}
static async Task UploadVideo(string outputVideoPath)
{
BlobStorageClient blobClient = new BlobStorageClient();
string path = await blobClient.UploadVideo(File.ReadAllBytes(outputVideoPath), Path.GetFileName(outputVideoPath));
}
}
}
|
7e6219386dfbba53f82e404f4e36782eca290606
|
[
"Markdown",
"C#"
] | 10
|
C#
|
msaha-finomial/movie-maker
|
73c9b04f1f839e2b5c75cdc56ad3aed5f26d8259
|
eed8b17c9a71a88e4bfea7e34991a9e5350dcf7b
|
refs/heads/master
|
<repo_name>hernan604/JooseComponent<file_sep>/lib/forms_joose.js
(function () {
"use strict";
Role("ElemEvents", {
requires : [
'setElem', // requires other class to have attr elem -- or this.setElem
],
has : {
events : { is : "rw", init : ( function () { return {} } ) },
},
methods : {
init_events : function () {
var self = this;
for ( var event in this.events ) {
if ( this.events.hasOwnProperty( event ) ) {
this.elem[ event ]( function ( ev ) {
//[].unshift.call(arguments, self);
self.events[ event ].apply(self, arguments );
} )
}
}
},
},
after : {
render : function () {
this.init_events();
}
}
})
Role( "BeforeAfter", {
has : {
before_initialize : { is : "rw" },
after_initialize : { is : "rw" },
before_render : { is : "rw" },
after_render : { is : "rw" },
before_appendTo : { is : "rw" },
after_appendTo : { is : "rw" },
before_prependTo : { is : "rw" },
after_prependTo : { is : "rw" },
},
before : {
initialize : function () {
if ( this.before_initialize ) {
this.before_initialize();
}
},
render : function () {
if ( this.before_render ) {
this.before_render();
}
},
appendTo : function () {
if ( this.before_appendTo ) {
this.before_appendTo();
}
},
prependTo : function () {
if ( this.before_prependTo ) {
this.before_prependTo();
}
},
},
after : {
initialize : function () {
if ( this.after_initialize ) {
this.after_initialize();
}
},
render : function () {
if ( this.after_render ) {
this.after_render();
}
},
appendTo : function () {
if ( this.after_appendTo ) {
this.after_appendTo();
}
},
prependTo : function () {
if ( this.after_prependTo ) {
this.after_prependTo();
}
},
},
} )
Role("Elem", {
does : [ BeforeAfter ],
has : {
elem : { is : "rw" },
content : { is : "rw" },
css_class : { is : "rw" },
form : { is : "rw" },
form_field : { is : "rw" },
is_required : { is : "rw", init : ( function () { return false } ) },
},
before : {
initialize : function () {
}
},
methods : {
render : function () {
this.elem.html( this.content );
},
show : function () {
this.elem.show();
},
hide : function () {
this.elem.hide();
},
add_error : function ( error ) {
this.form_field.errors.push( error );
},
trigger : function ( event ) {
//shortcut to field_data
this.field_data.elem.trigger( event );
},
appendTo : function ( elem ) {
this.elem.appendTo( elem )
},
prependTo : function ( elem ) {
this.elem.prependTo( elem )
},
append : function ( elem ) {
this.elem.append( elem )
},
prepend : function ( elem ) {
this.elem.prepend( elem )
},
},
after : {
initialize : function () {
this.render();
},
},
});
Class("FormButton", {
does : [ Elem, ElemEvents ],
has : {
},
before : {
initialize : function () {
this.setElem( $( "<button/>" ) );
}
},
methods : {
render : function () {
this.elem.html( this.content );
},
},
});
Class("FormFieldInput", {
does : [ Elem, ElemEvents ],
has : {
placeholder : { is : "rw" },
value : { is : "rw" },
validate : { is : "rw" },
},
before : {
initialize : function () {
this.setElem( $( '<input/>' ) );
}
},
methods : {
render : function () {
this.elem.addClass( this.css_class )
this.elem.attr( 'placeholder', this.placeholder )
this.elem.val( this.value )
return this;
},
hide_validation_errors : function () {
this.elem.removeClass('has_error');
},
show_validation_errors : function () {
this.elem.addClass('has_error')
},
set_value : function ( value ) {
this.elem.val( value )
},
get_value : function () {
return this.elem.val();
},
clear : function () {
this.elem.val('')
}
},
})
Class("FormFieldCheckbox", {
does : [ Elem, ElemEvents ],
has : {
value : { is : "rw" },
validate : { is : "rw" },
},
before : {
initialize : function () {
this.setElem( $( '<input/>' ).attr('type', 'checkbox') );
}
},
methods : {
set_value : function ( value ) {
this.elem.prop( 'checked', value )
},
get_value : function () {
return this.elem.prop( 'checked' );
},
hide_validation_errors : function () {
this.elem.removeClass('has_error');
},
show_validation_errors : function () {
this.elem.addClass('has_error')
},
clear : function () {
this.elem.prop('checked', false)
}
}
});
Class("FormFieldSelect", {
does : [ Elem, ElemEvents ],
has : {
value : { is : "rw" },
validate : { is : "rw" },
options : { is : "rw", init : ( function () { return [] } )() },
is_multiple : { is : "rw" },
},
before : {
initialize : function () {
this.setElem( $( '<select/>' ).attr('type', 'checkbox') );
}
},
methods : {
set_value : function ( value ) {
this.elem.val( value );
},
get_value : function () {
return this.elem.val();
},
hide_validation_errors : function () {
this.elem.removeClass('has_error');
},
show_validation_errors : function () {
this.elem.addClass('has_error')
},
clear : function () {
this.elem.val('');
},
update : function ( options ) {
if ( options ) { this.setOptions( options ) }
this.elem.html('');
for ( var i = 0, item ; item = this.options[ i++ ] ; ) {
this.elem.append( $('<option>', item ) );
}
}
},
after : {
initialize : function () {
},
render : function () {
this.update();
this.elem.attr('multiple', this.is_multiple )
}
}
})
Class("FormFieldTable", {
does : [ Elem, ElemEvents ],
has : {
column : { is : "rw", init: ( function () { return {} } ) },
columns : { is : "rw", init: ( function () { return [] } ) },
value : { is : "rw", init: ( function () { return [] } ) },
},
before : {
initialize : function () {
this.setElem( $( '<table/>' ).addClass('table').addClass('table-bordered') );
}
},
methods : {
clear : function () {
},
update : function ( value ) {
if ( value ) {
this.setValue( value )
}
this.elem.html('');
this.set_headers();
var tbody = $( '<tbody/>' );
tbody.appendTo( this.elem );
console.log('set items', this.value );
for ( var i = 0, item; item = this.value[ i++ ] ; ) {
console.log( item );
var tr = $('<tr/>');
for ( var k in item ) {
if ( this.column[ k ] ) {
var td = $('<td/>').html( this.column[ k ].build( item, item[ k ] ) );
td.appendTo(tr);
}
}
tr.appendTo( tbody )
console.log( tr );
}
console.log( this.elem )
},
set_headers : function () {
var thead = $('<thead/>');
var tr = $('<tr/>');
thead.appendTo( this.elem );
tr.appendTo( thead );
for ( var i = 0, item ; item = this.columns[ i++ ] ; ) {
$('<td/>').html( item.label ).appendTo(tr);
}
},
set_value : function ( value ) {
this.update( value );
}
},
after : {
setColumns : function () {
var column = {}
for ( var i=0, col; col = this.columns[ i++ ] ; ) {
column[ col.id ] = col;
}
this.setColumn( column );
},
render : function ( ) {
this.update();
},
}
})
Class("FormFieldLabel", {
does : [ Elem, ElemEvents ],
has : {
},
before : {
initialize : function () {
this.setElem( $( '<label/>' ) );
}
},
methods : {
render : function () {
this.elem.html( this.content )
}
},
after : {
initialize : function () {
this.render();
}
},
} )
Class("SectionHeader", {
does : [ Elem, ElemEvents ],
has : {},
before : {
initialize : function () {
this.setElem( $( '<h2/>' ) );
}
},
methods : {
render : function () {
this.elem.html( this.content )
}
},
after : {
initialize : function () {
this.render();
}
},
});
Class("FormField", {
does : [ Elem, ElemEvents ],
has : {
id : { is : 'rw', },
field_label : { is : "rw" },
field_data : { is : "rw" },
errors : { is : "rw", init : ( function () { return [] } ) },
},
before : {
initialize : function () {
this.setElem( $( '<ul/>' ) );
}
},
methods : {
set_label : function ( elem ) {
this.setField_label( elem );
return this;
},
set_data_field : function ( elem ) {
this.setField_data( elem );
return this;
},
render : function () {
this.elem.addClass('field').addClass( this.css_class ).attr( 'id', this.id );
return this;
},
get_value : function () {
return this.field_data.get_value();
},
validate : function () {
this.setErrors( [] );
if ( ! this.field_data || ! this.field_data.get_value ) { return }
var value = this.field_data.get_value();
if ( this.is_required && ( typeof value == 'undefined' || value === '' ) ) {
this.errors.push('This field is required.');
}
if ( this.field_data.validate ) {
this.field_data.validate( this.field_data.get_value() );
}
},
hide_validation_errors : function ( ) {
this.elem.removeClass('has_error');
this.elem.find('.error_list').remove();
},
show_validation_errors : function () {
this.elem.addClass('has_error')
var error_list = $('<ul/>');
for ( var i = 0, error; error = this.errors[ i++ ] ; ) {
error_list.append( $('<li/>').html( error ) );
}
$( '<li/>' ).addClass('error_list').html( error_list ).appendTo( this.elem )
},
set_value : function ( value ) {
this.field_data.set_value( value );
},
clear : function () {
if ( ! this.field_data || ! this.field_data.clear ) { return }
this.field_data.clear()
}
},
after : {
initialize : function () {
},
setForm : function () {
if ( this.field_label ) {
this.field_label.setForm( this.form );
this.field_label.setForm_field( this );
}
if ( this.field_data ) {
this.field_data.setForm( this.form );
this.field_data.setForm_field( this );
}
},
setField_label : function () {
$('<li/>').addClass('label').append(this.field_label.elem).appendTo( this.elem );
this.field_label.setForm( this.form );
this.field_label.setForm_field( this );
},
setField_data : function () {
$('<li/>').addClass('input').append(this.field_data.elem).appendTo( this.elem );
this.field_data.setForm( this.form );
this.field_data.setForm_field( this );
},
},
})
Class("Form", {
does : [ Elem, ElemEvents ],
has : {
fields : { is : 'rw', init: ( function () { return [] } ) },
field : { is : 'rw', init: ( function () { return {} } ) },
is_valid : { is : 'rw' }
},
before : {
initialize : function () {
this.setElem( $( '<ul/>' ).addClass('field_list') );
}
},
methods : {
validate : function () {
//check each vield value and make sure all of them are valid
var is_valid = true;
for ( var id in this.field ) {
if ( this.field.hasOwnProperty( id ) ) {
var field = this.field[ id ];
field.validate();
field.hide_validation_errors();
if ( field.errors.length ) {
is_valid = false;
field.show_validation_errors();
}
}
}
this.setIs_valid( is_valid );
return this.setIs_valid;
},
render: function () {
this.elem.addClass(this.css_class)
this.render_elements( this.fields );
},
render_elements : function ( elements ) {
for ( var i = 0, fields; fields = elements[ i++ ] ; ) {
var li = $( '<li/>' ).addClass('field_row').appendTo( this.elem );
for ( var j = 0, field; field = fields[j++]; ) {
if ( field.id ) { this.field[ field.id ] = field; }
field.setForm( this );
li.append( field.elem )
}
}
},
fill : function ( obj ) {
for ( var attr in obj ) {
if ( obj.hasOwnProperty( attr ) ) {
try {
this.field[ attr ].set_value( obj[ attr ] );
} catch ( e ) {}
}
}
},
clear : function () {
var elements = this.fields;
for ( var i = 0, fields; fields = elements[ i++ ] ; ) {
for ( var j = 0, field; field = fields[j++]; ) {
if ( field.hide_validation_errors ) {
field.hide_validation_errors();
}
if ( field.clear ) {
field.clear();
}
}
}
}
},
after : {
initialize : function () {
}
},
})
})()
|
2b0e65286cf8ee85fb79c92a401f589449076e22
|
[
"JavaScript"
] | 1
|
JavaScript
|
hernan604/JooseComponent
|
d9015ac14f3ccdae466788f9226423293289c164
|
0b25c5f149737838f86d01a524a91565d8c9d38f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.