Dataset Viewer (First 5GB)
repo
string | content
string |
---|---|
tincho006/Tincho
|
tincho006/Tincho
sessionstore.js
```{"version":["sessionrestore",1],"windows":[{"tabs":[{"entries":[{"url":"https://www.mozilla.org/en-US/firefox/45.0.2/firstrun/","title":"Mozilla Firefox Web Browser — — Mozilla","charset":"UTF-8","ID":4,"docshellID":5,"originalURI":"https://www.mozilla.org/en-US/firefox/45.0.2/firstrun/","docIdentifier":4,"children":[{"url":"about:blank","charset":"","ID":6,"docshellID":10,"owner_b64":"ZT4OTT7kRfqycpfCC8AeuAAAAAAAAAAAwAAAAAAAAEYB3pRy0IA0EdOTmQAQS6D9QJIHOlRteE8wkTq4cYEyCMYAAAAC/////wAAAbsBAAAANmh0dHBzOi8vd3d3Lm1vemlsbGEub3JnL2VuLVVTL2ZpcmVmb3gvNDUuMC4yL2ZpcnN0cnVuLwAAAAAAAAAFAAAACAAAAA8AAAAI/////wAAAAj/////AAAACAAAAA8AAAAXAAAAHwAAABcAAAAfAAAAFwAAAB8AAAA2AAAAAAAAADb/////AAAAAP////8AAAAX/////wAAABf/////AQAAAAAAAAAAAAEAAAAAAAA=","docIdentifier":6}],"persist":true}],"lastAccessed":1472134547322,"hidden":false,"attributes":{},"index":1,"image":"https://www.mozilla.org/media/img/firefox/favicon.dc6635050bf5.ico"},{"entries":[{"url":"https://www.mozilla.org/en-US/firefox/45.0.2/firstrun/learnmore/","title":"More protection. The most privacy. Only from Firefox.","charset":"UTF-8","ID":5,"docshellID":6,"originalURI":"https://www.mozilla.org/en-US/firefox/45.0.2/firstrun/learnmore/","docIdentifier":5,"persist":true}],"lastAccessed":1472134542135,"hidden":false,"attributes":{},"index":1,"image":"https://www.mozilla.org/media/img/firefox/favicon.dc6635050bf5.ico"},{"entries":[{"url":"about:home","title":"Mozilla Firefox Start Page","charset":"","ID":2,"docshellID":7,"docIdentifier":2,"persist":true}],"lastAccessed":1472134542176,"hidden":false,"attributes":{},"index":1,"image":"chrome://branding/content/icon32.png"}],"selected":1,"_closedTabs":[],"width":1020,"height":553,"screenX":-4,"screenY":0,"sizemode":"normal","title":"Mozilla Firefox Web Browser — — Mozilla","_shouldRestore":true,"closedAt":1472134547337}],"selectedWindow":0,"_closedWindows":[],"session":{"lastUpdate":1472134547665,"startTime":1472134539489,"recentCrashes":0},"global":{}}```
|
tincuvalentingabriel/ProiectIP
|
tincuvalentingabriel/ProiectIP
mainwindow.h
```#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<list_util.h>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void SelectionUnit(QString);
void Transform();
void Reset();
private:
Ui::MainWindow *ui;
Lista *length_items;
Lista *area_items;
Lista *volume_items;
Lista *time_items;
Lista *speed_items;
Lista *temperature_items;
Lista *weight_items;
Lista *energy_items;
Lista *pressure_items;
Lista *density_items;
Lista *items;
private:
void update_items();
};
#endif // MAINWINDOW_H
```
list_util.h
```#ifndef LIST_UTIL_H
#define LIST_UTIL_H
#include<QString>
struct Lista {
QString nume;
double valoare;
Lista *urm;
Lista *ultim;
};
void Inserare(Lista *Prim, QString s, double x);
double cautare (Lista*, QString);
struct conv_len
{
QString name;
double mult;
};
double conv(double Us, double Ud, double val);
#endif // LIST_UTIL_H
```
ui_mainwindow.h
```/********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.7.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QWidget *centralWidget;
QGridLayout *gridLayout_2;
QFormLayout *formLayout_3;
QLabel *label_3;
QVBoxLayout *verticalLayout_3;
QLabel *label_4;
QComboBox *convert_unit;
QFormLayout *formLayout;
QLabel *label;
QComboBox *unit_1;
QLineEdit *value;
QSpacerItem *verticalSpacer_2;
QHBoxLayout *horizontalLayout;
QSpacerItem *horizontalSpacer;
QPushButton *reset;
QSpacerItem *horizontalSpacer_2;
QFormLayout *formLayout_2;
QLabel *label_2;
QComboBox *unit_2;
QLineEdit *result;
QSpacerItem *verticalSpacer_3;
QVBoxLayout *verticalLayout;
QPushButton *convert;
QSpacerItem *verticalSpacer;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QStringLiteral("MainWindow"));
MainWindow->resize(557, 434);
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
centralWidget->setEnabled(true);
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(centralWidget->sizePolicy().hasHeightForWidth());
centralWidget->setSizePolicy(sizePolicy);
centralWidget->setAutoFillBackground(false);
centralWidget->setStyleSheet(QLatin1String("alternate-background-color: rgb(170, 170, 127);\n"
"border-color: rgb(170, 0, 127);"));
gridLayout_2 = new QGridLayout(centralWidget);
gridLayout_2->setSpacing(6);
gridLayout_2->setContentsMargins(11, 11, 11, 11);
gridLayout_2->setObjectName(QStringLiteral("gridLayout_2"));
formLayout_3 = new QFormLayout();
formLayout_3->setSpacing(6);
formLayout_3->setObjectName(QStringLiteral("formLayout_3"));
formLayout_3->setSizeConstraint(QLayout::SetFixedSize);
formLayout_3->setContentsMargins(-1, 0, -1, -1);
label_3 = new QLabel(centralWidget);
label_3->setObjectName(QStringLiteral("label_3"));
QSizePolicy sizePolicy1(QSizePolicy::Fixed, QSizePolicy::Expanding);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(label_3->sizePolicy().hasHeightForWidth());
label_3->setSizePolicy(sizePolicy1);
QFont font;
font.setFamily(QStringLiteral("Arial Black"));
font.setPointSize(14);
font.setBold(true);
font.setWeight(75);
label_3->setFont(font);
label_3->setTextFormat(Qt::AutoText);
label_3->setWordWrap(true);
formLayout_3->setWidget(1, QFormLayout::LabelRole, label_3);
verticalLayout_3 = new QVBoxLayout();
verticalLayout_3->setSpacing(6);
verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3"));
formLayout_3->setLayout(2, QFormLayout::FieldRole, verticalLayout_3);
label_4 = new QLabel(centralWidget);
label_4->setObjectName(QStringLiteral("label_4"));
formLayout_3->setWidget(0, QFormLayout::LabelRole, label_4);
convert_unit = new QComboBox(centralWidget);
convert_unit->setObjectName(QStringLiteral("convert_unit"));
formLayout_3->setWidget(0, QFormLayout::FieldRole, convert_unit);
gridLayout_2->addLayout(formLayout_3, 1, 0, 2, 1);
formLayout = new QFormLayout();
formLayout->setSpacing(6);
formLayout->setObjectName(QStringLiteral("formLayout"));
label = new QLabel(centralWidget);
label->setObjectName(QStringLiteral("label"));
formLayout->setWidget(1, QFormLayout::LabelRole, label);
unit_1 = new QComboBox(centralWidget);
unit_1->setObjectName(QStringLiteral("unit_1"));
formLayout->setWidget(1, QFormLayout::FieldRole, unit_1);
value = new QLineEdit(centralWidget);
value->setObjectName(QStringLiteral("value"));
QSizePolicy sizePolicy2(QSizePolicy::Expanding, QSizePolicy::Fixed);
sizePolicy2.setHorizontalStretch(0);
sizePolicy2.setVerticalStretch(0);
sizePolicy2.setHeightForWidth(value->sizePolicy().hasHeightForWidth());
value->setSizePolicy(sizePolicy2);
formLayout->setWidget(3, QFormLayout::FieldRole, value);
verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
formLayout->setItem(2, QFormLayout::FieldRole, verticalSpacer_2);
gridLayout_2->addLayout(formLayout, 1, 1, 2, 1);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setSpacing(6);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
horizontalLayout->setSizeConstraint(QLayout::SetNoConstraint);
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addItem(horizontalSpacer);
reset = new QPushButton(centralWidget);
reset->setObjectName(QStringLiteral("reset"));
QSizePolicy sizePolicy3(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
sizePolicy3.setHorizontalStretch(0);
sizePolicy3.setVerticalStretch(0);
sizePolicy3.setHeightForWidth(reset->sizePolicy().hasHeightForWidth());
reset->setSizePolicy(sizePolicy3);
horizontalLayout->addWidget(reset);
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addItem(horizontalSpacer_2);
gridLayout_2->addLayout(horizontalLayout, 3, 1, 1, 4);
formLayout_2 = new QFormLayout();
formLayout_2->setSpacing(6);
formLayout_2->setObjectName(QStringLiteral("formLayout_2"));
label_2 = new QLabel(centralWidget);
label_2->setObjectName(QStringLiteral("label_2"));
formLayout_2->setWidget(1, QFormLayout::LabelRole, label_2);
unit_2 = new QComboBox(centralWidget);
unit_2->setObjectName(QStringLiteral("unit_2"));
formLayout_2->setWidget(1, QFormLayout::FieldRole, unit_2);
result = new QLineEdit(centralWidget);
result->setObjectName(QStringLiteral("result"));
sizePolicy2.setHeightForWidth(result->sizePolicy().hasHeightForWidth());
result->setSizePolicy(sizePolicy2);
formLayout_2->setWidget(3, QFormLayout::FieldRole, result);
verticalSpacer_3 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
formLayout_2->setItem(2, QFormLayout::FieldRole, verticalSpacer_3);
gridLayout_2->addLayout(formLayout_2, 1, 4, 2, 1);
verticalLayout = new QVBoxLayout();
verticalLayout->setSpacing(6);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
verticalLayout->setSizeConstraint(QLayout::SetMaximumSize);
verticalLayout->setContentsMargins(-1, 34, -1, -1);
convert = new QPushButton(centralWidget);
convert->setObjectName(QStringLiteral("convert"));
QIcon icon;
icon.addFile(QStringLiteral("2000px-Right_arrow.svg.png"), QSize(), QIcon::Normal, QIcon::Off);
convert->setIcon(icon);
verticalLayout->addWidget(convert);
verticalSpacer = new QSpacerItem(20, 60, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout->addItem(verticalSpacer);
gridLayout_2->addLayout(verticalLayout, 2, 2, 1, 2);
MainWindow->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MainWindow);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 557, 21));
MainWindow->setMenuBar(menuBar);
mainToolBar = new QToolBar(MainWindow);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QStringLiteral("statusBar"));
MainWindow->setStatusBar(statusBar);
retranslateUi(MainWindow);
QObject::connect(convert_unit, SIGNAL(currentIndexChanged(QString)), MainWindow, SLOT(SelectionUnit(QString)));
QObject::connect(convert, SIGNAL(clicked()), MainWindow, SLOT(Transform()));
QObject::connect(reset, SIGNAL(clicked()), MainWindow, SLOT(Reset()));
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "Convertor", Q_NULLPTR));
label_3->setText(QApplication::translate("MainWindow", "<html><head/><body><p><br/><span style=\" font-size:14pt; font-weight:600; font-style:italic;\">C</span></p><p><span style=\" font-size:14pt; font-weight:600; font-style:italic;\">o</span></p><p><span style=\" font-size:14pt; font-weight:600; font-style:italic;\">n</span></p><p><span style=\" font-size:14pt; font-weight:600; font-style:italic;\">v</span></p><p><span style=\" font-size:14pt; font-weight:600; font-style:italic;\">e</span></p><p><span style=\" font-size:14pt; font-weight:600; font-style:italic;\">r</span></p><p><span style=\" font-size:14pt; font-weight:600; font-style:italic;\">t</span></p></body></html>", Q_NULLPTR));
label_4->setText(QApplication::translate("MainWindow", "Unit:", Q_NULLPTR));
label->setText(QApplication::translate("MainWindow", "From:", Q_NULLPTR));
reset->setText(QApplication::translate("MainWindow", "Reset", Q_NULLPTR));
label_2->setText(QApplication::translate("MainWindow", "To:", Q_NULLPTR));
convert->setText(QString());
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
```
list_util.cpp
```#include "list_util.h"
void Inserare(Lista *Prim, QString s, double x)
{
Lista *q;
if (Prim->ultim==nullptr)
{
q=Prim;
}
else
{
q=new Lista;
Prim->ultim->urm=q;
}
q->nume=s;
q->valoare = x;
q->urm=nullptr;
q->ultim=nullptr;
Prim->ultim=q;
}
double cautare (Lista* L, QString x )
{
Lista* p = L;
while (p!=nullptr)
{
if (p->nume == x)
{
return p->valoare;
}
p=p->urm;
}
return 0;
}
double conv(double Us, double Ud, double val)
{
return val/Us * Ud;
}
```
main.cpp
```#include "mainwindow.h"
#include <QApplication>
#include <QComboBox>
#include "list_util.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
QComboBox* cd=w.centralWidget()->findChild<QComboBox*>("convert_unit");
cd->addItem("lungime");
cd->addItem("arie");
cd->addItem("volum");
cd->addItem("timp");
cd->addItem("viteza");
cd->addItem("temperatura");
cd->addItem("masa");
cd->addItem("energie");
cd->addItem("presiune");
cd->addItem("densitate");
return a.exec();
}
```
mainwindow.cpp
```#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
conv_len b[] = { {"mm", 1000},{"dm", 10},{"cm", 100}, {"ft", 3.2808},{"inch", 39.370}, {"m", 1},{"yd", 1.0936}, {"nmi", 0.0005}, {"mi", 0.0006}, {"km", 0.001} };
length_items = new Lista;
length_items->ultim = nullptr;
for (int i = 0; i<10; i++)
{
Inserare(length_items , b[i].name, b[i].mult);
}
conv_len c[] = {{"ari", 0.01}, {"acri", 0.0002}, {"cm^2", 10000}, {"ft^2", 10.764}, {"ha", 0.0001},{"inch^2", 1549.90}, {"km^2", 0.000001}, {"m^2", 1}, {"mm^2", 1000000}, {"yd^2", 1.1959}};
area_items = new Lista;
area_items->ultim = nullptr;
for(int i=0;i<9;i++)
{
Inserare(area_items, c[i].name, c[i].mult);
}
conv_len d[] = {{"cl", 99999.99}, {"cm^3", 1000000}, {"dl", 10000}, {"dm^3", 1000}, {"ft^3", 35.310}, {"gal(UK)", 219.973}, {"gal(US)", 264.200}, {"inch^3", 61023.744}, {"l", 1000}, {"m^3", 1}, {"ml", 1000000}, {"yd^3", 1.3079}};
volume_items = new Lista;
volume_items->ultim = nullptr;
for (int i=0; i<12;i++)
{
Inserare (volume_items, d[i].name, d[i].mult);
}
conv_len e[] = {{"mileniu", 2.74167343}, {"deceniu", 0.00027397}, {"an", 0.00273972}, {"sapt", 0.14285714}, {"zi", 1}, {"ora", 24}, {"min", 1440}, {"sec", 86400}, {"decisec", 864000}, {"centisec", 8640000}, {"milisec", 86400000}, {"micrsec", 86400000000}, {"nanosec", 86400000000}, {"picosec", 86400000000000000}};
time_items = new Lista;
time_items->ultim = nullptr;
for (int i=0;i<14;i++)
{
Inserare(time_items, e[i].name, e[i].mult);
}
conv_len f[] = {{"km/h", 3.5999}, {"mph", 2.2369}, {"m/s", 1}};
speed_items = new Lista;
speed_items->ultim = nullptr;
for (int i=0; i<3;i++)
{
Inserare(speed_items, f[i].name, f[i].mult);
}
conv_len g[] = {{"F", 33.8}, {"K", 274.15}, {"R", 493.47}, {"C", 1}};
temperature_items = new Lista;
temperature_items->ultim = nullptr;
for (int i=0;i<4; i++)
{
Inserare(temperature_items, g[i].name, g[i].mult);
}
conv_len h[] = {{"kg", 0.001}, {"mg", 1000.000}, {"t", 0.000001}, {"g", 1}, {"lb", 0.00220}};
weight_items = new Lista;
weight_items->ultim = nullptr;
for(int i=0; i<5; i++)
{
Inserare (weight_items, h[i].name, h[i].mult);
}
conv_len k[] = {{"cal", 0.238845}, {"kcal", 0.0002388}, {"kJ",0.001}, {"W*h", 0.00027777777}, {"W*s", 1}, {"J", 1}};
energy_items = new Lista;
energy_items->ultim = nullptr;
for(int i=0;i<6;i++)
{
Inserare(energy_items,k[i].name, k[i].mult );
}
conv_len l[] = {{"at", 0.999321888}, {"atm", 0.9671821878}, {"in.H2O", 393.8273589}, {"inHg", 28.939387}, {"mH20", 10}, {"mmH20", 10000}, {"mmHg", 735.06044}, {"MPa", 0.098}, {"Pa", 98000}, {"bar", 1} };
pressure_items = new Lista;
pressure_items->ultim= nullptr;
for (int i=0;i<10;i++)
{
Inserare (pressure_items, l[i].name, l[i].mult);
}
conv_len m[] = {{"g/l", 1000}, {"g/m^3", 1000000}, {"g/ml", 1},{"g/mm^3", 0.001}, {"kg/cm^3", 0.001}, {"kg/l", 1},{"kg/m^3", 1000}, {"mg/cm^3", 1000}, {"mg/l", 1000000}, {"mg/m^3", 1000000000}, {"t/m^3", 1}, {"g/cm^3", 1}};
density_items = new Lista;
density_items->ultim = nullptr;
for(int i=0; i<12; i++)
{
Inserare(density_items, m[i].name, m[i].mult);
}
ui->result->setReadOnly(true);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::update_items()
{
ui->unit_1->clear();
ui->unit_2->clear();
Lista *p=this->items;
while (p)
{
ui->unit_1->addItem(p->nume);
ui->unit_2->addItem(p->nume);
p=p->urm;
}
}
void MainWindow::SelectionUnit(QString index)
{
if (index == "lungime")
{
this->items = length_items;
}
else if (index=="arie")
{
this->items = area_items;
}
else if (index == "volum")
{
this->items = volume_items;
}
else if (index == "timp")
{
this->items = time_items;
}
else if (index == "viteza")
{
this->items = speed_items;
}
else if (index == "temperatura")
{
this->items = temperature_items;
}
else if (index=="masa")
{
this->items = weight_items;
}
else if (index == "energie")
{
this->items = energy_items;
}
else if (index =="presiune")
{
this->items = pressure_items;
}
else if (index =="densitate")
{
this->items = density_items;
}
this->update_items();
}
void MainWindow::Transform()
{
double from_valoare = cautare(this->items, ui->unit_1->currentText());
double to_valoare = cautare(this->items, ui->unit_2->currentText());
double conv_value = ui->value->text().toDouble();
ui->result->setText(QString::number(conv(from_valoare, to_valoare, conv_value)));
}
void MainWindow::Reset()
{
ui->value->setText("");
ui->result->setText("");
}
```
|
tinevancorenland/DataVisualisation
|
tinevancorenland/DataVisualisation
tine.js
```// Create a chart via chart.js without altering html
var canvas = document.createElement("canvas");
canvas.id = "myChart";
var header = document.getElementsByTagName("h3")[0];
header.appendChild(canvas);
//Create variables to insert in chart
// Years for labels x axis
var table = document.getElementById("table1");
console.log(table);
var rowYears = table.rows[1];
var yearList = [];
for (y = 2; y < rowYears.cells.length; y++) {
var years = rowYears.cells[y].firstChild.data;
yearList.push(years);
}
// // Country dataset 1
// var rowBe = table.rows[2];
// console.log(rowBe);
// var BeName = rowBe.cells[1].firstChild.data;
// var BeData = [];
// for (Be = 2; Be < rowBe.cells.length; Be++) {
// var BeNrs = parseInt(rowBe.cells[Be].firstChild.data);
// BeData.push(BeNrs);
// }
// // Country dataset 2
// var rowBu = table.rows[3];
// console.log(rowBu);
// var BuName = table.rows[3].cells[1].firstChild.data;
// var BuData = [];
// for (d = 2; d < table.rows[3].cells.length; d++) {
// var BuNrs = parseInt(table.rows[3].cells[d].firstChild.data);
// BuData.push(BuNrs);
// }
// // Loop to pull data from every country
// var allRows = [];
// var allCountries = [];
// var allData = [];
// for (ro = 2; ro < table.rows.length; ro++) {
// var currentRow = table.rows[ro].cells;
// allRows.push(currentRow);
// var currentCountry = table.rows[ro].cells[1].firstChild.data;
// allCountries.push(currentCountry);
// for (nrs = 2; nrs < table.rows[ro].cells.length; nrs++) {
// var currentData = parseInt(table.rows[ro].cells[nrs].firstChild.data);
// allData.push(currentData);
// }
// }
// console.log(allRows);
// console.log(allCountries);
// console.log(allData);
// Livecoding Filip
var theTable = document.getElementById("table1");
var belgium = theTable.rows[1];
function findBelgiumData() {
var belgiumData = [];
for (let i = 2; i < belgium.cells.length; i++) {
var cellData = belgium.cells[i].innerHTML;
belgiumData.push(parseFloat(cellData));
}
}
findBelgiumData();
//FIND THE DATA FOR EACH COUNTRY: PUT A LOOP AROUND THE BELGIUM FUNCTION
// Takes in a table row and iterates starting at the second cell and returns te rest of the data
function findCountryData(country) {
var countryData = [];
for (let i = 2; i < country.cells.length; i++) {
var cellData = country.cells[i].innerHTML;
countryData.push(parseFloat(cellData));
}
return countryData;
}
// findCountryData(theTable.rows[1]);
// findCountryData(theTable.rows[2]);
// ...
// This function takes in a table and returns all the data in the format below
// RETURNS:
// {
// belgium : [..., ...],
// bulgarie : [..., ...]
// }
function getDataFromTable(theTable) {
var countriesData = {};
for (var i = 2; i < document.getElementById("table1").rows.length; i++) {
var countryRow = document.getElementById("table1").rows[i];
var data = findCountryData(countryRow);
var countryName = getNameOfCountry(countryRow);
}
return (countriesData[countryName] = data);
}
function getNameOfCountry() {
return document.getElementById("table1").rows.cells[1].innerHTML;
}
getDataFromTable();
// //
// JSON.stringify(getDataFromTable(theTable));
// //
// Chart js basic data
var ctx = document.getElementById("myChart").getContext("2d");
var chart = new Chart(ctx, {
type: "line",
data: {
labels: yearList,
datasets: [
{
label: getNameOfCountry(),
data: findCountryData()
}
]
}
});
```
vb.js
```var speedCanvas = document.getElementById("speedChart");
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 18;
var dataFirst = {
label: "Car A - Speed (mph)",
data: [0, 59, 75, 20, 20, 55, 40],
lineTension: 0,
fill: false,
borderColor: "red"
};
var dataSecond = {
label: "Car B - Speed (mph)",
data: [20, 15, 60, 60, 65, 30, 70],
lineTension: 0,
fill: false,
borderColor: "blue"
};
var speedData = {
labels: ["0s", "10s", "20s", "30s", "40s", "50s", "60s"],
datasets: [dataFirst, dataSecond]
};
var chartOptions = {
legend: {
display: true,
position: "top",
labels: {
boxWidth: 80,
fontColor: "black"
}
}
};
var lineChart = new Chart(speedCanvas, {
type: "line",
data: speedData,
options: chartOptions
});
//
// CREATE CANVAS WITHOUT TOUCHING HTML
var canvas = document.createElement("canvas");
canvas.id = "myChart";
var header = document.getElementsByTagName("h3")[0];
header.appendChild(canvas);
// YEARS FROM TABLE TO CHART LABEL
var tableOne = document.getElementById("table1");
console.log(tableOne);
var tableOneBody = tableOne.getElementsByTagName("tbody");
var years = tableOneBody[0].childNodes[1];
var correctYear = years.getElementsByTagName("th");
// var time = tableOne.rows.item(1).cells;
// console.log(time);
// for (y = 2; y <time.length; y++) {
// var years = time.item(y).innerHTML;
// console.log(years);
// yearList.push(years);
// }
var yearList = [];
for (l = 2; l < correctYear.length; l++) {
var awesomeYears = correctYear[l].innerHTML;
yearList.push(awesomeYears);
}
//Countrylist tryout
// var countryList = [];
// var tableRowLength = tableOne.rows.length;
// console.log(tableRowLength);
// var country = tableOne.rows.item(2).cells;
// var countryName = country.item(1).innerHTML;
// console.log(countryName);
// for (co = 2; co < tableOne.rows.length; co++) {
// var countryNames = tableOne.rows(co).item(2).innerHTML;
// console.log(countryNames);
// }
// DATA
//BELGIQUE
var Belgique = tableOne.rows.item(2).cells;
var BelgiqueNom = Belgique.item(1).innerHTML;
var BelgiqueNombres = [];
for (b = 2; b < Belgique.length; b++) {
var BelgiqueNrs = Belgique.item(b).innerHTML;
BelgiqueNombres.push(BelgiqueNrs);
}
// console.log(Belgique);
console.log(BelgiqueNom);
// console.log(BelgiqueNrs);
console.log(BelgiqueNombres);
var dataBelgique = {
label: BelgiqueNom,
data: [BelgiqueNombres]
};
//BULGARIE
var Bulgarie = tableOne.rows.item(3).cells;
var BulgarieNom = Bulgarie.item(1).innerHTML;
var BulgarieNombres = [];
for (bb = 2; bb < Bulgarie.length; bb++) {
var BulgarieNrs = Bulgarie.item(bb).innerHTML;
BulgarieNombres.push(BelgiqueNrs);
}
// console.log(Bulgarie);
// console.log(BulgarieNom);
// console.log(BulgarieNrs);
// console.log(BulgarieNombres);
var dataBulgarie = {
label: BulgarieNom,
data: BulgarieNombres
};
//REP TCHEQUE
var RepTcheque = tableOne.rows.item(4).cells;
var RepTchequeNom = RepTcheque.item(1).innerHTML;
var RepTchequeNombres = [];
for (rt = 2; rt < RepTcheque.length; rt++) {
var RepTchequeNrs = RepTcheque.item(rt).innerHTML;
RepTchequeNombres.push(RepTchequeNrs);
}
// console.log(RepTcheque);
// console.log(RepTchequeNom);
// console.log(RepTchequeNrs);
// console.log(RepTchequeNombres);
var dataReptcheque = {
label: RepTchequeNom,
data: RepTchequeNombres
};
//DANMARK
var Danmark = tableOne.rows.item(5).cells;
var DanmarkNom = Danmark.item(1).innerHTML;
var DanmarkNombres = [];
for (d = 2; d < Danmark.length; d++) {
var DanmarkNrs = Danmark.item(d).innerHTML;
DanmarkNombres.push(DanmarkNrs);
}
// console.log(Danmark);
// console.log(DanmarkNom);
// console.log(DanmarkNrs);
// console.log(DanmarkNombres);
var dataDanmark = {
label: DanmarkNom,
data: DanmarkNombres
};
//ALLEMAGNE
var Allemagne = tableOne.rows.item(6).cells;
var AllemagneNom = Allemagne.item(1).innerHTML;
var AllemagneNombres = [];
for (al = 2; al < Allemagne.length; al++) {
var AllemagneNrs = Allemagne.item(al).innerHTML;
AllemagneNombres.push(AllemagneNrs);
}
// console.log(Allemagne);
// console.log(AllemagneNom);
// console.log(AllemagneNrs);
// console.log(AllemagneNombres);
var dataAllemagne = {
label: AllemagneNom,
data: AllemagneNombres
};
//ESTONIE
var Estonie = tableOne.rows.item(7).cells;
var EstonieNom = Estonie.item(1).innerHTML;
var EstonieNombres = [];
for (es = 2; es < Estonie.length; es++) {
var EstonieNrs = Estonie.item(es).innerHTML;
EstonieNombres.push(EstonieNrs);
}
// console.log(Estonie);
// console.log(EstonieNom);
// console.log(EstonieNrs);
// console.log(EstonieNombres);
var dataEstonie = {
label: EstonieNom,
data: EstonieNombres
};
//IRLANDE
var Irlande = tableOne.rows.item(8).cells;
var IrlandeNom = Irlande.item(1).innerHTML;
var IrlandeNombres = [];
for (ir = 2; ir < Irlande.length; ir++) {
var IrlandeNrs = Irlande.item(ir).innerHTML;
IrlandeNombres.push(IrlandeNrs);
}
var dataIrlande = {
label: IrlandeNom,
data: IrlandeNombres
};
// console.log(Irlande);
// console.log(IrlandeNom);
// console.log(IrlandeNrs);
// console.log(IrlandeNombres);
// console.log(dataIrlande);
// var crimiData = {
// labels: yearList,
// datasets: [dataBelgique, dataBulgarie, dataReptcheque, dataDanmark, dataAllemagne, dataEstonie, dataIrlande],
// };
// console.log(crimiData);
//Options
var options = {
scales: {
yAxes: [
{
ticks: {
max: 7000,
min: 0,
stepSize: 200
}
}
]
}
};
// CHART.JS CODE
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "line",
labels: [
"2002",
"2003",
"2004",
"2005",
"2006",
"2007",
"2008",
"2009",
"2010",
"2011",
"2012"
],
datasets: [
{
label: BelgiqueNom,
data: [BelgiqueNombres]
}
],
options: options
});
console.log(yearList);
```
|
tingkts/Android-OTA-update-by-USB-disk
|
tingkts/Android-OTA-update-by-USB-disk
SystemUpdateActivity.java
```package com.ui.android.ota;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.RecoverySystem;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
// Controller of OTA Activity
public class SystemUpdateActivity extends Activity {
final String TAG = "SystemUpdateActivity";
private String mUpdatePackageLocation= "/udisk/";
private String mUpdatePackageFile= "update.zip";
WakeLock mWakelock;
private AlertDialog m_AlertDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate--------------");
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakelock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "OTA Wakelock");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume--------------");
Message msg = mHandler1.obtainMessage(1);
mHandler1.removeMessages(1);
mHandler1.sendMessageDelayed(msg, 10);
}
private Handler mHandler1 = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
m_AlertDialog=onCreateDialog();
m_AlertDialog.show();
Log.d(TAG, "m_AlertDialog.show()");
break;
default:
break;
}
}
};
private AlertDialog onCreateDialog() {
Log.d(TAG, "onCreateDialog--------------");
CharSequence[] array = { "OS (update.zip)"};//, "MCU (mcu.zip)"
return new AlertDialog.Builder(this).setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle(R.string.system_update_activity_mesg)
.setCancelable(false)
.setSingleChoiceItems(array, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked on a radio button do some stuff */
if (whichButton == 1) {
mUpdatePackageFile= "mcu.zip";
} /*else {
mUpdatePackageFile= "update.zip";
}*/
}
}).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Yes so do some stuff */
Toast.makeText(getBaseContext(),"update:"+mUpdatePackageLocation+mUpdatePackageFile, Toast.LENGTH_SHORT).show();
startInstallUpgradePackage();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked No so do some stuff */
dialog.dismiss();
finish();
}
}).create();
}
private void startInstallUpgradePackage() {
File recoveryFile = new File(mUpdatePackageLocation+mUpdatePackageFile);
try {
mWakelock.acquire();
RecoverySystem.installPackage(this, recoveryFile);
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
mWakelock.release();
}
}
@Override
protected void onPause() {
super.onPause();
try {
if (m_AlertDialog !=null && m_AlertDialog.isShowing()) {
m_AlertDialog.dismiss();
}
} catch (Exception e) {
}
finish();
}
}
```
README.md
```### Prepare OTA package
+ make ota package :
`source build/envsetup.sh ; lunch aosp_arm64-eng ; make -j8 otapackage`
+ will generate OTA update package *.zip at out folder : `out/target/product/aosp_arm64/aosp_arm64-ota-eng.tingsung.zip`
+ rename it to update.zip and put it into the usb removeable disk
<br>
### Prepare Apk to show UI and trigger OTA update
+ create activity as the one Settings entry
<div align="center">
<img src="./aosp/packages/apps/OtaUI/screencap/1.png" height="50%" width="50%">
<img src="./aosp/packages/apps/OtaUI/screencap/2.png" height="50%" width="50%">
<img src="./aosp/packages/apps/OtaUI/screencap/3.png" height="50%" width="50%">
<img src="./aosp/packages/apps/OtaUI/screencap/4.png" height="50%" width="50%">
</div>
<br>
```
diff --git a/device.mk b/imx8q/ms5765/device.mk
index ed39733b..1f3cd41c 100644
--- a/device.mk
+++ b/device.mk
@@ -294,3 +294,6 @@ PRODUCT_PROPERTY_OVERRIDES += ro.frp.pst=/dev/block/by-name/presistdata
PRODUCT_COMPATIBLE_PROPERTY_OVERRIDE := true
BOARD_VNDK_VERSION := current
+
+PRODUCT_PACKAGES += \
+ OtaUI
\ No newline at end of file
diff --git a/packages/apps/Settings/res/values/config.xml b/packages/apps/Settings/res/values/config.xml
index 5380d2d0..e23a0295 100644
--- a/packages/apps/Settings/res/values/config.xml
+++ b/packages/apps/Settings/res/values/config.xml
@@ -15,7 +15,7 @@
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string name="additional_system_update" translatable="false">com.android.ota</string>
- <string name="additional_system_update_menu" translatable="false">com.android.ota.OtaAppActivity</string>
+ <string name="additional_system_update" translatable="false">com.ui.android.ota</string>
+ <string name="additional_system_update_menu" translatable="false">com.ui.android.ota.SystemUpdateActivity</string>
</resources>
--
```
<br>
+ call `RecoverySystem.installPackage(this, recoveryFile);` to execute recovery "setup-bcb" service and reboot to recovery mode.
```
xref: /frameworks/base/services/core/java/com/android/server/RecoverySystemService.java
258 private boolean setupOrClearBcb(boolean isSetup, String command) {
259 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
260
261 final boolean available = checkAndWaitForUncryptService();
262 if (!available) {
263 Slog.e(TAG, "uncrypt service is unavailable.");
264 return false;
265 }
266
267 if (isSetup) {
268 SystemProperties.set("ctl.start", "setup-bcb");
269 } else {
270 SystemProperties.set("ctl.start", "clear-bcb");
271 }
272
273 // Connect to the uncrypt service socket.
274 LocalSocket socket = connectService();
275 if (socket == null) {
276 Slog.e(TAG, "Failed to connect to uncrypt socket");
277 return false;
278 }
279
280 DataInputStream dis = null;
281 DataOutputStream dos = null;
282 try {
283 dis = new DataInputStream(socket.getInputStream());
284 dos = new DataOutputStream(socket.getOutputStream());
285
286 // Send the BCB commands if it's to setup BCB.
287 if (isSetup) {
288 byte[] cmdUtf8 = command.getBytes("UTF-8");
289 dos.writeInt(cmdUtf8.length);
290 dos.write(cmdUtf8, 0, cmdUtf8.length);
291 dos.flush();
292 }
293
294 // Read the status from the socket.
295 int status = dis.readInt();
296
297 // Ack receipt of the status code. uncrypt waits for the ack so
298 // the socket won't be destroyed before we receive the code.
299 dos.writeInt(0);
300
301 if (status == 100) {
302 Slog.i(TAG, "uncrypt " + (isSetup ? "setup" : "clear") +
303 " bcb successfully finished.");
304 } else {
305 // Error in /system/bin/uncrypt.
306 Slog.e(TAG, "uncrypt failed with status: " + status);
307 return false;
308 }
309 } catch (IOException e) {
310 Slog.e(TAG, "IOException when communicating with uncrypt:", e);
311 return false;
312 } finally {
313 IoUtils.closeQuietly(dis);
314 IoUtils.closeQuietly(dos);
315 IoUtils.closeQuietly(socket);
316 }
317
318 return true;
319 }
```
<br>
<br>
### Mount usb disk in the recovery mode
mount usb removeable disk, generally its node is /dev/block/sda1 to the specific mount point /udisk.
[0001-mount-usb-removeable-disk.patch](./aosp/bootable/recovery/0001-mount-usb-removeable-disk.patch)
[0002-disable-selinux-before-execute-install_pacakge.patch](./aosp/bootable/recovery/0002-disable-selinux-before-execute-install_pacakge.patch)
!! issue: in the recovery mode, need to close selinux, and thus it can mount /dev/block/sda1 to /udisk,
otherwise fails. However, they are no avc denied logs to show which rule is violated!
<br>
add sepolicy to allow recovery to setenforce/getenforce
[0001-add-sepolicy-rule-for-recovery-to-set-getenforce.patch](./aosp/bootable/device/fsl/imx8q/sepolicy/0001-add-sepolicy-rule-for-recovery-to-set-getenforce.patch)
!! issue: `permissive recovery;` only allow to be used in eng or user-debug build, can not use it in user build.
<br>
### Print log to UART console in the recovery mode
```
#ifndef _LANDSEM_RECOVERY_LOG_H
#define _LANDSEM_RECOVERY_LOG_H
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdarg.h>
#define USE_UART_DEBUG 1
#if USE_UART_DEBUG
#define DEBUG_UART_PORT /* "/dev/ttyS0" */ /* "/dev/console" */ "/dev/ttyLP0"
#endif
static int consolelog(const char *fmt, ...) {
int ret;
va_list ap;
va_start(ap, fmt);
#if USE_UART_DEBUG
FILE *tty_out = fopen(DEBUG_UART_PORT, "w+");
if(NULL != tty_out) {
ret = vfprintf(tty_out, fmt, ap);
fclose(tty_out);
tty_out = NULL;
}
else {
ret = vfprintf(stdout, fmt, ap);
}
#else
ret = vfprintf(stdout, fmt, ap);
#endif
va_end(ap);
return ret;
}
#endif // _LANDSEM_RECOVERY_LOG_H
```
> ref: [【recovery】android使用串口打印recovery调试日志 by yingxian_Fei](https://blog.csdn.net/smilefyx/article/details/78836476)
> ref: [redirect_stdio()](http://androidxref.com/9.0.0_r3/search?q=&defs=redirect_stdio&refs=&path=&hist=&project=art&project=bionic&project=bootable&project=build&project=compatibility&project=cts&project=dalvik&project=developers&project=development&project=device&project=external&project=frameworks&project=hardware&project=kernel&project=libcore&project=libnativehelper&project=packages&project=pdk&project=platform_testing&project=prebuilts&project=sdk&project=system&project=test&project=toolchain&project=tools), [ui->Print()](http://androidxref.com/9.0.0_r3/search?q=%22ui-%3Eprint%22&defs=&refs=&path=&hist=&project=art&project=bionic&project=bootable&project=build&project=compatibility&project=cts&project=dalvik&project=developers&project=development&project=device&project=external&project=frameworks&project=hardware&project=kernel&project=libcore&project=libnativehelper&project=packages&project=pdk&project=platform_testing&project=prebuilts&project=sdk&project=system&project=test&project=toolchain&project=tools)
<br>
### Disable selinux in the recovery mode
* append [BOARD_KERNEL_CMDLINE += androidboot.selinux=permissive](http://androidxref.com/9.0.0_r3/search?q=%22androidboot.selinux%22&defs=&refs=&path=&hist=&project=art&project=bionic&project=bootable&project=build&project=compatibility&project=cts&project=dalvik&project=developers&project=development&project=device&project=external&project=frameworks&project=hardware&project=kernel&project=libcore&project=libnativehelper&project=packages&project=pdk&project=platform_testing&project=prebuilts&project=sdk&project=system&project=test&project=toolchain&project=tools) to kernel commands.
```
@ BoardConfig.mk
BOARD_KERNEL_CMDLINE += androidboot.selinux=permissive
```
* setenforce/getenforce
library: `LOCAL_STATIC_LIBRARIES += libselinux` or `LOCAL_SHARED_LIBRARIES := libselinux`
header file: `#include <selinux/selinux.h>`
[xref: /external/selinux/libselinux/include/selinux/selinux.h](http://androidxref.com/9.0.0_r3/xref/external/selinux/libselinux/include/selinux/selinux.h#329)
```
H A D selinux.h 329 extern int security_setenforce(int value);
```
[xref: /external/selinux/libselinux/src/setenforce.c](http://androidxref.com/9.0.0_r3/xref/external/selinux/libselinux/src/setenforce.c#12)
```
12int security_setenforce(int value)
13{
14 int fd, ret;
15 char path[PATH_MAX];
16 char buf[20];
17
18 if (!selinux_mnt) {
19 errno = ENOENT;
20 return -1;
21 }
22
23 snprintf(path, sizeof path, "%s/enforce", selinux_mnt);
24 fd = open(path, O_RDWR | O_CLOEXEC);
25 if (fd < 0)
26 return -1;
27
28 snprintf(buf, sizeof buf, "%d", value);
29 ret = write(fd, buf, strlen(buf));
30 close(fd);
31 if (ret < 0)
32 return -1;
33
34 return 0;
35}
```
* print kernel command line:
```
cat /proc/cmdline
```
* final solution:
[append "androidboot.selinux=permissive" into kernel cmdline in uboot](./aosp/vendor/nxp-opensource/uboot-imx/0001-disable-selinux-in-recovery-mode.patch)
[define DALLOW_PERMISSIVE_SELINUX in init service](./aosp/system/core/0001-disable-selinux-in-recovery-mode.patch)
<br>
ref: [【Android】如何配置打开和关闭selinux by xlnaan](https://blog.csdn.net/xlnaan/article/details/87867698)
<br>
<br>
> Base on android 9 with Non-A/B update system mechanism.
```
|
tingng123/newdynamic
|
tingng123/newdynamic
throw_bricks.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class throw_bricks : MonoBehaviour
{
public Rigidbody2D rb;
public GameObject BRICK_notHit;
public float torque;
public float damage = 1f;
private Vector2 direction;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
direction = Vector2.right;
torque = 0.5f;
// rb.AddForce(new Vector2(0f, UpForce), ForceMode2D.Impulse);
}
void Update()
{
Rigidbody2D rb = GetComponent<Rigidbody2D>();
if (rb.velocity.magnitude < 1f)
{
BRICK_notHit = Instantiate(BRICK_notHit, transform.position, Quaternion.identity) as GameObject;
Destroy(this.gameObject);
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy")
{ collision.gameObject.GetComponent<EnemyHealth>().TakeDamage(damage);
GameObject BRICK_notHitclone = Instantiate(BRICK_notHit, transform.position, Quaternion.identity) as GameObject;
BRICK_notHitclone.GetComponent<Rigidbody2D>().AddTorque(torque, ForceMode2D.Impulse);
Destroy(this.gameObject);
Destroy(BRICK_notHitclone, 20f);
}
}
/// void OnCollisionExit2D(Collision2D collision)
/// {
/// if (collision.gameObject.tag == "Enemy")
/// {
/// transform.gameObject.tag = "Untagged";
/// }
/// }
// Update is called once per frame
void FixedUpdate()
{
// rb.velocity = direction * speed;
//// rb.velocity = new Vector2( 0f , 20f);
}
}
```
flip.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class flip : MonoBehaviour
{
private Transform target;
// Start is called before the first frame update
// private GameObject child;
private Canvas healthCavas;
// public GameObject canvasBoard; // variable
/// private Vector3 theScale;
public bool m_FacingRight;
public float stoppingDistance = 3f;
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
// healthCavas.transform.localScale = new Vector3(1f, 1f, 1f);
//Vector3 canvasscale = canvasBoard.transform.localScale;
}
// Update is called once per frame
void FixedUpdate()
{
if (Vector2.Distance(transform.position, target.position) < stoppingDistance)
{
if (target.position.x > transform.position.x && !m_FacingRight)
{
//face right
// child.transform.parent = parent.transform;
// transform.DetachChildren();
// transform.localScale = new Vector3(-1.2f, 1.4f, 1);
// theScale = transform.localScale;
Flip();
}
else if (target.position.x < transform.position.x && m_FacingRight)
{
//face left
//transform.localScale = new Vector3(1.2f, 1.4f, 1);
/// theScale = transform.localScale;
// theScale.x = Mathf.Abs(theScale.x);
Flip();
}
}
// canvasBoard.transform.localScale = canvasscale;
}
public void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
////////theScale.x *= Mathf.Abs(theScale.x);
// healthCavas.transform.localScale = theScale;
// canvasBoard.transform.localScale = canvasscale;
}
}
```
enemy_green_object.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy_green_object : MonoBehaviour
{
public EnemyHealth health;
public GameObject[] bodypart;
public CommonScript commonscript;
public GameObject blood;
public GameObject bloodparticle;
private Rigidbody2D rb;
public Animator anim;
public float speed = 1f;
private Transform target;
public float patrolspeed = 0.5f;
public float waitTime = 4f;
public float startWaitTime;
public Transform[] moveSpots;
private int randomspot;
public flip flipping;
public bool m_FacingRight;
public Transform reference;
public float knockbackAmount = 2f;
public Vector2 impulse;
public float attackrange;
public float attackcooltime;
public float Timesinceattack =0f;
//private Transform target;
// Start is called before the first frame update
void Start()
{
Rigidbody2D rb = GetComponent<Rigidbody2D>();
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
m_FacingRight = flipping.m_FacingRight;
// waitTime = startWaitTime;
randomspot = Random.Range(0, moveSpots.Length);
}
// Update is called once per frame
void Update()
{
Timesinceattack += Time.deltaTime;
// if (target.position.x > transform.position.x)
// {
// //face right
// transform.localScale = new Vector3(-1, 1, 1);
// }
// else if (target.position.x < transform.position.x)
// {
// //face left
// transform.localScale = new Vector3(1, 1, 1);
// }
if (anim.GetBool("chasing"))
{
transform.position = Vector2.MoveTowards(transform.position, new Vector2(target.position.x, transform.position.y), speed * Time.deltaTime);
}
if (transform.position.x - target.position.x < attackrange && attackcooltime <= Timesinceattack)
{
Timesinceattack = 0f;
// anim.SetBool("chasinig", false);
}
if (anim.GetBool("patrol"))
{
transform.position = Vector2.MoveTowards(transform.position, new Vector2(moveSpots[randomspot].position.x, transform.position.y), patrolspeed * Time.deltaTime);
if (moveSpots[randomspot].position.x > transform.position.x && flipping.m_FacingRight == false)
{
//face right
// child.transform.parent = parent.transform;
// transform.DetachChildren();
// transform.localScale = new Vector3(-1.2f, 1.4f, 1);
// theScale = transform.localScale;
flipping.Flip();
}
else if (moveSpots[randomspot].position.x < transform.position.x && flipping.m_FacingRight )
{
//face left
//transform.localScale = new Vector3(1.2f, 1.4f, 1);
/// theScale = transform.localScale;
// theScale.x = Mathf.Abs(theScale.x);
// flipping.Flip();
flipping.Flip();
}
if (Vector2.Distance(transform.position, moveSpots[randomspot].position) < 0.3f)
{
anim.SetBool("patrol", false);
// if (waitTime <= 0)
// {
randomspot = Random.Range(0, moveSpots.Length);
// waitTime = startWaitTime;
// }
// else
// {
// waitTime -= Time.deltaTime;
/// }
}
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "brick" || collision.gameObject.tag == "weapon")
{
GameObject bloodclone = Instantiate(blood, transform.position, Quaternion.identity);
Destroy(bloodclone, 5f);
GameObject bloodparticleclone = Instantiate(bloodparticle, transform.position, Quaternion.identity);
Destroy(bloodparticleclone, 5f);
}
if (collision.gameObject.tag == "weapon")
{
Debug.Log("knockback");
}
if (collision.gameObject.tag == "roadblock")
{
// if (anim.)
anim.SetBool("patrol", false);
}
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "brick")
{
GameObject bloodclone = Instantiate(blood, transform.position, Quaternion.identity);
Destroy(bloodclone, 5f);
GameObject bloodparticleclone = Instantiate(bloodparticle, transform.position, Quaternion.identity);
Destroy(bloodparticleclone, 5f);
}
if (collision.gameObject.tag == "weapon")
{
GameObject bloodclone = Instantiate(blood, transform.position, Quaternion.identity);
Destroy(bloodclone, 5f);
GameObject bloodparticleclone = Instantiate(bloodparticle, transform.position, Quaternion.identity);
Destroy(bloodparticleclone, 5f);
Debug.Log("knockback");
}
}
void OnDestroy()
{
commonscript.BodyBreakDown(bodypart, transform.position);
}
}
```
GameAsset.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameAsset : MonoBehaviour
{
private static GameAsset _i;
public static GameAsset i
{
get
{
if (_i == null) _i = Instantiate(Resources.Load<GameAsset>("GameAsset"));
return _i;
}
}
public SoundAudioClip[] soundAudioClipArray;
[System.Serializable]
public class SoundAudioClip {
public SoundManager.Sound sound;
public AudioClip audioClip;
}
// Start is called before the first frame update
private void awake()
{
SoundManager.Initialize();
}
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
```
playercontroller.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playercontroller : MonoBehaviour
{
public CharacterController2D controller;
public Rigidbody2D rb;
public bool facingRt = true;
//public bool flip = true;
public float runSpeed = 40f;
float horizontalMove = 0f;
bool jump = false;
bool crouch = false;
private Vector3 difference;
public bool isCrouching;
public Transform ceiling;
public float radiuss = 0.02f;
public LayerMask ground;
public bool isGrounded;
public Transform grounder;
public float radiuss2 = 0.02f;
public LayerMask ground2;
public Animator anim;
public GameObject brick;
public Transform throwPt;
public float distance;
public float height;
public float Force;
public float rotZ;
public GameObject glassbottle;
/// jump
public float actionCooldown = 1.0f;
public float timeSinceAction = 0.0f;
/// run
public float throwActionCooldown = 1.0f;
public float timeSincethrowAction = 0.0f;
// throw
public float animCooldown = 1.0f;
public float timeSinceanim = 0.0f;
//CryOut: varaible for new equipment and attack system
public PlayerInventory PlayerInventory;
public InventoryScript InventoryScript;
//CryOut: Dialgoue system
public DialogueManager dialoguemanager;
//CryOut: PlayerStat
public int playerhp;
// Update is called once per frame
// public AudioSource walk;
void Start()
{
//walk= GetComponent<AudioSource>();
PlayerInventory = this.GetComponent<PlayerInventory>();
InventoryScript = GameObject.Find("MainCanvas").GetComponent<InventoryScript>();
}
void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
isCrouching = Physics2D.OverlapCircle(ceiling.transform.position, radiuss, ground);
isGrounded = Physics2D.OverlapCircle(grounder.transform.position, radiuss2, ground2);
timeSinceAction += Time.deltaTime;
timeSincethrowAction += Time.deltaTime;
timeSinceanim += Time.deltaTime;
///move
///
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
anim.SetFloat("speed", Mathf.Abs(horizontalMove));
///facing right?
if (Input.GetAxisRaw("Horizontal") > 0)
{
facingRt = true;
}
else if (Input.GetAxisRaw("Horizontal") < 0)
{
facingRt = false;
}
///Jump
/// if (Input.GetKey(KeyCode.W) && isCrouching == false && timeSinceAction >= actionCooldown)
if (Input.GetKeyDown(KeyCode.W) && isCrouching == false && jump == false)
{
anim.SetBool("isJumping", true);
/// timeSinceAction = 0;
anim.SetBool("landing", false);
}
if (anim.GetBool("Jump"))
{
jump = true;
}
///Crouch
if (Input.GetKeyDown(KeyCode.S))
{
crouch = true;
anim.SetBool("isCrouching", true);
}
else if (Input.GetKeyUp(KeyCode.S))
{
crouch = false;
anim.SetBool("isCrouching", false);
}
///attack
if (Input.GetKeyDown(KeyCode.K) && isGrounded)
{
Debug.Log("attack");
anim.SetBool("attack", true);
}
///throw
if (Input.GetKeyDown(KeyCode.J) && isGrounded && timeSinceanim >= animCooldown)
{
Debug.Log("Throw");
anim.SetTrigger("throw");
timeSincethrowAction = 0f;
throwbrick(0);
timeSinceanim = 0f;
SoundManager.PlaySound(SoundManager.Sound.playerthrow);
}
///throw
if (Input.GetKeyDown(KeyCode.L) && isGrounded && timeSinceanim >= animCooldown)
{
Debug.Log("ThrowGlass");
anim.SetTrigger("throw");
timeSincethrowAction = 0f;
throwglass(0);
timeSinceanim = 0f;
SoundManager.PlaySound(SoundManager.Sound.playerthrow);
}
//New attack system by CryOut
if (Input.GetKeyDown(KeyCode.Q))
{
if(PlayerInventory.EquippedItem != null && PlayerInventory.EquippedItem.type == "Projectile" && PlayerInventory.stackamount[PlayerInventory.EquippedSlotNumber] > 0)
{
if (PlayerInventory.EquippedItem.ID == 1)
{
// ID 1 : Glass Bottle
anim.SetTrigger("throw");
timeSincethrowAction = 0f;
throwglass(0);
timeSinceanim = 0f;
SoundManager.PlaySound(SoundManager.Sound.playerthrow);
}
if (PlayerInventory.EquippedItem.ID == 2)
{
// ID 2 : Brick
anim.SetTrigger("throw");
timeSincethrowAction = 0f;
throwbrick(0);
timeSinceanim = 0f;
SoundManager.PlaySound(SoundManager.Sound.playerthrow);
}
PlayerInventory.stackamount[PlayerInventory.EquippedSlotNumber] -= 1;
if (PlayerInventory.StackChecking(PlayerInventory.EquippedSlotNumber) == false)
{
PlayerInventory.EquippedItem = null;
PlayerInventory.EquippedSlotNumber = 100;
}
StartCoroutine(InventoryScript.inventoryReset());
//checking stack remained
//player.EquippedStackAmount -= 1;
if (PlayerInventory.EquippedSlotNumber != 100)
{
InventoryScript.equipmentsetup(PlayerInventory.stackamount[PlayerInventory.EquippedSlotNumber]);
}
else
{
InventoryScript.equipmentsetup(100);
}
}
}
//
// if(anim.GetBool("IsRunning"))
//{
// if (!footstep.isPlaying)
// {
// footstep.Play(0);
// }
//}
// else
// { walk.Stop(); }
}
public void OnLanding()
{
// anim.SetBool("isJumping", false);
anim.SetBool("Jump", false);
jump = false;
anim.SetBool("landing", true);
}
public void OnCrouching(bool isCrouching)
{
}
public void throwglass(int value)
{
GameObject glassbottleclone = Instantiate(glassbottle, throwPt.transform.position, Quaternion.Euler(new Vector3(0, 0, -90))) as GameObject;
glassbottleclone.GetComponent<Rigidbody2D>().AddForce(throwPt.up * Force, ForceMode2D.Impulse);
glassbottleclone.GetComponent<Rigidbody2D>().AddTorque(-0.005f, ForceMode2D.Impulse);
horizontalMove = 0f;
}
public void throwbrick(int value)
{
GameObject brickclone = Instantiate(brick, throwPt.transform.position, Quaternion.Euler(new Vector3(0, 0, -90))) as GameObject;
brickclone.GetComponent<Rigidbody2D>().AddForce(throwPt.up * Force, ForceMode2D.Impulse);
brickclone.GetComponent<Rigidbody2D>().AddTorque(-0.01f, ForceMode2D.Impulse);
// ... flip the player.
horizontalMove = 0f;
}
// if (collision.gameObject.tag == "Enemy" )
// {
// Destroy(brick);//}
void FixedUpdate()
{
// Move our character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
}
}```
InventoryScript.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class InventoryScript : MonoBehaviour
{
//inventory
public GameObject InventoryBoard;
public Button[] slots;
public bool inventory_opened = false;
public PlayerInventory PlayerInventory;
public Sprite buttonimg;
//equipment
public GameObject EquipmentBoard;
public Text ProjectileNumber;
public Image equipImg;
public bool closeinventory()
{
EquipmentBoard.SetActive(false);
InventoryBoard.SetActive(false);
inventory_opened = false;
ButtonClear();
return false;
}
public void ButtonClear()
{
//clear all item set in InventorySetUp function (to reset inventory panel)
for (int i = 0; i < slots.Length; i++)
{
Destroy(slots[i].gameObject.GetComponent<Item>());
}
}
public bool openinventory()
{
inventorysetup(PlayerInventory.inventory);
EquipmentBoard.SetActive(true);
InventoryBoard.SetActive(true);
inventory_opened = true;
return true;
}
public void inventorysetup(List<Item> inventory)
{
for (int i = 0; i< inventory.Count; i++)
{
if (inventory[i] == null)
{
//set item slot image default image
slots[i].image.sprite = buttonimg;
break;
}
else
{
if (slots[i].gameObject.GetComponent<Item>() == null)
{
//add item to each item slot
Item temp = slots[i].gameObject.AddComponent<Item>();
temp.ItemName = inventory[i].ItemName;
temp.ID = inventory[i].ID;
temp.icon = inventory[i].icon;
temp.type = inventory[i].type;
slots[i].image.sprite = temp.icon;
//set stack text
Text text = slots[i].gameObject.GetComponentInChildren<Text>();
text.text = PlayerInventory.stackamount[i].ToString();
}
}
}
//slot number assign and button set up
for (int i = 0; i < slots.Length; i++)
{
slots[i].gameObject.GetComponent<inventoryButton>().slotnumber = i;
slots[i].gameObject.GetComponent<inventoryButton>().ButtonSetUp();
}
}
public void equipmentsetup(int stacknumber)
{
Debug.Log("equip set up");
ProjectileNumber.text = stacknumber.ToString();
if(stacknumber == 0 || stacknumber == 100)
{
ProjectileNumber.text = "";
equipImg.enabled = false;
equipImg.sprite = null;
}
}
public IEnumerator inventoryReset()
{
ButtonClear();
yield return new WaitForEndOfFrame();
inventorysetup(PlayerInventory.inventory);
}
}
```
SoundManager.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class SoundManager
{
// Start is called before the first frame update
public enum Sound
{
playerthrow,
playerwalk
}
private static Dictionary<Sound, float> soundTimerDictionary;
public static void Initialize() {
soundTimerDictionary = new Dictionary<Sound, float>();
soundTimerDictionary[Sound.playerwalk] = 0f;
}
public static void PlaySound(Sound sound)
{if (CanPlaySound(sound)) {
GameObject soundGameObject = new GameObject("Sound");
AudioSource audioSource = soundGameObject.AddComponent<AudioSource>();
audioSource.PlayOneShot(GetAudioClip(sound));
}
}
public static bool CanPlaySound(Sound sound)
{
switch (sound)
{
default:
return true;
case Sound.playerwalk:
if (soundTimerDictionary.ContainsKey(sound))
{
float lastTimePlayed = soundTimerDictionary[sound];
float playerwalkTimeMax = .4f;
if (lastTimePlayed + playerwalkTimeMax < Time.time)
{
soundTimerDictionary[sound] = Time.time;
return true;
}
else
{
return false;
}
} else { return true; }
// break;
}
}
public static AudioClip GetAudioClip(Sound sound)
{
foreach (GameAsset.SoundAudioClip soundAudioClip in GameAsset.i.soundAudioClipArray)
{
if (soundAudioClip.sound == sound)
{
return soundAudioClip.audioClip;
}
}
Debug.LogError("Sound" + sound + "not found");
return null;
}
}```
glassbottle.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class glassbottle : MonoBehaviour
{
private Rigidbody2D rb;
public float damage =3f;
/// public GameObject glassshatter;
public GameObject shatter;
public float speed = 2f;
// public GameObject fireballprefab;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
}
void OnCollisionEnter2D(Collision2D collision)
{
Destroy(this.gameObject);
// GameObject glassshatterclone = Instantiate(glassshatter, transform.position, Quaternion.identity) as GameObject;
GameObject shatterpoint = Instantiate(shatter, transform.position, Quaternion.identity) as GameObject;
// GameObject fireballclone = Instantiate(fireballprefab, transform.position, Quaternion.Euler(0.0f, 0.0f, 0.0f)) as GameObject;
// BRICK_notHit.GetComponent<Rigidbody2D>().AddTorque(torque, ForceMode2D.Impulse);
// Destroy(fireballclone, 0.9f);
Destroy(shatterpoint, 10f);
Debug.Log(22);
if (collision.gameObject.tag == "Enemy")
{
collision.gameObject.GetComponent<EnemyHealth>().TakeDamage(damage);
}
}
/// void OnCollisionExit2D(Collision2D collision)
/// {
/// if (collision.gameObject.tag == "Enemy")
/// {
/// transform.gameObject.tag = "Untagged";
/// }
/// }
// Update is called once per frame
void FixedUpdate()
{
// rb.velocity = direction * speed;
//// rb.velocity = new Vector2( 0f , 20f);
}
}
```
PlayerInventory.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInventory : MonoBehaviour
{
public List<Item> inventory = new List<Item>();
public List<int> stackamount;
public ItemDB itemDB;
public GameObject canvas;
public InventoryScript InventoryScript;
public GameObject droplocation;
public bool CanPickUp;
public GameObject pickupobj = null;
public Item EquippedItem;
//100 = no equipment
public int EquippedSlotNumber;
private void Start()
{
itemDB = GameObject.Find("ItemDB").GetComponent<ItemDB>();
InventoryScript = GameObject.Find("MainCanvas").GetComponent<InventoryScript>();
InventoryScript.PlayerInventory = this;
droplocation = gameObject.transform.GetChild(0).gameObject;
//for (int i = 0; i < InventoryScript.slots.Length; i++)
//{
// InventoryScript.slots[i].gameObject.GetComponent<inventoryButton>().InventoryScript =
//}
}
public void additem(int id)
{
StartCoroutine(InventoryScript.inventoryReset());
for (int i = 0; i < inventory.Count; i++)
{
//there is item inside inventory of player
if (inventory[i] != null)
{
// there is "same" item inside inventory
if (inventory[i].ID == id)
{
//check whether we can stack it up
if (stackamount[i] == inventory[i].maxamount)
{
Debug.Log("full stack");
}
else
{
//stack
stackamount[i] += 1;
break;
}
}
}
//cant stack-> normal new item adding process
if (inventory[i] == null)
{
inventory[i] = itemDB.items[id];
stackamount[i] += 1;
break;
}
}
}
public bool StackChecking(int slotnumber)
{
//check whether we used up all the stack
if (stackamount[slotnumber] == 0)
{
inventory.RemoveAt(slotnumber);
inventory.Add(null);
stackamount.Remove(stackamount[slotnumber]);
stackamount.Add(0);
return false;
}
else
{
return true;
}
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Pickable")
{
CanPickUp = true;
pickupobj = collision.gameObject;
}
}
public void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Pickable")
{
CanPickUp = false;
pickupobj = null;
}
}
public void Update()
{
if (Input.GetKeyDown(KeyCode.E) && CanPickUp == true)
{
Debug.Log("pick up");
pickupobj.gameObject.GetComponent<Item>().pikcup(this);
}
}
}
```
CommonScript.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CommonScript : MonoBehaviour
{
public InventoryScript inventoryScript;
private bool inventory_opened;
public bool startmenu_opened;
public bool pausing;
public GameObject MainMenu;
public GameObject InGameObj;
public GameObject PauseMenu;
private void Update()
{
if (startmenu_opened == false)
{
//pause menu
if (Input.GetKeyDown(KeyCode.Escape))
{
if (pausing == true)
{
resumegame();
}
else
{
pausegame();
}
}
//inventory menu
if (Input.GetKeyDown(KeyCode.I))
{
if (inventory_opened == true)
{
inventory_opened = inventoryScript.closeinventory();
}
else
{
inventory_opened = inventoryScript.openinventory();
}
}
}
}
public void StartGame(int sceneindex)
{
MainMenu.SetActive(false);
InGameObj.SetActive(true);
startmenu_opened = false;
SceneManager.LoadScene(sceneindex);
}
public void QuitGame()
{
Application.Quit();
}
public void pausegame()
{
Time.timeScale = 0.0f;
PauseMenu.SetActive(true);
pausing = true;
}
public void resumegame()
{
Time.timeScale = 1.0f;
PauseMenu.SetActive(false);
pausing = false;
}
public void BodyBreakDown(GameObject[] bodypart, Vector3 position)
{
for (int i = 0; i < bodypart.Length; i++)
{
GameObject temp = Instantiate(bodypart[i], position, Quaternion.identity);
Destroy(temp, 5f);
}
}
}
```
shatterpoint.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shatterpoint : MonoBehaviour
{
ParticleSystem particle;
public GameObject fireprefab;
public GameObject fireballprefab;
//public GameObject glassbroken;
///public Transform bloodground;
private List<ParticleCollisionEvent> collisionEvents = new List<ParticleCollisionEvent>();
// public AudioSource audioSource;
// public AudioClip[] sounds;
public float SoundCapResetSpeed = 0.55f;
public int MaxSounds = 3;
float TimePassed;
int soundsPlayed;
/// public float offset;
///float Vector3 Offset;
private void Start()
{
particle = GetComponent<ParticleSystem>();
}
private void Update()
{
///Vector3 Offset = new Vector3(0.0f, offset, 0.0f);
// TimePassed += Time.deltaTime;
// if (TimePassed > SoundCapResetSpeed)
// {
// soundsPlayed = 0;
// TimePassed = 0;
// }
}
private void OnParticleCollision(GameObject other)
{
ParticlePhysicsExtensions.GetCollisionEvents(particle, other, collisionEvents);
int count = collisionEvents.Count;
/// for (int i = 0; i < count; i++)
// {
GameObject fireprefabclone = Instantiate(fireprefab, transform.position, Quaternion.Euler(0.0f, 0.0f, 0.0f)) as GameObject;
GameObject fireballclone = Instantiate(fireballprefab, transform.position, Quaternion.Euler(0.0f, 0.0f, 0.0f)) as GameObject;
Destroy(fireprefabclone, 5f);
// if (soundsPlayed < MaxSounds)
// {
// soundsPlayed += 1;
// audioSource.pitch = Random.Range(0.9f, 1.1f);
// audioSource.PlayOneShot(sounds[Random.Range(0, sounds.Length)], Random.Range(0.1f, 0.35f));
//}
//}
}
}
```
umbrella.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class umbrella : MonoBehaviour
{
public Animator anim;
public Animator pen;
float horizontalMove = 0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (pen.GetBool("isRunning"))
{
anim.SetBool("isRunning", true);
}
else
{
anim.SetBool("isRunning", false);
}
if(pen.GetBool("isCrouching"))
{
anim.SetBool("isCrouching", true);
}
else
{
anim.SetBool("isCrouching", false);
}
if (pen.GetBool("isCrouchingrunning"))
{
anim.SetBool("isCrouchingrunning", true);
}
else
{
anim.SetBool("isCrouchingrunning", false);
}
}
}
```
EnemyHealth.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class EnemyHealth : MonoBehaviour
{
public float MaxHealth = 100;
public Slider HealthBar;
public TextMeshProUGUI hp;
public GameObject popup;
public float CurrentHealth;
public Animator anim;
void start()
{
hp = GetComponent<TextMeshProUGUI>();
CurrentHealth = MaxHealth ;
hp.text = CurrentHealth.ToString() + "/" + MaxHealth.ToString();
}
public void TakeDamage(float damage)
{
CurrentHealth -= damage;
anim.SetTrigger("hurt");
HealthBar.value = CurrentHealth;
if (CurrentHealth <= 0)
{
Destroy(gameObject);
}
hp.text = CurrentHealth.ToString() + "/" + MaxHealth.ToString();
GameObject popupclone = Instantiate(popup, transform.position, Quaternion.identity,transform);
popupclone.GetComponent<TextMeshPro>().text = damage.ToString();
}
void Update()
{
// print(CurrentHealth);
}
}```
mouseaim.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouseaim : MonoBehaviour
{
public float offset;
public float rotZ;
public CharacterController2D controller;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
}
}
```
hitpoint.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class hitpoint : MonoBehaviour
{
private Rigidbody2D rb;
public Transform attack;
public float radiuss = 0.02f;
public LayerMask enemy;
public float damage = 3f;
public Vector2 direction;
public float knockbackAmount = 10f;
public bool knockfromRt;
public playercontroller controller;
public Transform player;
// public float knockbackStrength;
// public float knockbackRadius;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attack.transform.position, radiuss, enemy);
foreach (Collider2D enemy in hitEnemies)
{
}
}
public void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag ("Enemy"))
{
Rigidbody2D enemy = other.GetComponent<Rigidbody2D>();
if(enemy != null)
{
if (enemy.transform.position.x < player.transform.position.x)
{
enemy.transform.Translate(-1f*knockbackAmount,0f,0f);
}
else if (enemy.transform.position.x > player.transform.position.x )
{
enemy.transform.Translate(1f* knockbackAmount,0f,0f);
}
enemy.GetComponent<EnemyHealth>().TakeDamage(damage);
}
// enemy.transform.Translate(direction * knockbackAmount);
Debug.Log("knockback");
}
}
void OnDrawGizmosSelected()
{
if (attack == null)
return;
Gizmos.DrawWireSphere(attack.position, radiuss);
}
}
```
Item.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Item : MonoBehaviour
{
public int ID;
public string ItemName;
public Sprite icon;
public int maxamount;
public string type;
public int damage;
public int healing;
public int durability;
public virtual void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player" )
{
Debug.Log("enter");
collision.gameObject.GetComponent<PlayerInventory>().CanPickUp = true;
}
}
public void pikcup(PlayerInventory inventory)
{
Debug.Log("pick");
inventory.additem(this.GetComponent<Item>().ID);
Destroy(this.gameObject);
inventory.gameObject.GetComponent<PlayerInventory>().CanPickUp = false;
}
}
```
melee_attack.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class melee_attack : MonoBehaviour
{
private Collider2D hitbox;
public float damage = 3f;
public Animator anim;
public bool attack;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Enemy" && anim.GetBool("attack"))
{
if (this.transform.position.x > gameObject.transform.position.x)
{
// Vector2 impulse = new Vector2(knockback, 0f);
}
else if (this.transform.position.x < gameObject.transform.position.x)
{
// Vector2 impulse = new Vector2(-knockback, 0f);
}
collision.gameObject.GetComponent<EnemyHealth>().TakeDamage(damage);
}
}
}```
Dialogue.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dialogue: MonoBehaviour
{
public int set;
public string NPC_name;
public string[] sentences;
public bool optionCheck;
public string[] options;
public List<Item> HandCarry = new List<Item>();
}
```
DialogueManager.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DialogueManager : MonoBehaviour
{
public Text DialogueText;
public Text SpeakerName;
public string fulltext;
public string currenttext;
public Dialogue[] DialogueSet;
public int DialogueSetOrder;
public bool FirstDialogue;
public bool displaying;
public Dialogue currentDialogue;
public GameObject dialoguepanel;
public GameObject optionpanel;
public GameObject[] optionbuttons;
public Text[] optiontext;
public Queue<string> sentences = new Queue<string>();
public playercontroller playercontroller;
//item system
public GameObject currentNPC;
public NPC currentNPCstat;
public PlayerInventory playerinventory;
public GameObject InformationPanel;
public ItemDB itemdb;
public void DialogueStart(Dialogue dialogue)
{
if (FirstDialogue == true)
{
DialogueSetOrder = 0;
FirstDialogue = false;
}
currentDialogue = dialogue;
sentences.Clear();
//putting sentence inside dialogue class into the queue
foreach (string sentence in dialogue.sentences)
{
sentences.Enqueue(sentence);
}
dialoguepanel.SetActive(true);
currentNPCstat = currentNPC.GetComponent<NPC>();
NextSentence();
DialogueSet = dialogue.gameObject.GetComponents<Dialogue>();
SpeakerName.text = dialogue.NPC_name;
}
public void NextSentence()
{
//Clearing of the sentence;
if (sentences.Count == 0)
{
//item system (Getting item from NPC)
if(currentDialogue.HandCarry.Count >= 1)
{
Debug.Log("hand carry");
playerinventory = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerInventory>();
int loopNumber = currentDialogue.HandCarry.Count;
Item item = currentDialogue.HandCarry[0];
for (int i = 0; i< loopNumber; i++)
{
Debug.Log(currentDialogue.HandCarry.Count);
if (currentDialogue.HandCarry.Count > 0)
{
if(currentDialogue.HandCarry[0] != null)
{
Debug.Log("test");
playerinventory.additem(currentDialogue.HandCarry[0].ID);
currentDialogue.HandCarry.RemoveAt(0);
}
}
}
Debug.Log("finished");
itemdb = GameObject.Find("ItemDB").GetComponent<ItemDB>();
InformationPanel.transform.GetChild(0).gameObject.GetComponent<Image>().sprite = itemdb.items[item.ID].icon;
InformationPanel.transform.GetChild(1).gameObject.GetComponent<Text>().text = "你獲得了" + itemdb.items[item.ID].ItemName + " " + loopNumber + "個。";
StartCoroutine(InfoDisplay());
}
if (currentDialogue.optionCheck == true)
{
optionbuttons = new GameObject[currentDialogue.options.Length];
optiontext = new Text[currentDialogue.options.Length];
for (int i = 0; i < currentDialogue.options.Length; i++)
{
Debug.Log("option " + i + " is " + currentDialogue.options[i]);
optionbuttons[i] = optionpanel.transform.GetChild(i).gameObject;
optionbuttons[i].SetActive(true);
optiontext[i] = optionbuttons[i].transform.GetChild(0).gameObject.GetComponent<Text>();
optiontext[i].text = currentDialogue.options[i];
}
optionpanel.SetActive(true);
}
else
{
currentNPCstat.talked = true;
DialogueReset();
}
}
else
{
// Quickly show the whole sentence
if (displaying == true)
{
displaying = false;
currenttext = fulltext;
DialogueText.text = currenttext;
}
//normal process, display next sentence
else
{
fulltext = sentences.Dequeue();
StartCoroutine(DisplayDialogue());
}
}
}
public void DialogueReset()
{
//reset
dialoguepanel.SetActive(false);
FirstDialogue = true;
currenttext = "";
DialogueText.text = currenttext;
optionpanel.SetActive(false);
currentNPC = null;
}
IEnumerator DisplayDialogue()
{
displaying = true;
//keyboard typing display style
for (int i = 0; i < fulltext.Length; i ++)
{
if (displaying == true)
{
currenttext = fulltext.Substring(0, i + 1);
DialogueText.text = currenttext;
yield return new WaitForSeconds(0.05f);
if (currenttext.Length == fulltext.Length && currentDialogue.optionCheck == true && sentences.Count == 0)
{
NextSentence();
}
}
}
displaying = false;
}
//called when option button is onclicked
public void OptionDetermine(int chosennumber)
{
DialogueSetOrder += chosennumber;
DialogueStart(DialogueSet[DialogueSetOrder]);
optionpanel.SetActive(false);
}
//called to display information in the middle of the screen
IEnumerator InfoDisplay()
{
InformationPanel.SetActive(true);
Color imgColor = InformationPanel.GetComponent<Image>().color;
Color itemColor = InformationPanel.transform.GetChild(0).gameObject.GetComponent<Image>().color;
Color textColor = InformationPanel.transform.GetChild(1).gameObject.GetComponent<Text>().color;
imgColor.a = 1;
itemColor.a = 1;
while (imgColor.a > 0)
{
imgColor.a -= 0.01f;
itemColor.a -= 0.01f;
textColor.a -= 0.01f;
InformationPanel.GetComponent<Image>().color = imgColor;
InformationPanel.transform.GetChild(0).gameObject.GetComponent<Image>().color = itemColor;
InformationPanel.transform.GetChild(1).gameObject.GetComponent<Text>().color = textColor;
yield return new WaitForSeconds(0.05f);
}
if (imgColor.a < 0)
{
InformationPanel.SetActive(false);
}
}
}
```
firedamage.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class firedamage : MonoBehaviour
{
ParticleSystem particle;
private List<ParticleCollisionEvent> collisionEvents = new List<ParticleCollisionEvent>();
public int damage;
public float DPS = 1f;
private float timeSinceDPS;
// Start is called before the first frame update
void Start()
{
particle = GetComponent<ParticleSystem>();
timeSinceDPS = DPS;
}
// Update is called once per frame
void Update()
{
timeSinceDPS += Time.deltaTime;
}
private void OnParticleCollision(GameObject other)
{
ParticlePhysicsExtensions.GetCollisionEvents(particle, other, collisionEvents);
int count = collisionEvents.Count;
if (other.gameObject.tag == "Enemy" && timeSinceDPS >= DPS)
{
int damage = Random.Range( 2, 5);
other.gameObject.GetComponent<EnemyHealth>().TakeDamage(damage);
timeSinceDPS = 0f;
}
}
}```
idle.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class idle : StateMachineBehaviour
{
public float stoppingDistance;
private Transform target;
public float patrolWaitTime = 3f;
public float idleTime = 0f;
public float attackrange =0.5f;
// OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
// OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
idleTime += Time.deltaTime;
if (attackrange < Vector2.Distance(animator.transform.position, target.position) && Vector2.Distance(animator.transform.position, target.position) < stoppingDistance)
{
animator.SetBool("chasing", true);
}
else if (attackrange > Vector2.Distance(animator.transform.position, target.position) )
{
animator.SetBool("chasing", false);
animator.SetBool("attack", false);
}
if (idleTime >= patrolWaitTime)
{
animator.SetBool("patrol", true);
idleTime = 0f;
}
if (attackrange < Vector2.Distance(animator.transform.position, target.position))
{
animator.SetBool("attack", true);
}
}
// OnStateExit is called when a transition ends and the state machine finishes evaluating this state
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
}
// OnStateMove is called right after Animator.OnAnimatorMove()
//override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
//{
// // Implement code that processes and affects root motion
//}
// OnStateIK is called right after Animator.OnAnimatorIK()
//override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
//{
// // Implement code that sets up animation IK (inverse kinematics)
//}
}
```
SaveSystem.cs
```using System.IO;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
public class SaveSystem
{
public static void saveplayer(PlayerSave player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/player.save";
FileStream filestream = new FileStream(path, FileMode.Create);
//PlayerSave data = new PlayerSave();
}
}
```
popup.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class popup : MonoBehaviour
{
public float destroy = 10f;
public Vector3 Offset = new Vector3(0,0,0);
// Start is called before the first frame update
void Start()
{
Vector3 Offset = new Vector3(Random.Range(-0.4f, 0.4f), Random.Range(0.8f, 1.0f), 0);
transform.localPosition += Offset;
transform.eulerAngles = new Vector3(0,0 , Random.Range(-30f,30f));
}
// Update is called once per frame
void Update()
{
Destroy(gameObject, destroy);
}
}
```
NPC.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPC : MonoBehaviour
{
public bool talked;
private GameObject talkboard;
public bool readytotalk;
public bool istalking;
public DialogueManager dialoguemanager;
public bool timerbool;
public GameObject test;
public bool talkinput;
public void Start()
{
talkboard = gameObject.transform.GetChild(0).gameObject;
dialoguemanager = GameObject.Find("MainCanvas").gameObject.GetComponent<DialogueManager>();
}
public void Update()
{
if (Input.GetKeyDown(KeyCode.Z))
{
talkinput = true;
}
else
{
talkinput = false;
}
// if collision trigger
if (readytotalk == true)
{
if (talkinput == true && istalking == false)
{
if (talked == true)
{
//if talked already
Debug.Log("talked already");
dialoguemanager.DialogueStart(gameObject.GetComponent<RemainedDialogue>());
istalking = true;
StartCoroutine(timer());
}
else
{
istalking = true;
dialoguemanager.DialogueStart(gameObject.GetComponent<Dialogue>());
StartCoroutine(timer());
//dialoguemanager.NextSentence();
}
}
if (talkinput == true && istalking == true && dialoguemanager.FirstDialogue == false && timerbool == true)
{
StartCoroutine(timer());
dialoguemanager.NextSentence();
}
}
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
talkboard.SetActive(true);
readytotalk = true;
dialoguemanager.currentNPC = this.gameObject;
}
}
public void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
talkboard.SetActive(false);
readytotalk = false;
istalking = false;
dialoguemanager.DialogueReset();
dialoguemanager.currentNPC = null;
}
}
IEnumerator timer()
{
timerbool = false;
yield return new WaitForSeconds(0.1f);
timerbool = true;
}
}
```
RemainedDialogue.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RemainedDialogue : Dialogue
{
}
```
chasing.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class chasing : StateMachineBehaviour
{
public float speed;
public float stoppingDistance;
public float attackrange = 1f;
private Transform target;
// OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
// OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
// animator.transform.position = Vector2.MoveTowards(animator.transform.position, new Vector2(target.position.x, animator.transform.position.y), speed * Time.deltaTime);
if (Vector2.Distance(animator.transform.position, target.position) > stoppingDistance)
{
animator.SetBool("chasing", false);
animator.SetBool("patrol", false);
}
if (Vector2.Distance(animator.transform.position, target.position) < attackrange)
{
animator.SetBool("patrol", false);
animator.SetBool("chasing", false);
animator.SetBool("attack", true);
}
}
// OnStateExit is called when a transition ends and the state machine finishes evaluating this state
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
}
// OnStateMove is called right after Animator.OnAnimatorMove()
//override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
//{
// // Implement code that processes and affects root motion
//}
// OnStateIK is called right after Animator.OnAnimatorIK()
//override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
//{
// // Implement code that sets up animation IK (inverse kinematics)
//}
}
```
firesound.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class firesound : MonoBehaviour
{ private AudioSource audioSource;
public AudioClip glassbreak;
// Start is called before the first frame update
void Start()
{
audioSource = GetComponent<AudioSource>();
audioSource.clip = glassbreak;
audioSource.pitch = (Random.Range(0.7f, 1.6f));
audioSource.Play();
}
// Update is called once per frame
void Update()
{
}
}
```
inventoryButton.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class inventoryButton : MonoBehaviour
{
public Item item;
public PlayerInventory PlayerInventory;
public int slotnumber;
public Text text;
public InventoryScript InventoryScript;
public ItemDB itemDB;
public Button CloseButton;
public Button UseButton;
public GameObject EquipmentPanel;
private void Start()
{
itemDB = GameObject.Find("ItemDB").GetComponent<ItemDB>();
EquipmentPanel = InventoryScript.gameObject.transform.Find("InGameObj").gameObject.transform.Find("EquipmentPanel").gameObject;
InventoryScript.equipImg = EquipmentPanel.transform.Find("Equipped Image").GetComponent<Image>();
}
public void ButtonSetUp()
{
CloseButton = gameObject.transform.GetChild(1).gameObject.GetComponent<Button>();
UseButton = gameObject.GetComponent<Button>();
if (this.gameObject.GetComponent<Item>() != null)
{
item = this.gameObject.GetComponent<Item>();
CloseButton.gameObject.SetActive(true);
UseButton.enabled = true;
}
PlayerInventory = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerInventory>();
InventoryScript = GameObject.Find("MainCanvas").GetComponent<InventoryScript>();
text.text = PlayerInventory.stackamount[slotnumber].ToString();
//reset stack number in UI
if (text.text == "0")
{
text.text = "";
CloseButton.gameObject.SetActive(false);
UseButton.enabled = false;
}
}
public void itemUse()
{
Debug.Log("I used" + item.ItemName);
if (item.type == "Projectile")
{
Debug.Log("proj");
PlayerInventory.EquippedSlotNumber = slotnumber;
PlayerInventory.EquippedItem = PlayerInventory.inventory[slotnumber];
InventoryScript.equipImg.enabled = true;
InventoryScript.equipImg.sprite = PlayerInventory.EquippedItem.icon;
//player.stackamount[slotnumber] -= 1;
PlayerInventory.StackChecking(slotnumber);
StartCoroutine(InventoryScript.inventoryReset());
// become zero
if (PlayerInventory.StackChecking(slotnumber) == false){
InventoryScript.equipImg.enabled = false;
InventoryScript.equipImg.sprite = null;
}
InventoryScript.equipmentsetup(PlayerInventory.stackamount[PlayerInventory.EquippedSlotNumber]);
} else if(item.type == "Consumable")
{
Debug.Log("consumable");
InventoryRefresh();
} else
{
InventoryRefresh();
}
}
public void InventoryRefresh()
{
PlayerInventory.stackamount[slotnumber] -= 1;
PlayerInventory.StackChecking(slotnumber);
StartCoroutine(InventoryScript.inventoryReset());
}
public void itemRemove()
{
Debug.Log("remove" +item.ItemName);
PlayerInventory.stackamount[slotnumber] -= 1;
PlayerInventory.StackChecking(slotnumber);
StartCoroutine(InventoryScript.inventoryReset());
//drop item
Instantiate(itemDB.items[item.ID], PlayerInventory.droplocation.transform.position, Quaternion.identity);
}
}
```
PlayerSave.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PlayerSave
{
public int level;
public string Playername;
public PlayerSave(int level, string Playername)
{
this.level = level;
this.Playername = Playername;
}
}
```
DontDestoryScript.cs
```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DontDestoryScript : MonoBehaviour
{
public GameObject obj;
private void Awake()
{
obj = this.gameObject;
DontDestroyOnLoad(obj);
}
public void destory()
{
Destroy(obj);
}
}
```
|
tingxiongbest/MyRepository
|
tingxiongbest/MyRepository
README.md
```# MyRepository
It Just A begin
```
|
tinlokijusaringan/SimsH4CK3R
|
tinlokijusaringan/SimsH4CK3R
README.md
```# SIMS4 BY SimsH4CK3R
TORRENTS ONLY
magnet:?xt=urn:btih:8f295a975b9232dbb2add424c16b09ba6db2e822&dn=rutor.info_The+Sims+4%3A+Deluxe+Edition+%5Bv+1.52.100.1020+%2B+DLCs%5D+%282014%29+PC+%7C+RePack+%D0%BE%D1%82+FitGirl&tr=udp://opentor.org:2710&tr=udp://opentor.org:2710&tr=http://retracker.local/announce
```
|
tinomwadeyi/tinomwadeyi.github.io
|
tinomwadeyi/tinomwadeyi.github.io
README.md
```A personal portolio of my projects with extra details that cannot fit onto my CV.
```
|
tinoni/gloss
|
tinoni/gloss
glossify.min.js
```var magic_gloss={supports_canvas:function(){return !!document.createElement("canvas").getContext},supports_ToDataURL:function(){if(!this.supports_canvas()){return false}var a=document.createElement("canvas");var b=a.toDataURL("image/png");return(b.indexOf("data:image/png")==0)},hex2rgb:function(b){var a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(b);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:{r:0,g:0,b:0}},rgb_str:function(a,b){return"rgba("+a.r+","+a.g+","+a.b+","+b+")"},main:function(k,g,l){if(!$(k).is("img")){return}l=l||1;var i=this.hex2rgb(g);var c=document.createElement("canvas");var b=c.getContext("2d");var p=k.width;var j=k.height;var m=Math.min(p,j);c.width=m;c.height=m+m/3;b.save();b.beginPath();b.arc(m/2,m/2,m/2,0,Math.PI*2,false);b.clip();try{b.drawImage(k,0,0,p,j)}catch(f){return}b.restore();b.save();var s=b.createRadialGradient(m/3,m/1.2,0,m/2,m/2,m/2);s.addColorStop(0,"rgba(255,255,255,0)");s.addColorStop(1,this.rgb_str(i,0.9*l));b.fillStyle=s;b.beginPath();b.arc(m/2,m/2,m/2,0,Math.PI*2,false);b.fill();b.restore();var e=b.createLinearGradient(m/2,0,m/2,m/2);e.addColorStop(0,this.rgb_str({r:255,g:255,b:255},1*l));e.addColorStop(1,this.rgb_str({r:255,g:255,b:255},0.11*l));b.save();b.scale(1.25,1);b.beginPath();b.arc(m/2.5,m/3.5,m/4,0,2*Math.PI,false);b.restore();b.fillStyle=e;b.fill();var o=m/3;var n=m/1.2;var a=m/7;b.save();var s=b.createRadialGradient(o,n,0,o,n,a);s.addColorStop(0,"rgba(255,255,255,1)");s.addColorStop(1,"rgba(255,255,255,0)");b.fillStyle=s;b.beginPath();b.arc(o,n,a,0,Math.PI*2,false);b.fill();b.restore();var q=function(h,d,u,t,r){b.save();b.globalCompositeOperation="destination-over";b.beginPath();b.fillStyle="#fff";b.translate(d-t,u-r);b.scale(t,r);b.arc(1,1,1,0,2*Math.PI,false);b.shadowColor=h.rgb_str(i,0.5*l);b.shadowBlur=3*m/14;b.shadowOffsetX=0;b.shadowOffsetY=1.5*m/14;b.fill();b.restore()};q(this,m/2,m/1.35,m/2.7,m/4);k.please_glow=false;k.src=c.toDataURL("image/png");k.width=c.width;k.height=c.height}};$(function(){if(!magic_gloss.supports_ToDataURL()){return}$("img[data-gloss]").each(function(a,b){$(b).load(function(){if(this.please_glow!=false){var e=$(b).attr("data-glosscolor");var d=$(b).attr("data-glossalpha");magic_gloss.main(b,e,d)}}).each(function(){if(b.complete){$(b).load()}})})});(function(a){a.fn.glossify=function(b){var d=this;var c={color:"#000000",alpha:1};c=a.extend(c,b||{});this.each(function(e,f){magic_gloss.main(f,c.color,c.alpha)});return this}})(jQuery);```
README.md
```glossify.js
============
A jQuery plugin that transforms any image into a beautiful and colourful glossy sphere.
## Home and demo
View a live [demo](https://tinoni.github.io/gloss/).
## Usage
Step 1: include JQuery and glossify.js in your page
<script src="jquery.js"/>
<script src="glossify.js"/>
Step 2: every image you want to glossify just include the data-gloss attribute
<image src="html5.png" data-gloss/>
Step 3: there is no step 3 :-)
## Further options
There are more options. Please visit the homepage to read the complete documentation.
## License
You may use polaroid.js under the terms of the MIT License. [More information](http://en.wikipedia.org/wiki/MIT_License).
```
glossify.js
```/**
* User: mfernandes http://openxrest.com/gloss/
* Date: 22/11/13
* Time: 14:42
* minify with http://refresh-sf.com/yui/
*/
var magic_gloss = {
supports_canvas: function () {
return !!document.createElement('canvas').getContext;
},
supports_ToDataURL: function () {
if(!this.supports_canvas()) return false;
var canvas = document.createElement("canvas");
var data = canvas.toDataURL("image/png");
return (data.indexOf("data:image/png") == 0);
},
hex2rgb: function (hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : {
r: 0,
g: 0,
b: 0
};
},
rgb_str: function(rgb_obj, alpha) {
return 'rgba(' + rgb_obj.r + ',' + rgb_obj.g + ',' + rgb_obj.b + ',' + alpha + ')';
},
main: function (src_img, color, alpha_factor) {
if (!$(src_img).is('img')) return; //if not image then move on
alpha_factor = alpha_factor || 1;
var color_rgb = this.hex2rgb(color);
//var canvas = document.getElementById("b");
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
var w = src_img.width;
var h = src_img.height;
var d = Math.min(w, h);
canvas.width = d;
canvas.height = d+d/3;
//define the clipping path
context.save();
context.beginPath();
context.arc(d/2, d/2, d/2, 0, Math.PI * 2, false);
context.clip();
//draw image
try {
context.drawImage(src_img, 0, 0, w, h);
}
catch (err) {
return; //some problem with this image: nothing to do
}
context.restore(); //end clipping path
//radial gradient (inner glow)
context.save();
var gradient_innerglow = context.createRadialGradient(d/3, d/1.2, 0, d/2, d/2, d/2);
gradient_innerglow.addColorStop(0.0, 'rgba(255,255,255,0)');
gradient_innerglow.addColorStop(1.0, this.rgb_str(color_rgb, 0.9*alpha_factor)); //with transparency
//draw
context.fillStyle = gradient_innerglow;
context.beginPath();
context.arc(d/2, d/2, d/2, 0, Math.PI * 2, false);
context.fill();
context.restore();
//top glow
//linear gradient
var gradient_linear = context.createLinearGradient(d/2, 0, d/2, d/2);
gradient_linear.addColorStop(0.0, this.rgb_str({r:255,g:255,b:255}, 1*alpha_factor));
gradient_linear.addColorStop(1.0, this.rgb_str({r:255,g:255,b:255}, 0.11*alpha_factor));
//draw
context.save();
// scale context horizontally
context.scale(1.25, 1);
// draw circle which will be stretched into an oval
context.beginPath();
context.arc(d/2.5, d/3.5, d/4, 0, 2 * Math.PI, false);
// restore to original state
context.restore();
// apply styling
context.fillStyle = gradient_linear;
context.fill();
//shinning
var x = d/3;
var y = d/1.2;
var r = d/7;
context.save();
var gradient_innerglow = context.createRadialGradient(x, y, 0, x, y, r);
gradient_innerglow.addColorStop(0.0, 'rgba(255,255,255,1)');
gradient_innerglow.addColorStop(1.0, 'rgba(255,255,255,0)'); //with transparency
//draw
context.fillStyle = gradient_innerglow;
context.beginPath();
context.arc(x, y, r, 0, Math.PI * 2, false);
context.fill();
context.restore();
//shadow
var elypse = function(that, cx, cy, rx, ry) {
context.save();
context.globalCompositeOperation = "destination-over";
context.beginPath();
context.fillStyle = '#fff';
context.translate(cx-rx, cy-ry);
context.scale(rx, ry);
context.arc(1, 1, 1, 0, 2 * Math.PI, false);
context.shadowColor = that.rgb_str(color_rgb, 0.5*alpha_factor);
context.shadowBlur = 3*d/14;
context.shadowOffsetX = 0;
context.shadowOffsetY = 1.5*d/14;
context.fill();
context.restore();
};
elypse(this, d/2, d/1.35, d/2.7, d/4); //shadow
//copy canvas back to original img
src_img.please_glow = false; //do not fire load event again
src_img.src = canvas.toDataURL("image/png");
//correct width and height
src_img.width = canvas.width;
src_img.height = canvas.height;
//cleanup
canvas = null;
} //end main
}; //end magic_gloss namespace
$(function() {
//main
if (!magic_gloss.supports_ToDataURL()) {
return; //quit if ToDataURL not supported by this browser
}
$("img[data-gloss]").each(function(i, obj) {
$(obj).load(function() {
if (this.please_glow != false) {
var c = $(obj).attr("data-glosscolor");
var a = $(obj).attr("data-glossalpha");
magic_gloss.main(obj, c, a);
}
}).each(function() {
if(obj.complete) $(obj).load();
});
});
}); //end magic_gloss
//jquery plugin
(function($){
$.fn.glossify = function(options) {
var that = this; //a reference to ourselves
var settings = {
color: "#000000",
alpha: 1
};
settings = $.extend(settings, options || {});
//main
//magic_gloss.main(this[0], settings.color, settings.alpha);
this.each(function(i, obj) {
magic_gloss.main(obj, settings.color, settings.alpha);
});
return this;
};
})(jQuery);```
|
tinsleyfok/portfolio
|
tinsleyfok/portfolio
README.md
```# portfolio
This is a new portfolio website designed and developed by me @2023
```
|
tintabari/first
|
tintabari/first
README.md
```# Flow App
This repository is the pushbreaker example
Gihub hook activated
feature-001 - set page backgound color to #00aab4
feature-002 add first paragraph to index page
```
|
tintinap/flask-api
|
tintinap/flask-api
app.py
```# Server Side
from flask import Flask
from flask_restful import Api, Resource, abort, reqparse, marshal_with, fields
from flask_sqlalchemy import SQLAlchemy, Model
app = Flask(__name__)
#database
db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///dabase.db'
api = Api(app)
class CityModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
temp = db.Column(db.String(100), nullable=False)
weather = db.Column(db.String(100), nullable=False)
people = db.Column(db.String(100), nullable=False)
def __repr__(self):
return f'City(name={name}, temp={temp}, weather={weather}, people={people})'
db.create_all()
#Add Request Parser
city_add_args = reqparse.RequestParser()
city_add_args.add_argument('name', type=str, required=True, help='pls fill ur province name')
city_add_args.add_argument('temp', type=str, required=True, help='pls fill ur province temperature')
city_add_args.add_argument('weather', type=str, required=True, help='pls fill ur province weather')
city_add_args.add_argument('people', type=str, required=True, help='pls fill ur number of people of the province ')
#Update Request Parser
city_update_args = reqparse.RequestParser()
city_update_args.add_argument('name', type=str, help='pls specify ur province name')
city_update_args.add_argument('temp', type=str, help='pls specify ur province temperature')
city_update_args.add_argument('weather', type=str, help='pls specify ur province weather')
city_update_args.add_argument('people', type=str, help='pls specify ur number of people of the province ')
resource_field = {
'id': fields.Integer,
'name': fields.String,
'temp': fields.String,
'weather': fields.String,
'people': fields.String
}
# my_city = {
# 1 : { 'province_name':'Bangkok', 'weather': 'hot', 'people': 5000},
# 2 : { 'province_name':'Chonburi', 'weather': 'rainny', 'people': 4000},
# 3 : { 'province_name':'Rayong', 'weather': 'cloudy', 'people': 3000}
# }
# #validate request
# def not_found_name_city(city_id):
# if name not in my_city:
# abort(404, message="no province u've called")
#design
class WeatherCity(Resource):
@marshal_with(resource_field)
def get(self, city_id):
# not_found_city_id_city(city_id)
# return my_city[name]
result = CityModel.query.filter_by(id=city_id).first()
if not result:
abort(404, message='city not found')
return result
@marshal_with(resource_field)
def post(self, city_id):
result = CityModel.query.filter_by(id=city_id).first()
if result:
abort(409, message='used id')
args = city_add_args.parse_args()
city = CityModel(id=city_id, name=args['name'], temp=args['temp'], weather=args['weather'], people=args['people'])
db.session.add(city)
db.session.commit()
return city, 201
@marshal_with(resource_field)
def patch(self, city_id):
args=city_update_args.parse_args()
result = CityModel.query.filter_by(id=city_id).first()
if not result:
abort(404, message='city to update not found')
if args['name']:
result.name = args['name'] # change name
if args['temp']:
result.temp = args['temp'] # change temp
if args['weather']:
result.weather = args['weather'] # change weather
if args['people']:
result.people = args['people'] # change people
db.session.commit()
return result
#call
api.add_resource(WeatherCity, "/weather/<string:city_id>")
if __name__ == "__main__":
app.run(debug=True)```
test_request.py
```# Client Side
import requests
URL = 'http://127.0.0.1:5000/weather/2'
response = requests.get(URL)
message = response.json()
print(message)```
|
tinyteabird/Portfolio-website
|
tinyteabird/Portfolio-website
README.md
```# Portfolio-website
Portfolio for our every little thing
```
|
tinywall/tinywall.net
|
tinywall/tinywall.net
README.md
```tinywallnet.github.io
=====================
Tinywall.net website
```
|
tipmvp/GitHub
|
tipmvp/GitHub
T.java
```package github;
/**
* @author XRZ
* @date 2019/5/8
* @Description :
*/
public class T {
public static void main(String[] args) {
System.out.println("conmjgdm");
System.out.println("dddff");
}
}
```
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 13