branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>import json import decimal from flask import Flask, request, jsonify from database import get_connection # from flask_marshmallow import Marshmallow app = Flask(__name__) def json_encode_decimal(obj): if isinstance(obj, decimal.Decimal): return str(obj) raise TypeError(repr(obj) + " is not JSON serializable") # endpoint to get min price # @app.route('/api/minprice/<product_id>', methods=['GET']) def get_min_price(product_id): connect = get_connection() cursor = connect.cursor() sql = "{CALL GetGiaNhapThapNhat (@tukhoa=?)}" params = product_id cursor.execute(sql, params) rows = cursor.fetchall() # data = [] # column_names = [column[0] for column in cursor.description] # for r in row: # data.append(dict(zip(column_names, r))) data = [] for row in rows: data.append([x for x in row]) price_str = json.dumps(data[0][3], default=json_encode_decimal) price = float(price_str.replace('"', '')) res = { 'NCC': data[0][4], 'price': price, 'thoi_gian_giao_hang': data[0][5] } return res @app.route("/api/min/price", methods=['POST', 'GET']) def get_params(): data = request.json l = [] for i in data: a = get_min_price(i["MA_HANG"]) l.append(a) return jsonify(l) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') <file_sep>from database import get_connection import pyodbc import json import decimal connect = get_connection() cursor = connect.cursor() #Sample select query # cursor.execute("SELECT * from KHO_XUAT_KHO WHERE NGAY_CHUNG_TU = '2019-12-03';") # cursor.execute("exec GetGiaNhapThapNhat('MH00229842')") # cursor.execute("{call GetGiaNhapThapNhat(MH00229841)}") sql = """\ { CALL GetGiaNhapThapNhat (@tukhoa=?) } """ params = ('MH00229842') cursor.execute(sql, params) # rows = cursor.fetchone() rows = cursor.fetchall() data = [] for row in rows: data.append([x for x in row]) # # # while row: # # # print(row[0]) # # # row = cursor.fetchone() # # print(data) # column_names = [column[0] for column in cursor.description] # for row in rows: # data.append(dict(zip(column_names, row))) # res = { # 'price': data[0][] # } def json_encode_decimal(obj): if isinstance(obj, decimal.Decimal): return str(obj) raise TypeError(repr(obj) + " is not JSON serializable") d = json.dumps(data[0][3], default=json_encode_decimal) d_1 = d.replace('"', '') # print(data[0][3], type(data[0][3])) print(type(rows), rows) print(d) print(d_1, type(d_1)) print(float(d_1))
bd562d91eed4f87e0d2eb311418294a8eaabf3d5
[ "Python" ]
2
Python
datnt-dev/min_price_sql
7ba36ad1cdedbe457c75be9b1d75750da73218fd
70cbb094b18f3aea14896e51a02991fde8bd8b15
refs/heads/master
<repo_name>mazoruss/chatterbox-server<file_sep>/server/request-handler2.js var fs = require('fs'); var path = require('path'); // var bodyParser = require('bodyParser'); var defaultCorsHeaders = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS', 'access-control-allow-headers': 'content-type, accept', 'access-control-max-age': 10 // Seconds. }; // Set up the headers and body var actions = { GET: function(request, response, responseBody ) { response.status(200); fs.readFile('messages.txt', (err, data) => { responseBody.results = JSON.parse(data); response.end(JSON.stringify(responseBody)); }); }, POST: function(request, response, responseBody) { statusCode = 201; fs.readFile('messages.txt', (err, data) => { //Get the currently stored messages // console.log('req body', request.body); var messageData = JSON.parse(data.toString()); var newMessage = JSON.parse(Object.keys(request.body)[0]); newMessage.createdAt = new Date(); //Add the new message to the messages array and write it to the file messageData.unshift(newMessage); fs.writeFile('messages.txt', JSON.stringify(messageData), (err) => { }); response.end(); }); }, OPTIONS: function(request, response, responseBody) { response.status(200); fs.readFile('messages.txt', (err, data) => { responseBody.results = JSON.parse(data); response.end(JSON.stringify(responseBody)); }); } }; var requestHandler = function(request, response) { var responseBody = { method: request.method, url: request.url, results: [] }; console.log('Serving request type ' + request.method + ' for url ' + request.url); var action = actions[request.method]; action(request, response, responseBody); }; exports.requestHandler = requestHandler;<file_sep>/server/expressive.js var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var handler = require('./request-handler2'); //app.use(function1) var addHeader = function(req, res, next) { res.set('access-control-allow-origin', '*'); res.set('access-control-allow-methods', 'GET, POST, PUT, DELETE, OPTIONS'); res.set('access-control-allow-headers', 'content-type, accept'); res.set('access-control-max-age', 10 ); res.set('Content-Type', 'application/json'); next(); }; app.use(express.static('/Users/student/Desktop/2016-09-chatterbox-server/client/client/')); app.use(addHeader); app.use(bodyParser()); app.get('/classes/messages', handler.requestHandler); app.post('/classes/messages', handler.requestHandler); // app.options('/classes/messages', handler.requestHandler); app.listen(3005, function() { console.log('You\'ve been hacked!'); }); // var responseBody = { // headers: headers, // method: request.method, // url: request.url, // results: [] // };
c9167cc8322a28ad4caf733d7539357739e91d53
[ "JavaScript" ]
2
JavaScript
mazoruss/chatterbox-server
ce3ec097da731038f3c0b101ea8c51f400958ffc
aecddb2ef2ac53505b744ad48d5888f392f00ad5
refs/heads/master
<repo_name>xw5/first_uniapp<file_sep>/backupData/ulick.js export default uLikeData = [ { "id": "marvel-1026", "name": "毒液:致命守护者", "poster": "http://172.16.58.3:88/superhero/MARVEL/Venom/poster.png", "cover": "http://172.16.58.3:88/superhero/MARVEL/Venom/cover.png", "trailer": "http://172.16.58.3:88/superhero/MARVEL/Venom/trailer.mp4", "score": 8.9, "prisedCounts": 7892, "basicInfo": "2018 / 美国 / 科幻 / 超级英雄", "originalName": "原名:Venom", "releaseDate": "上映时间:2018-11-09(中国大陆)", "totalTime": "影片时长:112分钟", "plotDesc": "艾迪(汤姆·哈迪 <NAME> 饰)是一位深受观众喜爱的新闻记者,和女友安妮(米歇尔·威廉姆斯 <NAME> 饰)相恋多年,彼此之间感情十分要好。安妮是一名律师,接手了生命基金会的案件,在女友的邮箱里,艾迪发现了基金会老板德雷克(里兹·阿迈德 Riz Ahmed 饰)不为人知的秘密。为此,艾迪不仅丢了工作,女友也离他而去", "directors": "['']", "actors": "['']", "plotPics": "[\"http://172.16.58.3:88/superhero/MARVEL/Venom/photos/1.png\",\"http://172.16.58.3:88/superhero/MARVEL/Venom/photos/2.png\",\"http://172.16.58.3:88/superhero/MARVEL/Venom/photos/3.png\",\"http://172.16.58.3:88/superhero/MARVEL/Venom/photos/4.png\",\"http://172.16.58.3:88/superhero/MARVEL/Venom/photos/5.png\"]", "createTime": "2018-11-09T07:40:37.000+0000" }, { "id": "marvel-1007", "name": "黑豹", "poster": "http://172.16.58.3:88/superhero/MARVEL/BlackPanther/poster.png", "cover": "http://172.16.58.3:88/superhero/MARVEL/BlackPanther/cover.png", "trailer": "http://172.16.58.3:88/superhero/MARVEL/BlackPanther/trailer.mp4", "score": 5.9, "prisedCounts": 2367, "basicInfo": "2018 / 美国 / 科幻 / 超级英雄", "originalName": "原名:<NAME>", "releaseDate": "上映时间:2018-03-09(中国大陆) ", "totalTime": "影片时长:134分钟", "plotDesc": "位于非洲的神秘国家瓦坎达,凭借来自宇宙的振金而成为科技极度发达的国家,不过他们长久封闭,始终对外界保守这个秘密。在前国王死于联合国爆炸袭击后,特查拉王子(查德维克·博斯曼 <NAME> 饰)继任成为新的国王,同时他也是黑豹的继承者。登基之后,特查拉与前女友娜吉雅(露皮塔·尼永奥 Lupita Nyong'o 饰)、贴身侍卫奥姆烨(丹娜·奎里拉 Danai Gurira 饰)追查曾经盗取振金并杀害瓦坎达人的尤利西斯·克劳(安迪·瑟金斯 Andy Serkis 饰)。一番厮杀后,克劳侥幸逃脱,谁知最终死于合伙人艾瑞克·克尔芒戈(迈克尔·B·乔丹 <NAME> 饰)之手。艾瑞克同样具有瓦坎达血统,而且当年他的父亲死在了自己的兄弟——特查拉父亲的手中。 ", "directors": "['']", "actors": "['']", "plotPics": "[\"http://172.16.58.3:88/superhero/MARVEL/BlackPanther/photos/1.png\",\"http://172.16.58.3:88/superhero/MARVEL/BlackPanther/photos/2.png\",\"http://172.16.58.3:88/superhero/MARVEL/BlackPanther/photos/3.png\",\"http://172.16.58.3:88/superhero/MARVEL/BlackPanther/photos/4.png\",\"http://172.16.58.3:88/superhero/MARVEL/BlackPanther/photos/5.png\"]", "createTime": "2018-03-09T07:40:37.000+0000" }, { "id": "xman-1001", "name": "X战警:天启", "poster": "http://172.16.58.3:88/superhero/xman/Apocalypse/poster.png", "cover": "http://172.16.58.3:88/superhero/xman/Apocalypse/cover.png", "trailer": "http://172.16.58.3:88/superhero/xman/Apocalypse/trailer.mp4", "score": 7.8, "prisedCounts": 5743, "basicInfo": "2018 / 美国 / 科幻 / 超级英雄", "originalName": "原名:xman: Apocalypse", "releaseDate": "上映时间:2016-06-03(中国大陆)", "totalTime": "影片时长:144分钟", "plotDesc": "变种人天启(奥斯卡·伊萨克 Oscar Isaac 饰)诞生于人类文明的最开端,被人类当做神一般敬仰膜拜,然而,这样的他,却遭到了他最蔑视的人类的背叛,被埋葬于废墟石砾之下,一晃眼就是数千年过去。 ", "directors": "[\"s-1011\"]", "actors": "[\"s-1012\",\"s-1013\",\"s-1014\",\"s-1015\",\"s-1016\"]", "plotPics": "[\"http://172.16.58.3:88/superhero/xman/Apocalypse/photos/1.png\",\"http://172.16.58.3:88/superhero/xman/Apocalypse/photos/2.png\",\"http://172.16.58.3:88/superhero/xman/Apocalypse/photos/3.png\",\"http://172.16.58.3:88/superhero/xman/Apocalypse/photos/4.png\",\"http://172.16.58.3:88/superhero/xman/Apocalypse/photos/5.png\",\"http://172.16.58.3:88/superhero/xman/Apocalypse/photos/6.png\"]", "createTime": "2016-06-03T07:40:37.000+0000" }, { "id": "dc-1008", "name": "神奇女侠", "poster": "http://172.16.58.3:88/superhero/DC/WonderWoman/poster.jpg", "cover": "http://172.16.58.3:88/superhero/DC/WonderWoman/cover.jpg", "trailer": "http://172.16.58.3:88/superhero/DC/WonderWoman/trailer.mp4", "score": 7.1, "prisedCounts": 5214, "basicInfo": "2018 / 美国 / 科幻 / 超级英雄", "originalName": "原名:<NAME>", "releaseDate": "上映时间: 2017-06-02(中国大陆)", "totalTime": "影片时长:141分钟", "plotDesc": "戴安娜(盖尔·加朵 Gal Gadot 饰)是女王希波吕忒(康妮·尼尔森 <NAME> 饰)的女儿,自幼生活在天堂岛上。巨大的屏障将这座岛屿同外界的纷纷扰扰隔开犹如一个世外桃源,而岛上生活着的亦都是女性。在女武官安提奥普(罗宾·莱特 <NAME> 饰)的教导之下,戴安娜习得了高强的武艺,而她的体内,似乎隐藏着某种强大的未知力量。 \r\n  一场意外中,一位名为史蒂夫(克里斯·派恩 <NAME> 饰)的男子来到了岛上,从他口中,戴安娜得知外面的世界正在经历战争的磨难,而造成这一切的罪魁祸首,是战神阿瑞斯(大卫·休里斯 David Thewlis 饰)。为了拯救人类于水火之中,戴安娜依然拿起了长剑与盾牌,发誓要彻底摧毁阿瑞斯的阴谋。", "directors": "['']", "actors": "['']", "plotPics": "[\"http://172.16.58.3:88/superhero/DC/WonderWoman/photos/1.jpg\",\"http://172.16.58.3:88/superhero/DC/WonderWoman/photos/2.jpg\",\"http://172.16.58.3:88/superhero/DC/WonderWoman/photos/3.jpg\",\"http://172.16.58.3:88/superhero/DC/WonderWoman/photos/4.jpg\"]", "createTime": "2017-06-02T07:40:37.000+0000" }, { "id": "marvel-1008", "name": "美国队长", "poster": "http://172.16.58.3:88/superhero/MARVEL/CaptainAmerica1/poster.png", "cover": "http://172.16.58.3:88/superhero/MARVEL/CaptainAmerica1/cover.png", "trailer": "http://172.16.58.3:88/superhero/MARVEL/CaptainAmerica1/trailer.mp4", "score": 7.1, "prisedCounts": 5364, "basicInfo": "2018 / 美国 / 科幻 / 超级英雄", "originalName": "原名:Captain America", "releaseDate": "上映时间:2011-09-09(中国大陆) ", "totalTime": "影片时长:124分钟", "plotDesc": "上世纪40年代,纳粹及其邪恶轴心的战火烧遍世界各个角落。居住在布鲁克林的小个子史蒂夫·罗格斯(克里斯·埃文斯 <NAME> 饰)心系国家,一心上阵杀敌,可是糟糕的体格让他始终被征兵办拒之门外。偶然的机会,在德籍科学家厄斯金博士(<NAME> 饰)的帮助下,这个小个子男孩得以走入兵营,并接受了博士的试验,化身成为高大健壮、膂力过人的超级战士。与此同时,德国纳粹红骷髅部队的首领约翰·施密特(雨果·维文 Hugo Weaving 饰)依靠超自然的力量建立起一支超级战队,企图称霸全世界。 ", "directors": "['']", "actors": "['']", "plotPics": "[\"http://172.16.58.3:88/superhero/MARVEL/CaptainAmerica1/photos/1.png\",\"http://172.16.58.3:88/superhero/MARVEL/CaptainAmerica1/photos/2.png\",\"http://172.16.58.3:88/superhero/MARVEL/CaptainAmerica1/photos/3.png\",\"http://172.16.58.3:88/superhero/MARVEL/CaptainAmerica1/photos/4.png\",\"http://172.16.58.3:88/superhero/MARVEL/CaptainAmerica1/photos/5.png\"]", "createTime": "2011-09-09T07:40:37.000+0000" } ]<file_sep>/utils/request.js import {serverUrl,linkqq} from "../constant.js"; export default class superRequest{ static get(url, data, type) { return new Promise((resolve, reject) => { uni.request({ url: serverUrl+url, data: { qq: linkqq, ...data }, header: { 'content-type':type ? type :'application/x-www-form-urlencoded' }, method:"GET", success: (res) => { let resData = res.data; // 获取真实数据之前,务必判断状态是否为200 if (resData && resData.status == 200) { resolve(resData.data); } else { reject(res); } }, fail:(err) => { reject(err); } }); }) } static post(url, data, type) { return new Promise((resolve, reject) => { uni.request({ url: serverUrl+url, data: { qq: linkqq, ...data }, header: { 'content-type':type ? type :'application/x-www-form-urlencoded' }, method:"POST", success: (res) => { console.log("请求拿到的原始数据:",res); let resData = res.data; // 获取真实数据之前,务必判断状态是否为200 if (resData && resData.status == 200) { resolve(resData.data); } else { reject(res); } }, fail:(err) => { reject(err); } }); }) } } <file_sep>/constant.js const qqlink =["3388643380","2898007290","3129996800","2573971154"]; export const serverUrl = "https://www.imovietrailer.com/superhero"; export const linkqq = "3388643380";
ba24d2ca6fb6af57b46dfaedb728cf032b874e95
[ "JavaScript" ]
3
JavaScript
xw5/first_uniapp
112f933fc7a9695e67669c90396f272c414ec03f
eb86cc4d857b6b01c81e363d7d08a5afee252543
refs/heads/main
<repo_name>mohamedelshafie/Simple-chaining-hashing-project<file_sep>/README.md # Simple-chaining-hashing-project a structure representing student information consisting of the following: Student name Student ID (integer) Student date of birth in 3 integers (day, month, year) Student score of last year (integer) we used a hash function that maps the data to the hash table using student's name by making summation of the ASCII number of each letter and make it mod table size. We developed functions to insert, delete, find an element in the hash table. <file_sep>/Chaining.c #include <stdio.h> #include <stdlib.h> #include<string.h> #define TABLE_SIZE 10 struct node{ char name[20]; int ID; int day,month,year; int score; struct node *next; }; struct node *head[TABLE_SIZE]={NULL},*c; int hash_function(char str[],int CAPACITY) { int i = 0; for (int j=0; str[j]; j++) i += str[j]; return i % CAPACITY; } void insert(char myname[],int myID,int myDay,int myMonth,int myYear,int myScore){ int i; i= hash_function(myname ,TABLE_SIZE); struct node * newNode=(struct node *)malloc(sizeof(struct node)); strcpy(newNode->name,myname); newNode->ID = myID; newNode->day = myDay; newNode->month = myMonth; newNode->year = myYear; newNode->score = myScore; newNode->next = NULL; if(head[i] == NULL) head[i] = newNode; else { c=head[i]; while(c->next != NULL) { c=c->next; } c->next=newNode; } } void search(int myKey){ int key,index; key=myKey; index=key%TABLE_SIZE; if(head[index] == NULL) printf("\n Search element not found the slot is empty\n"); else printf("search element found\n"); } void print(){ int i; for(i=0;i<TABLE_SIZE;i++) { printf("\nentries at index: %d\n",i); if(head[i] == NULL) { printf("No Hash Entry"); } else { for(c=head[i];c!=NULL;c=c->next) { printf("name: %s\n",c->name); printf("ID: %d \n",c->ID); printf("Date of birth: %d/%d/%d \n",c->day,c->month,c->year); printf("Score: %d \n",c->score); printf("********************************\n"); } } } } void deletee(int value) { int key = value % TABLE_SIZE; if(head[key] == NULL) printf("element is not there to delete\n"); else head[key]= NULL; printf("element deleted\n"); } int main(){ //test insertion: /*insert("mohamed",1,15,6,2000,90); //mohamed:731 insert("ahmed",2,15,6,2000,90); //ahmed:511 insert("abdallah",9,15,6,2000,90); //abdallah:809 print();*/ //test search: /*insert("mohamed",1,15,6,2000,90); //mohamed:731 731%10=1 insert("ahmed",2,15,6,2000,90); //ahmed:511 511%10=1 insert("abdallah",9,15,6,2000,90); //abdallah:809 809%10=9 search(1); search(3); search(2); search(9);*/ //test delete: insert("mohamed",1,15,6,2000,90); //mohamed:731 insert("ahmed",2,15,6,2000,90); //ahmed:511 insert("abdallah",9,15,6,2000,90); //abdallah:809 deletee(1); print(); return 0; }
27ea596634b03c45cbf4117187dd0d84f79e2c24
[ "Markdown", "C" ]
2
Markdown
mohamedelshafie/Simple-chaining-hashing-project
b776d0ecd53a707ee264072f20f380b8fae28000
f1d1e130676a8d3c1cce9bd4fe9f84466cb114e3
refs/heads/master
<repo_name>VeniZhang/xiao_tuan_ti<file_sep>/xiaotuanti.py #!coding:utf8 #group_num = input("how many groups you want to create?") #node_num = input("how many nodes in one group") #print group_num, node_num import time import math class Network_(): def __init__(self): self.group_num = 0 self.node_num_per_group = 0 self.groups = {} def groupConsensus(self): for gk, gv in self.groups.items(): gv.consensus() def startSayHello(self): for gk, gv in self.groups.items(): for nk, nv in gv.nodes.items(): print "befoer hello",nv.name,nv.value nv.hello() print "after hello",nv.name, nv.value, nv.result_ask_node def update(self, times): for gk, gv in self.groups.items(): for n,v in gv.nodes.items() : print "befor update", n ,v.value,v.result_ask_node v.update(times) print "after update",v.value v.result_ask_node = [] def consensus(self): i = 0 while(not self.isConsensus()): i += 1 self.startSayHello() self.update(i) time.sleep(1) def isConsensus(self): v = list((i.getValue() for i in self.groups.values())) v.sort() print 'IN CONSENSUS',v if v[0] == v[-1]: return True else: return False def getValue(self): if self.isConsensus(): return self.groups.values()[0] else: return None def getAll(self): for gv in self.groups.values(): print gv.name, "--", gv.getValue() for nv in gv.nodes.values(): print nv.name, ":",nv.value def getInfoFromFile(self): ''' 第一行: 组数 每个组的节点数 第二行: 第一组的组名 第三行: (第一组的成员)节点编号 节点值 。。。 第 行: 第二组的组名 。。。 第 行: 各组之间的关系 ''' with open('xiaotuanti.zdq', 'r') as f: line = f.readline().split() self.group_num = int(line[0]) self.node_num_per_group = int(line[1]) for g in range(self.group_num): group_name = f.readline().strip() self.groups[group_name] = Group(group_name) for n in range(self.node_num_per_group): node = Node() node.name, node.value, node.attr = f.readline().split() node.value = float(node.value) node.attr = node.attr.strip() if ":" in node.attr: node.attr, node.updateFun = node.attr.split(":") node.group = self.groups[group_name] self.groups[group_name].nodes[node.name] = node #以上代码 输入了组,和组内的节点信息 #以下代码 处理各组之间的关系 #组名加节点名 组名加节点名 for l in f.readlines(): line = l.split() g_f, n_f = line[0].split('.') g_s, n_s = line[1].split(".") #self.groups.setdefault(g_f, self.groups[g_f].adj_groups.setdefault(g_s, {}) dict_ = {n_s: self.groups[g_s].nodes[n_s]} self.groups[g_f].adj_groups[g_s][n_f] = dict_ dict_ = {n_f: self.groups[g_f].nodes[n_f]} self.groups[g_s].adj_groups.setdefault(g_f, {}) self.groups[g_s].adj_groups[g_f][n_s] = dict_ class Group(): def __init__(self, name=""): self.name = name self.nodes = {} self.adj_groups = {} self.value = 0 def getValue(self): self.value = self.__getValue() return self.value def __getValue(self): tem = list(( i.value for i in self.nodes.values())) tem.sort() if len(tem) % 2 == 0: value = tem[len(tem)/2] + tem[len(tem)/2-1] else: value = tem[len(tem)/2] return value def __updateNode(self, name, value): if self.nodes[name].attr == "N": self.nodes[name].value = value def consensus(self): value = self.__getValue() for nk, nv in self.nodes.items(): self.__updateNode(nv.name, value) class Node(): def __init__(self): self.group = None self.value = 0 self.name = 0 self.attr = 0 self.updateFun = None self.result_ask_node = [] def getMates(self): return self.group.nodes def hello(self): for k, v in self.group.adj_groups.items(): #adj_node = v[self.name] self.ask(k) def ask(self, group): nodes = self.group.nodes for node_k, node_v in nodes.items(): node_ask = self.group.adj_groups[group][node_k] for nk, nv in node_ask.items(): node_value = nv if nv.attr == "N": self.result_ask_node.append(nv.group.getValue()) else: self.result_ask_node.append(nv.value) def update(self, times): if self.attr == "B": x = times self.value = eval(self.updateFun) print "zzz",self.value elif self.attr == "N": values = self.result_ask_node values.sort() v = 0 length = len(values) if length % 2 == 0: v = (values[length/2] + values[length/2 -1]) / 2 else : v = values[length/2] self.value = 0.5 * self.value + 0.5 *v if __name__ =="__main__": network_ = Network_() network_.getInfoFromFile() network_.groupConsensus() network_.consensus() print network_.getValue() print network_.getAll() """ print "*************" print network_.groups["A"].adj_groups for i in network_.groups["A"].nodes: print i.name, i.value, i.group.name #print network_.groups["A"].nodes print network_.groups["B"].adj_groups """ #print network_.groups["A"].getValue()
0d09eacc2e757e5527bfd507c9159b7398a5a7a5
[ "Python" ]
1
Python
VeniZhang/xiao_tuan_ti
f447b9e73d276b7a47c37c4ab0d73d6b440375dd
579256c30b6a3fc237c10946469633c75d5467e8
refs/heads/master
<file_sep>This file is not longer used. Please review documentation. <file_sep> //------------------------- //TIP Configurator Utility // //Owner: Troux TSG // //Author: <NAME> // //Updated By: <NAME>, <NAME> // //Updated Date: August, 2008 // //Date: May, 2006 // //Copyright (C) 2006 Troux Technologies. All rights reserved. // //SCRIPT PURPOSE: // // Used to generate TIP configuration information from a Metis Model. Currently the script generates // a TIP Type Constraints File and a Customer Configuration File used to define Navigators. // //GUIDE FOR USING THIS SCRIPT // //GUIDE FOR CONFIGURING THIS SCRIPT //------------------------- //------------------------- //Initialize constants //------------------------- var PARAM_STR_CONTAINER_TYPE_URI = "metis:stdtypes#oid3"; var PARAM_BOL_GENERATE_SIDEBARS = false; var PARAM_BOL_ADDITIONAL_PROPERTY_BOX = false; var PARAM_BOL_RELATIONSHIP_BOX = false; //------------------------- //Call the main function that will execute the TIP Configuration script //------------------------- main(); //------------------------- //Main function for script //------------------------- function main() { //------------------------- //Declares an instance of the model, modelview and objects to add //------------------------- var ifModel = metis.currentModel; var ifModelView = ifModel.currentModelView; var objectsToAdd = null; //------------------------- //The relationship layout to use, is defined in the relationship XML method //------------------------- var relLayoutToUse = ""; //------------------------- //Get global overrides from button properties if the user has edited them, else the defaults will be used //------------------------- overrideFromMetis("PARAM_BOL_GENERATE_SIDEBARS",PARAM_BOL_GENERATE_SIDEBARS, ifModel); overrideFromMetis("PARAM_BOL_ADDITIONAL_PROPERTY_BOX",PARAM_BOL_ADDITIONAL_PROPERTY_BOX, ifModel); overrideFromMetis("PARAM_BOL_RELATIONSHIP_BOX",PARAM_BOL_RELATIONSHIP_BOX, ifModel); overrideFromMetis("PARAM_STR_CONTAINER_TYPE_URI",PARAM_STR_CONTAINER_TYPE_URI, ifModel); //------------------------- //Get the layout string to append to the layout type. Default value is Layout, but may be specified by editing the //'Layout' property of the action button //------------------------- var layoutString = ifModel.currentInstance.getNamedValue("Layout").getString(); //------------------------- //Popup showing that the TIP Portal Configurator has succesfully started //------------------------- shell.popup("Welcome to the Troux TIP Portal Configurator"); //------------------------- //Unimplemented currently. The intended function is unknown so keeping here for reference. //------------------------- var objMetisProgressDialog = new ActiveXObject("Metis.ProgressBar." + metis.versionMajor + "." + metis.versionMinor); objMetisProgressDialog.title = "TIP Configuration Status Indicator"; objMetisProgressDialog.interactive = true; objMetisProgressDialog.logVisible = true; objMetisProgressDialog.logExpanded = false; objMetisProgressDialog.setProgressStatus("Initializing"); var progress = 1; //------------------------- //Build the container select dialog tree //------------------------- var ifDialog = new ActiveXObject("Metis.SelectDialog." + metis.versionMajor + "." + metis.versionMinor); ifDialog.title = "TIP Portal Configurator"; ifDialog.heading = "Select containers used to configure TIP"; ifDialog.singleSelect = false; ifDialog.columnLabel = true; ifDialog.columnURI = false; ifDialog.columnType = false; ifDialog.viewTree = true; //------------------------- //Get all instances with a view in the specified model view (filter on object type) //------------------------- var ifInstanceColl = metis.newInstanceList(); ifInstanceColl = GetAllInstancesInModelViewRecursively(ifModelView.children, PARAM_STR_CONTAINER_TYPE_URI, ifInstanceColl); if(ifInstanceColl.count == 0) { shell.popup("No instances in current view"); return; } //------------------------- //Add the container objects to the tree dialog and display the select dialog //------------------------- ifDialog.addData(ifInstanceColl); var ifSelectedColl = ifDialog.show(); if(ifSelectedColl.count == 0) { shell.popup("No instances selected or cancel button pressed.\nExiting Tip Configurator."); return; } //------------------------- //Create the XMLDOM object and create the <configuration/> node as the top-level node //------------------------- var navigatorXmlDoc = new ActiveXObject("Microsoft.XMLDOM"); navigatorXmlDoc.async = "false"; navigatorXmlDoc.appendChild(navigatorXmlDoc.createElement("configuration")); //------------------------- //Prompts for a .log file to save error logging information //------------------------- var fso = new ActiveXObject("Scripting.FileSystemObject"); shell.popup("Enter a filename to store tip generation logging information."); var logFileName = SelectFileFromDialog("Navigator Config Log File (*.log)"); if(logFileName == null || logFileName == "") { return; } var logFile = fso.OpenTextFile(logFileName, 8, true); //------------------------- //Builds the XMLDOM into memory, parsing through components, subcomponents and relationships //------------------------- ExecuteBuildWidgetLayouts(navigatorXmlDoc, layoutString, ifSelectedColl); //------------------------- //Prompts for the user for where to save the output file as an .xml //------------------------- var XMLNavigatorSaveFile = new String; while(XMLNavigatorSaveFile.indexOf(".xml") != XMLNavigatorSaveFile.length - 4) { var path = new String; XMLNavigatorSaveFile = metis.getFileName("*.xml",0); if(XMLNavigatorSaveFile == null || XMLNavigatorSaveFile == "") { return; } } var indentOrigLen = 0; //formatXml(navigatorXmlDoc.documentElement, " ") navigatorXmlDoc.save(XMLNavigatorSaveFile); //------------------------- //Close all open file streams and set their reference to null //------------------------- logFile.close(); logFile = null; fso = null; //------------------------- //Inform the user that the script has finished //------------------------- shell.popup("Files Generated"); //------------------------- //Set the container list to null for future runs of the script //------------------------- ifSelectedColl = null; } //------------------------- //Function that creates the XML for the component types and the relationships //------------------------- function ExecuteBuildWidgetLayouts(navigatorXmlDoc, layoutString, ifSelectedColl) { //Variables var navigatorConfiguration, navigatorNavigator, navigatorName, navigatorMaxComponentsInList, navigatorCustomWidgetLayout; var ifInstance; var repositoryCheck, alreadyAdded, ifObjectInObjectsToAdd; var ifObjectSelected, ifPart, ifParts, ifObjectTypeUUID, objectToAdd, navigatorTypes, navigatorType; var ifInstanceName; var ifObjectTypeTitle, navigatorWidgetUI, navigatorLayouts, navigatorWidgetUIName, navigatorWidgetUILayoutConfig; var navigatorWidgetUIPropertyBoxes, navigatorWidgetUICommonProperties; var navigatorWidgetUIPropertiesName, navigatorWidgetUIPropertiesDescription, navigatorWidgetUIPropertiesObjectType, navigatorWidgetUIPropertiesAncestorPath, navigatorWidgetUIPropertiesAncestorPathWidgetConfig, navigatorWidgetUIProperties; var navigatorWidgetUIWidgetConfigSetting1, navigatorWidgetUIWidgetConfigSetting2, navigatorWidgetUIWidgetConfigSetting3; var navigatorWidgetUIPropertiesLastModification, navigatorWidgetUIPropertiesRootProperties; var relColl, ifRel, ifRelTypeUUID, isOrigin, relInfo; var relsToAdd, relToAdd, relRepositoryCheck, relAlreadyAdded, ifRelInRelsToAdd, navigatorWidgetUIPropertiesRelNames; var navigatorRelNamesSetting1, navigatorRelNamesSetting2, navigatorWidgetUICommonPropertiesBoxType; var navigatorRelNamesWidgetConfig, navigatorRelNamesWidgetConfigSetting1, navigatorRelNamesWidgetConfigSetting2; var navigatorRelNamesWidgetConfigSetting3, navigatorRelNamesWidgetConfigSetting4, navigatorRelNamesWidgetConfigSetting5; var navigatorWidgetUIPropertyBoxesLabelColumnWidth, navigatorWidgetUINameSetting1, navigatorWidgetUINameSetting2, navigatorWidgetUINameSetting3; var navigatorRelationshipSetting1, navigatorRelationshipSetting2, navigatorRelationshipSetting3, navigatorWidgetUIAddPropProperties; var navigatorAdditionalPropertiesSetting1, navigatorAdditionalPropertiesSetting2, navigatorAdditionalPropertiesSetting3; var navigatorWidgetUIRelationships, navigatorWidgetUIRelationshipProperties, navigatorWidgetUICommonPropsBoxType, navigatorWidgetUIAdditionalProperties; var objectParts, objectPart, objectPartUUID, navigatorWidgetUIPropertiesPartNames; var navigatorPartNamesWidgetConfig, navigatorPartNamesWidgetConfigSetting1, navigatorPartNamesWidgetConfigSetting3; var navigatorPartNamesWidgetConfigSetting4, navigatorPartNamesWidgetConfigSetting5, navigatorPartNamesSetting1, navigatorPartNamesSetting2; var collapseProperties, collapseRelationships; var objectToLayout; repositoryCheck = 0; alreadyAdded = 0; //Find the top level XML node and build the 'widgetUI' and 'layouts' nodes navigatorConfiguration = navigatorXmlDoc.getElementsByTagName("configuration").item(0); navigatorWidgetUI = navigatorXmlDoc.createElement("group"); navigatorWidgetUI.setAttribute("name", "widgetUI"); navigatorLayouts = navigatorXmlDoc.createElement("list"); navigatorLayouts.setAttribute("name", "layouts"); //Iterate through each view specified by the user for(var i = 1; i <= ifSelectedColl.count; i++) { //Replace spaces with underscores in the container name ifInstanceName = new String; ifInstanceName = ifSelectedColl(i).name; ifInstanceName = ifInstanceName.replace(" ", "_"); objectsToAdd = metis.newInstanceList(); ifParts = ifSelectedColl(i).parts; //Iterate through each component type in the current view for(var j = 1; j <= ifParts.count; j++) { if(ifParts(j).type.inherits(metis.findType("metis:mer#MerObjectProp"))) { repositoryCheck = 2; repositoryCheck = ifParts(j).getNamedValue("dbms-admin.system-uploaded").getInteger(); //Check that the component is actually commitable to the metaverse if (repositoryCheck != 2) { alreadyAdded = 0; //Iterate throught the current list of objects to be added for(var k = 1; k <= objectsToAdd.count; k++) { //Check if the current object type has been added or not if (ifParts(j).type.title == objectsToAdd(k).type.title) { alreadyAdded = 1; break; } } if (alreadyAdded == 0) { //Add the object to the list of objects to be included in the XML file if (ifParts(j).parent.type.uri == PARAM_STR_CONTAINER_TYPE_URI) { objectsToAdd.AddLast(ifParts(j)); } } } //Check the subcomponents for unique object types and add them to the list if needed addObjects(ifParts(j)); } } //Iterate through the list of objects to be added and build the XML file for(var j = 1; j <= objectsToAdd.count; j++) { relsToAdd = metis.newInstanceList(); //Split the UUID from the uri var temp = new String; temp = objectsToAdd(j).type.uri; temp = temp.split("#", 2); ifObjectTypeUUID = temp[1]; //Create the component type node temp = objectsToAdd(j).type.title; temp = temp.replace(" ", "_"); ifObjectTypeTitle = temp; navigatorWidgetUIName = addXMLNode(navigatorXmlDoc, navigatorLayouts, "group", new Array("name", "replace"), new Array(ifInstanceName + layoutString + ifObjectTypeTitle, "true")); navigatorWidgetUILayoutConfig = addXMLNode(navigatorXmlDoc, navigatorWidgetUIName, "group", new Array("name"), new Array("layoutConfig")); navigatorWidgetUIPropertyBoxes = addXMLNode(navigatorXmlDoc, navigatorWidgetUILayoutConfig, "list", new Array("name"), new Array("propertyBoxes")); navigatorWidgetUICommonProperties = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertyBoxes, "group", new Array("name"), new Array("commonProperties")); navigatorWidgetUIProperties = addXMLNode(navigatorXmlDoc, navigatorWidgetUICommonProperties, "list", new Array("name"), new Array("properties")); navigatorWidgetUIPropertiesName = addXMLNode(navigatorXmlDoc, navigatorWidgetUIProperties, "group", new Array("name"), new Array("name")); navigatorWidgetUIPropertiesDescription = addXMLNode(navigatorXmlDoc, navigatorWidgetUIProperties, "group", new Array("name"), new Array("description")); navigatorWidgetUIPropertiesObjectType = addXMLNode(navigatorXmlDoc, navigatorWidgetUIProperties, "group", new Array("name"), new Array("objectType")); navigatorWidgetUIPropertiesAncestorPath = addXMLNode(navigatorXmlDoc, navigatorWidgetUIProperties, "group", new Array("name"), new Array("ancestorPath")); navigatorWidgetUIPropertiesAncestorPathWidgetConfig = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertiesAncestorPath, "group", new Array("name"), new Array("widgetConfig")); navigatorWidgetUIWidgetConfigSetting1 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertiesAncestorPathWidgetConfig, "setting", new Array("name", "value"), new Array("drillthroughURL", "/do/widget/editComponent?layoutType=" + ifInstanceName + layoutString + "&mode=view")); navigatorWidgetUIWidgetConfigSetting2 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertiesAncestorPathWidgetConfig, "setting", new Array("name", "value"), new Array("rootText", "Top-level")); navigatorWidgetUIWidgetConfigSetting3 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertiesAncestorPathWidgetConfig, "setting", new Array("name", "value"), new Array("selfText", "This item")); navigatorWidgetUIPropertiesLastModification = addXMLNode(navigatorXmlDoc, navigatorWidgetUIProperties, "group", new Array("name"), new Array("lastModification")); navigatorWidgetUICommonPropsBoxType = addXMLNode(navigatorXmlDoc, navigatorWidgetUICommonProperties, "setting", new Array("name", "value"), new Array("boxType", "none")); navigatorWidgetUIAdditionalProperties = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertyBoxes, "group", new Array("name"), new Array("additionalProperties")); navigatorWidgetUIAddPropProperties = addXMLNode(navigatorXmlDoc, navigatorWidgetUIAdditionalProperties, "list", new Array("name"), new Array("properties")); //Create the list of properties nodes var propCol, prop; var uuid = new String; propCol = objectsToAdd(j).type.allProperties; for(var k = 1; k <= propCol.count; k++) { uuid = objectsToAdd(j).type.getPropertyUUID(propCol(k).name); if (uuid.length > 0) { addXMLNode(navigatorXmlDoc, navigatorWidgetUIAddPropProperties, "group", new Array("name"), new Array(uuid)); } } collapseProperties = 0; var temp = new String; try { temp = objectsToAdd(j).getNamedStringValue("comments"); } catch(exception) { temp = ""; } collapseProperties = temp.indexOf("collapseProperties"); if (collapseProperties < 0) { navigatorAdditionalPropertiesSetting2 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIAdditionalProperties, "setting", new Array("name", "value"), new Array("boxType", "none")); } else { navigatorAdditionalPropertiesSetting1 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIAdditionalProperties, "setting", new Array("name", "value"), new Array("boxLabel", "Additional Properties")); navigatorAdditionalPropertiesSetting2 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIAdditionalProperties, "setting", new Array("name", "value"), new Array("boxType", "collapsible")); navigatorAdditionalPropertiesSetting3 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIAdditionalProperties, "setting", new Array("name", "value"), new Array("expanded", "false")); } navigatorWidgetUIRelationships = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertyBoxes, "group", new Array("name"), new Array("Relationships")); navigatorWidgetUIRelationshipProperties = addXMLNode(navigatorXmlDoc, navigatorWidgetUIRelationships, "list", new Array("name"), new Array("properties")); //Get the objects subcomponents and look through them for new component types objectParts = objectsToAdd(j).parts; var listComponents = metis.newInstanceList(); addSubComponentsToXML(objectParts, navigatorWidgetUIRelationshipProperties, ifInstanceName, listComponents, navigatorXmlDoc, layoutString); //Get the current component types relationships and all subcomponents of the same type's relationships relColl = objectsToAdd(j).neighbourRelationships; GetSubRelationships(relColl, objectsToAdd(j)); //Loop through the relationships and throw out any duplicates for(var k = 1; k <= relColl.count; k++) { relRepositoryCheck = 2; relRepositoryCheck = relColl(k).getNamedValue("dbms-admin.system-uploaded").getInteger(); if (relRepositoryCheck != 2) { relAlreadyAdded = 0; for(var l = 1; l <= relsToAdd.count; l++) { if (relColl(k).type.title == relsToAdd(l).type.title) { relAlreadyAdded = 1; break; } } if (relAlreadyAdded == 0) { relsToAdd.AddLast(relColl(k)); } } } //Add the relationship nodes addSubRelationshipsToXML(objectsToAdd(j), navigatorWidgetUIRelationshipProperties, ifInstanceName, relsToAdd, navigatorXmlDoc, layoutString); collapseProperties = 0; var temp = new String; try { temp = objectsToAdd(j).getNamedStringValue("comments"); } catch(exception) { temp = ""; } collapseRelationships = temp.indexOf("collapseRelationships"); if (collapseRelationships < 0) { navigatorRelationshipSetting2 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIRelationships, "setting", new Array("name", "value"), new Array("boxType", "none")); } else { navigatorRelationshipSetting1 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIRelationships, "setting", new Array("name", "value"), new Array("boxLabel", "Parts and Relationships")); navigatorRelationshipSetting2 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIRelationships, "setting", new Array("name", "value"), new Array("boxType", "collapsible")); navigatorRelationshipSetting3 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIRelationships, "setting", new Array("name", "value"), new Array("expanded", "false")); } //Closing XML statements navigatorWidgetUIPropertyBoxesLabelColumnWidth = addXMLNode(navigatorXmlDoc, navigatorWidgetUILayoutConfig, "setting", new Array("name", "value"), new Array("labelColumnWidth", "0%")); navigatorWidgetUINameSetting1 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIName, "setting", new Array("name", "value"), new Array("objectType", ifObjectTypeUUID)); navigatorWidgetUINameSetting2 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIName, "setting", new Array("name", "value"), new Array("layoutURL", "/widgets/boxedTwoColumnLayout.jsp")); navigatorWidgetUINameSetting3 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIName, "setting", new Array("name", "value"), new Array("layoutType", ifInstanceName + layoutString)); } objectsToAdd = null; } navigatorWidgetUI.appendChild(navigatorLayouts); navigatorConfiguration.appendChild(navigatorWidgetUI); } //------------------------- //Function that adds a XML node to the XML Document //------------------------- function addXMLNode(navigatorXmlDoc, appendNode, type, names, values) { var node = navigatorXmlDoc.createElement(type); for(var i = 0; i < names.length; i++) { node.setAttribute(names[i], values[i]); } appendNode.appendChild(node); return node; } //------------------------- //Function to add a component or relationship to an existing array of components or relationships //------------------------- function addObjects(ifPart) { var ifChild, ifPartChildren, repositoryCheck, alreadyAdded, ifObject; ifPartChildren = ifPart.parts; for (var i = 1; i <= ifPartChildren.count; i++) { repositoryCheck = 2; try { repositoryCheck = ifPartChildren(i).getNamedValue("dbms-admin.system-uploaded").getInteger(); } catch(exception) { } if (repositoryCheck != 2) { alreadyAdded = 0; for (var j = 1; j <= objectsToAdd.count; j++) { if(ifPartChildren(i).type.title == objectsToAdd(j).type.title) { alreadyAdded = 1; break; } } if (alreadyAdded == 0) { objectsToAdd.AddLast(ifPartChildren(i)); } } addObjects(ifPartChildren(i)); } } //------------------------- //Function that recursivly finds all instance of a metis container objects and appends the objects to an array //------------------------- function GetAllInstancesInModelViewRecursively(ifModelViewChildrenViews, sObjectTypeURI, ifInstanceColl) { for(var i = 1; i <= ifModelViewChildrenViews.count; i++) { if (ifModelViewChildrenViews(i).hasInstance) { var ifInstance = ifModelViewChildrenViews(i).instance; if (ifInstance.type.uri == sObjectTypeURI) { ifInstanceColl.addLast(ifInstance); } } GetAllInstancesInModelViewRecursively(ifModelViewChildrenViews(i).children, sObjectTypeURI, ifInstanceColl); } return ifInstanceColl; } //------------------------- //Function that takes the existing XMLDOM and adds tabs, spaces and return statements for ease of read; Currently unimplemented //------------------------- function formatXml(objDom, strIndent) { var objChild; var objNew; if (indentOrigLen == 0) { tempstrIndent = new String; tempstrIndent = strIndent; indentOrigLen = tempstrIndent.length; } if (objDom.childNodes.length > 0) { for(var i = 1; i < objDom.childNodes.count; i++) { var temp = new String; temp = strIndent; temp = temp.substr(0, indentOrigLen); formatXml(objChild, strIndent + temp); if (objDom.nodeType == 1) { if (objDom.nodeName == "configName" ) { } else { objNew = objDom.ownerDocument.createNode(3, "", ""); objNew.nodeValue = "\r\n" + strIndent; objNew = objDom.insertBefore(objNew, objChild); objNew = null; } } } if (objDom.nodeType == 1) { if (objDom.nodeName == "configName") { } else { objNew = objDom.ownerDocument.createNode(3, "", ""); var temp = new String; temp = strIndent; temp = temp.substr(0, temp.lenght - 1); objNew.nodeValue = "\r\n" + temp; objNew = objDom.appendChild(objNew); objNew = null; } } } } //------------------------- //Function that checks the calling actionButton to see if it has the defined parameter called the value of //strParameterName and return that value if this is the case //------------------------- function overrideFromMetis(strParameterName, parameter, ifModel) { var oProperty; var oPropvaluesCollection, oPropInstance; var PARAM_STR_CONFIG_CONTAINER; oPropvaluesCollection = ifModel.currentInstance.getNamedValue("variables").getCollection(); for (var i = 1; i < oPropvaluesCollection.count; i++) { if (oPropvaluesCollection(i).getValue(oPropvaluesCollection(i).type.getProperty("variableName")).getString == strParameterName) { parameter = oPropvaluesCollection(i).getValue(oPropvaluesCollection(i).type.getProperty("variableValue")).getString; break; } } } //------------------------- //Fucntion that create a metis fileselect dialog box with type filter szFilter //------------------------- function SelectFileFromDialog(szFilter) { SelectFileFromDialog = metis.getFileName(szFilter,0); return SelectFileFromDialog; } //------------------------- //Currently unimplemented becuase dosn't seem to be needed //------------------------- function resolveLayoutName(ifInstance) { var ifInstanceParent = ifInstance.parent; for(var i = 1; i <= ifSelectedColl.count; i++) { if (ifInstanceParent.uri == ifSelectedColl(i).uri) { var temp = new String; temp = ifSelectedColl(i).name; relLayoutToUse = temp.replace(" ", "_"); return; } } resolveLayoutName(ifInstanceParent); } //------------------------- //Function that recursivly traverses the subcomponents of a given component and add subcomponent relationships where needed. //The function will only add one relationship for each component type. //------------------------- function addSubComponentsToXML(objectParts, navigatorWidgetUIRelationshipProperties, ifInstanceName, listComponents, navigatorXmlDoc, layoutString) { var objectPart, objectPartUUID, navigatorWidgetUIPropertiesPartNames, isAdded; var navigatorPartNamesWidgetConfig, navigatorPartNamesWidgetConfigSetting1, navigatorPartNamesWidgetConfigSetting3; var navigatorPartNamesWidgetConfigSetting4, navigatorPartNamesWidgetConfigSetting5, navigatorPartNamesSetting1, navigatorPartNamesSetting2; //Loop through each subcomponent for (var i = 1; i <= objectParts.count; i++) { isAdded = 0; //Check to see if this subcomponent has been added before for (var j = 1; j <= listComponents.count; j++) { if (listComponents(j).type.name == objectParts(i).type.name) { isAdded = 1; } } if (isAdded != 1) { //Construct the subcomponent relationship XML var temp = new String; temp = objectParts(i).type.uri; temp = temp.split("#", 2); objectPartUUID = temp[1]; navigatorWidgetUIPropertiesPartNames = addXMLNode(navigatorXmlDoc, navigatorWidgetUIRelationshipProperties, "group", new Array("name"), new Array(objectPartUUID + ":0")); navigatorPartNamesWidgetConfig = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertiesPartNames, "group", new Array("name"), new Array("widgetConfig")); navigatorPartNamesWidgetConfigSetting1 = addXMLNode(navigatorXmlDoc, navigatorPartNamesWidgetConfig, "setting", new Array("name", "value"), new Array("drillthroughURL", "/do/widget/editComponent?layoutType=" + ifInstanceName + layoutString + "&mode=view")); navigatorPartNamesWidgetConfigSetting2 = addXMLNode(navigatorXmlDoc, navigatorPartNamesWidgetConfig, "setting", new Array("name", "value"), new Array("allowDeleteComponent", "true")); navigatorPartNamesWidgetConfigSetting3 = addXMLNode(navigatorXmlDoc, navigatorPartNamesWidgetConfig, "setting", new Array("name", "value"), new Array("componentEditorPopupURL", "/do/widget/editObjectPopup?layoutType=widgetGenericPropertiesOnly")); navigatorPartNamesWidgetConfigSetting4 = addXMLNode(navigatorXmlDoc, navigatorPartNamesWidgetConfig, "setting", new Array("name", "value"), new Array("allowCreate", "true")); navigatorPartNamesSetting1 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertiesPartNames, "setting", new Array("name", "value"), new Array("widget", "componentList")); navigatorPartNamesSetting2 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertiesPartNames, "setting", new Array("name", "value"), new Array("labelPosition", "above")); listComponents.AddLast(objectParts(i)); } var childParts = objectParts(i).parts; //Call this method on each of the subcomponents of the current component for(var j = 1; j <= childParts.count; j++) { addSubComponentsToXML(childParts, navigatorWidgetUIRelationshipProperties, ifInstanceName, listComponents, navigatorXmlDoc, layoutString); break; } } } //------------------------- //Function that inspects the subcomponents of a given top-level component and adds their relationships //------------------------- function addSubRelationshipsToXML(objectToAdd, navigatorWidgetUIRelationshipProperties, ifInstanceName, relsToAdd, navigatorXmlDoc, layoutString) { var relToAdd, isOrigin, objectToLayout, relLayoutToUse, ifRelTypeUUID, relInfo; var navigatorRelNamesSetting1, navigatorRelNamesSetting2, navigatorWidgetUICommonPropertiesBoxType, navigatorWidgetUIPropertiesRelNames; var navigatorRelNamesWidgetConfig, navigatorRelNamesWidgetConfigSetting1, navigatorRelNamesWidgetConfigSetting2; var navigatorRelNamesWidgetConfigSetting3, navigatorRelNamesWidgetConfigSetting4, navigatorRelNamesWidgetConfigSetting5; //Loop through each relationship type on the given component type for(var i = 1; i <= relsToAdd.count; i++) { //Determine if the relationship for this component type is the origin or the the target if (relsToAdd(i).origin.type.title == objectToAdd.type.title) { isOrigin = ":0"; objectToLayout = relsToAdd(i).target; relLayoutToUse = ifInstanceName; //resolveLayoutName(objectToLayout); } else { isOrigin = ":1"; objectToLayout = relsToAdd(i).origin; relLayoutToUse = ifInstanceName; //resolveLayoutName(objectToLayout); } //Construct the relationship XML var temp = new String; temp = relsToAdd(i).type.uri; temp = temp.split("#", 2); ifRelTypeUUID = temp[1]; navigatorWidgetUIPropertiesRelNames = addXMLNode(navigatorXmlDoc, navigatorWidgetUIRelationshipProperties, "group", new Array("name"), new Array(ifRelTypeUUID + isOrigin)); navigatorRelNamesWidgetConfig = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertiesRelNames, "group", new Array("name"), new Array("widgetConfig")); navigatorRelNamesWidgetConfigSetting1 = addXMLNode(navigatorXmlDoc, navigatorRelNamesWidgetConfig, "setting", new Array("name", "value"), new Array("drillthroughURL", "/do/widget/editComponent?layoutType=" + relLayoutToUse + layoutString + "&mode=view")); navigatorRelNamesWidgetConfigSetting2 = addXMLNode(navigatorXmlDoc, navigatorRelNamesWidgetConfig, "setting", new Array("name", "value"), new Array("relationshipEditorPopupURL", "/do/widget/editObjectPopup?layoutType=widgetGenericPropertiesOnly")); navigatorRelNamesWidgetConfigSetting3 = addXMLNode(navigatorXmlDoc, navigatorRelNamesWidgetConfig, "setting", new Array("name", "value"), new Array("allowDeleteComponent", "true")); navigatorRelNamesWidgetConfigSetting4 = addXMLNode(navigatorXmlDoc, navigatorRelNamesWidgetConfig, "setting", new Array("name", "value"), new Array("componentEditorPopupURL", "/do/widget/editObjectPopup?layoutType=widgetGenericPropertiesOnly")); navigatorRelNamesWidgetConfigSetting5 = addXMLNode(navigatorXmlDoc, navigatorRelNamesWidgetConfig, "setting", new Array("name", "value"), new Array("allowCreate", "true")); navigatorRelNamesSetting1 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertiesRelNames, "setting", new Array("name", "value"), new Array("widget", "componentList")); navigatorRelNamesSetting2 = addXMLNode(navigatorXmlDoc, navigatorWidgetUIPropertiesRelNames, "setting", new Array("name", "value"), new Array("labelPosition", "above")); } } //------------------------- //Function that recursivly traverses the components of a given top-level component and adds unique relationships to //the list of relationships to be added for that component in the addSubReltaionshipstoXML method //------------------------- function GetSubRelationships(relColl, objectToAdd) { for(var i = 1; i <= objectToAdd.parts.count; i++) { for (var j = 1; j <= objectToAdd.parts(i).neighbourRelationships.count; j++) { relColl.addLast(objectToAdd.parts(i).neighbourRelationships(j)); } } var childParts = objectToAdd.parts; for (var i = 1; i <= childParts.count; i++) { GetSubRelationships(relColl, childParts(i)); } return relColl; }<file_sep>import React from 'react'; import renderer from 'react-test-renderer'; import ContainerObject from '../components/ContainerObject.js'; const mockContainer = { objectReference: { id: 2, }, type: 'Mock', name: 'Mock', attributes: { scaleX: 5, scaleY: 5, scaleWidth: 10, scaleHeight: 10, }, }; describe('<ContainerObject />', () => { it('should not change unexpectedly', () => { const tree = renderer .create( <ContainerObject container={mockContainer} parentWidth={600} parentHeight={600} parentX={5} parentY={5} key={4} /> ) .toJSON(); expect(tree).toMatchSnapshot(); }); }); <file_sep>import React from 'react'; import Icon from 'antd/lib/icon'; import 'antd/lib/tabs/style/css'; import Workplace from './workplace'; import Uploader from './upload'; import Landingpage from './landingpage'; class App extends React.Component { constructor(props) { super(props); this.state = { selectedTab: '0', model: 'simple.kmv', activeComponent: <Landingpage handleButtonSelect={(model) => this.handleSelect(model)} />, }; } onChange = activeKey => { this.setState({ selectedTab: activeKey, }); }; handleSelect(model) { console.log('Selecting model! ', model); this.setState({ model, activeComponent: <Workplace model={model} /> }); } renderWorkspace() { console.log('Load workspace!'); this.setState({ activeComponent: <Workplace model={this.state.model} /> }); } renderLandingpage() { this.setState({ activeComponent: <Landingpage handleButtonSelect={(model) => this.handleSelect(model)} /> }); } renderUploader() { this.setState({ activeComponent: <Uploader /> }); } render() { const comp = this.state.activeComponent; return ( <div> <ul className="landing-page-navigation"> <div className="nav-inner"> <li className="nav-item nav-brand"> <a className="nav-link" onClick={() => this.setState({ activeComponent: <Landingpage handleButtonSelect={(model) => this.handleSelect(model)} /> })} > DOVCAP </a> </li> <li className="nav-item"> <a className="nav-link" onClick={() => this.setState({ activeComponent: <Uploader /> })} ><Icon type="file-add" />Upload</a> </li> </div> </ul> { comp } </div> ); } } export default App; <file_sep>import React, { Component } from 'react'; import { selectModelFromBackend } from './utlities'; const Dropzone = require('react-dropzone'); const request = require('superagent'); class Uploader extends Component { constructor(props) { super(props); this.state = { fileNames: [], selected: '' }; } componentWillMount() { fetch('/api/getModelNames') .then(response => response.json()) .then(fileNames => { fileNames.sort(); this.setState({ fileNames }); }) .catch(err => console.error(err.toString())); } getFileNameRows() { const fileNames = this.state.fileNames.map(file => ( <tr key={file}> <td>{file}</td> <td> <button o nClick={() => this.handleDelete(file)}> Delete </button> </td> </tr> )); return fileNames; } updateModels() { fetch('/api/getModelNames') .then(response => response.json()) .then(fileNames => { this.setState({ fileNames }); }) .catch(err => console.error(err.toString())); } dropHandler(files) { console.log('HELLO'); const file = files[0]; const fileRequest = new FormData(); fileRequest.append('file', file); fileRequest.append('name', file.name); request .post('/api/uploadModel') .send(fileRequest) .end((err, res) => { if (err) { console.log(err); } console.log(res); this.updateModels(); return res; }); } handleDelete(fileName) { const req = new FormData(); req.append('name', fileName.toString()); request .post('/api/deleteModel') .send(req) .end((err, res) => { if (err) { console.log(err); } this.updateModels(); return res; }); } render() { return ( <div className="upload-container"> <h1>Model Upload</h1> <h3>Select model to be uploaded: </h3> <Dropzone className="dropzone-container" multiple={false} onDrop={this.dropHandler.bind(this)} > <div>Drop a file, or click to add!</div> </Dropzone> <h3>Current models</h3> <table className="model-table table"> <thead> <tr className="theader"> <td> <strong>Model name</strong> </td> <td> <strong>Delete model</strong> </td> </tr> </thead> <tbody id="upload-table-body"> {this.state.fileNames.map(file => ( <tr key={file}> <td>{file}</td> {/* <td><button className="button" onClick={() => this.props.handleButtonSelect(file)} >Select</button></td>*/} <td> <button className="button" onClick={() => this.handleDelete(file)}> Delete </button> </td> </tr> ))} </tbody> </table> </div> ); } } export default Uploader; <file_sep>package com.dlizarra.starter; import java.util.*; /** * Class to store object information and descriptions. */ public class myObject { String id; String name; String type; ArrayList<String> viewChildren; Map<String, String> valueset; Map<String, String> attributes; ArrayList<myObject> children; myObject objectReference; public myObject(){ valueset = new HashMap<String, String>(); attributes = new HashMap<String, String>(); viewChildren = new ArrayList(); children = new ArrayList(); } @Override public String toString(){ return this.id; } public String getInfo(){ return this.id + ": " + this.name; } public void addValueset(String key, String value){ valueset.put(key, value); } public void addChild(String ref){ viewChildren.add(ref); } public void addModelChild(myObject child){ children.add(child); } public void setId(String id){ if (this.id == null) { this.id = id; } } public String getId(){ return this.id; } public void addObject(myObject obj){ this.objectReference = obj; } public void setType(String type){ if (this.type == null){ this.type = type; } } public void setAttributes(HashMap<String, String> att){ this.attributes.putAll(att); } public void setName(String name){ this.name = name; } public void updateAttributesWithScales(List<Double> scales){ if(scales != null){ this.attributes.put("scaleX", String.valueOf(scales.get(0))); this.attributes.put("scaleY", String.valueOf(scales.get(1))); this.attributes.put("scaleHeight", String.valueOf(scales.get(2))); this.attributes.put("scaleWidth", String.valueOf(scales.get(3))); } } } <file_sep>module.exports = { extends: 'airbnb', parser: 'babel-eslint', rules: { 'react/prop-types': 0, 'indent': 0, 'no-else-return': 0, 'prettier/prettier':0 } }; <file_sep>import React from 'react'; class PropertiesView extends React.Component { constructor(props) { super(props); this.state = { properties: this.props.properties }; this.onClose = this.onClose.bind(this); } onChange(event, key) { let properties = Object.assign({}, this.state.properties); // creating copy of object properties[key] = event.target.value; // updating value this.setState({ properties }); } onClose() { this.props.toggle(this.state.properties, true); } render() { const formHtml = Object.keys(this.state.properties).map(key => ( <div> <label>{key}</label> <input type="text" value={this.state.properties[key]} onChange={e => this.onChange(e, key)} /> </div> )); return ( <div className="dialog" style={{ width: this.props.width }}> <div className="close"> <i className="fa fa-times" onClick={this.onClose} /> </div> <div className="content">{formHtml}</div> </div> ); } } export default PropertiesView; <file_sep>const request = require('superagent'); export function getModelsFromBackend() { const res = request.get('/api/getModel'); console.log("Get models from backend", res); return res; } export function findModelByReference(reference, list) { for (const model in list) { if (model.id === reference) { return model; } } return false; } export function selectModelFromBackend(model) { const res = request.get('/api/selectModel').query({ name: model }); return res; } export function getModelNamesFromBackend() { fetch('http://localhost:8080/api/getModelNames') .then(response => response.json()) .then(data => { console.log('Data:', data); return data; }).catch(err => console.error(err.toString())); } export function getModelNames() { const res = request.get('/api/getModelNames'); return res; } <file_sep>import React from 'react'; import { Arrow, Group, Text } from 'react-konva'; import ObjectEmitter from './ObjectEmitter'; class Relationship extends React.Component { constructor(props) { super(props); this.state = { id: props.data.id, name: '', children: null, data: props.data, fromId: props.data.valueset.origin_href.substring(1), toId: props.data.valueset.target_href.substring(1), text1: ' ', text2: ' ', fromPos: { left: -1, top: -1, width: -1, height: -1 }, toPos: { left: -1, top: -1, width: -1, height: -1 }, visible: props.visible, }; } componentWillMount() { const emitter = ObjectEmitter; const num = this.props.data.type.split(' ').length; const name = this.props.data.type .split(' ') .slice(2, num - 1) .join(' '); this.setState({ text1: `has ${name}`, text2: `is ${name} of`, }); // REMOVE THIS LATER!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! and fix correct relationship text this.setState({ text1: '', text2: '', }); emitter.addListener(this.state.fromId, (x, y, width, height) => { this.setState({ fromPos: { left: x, top: y, width, height }, }); }); emitter.addListener(this.state.toId, (x, y, width, height) => { this.setState({ toPos: { left: x, top: y, width, height }, }); }); emitter.addListener('forceUpdate', bol => { if (bol) { this.setState({ fromPos: { left: -1, top: -1, width: -1, height: -1 }, toPos: { left: -1, top: -1, width: -1, height: -1 }, }); } }); } componentWillReceiveProps(newProps) { this.setState({ id: newProps.data.id, data: newProps.data, fromId: newProps.data.valueset.origin_href.substring(1), toId: newProps.data.valueset.target_href.substring(1), visible: newProps.visible, }); } render() { if (!this.state.visible.includes(this.state.data.type)) { return <Group />; } const minFrom = { pos: [0, 0], node: 0 }; const minTo = { pos: [0, 0], node: 0 }; let textFrom = [0, 0]; let textTo = [0, 0]; function getRectangleNodes(left, top, width, height) { return [ [left + width / 2, top], [left + width, top + height / 2], [left + width / 2, top + height], [left, top + height / 2], ]; } function squareDistance(x1, y1, x2, y2) { return Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2); } function getPerpendicularity(x1, y1, x2, y2, node) { if (node === 0 && y2 > y1) { return 0; } if (node === 1 && x1 > x2) { return 0; } if (node === 2 && y1 > y2) { return 0; } if (node === 3 && x2 > x1) { return 0; } if (node % 2 === 0) { return Math.abs(y2 - y1) / (Math.abs(x2 - x1) + Math.abs(y2 - y1)); } else { return Math.abs(x2 - x1) / (Math.abs(x2 - x1) + Math.abs(y2 - y1)); } } function getTextPosition(x1, y1, x2, y2, distanceFromObject, rightPerpendicular) { let perpendicularDistanceFromLine = 30; if (rightPerpendicular) { perpendicularDistanceFromLine += 20; } const a = Math.sqrt(distanceFromObject ** 2 / (2 * ((x2 - x1) ** 2 + (y2 - y1) ** 2))); let x = x1 + (x2 - x1) * a; let y = y1 + (y2 - y1) * a; const a2 = Math.sqrt( perpendicularDistanceFromLine ** 2 / (2 * ((x2 - x1) ** 2 + (y2 - y1) ** 2)) ); if (rightPerpendicular) { x += (y2 - y1) * a2; y += (x1 - x2) * a2; } else { x += (y1 - y2) * a2; y += (x2 - x1) * a2; } return [x, y]; } function sortByKey(array, key) { return array.sort((a, b) => { const x = a[key]; const y = b[key]; return x < y ? -1 : x > y ? 1 : 0; }); } function rightOrLeft(x1, y1, x2, y2, fromNode) { let angle = 0; if (fromNode === 0) { angle = Math.atan2(y1 - y2, x2 - x1); } else if (fromNode === 1) { angle = Math.atan2(x2 - x1, y2 - y1); } else if (fromNode === 2) { angle = Math.PI - Math.atan2(y2 - y1, x2 - x1); } else if (fromNode === 3) { angle = Math.atan2(x1 - x2, y1 - y2); } if (angle < Math.PI / 2) { return false; } else { return true; } } const fromNodes = getRectangleNodes( this.state.fromPos.left, this.state.fromPos.top, this.state.fromPos.width, this.state.fromPos.height ); const toNodes = getRectangleNodes( this.state.toPos.left, this.state.toPos.top, this.state.toPos.width, this.state.toPos.height ); let possiblePositions = []; for (let i = 0; i < fromNodes.length; i++) { for (let j = 0; j < toNodes.length; j++) { const d = squareDistance(fromNodes[i][0], fromNodes[i][1], toNodes[j][0], toNodes[j][1]); possiblePositions.push({ dist: d, from: fromNodes[i], to: toNodes[j], fromNode: i, toNode: j, }); } } possiblePositions = sortByKey(possiblePositions, 'dist'); possiblePositions = possiblePositions.slice(0, 3); let bestPerpendiculatiry = 0; for (let i = 0; i < possiblePositions.length; i++) { const fromNode = possiblePositions[i].fromNode; const toNode = possiblePositions[i].toNode; if (possiblePositions[i].fromNode === possiblePositions[i].toNode) { if (this.state.width !== -1) { continue; } } const fromP = getPerpendicularity( possiblePositions[i].from[0], possiblePositions[i].from[1], possiblePositions[i].to[0], possiblePositions[i].to[1], fromNode ); const toP = getPerpendicularity( possiblePositions[i].to[0], possiblePositions[i].to[1], possiblePositions[i].from[0], possiblePositions[i].from[1], toNode ); const currentP = Math.min(fromP, toP); if (currentP / bestPerpendiculatiry > 1.2 && currentP > bestPerpendiculatiry) { bestPerpendiculatiry = currentP; minFrom.pos = possiblePositions[i].from; minTo.pos = possiblePositions[i].to; minFrom.node = possiblePositions[i].fromNode; minTo.node = possiblePositions[i].toNode; } } // todo: make more general let rightPerpendicular = true; if (minTo.pos[1] < minFrom.pos[1]) { rightPerpendicular = false; } let toDist = 100; if (minTo.pos[0] < minFrom.pos[1]) { toDist = 20; } toDist = 50; const right = rightOrLeft( minFrom.pos[0], minFrom.pos[1], minTo.pos[0], minTo.pos[1], minFrom.node ); if (right) { rightPerpendicular = false; } else { rightPerpendicular = true; } textFrom = getTextPosition( minFrom.pos[0], minFrom.pos[1], minTo.pos[0], minTo.pos[1], toDist, rightPerpendicular ); textTo = getTextPosition( minTo.pos[0], minTo.pos[1], minFrom.pos[0], minFrom.pos[1], toDist, !rightPerpendicular ); if (minFrom.pos[0] <= 0 || minFrom.pos[1] <= 0 || minTo.pos[0] <= 0 || minTo.pos[1] <= 0) { return <Group />; } // console.log(this.state.data.type); return ( <Group> <Arrow x={minFrom.pos[0]} y={minFrom.pos[1]} points={[0, 0, minTo.pos[0] - minFrom.pos[0], minTo.pos[1] - minFrom.pos[1]]} pointerLength={5} pointerWidth={5} fil="black" stroke="black" strokeWidth={2} /> <Text x={textFrom[0]} y={textFrom[1]} text={this.state.text1} align="center" witdth={14} fontFamily="Calibri" /> <Text align="center" x={textTo[0]} y={textTo[1]} text={this.state.text2} witdth={14} fontFamily="Calibri" /> </Group> ); } } export default Relationship; <file_sep>import React from 'react'; import { Rect, Group, Text } from 'react-konva'; import ContainerObject from './component/ContainerObject.js'; import ActionButton from './component/ActionButton.js'; class Container extends React.Component { constructor(props) { super(props); const containerJson = props.container; this.state = { width: containerJson.attributes.scaleWidth * props.parentWidth, height: containerJson.attributes.scaleHeight * props.parentHeight, x: props.parentX + containerJson.attributes.scaleX * props.parentWidth, y: props.parentY + containerJson.attributes.scaleY * props.parentHeight, name: containerJson.name, }; } componentWillReceiveProps(nextProps) { const containerJson = nextProps.container; this.setState({ width: containerJson.attributes.scaleWidth * nextProps.parentWidth, height: containerJson.attributes.scaleHeight * nextProps.parentHeight, x: nextProps.parentX + containerJson.attributes.scaleX * nextProps.parentWidth, y: nextProps.parentY + containerJson.attributes.scaleY * nextProps.parentHeight, }); } handleClick() { console.log("click", this, this.state); console.log("data", this.props.fullData); // this.setState({ // name: "Pes" // }) var newJson = this.props.fullData; var properties = null; //find properties for (let prop of this.props.fullData.viewL) { if (prop.objectReference.id === this.state.id) { properties = prop.objectReference; } } //newJson.modelViewL[0].children[0].children[1].children[1].children[0].name="kk" console.log("Properties", properties); //this.props.propertiesView(properties); } render() { const children = this.props.container.children.length > 0 ? this.props.container.children.map(child => { if (child.type === 'View') { return ( <Container container={child} parentWidth={this.state.width} parentHeight={this.state.height} parentX={this.state.x} parentY={this.state.y} key={child.id} fullData={this.props.fullData} propertiesView={this.props.propertiesView} /> ); } else if (child.type !== 'Action Button') { return ( <ContainerObject container={child} parentWidth={this.state.width} parentHeight={this.state.height} parentX={this.state.x} parentY={this.state.y} key={child.id} fullData={this.props.fullData} propertiesView={this.props.propertiesView} /> ); } else { return ( <ActionButton container={child} parentWidth={this.state.width} parentHeight={this.state.height} parentX={this.state.x} parentY={this.state.y} key={child.id} fullData={this.props.fullData} propertiesView={this.props.propertiesView} /> ); } }) : null; let col = 'white'; let fontSize = 7; let textColor = 'black'; let fontStyle = 'normal'; let align = 'left'; let padding = 0; let strokeColor = 'DimGray'; let rectangleYPadding = 0; if (this.props.container.name === 'AKM Solution Developer Workplace') { col = '#bfd4d9'; fontSize = 20; textColor = '#666666'; } if (this.props.container.name === 'DOVCAP Project : Buttons / Close workarea ') { col = '#9cc7ce'; fontStyle = 'bold'; padding = -3; } if ( this.props.container.name === 'Copyright (c) 2008 Active Knowledge Modeling. All Rights Reserved.' ) { col = '#9cc7ce'; fontStyle = 'bold'; fontSize = 10; align = 'center'; padding = -6; } if (this.props.container.name === 'Workplace') { col = '#9cc7ce'; } if (this.props.container.name === 'CVW_ShortCutBar') { //return <Group />; col = '#bfd4d9'; strokeColor = 0 fontSize = 0; rectangleYPadding = 10 } return ( <Group> <Rect x={this.state.x} y={this.state.y + rectangleYPadding} width={this.state.width} height={this.state.height} cornerRadius={5} stroke={strokeColor} draggable fill={col} /> <Text x={this.state.x + 10} y={this.state.y + 10} width={this.state.width - 10} text={this.state.name} fontSize={fontSize} fontFamily="Arial" fill={textColor} fontStyle={fontStyle} align={align} padding={padding} /> {children} </Group> ); } } export default Container; <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import '../style/style.css'; import Root from './root'; import { BrowserRouter, HashRouter } from 'react-router-dom'; import Main from './main.js'; ReactDOM.render( <HashRouter> <Root /> </HashRouter>, document.querySelector('.container') ); <file_sep>const { EventEmitter } = require('fbemitter'); const emitter = new EventEmitter(); function getEmitter() { return emitter; } export default getEmitter(); <file_sep>import React from 'react'; import { Rect, Group, Text, Image } from 'react-konva'; import ObjectEmitter from './ObjectEmitter'; import ActionButton from './ActionButton.js'; import Container from '../Container.js'; function importAll(r) { const images = {}; r.keys().map(item => { images[item.replace('./', '')] = r(item); return null; }); return images; } const images = importAll(require.context('../image/', false, /\.(png|jpe?g|svg)$/)); class ContainerObject extends React.Component { constructor(props) { super(props); const containerJson = props.container; this.state = { width: containerJson.attributes.scaleWidth * props.parentWidth, height: containerJson.attributes.scaleHeight * props.parentHeight, x: props.parentX + containerJson.attributes.scaleX * props.parentWidth, y: props.parentY + containerJson.attributes.scaleY * props.parentHeight, name: containerJson.name, type: containerJson.type, imageWidth: 1, imageHeight: 1, id: containerJson.objectReference.id, }; if (containerJson.objectReference.valueset.iconProp) { let img = containerJson.objectReference.valueset.iconProp; img = img.substring(img.lastIndexOf('/') + 1, img.lastIndexOf('.') + 4); // TODO: Has to set a generic icon value } if (containerJson.objectReference.valueset.icon) { const image = new window.Image(); image.src = images[containerJson.objectReference.valueset.icon]; image.onload = () => { this.setState({ image, }); this.drawImage(); }; } this.drawImage = this.drawImage.bind(this); } componentWillMount() { const emitter = ObjectEmitter; emitter.emit(this.state.id, this.state.x, this.state.y, this.state.width, this.state.height); } componentWillReceiveProps(nextProps) { const containerJson = nextProps.container; const width = containerJson.attributes.scaleWidth * nextProps.parentWidth; const height = containerJson.attributes.scaleHeight * nextProps.parentHeight; const x = nextProps.parentX + containerJson.attributes.scaleX * nextProps.parentWidth; const y = nextProps.parentY + containerJson.attributes.scaleY * nextProps.parentHeight; this.setState({ width, height, x, y, }); // fix undefined if (this.state.image) { this.drawImage(); } const emitter = ObjectEmitter; emitter.emit(this.state.id, x, y, width, height); } componentWillUnMount() { // This does not work, but should be fixed in relationships? const emitter = ObjectEmitter; emitter.emit(this.state.id, -1, -1, -1, -1); } handleClick = () => { const emitter = ObjectEmitter; if (this.state.name === 'Tasks') { emitter.emit('tasks'); } else if (this.state.name === 'Users') { emitter.emit('Users'); } else { // this.setState({ // name: "Pes" // }) var newJson = this.props.fullData; var properties = null; // find properties for (let prop of this.props.fullData.viewL) { if (prop.objectReference.id === this.state.id) { properties = prop.objectReference; } } this.props.propertiesView(properties); } }; handleDragMove = e => { this.setState({ x: e.target.position().x, y: e.target.position().y, }); const emitter = ObjectEmitter; emitter.emit(this.state.id, this.state.x, this.state.y, this.state.width, this.state.height); }; drawImage() { this.setState({ imageWidth: this.state.image.naturalHeight, imageHeight: this.state.image.naturalWidth, }); } render() { const children = this.props.container.children.length > 0 ? this.props.container.children.map(child => { if (child.type === 'test') { return ( <Container container={child} parentWidth={this.state.width} parentHeight={this.state.height} parentX={this.state.x} parentY={this.state.y} key={child.id} fullData={this.props.fullData} propertiesView={this.props.propertiesView} /> ); } else if (child.type !== 'Action Button') { return ( <ContainerObject container={child} parentWidth={this.state.width} parentHeight={this.state.height} parentX={this.state.x} parentY={this.state.y} key={child.id} fullData={this.props.fullData} propertiesView={this.props.propertiesView} /> ); } else { return ( <ActionButton container={child} parentWidth={this.state.width} parentHeight={this.state.height} parentX={this.state.x} parentY={this.state.y} key={child.id} fullData={this.props.fullData} propertiesView={this.props.propertiesView} /> ); } }) : null; let imageHeight = this.state.height; let imageWidth = this.state.imageHeight / this.state.imageWidth * this.state.height; const ratio = imageWidth / (this.state.width / 2); if (ratio > 1) { imageHeight = imageHeight / ratio; imageWidth = imageWidth / ratio; } else { imageHeight = imageHeight / 1.3; imageWidth = imageWidth / 1.3; } let col = '#FFFFFF'; let fontSize = 7; let offSetX = 0; if (this.props.container.type === 'Role (Actor)') { col = '#FFEEAA'; } else if (this.props.container.type === 'Property (EKA)') { col = '#bed08c'; } else if (this.props.container.type === 'Button (CVW)') { col = 'lightblue'; } if (this.props.container.name === 'CVW_LeftPane') { col = 'FF0000'; } if (this.props.container.name === 'CVW_MenuLevel1') { col = 'PowderBlue'; fontSize = 0; } if (this.props.container.name === 'CVW_Workspace') { col = 'PowderBlue'; } if ( this.props.container.name === 'Cost Estimator' || this.props.container.name === 'Dicipline Lead' || this.props.container.name === 'Concept Designer' || this.props.container.name === 'Project Leader' ) { offSetX = 15; } if ( this.props.container.name === 'Type' || this.props.container.name === 'TypeId' || this.props.container.name === 'TypeName' || this.props.container.name === 'Description' || this.props.container.name === 'Name' ) { offSetX = 7; } if (isNaN(this.state.x) || isNaN(this.state.y)) { return <Group />; } return ( <Group> <Rect x={this.state.x} y={this.state.y} width={this.state.width} height={this.state.height} stroke={'DimGray'} cornerRadius={0} draggable onDragMove={this.handleDragMove} fill={col} onClick={this.handleClick.bind(this)} /> <Image x={this.state.x + (this.state.width / 2 - imageWidth) / 2} y={this.state.y + (this.state.height - imageHeight) / 2} height={imageHeight} width={imageWidth} image={this.state.image} offsetX={offSetX} onClick={this.handleClick.bind(this)} /> <Text width={this.state.width * (1 / 2)} height={this.state.height} align="center" x={this.state.x + this.state.width * (1 / 2)} y={this.state.y + this.state.height / 2 - 7} text={this.state.name} witdth={14} fontSize={fontSize} fontFamily="Arial" /> {children} </Group> ); } } export default ContainerObject; <file_sep>/* eslint no-debugger: 0 */ /* eslint no-eval: 0 */ import React from 'react'; import { Rect, Group, Text } from 'react-konva'; class ActionButton extends React.Component { constructor(props) { super(props); const containerJson = props.container; this.state = { width: containerJson.attributes.scaleWidth * props.parentWidth, height: containerJson.attributes.scaleHeight * props.parentHeight, x: props.parentX + containerJson.attributes.scaleX * props.parentWidth, y: props.parentY + containerJson.attributes.scaleY * props.parentHeight, name: containerJson.name, type: containerJson.type, action: containerJson.objectReference.valueset.description, }; } componentWillReceiveProps(nextProps) { const containerJson = nextProps.container; this.setState({ width: containerJson.attributes.scaleWidth * nextProps.parentWidth, height: containerJson.attributes.scaleHeight * nextProps.parentHeight, x: nextProps.parentX + containerJson.attributes.scaleX * nextProps.parentWidth, y: nextProps.parentY + containerJson.attributes.scaleY * nextProps.parentHeight, action: containerJson.objectReference.valueset.description, }); } handleClick = () => { const x = String(this.state.action).trim(); debugger; eval(x); }; render() { return ( <Group> <Rect x={this.state.x} y={this.state.y} width={this.state.width} height={this.state.height} stroke={1} cornerRadius={0} onClick={this.handleClick} fill="green" /> <Text width={this.state.width} height={this.state.height} align="center" x={this.state.x} y={this.state.y + 10} text={this.state.name} fontSize={8} fontFamily="Arial" onClick={this.handleClick} /> </Group> ); } } export default ActionButton; <file_sep>package com.dlizarra.starter; import org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration; import org.springframework.boot.context.embedded.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import javax.servlet.MultipartConfigElement; @SpringBootApplication @EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class }) public class AppConfig { // servlets, view resolvers... @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize("100MB"); factory.setMaxRequestSize("100MB"); return factory.createMultipartConfig(); } } <file_sep>import React from 'react'; import { selectModelFromBackend } from './utlities.js'; import ModelView from './ModelView.js'; import Tabs from 'antd/lib/tabs'; // for js import 'antd/lib/tabs/style/css'; const TabPane = Tabs.TabPane; import ObjectEmitter from './component/ObjectEmitter'; import PropertiesView from './component/PropertiesView.js'; class App extends React.Component { constructor() { super(); this.state = { selectedModel: false, modelViews: null, relationships: null, zoom: 1, movedX: 0, movedY: 0, xOffset: 0, yOffset: 0, modelViewWidth: 0, modelViewHeight: 0, direction: '', lastScrollPos: 0, relTypesSelected: [], propertiesView: false, }; this.zoom = this.zoom.bind(this); this.offsetRight = this.offsetRight.bind(this); this.offsetDown = this.offsetDown.bind(this); this.updateWindowDimensions = this.updateWindowDimensions.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.propertiesView = this.propertiesView.bind(this); this.renderEnvironment = this.renderEnvironment.bind(this); } componentWillMount() { selectModelFromBackend(this.props.match.params.modelID).then(res => { const json = JSON.parse(res.text); console.log('Whole JSON', json); this.renderEnvironment(json); this.updateWindowDimensions(); this.zoom(-0.1); this.setState({ selectedModel: 0, }); if (this.props.match.params.viewID) { const model = json.modelViewL.find( object => object.attributes.title === this.props.match.params.viewID ); const modelIndex = json.modelViewL.indexOf(model); this.setState({ selectedModel: modelIndex, }); } }); this.addListeningToEvents(); } componentDidMount() { this.updateWindowDimensions(); window.addEventListener('resize', this.updateWindowDimensions); document.addEventListener('keydown', this.handleKeyDown, false); } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowDimensions); document.removeEventListener('keydown', this.handleKeyDown, false); } renderEnvironment(json) { this.setState({ fullData: json, modelViews: json.modelViewL, relationships: json.relationshipL, objectViews: json.viewL, }); } propertiesView(json, part) { // called from properties if (part) { for (let prop of this.state.fullData.viewL) { if (prop.objectReference.id === this.state.properties.id) { prop.objectReference.valueset = json; this.renderEnvironment(this.state.fullData); } } } this.setState({ propertiesView: !this.state.propertiesView, properties: json, }); } onChange = activeKey => { this.setState({ selectedModel: parseInt(activeKey, 10), }); const emitter = ObjectEmitter; emitter.emit('forceUpdate', true); }; addListeningToEvents = () => { const emitter = ObjectEmitter; emitter.addListener('tasks', () => { const newView = this.state.objectViews.find( object => object.id === 'UUID4_8193025B-8CA4-4DC4-A444-1F190A41B85B' ); const newModelViews = this.state.modelViews; newView.attributes.scaleHeight = 0.5; newView.attributes.scaleWidth = 0.5; newView.attributes.scaleX = 0; newView.attributes.scaleY = 0.51; newModelViews[2].children[0].children[2].children.push(newView); this.setState({ modelViews: newModelViews, }); }); emitter.addListener('Users', () => { const newView = this.state.objectViews.find(object => object.id === '_002astd01rqf6b84i23l'); const newModelViews = this.state.modelViews; newView.attributes.scaleHeight = 0.5; newView.attributes.scaleWidth = 0.5; newView.attributes.scaleX = 0.5; newView.attributes.scaleY = 0.51; newModelViews[2].children[0].children[2].children.push(newView); this.setState({ modelViews: newModelViews, }); }); }; zoom(num) { const xDiffZoom = this.state.modelViewWidth * this.state.zoom - this.state.modelViewWidth * (this.state.zoom + num); const xDiffMove = this.state.movedX * num; const yDiffZoom = this.state.modelViewHeight * this.state.zoom - this.state.modelViewHeight * (this.state.zoom + num); const yDiffMove = this.state.movedY * num; if (num > 0 || this.state.zoom + num > 0) { this.setState({ zoom: (this.state.zoom += num), xOffset: this.state.xOffset + xDiffMove + xDiffZoom / 2, yOffset: this.state.yOffset + yDiffMove + yDiffZoom / 2, }); } } offsetRight(num) { this.setState({ movedX: (this.state.movedX += num / this.state.zoom), xOffset: (this.state.xOffset += num), }); } offsetDown(num) { this.setState({ movedY: (this.state.movedY += num / this.state.zoom), yOffset: (this.state.yOffset += num), }); } selectModel = model => { this.setState({ model }); }; updateWindowDimensions() { this.setState({ modelViewWidth: window.innerWidth * 1, modelViewHeight: window.innerHeight * 0.85, }); } handleKeyDown(event) { if (event.keyCode === 87) { this.offsetDown(50); } else if (event.keyCode === 83) { this.offsetDown(-50); } else if (event.keyCode === 65) { this.offsetRight(50); } else if (event.keyCode === 68) { this.offsetRight(-50); } else if (event.keyCode === 90) { this.zoom(0.25); } else if (event.keyCode === 88) { this.zoom(-0.25); } } render() { if ((this.state.selectedModel || this.state.selectedModel === 0) && this.state.modelViews) { return ( <div> {this.state.propertiesView ? ( <PropertiesView width={300} height={400} toggle={this.propertiesView} properties={this.state.properties.valueset} /> ) : null} <div style={{ display: 'flex', justifyContent: 'center' }}> <ModelView modelView={this.state.modelViews[this.state.selectedModel]} relationships={this.state.relationships} zoom={this.state.zoom} xOffset={this.state.xOffset} yOffset={this.state.yOffset} width={this.state.modelViewWidth} height={this.state.modelViewHeight} fullData={this.state.fullData} propertiesView={this.propertiesView} /> </div> <Tabs activeKey={this.state.selectedModel.toString()} onChange={this.onChange}> {this.state.modelViews.map((modelView, index) => { return ( <TabPane tab={modelView.attributes.title} key={index}> {modelView.attributes.title} </TabPane> ); })} </Tabs> </div> ); } return <h1>loading</h1>; } } export default App; <file_sep>package com.dlizarra.starter; import com.google.gson.Gson; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Stream; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.toList; @RestController public class ModelController { @CrossOrigin(origins = "http://localhost:9090") @RequestMapping(value = "/api/getModel", method = RequestMethod.GET) public String getModels() { Parser parser = new Parser("models/cvw-sprint4-workplace.kmv"); return parser.getJson(); } @CrossOrigin(origins = "http://localhost:9090") @RequestMapping(value = "/api/selectModel", method=RequestMethod.GET) public String selectModel(@RequestParam("name") String fileName) { Parser parser = new Parser("models/"+fileName); String json = parser.getJson(); return json; } @CrossOrigin(origins = "http://localhost:9090") @RequestMapping(value="/api/getModelNames", method=RequestMethod.GET) public String getModelNames() { File folder = new File("models"); File[] files = folder.listFiles(); ArrayList<String> fileNames = new ArrayList<>(); for(File file : files) { if (file.isFile()) { if (getFileExt(file).equals("kmv")) { fileNames.add(file.getName()); } } } String json = new Gson().toJson(fileNames); return json; } @CrossOrigin(origins="http://localhost:9090") @RequestMapping(value="/api/getAllFileNames", method=RequestMethod.GET) public String getAllFileNames() { File folder = new File("models"); Stream<File> files = Arrays.stream(folder.listFiles()); Map<String, List<String>> fileGroups = files .collect(groupingBy(f -> getFileExt(f), mapping((File f) -> f.getName(), toList()))); String json = new Gson().toJson(fileGroups); return json; } @CrossOrigin(origins="http://localhost:9090") @RequestMapping(value="/api/uploadModel", method=RequestMethod.POST) public @ResponseBody ResponseEntity<String> handleModelUpload( @RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws Exception { if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File("models/" + name))); stream.write(bytes); stream.close(); System.out.println("POST OK!"); return ResponseEntity.ok("File " + name + " uploaded."); } catch (Exception e) { return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(e.getMessage()); } } else { return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("You failed to upload " + name + " because the file was empty."); } } @CrossOrigin(origins="http://localhost:9090") @RequestMapping(value="/api/deleteModel", method=RequestMethod.POST) public @ResponseBody ResponseEntity<String> handleModelDelete(@RequestParam("name") String fileName) throws Exception { File folder = new File("models"); for (File file : folder.listFiles()) { if (file.getName().equals(fileName)) { file.delete(); return ResponseEntity.ok("File " + fileName + " deleted!"); } } return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("Couldn't find " + fileName + " in model folders!"); } private static String getFileExt(File file) { String fileName = file.getName(); int dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1); } }
23cc9ab81423bafa401eeeedc780adee7ab61df6
[ "JavaScript", "Java", "Text" ]
18
Text
vhellem/dovcap
9ab49d9a0770adacbece1952dc90dbf2c80f76db
bdbd93cd0ffb35877eee40846bc26be67681dcb0
refs/heads/master
<repo_name>Janini24/WorkyWork<file_sep>/WorkyworkV0/src/exercises/C10R17.java package exercises; import java.util.ArrayList; import java.util.Iterator; import java.util.Scanner; public class C10R17 { private static double num1 = 0, num2 = 0, result = 0; private static Scanner j = new Scanner(System.in); private static char opt, con; private final static String MESSAGEINPUT1 = "Enter First Number :"; private final static String MESSAGEINPUT2 = "Enter Second Number :"; private final static String RESULT = "The result of this operation is :"; private final static String DISPLAYVAR1 = "First Number:"; private final static String DISPLAYVAR2 = "Second Number:"; private final static String OPTION = "Select an option:"; private final static String KEY = "\nPress any C key and press ENTER to continue"; private final static String PROGRAMTERMINATE = "Program Terminated!"; //private static double product, quotient, sum, difference; private final static String MENU = "\nM - Multiplication\n" + "D - Division\n" + "A - Addition\n" + "S - Subtraction\n" + "Q - Quit\n"; private final static String TITLE = "\n<<Math Operation menu>>"; private static char MULTIPLICATION = 'M'; public static void main(String[] args) { Display_Menu(num1, num2, opt); } public static void Display_Menu(double num1, double num2, char opt) { do { System.out.print(MESSAGEINPUT1); num1 = j.nextDouble(); System.out.print(MESSAGEINPUT2); num2 = j.nextDouble(); System.out.println(TITLE); System.out.printf("\n%s %.1f %s %.1f\n", DISPLAYVAR1, num1, DISPLAYVAR2, num2); System.out.println(MENU); System.out.print(OPTION); opt = j.next().charAt(0); System.out.println(); if (opt == 'm' || opt == 'M') { Multiplication(num1, num2); } else if (opt == 'd' || opt == 'D') { Division(num1, num2); } else if (opt == 'a' || opt == 'A') { Addition(num1, num2); } else if (opt == 's' || opt == 'S') { subtraction(num1, num2); } else if (opt == 'q' || opt == 'Q') { System.out.println(PROGRAMTERMINATE); System.exit(0); }else { System.out.println("Not part of the option!!"); } System.out.println(KEY); con = j.next().charAt(0); }while (con == 'C' || con == 'c'); System.out.println(PROGRAMTERMINATE); } public static void Multiplication(double num1, double num2) { result = num1 * num2; System.out.println(RESULT + result); } public static void Division(double num1, double num2) { result = num1/num2; System.out.println(RESULT + result); } public static void Addition(double num1, double num2) { result = num1 + num2; System.out.println(RESULT + result); } public static void subtraction(double num1, double num2) { result = num1 * num2; System.out.println(RESULT + result); } } <file_sep>/WorkyworkV0/src/exercises/C10R11.java package exercises; import java.util.Scanner; import javax.swing.text.StyledEditorKit.BoldAction; public class C10R11 { private static final String MESSAGE = "[Rules] \n" + "1. A password must have at least ten characters.\n" + "2. A password consists of only letters and digits.\n" + "3. A password must contain at least two digits. "; private static final String MESSAGEINPUT = "Input a password(You are agreeing to the above Terms and Conditions.):"; private static final String MESSAGEINVALID = "Password is not valid:"; private static final String MESSAGEVALID = "Password is valid:"; private static char passChar; private static String password; private static Scanner j = new Scanner(System.in); private static int digits; private static int letters; public static void main(String[] args) { checkPassword(password); } public static void checkPassword(String password) { System.out.println(MESSAGE); System.out.print(MESSAGEINPUT); password = j.nextLine(); String splitPassword[] = password.split(""); for (int x = 0; x < password.length(); x++) { //int splitParsePassword = Integer.parseInt(splitPassword[x]); passChar = password.charAt(x); if(hasNumber(passChar)) { digits++; }else if(hasLetters(passChar)) { letters++; } } // System.out.println(digits); // System.out.println(letters); if(password.length() < 8) { System.out.println(MESSAGEINVALID+password); }else if(digits < 2) { System.out.println(MESSAGEINVALID+password); }else if(digits >2 && letters > 1) { System.out.println(MESSAGEVALID+password); } } public static boolean hasNumber(char passChar) { return (passChar >= '0' && passChar <= '9'); } public static boolean hasLetters(char passChar) { passChar = Character.toUpperCase(passChar); return (passChar >= 'A' && passChar <= 'Z'); } }<file_sep>/WorkyworkV0/src/exercises/C10R13.java package exercises; import java.util.Scanner; public class C10R13 { private static double val1, val2, val3, area; private static double comp; private static Scanner j = new Scanner(System.in); private final static String SIDE1 = "Input Side-1 :"; private final static String SIDE2 = "Input Side-2 :"; private final static String SIDE3 = "Input Side-3 :"; public static void main(String[] args) { calculateTriangle(val1, val2, val3); } public static void calculateTriangle(double val1, double val2, double val3) { System.out.print(SIDE1); val1 = j.nextInt(); System.out.print(SIDE2); val2 = j.nextInt(); System.out.print(SIDE3); val3 = j.nextInt(); comp = (val1 + val2 + val3) / 2; area = Math.sqrt(comp * (comp - val1) * (comp - val2) * (comp - val3)); System.out.println(area); } } <file_sep>/WorkyworkV0/src/exercises/GradeDisplay.java package exercises; public class GradeDisplay { public static void main(String[] args) { double gs; String Grade[] = new String[5]; // (gs[y]=(prelim[y]*0.3)+(midterm[y]*0.3)+(finals[y]*.4)) //Grade Grade[0] = "Name"; Grade[1] = "Prelim";Grade[2] = "Midterm";Grade[3] = "Final";Grade[4] = "Grade"; print(Grade); Grade[0] = "Justin"; Grade[1] = "88"; Grade[2] = "90"; Grade[3] = "88"; gs =(Integer.parseInt(Grade[1])*0.3 + Integer.parseInt(Grade[2])*0.3 + Integer.parseInt(Grade[3])*0.4); Grade[4] =String.valueOf(gs); print(Grade); Grade[0] = "Lorenz"; Grade[1] = "90"; Grade[2] = "88"; Grade[3] = "92"; gs =(Integer.parseInt(Grade[1])*0.3 + Integer.parseInt(Grade[2])*0.3 + Integer.parseInt(Grade[3])*0.4); Grade[4] =String.valueOf(gs); print(Grade); Grade[0] = "Jasmine"; Grade[1] = "86"; Grade[2] = "92"; Grade[3] = "86"; gs =(Integer.parseInt(Grade[1])*0.3 + Integer.parseInt(Grade[2])*0.3 + Integer.parseInt(Grade[3])*0.4); Grade[4] =String.valueOf(gs); print(Grade); Grade[0] = "Jericho"; Grade[1] = "83"; Grade[2] = "87"; Grade[3] = "85"; gs =(Integer.parseInt(Grade[1])*0.3 + Integer.parseInt(Grade[2])*0.3 + Integer.parseInt(Grade[3])*0.4); Grade[4] =String.valueOf(gs); print(Grade); Grade[0] = "Jasper"; Grade[1] = "91"; Grade[2] = "83"; Grade[3] = "87"; gs =(Integer.parseInt(Grade[1])*0.3 + Integer.parseInt(Grade[2])*0.3 + Integer.parseInt(Grade[3])*0.4); Grade[4] =String.valueOf(gs); print(Grade); } public static void print(String Grade[]) { for (int x = 0; x < Grade.length; x++) { // System.out.println(Grade[0] + "\t\t" + Grade[1] + "\t\t" + Grade[2] + "\t\t" + Grade[3] + "\t\t" + Grade[4]); System.out.printf("%s\t\t%s\t\t%s\t\t%s\t\t%s\n", Grade[0], Grade[1], Grade[2], Grade[3], Grade[4]); break; } } }<file_sep>/WorkyworkV0/src/exercises/NumToWordConverter.java package exercises; import java.util.Scanner; public class NumToWordConverter{ private static final String MESSAGE = "Please input a value:"; public static void main(String[] args) { int value; Scanner j = new Scanner(System.in); System.out.println(MESSAGE); value = j.nextInt(); while(value != 0) { if(value > 0 && value <=9999) { convert((value/1000)%100, " Thousand "); convert((value/100)%10, " Hundred " ); convert((value %100), " "); }else { System.out.println("We only accept values from (1-9999)"); } System.out.println(); System.out.print(MESSAGE); value = j.nextInt(); } System.out.println("Program Terminated!"); } public static void convert(int value, String name) { String one[] = {"", "One","Two","Three","Four","Five","Six","Seven","Eight","Nine", "Ten", "Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}; String tens[] = {"", "", "Twenty","Thrirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; //System.out.println(value + name); if(value > 19) { System.out.print(tens[value/10] + " " + one[value%10]); }else { System.out.print(one[value]); } if(value > 0) { System.out.print(name); } } } <file_sep>/WorkyworkV0/src/main/Pokedex.java package main; import java.io.Serializable; public class Pokedex implements Serializable{ String itemName; int price; public Pokedex(String itemName, int price) { this.itemName = itemName; this.price = price; } public String toString() { return itemName + " $" + price; } }<file_sep>/WorkyworkV0/src/exercises/C10R15.java package exercises; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class C10R15 { public static void main(String[] args) { Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd yyyy h:mm:ss"); String strDate = formatter.format(date); System.out.println("Current date and time: : "+strDate); } } <file_sep>/WorkyworkV0/src/main/potion.java package main; import java.util.InputMismatchException; import java.util.Scanner; import javax.swing.SwingConstants; public class potion{ public static void main(String[] args) { int value=0; int gate=0; Scanner j = new Scanner(System.in); int onesPlace = value % 10; int tensPlace = (value / 10) % 10; int hundredPlace = (value / 100) % 10; int thousandPlace = (value / 1000) % 10; do { while(!j.hasNextInt()) { System.out.println("Numbers only"); j.next(); } value = j.nextInt(); if(value ==0) { System.out.println("Program Terminated!"); System.exit(0); }else if( value > 9999) { System.out.println("Program only Accept values from (0-9999)"); }else { convertDigitToWord(value, "Tthousand"); } }while(gate == 0 ); System.out.println(value); } public static void convertDigitToWord(int value, String name) { String uns[] = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; String ten[] = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; String tens[] = { "", "", "Twenty", "Thrirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; String hun = "Hundred"; String tho = "Thousand"; } } <file_sep>/WorkyworkV0/src/main/Empty.java package main; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; public class Empty { public static void main(String[] args) { try(FileInputStream fi = new FileInputStream("try.txt")){ ObjectInputStream oi = new ObjectInputStream(fi); Pokedex[] px = (Pokedex[])oi.readObject(); ArrayList<Pokedex> pxs = (ArrayList<Pokedex>)oi.readObject(); for(Pokedex poke : px) { System.out.println(poke); } for(Pokedex poke : pxs) { System.out.println(poke); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }<file_sep>/WorkyworkV0/src/exercises/C10R02.java package exercises; //import C10R01; public class C10R02 { private static int n1, n2, n3; public static void main(String[] args) { C10R01.average(n1, n2, n3); //gfgf } }
b6e465c50229c6569e865feee7282a74135ba481
[ "Java" ]
10
Java
Janini24/WorkyWork
33fa6b059d123f9842a75a1b95e3b4bfd5978e0e
afcc442bbbf8611fad661be6f4c3a1b4ee5c4fc8
refs/heads/master
<file_sep>/* * AVR_registers.h * * Created on: Sep 16, 2019 * Author: Nour */ #ifndef AVR_REGISTERS_H_ #define AVR_REGISTERS_H_ #include "standard_library.h" /* General purpose I/O registers and bits */ #define PORTA_R (*(volatile uint8 * const)0x003B) #define PORTB_R (*(volatile uint8 * const)0x0038) #define PORTC_R (*(volatile uint8 * const)0x0035) #define PORTD_R (*(volatile uint8 * const)0x0032) #define DDRA_R (*(volatile uint8 * const)0x003A) #define DDRB_R (*(volatile uint8 * const)0x0037) #define DDRC_R (*(volatile uint8 * const)0x0034) #define DDRD_R (*(volatile uint8 * const)0x0031) #define PINA_R (*(volatile uint8 * const)0x0039) #define PINB_R (*(volatile uint8 * const)0x0036) #define PINC_R (*(volatile uint8 * const)0x0033) #define PIND_R (*(volatile uint8 * const)0x0030) #define PA0_B 0 #define PA1_B 1 #define PA2_B 2 #define PA3_B 3 #define PA4_B 4 #define PA5_B 5 #define PA6_B 6 #define PA7_B 7 #define PB0_B 0 #define PB1_B 1 #define PB2_B 2 #define PB3_B 3 #define PB4_B 4 #define PB5_B 5 #define PB6_B 6 #define PB7_B 7 #define PC0_B 0 #define PC1_B 1 #define PC2_B 2 #define PC3_B 3 #define PC4_B 4 #define PC5_B 5 #define PC6_B 6 #define PC7_B 7 #define PD0_B 0 #define PD1_B 1 #define PD2_B 2 #define PD3_B 3 #define PD4_B 4 #define PD5_B 5 #define PD6_B 6 #define PD7_B 7 /* Interrupts registers and bits */ /* Global interrupt (I-bit) */ #define SREG_R (*(volatile uint8 * const)0x005F) #define I_B 7 /* External interrupt */ #define MCUCR_R (*(volatile uint8 * const)0x0055) #define ISC01_B 0 #define ISC10_B 1 #define ISC11_B 2 #define MCUCSR_R (*(volatile uint8 * const)0x0054) #define ISC2_B 6 #define GICR_R (*(volatile uint8 * const)0x005B) #define INT0_B 6 #define INT1_B 7 #define INT2_B 5 #define GIFR_R (*(volatile uint8 * const)0x005A) #define INTF0_B 6 #define INTF1_B 7 #define INTF2_B 5 /* Timers registers and bits */ /* Watchdog Timer */ #define WDTCR_R (*(volatile uint8 * const)0x0041) #define WDP0 0 #define WDP1 1 #define WDP2 2 #define WDE 3 #define WDTOE 4 #endif /* AVR_REGISTERS_H_ */ <file_sep>/* * keypad.h * * Created on: Sep 16, 2019 * Author: Nour * Description: Header file for the Keypad driver */ #ifndef KEYPAD_H_ #define KEYPAD_H_ /******************************************************************************* * Includes * *******************************************************************************/ #include "AVR_registers.h" #include "standard_library.h" #include "common_macros.h" /******************************************************************************* * Preprocessor Defines * *******************************************************************************/ #define NO_OF_ROWS 4 #define NO_OF_COLUMNS 4 #define KEYPAD_DIR DDRA_R #define KEYPAD_OUT PORTA_R #define KEYPAD_IN PINA_R /******************************************************************************* * Functions Prototypes * *******************************************************************************/ extern uint8 Keypad_getPressedKey(void); #endif /* KEYPAD_H_ */ <file_sep>/* * measure_duty_cycle.c * * Created on: Jan 10, 2018 * Author: <NAME> */ #include "LCD.h" #include "Timer.h" #include "External_Interrupt.h" uint8 g_edgeCount = 0; uint16 g_timeHigh = 0; uint16 g_timePeriod = 0; uint16 g_timePeriodPlusHigh = 0; /* Create configuration structure for external_interrupt driver */ Interrupt_ConfigType Interrupt_Config = {interrupt0,rising}; void APP_edgeProcessing(void) { g_edgeCount++; if(g_edgeCount == 1) { /* * Clear the timer counter register to start measurements from the * first detected rising edge */ Timer1_clearTimerValue(); /* Detect falling edge */ Interrupt_setEdgeDetectionType(&Interrupt_Config,falling); } else if(g_edgeCount == 2) { /* Store the High time value */ g_timeHigh = Timer1_getTimerValue(); //LCD_intgerToString(g_timeHigh); /* Detect rising edge */ Interrupt_setEdgeDetectionType(&Interrupt_Config,rising); } else if(g_edgeCount == 3) { /* Store the Period time value */ g_timePeriod = Timer1_getTimerValue(); //LCD_intgerToString(g_timePeriod); /* Detect falling edge */ Interrupt_setEdgeDetectionType(&Interrupt_Config,falling); } else if(g_edgeCount == 4) { /* Store the Period time value + High time value */ g_timePeriodPlusHigh = Timer1_getTimerValue(); //LCD_intgerToString(g_timePeriodPlusHigh); /* Clear the timer counter register to start measurements again */ Timer1_clearTimerValue(); /* Detect rising edge */ Interrupt_setEdgeDetectionType(&Interrupt_Config,rising); } } int main() { uint32 dutyCycle = 0; /* Enable Global Interrupt I-Bit */ SREG_R |= (1<<7); /* Create configuration structure for Timer driver */ Timer_ConfigType Timer_Config = {Timer1,Overflow,0,No_prescaling,0,0,0,0,0,0}; /* Create configuration structure for external_interrupt driver */ Interrupt_ConfigType Interrupt_Config = {interrupt0,rising}; /* Initialize the drivers */ LCD_init(); Timer_init(&Timer_Config); Interrupt_init(&Interrupt_Config); //LCD_displayString("HELLO"); /* Set the Call back function pointer in the external_interrupt driver */ INT0_setCallBack(APP_edgeProcessing); while(1) { if(g_edgeCount == 4) { Timer1_DeInit(); /* Disable Timer1 Driver */ Interrupt0_DeInit(); /* Disable external_interrupt Driver */ g_edgeCount = 0; LCD_displayString("Duty = "); /* calculate the dutyCycle */ dutyCycle = ((float)(g_timePeriodPlusHigh-g_timePeriod) / (g_timePeriodPlusHigh - g_timeHigh)) * 100; /* display the dutyCycle on LCD screen */ LCD_intgerToString(dutyCycle); LCD_displayCharacter('%'); } } } <file_sep>/* * AVR_registers.h * * Created on: Sep 16, 2019 * Author: Nour */ #ifndef AVR_REGISTERS_H_ #define AVR_REGISTERS_H_ //#include "standard_library.h" /* General purpose I/O registers and bits */ #define PORTA_R (*(volatile uint8 * const)0x003B) #define PORTB_R (*(volatile uint8 * const)0x0038) #define PORTC_R (*(volatile uint8 * const)0x0035) #define PORTD_R (*(volatile uint8 * const)0x0032) #define DDRA_R (*(volatile uint8 * const)0x003A) #define DDRB_R (*(volatile uint8 * const)0x0037) #define DDRC_R (*(volatile uint8 * const)0x0034) #define DDRD_R (*(volatile uint8 * const)0x0031) #define PINA_R (*(volatile uint8 * const)0x0039) #define PINB_R (*(volatile uint8 * const)0x0036) #define PINC_R (*(volatile uint8 * const)0x0033) #define PIND_R (*(volatile uint8 * const)0x0030) #define PA0_B 0 #define PA1_B 1 #define PA2_B 2 #define PA3_B 3 #define PA4_B 4 #define PA5_B 5 #define PA6_B 6 #define PA7_B 7 #define PB0_B 0 #define PB1_B 1 #define PB2_B 2 #define PB3_B 3 #define PB4_B 4 #define PB5_B 5 #define PB6_B 6 #define PB7_B 7 #define PC0_B 0 #define PC1_B 1 #define PC2_B 2 #define PC3_B 3 #define PC4_B 4 #define PC5_B 5 #define PC6_B 6 #define PC7_B 7 #define PD0_B 0 #define PD1_B 1 #define PD2_B 2 #define PD3_B 3 #define PD4_B 4 #define PD5_B 5 #define PD6_B 6 #define PD7_B 7 /* Interrupts registers and bits */ /* Global interrupt (I-bit) */ #define SREG_R (*(volatile uint8 * const)0x005F) #define I_B 7 /* External interrupt */ #define MCUCR_R (*(volatile uint8 * const)0x0055) #define ISC01_B 0 #define ISC10_B 1 #define ISC11_B 2 #define MCUCSR_R (*(volatile uint8 * const)0x0054) #define ISC2_B 6 #define GICR_R (*(volatile uint8 * const)0x005B) #define INT0_B 6 #define INT1_B 7 #define INT2_B 5 #define GIFR_R (*(volatile uint8 * const)0x005A) #define INTF0_B 6 #define INTF1_B 7 #define INTF2_B 5 /* Timers registers and bits */ /* Watchdog Timer */ #define WDTCR_R (*(volatile uint8 * const)0x0041) #define WDP0_B 0 #define WDP1_B 1 #define WDP2_B 2 #define WDE_B 3 #define WDTOE_B 4 /* Timer 1 */ /* ADC registers and bits */ #define ADMUX_R (*(volatile uint8 * const)0x0027) #define MUX0_B 0 #define MUX1_B 1 #define MUX2_B 2 #define MUX3_B 3 #define MUX4_B 4 #define ADLAR_B 5 #define REFS0_B 6 #define REFS1_B 7 #define ADCSRA_R (*(volatile uint8 * const)0x0026) #define ADPS0_B 0 #define ADPS1_B 1 #define ADPS2_B 2 #define ADIE_B 3 #define ADIF_B 4 #define ADATE_B 5 #define ADSC_B 6 #define ADEN_B 7 #define ADCL_R (*(volatile uint8 * const)0x0024) #define ADCH_R (*(volatile uint8 * const)0x0025) #define ADC_R (*(volatile uint16 * const)0x0024) #define SFIOR_R (*(volatile uint8 * const)0x0050) #define ADTS0_B 5 #define ADTS1_B 6 #define ADTS2_B 7 #endif /* AVR_REGISTERS_H_ */ <file_sep>/* * Timer.h * * Created on: Sep 28, 2019 * Author: Nour */ #ifndef TIMER_H_ #define TIMER_H_ #include "standard_library.h" #include "common_macros.h" #include "AVR_registers.h" #include <avr/interrupt.h> typedef enum { Timer0,Timer1,Timer2 }Timer; typedef enum { Overflow,CTC = 2 }Mode; typedef enum { No_clock,No_prescaling,CLK_8,CLK_64,CLK_256,CLK_1024,External_falling,External_rising }Prescalar_Timer0,Prescalar_Timer1; typedef enum { no_clock,no_prescaling,CLK__8,CLK__32,CLK__64,CLK__128,CLK__256,CLK__1024 }Prescalar_Timer2; typedef enum { Normal,Toggle,Clear,Set }Compare_Output_Mode; typedef enum { Channel_A,Channel_B }Channel; typedef struct { Timer timer; Mode mode; Prescalar_Timer0 prescalar_Timer0; Prescalar_Timer1 prescalar_Timer1; Prescalar_Timer2 prescalar_Timer2; Compare_Output_Mode COM; uint8 u8_comp_value; uint16 u16_comp_value_A; uint16 u16_comp_value_B; Channel channel; }Timer_ConfigType; extern void Timer_init(Timer_ConfigType * Config_Ptr); extern void Timer0_OVF_setCallBack(void(*a_ptr)(void)); extern void Timer0_COMP_setCallBack(void(*a_ptr)(void)); extern void Timer2_OVF_setCallBack(void(*a_ptr)(void)); extern void Timer2_COMP_setCallBack(void(*a_ptr)(void)); extern void Timer1_OVF_setCallBack(void(*a_ptr)(void)); extern void Timer1_COMPA_setCallBack(void(*a_ptr)(void)); extern void Timer1_COMPB_setCallBack(void(*a_ptr)(void)); #endif /* TIMER_H_ */ <file_sep>/* * DC_Motor.c * * Created on: Sep 29, 2019 * Author: Nour */ #include "DC_Motor.h" void DC_Motor_init(void) { /* set the output pins */ SET_BIT(DC_MOTOR_DIR,IN1); SET_BIT(DC_MOTOR_DIR,IN2); /* DC Motor is stopped initially */ CLEAR_BIT(DC_MOTOR_OUT,IN1); CLEAR_BIT(DC_MOTOR_OUT,IN2); } void DC_Motor_rotate_clockwise(void) { CLEAR_BIT(DC_MOTOR_OUT,IN1); SET_BIT(DC_MOTOR_OUT,IN2); } void DC_Motor_rotate_anti_clockwise(void) { SET_BIT(DC_MOTOR_OUT,IN1); CLEAR_BIT(DC_MOTOR_OUT,IN2); } void DC_Motor_stop(void) { CLEAR_BIT(DC_MOTOR_OUT,IN1); CLEAR_BIT(DC_MOTOR_OUT,IN2); } <file_sep>/* * keypad.c * * Created on: Sep 16, 2019 * Author: Nour * Description: Source file for the Keypad driver */ #include "keypad.h" /******************************************************************************* * Private Functions Prototypes * *******************************************************************************/ #if(NO_OF_COLUMNS == 3) static uint8 KeyPad_4x3_adjustKeyNumber(uint8 button_number); #elif(NO_OF_COLUMNS == 4) static uint8 KeyPad_4x4_adjustKeyNumber(uint8 button_number); #endif uint8 Keypad_getPressedKey(void) { uint8 col,row; while(TRUE) { for(col = LOW;col < NO_OF_COLUMNS;col++) { KEYPAD_DIR = 0b00010000 << col; KEYPAD_OUT = ~(0b00010000 << col); for(row = LOW;row < NO_OF_ROWS;row++) { if(BIT_IS_CLEAR(KEYPAD_IN,row)) { #if(NO_OF_COLUMNS == 3) return KeyPad_4x3_adjustKeyNumber((row * NO_OF_COLUMNS) + col + 1); #elif(NO_OF_COLUMNS == 4) return KeyPad_4x4_adjustKeyNumber((row * NO_OF_COLUMNS) + col + 1); #endif } } } } } #if(NO_OF_COLUMNS == 3) static uint8 KeyPad_4x3_adjustKeyNumber(uint8 button_number) { switch (button_number) { case 10: return '*'; break; case 11: return 0; break; case 12: return '#'; break; default: return button_number; break; } } #elif(NO_OF_COLUMNS == 4) static uint8 KeyPad_4x4_adjustKeyNumber(uint8 button_number) { switch(button_number) { case 1: return 7; break; case 2: return 8; break; case 3: return 9; break; case 4: return '/'; break; case 5: return 4; break; case 6: return 5; break; case 7: return 6; break; case 8: return '*'; break; case 9: return 1; break; case 10: return 2; break; case 11: return 3; break; case 12: return '-'; break; case 14: return 0; break; case 15: return '='; break; case 16: return '+'; break; default: return button_number; break; } } #endif <file_sep>/* * Leds.c * * Created on: Mar 21, 2020 * Author: Nour * Purpose: contains all leds functions needed in this project */ /******************************************************************************* * Includes * *******************************************************************************/ #include "Leds.h" #include "Port.h" #include "DIO.h" /******************************************************************************* * Function Definitions * *******************************************************************************/ /***************************************************** * Function Prototype: void leds_init(void) * Description: Initialization leds. * Input: None * Output: None * return: void ******************************************************/ void leds_init(void) { /* initialize lamp and heater as outputs */ set_direction(LEDS_DIR,LAMP,OUT); set_direction(LEDS_DIR,HEATER,OUT); /* initial value of lamp and heater is low */ write_pin(LEDS_OUT,LAMP,LOW); write_pin(LEDS_OUT,HEATER,LOW); } <file_sep>/* * main.c * * Created on: Sep 17, 2019 * Author: Nour */ #include "LCD.h" #include "keypad.h" #define ARRAY_SIZE (uint8)100 #define DELAY_TIME 500 int main(void) { uint8 key[ARRAY_SIZE] = {0}; uint8 i; uint8 var1,var2,res; LCD_init(); /* initialize LCD */ LCD_displayStringRowColumn(0,2,"Welcome to"); LCD_displayStringRowColumn(1,1,"The Calculator"); _delay_ms(DELAY_TIME); /* wait four seconds */ LCD_clearScreen(); /* clear the LCD display */ for(i = LOW;i < ARRAY_SIZE;i++) { key[i] = Keypad_getPressedKey(); switch(key[i]) { case 47: /* ASCII of '/' */ var1 = key[i - 1]; LCD_displayCharacter(' '); LCD_displayCharacter('/'); LCD_displayCharacter(' '); _delay_ms(DELAY_TIME); var2 = Keypad_getPressedKey(); LCD_intgerToString(var2); res = var1 / var2; break; case 42: var1 = key[i - 1]; LCD_displayCharacter(' '); LCD_displayCharacter('*'); LCD_displayCharacter(' '); _delay_ms(DELAY_TIME); var2 = Keypad_getPressedKey(); LCD_intgerToString(var2); res = var1 * var2; break; case 45: var1 = key[i - 1]; LCD_displayCharacter(' '); LCD_displayCharacter('-'); LCD_displayCharacter(' '); _delay_ms(DELAY_TIME); var2 = Keypad_getPressedKey(); LCD_intgerToString(var2); res = var1 - var2; break; case 43: var1 = key[i - 1]; LCD_displayCharacter(' '); LCD_displayCharacter('+'); LCD_displayCharacter(' '); _delay_ms(DELAY_TIME); var2 = Keypad_getPressedKey(); LCD_intgerToString(var2); res = var1 + var2; break; case 61: LCD_displayCharacter(' '); LCD_displayCharacter('='); LCD_displayCharacter(' '); LCD_intgerToString(res); break; /*ASCII of ON button*/ case 13: LCD_clearScreen(); break; default: LCD_intgerToString(key[i]); break; } _delay_ms(DELAY_TIME); } while(TRUE) { } } <file_sep>/* * External_Interrupt.c * * Created on: Oct 24, 2019 * Author: Nour * Purpose: contains all external interrupt functions needed in this project */ /******************************************************************************* * Includes * *******************************************************************************/ #include "External_Interrupt.h" #include "Port.h" /******************************************************************************* * Global Variables * *******************************************************************************/ /* Global variables to hold the address of the call back function in the application */ static volatile void (*g_INT0_callBackPtr)(void) = NULL_PTR; static volatile void (*g_INT1_callBackPtr)(void) = NULL_PTR; static volatile void (*g_INT2_callBackPtr)(void) = NULL_PTR; /******************************************************************************* * Interrupt Service Routines * *******************************************************************************/ ISR(INT0_vect) { if(g_INT0_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_INT0_callBackPtr)(); } } ISR(INT1_vect) { if(g_INT1_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_INT1_callBackPtr)(); } } ISR(INT2_vect) { if(g_INT2_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_INT2_callBackPtr)(); } } /******************************************************************************* * Function Definitions * *******************************************************************************/ /***************************************************** * Function Prototype: void INT0_setCallBack(void(*a_ptr)(void)) * Description: call back function when interrupt0 is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ void INT0_setCallBack(void(*a_ptr)(void)) { g_INT0_callBackPtr = a_ptr; } /***************************************************** * Function Prototype: void INT1_setCallBack(void(*a_ptr)(void)) * Description: call back function when interrupt1 is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ void INT1_setCallBack(void(*a_ptr)(void)) { g_INT1_callBackPtr = a_ptr; } /***************************************************** * Function Prototype: void INT2_setCallBack(void(*a_ptr)(void)) * Description: call back function when interrupt2 is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ void INT2_setCallBack(void(*a_ptr)(void)) { g_INT2_callBackPtr = a_ptr; } /***************************************************** * Function Prototype: void Interrupt_init(Interrupt_ConfigType * Config_Ptr); * Description: Initialization external interrupts. * Input: Interrupt_ConfigType represents pointer to interrupt configuration structure * Output: None * return: void ******************************************************/ void Interrupt_init(Interrupt_ConfigType * Config_Ptr) { if(Config_Ptr -> interrupt == interrupt0) { /* set the interrupt state */ MCUCR_R |= Config_Ptr -> state; /* set pin corresponding to INT0 as input pin */ set_direction(DDRD_R,PD2_B,IN); /* enable INT0 */ SET_BIT(GICR_R,INT0_B); } else if(Config_Ptr -> interrupt == interrupt1) { /* set the interrupt state */ MCUCR_R |= (Config_Ptr -> state) << ISC10_B; /* set pin corresponding to INT1 as input pin */ set_direction(DDRD_R,PD3_B,IN); /* enable INT1 */ SET_BIT(GICR_R,INT1_B); } else if(Config_Ptr -> interrupt == interrupt2) { /* set the interrupt state */ MCUCSR_R |= ((Config_Ptr -> state) & 0x1) << ISC2_B; /* set pin corresponding to INT2 as input pin */ set_direction(DDRB_R,PB2_B,IN); /* enable INT2 */ SET_BIT(GICR_R,INT2_B); } } /***************************************************** * Function Prototype: void Interrupt0_setEdgeDetectionType(State state) * Description: set edge of external interrupt0. * Input: State refers to rising or falling edge * Output: None * return: void ******************************************************/ void Interrupt0_setEdgeDetectionType(State state) { /* set the interrupt state */ MCUCR_R |= state; } /***************************************************** * Function Prototype: void Interrupt1_setEdgeDetectionType(State state) * Description: set edge of external interrupt1. * Input: State refers to rising or falling edge * Output: None * return: void ******************************************************/ void Interrupt1_setEdgeDetectionType(State state) { /* set the interrupt state */ MCUCR_R |= state << ISC10_B; } /***************************************************** * Function Prototype: void Interrupt2_setEdgeDetectionType(State state) * Description: set edge of external interrupt2. * Input: State refers to rising or falling edge * Output: None * return: void ******************************************************/ void Interrupt2_setEdgeDetectionType(State state) { /* set the interrupt state */ MCUCSR_R |= (state & 0x1) << ISC2_B; } /***************************************************** * Function Prototype: void Interrupt0_DeInit(void) * Description: De-initialize interrupt0. * Input: None * Output: None * return: void ******************************************************/ void Interrupt0_DeInit(void) { CLEAR_BIT(GICR_R,INT0_B); } /***************************************************** * Function Prototype: void Interrupt1_DeInit(void) * Description: De-initialize interrupt1. * Input: None * Output: None * return: void ******************************************************/ void Interrupt1_DeInit(void) { CLEAR_BIT(GICR_R,INT1_B); } /***************************************************** * Function Prototype: void Interrupt2_DeInit(void) * Description: De-initialize interrupt2. * Input: None * Output: None * return: void ******************************************************/ void Interrupt2_DeInit(void) { CLEAR_BIT(GICR_R,INT2_B); } <file_sep>/* * DC_Motor.h * * Created on: Sep 29, 2019 * Author: Nour */ #ifndef DC_MOTOR_H_ #define DC_MOTOR_H_ #include "standard_library.h" #include "common_macros.h" #include "AVR_registers.h" #define DC_MOTOR_DIR DDRD_R #define DC_MOTOR_OUT PORTD_R #define IN1 PD2_B #define IN2 PD3_B extern void DC_Motor_init(void); extern void DC_Motor_rotate_clockwise(void); extern void DC_Motor_rotate_anti_clockwise(void); extern void DC_Motor_stop(void); #endif /* DC_MOTOR_H_ */ <file_sep>/* * TWI.h * * Created on: Oct 6, 2019 * Author: Nour */ #ifndef TWI_H_ #define TWI_H_ #include "AVR_registers.h" #include "common_macros.h" #include "standard_library.h" /* I2C Status Bits in the TWSR Register */ #define TW_START 0x08 // start has been sent #define TW_REP_START 0x10 // repeated start #define TW_MT_SLA_W_ACK 0x18 // Master transmit ( slave address + Write request ) to slave + Ack received from slave #define TW_MT_SLA_R_ACK 0x40 // Master transmit ( slave address + Read request ) to slave + Ack received from slave #define TW_MT_DATA_ACK 0x28 // Master transmit data and ACK has been received from Slave. #define TW_MR_DATA_ACK 0x50 // Master received data and send ACK to slave #define TW_MR_DATA_NACK 0x58 // Master received data but doesn't send ACK to slave #define NORMAL 100000 #define FAST 400000 #define SCL FAST /* F_CPU=8Mhz */ #define TWBR_VALUE (uint8)(((F_CPU/SCL) - 16) / 2) extern void TWI_init(void); extern void TWI_start(void); extern void TWI_stop(void); extern void TWI_write(uint8 data); extern uint8 TWI_read_with_ACK(void); extern uint8 TWI_read_with_NACK(void); extern uint8 TWI_get_status(void); #endif /* TWI_H_ */ <file_sep>/* * Timer.c * * Created on: Sep 28, 2019 * Author: Nour * Purpose: contains all timer functions needed in this project */ /******************************************************************************* * Includes * *******************************************************************************/ #include "Timer.h" #include "Port.h" /******************************************************************************* * Global Variables * *******************************************************************************/ /* Global variables to hold the address of the call back function in the application */ static volatile void (*g_Timer0_OVF_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer0_COMP_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer2_OVF_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer2_COMP_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer1_OVF_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer1_COMPA_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer1_COMPB_callBackPtr)(void) = NULL_PTR; /******************************************************************************* * Interrupt Service Routines * *******************************************************************************/ ISR(TIMER0_OVF_vect) { if(g_Timer0_OVF_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer0_OVF_callBackPtr)(); } } ISR(TIMER0_COMP_vect) { if(g_Timer0_COMP_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer0_COMP_callBackPtr)(); } } ISR(TIMER1_OVF_vect) { if(g_Timer1_OVF_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer1_OVF_callBackPtr)(); } } ISR(TIMER1_COMPA_vect) { if(g_Timer1_COMPA_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer1_COMPA_callBackPtr)(); } } ISR(TIMER1_COMPB_vect) { if(g_Timer1_COMPB_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer1_COMPB_callBackPtr)(); } } ISR(TIMER2_OVF_vect) { if(g_Timer2_OVF_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer2_OVF_callBackPtr)(); } } ISR(TIMER2_COMP_vect) { if(g_Timer2_COMP_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer2_COMP_callBackPtr)(); } } /******************************************************************************* * Function Definitions * *******************************************************************************/ /***************************************************** * Function Prototype: void Timer_init(Timer_ConfigType * Config_Ptr) * Description: Initialization timers. * Input: Timer_ConfigType represents pointer to timer configuration structure * Output: None * return: void ******************************************************/ void Timer_init(Timer_ConfigType * Config_Ptr) { if(Config_Ptr -> timer == Timer0) { /* Timer initial value */ TCNT0_R = 0; /* In case of overflow or CTC mode */ /* Note: WGM00 and WGM01 are not followed in registers arrangement */ TCCR0_R = (1 << FOC0_B) | ((Config_Ptr -> mode & 0x1) << WGM00_B) | (((Config_Ptr -> mode & 0x2) >> 1) << WGM01_B) | (Config_Ptr -> prescalar_Timer0 << CS00_B); if(Config_Ptr -> mode == Overflow) { /* check if interrupt is enabled */ if(Config_Ptr -> state == interrupt) { /* Enable Timer0 overflow interrupt */ SET_BIT(TIMSK_R,TOIE0_B); } } else if(Config_Ptr -> mode == CTC) { /* Compare value */ OCR0_R = Config_Ptr -> u8_comp_value; /* Check if we are not producing a square wave on OCO pin */ if(Config_Ptr -> COM == Normal) { /* check if interrupt is enabled */ if(Config_Ptr -> state == interrupt) { /* Enable Timer0 CTC interrupt */ SET_BIT(TIMSK_R,OCIE0_B); } } else { TCCR0_R = (1 << FOC0_B) | ((Config_Ptr -> mode & 0x1) << WGM00_B) | (((Config_Ptr -> mode & 0x2) >> 1) << WGM01_B) | (Config_Ptr -> prescalar_Timer0 << CS00_B) | (Config_Ptr -> COM << COM00_B); /* Set OC0 as output pin */ set_direction(DDRB_R,PB3_B,OUT); } } } else if(Config_Ptr -> timer == Timer2) { /* Timer initial value */ TCNT2_R = 0; /* In case of overflow or CTC mode */ /* Note: WGM20 and WGM21 are not followed in registers arrangement */ TCCR2_R = (1 << FOC2_B) | ((Config_Ptr -> mode & 0x1) << WGM20_B) | (((Config_Ptr -> mode & 0x2) >> 1) << WGM21_B) | (Config_Ptr -> prescalar_Timer2 << CS20_B); if(Config_Ptr -> mode == Overflow) { /* check if interrupt is enabled */ if(Config_Ptr -> state == interrupt) { /* Enable Timer2 overflow interrupt */ SET_BIT(TIMSK_R,TOIE2_B); } } else if(Config_Ptr -> mode == CTC) { /* Compare value */ OCR2_R = Config_Ptr -> u8_comp_value; /* Check if we are not producing a square wave on OC2 pin */ if(Config_Ptr -> COM == Normal) { /* check if interrupt is enabled */ if(Config_Ptr -> state == interrupt) { /* Enable Timer2 CTC interrupt */ SET_BIT(TIMSK_R,OCIE2_B); } } else { TCCR2_R = (1 << FOC2_B) | ((Config_Ptr -> mode & 0x1) << WGM20_B) | (((Config_Ptr -> mode & 0x2) >> 1) << WGM21_B) | (Config_Ptr -> prescalar_Timer2 << CS20_B) | (Config_Ptr -> COM << COM20_B); /* Set OC2 as output pin */ set_direction(DDRD_R,PD7_B,OUT); } } } else if(Config_Ptr -> timer == Timer1) { /* Timer initial value */ TCNT1_R = 0; /* In case of overflow or CTC mode */ TCCR1A_R = (1 << FOC1A_B) | (1 << FOC1B_B); TCCR1B_R = (Config_Ptr -> prescalar_Timer1 << CS10_B) | ((Config_Ptr -> mode >> 1) << WGM12_B); if(Config_Ptr -> mode == Overflow) { if(Config_Ptr -> state == interrupt) { /* Enable Timer1 overflow interrupt */ SET_BIT(TIMSK_R,TOIE1_B); } } /* We have two channels Channel A and Channel B */ else if(Config_Ptr -> mode == CTC) { if(Config_Ptr -> channel == Channel_A) { /* Compare value */ OCR1A_R = Config_Ptr -> u16_comp_value_A; /* Check if we are not producing a square wave on OC1A pin */ if(Config_Ptr -> COM == Normal) { /* check if interrupt is enabled */ if(Config_Ptr -> state == interrupt) { /* Enable Timer1_A CTC interrupt */ SET_BIT(TIMSK_R,OCIE1A_B); } } else { TCCR1A_R = (1 << FOC1A_B) | (1 << FOC1B_B) | (Config_Ptr -> COM << COM1A0_B); /* Set OC1A as output pin */ set_direction(DDRD_R,PD5_B,OUT); } } else if(Config_Ptr -> channel == Channel_B) { /* Compare value */ OCR1B_R = Config_Ptr -> u16_comp_value_B; /* Check if we are not producing a square wave on OC1B pin */ if(Config_Ptr -> COM == Normal) { /* check if interrupt is enabled */ if(Config_Ptr -> state == interrupt) { /* Enable Timer1_B CTC interrupt */ SET_BIT(TIMSK_R,OCIE1B_B); } } else { TCCR1A_R = (1 << FOC1A_B) | (1 << FOC1B_B) | (Config_Ptr -> COM << COM1B0_B); /* Set OC1B as output pin */ set_direction(DDRD_R,PD4_B,OUT); } } } } } /***************************************************** * Function Prototype: void Timer0_DeInit(void) * Description: De-initialize timer0. * Input: None * Output: None * return: void ******************************************************/ void Timer0_DeInit(void) { TCNT0_R = 0; TCCR0_R = 0; } /***************************************************** * Function Prototype: void Timer1_DeInit(void) * Description: De-initialize timer1. * Input: None * Output: None * return: void ******************************************************/ void Timer1_DeInit(void) { TCNT1_R = 0; TCCR1A_R = 0; TCCR1B_R = 0; } /***************************************************** * Function Prototype: void Timer2_DeInit(void) * Description: De-initialize timer2. * Input: None * Output: None * return: void ******************************************************/ void Timer2_DeInit(void) { TCNT2_R = 0; TCCR2_R = 0; } /***************************************************** * Function Prototype: void Timer0_clearTimerValue(void) * Description: clear timer0 value. * Input: None * Output: None * return: void ******************************************************/ void Timer0_clearTimerValue(void) { TCNT0_R = 0; } /***************************************************** * Function Prototype: void Timer1_clearTimerValue(void) * Description: clear timer1 value. * Input: None * Output: None * return: void ******************************************************/ void Timer1_clearTimerValue(void) { TCNT1_R = 0; } /***************************************************** * Function Prototype: void Timer2_clearTimerValue(void) * Description: clear timer2 value. * Input: None * Output: None * return: void ******************************************************/ void Timer2_clearTimerValue(void) { TCNT2_R = 0; } /***************************************************** * Function Prototype: uint8 Timer0_getTimerValue(void) * Description: get timer0 value. * Input: None * Output: uint8 represents timer0 value * return: uint8 ******************************************************/ uint8 Timer0_getTimerValue(void) { return TCNT0_R; } /***************************************************** * Function Prototype: uint16 Timer1_getTimerValue(void) * Description: get timer1 value. * Input: None * Output: uint16 represents timer1 value * return: uint16 ******************************************************/ uint16 Timer1_getTimerValue(void) { return TCNT1_R; } /***************************************************** * Function Prototype: uint8 Timer2_getTimerValue(void) * Description: get timer2 value. * Input: None * Output: uint8 represents timer2 value * return: uint8 ******************************************************/ uint8 Timer2_getTimerValue(void) { return TCNT2_R; } /***************************************************** * Function Prototype: void Timer0_OVF_setInterrupt(void) * Description: set interrupt for timer0 overflow mode. * Input: None * Output: None * return: void ******************************************************/ void Timer0_OVF_setInterrupt(void) { /* Enable Timer0 overflow interrupt */ SET_BIT(TIMSK_R,TOIE0_B); } /***************************************************** * Function Prototype: void Timer0_COMP_setInterrupt(void) * Description: set interrupt for timer0 CTC mode. * Input: None * Output: None * return: void ******************************************************/ void Timer0_COMP_setInterrupt(void) { /* Enable Timer0 CTC interrupt */ SET_BIT(TIMSK_R,OCIE0_B); } /***************************************************** * Function Prototype: void Timer1_OVF_setInterrupt(void) * Description: set interrupt for timer1 overflow mode. * Input: None * Output: None * return: void ******************************************************/ void Timer1_OVF_setInterrupt(void) { /* Enable Timer1 overflow interrupt */ SET_BIT(TIMSK_R,TOIE1_B); } /***************************************************** * Function Prototype: void Timer1_COMPA_setInterrupt(void) * Description: set interrupt for timer1 CTC mode channelA. * Input: None * Output: None * return: void ******************************************************/ void Timer1_COMPA_setInterrupt(void) { /* Enable Timer1 CTC interrupt channelA */ SET_BIT(TIMSK_R,OCIE1A_B); } /***************************************************** * Function Prototype: void Timer1_COMPB_setInterrupt(void) * Description: set interrupt for timer1 CTC mode channelB. * Input: None * Output: None * return: void ******************************************************/ void Timer1_COMPB_setInterrupt(void) { /* Enable Timer1_B CTC interrupt */ SET_BIT(TIMSK_R,OCIE1B_B); } /***************************************************** * Function Prototype: void Timer2_OVF_setInterrupt(void) * Description: set interrupt for timer2 overflow mode. * Input: None * Output: None * return: void ******************************************************/ void Timer2_OVF_setInterrupt(void) { /* Enable Timer2 overflow interrupt */ SET_BIT(TIMSK_R,TOIE2_B); } /***************************************************** * Function Prototype: void Timer2_COMP_setInterrupt(void) * Description: set interrupt for timer2 CTC mode. * Input: None * Output: None * return: void ******************************************************/ void Timer2_COMP_setInterrupt(void) { /* Enable Timer2 CTC interrupt */ SET_BIT(TIMSK_R,OCIE2_B); } /***************************************************** * Function Prototype: void Timer0_OVF_clearInterrupt(void) * Description: clear interrupt for timer0 overflow mode. * Input: None * Output: None * return: void ******************************************************/ void Timer0_OVF_clearInterrupt(void) { /* Disable Timer0 overflow interrupt */ CLEAR_BIT(TIMSK_R,TOIE0_B); } /***************************************************** * Function Prototype: void Timer0_COMP_clearInterrupt(void) * Description: clear interrupt for timer0 CTC mode. * Input: None * Output: None * return: void ******************************************************/ void Timer0_COMP_clearInterrupt(void) { /* Disable Timer0 CTC interrupt */ CLEAR_BIT(TIMSK_R,OCIE0_B); } /***************************************************** * Function Prototype: void Timer1_OVF_clearInterrupt(void) * Description: clear interrupt for timer1 overflow mode. * Input: None * Output: None * return: void ******************************************************/ void Timer1_OVF_clearInterrupt(void) { /* Disable Timer1 overflow interrupt */ CLEAR_BIT(TIMSK_R,TOIE1_B); } /***************************************************** * Function Prototype: void Timer1_COMPA_clearInterrupt(void) * Description: clear interrupt for timer1 CTC mode channelA. * Input: None * Output: None * return: void ******************************************************/ void Timer1_COMPA_clearInterrupt(void) { /* Disable Timer1 CTC interrupt channelA */ CLEAR_BIT(TIMSK_R,OCIE1A_B); } /***************************************************** * Function Prototype: void Timer1_COMPB_clearInterrupt(void) * Description: clear interrupt for timer1 CTC mode channelB. * Input: None * Output: None * return: void ******************************************************/ void Timer1_COMPB_clearInterrupt(void) { /* Disable Timer1_B CTC interrupt */ CLEAR_BIT(TIMSK_R,OCIE1B_B); } /***************************************************** * Function Prototype: void Timer2_OVF_clearInterrupt(void) * Description: clear interrupt for timer2 overflow mode. * Input: None * Output: None * return: void ******************************************************/ void Timer2_OVF_clearInterrupt(void) { /* Disable Timer2 overflow interrupt */ CLEAR_BIT(TIMSK_R,TOIE2_B); } /***************************************************** * Function Prototype: void Timer2_COMP_clearInterrupt(void) * Description: clear interrupt for timer2 CTC mode. * Input: None * Output: None * return: void ******************************************************/ void Timer2_COMP_clearInterrupt(void) { /* Disable Timer2 CTC interrupt */ CLEAR_BIT(TIMSK_R,OCIE2_B); } /***************************************************** * Function Prototype: void Timer0_OVF_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer0 overflow interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ void Timer0_OVF_setCallBack(void(*a_ptr)(void)) { g_Timer0_OVF_callBackPtr = a_ptr; } /***************************************************** * Function Prototype: void Timer0_COMP_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer0 CTC interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ void Timer0_COMP_setCallBack(void(*a_ptr)(void)) { g_Timer0_COMP_callBackPtr = a_ptr; } /***************************************************** * Function Prototype: void Timer1_OVF_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer1 overflow interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ void Timer1_OVF_setCallBack(void(*a_ptr)(void)) { g_Timer1_OVF_callBackPtr = a_ptr; } /***************************************************** * Function Prototype: void Timer1_COMPA_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer1 channelA CTC interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ void Timer1_COMPA_setCallBack(void(*a_ptr)(void)) { g_Timer1_COMPA_callBackPtr = a_ptr; } /***************************************************** * Function Prototype: void Timer1_COMPB_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer1 channelB CTC interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ void Timer1_COMPB_setCallBack(void(*a_ptr)(void)) { g_Timer1_COMPB_callBackPtr = a_ptr; } /***************************************************** * Function Prototype: void Timer2_OVF_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer2 overflow interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ void Timer2_OVF_setCallBack(void(*a_ptr)(void)) { g_Timer2_OVF_callBackPtr = a_ptr; } /***************************************************** * Function Prototype: void Timer2_COMP_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer2 CTC interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ void Timer2_COMP_setCallBack(void(*a_ptr)(void)) { g_Timer2_COMP_callBackPtr = a_ptr; } <file_sep>/* * SPI.h * * Created on: Sep 25, 2019 * Author: Nour */ #ifndef SPI_H_ #define SPI_H_ #include "AVR_registers.h" #include "common_macros.h" #include "standard_library.h" typedef enum { _4,_16,_64,_128,_2,_8,_32 }SCK_Frequency; typedef struct { SCK_Frequency frequency; }SPI_ConfigType; extern void SPI_initMaster(const SPI_ConfigType * Config_Ptr); extern void SPI_initSlave(const SPI_ConfigType * Config_Ptr); extern void SPI_sendByte(uint8 byte); extern void SPI_sendString(const uint8 * Str_Ptr); extern uint8 SPI_recieveByte(void); extern void SPI_recieveString(uint8 * Str_Ptr); #endif /* SPI_H_ */ <file_sep>/* * External_Interrupt.h * * Created on: Oct 24, 2019 * Author: Nour */ #ifndef EXTERNAL_INTERRUPT_H_ #define EXTERNAL_INTERRUPT_H_ #include "standard_library.h" #include "common_macros.h" #include "AVR_registers.h" #include <avr/interrupt.h> typedef enum { interrupt0,interrupt1,interrupt2 }Interrupt; typedef enum { low,high,falling,rising }State; typedef struct { Interrupt interrupt; State state; }Interrupt_ConfigType; extern void Interrupt_init(Interrupt_ConfigType * Config_Ptr); extern void INT0_setCallBack(void(*a_ptr)(void)); extern void INT1_setCallBack(void(*a_ptr)(void)); extern void INT2_setCallBack(void(*a_ptr)(void)); #endif /* EXTERNAL_INTERRUPT_H_ */ <file_sep>/* * seven_segment.h * * Created on: Sep 16, 2019 * Author: Nour * Description: Header file for the seven_segment driver */ #ifndef SEVEN_SEGMENT_H_ #define SEVEN_SEGMENT_H_ /******************************************************************************* * Includes * *******************************************************************************/ #include "AVR_registers.h" #include "standard_library.h" #include "common_macros.h" /******************************************************************************* * Preprocessor Defines * *******************************************************************************/ #define SEVEN_SEGMENT_DIR DDRC_R #define SEVEN_SEGMENT_OUT PORTC_R #define FIRST_4_PINS #ifdef FIRST_4_PINS #define FIRST_FOUR_PINS 0x0F #endif #ifdef SECOND_FOUR_PINS #define SECOND_FOUR_PINS 0xF0 #endif /******************************************************************************* * Functions Prototypes * *******************************************************************************/ extern void seven_segment_init(void); #endif /* SEVEN_SEGMENT_H_ */ <file_sep>/* * Simple_Microwave.c * * Created on: Mar 19, 2020 * Author: Nour */ /******************************************************************************* * Includes * *******************************************************************************/ #include "LCD.h" #include "keypad.h" #include "Buttons.h" #include "Leds.h" #include "DC_Motor.h" #include "DIO.h" #include "Timer.h" #include <util/delay.h> /******************************************************************************* * Preprocessor Defines * *******************************************************************************/ /* default display on LCD */ #define DEFAULT_DISPLAY "00:00" /******************************************************************************* * ENUMS * *******************************************************************************/ typedef enum { operate,stop } State; /******************************************************************************* * Global Variables * *******************************************************************************/ /* default state is stop state */ State state = stop; /* time variables */ uint8 time_in_seconds; uint8 time_in_minutes; uint8 flag_1 = HIGH; uint8 flag_2 = HIGH; /******************************************************************************* * Functions Prototypes * *******************************************************************************/ /***************************************************** * Function Prototype: void Timer_App(void) * Description: Call back function called by timer interrupt. * Input: None * Output: None * return: void ******************************************************/ void Timer_App(void); /***************************************************** * Function Prototype: void init_all(void) * Description: Initialize all. * Input: None * Output: None * return: void ******************************************************/ void init_all(void); /***************************************************** * Function Prototype: void operate_all(void) * Description: Operation state. * Input: None * Output: None * return: void ******************************************************/ void operate_all(void); /***************************************************** * Function Prototype: void stop_all(void) * Description: Stop state. * Input: None * Output: None * return: void ******************************************************/ void stop_all(void); /***************************************************** * Function Prototype: void set_time(void) * Description: Set the time of the microwave. * Input: None * Output: None * return: void ******************************************************/ void set_time(void); /******************************************************************************* * Function Definitions * *******************************************************************************/ /***************************************************** * Function Prototype: void Timer_App(void) * Description: Call back function called by timer interrupt. * Input: None * Output: None * return: void ******************************************************/ void Timer_App(void) { /* decrement the value of time in seconds */ time_in_seconds--; if(time_in_seconds >= 10) { /* display the value of time in certain position */ LCD_goToRowColumn(0,3); LCD_intgerToString(time_in_seconds); } else { /* display the value of time in certain position */ LCD_goToRowColumn(0,3); LCD_intgerToString(0); /* display the value of time in certain position */ LCD_goToRowColumn(0,4); LCD_intgerToString(time_in_seconds); } if(time_in_seconds == 0) { /* check if the user entered time in minutes */ if(time_in_minutes != 0) { /* decrement the value of time in minutes */ time_in_minutes--; /* convert minutes to seconds */ time_in_seconds = 60; if(time_in_minutes >= 10) { /* display the value of time in certain position */ LCD_goToRowColumn(0,0); LCD_intgerToString(time_in_minutes); } else { /* display the value of time in certain position */ LCD_goToRowColumn(0,0); LCD_intgerToString(0); /* display the value of time in certain position */ LCD_goToRowColumn(0,1); LCD_intgerToString(time_in_minutes); } } /* reach here when time in seconds and minutes equal 0 */ else { /* * clear weight sensor when operation finish * clear door sensor flags when operation finish * set flag to high when operation finish */ weight_sensor_flag = LOW; door_sensor_flag = LOW; flag_1 = HIGH; /* go to stop state */ state = stop; } } } /***************************************************** * Function Prototype: void init_all(void) * Description: Initialize all. * Input: None * Output: None * return: void ******************************************************/ void init_all(void) { /* set global interrupt */ SET_BIT(SREG_R,I_B); /* set initializations */ LCD_init(); leds_init(); buttons_init(); DC_Motor_init(); } /***************************************************** * Function Prototype: void operate_all(void) * Description: Operation state. * Input: None * Output: None * return: void ******************************************************/ void operate_all(void) { /* * turn on heater * turn on lamp * operate motor * operate timer */ write_pin(LEDS_OUT,HEATER,HIGH); write_pin(LEDS_OUT,LAMP,HIGH); DC_Motor_rotate_clockwise(); Timer1_COMPA_setInterrupt(); } /***************************************************** * Function Prototype: void stop_all(void) * Description: Stop state. * Input: None * Output: None * return: void ******************************************************/ void stop_all(void) { /* * turn off heater * turn off lamp * stop motor * stop timer */ write_pin(LEDS_OUT,HEATER,LOW); write_pin(LEDS_OUT,LAMP,LOW); DC_Motor_stop(); Timer1_COMPA_clearInterrupt(); /* check if weight sensor and door sensor are high again to go to operate state */ if(weight_sensor_flag == HIGH && door_sensor_flag == HIGH) { /* * clear cancel button when operation state detected * set flag to high when operation state detected */ cancel_button_flag = LOW; flag_2 = HIGH; } } /***************************************************** * Function Prototype: void set_time(void) * Description: Set the time of the microwave. * Input: None * Output: None * return: void ******************************************************/ void set_time(void) { /* keypad variables */ uint8 keypad; uint8 keypad_input[4] = {0}; /* variable i refers to counter */ uint8 i = 0; /* 13 refers to on key, must be pressed to terminate set time function */ while(keypad != 13) { /* get input key from keypad */ keypad = Keypad_getPressedKey(); /* wait for half a second */ _delay_ms(500); if(keypad != 13) { /* save the keypad input in keypad_input array */ keypad_input[i] = keypad; if(i < 2) { /* display entered value in certain position */ LCD_goToRowColumn(0,i+3); LCD_intgerToString(keypad_input[i]); } else if(i == 2) { /* display ':' in certain position */ LCD_goToRowColumn(0,i); LCD_displayCharacter(':'); /* display entered value in certain position */ LCD_goToRowColumn(0,i-2); LCD_intgerToString(keypad_input[i]); } else if(i > 2) { /* display entered value in certain position */ LCD_goToRowColumn(0,i-2); LCD_intgerToString(keypad_input[i]); } i++; } } /* calculate time in seconds and time in minutes */ time_in_seconds = keypad_input[0] * 10 + keypad_input[1]; time_in_minutes = keypad_input[2] * 10 + keypad_input[3]; } int main(void) { /* call init_all function */ init_all(); /* display 00:00 as default */ LCD_displayString(DEFAULT_DISPLAY); /* configure the timer to interrupt every 1 sec */ Timer_ConfigType Config_struct = {Timer1,CTC,0,CLK_1024,0,0,0,1000,0,Channel_A,0}; /* initialize the timer */ Timer_init(&Config_struct); /* set the callback function */ Timer1_COMPA_setCallBack(Timer_App); while(TRUE) { /* * check if food is in microwave * check if door is closed * set time * check if start button is pressed * go to operate state */ if( weight_sensor_flag == HIGH && door_sensor_flag == HIGH) { /* we want to set time only once */ if(flag_1 == HIGH) { set_time(); flag_1 = LOW; } if(read_pin(START_BUTTON_IN,START_BUTTON)) { state = operate; } } /* * check if cancel button is pressed * go to stop state */ if(cancel_button_flag == HIGH) { /* we want to go to stop state only once */ if(flag_2 == HIGH) { flag_2 = LOW; /* clear LCD screen */ LCD_clearScreen(); /* display 00:00 as default */ LCD_displayString(DEFAULT_DISPLAY); /* * clear weight sensor when operation finish * clear door sensor flags when operation finish * set flag to high when operation finish */ weight_sensor_flag = LOW; door_sensor_flag = LOW; flag_1 = HIGH; /* go to stop state */ state = stop; } } switch(state) { case operate: operate_all(); break; case stop: stop_all(); break; } } } <file_sep>/* * Buttons.h * * Created on: Mar 21, 2020 * Author: Nour * Purpose: contains all buttons functions needed in this project */ #ifndef BUTTONS_H_ #define BUTTONS_H_ /******************************************************************************* * Includes * *******************************************************************************/ #include "standard_library.h" /******************************************************************************* * Preprocessor Defines * *******************************************************************************/ #define START_BUTTON_DIR DDRB_R #define START_BUTTON_IN PINB_R #define START_BUTTON PB3_B /******************************************************************************* * Extern Module Shared Global Variables * *******************************************************************************/ extern volatile uint8 weight_sensor_flag; extern volatile uint8 door_sensor_flag; extern volatile uint8 cancel_button_flag; /******************************************************************************* * Functions Prototypes * *******************************************************************************/ /***************************************************** * Function Prototype: void buttons_init(void) * Description: Initialization buttons. * Input: None * Output: None * return: void ******************************************************/ extern void buttons_init(void); #endif /* BUTTONS_H_ */ <file_sep>/* * LCD.h * * Created on: Sep 16, 2019 * Author: Nour * Purpose: contains all LCD functions needed in this project */ #ifndef LCD_H_ #define LCD_H_ /******************************************************************************* * Includes * *******************************************************************************/ #include "standard_library.h" /******************************************************************************* * Preprocessor Defines * *******************************************************************************/ #define TWO_LINE_LCD_8_BIT_MODE #define LCD_CTRL_DIR DDRD_R #define LCD_CTRL_OUT PORTD_R #define LCD_DATA_DIR DDRC_R #define LCD_DATA_OUT PORTC_R #define RS PD4_B #define RW PD5_B #define E PD6_B /* LCD Commands */ #ifdef TWO_LINE_LCD_4_BIT_MODE #define TWO_LINE_LCD_Four_BIT_MODE 0x28 #define FOUR_BITS_DATA_MODE 0x02 #endif #ifdef TWO_LINE_LCD_8_BIT_MODE #define TWO_LINE_LCD_Eight_BIT_MODE 0x38 #endif #define CLEAR_COMMAND 0x01 #define CURSOR_OFF 0x0C #define CURSOR_ON 0x0E #define SET_CURSOR_LOCATION 0x80 /******************************************************************************* * Functions Prototypes * *******************************************************************************/ /***************************************************** * Function Prototype: void LCD_init(void) * Description: Initialization LCD. * Input: None * Output: None * return: void ******************************************************/ extern void LCD_init(void); /***************************************************** * Function Prototype: void LCD_sendCommand(uint8 cmd) * Description: Send command. * Input: uint8 refers to command * Output: None * return: void ******************************************************/ extern void LCD_sendCommand(uint8 cmd); /***************************************************** * Function Prototype: void LCD_displayCharacter(uint8 data) * Description: Display character. * Input: uint8 refers to data * Output: None * return: void ******************************************************/ extern void LCD_displayCharacter(uint8 data); /***************************************************** * Function Prototype: void LCD_displayString(const uint8 *str) * Description: Display string. * Input: uint8* refers to string * Output: None * return: void ******************************************************/ extern void LCD_displayString(const uint8 *str); /***************************************************** * Function Prototype: void LCD_displayStringRowColumn(uint8 row,uint8 col,const uint8 *str) * Description: Display string at certain row and column. * Input: uint8* refers to string,uint8 refers to row and uint8 refers to column * Output: None * return: void ******************************************************/ extern void LCD_displayStringRowColumn(uint8 row,uint8 col,const uint8 *str); /***************************************************** * Function Prototype: void LCD_goToRowColumn(uint8 row,uint8 col) * Description: Go to a certain row and column. * Input: uint8 refers to row and uint8 refers to column * Output: None * return: void ******************************************************/ extern void LCD_goToRowColumn(uint8 row,uint8 col); /***************************************************** * Function Prototype: void LCD_intgerToString(uint8 data) * Description: Converts integer data to string. * Input: uint8 refers to data * Output: None * return: void ******************************************************/ extern void LCD_intgerToString(uint8 data); /***************************************************** * Function Prototype: void LCD_clearScreen(void) * Description: Clear LCD screen. * Input: None * Output: None * return: void ******************************************************/ extern void LCD_clearScreen(void); #endif /* LCD_H_ */ <file_sep>/* * External_Interrupt.h * * Created on: Oct 24, 2019 * Author: Nour * Purpose: contains all external interrupt functions needed in this project */ #ifndef EXTERNAL_INTERRUPT_H_ #define EXTERNAL_INTERRUPT_H_ /******************************************************************************* * Includes * *******************************************************************************/ #include "common_macros.h" #include "standard_library.h" #include "AVR_registers.h" #include <avr/interrupt.h> /******************************************************************************* * ENUMS * *******************************************************************************/ typedef enum { interrupt0,interrupt1,interrupt2 }Interrupt; typedef enum { low,high,falling,rising }State; /******************************************************************************* * Structures * *******************************************************************************/ /***************************************************** * Structure Name: Interrupt_ConfigType * Description: This structure is responsible for dynamic configuration of external interrupt module. ******************************************************/ typedef struct { Interrupt interrupt; State state; }Interrupt_ConfigType; /******************************************************************************* * Functions Prototypes * *******************************************************************************/ /***************************************************** * Function Prototype: void Interrupt_init(Interrupt_ConfigType * Config_Ptr); * Description: Initialization external interrupts. * Input: Interrupt_ConfigType represents pointer to interrupt configuration structure * Output: None * return: void ******************************************************/ extern void Interrupt_init(Interrupt_ConfigType * Config_Ptr); /***************************************************** * Function Prototype: void Interrupt0_DeInit(void) * Description: De-initialize interrupt0. * Input: None * Output: None * return: void ******************************************************/ extern void Interrupt0_DeInit(void); /***************************************************** * Function Prototype: void Interrupt1_DeInit(void) * Description: De-initialize interrupt1. * Input: None * Output: None * return: void ******************************************************/ extern void Interrupt1_DeInit(void); /***************************************************** * Function Prototype: void Interrupt2_DeInit(void) * Description: De-initialize interrupt2. * Input: None * Output: None * return: void ******************************************************/ extern void Interrupt2_DeInit(void); /***************************************************** * Function Prototype: void Interrupt0_setEdgeDetectionType(State state) * Description: set edge of external interrupt0. * Input: State refers to rising or falling edge * Output: None * return: void ******************************************************/ extern void Interrupt0_setEdgeDetectionType(State state); /***************************************************** * Function Prototype: void Interrupt1_setEdgeDetectionType(State state) * Description: set edge of external interrupt1. * Input: State refers to rising or falling edge * Output: None * return: void ******************************************************/ extern void Interrupt1_setEdgeDetectionType(State state); /***************************************************** * Function Prototype: void Interrupt2_setEdgeDetectionType(State state) * Description: set edge of external interrupt2. * Input: State refers to rising or falling edge * Output: None * return: void ******************************************************/ extern void Interrupt2_setEdgeDetectionType(State state); /***************************************************** * Function Prototype: void INT0_setCallBack(void(*a_ptr)(void)) * Description: call back function when interrupt0 is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ extern void INT0_setCallBack(void(*a_ptr)(void)); /***************************************************** * Function Prototype: void INT1_setCallBack(void(*a_ptr)(void)) * Description: call back function when interrupt1 is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ extern void INT1_setCallBack(void(*a_ptr)(void)); /***************************************************** * Function Prototype: void INT2_setCallBack(void(*a_ptr)(void)) * Description: call back function when interrupt2 is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ extern void INT2_setCallBack(void(*a_ptr)(void)); #endif /* EXTERNAL_INTERRUPT_H_ */ <file_sep>/* * TWI.c * * Created on: Oct 6, 2019 * Author: Nour */ #include "TWI.h" void TWI_init(void) { TWBR_R = TWBR_VALUE; TWSR_R = 0; /* * Two Wire Bus address: my address if any master device want to call me * General Call Recognition: Off */ TWAR_R = 0x01 << TWA0_B; TWCR_R = (1 << TWEN_B); } void TWI_start(void) { /* * Clear the TWINT flag before sending the start bit TWINT=1 * send the start bit by TWSTA=1 * Enable TWI Module TWEN=1 */ TWCR_R = (1 << TWEN_B) | (1 << TWSTA_B) | (1 << TWINT_B); /* Wait for TWINT flag set in TWCR Register (start bit is send successfully) */ while(BIT_IS_CLEAR(TWCR_R,TWINT_B)); } void TWI_stop(void) { /* * Clear the TWINT flag before sending the start bit TWINT=1 * send the stop bit by TWSTO=1 * Enable TWI Module TWEN=1 */ TWCR_R = (1 << TWEN_B) | (1 << TWSTO_B) | (1 << TWINT_B); } void TWI_write(uint8 data) { /* Put data On TWI data Register */ TWDR_R = data; /* * Clear the TWINT flag before sending the data TWINT=1 * Enable TWI Module TWEN=1 */ TWCR_R = (1 << TWEN_B) | (1 << TWWC_B) | (1 << TWINT_B); /* Wait for TWINT flag set in TWCR Register (start bit is send successfully) */ while(BIT_IS_CLEAR(TWCR_R,TWINT_B)); } uint8 TWI_read_with_ACK(void) { /* * Clear the TWINT flag before reading the data TWINT=1 * Enable sending ACK after reading or receiving data TWEA=1 * Enable TWI Module TWEN=1 */ TWCR_R = (1 << TWEN_B) | (1 << TWINT_B) | (1 << TWEA_B); /* Wait for TWINT flag set in TWCR Register (start bit is send successfully) */ while(BIT_IS_CLEAR(TWCR_R,TWINT_B)); /* Read Data */ return TWDR_R; } uint8 TWI_read_with_NACK(void) { /* * Clear the TWINT flag before reading the data TWINT=1 * Enable TWI Module TWEN=1 */ TWCR_R = (1 << TWINT_B) | (1 << TWEN_B); /* Wait for TWINT flag set in TWCR Register (data received successfully) */ while(BIT_IS_CLEAR(TWCR_R,TWINT_B)); /* Read Data */ return TWDR_R; } uint8 TWI_get_status(void) { uint8 status; /* masking to eliminate first 3 bits and get the last 5 bits (status bits) */ status = TWSR_R & 0xF8; return status; } <file_sep>/* * standard_library.h * * Created on: Sep 16, 2019 * Author: Nour */ #ifndef STANDARD_LIBRARY_H_ #define STANDARD_LIBRARY_H_ #define LOW 0u #define HIGH 1u #define FALSE 0u #define TRUE 1u typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned long uint32; typedef unsigned long long uint64; #endif /* STANDARD_LIBRARY_H_ */ <file_sep>/* * AVR_registers.h * * Created on: Sep 16, 2019 * Author: Nour */ #ifndef AVR_REGISTERS_H_ #define AVR_REGISTERS_H_ /* General purpose I/O registers and bits */ #define PORTA_R (*(volatile uint8 * const)0x003B) #define PORTB_R (*(volatile uint8 * const)0x0038) #define PORTC_R (*(volatile uint8 * const)0x0035) #define PORTD_R (*(volatile uint8 * const)0x0032) #define DDRA_R (*(volatile uint8 * const)0x003A) #define DDRB_R (*(volatile uint8 * const)0x0037) #define DDRC_R (*(volatile uint8 * const)0x0034) #define DDRD_R (*(volatile uint8 * const)0x0031) #define PINA_R (*(volatile uint8 * const)0x0039) #define PINB_R (*(volatile uint8 * const)0x0036) #define PINC_R (*(volatile uint8 * const)0x0033) #define PIND_R (*(volatile uint8 * const)0x0030) #define PA0_B 0 #define PA1_B 1 #define PA2_B 2 #define PA3_B 3 #define PA4_B 4 #define PA5_B 5 #define PA6_B 6 #define PA7_B 7 #define PB0_B 0 #define PB1_B 1 #define PB2_B 2 #define PB3_B 3 #define PB4_B 4 #define PB5_B 5 #define PB6_B 6 #define PB7_B 7 #define PC0_B 0 #define PC1_B 1 #define PC2_B 2 #define PC3_B 3 #define PC4_B 4 #define PC5_B 5 #define PC6_B 6 #define PC7_B 7 #define PD0_B 0 #define PD1_B 1 #define PD2_B 2 #define PD3_B 3 #define PD4_B 4 #define PD5_B 5 #define PD6_B 6 #define PD7_B 7 /* Interrupts registers and bits */ /* Global interrupt (I-bit) */ #define SREG_R (*(volatile uint8 * const)0x005F) #define I_B 7 /* External interrupt */ #define MCUCR_R (*(volatile uint8 * const)0x0055) #define ISC01_B 0 #define ISC10_B 1 #define ISC11_B 2 #define MCUCSR_R (*(volatile uint8 * const)0x0054) #define ISC2_B 6 #define GICR_R (*(volatile uint8 * const)0x005B) #define INT0_B 6 #define INT1_B 7 #define INT2_B 5 #define GIFR_R (*(volatile uint8 * const)0x005A) #define INTF0_B 6 #define INTF1_B 7 #define INTF2_B 5 /* Timers registers and bits */ /* Watchdog Timer */ #define WDTCR_R (*(volatile uint8 * const)0x0041) #define WDP0_B 0 #define WDP1_B 1 #define WDP2_B 2 #define WDE_B 3 #define WDTOE_B 4 /* Timer 1 */ /* ADC registers and bits */ #define ADMUX_R (*(volatile uint8 * const)0x0027) #define MUX0_B 0 #define MUX1_B 1 #define MUX2_B 2 #define MUX3_B 3 #define MUX4_B 4 #define ADLAR_B 5 #define REFS0_B 6 #define REFS1_B 7 #define ADCSRA_R (*(volatile uint8 * const)0x0026) #define ADPS0_B 0 #define ADPS1_B 1 #define ADPS2_B 2 #define ADIE_B 3 #define ADIF_B 4 #define ADATE_B 5 #define ADSC_B 6 #define ADEN_B 7 #define ADCL_R (*(volatile uint8 * const)0x0024) #define ADCH_R (*(volatile uint8 * const)0x0025) #define ADC_R (*(volatile uint16 * const)0x0024) #define SFIOR_R (*(volatile uint8 * const)0x0050) #define ADTS0_B 5 #define ADTS1_B 6 #define ADTS2_B 7 /* SPI registers and bits */ #define SPCR_R (*(volatile uint8 * const)0x002D) #define SPR0_B 0 #define SPR1_B 1 #define CPHA_B 2 #define CPOL_B 3 #define MSTR_B 4 #define DORD_B 5 #define SPE_B 6 #define SPIE_B 7 #define SPSR_R (*(volatile uint8 * const)0x002E) #define SPI2X_B 0 #define WCOL_B 6 #define SPIF_B 7 #define SPDR_R (*(volatile uint8 * const)0x002F) #define LSB_B 0 #define MSB_B 7 /* UART registers and bits */ #define UDR_R (*(volatile uint8 * const)0x002C) #define UCSRA_R (*(volatile uint8 * const)0x002B) #define MPCM_B 0 #define U2X_B 1 #define PE_B 2 #define DOR_B 3 #define FE_B 4 #define UDRE_B 5 #define TXC_B 6 #define RXC_B 7 #define UCSRB_R (*(volatile uint8 * const)0x002A) #define TXB8_B 0 #define RXB8_B 1 #define UCSZ2_B 2 #define TXEN_B 3 #define RXEN_B 4 #define UDRIE_B 5 #define TXCIE_B 6 #define RXCIE_B 7 #define UCSRC_R (*(volatile uint8 * const)0x0040) #define UCPOL_B 0 #define UCSZ0_B 1 #define UCSZ1_B 2 #define USBS_B 3 #define UPM0_B 4 #define UPM1_B 5 #define UMSEL_B 6 #define URSEL_B 7 #define UBRRL_R (*(volatile uint8 * const)0x0029) #define UBRRH_R (*(volatile uint8 * const)0x0040) #endif /* AVR_REGISTERS_H_ */ <file_sep>/* * AVR_registers.h * * Created on: Sep 16, 2019 * Author: Nour */ #ifndef AVR_REGISTERS_H_ #define AVR_REGISTERS_H_ /* General purpose I/O registers and bits */ #define PORTA_R (*(volatile uint8 * const)0x003B) #define PORTB_R (*(volatile uint8 * const)0x0038) #define PORTC_R (*(volatile uint8 * const)0x0035) #define PORTD_R (*(volatile uint8 * const)0x0032) #define DDRA_R (*(volatile uint8 * const)0x003A) #define DDRB_R (*(volatile uint8 * const)0x0037) #define DDRC_R (*(volatile uint8 * const)0x0034) #define DDRD_R (*(volatile uint8 * const)0x0031) #define PINA_R (*(volatile uint8 * const)0x0039) #define PINB_R (*(volatile uint8 * const)0x0036) #define PINC_R (*(volatile uint8 * const)0x0033) #define PIND_R (*(volatile uint8 * const)0x0030) #define PA0_B 0 #define PA1_B 1 #define PA2_B 2 #define PA3_B 3 #define PA4_B 4 #define PA5_B 5 #define PA6_B 6 #define PA7_B 7 #define PB0_B 0 #define PB1_B 1 #define PB2_B 2 #define PB3_B 3 #define PB4_B 4 #define PB5_B 5 #define PB6_B 6 #define PB7_B 7 #define PC0_B 0 #define PC1_B 1 #define PC2_B 2 #define PC3_B 3 #define PC4_B 4 #define PC5_B 5 #define PC6_B 6 #define PC7_B 7 #define PD0_B 0 #define PD1_B 1 #define PD2_B 2 #define PD3_B 3 #define PD4_B 4 #define PD5_B 5 #define PD6_B 6 #define PD7_B 7 /* Interrupts registers and bits */ /* Global interrupt (I-bit) */ #define SREG_R (*(volatile uint8 * const)0x005F) #define I_B 7 /* External interrupt */ #define MCUCR_R (*(volatile uint8 * const)0x0055) #define ISC01_B 0 #define ISC10_B 1 #define ISC11_B 2 #define MCUCSR_R (*(volatile uint8 * const)0x0054) #define ISC2_B 6 #define GICR_R (*(volatile uint8 * const)0x005B) #define INT0_B 6 #define INT1_B 7 #define INT2_B 5 #define GIFR_R (*(volatile uint8 * const)0x005A) #define INTF0_B 6 #define INTF1_B 7 #define INTF2_B 5 /* Timers registers and bits */ #define TIMSK_R (*(volatile uint8 * const)0x0059) #define TOIE0_B 0 /* Timer 0 */ #define OCIE0_B 1 /* Timer 0 */ #define TOIE1_B 2 /* Timer 1 */ #define OCIE1B_B 3 /* Timer 1 */ #define OCIE1A_B 4 /* Timer 1 */ #define TICIE1_B 5 /* Timer 1 */ #define TOIE2_B 6 /* Timer 2 */ #define OCIE2_B 7 /* Timer 2 */ #define TIFR_R (*(volatile uint8 * const)0x0058) #define TOV0_B 0 /* Timer 0 */ #define OCF0_B 1 /* Timer 0 */ #define TOV1_B 2 /* Timer 1 */ #define OCF1B_B 3 /* Timer 1 */ #define OCF1A_B 4 /* Timer 1 */ #define ICF1_B 5 /* Timer 1 */ #define TOV2_B 6 /* Timer 2 */ #define OCF2_B 7 /* Timer 2 */ /* Watchdog Timer */ #define WDTCR_R (*(volatile uint8 * const)0x0041) #define WDP0_B 0 #define WDP1_B 1 #define WDP2_B 2 #define WDE_B 3 #define WDTOE_B 4 /* Timer 0 */ #define TCCR0_R (*(volatile uint8 * const)0x0053) #define CS00_B 0 #define CS01_B 1 #define CS02_B 2 #define WGM01_B 3 #define COM00_B 4 #define COM01_B 5 #define WGM00_B 6 #define FOC0_B 7 #define TCNT0_R (*(volatile uint8 * const)0x0052) #define OCR0_R (*(volatile uint8 * const)0x005C) /* Timer 1 */ #define TCCR1A_R (*(volatile uint8 * const)0x004F) #define WGM10_B 0 #define WGM11_B 1 #define FOC1B_B 2 #define FOC1A_B 3 #define COM1B0_B 4 #define COM1B1_B 5 #define COM1A0_B 6 #define COM1A1_B 7 #define TCCR1B_R (*(volatile uint8 * const)0x004E) #define CS10_B 0 #define CS11_B 1 #define CS12_B 2 #define WGM12_B 3 #define WGM13_B 4 #define ICES1_B 6 #define ICNC1_B 7 #define TCNT1_R (*(volatile uint16 * const)0x004C) #define OCR1A_R (*(volatile uint16 * const)0x004A) #define OCR1B_R (*(volatile uint16 * const)0x0048) #define ICR1_R (*(volatile uint16 * const)0x0046) /* Timer 2 */ #define TCCR2_R (*(volatile uint8 * const)0x0045) #define CS20_B 0 #define CS21_B 1 #define CS22_B 2 #define WGM21_B 3 #define COM20_B 4 #define COM21_B 5 #define WGM20_B 6 #define FOC2_B 7 #define TCNT2_R (*(volatile uint8 * const)0x0044) #define OCR2_R (*(volatile uint8 * const)0x0043) /* ADC registers and bits */ #define ADMUX_R (*(volatile uint8 * const)0x0027) #define MUX0_B 0 #define MUX1_B 1 #define MUX2_B 2 #define MUX3_B 3 #define MUX4_B 4 #define ADLAR_B 5 #define REFS0_B 6 #define REFS1_B 7 #define ADCSRA_R (*(volatile uint8 * const)0x0026) #define ADPS0_B 0 #define ADPS1_B 1 #define ADPS2_B 2 #define ADIE_B 3 #define ADIF_B 4 #define ADATE_B 5 #define ADSC_B 6 #define ADEN_B 7 #define ADC_R (*(volatile uint16 * const)0x0024) #define SFIOR_R (*(volatile uint8 * const)0x0050) #define ADTS0_B 5 #define ADTS1_B 6 #define ADTS2_B 7 /* SPI registers and bits */ #define SPCR_R (*(volatile uint8 * const)0x002D) #define SPR0_B 0 #define SPR1_B 1 #define CPHA_B 2 #define CPOL_B 3 #define MSTR_B 4 #define DORD_B 5 #define SPE_B 6 #define SPIE_B 7 #define SPSR_R (*(volatile uint8 * const)0x002E) #define SPI2X_B 0 #define WCOL_B 6 #define SPIF_B 7 #define SPDR_R (*(volatile uint8 * const)0x002F) #define LSB_B 0 #define MSB_B 7 /* UART registers and bits */ #define UDR_R (*(volatile uint8 * const)0x002C) #define UCSRA_R (*(volatile uint8 * const)0x002B) #define MPCM_B 0 #define U2X_B 1 #define PE_B 2 #define DOR_B 3 #define FE_B 4 #define UDRE_B 5 #define TXC_B 6 #define RXC_B 7 #define UCSRB_R (*(volatile uint8 * const)0x002A) #define TXB8_B 0 #define RXB8_B 1 #define UCSZ2_B 2 #define TXEN_B 3 #define RXEN_B 4 #define UDRIE_B 5 #define TXCIE_B 6 #define RXCIE_B 7 #define UCSRC_R (*(volatile uint8 * const)0x0040) #define UCPOL_B 0 #define UCSZ0_B 1 #define UCSZ1_B 2 #define USBS_B 3 #define UPM0_B 4 #define UPM1_B 5 #define UMSEL_B 6 #define URSEL_B 7 #define UBRRL_R (*(volatile uint8 * const)0x0029) #define UBRRH_R (*(volatile uint8 * const)0x0040) #endif /* AVR_REGISTERS_H_ */ <file_sep>/* * main.c * * Created on: Sep 16, 2019 * Author: Nour * Description: The main file */ #include "seven_segment.h" #include "keypad.h" int main(void) { uint8 key; seven_segment_init(); while(TRUE) { /* get the pressed button from keypad */ key = Keypad_getPressedKey(); if((key >= 0) && (key <= 9)) { #ifdef FIRST_4_PINS SEVEN_SEGMENT_OUT = (SEVEN_SEGMENT_OUT & ~FIRST_FOUR_PINS) | (key & FIRST_FOUR_PINS); #endif #ifdef SECOND_4_PINS SEVEN_SEGMENT_OUT = (SEVEN_SEGMENT_OUT & ~SECOND_FOUR_PINS) | (key & SECOND_FOUR_PINS); #endif } } } <file_sep>/* * standard_library.h * * Created on: Sep 16, 2019 * Author: Nour */ #ifndef STANDARD_LIBRARY_H_ #define STANDARD_LIBRARY_H_ #define LOW 0u #define HIGH 1u #define FALSE 0u #define TRUE 1u #define NULL_PTR (void *)0 typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned long uint32; typedef unsigned long long uint64; #endif /* STANDARD_LIBRARY_H_ */ <file_sep>/* * adc.h * Created on: Sep 23, 2019 * Author: <NAME> */ #ifndef ADC_H_ #define ADC_H_ #include "micro_config.h" #include "standard_library.h" #include "common_macros.h" #include "AVR_registers.h" /******************************************************************************* * Functions Prototypes * *******************************************************************************/ /* * Description : * Function responsible for initialize the ADC driver. */ extern volatile uint16 g_ADC_value; typedef enum { AREF,AVCC,INTERNAL = 3 }ADC_Voltage; typedef enum { NO_PRESCALING,_2,_4,_8,_16,_32,_64,_128 }ADC_Prescalar; typedef enum { Polling,Interrupt }ADC_Mode; typedef struct { ADC_Voltage voltage; ADC_Prescalar prescalar; ADC_Mode mode; }ADC_ConfigType; void ADC_init(const ADC_ConfigType * Config_Ptr); /* * Description : * Function responsible for read analog data from a certain ADC channel * and convert it to digital using the ADC driver. */ void ADC_readChannel(uint8 channel_num,const ADC_ConfigType * Config_Ptr); #endif /* ADC_H_ */ <file_sep>/* * UART.h * * Created on: Sep 25, 2019 * Author: Nour */ #ifndef UART_H_ #define UART_H_ #include "AVR_registers.h" #include "common_macros.h" #include "standard_library.h" #define USART_BAUDRATE 9600 typedef enum { Disabled,Even = 2,Odd }UART_Parity; typedef enum { _1_bit,_2_bit }UART_StopBit; typedef enum { _5_bit,_6_bit,_7_bit,_8_bit }UART_Bits; typedef struct { UART_Parity parity; UART_StopBit stop_bit; UART_Bits bits; }UART_ConfigType; extern void UART_init(const UART_ConfigType * Config_Ptr); extern void UART_sendByte(uint8 data); extern void UART_sendString(const uint8 * Str_Ptr); extern uint8 UART_recieveByte(void); extern void UART_recieveString(uint8 * Str_Ptr); #endif /* UART_H_ */ <file_sep>/* * LCD.h * * Created on: Sep 16, 2019 * Author: Nour */ #ifndef LCD_H_ #define LCD_H_ #include <util/delay.h> #include "standard_library.h" #include "common_macros.h" #include "AVR_registers.h" //#define FIRST_4_PINS #define TWO_LINE_LCD_8_BIT_MODE #ifdef FIRST_4_PINS #define FIRST_FOUR_PINS 0x0F #endif #ifdef SECOND_4_PINS #define SECOND_FOUR_PINS 0xF0 #endif #define LCD_CTRL_DIR DDRD_R #define LCD_CTRL_OUT PORTD_R #define LCD_DATA_DIR DDRC_R #define LCD_DATA_OUT PORTC_R #define RS PD4_B #define RW PD5_B #define E PD6_B /* LCD Commands */ #ifdef TWO_LINE_LCD_4_BIT_MODE #define TWO_LINE_LCD_Four_BIT_MODE 0x28 #define FOUR_BITS_DATA_MODE 0x02 #endif #ifdef TWO_LINE_LCD_8_BIT_MODE #define TWO_LINE_LCD_Eight_BIT_MODE 0x38 #endif #define CLEAR_COMMAND 0x01 #define CURSOR_OFF 0x0C #define CURSOR_ON 0x0E #define SET_CURSOR_LOCATION 0x80 extern void LCD_init(void); extern void LCD_sendCommand(uint8 cmd); extern void LCD_displayCharacter(uint8 data); extern void LCD_displayString(const uint8 *str); extern void LCD_displayStringRowColumn(uint8 row,uint8 col,const uint8 *str); extern void LCD_goToRowColumn(uint8 row,uint8 col); extern void LCD_intgerToString(uint8 data); extern void LCD_clearScreen(void); #endif /* LCD_H_ */ <file_sep>/* * delay.c * * Created on: Oct 7, 2019 * Author: Nour */ #include "delay.h" void delay_s(uint16 sec) { delay_ms(sec * 1000); } void delay_ms(uint16 msec) { for(uint16 i = LOW;i < msec;i++) { while(BIT_IS_CLEAR(TIFR_R,OCF1A_B)); SET_BIT(TIFR_R,OCF1A_B); } } <file_sep>/* * seven_segment.c * * Created on: Sep 16, 2019 * Author: Nour * Description: Header file for the seven_segment driver */ #include "seven_segment.h" void seven_segment_init(void) { #ifdef FIRST_4_PINS SEVEN_SEGMENT_DIR |= FIRST_FOUR_PINS; SEVEN_SEGMENT_OUT &= ~FIRST_FOUR_PINS; #endif #ifdef SECOND_4_PINS SEVEN_SEGMENT_DIR |= SECOND_FOUR_PINS; SEVEN_SEGMENT_OUT &= ~SECOND_FOUR_PINS; #endif } <file_sep>/* * Leds.h * * Created on: Mar 20, 2020 * Author: Nour * Purpose: contains all leds functions needed in this project */ #ifndef LEDS_H_ #define LEDS_H_ /******************************************************************************* * Includes * *******************************************************************************/ #include "standard_library.h" /******************************************************************************* * Preprocessor Defines * *******************************************************************************/ #define LEDS_DIR DDRB_R #define LEDS_OUT PORTB_R #define LAMP PB0_B #define HEATER PB1_B /******************************************************************************* * Functions Prototypes * *******************************************************************************/ /***************************************************** * Function Prototype: void leds_init(void) * Description: Initialization leds. * Input: None * Output: None * return: void ******************************************************/ extern void leds_init(void); #endif /* LEDS_H_ */ <file_sep>/* * keypad.c * * Created on: Sep 16, 2019 * Author: Nour * Purpose: contains all keypad functions needed in this project */ /******************************************************************************* * Includes * *******************************************************************************/ #include "keypad.h" #include "DIO.h" /******************************************************************************* * Private Functions Prototypes * *******************************************************************************/ #if(NO_OF_COLUMNS == 3) /***************************************************** * Function Prototype: uint8 KeyPad_4x3_adjustKeyNumber(uint8 button_number) * Description: Adjust button number of 4x3 keypad. * Input: uint8 refers to keypad input number * Output: uint8 refers to adjusted value * return: uint8 ******************************************************/ static uint8 KeyPad_4x3_adjustKeyNumber(uint8 button_number); #elif(NO_OF_COLUMNS == 4) /***************************************************** * Function Prototype: uint8 KeyPad_4x4_adjustKeyNumber(uint8 button_number) * Description: Adjust button number of 4x4 keypad. * Input: uint8 refers to keypad input number * Output: uint8 refers to adjusted value * return: uint8 ******************************************************/ static uint8 KeyPad_4x4_adjustKeyNumber(uint8 button_number); #endif /******************************************************************************* * Function Definitions * *******************************************************************************/ /***************************************************** * Function Prototype: uint8 Keypad_getPressedKey(void) * Description: get the value of keypad pressed button. * Input: None * Output: uint8 refers to keypad input number * return: uint8 ******************************************************/ uint8 Keypad_getPressedKey(void) { uint8 col,row; while(TRUE) { for(col = LOW;col < NO_OF_COLUMNS;col++) { KEYPAD_DIR = 0b00010000 << col; KEYPAD_OUT = ~(0b00010000 << col); for(row = LOW;row < NO_OF_ROWS;row++) { if(!(read_pin(KEYPAD_IN,row))) { #if(NO_OF_COLUMNS == 3) return KeyPad_4x3_adjustKeyNumber((row * NO_OF_COLUMNS) + col + 1); #elif(NO_OF_COLUMNS == 4) return KeyPad_4x4_adjustKeyNumber((row * NO_OF_COLUMNS) + col + 1); #endif } } } } } #if(NO_OF_COLUMNS == 3) /***************************************************** * Function Prototype: uint8 KeyPad_4x3_adjustKeyNumber(uint8 button_number) * Description: Adjust button number of 4x3 keypad. * Input: uint8 refers to keypad input number * Output: uint8 refers to adjusted value * return: uint8 ******************************************************/ static uint8 KeyPad_4x3_adjustKeyNumber(uint8 button_number) { switch (button_number) { case 10: return '*'; break; case 11: return 0; break; case 12: return '#'; break; default: return button_number; break; } } #elif(NO_OF_COLUMNS == 4) /***************************************************** * Function Prototype: uint8 KeyPad_4x4_adjustKeyNumber(uint8 button_number) * Description: Adjust button number of 4x4 keypad. * Input: uint8 refers to keypad input number * Output: uint8 refers to adjusted value * return: uint8 ******************************************************/ static uint8 KeyPad_4x4_adjustKeyNumber(uint8 button_number) { switch(button_number) { case 1: return 7; break; case 2: return 8; break; case 3: return 9; break; case 4: return '/'; break; case 5: return 4; break; case 6: return 5; break; case 7: return 6; break; case 8: return '*'; break; case 9: return 1; break; case 10: return 2; break; case 11: return 3; break; case 12: return '-'; break; case 14: return 0; break; case 15: return '='; break; case 16: return '+'; break; default: return button_number; break; } } #endif <file_sep>/* * delay.h * * Created on: Oct 7, 2019 * Author: Nour */ #ifndef DELAY_H_ #define DELAY_H_ #include "standard_library.h" #include "common_macros.h" #include "AVR_registers.h" extern void delay_ms(uint16 msec); extern void delay_s(uint16 sec); #endif /* DELAY_H_ */ <file_sep>/* * DIO.h * * Created on: Mar 20, 2020 * Author: Nour * Purpose: contains all DIO functions needed in this project */ #ifndef DIO_H_ #define DIO_H_ /******************************************************************************* * Includes * *******************************************************************************/ #include "common_macros.h" #include "standard_library.h" #include "AVR_registers.h" /******************************************************************************* * Preprocessor Defines * *******************************************************************************/ #define FIRST_FOUR_PINS 0x0F #define SECOND_FOUR_PINS 0xF0 /******************************************************************************* * Functions-Like Macros * *******************************************************************************/ /***************************************************** * Macro: write_pin(port,pin,value) * Description: Write output to a certain pin. * Input: port, pin and value: high or low * Output: None ******************************************************/ #define write_pin(port,pin,value)\ {\ if(value == HIGH)\ SET_BIT(port,pin);\ else if(value == LOW)\ CLEAR_BIT(port,pin);\ } /***************************************************** * Macro: write_port(port,value) * Description: Write output to a port. * Input: port and value: high or low * Output: None ******************************************************/ #define write_port(port,value)\ {\ port = value;\ } /***************************************************** * Macro: write_group(port,group,value) * Description: Write output to a group. * Input: port, group and value: high or low * Output: None ******************************************************/ #define write_group(port,group,value)\ {\ if(value == HIGH)\ port |= group;\ else if(value == LOW)\ port &= ~group;\ } /***************************************************** * Macro: read_pin(port,pin) * Description: Read input from a pin. * Input: port and pin * Output: value of the pin ******************************************************/ #define read_pin(port,pin)\ (BIT_IS_SET(port,pin))\ #endif /* DIO_H_ */ <file_sep>/* * DC_Motor.c * * Created on: Sep 29, 2019 * Author: Nour * Purpose: contains all DC Motor functions needed in this project */ /******************************************************************************* * Includes * *******************************************************************************/ #include "DC_Motor.h" #include "Port.h" #include "DIO.h" /******************************************************************************* * Function Definitions * *******************************************************************************/ /***************************************************** * Function Prototype: void DC_Motor_init(void) * Description: Initialization DC motor. * Input: None * Output: None * return: void ******************************************************/ void DC_Motor_init(void) { /* set output pins */ set_direction(DC_MOTOR_DIR,IN1,OUT); set_direction(DC_MOTOR_DIR,IN2,OUT); /* set default value of output is low */ write_pin(DC_MOTOR_OUT,IN1,LOW); write_pin(DC_MOTOR_OUT,IN2,LOW); } /***************************************************** * Function Prototype: void DC_Motor_rotate_clockwise(void) * Description: Rotate DC motor clockwise. * Input: None * Output: None * return: void ******************************************************/ void DC_Motor_rotate_clockwise(void) { /* set IN1 low */ write_pin(DC_MOTOR_OUT,IN1,LOW); /* set IN2 high */ write_pin(DC_MOTOR_OUT,IN2,HIGH); } /***************************************************** * Function Prototype: void DC_Motor_rotate_anti_clockwise(void) * Description: Rotate DC motor anti_clockwise. * Input: None * Output: None * return: void ******************************************************/ void DC_Motor_rotate_anti_clockwise(void) { /* set IN1 high */ write_pin(DC_MOTOR_OUT,IN1,HIGH); /* set IN2 low */ write_pin(DC_MOTOR_OUT,IN2,LOW); } /***************************************************** * Function Prototype: void DC_Motor_stop(void) * Description: Stop DC motor. * Input: None * Output: None * return: void ******************************************************/ void DC_Motor_stop(void) { /* set value of output is low */ write_pin(DC_MOTOR_OUT,IN1,LOW); write_pin(DC_MOTOR_OUT,IN2,LOW); } <file_sep>/* * UART_TX.c * * Created on: Sep 26, 2019 * Author: Nour */ #include "UART.h" #include "keypad.h" #include <util\delay.h> int main(void) { uint8 key; UART_ConfigType UART_Config = {Disabled,_1_bit,_8_bit}; UART_init(&UART_Config); while(TRUE) { key = Keypad_getPressedKey(); UART_sendByte(key); _delay_ms(500); } } <file_sep>/* * Test.c * * Created on: Oct 25, 2019 * Author: Nour */ #include "External_Interrupt.h" void App(void) { TOGGLE_BIT(PORTC_R,PC0_B); } int main(void) { SET_BIT(SREG_R,I_B); SET_BIT(DDRC_R,PC0_B); SET_BIT(PORTC_R,PC0_B); Interrupt_ConfigType Interrupt_Config = {interrupt0,rising}; Interrupt_init(&Interrupt_Config); INT0_setCallBack(App); while(TRUE) { } } <file_sep>/* * Timer.h * * Created on: Sep 28, 2019 * Author: Nour * Purpose: contains all timer functions needed in this project */ #ifndef TIMER_H_ #define TIMER_H_ /******************************************************************************* * Includes * *******************************************************************************/ #include "common_macros.h" #include "standard_library.h" #include "AVR_registers.h" #include <avr/interrupt.h> /******************************************************************************* * ENUMS * *******************************************************************************/ typedef enum { Timer0,Timer1,Timer2 }Timer; typedef enum { Overflow,CTC = 2 }Mode; typedef enum { No_clock,No_prescaling,CLK_8,CLK_64,CLK_256,CLK_1024,External_falling,External_rising }Prescalar_Timer0,Prescalar_Timer1; typedef enum { no_clock,no_prescaling,CLK__8,CLK__32,CLK__64,CLK__128,CLK__256,CLK__1024 }Prescalar_Timer2; typedef enum { Normal,Toggle,Clear,Set }Compare_Output_Mode; typedef enum { no_interrupt,interrupt }interrupt_state; typedef enum { Channel_A,Channel_B }Channel; /******************************************************************************* * Structures * *******************************************************************************/ /***************************************************** * Structure Name: Timer_ConfigType * Description: This structure is responsible for dynamic configuration of timer module. ******************************************************/ typedef struct { Timer timer; Mode mode; Prescalar_Timer0 prescalar_Timer0; Prescalar_Timer1 prescalar_Timer1; Prescalar_Timer2 prescalar_Timer2; Compare_Output_Mode COM; uint8 u8_comp_value; uint16 u16_comp_value_A; uint16 u16_comp_value_B; Channel channel; interrupt_state state; }Timer_ConfigType; /******************************************************************************* * Functions Prototypes * *******************************************************************************/ /***************************************************** * Function Prototype: void Timer_init(Timer_ConfigType * Config_Ptr) * Description: Initialization timers. * Input: Timer_ConfigType represents pointer to timer configuration structure * Output: None * return: void ******************************************************/ extern void Timer_init(Timer_ConfigType * Config_Ptr); /***************************************************** * Function Prototype: void Timer0_DeInit(void) * Description: De-initialize timer0. * Input: None * Output: None * return: void ******************************************************/ extern void Timer0_DeInit(void); /***************************************************** * Function Prototype: void Timer1_DeInit(void) * Description: De-initialize timer1. * Input: None * Output: None * return: void ******************************************************/ extern void Timer1_DeInit(void); /***************************************************** * Function Prototype: void Timer2_DeInit(void) * Description: De-initialize timer2. * Input: None * Output: None * return: void ******************************************************/ extern void Timer2_DeInit(void); /***************************************************** * Function Prototype: void Timer0_clearTimerValue(void) * Description: clear timer0 value. * Input: None * Output: None * return: void ******************************************************/ extern void Timer0_clearTimerValue(void); /***************************************************** * Function Prototype: void Timer1_clearTimerValue(void) * Description: clear timer1 value. * Input: None * Output: None * return: void ******************************************************/ extern void Timer1_clearTimerValue(void); /***************************************************** * Function Prototype: void Timer2_clearTimerValue(void) * Description: clear timer2 value. * Input: None * Output: None * return: void ******************************************************/ extern void Timer2_clearTimerValue(void); /***************************************************** * Function Prototype: uint8 Timer0_getTimerValue(void) * Description: get timer0 value. * Input: None * Output: uint8 represents timer0 value * return: uint8 ******************************************************/ extern uint8 Timer0_getTimerValue(void); /***************************************************** * Function Prototype: uint16 Timer1_getTimerValue(void) * Description: get timer1 value. * Input: None * Output: uint16 represents timer1 value * return: uint16 ******************************************************/ extern uint16 Timer1_getTimerValue(void); /***************************************************** * Function Prototype: uint8 Timer2_getTimerValue(void) * Description: get timer2 value. * Input: None * Output: uint8 represents timer2 value * return: uint8 ******************************************************/ extern uint8 Timer2_getTimerValue(void); /***************************************************** * Function Prototype: void Timer0_OVF_setInterrupt(void) * Description: set interrupt for timer0 overflow mode. * Input: None * Output: None * return: void ******************************************************/ extern void Timer0_OVF_setInterrupt(void); /***************************************************** * Function Prototype: void Timer0_COMP_setInterrupt(void) * Description: set interrupt for timer0 CTC mode. * Input: None * Output: None * return: void ******************************************************/ extern void Timer0_COMP_setInterrupt(void); /***************************************************** * Function Prototype: void Timer1_OVF_setInterrupt(void) * Description: set interrupt for timer1 overflow mode. * Input: None * Output: None * return: void ******************************************************/ extern void Timer1_OVF_setInterrupt(void); /***************************************************** * Function Prototype: void Timer1_COMPA_setInterrupt(void) * Description: set interrupt for timer1 CTC mode channelA. * Input: None * Output: None * return: void ******************************************************/ extern void Timer1_COMPA_setInterrupt(void); /***************************************************** * Function Prototype: void Timer1_COMPB_setInterrupt(void) * Description: set interrupt for timer1 CTC mode channelB. * Input: None * Output: None * return: void ******************************************************/ extern void Timer1_COMPB_setInterrupt(void); /***************************************************** * Function Prototype: void Timer2_OVF_setInterrupt(void) * Description: set interrupt for timer2 overflow mode. * Input: None * Output: None * return: void ******************************************************/ extern void Timer2_OVF_setInterrupt(void); /***************************************************** * Function Prototype: void Timer2_COMP_setInterrupt(void) * Description: set interrupt for timer2 CTC mode. * Input: None * Output: None * return: void ******************************************************/ extern void Timer2_COMP_setInterrupt(void); /***************************************************** * Function Prototype: void Timer0_OVF_clearInterrupt(void) * Description: clear interrupt for timer0 overflow mode. * Input: None * Output: None * return: void ******************************************************/ extern void Timer0_OVF_clearInterrupt(void); /***************************************************** * Function Prototype: void Timer0_COMP_clearInterrupt(void) * Description: clear interrupt for timer0 CTC mode. * Input: None * Output: None * return: void ******************************************************/ extern void Timer0_COMP_clearInterrupt(void); /***************************************************** * Function Prototype: void Timer1_OVF_clearInterrupt(void) * Description: clear interrupt for timer1 overflow mode. * Input: None * Output: None * return: void ******************************************************/ extern void Timer1_OVF_clearInterrupt(void); /***************************************************** * Function Prototype: void Timer1_COMPA_clearInterrupt(void) * Description: clear interrupt for timer1 CTC mode channelA. * Input: None * Output: None * return: void ******************************************************/ extern void Timer1_COMPA_clearInterrupt(void); /***************************************************** * Function Prototype: void Timer1_COMPB_clearInterrupt(void) * Description: clear interrupt for timer1 CTC mode channelB. * Input: None * Output: None * return: void ******************************************************/ extern void Timer1_COMPB_clearInterrupt(void); /***************************************************** * Function Prototype: void Timer2_OVF_clearInterrupt(void) * Description: clear interrupt for timer2 overflow mode. * Input: None * Output: None * return: void ******************************************************/ extern void Timer2_OVF_clearInterrupt(void); /***************************************************** * Function Prototype: void Timer2_COMP_clearInterrupt(void) * Description: clear interrupt for timer2 CTC mode. * Input: None * Output: None * return: void ******************************************************/ extern void Timer2_COMP_clearInterrupt(void); /***************************************************** * Function Prototype: void Timer0_OVF_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer0 overflow interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ extern void Timer0_OVF_setCallBack(void(*a_ptr)(void)); /***************************************************** * Function Prototype: void Timer0_COMP_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer0 CTC interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ extern void Timer0_COMP_setCallBack(void(*a_ptr)(void)); /***************************************************** * Function Prototype: void Timer1_OVF_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer1 overflow interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ extern void Timer1_OVF_setCallBack(void(*a_ptr)(void)); /***************************************************** * Function Prototype: void Timer1_COMPA_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer1 channelA CTC interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ extern void Timer1_COMPA_setCallBack(void(*a_ptr)(void)); /***************************************************** * Function Prototype: void Timer1_COMPB_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer1 channelB CTC interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ extern void Timer1_COMPB_setCallBack(void(*a_ptr)(void)); /***************************************************** * Function Prototype: void Timer2_OVF_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer2 overflow interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ extern void Timer2_OVF_setCallBack(void(*a_ptr)(void)); /***************************************************** * Function Prototype: void Timer2_COMP_setCallBack(void(*a_ptr)(void)) * Description: call back function when timer2 CTC interrupt is initiated. * Input: void(*a_ptr)(void) refers to function called by the call-back function in upper layer * Output: None * return: void ******************************************************/ extern void Timer2_COMP_setCallBack(void(*a_ptr)(void)); #endif /* TIMER_H_ */ <file_sep>/* * potentiometer.c * Created on: Sep 23, 2019 * Author: <NAME> */ #include "adc.h" #include "lcd.h" int main(void) { SET_BIT(SREG_R,I_B); /* Create configuration structure for ADC driver */ ADC_ConfigType ADC_Config = {AREF,_8,Interrupt}; /* initialize LCD driver */ LCD_init(); /* initialize ADC driver */ ADC_init(&ADC_Config); /* clear LCD at the beginning */ LCD_clearScreen(); /* display this string "ADC Value = " only once at LCD */ LCD_displayString("ADC Value = "); while(TRUE) { /* display the number every time at this position */ LCD_goToRowColumn(0,12); /* read channel zero where the potentiometer is connect */ ADC_readChannel(0,&ADC_Config); /* display the ADC value on LCD screen */ LCD_intgerToString(g_ADC_value); } } <file_sep>/* * EEPROM_external.c * * Created on: Oct 6, 2019 * Author: Nour */ #include "EEPROM_external.h" #include "TWI.h" void EEPROM_external_init(void) { TWI_init(); } uint8 EEPROM_external_write_byte(uint16 u16addr,uint8 u8data) { TWI_start(); if (TWI_get_status() != TW_START) return ERROR; /* Send the device address, we need to get A8 A9 A10 address bits from the * memory location address and R/W=0 (write) */ TWI_write((uint8)(0xA0 | ((u16addr & 0x0700) >> 7))); if (TWI_get_status() != TW_MT_SLA_W_ACK) return ERROR; /* Send the required memory location address */ TWI_write((uint8)(u16addr)); if (TWI_get_status() != TW_MT_DATA_ACK) return ERROR; /* write byte to EEPROM */ TWI_write(u8data); if (TWI_get_status() != TW_MT_DATA_ACK) return ERROR; /* Send the Stop Bit */ TWI_stop(); return SUCCESS; } uint8 EEPROM_external_read_byte(uint16 u16addr,uint8 * u8data) { /* Send the Start Bit */ TWI_start(); if (TWI_get_status() != TW_START) return ERROR; /* Send the device address, we need to get A8 A9 A10 address bits from the * memory location address and R/W=0 (write) */ TWI_write((uint8)((0xA0) | ((u16addr & 0x0700)>>7))); if (TWI_get_status() != TW_MT_SLA_W_ACK) return ERROR; /* Send the required memory location address */ TWI_write((uint8)(u16addr)); if (TWI_get_status() != TW_MT_DATA_ACK) return ERROR; /* Send the Repeated Start Bit */ TWI_start(); if (TWI_get_status() != TW_REP_START) return ERROR; /* Send the device address, we need to get A8 A9 A10 address bits from the * memory location address and R/W=1 (Read) */ TWI_write((uint8)((0xA0) | ((u16addr & 0x0700)>>7) | 1)); if (TWI_get_status() != TW_MT_SLA_R_ACK) return ERROR; /* Read Byte from Memory without send ACK */ *u8data = TWI_read_with_NACK(); if (TWI_get_status() != TW_MR_DATA_NACK) return ERROR; /* Send the Stop Bit */ TWI_stop(); return SUCCESS; } <file_sep>/* * SPI.c * * Created on: Sep 25, 2019 * Author: Nour */ #include "SPI.h" void SPI_initMaster(const SPI_ConfigType * Config_Ptr) { /* SS output */ SET_BIT(DDRB_R,PB4_B); /* MOSI output and MISO input */ SET_BIT(DDRB_R,PB5_B); CLEAR_BIT(DDRB_R,PB6_B); /* SCK output */ SET_BIT(DDRB_R,PB7_B); /* * Enable SPI * Enable Master * Set SPI frequency */ SPCR_R = (1 << SPE_B) | (1 << MSTR_B) | (Config_Ptr -> frequency << SPR0_B); } void SPI_initSlave(const SPI_ConfigType * Config_Ptr) { /* SS input */ CLEAR_BIT(DDRB_R,PB4_B); /* MOSI input and MISO output */ CLEAR_BIT(DDRB_R,PB5_B); SET_BIT(DDRB_R,PB6_B); /* SCK input */ CLEAR_BIT(DDRB_R,PB7_B); /* * Enable SPI * Enable Master * Set SPI frequency */ SPCR_R = (1 << SPE_B) | (Config_Ptr -> frequency << SPR0_B); } void SPI_sendByte(uint8 byte) { SPDR_R = byte; while(BIT_IS_CLEAR(SPSR_R,SPIF_B)); } void SPI_sendString(const uint8 * Str_Ptr) { uint8 i = 0; while (Str_Ptr[i] != '\0') { SPI_sendByte(Str_Ptr[i]); i++; } } uint8 SPI_recieveByte(void) { while(BIT_IS_CLEAR(SPSR_R,SPIF_B)); return SPDR_R; } void SPI_recieveString(uint8 * Str_Ptr) { uint8 i = 0; Str_Ptr[i] = SPI_recieveByte(); do { i++; Str_Ptr[i] = SPI_recieveByte(); } while(Str_Ptr[i] != '#'); Str_Ptr[i] = '\0'; } <file_sep>/* * main.c * * Created on: Sep 17, 2019 * Author: Nour */ #include "LCD.h" int main(void) { SET_BIT(DDRA_R,PA0_B); LCD_init(); /* initialize LCD */ LCD_displayCharacter('A'); // LCD_displayStringRowColumn(0,2,"My LCD Driver"); // LCD_displayStringRowColumn(1,3,"Embedded WS"); // _delay_ms(4000); /* wait four seconds */ // // LCD_clearScreen(); /* clear the LCD display */ // LCD_displayString("Interf. Course"); // LCD_displayStringRowColumn(1,5,"Group "); // LCD_intgerToString(40); while(TRUE) { SET_BIT(PORTA_R,PA0_B); } } <file_sep>/* * Buttons.c * * Created on: Mar 21, 2020 * Author: Nour * Purpose: contains all buttons functions needed in this project */ /******************************************************************************* * Includes * *******************************************************************************/ #include "Buttons.h" #include "Port.h" #include "DIO.h" #include "External_Interrupt.h" #include "LCD.h" /******************************************************************************* * Global Variables * *******************************************************************************/ volatile uint8 weight_sensor_flag = LOW; volatile uint8 door_sensor_flag = LOW; volatile uint8 cancel_button_flag = LOW; /******************************************************************************* * Private Functions Prototypes * *******************************************************************************/ /***************************************************** * Function Prototype: void weight_sensor_API(void) * Description: Function called when external interrupt corresponding to weight sensor initiated. * Input: None * Output: None * return: void ******************************************************/ static void weight_sensor_API(void); /***************************************************** * Function Prototype: void door_sensor_API(void) * Description: Function called when external interrupt corresponding to door sensor initiated. * Input: None * Output: None * return: void ******************************************************/ static void door_sensor_API(void); /***************************************************** * Function Prototype: void cancel_button_API(void) * Description: Function called when external interrupt corresponding to cancel button initiated. * Input: None * Output: None * return: void ******************************************************/ static void cancel_button_API(void); /******************************************************************************* * Function Definitions * *******************************************************************************/ /***************************************************** * Function Prototype: void buttons_init(void) * Description: Initialization buttons. * Input: None * Output: None * return: void ******************************************************/ void buttons_init(void) { /* initialize start button as input */ set_direction(START_BUTTON_DIR,START_BUTTON,IN); /* set interrupt configuration structures */ Interrupt_ConfigType weight_sensor = {interrupt0,rising}; Interrupt_ConfigType door_sensor = {interrupt1,rising}; Interrupt_ConfigType cancel_button = {interrupt2,rising}; /* initialize the interrupts */ Interrupt_init(&weight_sensor); Interrupt_init(&door_sensor); Interrupt_init(&cancel_button); /* set call back functions for external interrupts */ INT0_setCallBack(weight_sensor_API); INT1_setCallBack(door_sensor_API); INT2_setCallBack(cancel_button_API); } /***************************************************** * Function Prototype: void weight_sensor_API(void) * Description: Function called when external interrupt corresponding to weight sensor initiated. * Input: None * Output: None * return: void ******************************************************/ static void weight_sensor_API(void) { /* raise weight sensor flag */ weight_sensor_flag = HIGH; } /***************************************************** * Function Prototype: void door_sensor_API(void) * Description: Function called when external interrupt corresponding to door sensor initiated. * Input: None * Output: None * return: void ******************************************************/ static void door_sensor_API(void) { /* raise door sensor flag */ door_sensor_flag = HIGH; } /***************************************************** * Function Prototype: void cancel_button_API(void) * Description: Function called when external interrupt corresponding to cancel button initiated. * Input: None * Output: None * return: void ******************************************************/ static void cancel_button_API(void) { /* raise cancel button flag */ cancel_button_flag = HIGH; } <file_sep>/* * keypad.h * * Created on: Sep 16, 2019 * Author: Nour * Purpose: contains all keypad functions needed in this project */ #ifndef KEYPAD_H_ #define KEYPAD_H_ /******************************************************************************* * Includes * *******************************************************************************/ #include "standard_library.h" #include "AVR_registers.h" /******************************************************************************* * Preprocessor Defines * *******************************************************************************/ #define NO_OF_ROWS 4 #define NO_OF_COLUMNS 4 #define KEYPAD_DIR DDRA_R #define KEYPAD_OUT PORTA_R #define KEYPAD_IN PINA_R /******************************************************************************* * Functions Prototypes * *******************************************************************************/ /***************************************************** * Function Prototype: uint8 Keypad_getPressedKey(void) * Description: Get the value of keypad pressed button. * Input: None * Output: uint8 refers to keypad input number * return: uint8 ******************************************************/ extern uint8 Keypad_getPressedKey(void); #endif /* KEYPAD_H_ */ <file_sep>/* * LCD.c * * Created on: Sep 16, 2019 * Author: Nour * Purpose: contains all LCD functions needed in this project */ /******************************************************************************* * Includes * *******************************************************************************/ #include "LCD.h" #include "Port.h" #include "DIO.h" #include <util/delay.h> /******************************************************************************* * Function Definitions * *******************************************************************************/ /***************************************************** * Function Prototype: void LCD_init(void) * Description: Initialization LCD. * Input: None * Output: None * return: void ******************************************************/ void LCD_init(void) { #ifdef TWO_LINE_LCD_8_BIT_MODE set_direction_port(LCD_DATA_DIR,OUT); /* 8 bit mode */ #endif #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef FIRST_4_PINS set_direction_group(LCD_DATA_DIR,FIRST_FOUR_PINS,OUT); #endif #endif #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef SECOND_4_PINS set_direction_group(LCD_DATA_DIR,SECOND_FOUR_PINS,OUT); #endif #endif /* set RS corresponding pin as output */ set_direction(LCD_CTRL_DIR,RS,OUT); /* set RW corresponding pin as output */ set_direction(LCD_CTRL_DIR,RW,OUT); /* set E corresponding pin as output */ set_direction(LCD_CTRL_DIR,E,OUT); #ifdef TWO_LINE_LCD_4_BIT_MODE /* initialize LCD in 4-bit mode */ LCD_sendCommand(FOUR_BITS_DATA_MODE); /* use 2-line lcd + 4-bit Data Mode + 5*7 dot display Mode */ LCD_sendCommand(TWO_LINE_LCD_Four_BIT_MODE); #endif #ifdef TWO_LINE_LCD_8_BIT_MODE /* use 2-line lcd + 8-bit Data Mode + 5*7 dot display Mode */ LCD_sendCommand(TWO_LINE_LCD_Eight_BIT_MODE); #endif /* cursor off */ LCD_sendCommand(CURSOR_OFF); /* clear LCD at the beginning */ LCD_sendCommand(CLEAR_COMMAND); } /***************************************************** * Function Prototype: void LCD_sendCommand(uint8 cmd) * Description: Send command. * Input: uint8 refers to command * Output: None * return: void ******************************************************/ void LCD_sendCommand(uint8 cmd) { /* Instruction Mode RS=0 */ write_pin(LCD_CTRL_OUT,RS,LOW); /* write data to LCD so RW=0 */ write_pin(LCD_CTRL_OUT,RW,LOW); /* delay for processing Tas = 50ns */ _delay_ms(1); /* Enable LCD E=1 */ write_pin(LCD_CTRL_OUT,E,HIGH); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef FIRST_4_PINS LCD_DATA_OUT = (LCD_DATA_OUT & ~FIRST_FOUR_PINS) | ((cmd & ~FIRST_FOUR_PINS) >> 4); /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ write_pin(LCD_CTRL_OUT,E,LOW); /* delay for processing Th = 13ns */ _delay_ms(1); /* Enable LCD E=1 */ write_pin(LCD_CTRL_OUT,E,HIGH); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); LCD_DATA_OUT = (LCD_DATA_OUT & ~FIRST_FOUR_PINS) | (cmd & FIRST_FOUR_PINS); #endif #endif #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef SECOND_4_PINS LCD_DATA_OUT = (LCD_DATA_OUT & ~SECOND_FOUR_PINS) | ((cmd & SECOND_FOUR_PINS) >> 4); /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ write_pin(LCD_CTRL_OUT,E,LOW); /* delay for processing Th = 13ns */ _delay_ms(1); /* Enable LCD E=1 */ write_pin(LCD_CTRL_OUT,E,HIGH); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); LCD_DATA_OUT = (LCD_DATA_OUT & ~SECOND_FOUR_PINS) | ((cmd & ~SECOND_FOUR_PINS) << 4); #endif #endif #ifdef TWO_LINE_LCD_8_BIT_MODE /* out the required command to the data bus D0 --> D7 */ write_port(LCD_DATA_OUT,cmd); #endif /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ write_pin(LCD_CTRL_OUT,E,LOW); /* delay for processing Th = 13ns */ _delay_ms(1); } /***************************************************** * Function Prototype: void LCD_displayCharacter(uint8 data) * Description: Display character. * Input: uint8 refers to data * Output: None * return: void ******************************************************/ void LCD_displayCharacter(uint8 data) { /* Instruction Mode RS=1 */ write_pin(LCD_CTRL_OUT,RS,HIGH); /* write data to LCD so RW=0 */ write_pin(LCD_CTRL_OUT,RW,LOW); /* delay for processing Tas = 50ns */ _delay_ms(1); /* Enable LCD E=1 */ write_pin(LCD_CTRL_OUT,E,HIGH); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef FIRST_4_PINS LCD_DATA_OUT = (LCD_DATA_OUT & ~FIRST_FOUR_PINS) | ((data & ~FIRST_FOUR_PINS) >> 4); /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ write_pin(LCD_CTRL_OUT,E,LOW); /* delay for processing Th = 13ns */ _delay_ms(1); /* Enable LCD E=1 */ write_pin(LCD_CTRL_OUT,E,HIGH); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); LCD_DATA_OUT = (LCD_DATA_OUT & ~FIRST_FOUR_PINS) | (data & FIRST_FOUR_PINS); #endif #endif #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef SECOND_4_PINS LCD_DATA_OUT = (LCD_DATA_OUT & ~SECOND_FOUR_PINS) | ((data & SECOND_FOUR_PINS) >> 4); /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ write_pin(LCD_CTRL_OUT,E,LOW); /* delay for processing Th = 13ns */ _delay_ms(1); /* Enable LCD E=1 */ write_pin(LCD_CTRL_OUT,E,HIGH); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); LCD_DATA_OUT = (LCD_DATA_OUT & ~SECOND_FOUR_PINS) | ((cmd & ~SECOND_FOUR_PINS) << 4); #endif #endif #ifdef TWO_LINE_LCD_8_BIT_MODE /* out the required command to the data bus D0 --> D7 */ write_port(LCD_DATA_OUT,data); #endif /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ write_pin(LCD_CTRL_OUT,E,LOW); /* delay for processing Th = 13ns */ _delay_ms(1); } /***************************************************** * Function Prototype: void LCD_displayString(const uint8 *str) * Description: Display string. * Input: uint8* refers to string * Output: None * return: void ******************************************************/ void LCD_displayString(const uint8 *str) { uint8 i = 0; /* loop to the end of the string */ while(str[i] != '\0') { LCD_displayCharacter(str[i]); i++; } } /***************************************************** * Function Prototype: void LCD_displayStringRowColumn(uint8 row,uint8 col,const uint8 *str) * Description: Display string at certain row and column. * Input: uint8* refers to string,uint8 refers to row and uint8 refers to column * Output: None * return: void ******************************************************/ void LCD_displayStringRowColumn(uint8 row,uint8 col,const uint8 *str) { /* go to to the required LCD position */ LCD_goToRowColumn(row,col); /* display the string */ LCD_displayString(str); } /***************************************************** * Function Prototype: void LCD_goToRowColumn(uint8 row,uint8 col) * Description: Go to a certain row and column. * Input: uint8 refers to row and uint8 refers to column * Output: None * return: void ******************************************************/ void LCD_goToRowColumn(uint8 row,uint8 col) { uint8 Address; /* first of all calculate the required address */ switch(row) { case 0: Address=col; break; case 1: Address=col+0x40; break; } /* * to write to a specific address in the LCD * we need to apply the corresponding command 0b10000000+Address */ LCD_sendCommand(Address | SET_CURSOR_LOCATION); } /***************************************************** * Function Prototype: void LCD_intgerToString(uint8 data) * Description: Converts integer data to string. * Input: uint8 refers to data * Output: None * return: void ******************************************************/ void LCD_intgerToString(uint8 data) { /* String to hold the ascii result */ uint8 buff[16]; /* 10 for decimal */ itoa(data,buff,10); /* display converted decimal */ LCD_displayString(buff); } /***************************************************** * Function Prototype: void LCD_clearScreen(void) * Description: Clear LCD screen. * Input: None * Output: None * return: void ******************************************************/ void LCD_clearScreen(void) { /* send clear command */ LCD_sendCommand(CLEAR_COMMAND); } <file_sep>/* * EEPROM_external.h * * Created on: Oct 6, 2019 * Author: Nour */ #ifndef EEPROM_EXTERNAL_H_ #define EEPROM_EXTERNAL_H_ #include "standard_library.h" #define ERROR 0 #define SUCCESS 1 extern void EEPROM_external_init(void); extern uint8 EEPROM_external_write_byte(uint16 u16addr,uint8 u8data); extern uint8 EEPROM_external_read_byte(uint16 u16addr,uint8 * u8data); #endif /* EEPROM_EXTERNAL_H_ */ <file_sep>/* * LCD.c * * Created on: Sep 16, 2019 * Author: Nour */ #include "LCD.h" void LCD_init(void) { #ifdef TWO_LINE_LCD_8_BIT_MODE LCD_DATA_DIR = 0xFF; /* 8 bit mode */ #endif #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef FIRST_4_PINS LCD_DATA_DIR = FIRST_FOUR_PINS; #endif #endif #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef SECOND_4_PINS LCD_DATA_DIR = SECOND_FOUR_PINS; #endif #endif SET_BIT(LCD_CTRL_DIR,RS); SET_BIT(LCD_CTRL_DIR,RW); SET_BIT(LCD_CTRL_DIR,E); #ifdef TWO_LINE_LCD_4_BIT_MODE /* initialize LCD in 4-bit mode */ LCD_sendCommand(FOUR_BITS_DATA_MODE); /* use 2-line lcd + 4-bit Data Mode + 5*7 dot display Mode */ LCD_sendCommand(TWO_LINE_LCD_Four_BIT_MODE); #endif #ifdef TWO_LINE_LCD_8_BIT_MODE /* use 2-line lcd + 8-bit Data Mode + 5*7 dot display Mode */ LCD_sendCommand(TWO_LINE_LCD_Eight_BIT_MODE); #endif /* cursor off */ LCD_sendCommand(CURSOR_OFF); /* clear LCD at the beginning */ LCD_sendCommand(CLEAR_COMMAND); } void LCD_sendCommand(uint8 cmd) { /* Instruction Mode RS=0 */ CLEAR_BIT(LCD_CTRL_OUT,RS); /* write data to LCD so RW=0 */ CLEAR_BIT(LCD_CTRL_OUT,RW); /* delay for processing Tas = 50ns */ _delay_ms(1); /* Enable LCD E=1 */ SET_BIT(LCD_CTRL_OUT,E); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef FIRST_4_PINS LCD_DATA_OUT = (LCD_DATA_OUT & ~FIRST_FOUR_PINS) | ((cmd & ~FIRST_FOUR_PINS) >> 4); /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ CLEAR_BIT(LCD_CTRL_OUT,E); /* delay for processing Th = 13ns */ _delay_ms(1); /* Enable LCD E=1 */ SET_BIT(LCD_CTRL_OUT,E); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); LCD_DATA_OUT = (LCD_DATA_OUT & ~FIRST_FOUR_PINS) | (cmd & FIRST_FOUR_PINS); #endif #endif #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef SECOND_4_PINS LCD_DATA_OUT = (LCD_DATA_OUT & ~SECOND_FOUR_PINS) | ((cmd & SECOND_FOUR_PINS) >> 4); /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ CLEAR_BIT(LCD_CTRL_OUT,E); /* delay for processing Th = 13ns */ _delay_ms(1); /* Enable LCD E=1 */ SET_BIT(LCD_CTRL_OUT,E); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); LCD_DATA_OUT = (LCD_DATA_OUT & ~SECOND_FOUR_PINS) | ((cmd & ~SECOND_FOUR_PINS) << 4); #endif #endif #ifdef TWO_LINE_LCD_8_BIT_MODE /* out the required command to the data bus D0 --> D7 */ LCD_DATA_OUT = cmd; #endif /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ CLEAR_BIT(LCD_CTRL_OUT,E); /* delay for processing Th = 13ns */ _delay_ms(1); } void LCD_displayCharacter(uint8 data) { /* Instruction Mode RS=1 */ SET_BIT(LCD_CTRL_OUT,RS); /* write data to LCD so RW=0 */ CLEAR_BIT(LCD_CTRL_OUT,RW); /* delay for processing Tas = 50ns */ _delay_ms(1); /* Enable LCD E=1 */ SET_BIT(LCD_CTRL_OUT,E); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef FIRST_4_PINS LCD_DATA_OUT = (LCD_DATA_OUT & ~FIRST_FOUR_PINS) | ((data & ~FIRST_FOUR_PINS) >> 4); /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ CLEAR_BIT(LCD_CTRL_OUT,E); /* delay for processing Th = 13ns */ _delay_ms(1); /* Enable LCD E=1 */ SET_BIT(LCD_CTRL_OUT,E); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); LCD_DATA_OUT = (LCD_DATA_OUT & ~FIRST_FOUR_PINS) | (data & FIRST_FOUR_PINS); #endif #endif #ifdef TWO_LINE_LCD_4_BIT_MODE #ifdef SECOND_4_PINS LCD_DATA_OUT = (LCD_DATA_OUT & ~SECOND_FOUR_PINS) | ((data & SECOND_FOUR_PINS) >> 4); /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ CLEAR_BIT(LCD_CTRL_OUT,E); /* delay for processing Th = 13ns */ _delay_ms(1); /* Enable LCD E=1 */ SET_BIT(LCD_CTRL_OUT,E); /* delay for processing Tpw - Tdws = 190ns */ _delay_ms(1); LCD_DATA_OUT = (LCD_DATA_OUT & ~SECOND_FOUR_PINS) | ((cmd & ~SECOND_FOUR_PINS) << 4); #endif #endif #ifdef TWO_LINE_LCD_8_BIT_MODE /* out the required command to the data bus D0 --> D7 */ LCD_DATA_OUT = data; #endif /* delay for processing Tdsw = 100ns */ _delay_ms(1); /* disable LCD E=0 */ CLEAR_BIT(LCD_CTRL_OUT,E); /* delay for processing Th = 13ns */ _delay_ms(1); } void LCD_displayString(const uint8 *str) { uint8 i = 0; while(str[i] != '\0') { LCD_displayCharacter(str[i]); i++; } } void LCD_displayStringRowColumn(uint8 row,uint8 col,const uint8 *str) { /* go to to the required LCD position */ LCD_goToRowColumn(row,col); /* display the string */ LCD_displayString(str); } void LCD_goToRowColumn(uint8 row,uint8 col) { uint8 Address; /* first of all calculate the required address */ switch(row) { case 0: Address=col; break; case 1: Address=col+0x40; break; } /* to write to a specific address in the LCD * we need to apply the corresponding command 0b10000000+Address */ LCD_sendCommand(Address | SET_CURSOR_LOCATION); } void LCD_intgerToString(uint8 data) { uint8 buff[16]; /* String to hold the ascii result */ itoa(data,buff,10); /* 10 for decimal */ LCD_displayString(buff); } void LCD_clearScreen(void) { LCD_sendCommand(CLEAR_COMMAND); //clear display } <file_sep>/* * Port.h * * Created on: Mar 20, 2020 * Author: Nour * Purpose: contains all port functions needed in this project */ #ifndef PORT_H_ #define PORT_H_ /******************************************************************************* * Includes * *******************************************************************************/ #include "common_macros.h" #include "standard_library.h" #include "AVR_registers.h" /******************************************************************************* * Preprocessor Defines * *******************************************************************************/ #define FIRST_FOUR_PINS 0x0F #define SECOND_FOUR_PINS 0xF0 /******************************************************************************* * Functions-Like Macros * *******************************************************************************/ /***************************************************** * Macro: set_direction(port,pin,direction) * Description: set the direction of a pin. * Input: port, pin and direction: output or input * Output: None ******************************************************/ #define set_direction(port,pin,direction)\ {\ if(direction == OUT)\ SET_BIT(port,pin);\ else if(direction == IN)\ CLEAR_BIT(port,pin);\ } /***************************************************** * Macro: set_direction_group(port,group,direction) * Description: set the direction of a group. * Input: port, group and direction: output or input * Output: None ******************************************************/ #define set_direction_group(port,group,direction)\ {\ if(direction == OUT)\ port |= group;\ else if(direction == IN)\ port &= ~group;\ } /***************************************************** * Macro: set_direction_port(port,direction) * Description: set the direction of a port. * Input: port and direction: output or input * Output: None ******************************************************/ #define set_direction_port(port,direction)\ {\ if(direction == OUT)\ port = 0xFF;\ else if(direction == IN)\ port = 0;\ } #endif /* PORT_H_ */ <file_sep>/* * Timer.c * * Created on: Sep 28, 2019 * Author: Nour */ #include "Timer.h" /* Global variables to hold the address of the call back function in the application */ static volatile void (*g_Timer0_OVF_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer0_COMP_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer2_OVF_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer2_COMP_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer1_OVF_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer1_COMPA_callBackPtr)(void) = NULL_PTR; static volatile void (*g_Timer1_COMPB_callBackPtr)(void) = NULL_PTR; ISR(TIMER0_OVF_vect) { if(g_Timer0_OVF_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer0_OVF_callBackPtr)(); } } ISR(TIMER0_COMP_vect) { if(g_Timer0_COMP_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer0_COMP_callBackPtr)(); } } ISR(TIMER2_OVF_vect) { if(g_Timer2_OVF_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer2_OVF_callBackPtr)(); } } ISR(TIMER2_COMP_vect) { if(g_Timer2_COMP_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer2_COMP_callBackPtr)(); } } ISR(TIMER1_OVF_vect) { if(g_Timer1_OVF_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer1_OVF_callBackPtr)(); } } ISR(TIMER1_COMPA_vect) { if(g_Timer1_COMPA_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer1_COMPA_callBackPtr)(); } } ISR(TIMER1_COMPB_vect) { if(g_Timer1_COMPB_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_Timer1_COMPB_callBackPtr)(); } } void Timer0_OVF_setCallBack(void(*a_ptr)(void)) { g_Timer0_OVF_callBackPtr = a_ptr; } void Timer0_COMP_setCallBack(void(*a_ptr)(void)) { g_Timer0_COMP_callBackPtr = a_ptr; } void Timer2_OVF_setCallBack(void(*a_ptr)(void)) { g_Timer2_OVF_callBackPtr = a_ptr; } void Timer2_COMP_setCallBack(void(*a_ptr)(void)) { g_Timer2_COMP_callBackPtr = a_ptr; } void Timer1_OVF_setCallBack(void(*a_ptr)(void)) { g_Timer1_OVF_callBackPtr = a_ptr; } void Timer1_COMPA_setCallBack(void(*a_ptr)(void)) { g_Timer1_COMPA_callBackPtr = a_ptr; } void Timer1_COMPB_setCallBack(void(*a_ptr)(void)) { g_Timer1_COMPB_callBackPtr = a_ptr; } void Timer_init(Timer_ConfigType * Config_Ptr) { if(Config_Ptr -> timer == Timer0) { /* Timer initial value */ TCNT0_R = 0; /* In case of overflow or CTC mode */ /* Note: WGM00 and WGM01 are not followed in registers arrangement */ TCCR0_R = (1 << FOC0_B) | ((Config_Ptr -> mode & 0x1) << WGM00_B) | (((Config_Ptr -> mode & 0x2) >> 1) << WGM01_B) | (Config_Ptr -> prescalar_Timer0 << CS00_B); if(Config_Ptr -> mode == Overflow) { /* Enable Timer0 overflow interrupt */ SET_BIT(TIMSK_R,TOIE0_B); } else if(Config_Ptr -> mode == CTC) { /* Compare value */ OCR0_R = Config_Ptr -> u8_comp_value; /* Check if we are not producing a square wave on OCO pin */ if(Config_Ptr -> COM == Normal) { /* Enable Timer0 CTC interrupt */ SET_BIT(TIMSK_R,OCIE0_B); } else { TCCR0_R = (1 << FOC0_B) | ((Config_Ptr -> mode & 0x1) << WGM00_B) | (((Config_Ptr -> mode & 0x2) >> 1) << WGM01_B) | (Config_Ptr -> prescalar_Timer0 << CS00_B) | (Config_Ptr -> COM << COM00_B); /* Set OC0 as output pin */ SET_BIT(DDRB_R,PB3_B); } } } else if(Config_Ptr -> timer == Timer2) { /* Timer initial value */ TCNT2_R = 0; /* In case of overflow or CTC mode */ /* Note: WGM20 and WGM21 are not followed in registers arrangement */ TCCR2_R = (1 << FOC2_B) | ((Config_Ptr -> mode & 0x1) << WGM20_B) | (((Config_Ptr -> mode & 0x2) >> 1) << WGM21_B) | (Config_Ptr -> prescalar_Timer2 << CS20_B); if(Config_Ptr -> mode == Overflow) { /* Enable Timer2 overflow interrupt */ SET_BIT(TIMSK_R,TOIE2_B); } else if(Config_Ptr -> mode == CTC) { /* Compare value */ OCR2_R = Config_Ptr -> u8_comp_value; /* Check if we are not producing a square wave on OC2 pin */ if(Config_Ptr -> COM == Normal) { /* Enable Timer2 CTC interrupt */ SET_BIT(TIMSK_R,OCIE2_B); } else { TCCR2_R = (1 << FOC2_B) | ((Config_Ptr -> mode & 0x1) << WGM20_B) | (((Config_Ptr -> mode & 0x2) >> 1) << WGM21_B) | (Config_Ptr -> prescalar_Timer2 << CS20_B) | (Config_Ptr -> COM << COM20_B); /* Set OC2 as output pin */ SET_BIT(DDRD_R,PD7_B); } } } else if(Config_Ptr -> timer == Timer1) { /* Timer initial value */ TCNT1_R = 0; /* In case of overflow or CTC mode */ TCCR1A_R = (1 << FOC1A_B) | (1 << FOC1B_B); TCCR1B_R = (Config_Ptr -> prescalar_Timer1 << CS10_B) | ((Config_Ptr -> mode >> 1) << WGM12_B); if(Config_Ptr -> mode == Overflow) { SET_BIT(TIMSK_R,TOIE1_B); } /* We have two channels Channel A and Channel B */ else if(Config_Ptr -> mode == CTC) { if(Config_Ptr -> channel == Channel_A) { /* Compare value */ OCR1A_R = Config_Ptr -> u16_comp_value_A; /* Check if we are not producing a square wave on OC1A pin */ if(Config_Ptr -> COM == Normal) { /* Enable Timer1_A CTC interrupt */ SET_BIT(TIMSK_R,OCIE1A_B); } else { TCCR1A_R = (1 << FOC1A_B) | (1 << FOC1B_B) | (Config_Ptr -> COM << COM1A0_B); /* Set OC1A as output pin */ SET_BIT(DDRD_R,PD5_B); } } else if(Config_Ptr -> channel == Channel_B) { /* Compare value */ OCR1B_R = Config_Ptr -> u16_comp_value_B; /* Check if we are not producing a square wave on OC1B pin */ if(Config_Ptr -> COM == Normal) { /* Enable Timer1_B CTC interrupt */ SET_BIT(TIMSK_R,OCIE1B_B); } else { TCCR1A_R = (1 << FOC1A_B) | (1 << FOC1B_B) | (Config_Ptr -> COM << COM1B0_B); /* Set OC1B as output pin */ SET_BIT(DDRD_R,PD4_B); } } } } } <file_sep>/* * SPI_RX.c * * Created on: Sep 26, 2019 * Author: Nour */ #include "SPI.h" #include "LCD.h" int main(void) { uint8 Byte; SPI_ConfigType SPI_Config = {_4}; SPI_initSlave(&SPI_Config); LCD_init(); while(TRUE) { Byte = SPI_recieveByte(); //receive the pressed key from spi if((Byte >= 0) && (Byte <= 9)) { LCD_intgerToString(Byte); //display the pressed key } else { LCD_displayCharacter(Byte); } } } <file_sep>/* * DC_Motor.h * * Created on: Sep 29, 2019 * Author: Nour * Purpose: contains all DC Motor functions needed in this project */ #ifndef DC_MOTOR_H_ #define DC_MOTOR_H_ /******************************************************************************* * Includes * *******************************************************************************/ #include "standard_library.h" /******************************************************************************* * Preprocessor Defines * *******************************************************************************/ #define DC_MOTOR_DIR DDRD_R #define DC_MOTOR_OUT PORTD_R #define IN1 PD0_B #define IN2 PD1_B /******************************************************************************* * Functions Prototypes * *******************************************************************************/ /***************************************************** * Function Prototype: void DC_Motor_init(void) * Description: Initialization DC motor. * Input: None * Output: None * return: void ******************************************************/ extern void DC_Motor_init(void); /***************************************************** * Function Prototype: void DC_Motor_rotate_clockwise(void) * Description: Rotate DC motor clockwise. * Input: None * Output: None * return: void ******************************************************/ extern void DC_Motor_rotate_clockwise(void); /***************************************************** * Function Prototype: void DC_Motor_rotate_anti_clockwise(void) * Description: Rotate DC motor anti_clockwise. * Input: None * Output: None * return: void ******************************************************/ extern void DC_Motor_rotate_anti_clockwise(void); /***************************************************** * Function Prototype: void DC_Motor_stop(void) * Description: Stop DC motor. * Input: None * Output: None * return: void ******************************************************/ extern void DC_Motor_stop(void); #endif /* DC_MOTOR_H_ */ <file_sep>/* * SPI_TX.c * * Created on: Sep 26, 2019 * Author: Nour */ #include "SPI.h" #include "keypad.h" #include <util\delay.h> int main(void) { uint8 key; SPI_ConfigType SPI_Config = {_4}; SPI_initMaster(&SPI_Config); while(TRUE) { key = Keypad_getPressedKey(); SPI_sendByte(key); _delay_ms(500); } } <file_sep>/* * External_Interrupt.c * * Created on: Oct 24, 2019 * Author: Nour */ #include "External_Interrupt.h" /* Global variables to hold the address of the call back function in the application */ static volatile void (*g_INT0_callBackPtr)(void) = NULL_PTR; static volatile void (*g_INT1_callBackPtr)(void) = NULL_PTR; static volatile void (*g_INT2_callBackPtr)(void) = NULL_PTR; ISR(INT0_vect) { if(g_INT0_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_INT0_callBackPtr)(); } } ISR(INT1_vect) { if(g_INT1_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_INT1_callBackPtr)(); } } ISR(INT2_vect) { if(g_INT2_callBackPtr != NULL_PTR) { /* Call the Call Back function in the application */ (*g_INT2_callBackPtr)(); } } void INT0_setCallBack(void(*a_ptr)(void)) { g_INT0_callBackPtr = a_ptr; } void INT1_setCallBack(void(*a_ptr)(void)) { g_INT1_callBackPtr = a_ptr; } void INT2_setCallBack(void(*a_ptr)(void)) { g_INT2_callBackPtr = a_ptr; } void Interrupt_init(Interrupt_ConfigType * Config_Ptr) { if(Config_Ptr -> interrupt == interrupt0) { MCUCR_R = Config_Ptr -> state; CLEAR_BIT(DDRD_R,PD2_B); SET_BIT(GICR_R,INT0_B); } else if(Config_Ptr -> interrupt == interrupt1) { MCUCR_R = (Config_Ptr -> state) << ISC10_B; CLEAR_BIT(DDRD_R,PD3_B); SET_BIT(GICR_R,INT1_B); } else if(Config_Ptr -> interrupt == interrupt2) { MCUCSR_R = ((Config_Ptr -> state) & 0x1) << ISC2_B; CLEAR_BIT(DDRB_R,PB2_B); SET_BIT(GICR_R,INT2_B); } } void Interrupt_setEdgeDetectionType(Interrupt_ConfigType * Config_Ptr,State state) { if(Config_Ptr -> interrupt == interrupt0) { MCUCR_R = state; } else if(Config_Ptr -> interrupt == interrupt1) { MCUCR_R = state << ISC10_B; } else if(Config_Ptr -> interrupt == interrupt2) { MCUCSR_R = (state & 0x1) << ISC2_B; } } void Interrupt0_DeInit(void) { CLEAR_BIT(GICR_R,INT0_B); } void Interrupt1_DeInit(void) { CLEAR_BIT(GICR_R,INT1_B); } void Interrupt2_DeInit(void) { CLEAR_BIT(GICR_R,INT2_B); } <file_sep>/* * MC1.c * * Created on: Oct 7, 2019 * Author: Nour */ #include "LCD.h" #include "UART.h" #include "Timer.h" #include "keypad.h" #include "delay.h" /* compare value for timer1 */ #define _1_M_SEC (uint16)7999 /* UART ready status */ #define READY (uint8)0x01 #define ARRAY_SIZE (uint8)16 #define ACTIVATE_BUZZER (uint8)0xFF #define DELAY_TIME 100 #define DOOR_TIME 30 #define BUZZER_TIME 60 /* variable indicates how many times the password is repeated */ uint8 counter = LOW; /* * in: password array * out: password size * A function that handles the entering of the password */ uint8 password_handling(uint8 * pass); /* * in: password array, password check array,size of password array * out: none * A function that compares two passwords */ uint8 comp_password(uint8 * pass1,uint8 * pass2,uint8 size); /* A function that gathers all initializations */ void init_all(void); int main(void) { /* initial definition of size variable */ uint8 size = LOW; uint8 keypad; uint8 password[ARRAY_SIZE] = {LOW}; uint8 password_check[ARRAY_SIZE] = {LOW}; uint8 temp_password[ARRAY_SIZE] = {LOW}; uint8 comp_result; init_all(); /* Enter the password for the first time */ size = password_handling(password); /* enter the password again */ password_handling(password_check); /* compare the 2 passwords */ comp_result = comp_password(password,password_check,size); while(comp_result != 1) { comp_result = comp_password(password,password_check,size); } /* Reach here if password is matched */ LCD_displayString("password matched"); delay_ms(DELAY_TIME); LCD_clearScreen(); /* send the password */ for(uint8 count = LOW;count < size;count++) { UART_sendByte(password[count]); } UART_sendByte(LOW); while(TRUE) { LCD_displayStringRowColumn(0,0,"+:Open Door"); LCD_displayStringRowColumn(1,0,"-:ChangePassword"); keypad = Keypad_getPressedKey(); delay_ms(DELAY_TIME); /* ASCII of - */ if(keypad == 45) { /* reset counter before compare function */ counter = LOW; LCD_clearScreen(); delay_ms(DELAY_TIME); /* enter the password again */ password_handling(temp_password); /* compare the 2 passwords */ comp_result = comp_password(password,temp_password,size); while(comp_result != 1) { comp_result = comp_password(password,temp_password,size); if(comp_result == 3) { LCD_displayStringRowColumn(0,0,"Password wrong"); LCD_displayStringRowColumn(1,0,"three times"); delay_ms(DELAY_TIME); UART_sendByte(ACTIVATE_BUZZER); delay_s(BUZZER_TIME); /* wait for a minute */ LCD_clearScreen(); break; } } /* compare the 2 passwords */ comp_result = comp_password(password,temp_password,size); while(comp_result != 1) { comp_result = comp_password(password,temp_password,size); } /* Reach here if password is matched */ LCD_displayString("password matched"); delay_ms(DELAY_TIME); LCD_clearScreen(); /* enter the new password */ size = password_handling(password); /* send the password */ for(uint8 count = LOW;count < size;count++) { UART_sendByte(password[count]); } UART_sendByte(LOW); } /* ASCII of + */ else if(keypad == 43) { /* reset counter before compare function */ counter = LOW; LCD_clearScreen(); delay_ms(DELAY_TIME); /* enter the password again */ password_handling(temp_password); /* compare the 2 passwords */ comp_result = comp_password(password,temp_<PASSWORD>,size); while(comp_result != 1) { comp_result = comp_password(password,temp_password,size); if(comp_result == 3) { LCD_displayStringRowColumn(0,0,"Password wrong"); LCD_displayStringRowColumn(1,0,"three times"); delay_ms(DELAY_TIME); UART_sendByte(ACTIVATE_BUZZER); delay_s(BUZZER_TIME); /* wait for a minute */ LCD_clearScreen(); break; } } /* compare the 2 passwords */ comp_result = comp_password(password,temp_password,size); while(comp_result != 1) { comp_result = comp_password(password,password_check,size); } /* Reach here if password is matched */ LCD_displayString("password matched"); delay_ms(DELAY_TIME); LCD_clearScreen(); UART_sendByte(keypad); delay_ms(DELAY_TIME); LCD_displayString("Door opening"); delay_s(DOOR_TIME); LCD_clearScreen(); } } } void init_all(void) { /* UART configuration */ UART_ConfigType UART_Config = {Disabled,_1_bit,_8_bit}; /* Timer 1 is configured to operate for 1 secs */ Timer_ConfigType Timer_Config = {Timer1,CTC,0,no_prescaling,0,0,0,_1_M_SEC,0,Channel_A}; /* LCD initialization */ LCD_init(); /* UART initialization */ UART_init(&UART_Config); /* Timer initialization */ Timer_init(&Timer_Config); } uint8 password_handling(uint8 * pass) { uint8 keypad; uint8 size = LOW; LCD_displayStringRowColumn(0,0,"Please enter"); LCD_displayStringRowColumn(1,0,"the password"); delay_ms(DELAY_TIME); LCD_clearScreen(); do { keypad = Keypad_getPressedKey(); delay_ms(DELAY_TIME); if(keypad != 13) { pass[size] = keypad; (size)++; LCD_displayCharacter('*'); } } while(keypad != 13); /*ASCII of ON button*/ LCD_clearScreen(); return size; } uint8 comp_password(uint8 * pass1,uint8 * pass2,uint8 size) { for(uint8 count = LOW;count < size;count++) { if(pass1[count] != pass2[count]) { counter++; /* if user enters the wrong password 3 times */ if(counter == 3) { return counter; } /* enter the password again */ password_handling(pass2); /* reach here when compare failed */ return 0; } } /* reach here when compare succeed */ return 1; } <file_sep>/* * MC2.c * * Created on: Oct 8, 2019 * Author: Nour */ #include "UART.h" #include "EEPROM_external.h" #include "DC_Motor.h" #include "Timer.h" #include "delay.h" /* compare value for timer1 */ #define _1_M_SEC (uint16)7999 /* UART ready status */ #define READY (uint8)0x01 #define ARRAY_SIZE (uint8)16 #define ACTIVATE_BUZZER (uint8)0xFF #define DELAY_TIME 100 #define BUZZER_TIME 60 #define MOTOR_TIME 15 /* A function that gathers all initializations */ void init_all(void); int main(void) { uint8 password[ARRAY_SIZE] = {LOW}; uint8 count = LOW; /* variable to store received value */ uint8 dummy; /* address of EEPROM */ uint16 Adress = 0x0001; init_all(); do { dummy = UART_recieveByte(); if(dummy != LOW) { password[count] = dummy; EEPROM_external_write_byte(Adress,password[count]); count++; } } while(dummy != LOW); while(TRUE) { dummy = UART_recieveByte(); delay_ms(DELAY_TIME); /* rotate the motor */ if(dummy == 43) { DC_Motor_rotate_clockwise(); delay_s(MOTOR_TIME); DC_Motor_rotate_anti_clockwise(); delay_s(MOTOR_TIME); DC_Motor_stop(); } /* save the changed password */ else if(dummy == 45) { do { dummy = UART_recieveByte(); if(dummy != LOW) { password[count] = dummy; EEPROM_external_write_byte(Adress,password[count]); count++; } } while(dummy != LOW); } /* activate the buzzer */ else if(dummy == ACTIVATE_BUZZER) { SET_BIT(PORTC_R,PC4_B); delay_s(BUZZER_TIME); CLEAR_BIT(PORTC_R,PC4_B); } } } void init_all(void) { /* UART configuration */ UART_ConfigType UART_Config = {Disabled,_1_bit,_8_bit}; /* Timer 1 is configured to operate for 1 secs */ Timer_ConfigType Timer_Config = {Timer1,CTC,0,no_prescaling,0,0,0,_1_M_SEC,0,Channel_A}; /* DC_Motor initialization */ DC_Motor_init(); /* EEPROM_external initialization */ EEPROM_external_init(); /* UART initialization */ UART_init(&UART_Config); /* Timer initialization */ Timer_init(&Timer_Config); /* Buzzer initialization */ SET_BIT(DDRC_R,PC4_B); CLEAR_BIT(PORTC_R,PC4_B); } <file_sep>/* * adc.c * Created on: Sep 23, 2019 * Author: <NAME> */ #include "adc.h" /******************************************************************************* * Functions Definitions * *******************************************************************************/ volatile uint16 g_ADC_value = 0; ISR(ADC_vect) { g_ADC_value = ADC_R; } void ADC_init(const ADC_ConfigType * Config_Ptr) { /* ADMUX Register Bits Description: * REFS1:0 = 00 to choose to connect external reference voltage by input this voltage through AREF pin * ADLAR = 0 right adjusted * MUX4:0 = 00000 to choose channel 0 as initialization */ ADMUX_R = ((Config_Ptr -> voltage) << 6) & 0xC0; /* ADCSRA Register Bits Description: * ADEN = 1 Enable ADC * ADIE = 1 Enable ADC Interrupt * ADPS2:0 = 011 to choose ADC_Clock=F_CPU/8=1Mhz/8=125Khz --> ADC must operate in range 50-200Khz */ /* Check if we are using polling mode */ if(Config_Ptr -> mode == 0) { ADCSRA_R = (1 << ADEN_B) | (Config_Ptr -> prescalar & 0x07); } /* Check if we are using interrupt mode */ else if(Config_Ptr -> mode == 1) { ADCSRA_R = (1 << ADEN_B) | (1 << ADIE_B) | (Config_Ptr -> prescalar & 0x07); } } void ADC_readChannel(uint8 channel_num,const ADC_ConfigType * Config_Ptr) { ADMUX_R = (ADMUX_R & 0xE0) | (channel_num & 0x07) ; /* start conversion write '1' to ADSC */ SET_BIT(ADCSRA_R,ADSC_B); if(Config_Ptr -> mode == 0) { /* wait for conversion to complete ADIF becomes '1' */ while(BIT_IS_CLEAR(ADCSRA_R,ADIF_B)); /* clear ADIF by write '1' to it */ SET_BIT(ADCSRA_R,ADIF_B); /* return the data register */ g_ADC_value = ADC_R; } } <file_sep>/* * UART.c * * Created on: Sep 25, 2019 * Author: Nour */ #include "UART.h" #define Baud_prescale (((F_CPU / (USART_BAUDRATE * 8UL))) - 1) void UART_init(const UART_ConfigType * Config_Ptr) { UCSRC_R = (1 << URSEL_B) | (Config_Ptr -> parity << UPM0_B) | (Config_Ptr -> stop_bit << USBS_B) | (Config_Ptr -> bits << UCSZ0_B); UCSRB_R = (1 << RXEN_B) | (1 << TXEN_B); UCSRA_R = (1 << U2X_B); UBRRL_R = Baud_prescale; UBRRH_R = Baud_prescale >> 8; } void UART_sendByte(uint8 data) { UDR_R = data; while(BIT_IS_CLEAR(UCSRA_R,TXC_B)); SET_BIT(UCSRA_R,TXC_B); } void UART_sendString(const uint8 * Str_Ptr) { uint8 i = 0; while (Str_Ptr[i] != '\0') { UART_sendByte(Str_Ptr[i]); i++; } } uint8 UART_recieveByte(void) { while(BIT_IS_CLEAR(UCSRA_R,RXC_B)); if(BIT_IS_SET(UCSRA_R,FE_B)) { return 0; } if(BIT_IS_SET(UCSRA_R,DOR_B)) { return 0; } if(BIT_IS_SET(UCSRA_R,PE_B)) { return 0; } return UDR_R; } void UART_recieveString(uint8 * Str_Ptr) { uint8 i = 0; Str_Ptr[i] = UART_recieveByte(); do { i++; Str_Ptr[i] = UART_recieveByte(); } while(Str_Ptr[i] != '#'); Str_Ptr[i] = '\0'; }
f85d11cbeb62c3d85ab64d272a2ba38231127e0f
[ "C" ]
58
C
NourAlaaeldin/AVR_Projects
5867a2058db407abf368ad50ff6b789b75434630
9c019e442ceeaa1a2375c1bbb50a794c26546fe3
refs/heads/master
<file_sep> numbers = {}; base = 2; power = 2; combo_cnt = 0; duplicate_cnt = 0; while (base <= 100): power=2; while (power <= 100): combo_cnt += 1; n = base**power; if (numbers.has_key(n)): numbers[n].append((base,power)); #print "%d; %d" % (power, base) duplicate_cnt += 1; else: numbers[n] = [(base,power)]; power = power + 1; base = base + 1; print "Duplicates:",duplicate_cnt print "Combinations:",combo_cnt print "Count:", len(numbers.keys()) <file_sep>#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> int main(int argc, char **argv) { double i; for (i = 1.0; i < 10.0; ++i) { printf("%d: %u\n", (int)i, (int)pow(i, 5.0)); } return(0); } <file_sep>/* * Solution to Project Euler Problem #xx * * <NAME> * * Modification Log: * Date Change * 2013/02/14 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> typedef struct num { int max; int len; unsigned char* num; } num_t; int num_alloc(int max, num_t* n) { n->max = max; n->len = 0; n->num = malloc(max * sizeof(unsigned char)); memset(n->num, 0, max * sizeof(unsigned char)); return(0); } int rexpy(num_t* r, num_t* n1, num_t* n2) { if (!r || !n1 || !n2) { return(-1); } int end = (n1->len > n2->len ? n1->len : n2->len); if (r->max < end + 2) { printf("Error: Destination doesn't have enough space for result: %d < %d\n", r->max, (end + 2)); return(-1); } memset(r->num, 0, sizeof(unsigned char) * r->max); int i; for (i = 0; i < end; i++) { unsigned char t = n1->num[i] + n2->num[i] + r->num[i]; r->num[i] = t % 10; r->num[i+1] = t / 10; int j = i; while (r->num[j] > 10 || r->num[j+1] > 10) { r->num[j+1] += r->num[j] / 10; r->num[j] = r->num[j] % 10; j++; } } i = end + 2; while (r->num[i] == 0) { i--; } r->len = i+1; return(r->len); } int problem025(int argc, char** argv) { num_t n1; num_t n2; num_t n3; num_t* p1 = NULL; num_t* p2 = NULL; num_t* p3 = NULL; num_t* tmp = NULL; num_alloc(1100, &n1); num_alloc(1100, &n2); num_alloc(1100, &n3); p1 = &n1; p2 = &n2; p3 = &n3; n1.len = 1; n1.num[0] = 1; n2.len = 1; n2.num[0] = 1; int i = 3; int j; while (1) { rexpy(p3, p1, p2); // printf("[%3d] len = %d\n[%3d] ", i, p3->len, i); // for (j = p3->len-1; j >= 0; --j) { // printf("%c", p3->num[j] + 0x30); // } // printf("\n"); if (p3->len >= 1000) break; tmp = p1; p1 = p3; p3 = p2; p2 = tmp; i++; } printf("F_%d:\n", i); printf("len = %d\n", p3->len); for (j = p3->len-1; j >= 0; --j) { printf("%c", p3->num[j] + 0x30); } printf("\n"); return(0); } int main(int argc, char** argv) { return(problem025(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #xx * * <NAME> * * Modification Log: * Date Change * 2013/02/08 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <assert.h> #include <stdint.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> typedef struct node { struct node *next; struct node *prev; char *name; int score; } node_t; int name_score(const char* name) { if (!name) return(-1); int score = 0; const char* ptr = name; while (ptr && *ptr) { score += ((*ptr) - 0x40); ptr++; } return(score); } /* * n1 < n2 => -1 * n1 = n2 => 0 * n1 > n2 => 1 * * All strings must be NULL termintated since no lengths * are used. This is kind of dangerous/sloppy. */ int compare_names(const char* n1, const char* n2) { assert(n1); assert(n2); const char* ptr1 = n1; const char* ptr2 = n2; while (ptr1 && ptr2) { if (*ptr1 == 0 || *ptr2 == 0) { if (*ptr1 == *ptr2) return(0); else if (*ptr1 < *ptr2) return(-1); else return(1); } else if (*ptr1 < *ptr2) { return(-1); } else if (*ptr1 > *ptr2) { return (1); } ptr1++; ptr2++; } /* Should never happen */ assert(0); return(-500); } int problem22(int argc, char** argv) { char* fName = "names.txt"; int fd; struct stat sb; char *fData = NULL; fd = open(fName, O_RDONLY); if (fd == 0) { printf("Error: Failed opening file: \"%s\"\n", fName); return(1); } fstat(fd, &sb); printf("File size: %lu\n", sb.st_size); fData = malloc(sb.st_size+1); fData[sb.st_size-1] = 0; fData[sb.st_size] = 0; int size = read(fd, fData, sb.st_size); if (size != sb.st_size) { printf("Read and file sizes do not match:\nread = %d\nfile = %lu\n", size, sb.st_size); close(fd); return(1); } close(fd); printf("File put into memory\n"); int score; int list_count = 0; node_t* head = NULL; node_t* tail = NULL; node_t* curr = NULL; node_t* new = NULL; char* token = NULL; const char* delim = " ,\""; char* last_token = NULL; /* This initializes and "chomps" the '"' on the first name. * That way the first call in the loop is at the first name. * strtok "merges" multiple repeated delimiter character * into a single instance too. */ token = strtok(fData, delim); while (token) { if (strlen(token) < 1) { printf("Error: Token length too short (file offset: %d, last token: \"%s\")\n", (token - fData), last_token); continue; } score = name_score(token); if (score < 0) { printf("Error: Problem getting name score for token: \"%s\" (0x%08x)\n", (token ? token : ""), (unsigned int)token); continue; } /* This is inefficient, should do block allocates instead */ new = calloc(1, sizeof(node_t)); new->name = token; new->score = score; curr = head; if (!curr) { /* First in list */ head = new; tail = new; } else { /* Elsewhere in list */ int rc = -5; while (curr && (rc = compare_names(curr->name, token)) < 0) { curr = curr->next; } assert(rc != 0); /* Update pointers to insert new node */ if (curr == NULL) { /* Tail of list */ tail->next = new; new->prev = tail; tail = new; } else if (curr == head) { /* Head of list */ head = new; new->next = curr; curr->prev = new; } else { /* Middle of list */ curr->prev->next = new; new->prev = curr->prev; new->next = curr; curr->prev = new; } } last_token = token; token = strtok(NULL, delim); list_count++; } printf("List count: %d\n", list_count); /* Count scores */ int i = 1; unsigned long long total = 0; curr = head; while (curr) { total += (curr->score * i); curr = curr->next; i++; } printf("Total of all name scores: %llu\n", total); /* Clean memory */ node_t* tmp = NULL; curr = head; while (curr) { tmp = curr->next; free(curr); curr = tmp; } head = NULL; tail = NULL; free(fData); return(0); } int main(int argc, char** argv) { return(problem22(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #29 * * <NAME> * * Modification Log: * Date Change * 2013/10/14 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> // Using the Omega(x) = log(x)/log(2) equation to bound the upper // limit on the number of prime factor (including multiplicity of // terms). For a < 100, the maximum is 6. #define MAX_PRIME_FACTORS 6 #define MAX_POWER 100 #define MAX_BASE 100 #define MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MIN(a, b) (((a) < (b)) ? (a) : (b)) typedef struct _term { unsigned short base; unsigned short power; } term_t; typedef struct _num { int number; int cnt; term_t components[MAX_PRIME_FACTORS]; } num_t; typedef struct _ll_node { struct _ll_node* next; struct _ll_node* prev; num_t num; } ll_node_t; void print_num(num_t *n); num_t factor(unsigned int p_orig) { num_t factors; int i = 2; int j = 0; unsigned int p = p_orig; memset(&factors, 0, sizeof(num_t)); factors.number = p; while (i <= p) { if (factors.cnt == (MAX_PRIME_FACTORS - 1)) { printf("Error: Base has too many factors: %d\n", p); exit(1); } if (p % i == 0) { p /= i; for (j = 0; j < factors.cnt; ++j) { if (factors.components[j].base == i) { factors.components[j].power++; break; } } if (j == factors.cnt) { factors.components[j].base = i; factors.components[j].power = 1; factors.cnt++; } i = 2; } else { i++; } } unsigned int verify = 1; for (i = 0; i < factors.cnt; ++i) { verify *= pow(factors.components[i].base, factors.components[i].power); } if (verify != p_orig) { printf("Error: Factoring problem: %u, %u\n", p_orig, verify); print_num(&factors); exit(1); } return(factors); } void print_num(num_t *n) { int i = 0; if (n == NULL || n->number <= 0) { printf("Invalid number (0x%lx, %d)\n", (unsigned long)n, (n ? n->number : -1)); return; } printf("Factors for number %d (Cnt: %d):\n", n->number, n->cnt); for (i = 0; i < n->cnt; ++i) { printf(" %2d: %2d\n", n->components[i].base, n->components[i].power); } } void print_num_inline(num_t *n) { int i = 0; printf("(Cnt: %d)", n->cnt); for (; i < n->cnt; ++i) { printf(" %d(%d)", n->components[i].base, n->components[i].power); } } int ll_insert_before(ll_node_t **head, ll_node_t **tail, ll_node_t *ptr, num_t *n) { if (!head || !tail || !n) { printf("Error: Invalid parameter (head = %p, tail = %p, n = %p)\n", head, tail, n); return(0); } ll_node_t *new = calloc(1, sizeof(ll_node_t)); new->num = *n; if (ptr == NULL) { // Goes at end of list (or empty list) if (*tail == NULL) { // Empty list *tail = new; *head = new; } else { // End (*tail)->next = new; new->prev = (*tail); *tail = new; } } else { // Middle or first if (*head == ptr) { // First (*head)->prev = new; new->next = *head; *head = new; } else { // Middle ptr->prev->next = new; new->prev = ptr->prev; new->next = ptr; ptr->prev = new; } } return(1); } int problem29(int argc, char** argv) { int i; int j; int k; num_t f[MAX_BASE+1]; int ll_cnt = 0; ll_node_t* ll_head = NULL; ll_node_t* ll_tail = NULL; ll_node_t* ll_ptr = NULL; for (i = 2; i <= MAX_BASE; ++i) { f[i] = factor(i); } // int iterCnt = 0; int combo_cnt = 0; int duplicate_cnt = 0; for (i = 2; i <= MAX_BASE; ++i) { for (j = 2; j <= MAX_POWER; ++j) { combo_cnt++; num_t temp = f[i]; // printf("[%4d] Power: %d; Base number: ", __LINE__, j); // print_num_inline(&temp); // printf("\n"); for (k = 0; k < temp.cnt; ++k) { temp.components[k].power *= j; } // printf("[%4d] Starting insert search: ", __LINE__); // print_num_inline(&temp); // printf("\n"); if (ll_cnt == 0) { ll_cnt += ll_insert_before(&ll_head, &ll_tail, NULL, &temp); } else { // Existing ll_ptr = ll_head; int component = 0; int done = 0; while (ll_ptr) { int stop_component = MIN(temp.cnt, ll_ptr->num.cnt); // printf("[%4d] Comparing to: ", __LINE__); // print_num_inline(&ll_ptr->num); // printf("\n"); for (component = 0; component < stop_component; ++component) { if (temp.components[component].base > ll_ptr->num.components[component].base) { // printf("[%4d] New has larger base -> Skipping to next\n", __LINE__); ll_ptr = ll_ptr->next; break; } else if (temp.components[component].base < ll_ptr->num.components[component].base) { // printf("[%4d] New has smaller base -> Adding number\n", __LINE__); ll_cnt += ll_insert_before(&ll_head, &ll_tail, ll_ptr, &temp); done = 1; break; } else if (temp.components[component].power < ll_ptr->num.components[component].power) { // printf("[%4d] New has equal base with smaller power -> Adding number\n", __LINE__); ll_cnt += ll_insert_before(&ll_head, &ll_tail, ll_ptr, &temp); done = 1; break; } else if (temp.components[component].power > ll_ptr->num.components[component].power) { // printf("[%4d] New has equal base but larger power -> Skipping to next\n", __LINE__); ll_ptr = ll_ptr->next; break; } } // if (++iterCnt > 1000) { // printf("[%4d] Aborting...\n", __LINE__); // return (0); // } if (done) { break; } if (component == stop_component) { if (temp.cnt == ll_ptr->num.cnt) { // Duplicate // printf("[%4d] New is a duplicate -> Do nothing: ", __LINE__); // print_num_inline(&ll_ptr->num); // printf("\n"); duplicate_cnt++; break; } if (temp.cnt == stop_component) { // printf("[%4d] New has fewer components -> Adding number\n", __LINE__); ll_cnt += ll_insert_before(&ll_head, &ll_tail, ll_ptr, &temp); break; } ll_ptr = ll_ptr->next; } } if (ll_ptr == NULL) { ll_cnt += ll_insert_before(&ll_head, &ll_tail, NULL, &temp); } } // printf("[%4d] LL length: %d\n", __LINE__, ll_cnt); } } printf("Duplicates: %d\n", duplicate_cnt); printf("Combinations: %d\n", combo_cnt); printf("Linked List Count: %d\n", ll_cnt); ll_ptr = ll_head; while (ll_ptr) { ll_head = ll_head->next; if (ll_head) ll_head->prev = NULL; free(ll_ptr); ll_ptr = ll_head; } ll_tail = NULL; return(0); } int main(int argc, char** argv) { return(problem29(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #14 * * <NAME> * * Modification Log: * Date Change * 2012/05/01 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define MAX_START 1000000 // #define MAX_START 100 #define MAX_SAVED (MAX_START * 3 + 1) unsigned int numbers[MAX_SAVED + 1]; void printSavedTable() { unsigned int i; printf("Saved numbers table:\n"); for (i = 0; i <= MAX_SAVED; ++i) { if (i != 0 && i % 8 == 0) printf("\n"); printf("[%4d] = %5d ", i, numbers[i]); } if (i != 0 && i % 8 != 0) printf("\n"); } unsigned int printSequence(unsigned int num) { unsigned int cnt = 0; while (num > 1) { cnt++; printf("%5d -> ", num); if (num % 2 == 1) num = num * 3 + 1; else num = num / 2; if (cnt % 10 == 0) printf("\n"); } if (cnt % 10 != 0) printf(" 1\n"); printf("Count = %d\n", ++cnt); return (cnt); } unsigned int calcSequence(unsigned int start) { unsigned int cnt = 1; unsigned int num = start; while (num > 1) { if (num <= MAX_SAVED && numbers[num] != 0) { // At a known point return (cnt + numbers[num] - 1); } if (num % 2 == 0) { // Even number num >>= 1; // Divid by 2 } else { // Odd number num = num * 3 + 1; } cnt++; } return(cnt); } unsigned int populateMultiples(unsigned int base, unsigned int cnt) { unsigned int i; for (i = base; i <= MAX_SAVED; i <<= 1) { numbers[i] = cnt++; } return(0); } unsigned int populateSaved() { unsigned int i; unsigned int seqLen = 0; for (i = 1; i <= MAX_START; i += 2) { if (numbers[i] == 0) { seqLen = calcSequence(i); populateMultiples(i, seqLen); } } return(0); } unsigned int findBest(unsigned int* start) { unsigned int i; // unsigned int seqLen = 0; unsigned int longest = 0; unsigned int best = 0; for (i = MAX_START; i > 0; --i) { if (numbers[i] == 0) { printf("Problem...? i = %d has no count\n", i); } else { if (numbers[i] > longest) { longest = numbers[i]; best = i; } } } if (start) *start = best; return (longest); } int problem(int argc, char** argv) { unsigned int longest = 0; unsigned int bestStart = 0; memset(&numbers[0], 0, sizeof (numbers)); populateSaved(); // printSavedTable(); longest = findBest(&bestStart); printf("Longest sequence (%d) under %d starts at %d\n", longest, MAX_START, bestStart); return( 0 ); } int main(int argc, char** argv) { return( problem(argc, argv) ); } <file_sep>/* * Solution to Project Euler Problem #xx * * <NAME> * * Modification Log: * Date Change * 2011/xx/xx Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdint.h> #define MAX 28123 #define bm_set(i, arr) (((arr)[(i) / 32]) |= (0x1 << ((i) % 32))) int problem(int argc, char** argv) { int i; int j; int a_nums[MAX+1]; uint32_t abundant_sums[MAX+1]; uint32_t bm_abundant_sums[(MAX - 1) / 32 + 1]; int non_abundant_sum = 0; memset(&bm_abundant_sums[0], 0, sizeof(bm_abundant_sums)); memset(&abundant_sums[0], 0, sizeof(abundant_sums)); for (i = MAX; i >= 0; --i) { a_nums[i] = 1; } /* Generate all the factor sums: d(i) = n */ for (i = 2; i <= MAX / 2; ++i) { for (j = (i*2); j <= MAX; j += i) { a_nums[j] += i; } } for (i = 4; i <= MAX; ++i) { if (a_nums[i] <= i) continue; for (j = i; j <= MAX; ++j) { if (a_nums[j] <= j) continue; if (i + j > MAX) break; // printf("Abundant pair: %d (%d) + %d (%d) = %d\n", i, a_nums[i], j, a_nums[j], (i + j)); bm_set(i + j, bm_abundant_sums); abundant_sums[i+j] = 1; } } int count = 0; for (i = 1; i < MAX; ++i) { if (abundant_sums[i] != 1) { non_abundant_sum += i; count++; } } printf("Found = %d\n", count); printf("Sum of all non-abundant sumable numbers under %d: %d\n", MAX, non_abundant_sum); return( 0 ); } int main(int argc, char** argv) { return( problem(argc, argv) ); } <file_sep>/* * Solution to Project Euler Problem #9 * * <NAME> * * Modification Log: * Date Change * 2010/12/23 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int conditionTest(int a, int b, int c) { return( (a < c) && (b < c) && (1000 == a + b + c) && ((a*a + b*b) == (c*c)) ); } int problem(int argc, char** argv) { int a, b, c; double b_calc; for( a = 1; a < 500; ++a ) { b_calc = ((double)(5e5 - 1000*a)) / ((double)(1000 - a)); b = (int) b_calc; if( b == b_calc ) { c = 1000 - a - b; if( conditionTest(a, b, c) ) { printf("a = %d, b = %d, c = %d\n", a, b, c); printf("a+b+c = %d\n", (a + b + c)); printf("a*b*c = %d\n", (a * b * c)); break; } } } return( 0 ); } int main(int argc, char** argv) { return( problem(argc, argv) ); } <file_sep>For simplicity and verification, I just used Python quickly to generate the solution: >>> def factorial(n): ... if (n > 1): ... return(n * factorial(n-1)); ... else: ... return(1); ... >>> factorial(10) 3628800 >>> factorial(100) 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000L >>> number = factorial(100) >>> numStr = str(number) >>> numStr '93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000' >>> sum = 0; >>> for idx in range(0, len(numStr)): ... sum += int(numStr[idx]); ... >>> sum 648 >>> <file_sep>/* * Solution to Project Euler Problem #41 * * <NAME> * * Modification Log: * Date Change * 2016/05/26 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdint.h> int isPrime(unsigned int n) { unsigned int i; /* Negative, special, or even number */ if (n == 2) return (1); if (n < 2 || n % 2 == 0) return(0); /* Resume where the BM ended */ for (i = 3; i < (n/2) + 1; i += 2) { if (n % i == 0) { return(0); } } return(1); } char * printNum(int n, uint8_t digits[]) { static char digitStr[16]; int i; memset(digitStr, 0, sizeof (digitStr)); for (i = 0; i < n; ++i) digitStr[i] = digits[i] + 0x30; return (digitStr); } /* * checkDigits * * Check if the current digit combination is a prime number. * Returns the number if it is prime. Otherwise returns 0. */ int checkDigits(int n, uint8_t digits[]) { unsigned int num; unsigned int scalar; int i; if (digits[n - 1] % 2 == 0) return (0); for (i = n - 1, scalar = 1, num = 0; i >= 0; --i, scalar *= 10) num += (digits[i] * scalar); if (isPrime(num)) return (num); return (0); } /* * permute * * Recursive function to iterate through all the digit combinations * of a source array. Starts with the largest number and tests smaller * combinations until the first prime is found. * * Inputs: * n - number of digits * pos - current index position for iterating * digits - digit array for permuting * * Results: * 0 = No prime number found * <prime> = First prime found. */ int permute(int n, int pos, uint8_t digits[]) { int i; unsigned int num; uint8_t temp; if (pos == n - 1) { if ((num = checkDigits(n, digits))) return (num); else return (0); } /* Progressively swap the digit at the current position to the end */ for (i = pos; i < n; ++i) { if ((num = permute(n, pos + 1, digits))) { return (num); } if (i == n - 1) break; temp = digits[pos]; digits[pos] = digits[i + 1]; digits[i + 1] = temp; } /* Restore the digits to their original positions */ for (i--; i >= pos; --i) { temp = digits[pos]; digits[pos] = digits[i + 1]; digits[i + 1] = temp; } return (0); } int problem41(int argc, char** argv) { uint8_t digits[10]; int n = 2; unsigned int num = 0; int i; if (argc > 1) n = atoi(argv[1]); printf("n = %d\n", n); for (; n > 0; n--) { printf("n = %d\n", n); /* Initialize */ for (i = 0; i < n; ++i) digits[i] = n - i; num = permute(n, 0, digits); if (num) break; } if (num) { printf("Result: %u\n", num); } return (0); } int main(int argc, char** argv) { return (problem41(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #35 * * <NAME> * * Modification Log: * Date Change * 2015/10/11 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> #define BM_SET(b, bm) ((bm)[((b)/8)] |= (0x1 << ((b) % 8))) #define BM_CLR(b, bm) ((bm)[((b)/8)] &= (~(0x1 << ((b) % 8)))) #define BM_IS_SET(b, bm) ((bm)[((b)/8)] & (0x1 << ((b) % 8))) unsigned int bm_max = 0; unsigned char * bm_primes = NULL; int calc_primes(int max) { int i; int j; int cnt = 0; int size = (max >> 3) + 1; bm_primes = (unsigned char *)malloc(size); memset(bm_primes, 0, size); BM_SET(0, bm_primes); BM_SET(1, bm_primes); for (i = 2; i <= max; ++i) { if (!BM_IS_SET(i, bm_primes)) { for (j = 2; (i*j) <= max; ++j) { BM_SET((i*j), bm_primes); } } } for (i = 2; i <= max; ++i) { if (!BM_IS_SET(i, bm_primes)) { // printf("Prime: %d\n", i); cnt++; } } bm_max = max; return(cnt); } int isPrime(int n) { int i; /* Negative, special, or even number */ if (n < 2 || n % 2 == 0) return(0); /* Within the range of the BM of primes */ if (n < bm_max) { return(!BM_IS_SET(n, bm_primes)); } /* Now search using the primes from the BM */ for (i = 3; i < bm_max; i += 2) { if (BM_IS_SET(i, bm_primes)) continue; if (n % i == 0) return(0); } /* Resume where the BM ended */ for (; i < (n/2) + 1; i += 2) { if (n % i == 0) { return(0); } } return(1); } int test_rotations(int num, int order) { int i; int d; int largest = (int)pow(10.0, order-1); for (i = 0; i < order; ++i) { d = num % 10; num /= 10; num += (largest * d); if (!isPrime(num)) { return(0); } } return(1); } int problem35(int argc, char** argv) { int i; int cnt1 = 1; // Counts for 2 int tmp; int order; const int end = 1e6; // 1e7; calc_primes(end); for (i = 3; i < end; i += 2){ if (!isPrime(i)) continue; tmp = i; order = 0; while (tmp > 0) { if (tmp % 10 % 2 == 0) break; tmp /= 10; ++order; } if (tmp > 0) continue; if (test_rotations(i, order)) { // printf("Rotations are all primes: %d\n", i); cnt1++; } } printf("Circular Primes under %d: %d\n", end, cnt1); return(0); } int main(int argc, char** argv) { return(problem35(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #2 * * <NAME> * * Modification Log: * Date Change * 2010/12/02 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define index(i, off) (((i) + (3 - off)) % (3)) int main(int argc, char** argv) { int i = 2; int total = 2; int dataValues[] = {0, 2, 0}; /* Problem Solving */ while( dataValues[index(i, 1)] < 4000000 ) { dataValues[index(i,0)] = 4 * dataValues[index(i,1)] + dataValues[index(i,2)]; total += dataValues[index(i,0)]; ++i; } total -= dataValues[index(i,1)]; printf( "Total = %d;\n", total); printf( "Last value set = { %d, %d, %d }, i = %d, index = %d;\n", dataValues[0], dataValues[1], dataValues[2], i, index(1,0)); return( 0 ); } <file_sep>/* * Solution to Project Euler Problem #9 * * <NAME> * * Modification Log: * Date Change * 2010/12/23 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> int isPrime(unsigned int num) { if( num == 1 ) return( 0 ); else if( num < 4 ) return( 1 ); else if( num % 2 == 0 ) return( 0 ); else if( num < 9 ) return( 1 ); else if( num % 3 == 0 ) return( 0 ); else { int r = (int) sqrt(num); int f = 5; while( f <= r ) { if( num % f == 0 ) return( 0 ); if( num % (f+2) == 0 ) return( 0 ); f += 6; } } return( 1 ); } int problem(int argc, char** argv) { unsigned long long sum = 2; unsigned int num = 3; do { if( isPrime(num) ) { sum += num; } num += 2; } while( num < 2e6 ); printf("num = %d\n", num); printf("sum = %lld\n", sum); return( 0 ); } int main(int argc, char** argv) { return( problem(argc, argv) ); } <file_sep>/* * Solution to Project Euler Problem #xx * * <NAME> * * Modification Log: * Date Change * 2011/xx/xx Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> const int factorials[] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }; int problem34(int argc, char** argv) { int i; int tmp; int sum; int solution_sum = 0; for (i = 10; i < 1e7; ++i) { tmp = i; sum = 0; while(tmp > 0) { sum += factorials[tmp % 10]; tmp /= 10; } if (sum == i) { solution_sum += i; printf("Found match: %d ==", i); tmp = i; while (tmp > 0) { printf(" %d! +", tmp % 10); tmp /= 10; } tmp = i; printf(" =="); while (tmp > 0) { printf(" %d +", factorials[tmp % 10]); tmp /= 10; } printf(" == %d\n", sum); } } printf("Sum of matches: %d\n", solution_sum); return(0); } int main(int argc, char** argv) { return(problem34(argc, argv)); } <file_sep>#include <stdio.h> int main(int argc, char **argv) { int i; int prod = 1; printf("0\n"); for (i = 1; i < 10; ++i) { printf("%d\n", (prod *= i)); } return(0); } <file_sep>/* * Solution to Project Euler Problem #28 * * <NAME> * * Modification Log: * Date Change * 2013/09/23 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int problem28(int argc, char** argv) { unsigned long int sum = 1; int r = 3; int n; int pos = 1; int step = 2; int stop = 1001; if (argc == 2) { stop = atoi(argv[1]); if (stop < 3) { printf("Invalid valid parsed: \"%s\" (%d)\n", argv[1], stop); return(1); } if (stop % 2 == 0) { printf("Invalid row length (should be odd): %d\n", stop); return(1); } } for (; r <= stop; r += 2) { /* 4 corners */ for (n = 0; n < 4; ++n) { pos += step; sum += pos; } step += 2; } printf("Final sum: %lu\n", sum); return(0); } int main(int argc, char** argv) { return(problem28(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #30 * * SB * * Modification Log: * Date Change * 2015/10/01 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> #if 0 const unsigned int pow_4th[10] = { 0, // 0 1, // 1 16, // 2 81, // 3 256, // 4 625, // 5 1296, // 6 2401, // 7 4096, // 8 6561 // 9 }; #define powers pow_4th #define powers_depth 4 #else const unsigned int pow_5th[10] = { 0, // 0 1, // 1 32, // 2 243, // 3 1024, // 4 3125, // 5 7776, // 6 16807, // 7 32768, // 8 59049 // 9 }; #define powers pow_5th #define powers_depth 6 #endif int digits[10]; // Longer than necessary void print_result(int level, int sum, int *digits) { int j; for (j = 0; j <= level; ++j) { printf("%d", digits[j]); } printf(" = "); for (j = 0; j <= level; ++j) { printf("%d", powers[digits[j]]); if (j != level) printf(" + "); } printf("\n"); } int check_digits(int level, int sum, int *digits) { int i; int tmp = sum; for (i = level; i >= 0; --i) { if (digits[i] != tmp % 10) return(0); tmp /= 10; } return(1); } int gen_combinations(int level, int max_depth, int sum, int *digits, int *results_sum) { int i; // int k; int cnt = 0; int tmp = sum; int min = (int)pow(10.0, (double)level); int max = (int)pow(10.0, (double)(level + 1)); if (level >= max_depth) { return(0); } else { // for (k = 0; k < level; ++k) printf("\t"); // printf("[%d] min: %d, max: %d, sum: %d\n", level, min, max, sum); i = (level ? 0 : 1); for (; i < 10; ++i) { tmp = sum + powers[i]; // for (k = 0; k < level; ++k) printf("\t"); // printf("[%d] i:%d tmp:%d\n", level, i, tmp); digits[level] = i; if (tmp > min && tmp < max) { if (tmp % 10 == i) { if (check_digits(level, tmp, digits)) { printf("Found solution[%d:%d]: %d = ", level, cnt, tmp); print_result(level, tmp, digits); cnt++; *results_sum += tmp; } } } cnt += gen_combinations(level + 1, max_depth, tmp, digits, results_sum); } } return(cnt); } int problem30(int argc, char** argv) { int cnt = 0; int results_sum = 0; int digits[10] = { 0 }; printf("Hello World\n"); cnt = gen_combinations(0, powers_depth, 0, &digits[0], &results_sum); printf("Count: %d\n", cnt); printf("Sum of matches: %d\n", results_sum); printf("Goodbye World\n"); return(0); } int main(int argc, char** argv) { return(problem30(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #8 * * <NAME> * * Modification Log: * Date Change * 2010/12/14 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> /* NOTE: Numbers in ASCII start at 0x30 w/ 0 */ char target[] = "\ 73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557\ 66896648950445244523161731856403098711121722383113\ 62229893423380308135336276614282806444486645238749\ 30358907296290491560440772390713810515859307960866\ 70172427121883998797908792274921901699720888093776\ 65727333001053367881220235421809751254540594752243\ 52584907711670556013604839586446706324415722155397\ 53697817977846174064955149290862569321978468622482\ 83972241375657056057490261407972968652414535100474\ 82166370484403199890008895243450658541227588666881\ 16427171479924442928230863465674813919123162824586\ 17866458359124566529476545682848912883142607690042\ 24219022671055626321111109370544217506941658960408\ 07198403850962455444362981230987879927244284909188\ 84580156166097919133875499200524063689912560717606\ 05886116467109405077541002256983155200055935729725\ 71636269561882670428252483600823257530420752963450\ "; int problem(int argc, char** argv) { int digits[5] = {0, 0, 0, 0, 0}; int length = strlen(target); int i = 0; int j = 0; int index = 0; int product = 1; int largest = 0; char *ptr = &target[0]; for( i = 0; i < length; ++i ) { digits[i % 5] = ((int) (*ptr++)) - 0x30; product = 1; for( j = 0; j < 5; ++j ) product *= digits[j]; if( product > largest ) { printf("New largest: %d = (* %d %d %d %d %d);\n", product, digits[0], digits[1], digits[2], digits[3], digits[4]); largest = product; index = i; } } printf("largest = %d;\n", largest); printf("index = %d;\n", index); return( 0 ); } int main(int argc, char** argv) { return( problem(argc, argv) ); } <file_sep>/* * Solution to Project Euler Problem #39 * * <NAME> * * Modification Log: * Date Change * 2015/10/17 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define setDigit(d, c) ((c) |= (0x1 << d)) #define isDigit(d, c) ((c) & (0x1 << d)) int problem38(int argc, char** argv) { int n; int i; int j; int tmp; int sum = 0; int largest = 0; int digits = 0; for (i = 1; i < 10000; ++i) { // printf("%d\n", i); digits = 0; sum = 0; for (n = 1; n < 10; ++n) { // printf(" %d\n", n); tmp = i * n; while (tmp > 0) { if (isDigit(tmp % 10, digits)) break; setDigit(tmp % 10, digits); tmp /= 10; } if (tmp) break; // printf("i:%d, n:%d, d:0x%x\n", i, n, digits); if (digits == 0x3fe) { // All digits used for (j = 1; j <= n; ++j) { tmp = i * j; // printf("i:%d, j:%d: %d\n", i, j, i*j); while (tmp > 0) { sum *= 10; tmp /= 10; } sum += (i * j); } if (sum > largest) { // printf("Old largest: %d, new largest: %d\n", largest, sum); // printf(" i:%d, n:%d\n", i, n); largest = sum; } break; } } } printf("Largest: %d\n", largest); return(0); } int main(int argc, char** argv) { return(problem38(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #6 * * <NAME> * * Modification Log: * Date Change * 2010/12/xx Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int main(int argc, char** argv) { int end = 100; int triangleNumber = end * (end + 1) / 2; int i = 0; unsigned long long difference = 0; printf("Tn = %d;\n", triangleNumber); for( i = 0; i <= end; ++i ) { difference += i * triangleNumber; --triangleNumber; } printf( "Difference = %lld\n", difference ); return( 0 ); } <file_sep>/* * Solution to Project Euler Problem #19 * * <NAME> * * Modification Log: * Date Change * 2013/01/14 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int days[] = { 31, // January 28, // February 31, // March 30, // April 31, // May 30, // June 31, // July 31, // August 30, // Septempter 31, // October 30, // November 31 // December }; int problem(int argc, char** argv) { int year = 1900; int month = 0; int dayTotal = 1; int first_sundays = 0; while (year < 2001) { if (month == 1 && year % 4 == 0) { if (year % 100 != 0 || year % 400 == 0) { // Leap year dayTotal += days[month] + 1; } } else { dayTotal += days[month]; } if (dayTotal % 7 == 0) { if (year > 1900 && year < 2001) { first_sundays++; } } if (month == 11) year++; month = (month + 1) % 12; } printf("There have been %d Sundays on the first of a month\n", first_sundays); return(0); } int main(int argc, char** argv) { return(problem(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #31 * * <NAME> * * Modification Log: * Date Change * 2015/10/02 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define NUM_PENCE 8 const int pence[NUM_PENCE] = { 200, 100, 50, 20, 10, 5, 2, 1 }; int search(int start, int sum) { int i; int cnt = 0; if (start >= NUM_PENCE) return(0); for (i = start; i < NUM_PENCE; ++i) { if (sum + pence[i] == 200) { cnt++; } else if (sum + pence[i] > 200) { continue; } else { cnt += search(i, sum + pence[i]); } } return(cnt); } int problem(int argc, char** argv) { int cnt; printf("Hello World\n"); cnt = search(0, 0); printf("Possible combinations: %d\n", cnt); printf("Goodbye World\n"); return(0); } int main(int argc, char** argv) { return(problem(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #1 * * <NAME> * * Modification Log: * Date Change * 2010/12/02 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> int Tn(int mul, int n) { return( mul * (n * (n + 1) / 2) ); } int main(int argc, char** argv) { int m = 1000; int n = 0; int lcm = 0; int total = 0; int count = 0; int multiples[] = {3, 5}; int i = 0; /* Problem Solving */ count = sizeof( multiples ) / sizeof( int ); for( i = 0; i < count; ++i ) { n = (int) ((m - 1) / multiples[i]); total += Tn( multiples[i], n ); } lcm = multiples[0] * multiples[1]; total -= Tn( lcm, (int) ((m-1) / lcm)); printf("The total sum for the multiples of {"); for( i = 0; i < count; ++i ) { printf("%d%s", multiples[i], (i == (count-1) ? "" : ", ")); } printf("} in %d is equal to %d.\n", m, total); return( 0 ); } <file_sep>/* * Solution to Project Euler Problem #xx * * <NAME> * * Modification Log: * Date Change * 2013/01/24 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <assert.h> typedef struct big_num { int length; int max; unsigned char* num; } big_num_t; int big_num_init(big_num_t *n, unsigned int max) { if (n == NULL || max <= 0) return(-1); n->num = malloc(max * sizeof(char)); assert(n->num != NULL); memset(n->num, 0, max * sizeof(char)); n->max = max; n->length = 0; return(0); } int big_num_resize(big_num_t *n, unsigned int newMax) { if (n == NULL || newMax < n->length) { return(-1); } unsigned char* tmp = malloc(newMax * sizeof(char)); assert(tmp != NULL); memset(tmp, 0, newMax * sizeof(char)); memcpy(tmp, n->num, ((newMax > n->max) ? n->max : newMax)); free(n->num); n->num = tmp; return(0); } int big_num_clear(big_num_t *n) { memset(n->num, 0, n->max); n->length = 0; return(0); } int big_num_multiply(big_num_t *d, big_num_t *s1, big_num_t *s2) { if (d->max < s1->length + s2->length) { big_num_resize(d, s1->length + s2->length + 20); } big_num_clear(d); int i; int j; int k; unsigned char r; unsigned char m; for (i = 0; i < s2->length; i++) { m = s2->num[i]; for (j = 0; j < s1->length; j++) { /* Calculate single digit result */ r = m * s1->num[j]; /* Save into dest and carry */ d->num[i+j] += r % 10; d->num[i+j+1] += r / 10; /* Carry through */ k = i+j; while(d->num[k] > 9) { r = d->num[k]; d->num[k] %= 10; d->num[k+1] += r / 10; ++k; } } } d->length = s1->length + s2->length; /* Chomp leading zeros */ while(d->num[d->length-1] == 0) { d->length--; } return(0); } int big_num_add_one(big_num_t *n) { /* Check for size */ if (n->length == n->max) { big_num_resize(n, n->length + 20); } /* Add 1 */ n->num[0] += 1; /* Carry if needed */ int i = 0; while(n->num[i] > 9) { n->num[i+1] += n->num[i] / 10; n->num[i] %= 10; i++; } /* Incrase length if carried far enough */ if (i == n->length) { n->length++; } return(0); } void big_num_print(big_num_t *n, const char *name) { int i; printf("%s = ", name); for(i = n->length-1; i >= 0; i--) { printf("%c", (n->num[i] + 0x30)); } printf("\n"); } int big_num_sum_digits(big_num_t *n) { int i; int sum = 0; for (i = n->length-1; i >=0; i--) { sum += n->num[i]; } return(sum); } int problem(int argc, char** argv) { int i; big_num_t f; big_num_t r1; big_num_t r2; big_num_t *w1; big_num_t *w2; big_num_t *tmp; big_num_init(&f, (unsigned)10); big_num_init(&r1, (unsigned)200); big_num_init(&r2, (unsigned)200); big_num_clear(&f); big_num_clear(&r1); big_num_clear(&r2); f.num[0] = 1; f.length = 1; r1.num[0] = 1; r1.length = 1; w1 = &r1; w2 = &r2; tmp = NULL; for (i = 1; i < 100; ++i) { big_num_add_one(&f); big_num_multiply(w2, w1, &f); tmp = w2; w2 = w1; w1 = tmp; } big_num_print(&f, "f"); big_num_print(w1, "result"); printf("Digit sum: %d\n", big_num_sum_digits(w1)); return(0); } int main(int argc, char** argv) { return(problem(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #30 * * SB * * Modification Log: * Date Change * 2015/10/01 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> #if 0 const unsigned int pow_4th[10] = { 0, // 0 1, // 1 16, // 2 81, // 3 256, // 4 625, // 5 1296, // 6 2401, // 7 4096, // 8 6561 // 9 }; #define powers pow_4th #define powers_depth 4 #else const unsigned int pow_5th[10] = { 0, // 0 1, // 1 32, // 2 243, // 3 1024, // 4 3125, // 5 7776, // 6 16807, // 7 32768, // 8 59049 // 9 }; #define powers pow_5th #define powers_depth 6 #endif int check_digits(int num) { int tmp = num; int sum = 0; while (tmp > 0) { sum += powers[tmp % 10]; tmp /= 10; } if (sum == num) return(1); return(0); } int gen_combinations(int level, int max_depth, int sum, int *digits, int *results_sum) { int i; // int k; int cnt = 0; for (i = 2; i < 999999; ++i) { if (check_digits(i)) { printf("Found result: %d\n", i); cnt++; *results_sum += i; } } return(cnt); } int problem30(int argc, char** argv) { int cnt = 0; int results_sum = 0; int digits[10] = { 0 }; printf("Hello World\n"); cnt = gen_combinations(0, powers_depth, 0, &digits[0], &results_sum); printf("Count: %d\n", cnt); printf("Sum of matches: %d\n", results_sum); printf("Goodbye World\n"); return(0); } int main(int argc, char** argv) { return(problem30(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #7 * * <NAME> * * Modification Log: * Date Change * 2010/12/xx Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> int isPrime(unsigned long long num) { int i = 3; if (!(num & 0x1)) return( 0 ); while( i < num ) { if( num % i == 0 ) { return( 0 ); } i += 2; } return( 1 ); } int problem(int argc, char** argv) { int count = 3; const int target = 10001; unsigned long long number = 5; /* FIXME: Double check off-by-one indexing */ do { number += 2; if( isPrime( number ) ) { ++count; } } while( count < target ); printf("Number = %lld; count = %d;\n", number, count); return( 0 ); } int main(int argc, char** argv) { return( problem(argc, argv) ); } <file_sep>/* * Solution to Project Euler Problem #xx * * <NAME> * * Modification Log: * Date Change * 2011/xx/xx Initial authoring. * */ /* * Some references found during research for this problem. * * http://eli.thegreenplace.net/2009/02/25/project-euler-problem-26/ * http://pastebin.com/f1efaf62d (From a comment in the above blog post) * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdint.h> #define MAX_NUM (1000) #define BM_SET(b, bm) ((bm)[((b)/8)] |= (0x1 << ((b) % 8))) #define BM_CLR(b, bm) ((bm)[((b)/8)] &= (~(0x1 << ((b) % 8)))) #define BM_IS_SET(b, bm) ((bm)[((b)/8)] & (0x1 << ((b) % 8))) unsigned char * bm_primes = NULL; int calc_primes(int max) { int i; int j; int cnt = 0; int size = (max >> 3) + 1; bm_primes = (unsigned char *)malloc(size); memset(bm_primes, 0, size); BM_SET(0, bm_primes); BM_SET(1, bm_primes); for (i = 2; i <= max; ++i) { if (!BM_IS_SET(i, bm_primes)) { for (j = 2; (i*j) <= max; ++j) { BM_SET((i*j), bm_primes); } } } for (i = 2; i <= max; ++i) { if (!BM_IS_SET(i, bm_primes)) { printf("Prime: %d\n", i); cnt++; } } return(cnt); } int problem26(int argc, char** argv) { int i; int x; int max_num = MAX_NUM; int cnt; int len = 0; int max_len = 0; int max_len_prime = 0; if (argc == 2) { max_num = atoi(argv[1]); if (max_num < 2) { printf("Invalid Max: \"%s\" (%d)\n", argv[1], max_num); return(1); } printf("Setting max number: %d\n", max_num); } cnt = calc_primes(max_num); printf("%d primes under %d\n", cnt, max_num); /* Prime numbers are now determined (any 0 bits in the bitmap) */ for (i = 2; i <= max_num; ++i) { /* Skip non prime numbers */ if (BM_IS_SET(i, bm_primes)) continue; x = 1; len = 0; while (x != 0) { while (x <= i) { x *= 10; len++; } x %= i; if (x == 1) break; if (len > (2 * i)) { printf("Error on prime %d: len = %d\n", i, len); return (1); } } if (len > max_len) { max_len = len; max_len_prime = i; } } printf("Longest decimal pattern: %d from prime %d\n", max_len, max_len_prime); return(0); } int main(int argc, char** argv) { return(problem26(argc, argv)); } <file_sep> all: a.out a.out: solution_01.c gcc -Wall solution_01.c run: all ./a.out <file_sep>/* * Solution to Project Euler Problem #xx * * <NAME> * * Modification Log: * Date Change * 2011/xx/xx Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int problem(int argc, char** argv) { return( 0 ); } int main(int argc, char** argv) { return( problem(argc, argv) ); } <file_sep>/* * Solution to Project Euler Problem #17 * * <NAME> * * Modification Log: * Date Change * 2012/12/23 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int letterCount[100]; int tens[10]; void populateBase() { letterCount[0] = 0; // Zero letterCount[1] = 3; // One letterCount[2] = 3; // Two letterCount[3] = 5; // Three letterCount[4] = 4; // Four letterCount[5] = 4; // Five letterCount[6] = 3; // Six letterCount[7] = 5; // Seven letterCount[8] = 5; // Eight letterCount[9] = 4; // Nine letterCount[10] = 3; // Ten letterCount[11] = 6; // Eleven letterCount[12] = 6; // Twelve letterCount[13] = 8; // Thirteen letterCount[14] = 8; // Fourteen letterCount[15] = 7; // Fifteen letterCount[16] = 7; // Sixteen letterCount[17] = 9; // Seventeen letterCount[18] = 8; // Eighteen letterCount[19] = 8; // Nineteen tens[0] = 0; // Ones places tens[1] = -1; // Teens - Special case tens[2] = 6; // Twenty tens[3] = 6; // Thirty tens[4] = 6; // Fourty tens[5] = 5; // Fifty tens[6] = 5; // Sixty tens[7] = 7; // Seventy tens[8] = 6; // Eighty tens[9] = 5; // Ninty } void populateTens() { int i; for (i = 20; i < 100; ++i) { letterCount[i] = tens[(int)i / (int)10] + letterCount[i % 10]; } } int countTens() { int i; int total = 0; for (i = 1; i < 100; ++i) { total += letterCount[i]; } return(total); } int countHundreds(int tensTotal) { int total = 0; int i; for (i = 1; i < 10; ++i) { int hundreds = letterCount[i] + 7; // xx Hundred total += hundreds + (hundreds + 3) * 99 + tensTotal; } return(total); } int problem(int argc, char** argv) { int tensSum; int hundredsSum; int total; populateBase(); populateTens(); tensSum = countTens(); hundredsSum = countHundreds(tensSum); total = tensSum + hundredsSum + letterCount[1] + 8; // Tens + hundreds + "one thousand" printf("Number of letters in numbers from 1 to 1000: %d\n", total); return(0); } int main(int argc, char** argv) { return(problem(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #xx * * <NAME> * * Modification Log: * Date Change * 2013/01/24 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <assert.h> /* * This version is using the GMP library for comparison. * Tested with GMP v5.1.0. Copy the static library and * "gmp.h" header into this directory and then compile * with: * gcc -Wall -g solution_02.c libgmp.a * */ #include "gmp.h" int problem(int argc, char** argv) { int i; char *numStr; mpz_t f; mpz_t r; mpz_init_set_ui(f, 1); mpz_init_set_ui(r, 1); for (i = 1; i < 100; ++i) { mpz_add_ui(f, f, 1); mpz_mul(r, r, f); } numStr = mpz_get_str(NULL, 10, r); printf("%s\n", numStr); return(0); } int main(int argc, char** argv) { return(problem(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #3 * * <NAME> * * Modification Log: * Date Change * 2010/12/03 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> int factor(unsigned long long num) { int i = 2; while( i < num ) { if( num % i == 0 ) { printf("%d ", i); // These help to verify prime of the factors: // printf("("); // factor(i); // printf(") "); factor(num / i); return( i ); } ++i; } printf("%d", i); return( i ); } int main(int argc, char** argv) { // int target = 13195; unsigned long long target = 600851475143ULL; printf("Factoring %llu:\n", target); factor( target ); printf("\n"); return( 0 ); } <file_sep>/* * Solution to Project Euler Problem #36 * * <NAME> * * Modification Log: * Date Change * 2015/10/17 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int problem36(int argc, char** argv) { int i; int p; int cnt = 0; unsigned long sum = 0; const int stop = 1e6; int tmp; for (i = 1; i < stop; ++i) { p = 0; tmp = i; while (tmp > 0) { p = (p * 10) + (tmp % 10); tmp /= 10; } if (p != i) continue; p = 0; tmp = i; while (tmp > 0) { p = (p << 1) | (tmp & 0x1); tmp >>= 1; } if (p != i) continue; // printf("Palindrome found: %d, ", i); cnt++; sum += i; /* tmp = i; while (tmp > 0) { printf("%s", (tmp & 0x1 ? "1" : "0")); tmp >>= 1; } printf("\n"); */ } printf("%d palindromes found under %d with a sum of %lu\n", cnt, stop, sum); return(0); } int main(int argc, char** argv) { return(problem36(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #4 * * <NAME> * * Modification Log: * Date Change * 2010/12/03 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> int testPalindrome(int number) { int i = 0; int len = 0; char string[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; len = sprintf(&string[0], "%d", number); for( i = 0; i < (int)(len/2); ++i ){ if( string[i] != string[len-i-1] ) { return( 0 ); } } return( 1 ); } int main(int argc, char** argv) { int cursor1 = 999; int cursor2 = 999; int largest = 0; int terms[2] = {0, 0}; while( cursor1 > terms[1] ) { cursor2 = cursor1; while( cursor2 > terms[1] ) { if( cursor1 * cursor2 > largest ) { if( testPalindrome( cursor1 * cursor2 ) ) { largest = cursor1 * cursor2; terms[0] = cursor1; terms[1] = cursor2; } } --cursor2; } --cursor1; } printf("Largest palindrome = %d => {%d, %d}\n", largest, terms[0], terms[1]); return( 0 ); } <file_sep>/* * Solution to Project Euler Problem #27 * * <NAME> * * Modification Log: * Date Change * 2013/09/23 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define MAX_NUM (1000) #define BM_SET(b, bm) ((bm)[((b)/8)] |= (0x1 << ((b) % 8))) #define BM_CLR(b, bm) ((bm)[((b)/8)] &= (~(0x1 << ((b) % 8)))) #define BM_IS_SET(b, bm) ((bm)[((b)/8)] & (0x1 << ((b) % 8))) unsigned int bm_max = 0; unsigned char * bm_primes = NULL; int calc_primes(int max) { int i; int j; int cnt = 0; int size = (max >> 3) + 1; bm_primes = (unsigned char *)malloc(size); memset(bm_primes, 0, size); BM_SET(0, bm_primes); BM_SET(1, bm_primes); for (i = 2; i <= max; ++i) { if (!BM_IS_SET(i, bm_primes)) { for (j = 2; (i*j) <= max; ++j) { BM_SET((i*j), bm_primes); } } } for (i = 2; i <= max; ++i) { if (!BM_IS_SET(i, bm_primes)) { // printf("Prime: %d\n", i); cnt++; } } bm_max = max; return(cnt); } int isPrime(int n) { int i; /* Negative, special, or even number */ if (n < 2 || n % 2 == 0) return(0); /* Within the range of the BM of primes */ if (n < bm_max) { return(!BM_IS_SET(n, bm_primes)); } /* Now search using the primes from the BM */ for (i = 3; i < bm_max; i += 2) { if (BM_IS_SET(i, bm_primes)) continue; if (n % i == 0) return(0); } /* Resume where the BM ended */ for (; i < (n/2) + 1; i += 2) { if (n % i == 0) { return(0); } } return(1); } int problem27(int argc, char** argv) { int a; int b; int n; int cnt; int max_num = MAX_NUM; int max_prime_cnt_n = 0; int max_prime_cnt_a = 0; int max_prime_cnt_b = 0; if (argc == 2) { max_num = atoi(argv[1]); if (max_num < 2) { printf("Invalid Max: \"%s\" (%d)\n", argv[1], max_num); return(1); } printf("Setting max number: %d\n", max_num); } cnt = calc_primes(max_num); printf("%d primes under %d\n", cnt, max_num); /* Prime numbers are now determined (any 0 bits in the bitmap) */ for (b = 2; b < max_num; ++b) { /* Non primes are set to 1 in the BM */ /* When n = 0 => b must be a prime alreayd */ if (BM_IS_SET(b, bm_primes)) { continue; } /* If a < -b, then when n = 1, the result would be negative => no prime */ /* a +=2 because when n = 1, (1 + a + b) needs to be an odd number */ for (a = -b; a < max_num; a +=2) { for (n = 1; n < 100; ++n) { if (!isPrime(((n*n) + a*n + b))) { break; } } if (n >= 100) { printf("ERROR: n = %d, (a = %d, b = %d): I don't think it should " "ever get this high\n", n, a, b); } if (n > max_prime_cnt_n) { max_prime_cnt_n = n; max_prime_cnt_a = a; max_prime_cnt_b = b; } } } printf("Largest n = %d when a = %d, b = %d\n", max_prime_cnt_n, max_prime_cnt_a, max_prime_cnt_b); printf("Product of coefficients: %d\n", max_prime_cnt_a * max_prime_cnt_b); if (bm_primes) { free(bm_primes); bm_primes = NULL; } return(0); } int main(int argc, char** argv) { return(problem27(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #39 * * <NAME> * * Modification Log: * Date Change * 2015/10/19 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> int counts[1001] = { 0 }; int problem39(int argc, char** argv) { int i, i_s; int j, j_s; int k; for (i = 1; i < 500; ++i) { i_s = i * i; for (j = i; (j < 1000) && (i + j <= 1000); ++j) { j_s = j * j; k = (int)sqrt(i_s + j_s); if (k * k != i_s + j_s) continue; if (i + j + k > 1000) break; counts[i+j+k]++; } } int max = 0; int max_num = 0; for (i = 1; i <= 1000; ++i) { if (counts[i]) { if (counts[i] > max) { max = counts[i]; max_num = i; } } } printf("%d: %d (%d)\n", max_num, max, counts[max_num]); return(0); } int main(int argc, char** argv) { return(problem39(argc, argv)); } <file_sep> all: a.out run: all ./a.out a.out: solution_01.c gcc -Wall solution_01.c <file_sep>/* * Solution to Project Euler Problem #33 * * <NAME> * * Modification Log: * Date Change * 2015/10/05 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int reduce(int *n, int *d) { int c = 2; while (c <= *n && c <= *d) { if (*n % c == 0 && *d % c == 0) { *n /= c; *d /= c; c = 2; } else { if (c == 2) ++c; else c += 2; } } return(0); } int problem30(int argc, char** argv) { int n, d; int d1, d2, n1, n2; int n_prod = 1; int d_prod = 1; for (d = 99; d > 10; --d) { if (d % 10 == 0) continue; d1 = d % 10; d2 = (d / 10) % 10; for (n = d-1; n > 10; --n) { if (n % 10 == 0) continue; n1 = n%10; n2 = (n / 10) % 10; if (n1 == d1 && (double)n2 / (double)d2 == (double)n / (double)d) { printf("Found candidate: %d / %d == %d%d / %d%d == %d / %d == %f\n", n, d, n2, n1, d2, d1, n2, d2, (double)n / (double)d); reduce(&n2, &d2); printf(" Reduced: %d / %d == %f\n", n2, d2, (double)n2/d2); n_prod *= n2; d_prod *= d2; continue; } else if (n1 == d2 && (double)n2 / (double)d1 == (double)n / (double)d) { printf("Found candidate: %d / %d == %d%d / %d%d == %d / %d == %f\n", n, d, n2, n1, d2, d1, n2, d1, (double)n / (double)d); reduce(&n2, &d1); printf(" Reduced: %d / %d == %f\n", n2, d1, (double)n2/d1); n_prod *= n2; d_prod *= d1; continue; } if (n2 == d1 && (double)n1 / (double)d2 == (double)n / (double)d) { printf("Found candidate: %d / %d == %d%d / %d%d == %d / %d == %f\n", n, d, n2, n1, d2, d1, n1, d2, (double)n / (double)d); reduce(&n1, &d2); printf(" Reduced: %d / %d == %f\n", n1, d2, (double)n1/d2); n_prod *= n1; d_prod *= d2; continue; } else if (n2 == d2 && (double)n1 / (double)d1 == (double)n / (double)d) { printf("Found candidate: %d / %d == %d%d / %d%d == %d / %d == %f\n", n, d, n2, n1, d2, d1, n1, d1, (double)n / (double)d); reduce(&n1, &d1); printf(" Reduced: %d / %d == %f\n", n1, d1, (double)n1/d1); n_prod *= n1; d_prod *= d1; continue; } } } reduce(&n_prod, &d_prod); printf("Denominator product: %d\n", d_prod); return(0); } int main(int argc, char** argv) { return(problem30(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #14 * * <NAME> * * Modification Log: * Date Change * 2012/09/20 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define MAX_START 1000000 unsigned long calcSequence(unsigned long start) { unsigned long cnt = 1; unsigned long num = start; while (num > 1) { if (num % 2 == 0) { // Even number num /= 2; // Divid by 2 } else { // Odd number num = num * 3 + 1; } cnt++; } return(cnt); } int problem(int argc, char** argv) { unsigned long i; unsigned long seqLen = 0; unsigned long longest = 0; unsigned long bestStart = 0; for (i = MAX_START; i > 0; --i) { seqLen = calcSequence(i); if (seqLen >= longest) { longest = seqLen; bestStart = i; } } printf("Longest sequence (%lu) under %d starts at %lu\n", longest, MAX_START, bestStart); return(0); } int main(int argc, char** argv) { return(problem(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #15 * * <NAME> * * Modification Log: * Date Change * 2012/xx/xx Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> unsigned long _recurse(int x, int y, int N) { unsigned long cnt = 0; if (x == N-1 && y == N-1) { // At bottom edge corner cnt = 1; } else if (x == N-1) { // Along right edge cnt += _recurse(x, y+1, N); } else if (y == N-1) { // At bottom edge cnt += _recurse(x+1, y, N); } else { // In the middle or start cnt += _recurse(x+1, y, N); cnt += _recurse(x, y+1, N); } return(cnt); } unsigned long long _tablePropagation(int N) { int i; int k; unsigned long long result = 0; unsigned long long** table = NULL; table = calloc(N, sizeof(unsigned long long *)); for (i = 0; i < N; ++i) { table[i] = calloc(N, sizeof(unsigned long long)); } // Init boundary cases for (i = 0; i < N; ++i) { table[0][i] = 1; table[i][0] = 1; } for (i = 1; i < N; ++i) { // Traverse the diagonal for (k = i; k < N; ++k) { table[i][k] = table[i-1][k] + table[i][k-1]; table[k][i] = table[i][k]; } } result = table[N-1][N-1]; for (i = 0; i < N; ++i) { free(table[i]); table[i] = NULL; } free(table); table = NULL; return(result); } int problem15(int argc, char** argv) { int N = 0; unsigned long long pathCnt = 0; if (argc != 2) { printf("Error: Incorrect parameter count (%d)\n", argc); printf("Usage:\n"); printf(" %s <N = square size>\n", argv[0]); return(1); } N = atoi(argv[1]); if (N < 2) { printf("Error: Invalid size value %d (%s)\n", N, argv[1]); printf("Size must be 2 or larger (N >= 2)\n"); return(1); } // pathCnt = _recurse(0, 0, N); pathCnt = _tablePropagation(N+1); printf("Path count for a %dx%d grid: %llu\n", N, N, pathCnt); return(0); } int main(int argc, char** argv) { return(problem15(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #42 * * <NAME> * * Modification Log: * Date Change * 2017/03/26 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int *triNumbers = NULL; int triNumLast = 0; int growTriangleNumbers(int max) { int n = triNumLast - 1; if (triNumbers && triNumbers[n] > max) return (1); do { triNumLast += 16; triNumbers = realloc(triNumbers, ((triNumLast) * sizeof (int))); for (; n < triNumLast; ++n) triNumbers[n + 1] = triNumbers[n] + n + 1; } while (triNumbers[n - 1] < max); return (1); } int isTriangleNumber(int num) { int n = 1; if (!triNumbers || triNumbers[triNumLast] < num) growTriangleNumbers(num); for (;triNumbers[n] < num; ++n); if (triNumbers[n] == num) return (1); return (0); } int processWord(char *word) { int num = 0; char *ptr = word; for (ptr = word; *ptr != '\0'; ++ptr) { num += (*ptr - 0x40); } if (isTriangleNumber(num)) return (1); return (0); } int problem42(int argc, char** argv) { char buffer[4096]; char *ptr = NULL; char *end = NULL; char *start = NULL; size_t offset = 0; size_t len = 0; int triNumWords = 0; int wordCount = 0; FILE *fp = NULL; char *filename = "p042_words.txt"; printf("Opening file: %s\n", filename); fp = fopen(filename, "r"); if (!fp) { printf("Failed to open source word file: %s\n", filename); return (1); } memset(&buffer[0], 0, sizeof (buffer)); while ((len = fread(&buffer[offset], sizeof (char), sizeof (buffer) - offset, fp))) { ptr = &buffer[0]; end = &buffer[len + offset]; start = NULL; while (ptr < end) { if (*ptr == '"') { if (start) { // Process word wordCount++; start++; *ptr = '\0'; if (processWord(start)) triNumWords++; start = NULL; } else { start = ptr; } } ++ptr; } if (start) { for (ptr = &buffer[0], offset = 0; start < end; ++start, ++ptr, ++offset) { *ptr = *start; } } else { offset = 0; } } fclose(fp); printf("Triangle word count: %d\n", triNumWords); printf("Total word count: %d\n", wordCount); return (0); } int main(int argc, char** argv) { return (problem42(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #40 * * <NAME> * * Modification Log: * Date Change * 2016/04/12 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int problem40(int argc, char** argv) { int i = 1; int j; int num; int product = 1; int order = 1; int order_end = 10; int digit_count = 0; int target_digit = 1; while (1) { if (digit_count + order >= target_digit) { printf("[%4d] order:%d order_end:%d digit_count:%d target:%d\n", i, order, order_end, digit_count, target_digit); num = i; j = digit_count + order - target_digit; printf(" j:%d\n", j); for (; j > 0; --j) num /= 10; int r = num % 10; product *= r; printf(" r:%d product:%d\n", r, product); target_digit *= 10; } digit_count += order; ++i; if (i == order_end) { order += 1; order_end *= 10; } if (digit_count > 1e6) break; } printf("Product: %d\n", product); return(0); } int main(int argc, char** argv) { return(problem40(argc, argv)); } <file_sep> Since we are doing them in numerical order, if we fixed the first digit, that leaves 9 digits that can be iterated in the last 9 positions. Starting with 0 in the most significant position, with 9 remaining digits, that means there are 9! combinations: 9*8*7*6*5*4*3*2*1 362880 If we then used 1 as the first digit, we'd have a new set of 9 to be iterated over, giving us another 362880 combinations. So, iterating through all combinations with 0 & 1 in the first places, we've used nearly 725,000 combinations: 362880*2 725760 If we went all the way through combinations with a 2 in the most significant position, we'd go over our 1 millionth combination: 362880*3 1088640 So, we know that the 1 millionth combination must start with a 2 (0123456789): 2xxxxxxxxx Repeating, for each digit, we work towards the 1 millionth combination. For each value of y in 2yxxxxxxxx, there are 8! possibilities: 8*7*6*5*4*3*2*1 40320 1000000-725760 274240 274240/40320 6 40320*6 241920 725760+241920 967680 After that, we can see that 6 is the next digit in the sequence with 967,680 combinations used (01_3456789): 27xxxxxxxx Repeating for the 3rd digit (7!): 7*6*5*4*3*2*1 5040 1000000-967680 32320 32320/5040 6 5040*6 30240 967680+967680 1935360 967680+30240 997920 With 3rd (01_3456_89): 278xxxxxxx Repeating for the 4th digit (6!): 6*5*4*3*2*1 720 1000000-997920 2080 2080/720 2 720*2 1440 997920+1440 999360 With 4th (01_3456__9): 2783xxxxxx Repeating for the 5th digit (5!): 5*4*3*2*1 120 1000000-999360 640 640/120 5 120*5 600 999360+600 999960 With 5th (01__456__9): 27839xxxxx Repeating for the 6th digit (4!): 4*3*2*1 24 1000000-999960 40 40/24 1 999960+24 999984 With 6th (01__456___): 278391xxxx Repeating for the 7th digit (3!): 3*2*1 6 1000000-999984 16 16/6 2 6*2 12 999984+12 999996 With 7th (0___456___): 2783915xxx Repeating for the 8th digit (2!): 2*1 2 1000000-999996 4 With the 8th (0___4_6___): 27839154xx Since we are now at the millionth, it's the first combination: (0_____6___): 2783915406 Smaller example for thinking through the process: 0,1,2,3 0123 0132 0213 0231 0312 0321 1023 1032 1203 1230 1302 1320 2013 2031 2103 2130 2301 2310 3012 3021 3102 3120 3201 3210 3! = 6 20/6 = 3 0+18 = 18 (0123) -> 3xxx 2! = 2 20-18 = 2 2/2 = 1 (012_) -> 31xx @ 20 (0_2_) -> 3102 --> Wrong, 1 too many (012_) -> 30xx => (_12_) -> 3012 /* vim: set textwidth=80 nu: */ <file_sep>/* * Solution to Project Euler Problem #37 * * <NAME> * * Modification Log: * Date Change * 2015/10/17 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define BM_SET(b, bm) ((bm)[((b)/8)] |= (0x1 << ((b) % 8))) #define BM_CLR(b, bm) ((bm)[((b)/8)] &= (~(0x1 << ((b) % 8)))) #define BM_IS_SET(b, bm) ((bm)[((b)/8)] & (0x1 << ((b) % 8))) unsigned int bm_max = 0; unsigned char * bm_primes = NULL; int calcPrimes(unsigned int max) { unsigned int i; unsigned int j; int cnt = 0; int size = (max >> 3) + 1; bm_primes = (unsigned char *)malloc(size); memset(bm_primes, 0, size); BM_SET(0, bm_primes); BM_SET(1, bm_primes); for (i = 2; i <= max; ++i) { if (!BM_IS_SET(i, bm_primes)) { for (j = 2; (i*j) <= max; ++j) { BM_SET((i*j), bm_primes); } } } for (i = 2; i <= max; ++i) { if (!BM_IS_SET(i, bm_primes)) { // printf("Prime: %d\n", i); cnt++; } } bm_max = max; return(cnt); } int isPrime(unsigned int n) { unsigned int i; /* Negative, special, or even number */ if (n == 2) return(1); if (n < 2 || n % 2 == 0) return(0); /* Within the range of the BM of primes */ if (n < bm_max) { return(!BM_IS_SET(n, bm_primes)); } /* Now search using the primes from the BM */ for (i = 3; i < bm_max; i += 2) { if (BM_IS_SET(i, bm_primes)) continue; if (n % i == 0) return(0); } /* Resume where the BM ended */ for (; i < (n/2) + 1; i += 2) { if (n % i == 0) { return(0); } } return(1); } int problem37(int argc, char** argv) { int i; int r; int cnt = 0; int sum = 0; int tmp; int order; const unsigned int stop = 1e7; calcPrimes(stop); for (i = 11; i < stop && cnt < 11; i += 2) { order = 1; tmp = i; while (tmp > 0) { r = tmp % 10; if (r % 2 == 0 && r != 2) break; // Check "right-to-left" truncated primes" if (!isPrime(tmp)) break; tmp /= 10; order *= 10; } if (tmp) continue; order /= 10; tmp = i; while (order > 1) { if (!isPrime(tmp %= order)) break; order /= 10; } if (order != 1) continue; cnt++; sum += i; // printf("Found matching prime: %d\n", i); } printf("Matching count: %d (i = %d)\n", cnt, i); printf("Sum of all left- and right-truncated primes: %d\n", sum); return(0); } int main(int argc, char** argv) { return(problem37(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #4 * * <NAME> * * Modification Log: * Date Change * 2010/12/03 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int counters[21]; int maxCounts[21]; int factor(unsigned long long num) { int i = 2; while( i < num ) { if( num % i == 0 ) { factor(num / i); ++counters[i]; return( i ); } ++i; } ++counters[num]; return( i ); } int main(int argc, char** argv) { int i = 1; int j = 0; int lcm = 1; memset(&maxCounts[0], 0, 21 * sizeof(int)); for( i = 1; i < 21; ++i ) { memset(&counters[0], 0, 21 * sizeof(int)); factor(i); for( j = 0; j < 21; ++j ) { if( counters[j] > maxCounts[j] ) { maxCounts[j] = counters[j]; } } /* * / printf(" i = %d:\n", i); for( j = 0; j < 21; ++j ) printf("%2d ", j); printf("\n"); for( j = 0; j < 21; ++j ) printf("%2d ", counters[j]); printf("\n"); for( j = 0; j < 21; ++j ) printf("%2d ", maxCounts[j]); printf("\n\n"); / * */ } printf("Max Counts:\n"); for( j = 0; j < 21; ++j ) printf("%2d ", j); printf("\n"); for( j = 0; j < 21; ++j ) printf("%2d ", maxCounts[j]); printf("\n\n"); for( i = 1; i < 21; ++i ) { for( j = 0; j < maxCounts[i]; ++j ) lcm *= i; } printf("lcm = %d;\n", lcm); for( i = 1; i < 21; ++i ) { if( lcm % i != 0 ) printf("Error: %d %% %d = %d;\n", lcm, i, lcm % i); } return( 0 ); } <file_sep>/* * Solution to Project Euler Problem #16 * * <NAME> * * Modification Log: * Date Change * 2011/11/07 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <math.h> #define MAX_NUM_LENGTH (400) #define MAX_EXPONENT_BITS (32) // #define MAX_EXPONENT (0x1 << (MAX_EXPONENT_BITS-1)) #define MAX_EXPONENT 0xffffffff typedef struct BigExponent { // int base; // int exp; int length; char decimal[MAX_NUM_LENGTH]; } BigExponent_t; int max(int a, int b) { if (a > b) return(a); else return(b); } void initNumber(BigExponent_t* number) { if (number) { memset(number, 0, sizeof (BigExponent_t)); number->length = 1; } } char* convertAscii(BigExponent_t* number) { int srcIdx; int dstIdx; if (number == NULL) { printf("Cannot conver number: invalid number object specified (NULL)\n"); return (NULL); } if (number->length > MAX_NUM_LENGTH || number->length < 0) { printf("Cannot convert number: length invalid (%d)\n", number->length); return (NULL); } char *str; if (number->length == 0) { str = calloc(2, sizeof (char)); str[0] = '0'; } else { /* Transpose number and convert to ASCII */ str = calloc(number->length + 1, sizeof (char)); srcIdx = number->length - 1; dstIdx = 0; for (dstIdx = 0; dstIdx < MAX_NUM_LENGTH && srcIdx >= 0; ++dstIdx, --srcIdx) { str[dstIdx] = number->decimal[srcIdx] + 0x30; } } return (str); } BigExponent_t* multiplyNumbers(BigExponent_t *x, BigExponent_t *y, BigExponent_t *result) { if (x == NULL || y == NULL || result == NULL) { return (NULL); } initNumber(result); if (x->length < 0) { printf("X has no digits (%d)\n", x->length); return(result); } if (x->length > MAX_NUM_LENGTH) { printf("X reported as larger than buffer (%d)\n", x->length); return(NULL); } if (y->length < 0) { printf("Y has no digits (%d)\n", y->length); return(result); } if (y->length > MAX_NUM_LENGTH) { printf("Y reported as longer than buffer (%d)\n", y->length); return(NULL); } int idx; int xIdx; int yIdx; for (yIdx = 0; yIdx < y->length; ++yIdx) { for (xIdx = 0; xIdx < x->length; ++xIdx) { idx = yIdx + xIdx; if (idx >= MAX_NUM_LENGTH) { printf("Maximum number length exceeded (%d = %d + %d)\n", idx, yIdx, xIdx); return (NULL); } result->decimal[idx] += (x->decimal[xIdx] * y->decimal[yIdx]); /* Check for and perform carry operation */ for (; idx < MAX_NUM_LENGTH; ++idx) { if (result->decimal[idx] > 9) { /* Need to carry */ /* Check for room to cary */ if (idx == MAX_NUM_LENGTH - 1) { printf("Error: Number limits overflowed (%d)\n", idx); return (NULL); } int ones = result->decimal[idx] % 10; int tens = result->decimal[idx] / 10; result->decimal[idx] = ones; result->decimal[idx+1] += tens; } else { break; } } result->length = max(result->length, idx + 1); } } return (result); } BigExponent_t* squareNumber(BigExponent_t *x, BigExponent_t *result) { return (multiplyNumbers(x, x, result)); } long long int sumDigits(BigExponent_t *x) { long long int sum = 0; if (!x) { printf("No number specified for digit summing\n"); return (-1); } if (x->length > MAX_NUM_LENGTH) { printf("Invalid number length (%d)\n", x->length); return (-1); } int i; for (i = 0; i < x->length; ++i) { sum += x->decimal[i]; } return(sum); } /* These two timer helpers are from: * http://stackoverflow.com/questions/1468596/c-programming-calculate-elapsed-time-in-milliseconds-unix */ /* Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) { long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec); result->tv_sec = diff / 1000000; result->tv_usec = diff % 1000000; return (diff<0); } void timeval_print(struct timeval *tv) { char buffer[30]; time_t curtime; printf("%ld.%06ld", tv->tv_sec, tv->tv_usec); curtime = tv->tv_sec; strftime(buffer, 30, "%m-%d-%Y %T", localtime(&curtime)); printf(" = %s.%06ld\n", buffer, tv->tv_usec); } int problem16(int argc, char** argv) { int exp = 0; if (argc != 2) { printf("Error: Invalid parameter count (%d)\n", argc); printf("%s <2^x power>\n", argv[0]); return(1); } exp = atoi(argv[1]); if (exp < 0) { printf("Error: Invalid exponent specified: %d (%s)\n", exp, argv[1]); return(1); } printf("Captured exponent: %d\n", exp); /* Special case */ if (exp == 0) { printf("1\n"); return (0); } BigExponent_t *working = calloc(1, sizeof(BigExponent_t)); BigExponent_t *result = calloc(1, sizeof(BigExponent_t)); BigExponent_t *final = calloc(1, sizeof(BigExponent_t)); BigExponent_t *swap = NULL; initNumber(working); initNumber(result); initNumber(final); working->decimal[0] = 2; working->length = 1; if (exp & 0x1) { final->decimal[0] = 2; final->length = 1; } else { final->decimal[0] = 1; final->length = 1; } struct timeval tvBegin, tvEnd, tvDiff; gettimeofday(&tvBegin, NULL); int i; int bit = 0x2; int mask = MAX_EXPONENT & (~1); for (i = 2; i < MAX_EXPONENT_BITS; ++i) { /* Still more bits to be checked? */ // printf("mask = %08x, bit = %08x, i = %d\n", mask, bit, i); if (exp & mask) { if ((squareNumber(working, result)) != result) { printf("Failure squaring the working number\n"); return (1); } swap = working; working = result; result = swap; /* Does this bit need to be included in the final */ if (exp & bit) { // printf("Include bit (%d) in final\n", i); if ((multiplyNumbers(final, working, result)) != result) { printf("Failed multiplying the final and working numbers\n"); return (1); } swap = final; final = result; result = swap; } bit <<= 1; mask <<= 1; } else { // printf("No more bits in exponent (mask = %08x, bit = %08x, i = %d)\n", mask, bit, i); break; } } gettimeofday(&tvEnd, NULL); char *str = convertAscii(final); printf("2 ^ %d = %s\n", exp, str); printf("Sum of digits: %lld\n", sumDigits(final)); timeval_subtract(&tvDiff, &tvEnd, &tvBegin); printf("%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec); return(0); } int main(int argc, char** argv) { return(problem16(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #32 * * <NAME> * * Modification Log: * Date Change * 2015/10/02 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int digit_count(int num) { int cnt = 0; while (num > 0) { num /= 10; cnt++; } return(cnt); } int check_digits(int a, int b, int c) { int i, d; int nums[3] = { a, b, c }; int digits[10] = { 0 }; for (i = 0; i < 3; ++i) { while (nums[i] > 0) { d = nums[i] % 10; if (d == 0 || digits[d]) return(0); digits[d] = 1; nums[i] /= 10; } } return(1); } int problem32(int argc, char** argv) { int i, j, k; int cnt = 0; int sum = 0; int i_cnt, j_cnt, r_cnt; int pandigitals[20] = { 0 }; for (i = 1; i < 9999; ++i) { i_cnt = digit_count(i); for (j = i+1; j < 9999; ++j) { j_cnt = digit_count(j); r_cnt = digit_count(i*j); if (i_cnt + j_cnt + r_cnt > 9) break; if (i_cnt + j_cnt + r_cnt < 9) continue; if (check_digits(i, j, i*j)) { int found = 0; for (k = 0; k < 20 && pandigitals[k]; ++k) { if (pandigitals[k] == (i*j)) { found = 1; break; } } if (!found) { printf("Pandigital found: %d * %d = %d\n", i, j, i*j); cnt++; pandigitals[k] = i * j; sum += (i * j); } else { printf("Duplicate found: %d\n", i*j); } } } } printf("Count: %d\n", cnt); printf("Sum: %d\n", sum); return(0); } int main(int argc, char** argv) { return(problem32(argc, argv)); } <file_sep>/* * Solution to Project Euler Problem #14 * * <NAME> * * Modification Log: * Date Change * 2012/05/01 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int printSequence(int num) { int cnt = 0; while (num > 1) { cnt++; printf("%5d -> ", num); if (num % 2 == 1) num = num * 3 + 1; else num = num / 2; if (cnt % 10 == 0) printf("\n"); } if (cnt % 10 != 0) printf(" 1\n"); printf("Count = %d\n", ++cnt); return (cnt); } int main(int argc, char** argv) { if (argc != 2) { printf("Usage: %s <num>\n", argv[0]); return (1); } printSequence(atoi(argv[1])); return(0); } <file_sep>/* * Solution to Project Euler Problem #12 * * <NAME> * * Modification Log: * Date Change * 2011/01/01 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> int factorCount(int sum) { int count = 2; int max = sqrt(sum); int i = 0; if( max == 1 ) { return( count ); } for( i = 2; i <= max; i++ ) { if( sum % i == 0 ) { count += 2; } } if( sqrt(sum) - (int)sqrt(sum) <= 0.0 ) { /* The number has an even square root but was counted * as two factors. */ count--; } return( count ); } int factorPrint(int sum) { int i = 0; printf("Factors for %d:", sum); for( i = 1; i <= sum; i++ ) { if( sum % i == 0 ) { printf(" %d", i ); } } printf("\n"); return( 0 ); } int problem(int argc, char** argv) { int triangleNum = 1; int num = 1; int count = 0; while( 1 ) { num++; triangleNum += num; count = factorCount(triangleNum); // printf("num = %6d; Tn = %8d; count = %4d;\n", num, triangleNum, count); if( count >= 500 ) { break; } } printf("num = %d; triangleNum = %d; count = %d;\n", num, triangleNum, count); factorPrint(triangleNum); return( 0 ); } int main(int argc, char** argv) { return( problem(argc, argv) ); } <file_sep>/* * Solution to Project Euler Problem #xx * * <NAME> * * Modification Log: * Date Change * 2013/02/10 Initial authoring. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define MAX 10000 int problem021(int argc, char** argv) { int i; int j; int a_nums[MAX+1]; int pair_sum = 0; for (i = MAX; i >= 0; --i) { a_nums[i] = 1; } for (i = 2; i <= MAX / 2; ++i) { /* Add in the new divisor */ for (j = (i*2); j <= MAX; j += i) { a_nums[j] += i; } if (a_nums[i] < i) { if (a_nums[a_nums[i]] == i) { /* Found amicable pair */ printf("Amicable pair found: %d (%d) & %d (%d)\n", i, a_nums[i], a_nums[i], a_nums[a_nums[i]]); pair_sum += a_nums[i] + i; } } } for (; i <= MAX; ++i) { if (a_nums[i] < i) { if (a_nums[a_nums[i]] == i) { /* Found amicable pair */ printf("Amicable pair found: %d (%d) & %d (%d)\n", i, a_nums[i], a_nums[i], a_nums[a_nums[i]]); pair_sum += a_nums[i] + i; } } } printf("Sum of all amicable numbers under %d: %d\n", MAX, pair_sum); return(0); } int main(int argc, char** argv) { return(problem021(argc, argv)); }
61a03723b20e101caefe4140558a23f65c476bd5
[ "Makefile", "C", "Python", "Text" ]
50
Python
smb33186/Another-Project-Euler-Work
d387c643ebebe90ce7166e42165536083b0d4074
660381078c96004f4955592bddff6805a55d7f3d
refs/heads/master
<file_sep>#include "push_motor.h" void Push_Wheel_Stop() { TIM_SetCompare1(TIM5,1520); } void Push_Wheel_CW() { TIM_SetCompare1(TIM5,PUSH_CW_SPEED); } void Push_Wheel_CCW() { TIM_SetCompare1(TIM5,PUSH_CCW_SPEED); }<file_sep>#include "Start_Task.h" uint32_t test_dT_1000hz[3],test_rT[6]; static void Loop_1000Hz(void) //1ms执行一次,执行时间大约为 { test_dT_1000hz[0] = test_dT_1000hz[1]; test_rT[3] = test_dT_1000hz[1] = GetSysTime_us (); test_dT_1000hz[2] = (u32)(test_dT_1000hz[1] - test_dT_1000hz[0]) ;//test_dT_1000hz[2] 是该任务时间片周期 ////////////////////////////////////////////////////////////////////// // calibrate_task(); GIMBAL_task(); //保证云台自稳,同时接收控制指令 YAW 左大右小 ;PITCH 抬头小 低头大 ANODT_DATA_Task(); //匿名上位机数据观察 ////////////////////////////////////////////////////////////////////// test_rT[4]= GetSysTime_us (); test_rT[5] = (u32)(test_rT[4] - test_rT[3]) ; //test_rT[5] rT意思是RunTime 即1000HZ时间片里任务的执行时间 } static void Loop_500Hz(void) //2ms执行一次 姿态角速度环、电机输出 { chassis_task();//保证底盘接收控制指令 referee_usart_task(); } static void Loop_200Hz(void) //5ms执行一次 RPY计算、姿态角度环 { referee_tx_task(); //static s16 _tmp = 0; //ANODT_SendF1(_tmp, _tmp+100, _tmp+200); //_tmp += 50; } static void Loop_100Hz(void) //10ms执行一次,执行时间大约为20us 高度速度环、高度环 { // test_rT[0]= GetSysTime_us (); //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // test_rT[1]= GetSysTime_us (); // test_rT[2] = (u32)(test_rT[1] - test_rT[0]) ; //test_rT[2] rT意思是RunTime 即100HZ时间片里任务的执行时间 } static void Loop_50Hz(void) //20ms执行一次 位置速度环 { } static void Loop_20Hz(void) //50ms执行一次 { } static void Loop_2Hz(void) //500ms执行一次 { } //系统任务配置,创建不同执行频率的“线程” static sched_task_t sched_tasks[] = { {Loop_1000Hz,1000, 0, 0}, //void(*task_func)(void); 函数指针 指针就数据类型(int 整形常量,float,指针 地址) {Loop_500Hz , 500, 0, 0}, //uint16_t rate_hz; {Loop_200Hz , 200, 0, 0}, //uint16_t interval_ticks; {Loop_100Hz , 100, 0, 0}, //uint32_t last_run; {Loop_50Hz , 50, 0, 0}, {Loop_20Hz , 20, 0, 0}, {Loop_2Hz , 2, 0, 0}, }; //根据数组长度,判断线程数量 #define TASK_NUM (sizeof(sched_tasks)/sizeof(sched_task_t)) void Scheduler_Setup(void) { uint8_t index = 0; //初始化任务表 for(index=0;index < TASK_NUM;index++) { //计算每个任务的延时周期数 sched_tasks[index].interval_ticks = TICK_PER_SECOND/sched_tasks[index].rate_hz; // TICK_PER_SECOND = 1000 //最短周期为1,也就是1ms if(sched_tasks[index].interval_ticks < 1) { sched_tasks[index].interval_ticks = 1; } } } //这个函数放到main函数的while(1)中,不停判断是否有线程应该执行 void Scheduler_Run(void) { uint8_t index = 0; //循环判断所有线程,是否应该执行 for(index=0;index < TASK_NUM;index++) { //获取系统当前时间,单位MS uint32_t tnow = SysTick_GetTick();//获取到systime_ms的值,该值在Systick_Handler中每1ms递加1 //进行判断,如果当前时间减去上一次执行的时间,大于等于该线程的执行周期,则执行线程 if(tnow - sched_tasks[index].last_run >= sched_tasks[index].interval_ticks) { //更新线程的执行时间,用于下一次判断 sched_tasks[index].last_run = tnow; //执行线程函数,使用的是函数指针 sched_tasks[index].task_func(); } } } <file_sep>#include "adc.h" #include "delay.h" #include "stm32f4xx.h" static uint16_t get_ADC(uint8_t ch); static void temperature_ADC_Reset(void); void temperature_ADC_init(void) { ADC_CommonInitTypeDef ADC_CommonInitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE); RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC1, ENABLE); RCC_APB2PeriphResetCmd(RCC_APB2Periph_ADC1, DISABLE); ADC_TempSensorVrefintCmd(ENABLE); ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent; ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles; ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled; ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div4; ADC_CommonInit(&ADC_CommonInitStructure); temperature_ADC_Reset(); ADC_RegularChannelConfig(ADC1, ADC_Channel_18, 1, ADC_SampleTime_15Cycles); ADC_Cmd(ADC1, ENABLE); } static void temperature_ADC_Reset(void) { ADC_InitTypeDef ADC_InitStructure; ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b; ADC_InitStructure.ADC_ScanConvMode = DISABLE; ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None; ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; ADC_InitStructure.ADC_NbrOfConversion = 1; ADC_Init(ADC1, &ADC_InitStructure); } fp32 get_temprate(void) { uint16_t adcx = 0; static fp32 temperate; temperature_ADC_Reset(); adcx = get_ADC(ADC_Channel_18); temperate = (fp32)adcx * (3.3f / 4096.0f); temperate = (temperate - 0.76f) / 0.0025f + 25.0f; return temperate; } static uint16_t get_ADC(uint8_t ch) { ADC_ClearFlag(ADC1,ADC_FLAG_STRT|ADC_FLAG_OVR|ADC_FLAG_EOC); ADC_RegularChannelConfig(ADC1, ch, 1, ADC_SampleTime_15Cycles); ADC_SoftwareStartConv(ADC1); while (!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC)) { ; } return ADC_GetConversionValue(ADC1); } <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file main.c/h * @brief stm32初始化以及开始任务freeRTOS。h文件定义相关全局宏定义以及 * typedef 一些常用数据类型 * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ #include "main.h" #include "stm32f4xx.h" //test22 #include "adc.h" #include "buzzer.h" #include "can.h" #include "delay.h" #include "flash.h"//test #include "fric.h" #include "laser.h" #include "led.h" #include "power_ctrl.h" #include "rc.h" #include "rng.h" #include "sys.h" #include "timer.h" #include "usart6.h" #include "uart8.h" #include "GM6020_pwm.h" #include "exit_init.h" #include "shoot.h" #include "gimbal_task.h" #include "chassis_task.h" #include "calibrate_task.h" #include "remote_control.h" #include "start_task.h" #include "referee_usart_task.h" #include "user_task.h" #include "LX_IMU.h" #include "Ano_DT.h" #define configTICK_RATE_HZ 1000 void BSP_init(void); int main(void) { BSP_init(); //Board Support Package 硬件初始化(GPIO\DMA\) delay_ms(100);// 保证前面运行 Scheduler_Setup();// 软件(变量)初始化:创建任务(线程)、创建调度器 while (1) { Scheduler_Run(); //运行任务调度器,所有系统功能,除了中断服务函数,都在任务调度器内完成 ; } } //四个24v 输出 依次开启 间隔 709us #define POWER_CTRL_ONE_BY_ONE_TIME 709 void BSP_init(void) { //中断组 4 NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4); //初始化滴答时钟 1ms SysTick中断 中断服务函数位于delay.c delay_init(configTICK_RATE_HZ); //流水灯,红绿灯初始化 led_configuration(); //24输出控制口 初始化 power_ctrl_configuration(); //摩擦轮电机PWM初始化 TIM8 CH3 CH4 fric_PWM_configuration(); //激光IO初始化 laser_configuration(); //蜂鸣器初始化 TIM12 buzzer_init(350, 90); //CAN接口初始化 CAN1_mode_init(CAN_SJW_1tq, CAN_BS2_2tq, CAN_BS1_6tq, 5, CAN_Mode_Normal); //云台初始化 GIMBAL_Setup(); //底盘初始化 chassis_Setup(); //射击任务初始化 shoot_init(); trigger_switch_init(); GM6020_PWM_configuration();//TIM5_CH1 H10 D TIM5_CH2 H11 C 拨轮控制 //24v 输出 依次上电 for (uint8_t i = POWER1_CTRL_SWITCH; i < POWER4_CTRL_SWITCH + 1; i++) { power_ctrl_on(i); delay_us(POWER_CTRL_ONE_BY_ONE_TIME); } remote_control_init(); //USART1 + DMA 遥控器初始化 BSPInit_CompleteBeep(); buzzer_init(30000, 90); Referee_Task_Init(); //USART6 + DMA 裁判系统读取 LX_IMU_UART8_Configuration(500000); //UART8 陀螺仪初始化 ANO_DT_UART7_Configuration(500000); ANODT_DATA_Setup(); LX_ANO_DT_Init(); GPIOF_Exti0_GPIO_Init(); //限位开关外部中断 拨叉二级弹仓内限位开关 F0 I2 GPIOF_Exti1_GPIO_Init(); //限位开关外部中断 拨轮弹仓内限位开关 F1 I1 //定时器6 初始化 //TIM6_Init(60000, 90); //CAN2_mode_init(CAN_SJW_1tq, CAN_BS2_2tq, CAN_BS1_6tq, 5, CAN_Mode_Normal); //flash读取函数,把校准值放回对应参数 //cali_param_init(); //Calibration_Init(); } <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file gimbal_task.c/h * @brief 完成云台控制任务,由于云台使用陀螺仪解算出的角度,其范围在(-pi,pi) * 故而设置目标角度均为范围,存在许多对角度计算的函数。云台主要分为2种 * 状态,陀螺仪控制状态是利用板载陀螺仪解算的姿态角进行控制,编码器控制 * 状态是通过电机反馈的编码值控制的校准,此外还有校准状态,停止状态等。 * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ #ifndef GIMBALTASK_H #define GIMBALTASK_H #include "main.h" #include "CAN_Receive.h" #include "pid.h" #include "remote_control.h" //// 选择陀螺仪 #define IST8310 // 如果使用A板自带的陀螺仪就使能为1 //pitch 速度环 PID参数以及 PID最大输出,积分输出 #define PITCH_SPEED_PID_KP 15000.0f #define PITCH_SPEED_PID_KI 30.0f #define PITCH_SPEED_PID_KD 0.0f #define PITCH_SPEED_PID_MAX_OUT 30000.0f #define PITCH_SPEED_PID_MAX_IOUT 5000.0f #define YAW_SPEED_PID_KP 20000.0f #define YAW_SPEED_PID_KI 40.0f #define YAW_SPEED_PID_KD 2000.0f #define YAW_SPEED_PID_MAX_OUT 30000.0f #define YAW_SPEED_PID_MAX_IOUT 5000.0f //pitch 角度环 角度由陀螺仪解算 PID参数以及 PID最大输出,积分输出 #define PITCH_GYRO_ABSOLUTE_PID_KP 8.0f #define PITCH_GYRO_ABSOLUTE_PID_KI 0.0f #define PITCH_GYRO_ABSOLUTE_PID_KD 0.5f #define PITCH_GYRO_ABSOLUTE_PID_MAX_OUT 10000.0f #define PITCH_GYRO_ABSOLUTE_PID_MAX_IOUT 0.0f //yaw 角度环 角度由陀螺仪解算 PID参数以及 PID最大输出,积分输出 #define YAW_GYRO_ABSOLUTE_PID_KP 25.0f //原10 #define YAW_GYRO_ABSOLUTE_PID_KI 0.0f #define YAW_GYRO_ABSOLUTE_PID_KD 0.4f //0.3 #define YAW_GYRO_ABSOLUTE_PID_MAX_OUT 10.0f //原10 #define YAW_GYRO_ABSOLUTE_PID_MAX_IOUT 0.0f //pitch 角度环 角度由编码器 PID参数以及 PID最大输出,积分输出 #define PITCH_ENCODE_RELATIVE_PID_KP 0.0f #define PITCH_ENCODE_RELATIVE_PID_KI 0.00f #define PITCH_ENCODE_RELATIVE_PID_KD 0.0f #define PITCH_ENCODE_RELATIVE_PID_MAX_OUT 10.0f #define PITCH_ENCODE_RELATIVE_PID_MAX_IOUT 0.0f //yaw 角度环 角度由编码器 PID参数以及 PID最大输出,积分输出 #define YAW_ENCODE_RELATIVE_PID_KP 0.0f #define YAW_ENCODE_RELATIVE_PID_KI 0.0f #define YAW_ENCODE_RELATIVE_PID_KD 0.0f #define YAW_ENCODE_RELATIVE_PID_MAX_OUT 100.0f #define YAW_ENCODE_RELATIVE_PID_MAX_IOUT 0.0f //任务初始化 空闲一段时间 #define GIMBAL_TASK_INIT_TIME 201 //yaw,pitch控制通道以及状态开关通道 #define YawChannel 2 #define PitchChannel 3 #define ModeChannel 0 #define Swing 1 //掉头180 按键 #define TurnKeyBoard KEY_PRESSED_OFFSET_F //掉头云台速度 #define TurnSpeed 0.04f //测试按键尚未使用 #define TestKeyBoard KEY_PRESSED_OFFSET_R //遥控器输入死区,因为遥控器存在差异,摇杆在中间,其值不一定为零 #define RC_deadband 10 //yaw,pitch角度与遥控器输入比例 #define Yaw_RC_SEN -0.000005f #define Pitch_RC_SEN 0.000006f //0.005 //yaw,pitch角度和鼠标输入的比例 #define Yaw_Mouse_Sen 0.000025f #define Pitch_Mouse_Sen -0.000015f //云台编码器控制时候使用的比例 #define Yaw_Encoder_Sen 0.01f #define Pitch_Encoder_Sen 0.01f //云台控制周期 #define GIMBAL_CONTROL_TIME 1 //云台测试模式 宏定义 0 为不使用测试模式 #define GIMBAL_TEST_MODE 0 //电机是否反装 #define PITCH_TURN 0 #define YAW_TURN 0 //电机码盘值最大以及中值 #define Half_ecd_range 4096 #define ecd_range 8191 //云台初始化回中值,允许的误差,并且在误差范围内停止一段时间以及最大时间6s后解除初始化状态, #define GIMBAL_INIT_ANGLE_ERROR 0.1f #define GIMBAL_INIT_STOP_TIME 100 #define GIMBAL_INIT_TIME 6000 //云台初始化回中值的速度以及控制到的角度 #define GIMBAL_INIT_PITCH_SPEED 0.004f #define GIMBAL_INIT_YAW_SPEED 0.005f #define INIT_YAW_SET 0.0f //0代表头朝前 #define INIT_PITCH_SET 0.0f //0代表俯仰水平 //云台校准中值的时候,发送原始电流值,以及堵转时间,通过陀螺仪判断堵转 #define GIMBAL_CALI_MOTOR_SET 8000 #define GIMBAL_CALI_STEP_TIME 2000 #define GIMBAL_CALI_GYRO_LIMIT 0.1f #define GIMBAL_CALI_PITCH_MAX_STEP 1 #define GIMBAL_CALI_PITCH_MIN_STEP 2 #define GIMBAL_CALI_YAW_MAX_STEP 3 #define GIMBAL_CALI_YAW_MIN_STEP 4 #define GIMBAL_CALI_START_STEP GIMBAL_CALI_PITCH_MAX_STEP #define GIMBAL_CALI_END_STEP 5 //云台relative angle offset 根据实际装配来设置偏差 #define GIMBAL_YAW_RELATIVE_ANGLE_OFFSET 7474 //按步兵V2的装配,实际装配偏差 #define GIMBAL_PITCH_RELATIVE_ANGLE_OFFSET 7200 //还没有调Pitch轴,所以值为0 //云台relative angle最大值 根据实际装配来设置最大值 #define GIMBAL_YAW_MAX_RELATIVE_ANGLE 0.2 //rad #define GIMBAL_PITCH_MAX_RELATIVE_ANGLE 0.45 //云台relative angle最小值 根据实际装配来设置最大值 #define GIMBAL_YAW_MIN_RELATIVE_ANGLE -0.2 //rad #define GIMBAL_PITCH_MIN_RELATIVE_ANGLE -0.25 //判断遥控器无输入的时间以及遥控器无输入判断,设置云台yaw回中值以防陀螺仪漂移 #define GIMBAL_MOTIONLESS_RC_DEADLINE 10 #define GIMBAL_MOTIONLESS_TIME_MAX 3000 //电机编码值转化成角度值 #ifndef Motor_Ecd_to_Rad #define Motor_Ecd_to_Rad 0.000766990394f // 2* PI /8192 #endif typedef enum { GIMBAL_MOTOR_RAW = 0, //电机原始值控制 GIMBAL_MOTOR_GYRO, //电机陀螺仪角度控制 GIMBAL_MOTOR_ENCONDE, //电机编码值角度控制 } gimbal_motor_mode_e; typedef struct { fp32 kp; fp32 ki; fp32 kd; fp32 set; fp32 get; fp32 err; fp32 max_out; fp32 max_iout; fp32 Pout; fp32 Iout; fp32 Dout; fp32 out; } Gimbal_PID_t; typedef struct { const motor_measure_t *gimbal_motor_measure; Gimbal_PID_t gimbal_motor_absolute_angle_pid; Gimbal_PID_t gimbal_motor_relative_angle_pid; PidTypeDef gimbal_motor_gyro_pid; gimbal_motor_mode_e gimbal_motor_mode; gimbal_motor_mode_e last_gimbal_motor_mode; uint16_t offset_ecd; fp32 max_relative_angle; //rad fp32 min_relative_angle; //rad fp32 relative_angle; //rad fp32 relative_angle_set; //rad fp32 absolute_angle; //rad fp32 absolute_angle_set; //rad fp32 motor_gyro; //rad/s fp32 motor_gyro_set; fp32 motor_speed; fp32 raw_cmd_current; fp32 current_set; int16_t given_current; } Gimbal_Motor_t; typedef struct { fp32 max_yaw; fp32 min_yaw; fp32 max_pitch; fp32 min_pitch; uint16_t max_yaw_ecd; uint16_t min_yaw_ecd; uint16_t max_pitch_ecd; uint16_t min_pitch_ecd; uint8_t step; } Gimbal_Cali_t; #ifdef WT931 //维特智能IMU 额外买的 接UART8 typedef struct { const RC_ctrl_t *gimbal_rc_ctrl; //遥控器指针 const short *gimbal_INT_angle_point; //short用于维特智能 WT931 IMU const short *gimbal_INT_gyro_point; Gimbal_Motor_t gimbal_yaw_motor; //YAW电机结构体 Gimbal_Motor_t gimbal_pitch_motor; //PITCH电机结构体 Gimbal_Cali_t gimbal_cali; //云台校准结构体 } Gimbal_Control_t; #endif #ifdef IST8310 //A板自带的IMU 用的SPI typedef struct { const RC_ctrl_t *gimbal_rc_ctrl; //遥控器指针 const fp32 *gimbal_INT_angle_point; //IMU角度指针 // fp32用于A板自带IMU const fp32 *gimbal_INT_gyro_point; //IMU的陀螺仪角速度指针 // fp32用于A板自带IMU Gimbal_Motor_t gimbal_yaw_motor; //YAW电机结构体 Gimbal_Motor_t gimbal_pitch_motor; //PITCH电机结构体 Gimbal_Cali_t gimbal_cali; //云台校准结构体 } Gimbal_Control_t; #endif extern const Gimbal_Motor_t *get_yaw_motor_point(void); extern const Gimbal_Motor_t *get_pitch_motor_point(void); extern void GIMBAL_Setup(void); extern void GIMBAL_task(void); extern bool_t cmd_cali_gimbal_hook(uint16_t *yaw_offset, uint16_t *pitch_offset, fp32 *max_yaw, fp32 *min_yaw, fp32 *max_pitch, fp32 *min_pitch); extern void set_cali_gimbal_hook(const uint16_t yaw_offset, const uint16_t pitch_offset, const fp32 max_yaw, const fp32 min_yaw, const fp32 max_pitch, const fp32 min_pitch); #endif <file_sep>#ifndef __LX_IMU_H #define __LX_IMU_H //==引用 #include "main.h" #include "stm32f4xx.h" //==定义/声明 #define FUN_NUM_LEN 256 typedef struct { // void(*fun_frame_send)(void); u8 D_Addr; //目标地址 u8 WTS; //wait to send等待发送标记 // // u16 fre_hz; u16 fre_ms; //发送周期 u16 time_cnt_ms; //计时变量 }_dt_frame_st; //cmd typedef struct { u8 CID; u8 CMD[10]; }_cmd_st; //check typedef struct { u8 ID; u8 SC; u8 AC; }_ck_st; //param typedef struct { u16 par_id; s32 par_val; }_par_st; //data status typedef struct { _dt_frame_st fun[FUN_NUM_LEN]; // u8 wait_ck; // _cmd_st cmd_send; _ck_st ck_send; _ck_st ck_back; _par_st par_data; }_dt_st; enum { ch_1_rol=0, ch_2_pit, ch_3_thr, ch_4_yaw, ch_5_aux1, ch_6_aux2, ch_7_aux3, ch_8_aux4, ch_9_aux5, ch_10_aux6, }; //0x40 typedef struct { s16 ch_[10]; // }__attribute__ ((__packed__)) _rc_ch_st; typedef union { u8 byte_data[20]; _rc_ch_st st_data; }_rc_ch_un; //0x41 typedef struct { s16 rol; s16 pit; s16 thr; s16 yaw_dps; s16 vel_x; s16 vel_y; s16 vel_z; }__attribute__ ((__packed__)) _rt_tar_st; typedef union { u8 byte_data[14]; _rt_tar_st st_data; }_rt_tar_un; //0x0D typedef struct { u16 voltage_100; u16 current_100; }__attribute__ ((__packed__)) _fc_bat_st; typedef union { u8 byte_data[4]; _fc_bat_st st_data; }_fc_bat_un; // typedef struct { u16 pwm_m1; u16 pwm_m2; u16 pwm_m3; u16 pwm_m4; u16 pwm_m5; u16 pwm_m6; u16 pwm_m7; u16 pwm_m8; }_pwm_st; //==数据声明 extern _dt_st dt; extern _rt_tar_un rt_tar; extern _fc_bat_un fc_bat; extern _pwm_st pwm_to_esc; //==函数声明 //static static void ANO_DT_LX_Send_Data(u8 *dataToSend , u8 length); static void ANO_DT_LX_Data_Receive_Anl(u8 *data,u8 len); //public extern void ANO_LX_Task(void); extern void LX_ANO_DT_Init(void); extern const fp32 *get_LX_IMU_angle_point(void); extern const fp32 *get_LX_IMU_gyro_point(void); extern void ANO_LX_Data_Exchange_Task(float dT_s); extern void ANO_DT_LX_Data_Receive_Prepare(u8 data); // extern void CMD_Send(u8 dest_addr,_cmd_st *cmd); extern void CK_Back(u8 dest_addr,_ck_st *ck); extern void PAR_Back(u8 dest_addr,_par_st *par); #endif<file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file shoot.c/h * @brief 射击功能,其中射击的初始化,以及循环都是在云台任务中调用,故而此文件 * 不是freeRTOS任务,射击分关闭状态,准备状态,射击状态,以及完成状态 * 关闭状态是关闭摩擦轮以及激光,准备状态是将子弹拨到微型开关处,射击状 * 态是将子弹射出,判断微型开关值,进入完成状态,完成状态通过判断一定时间 * 微型开关无子弹认为已经将子弹射出。 * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ #include "Shoot.h" #include "CAN_Receive.h" #include "gimbal_behaviour.h" #include "Detect_Task.h" #include "pid.h" #include "laser.h" #include "fric.h" #include "arm_math.h" #include "user_lib.h" #include "delay.h" #define shoot_fric1_on(pwm) fric1_on((pwm)) //摩擦轮1pwm宏定义 #define shoot_fric2_on(pwm) fric2_on((pwm)) //摩擦轮2pwm宏定义 #define shoot_fric_off() fric_off() //关闭两个摩擦轮 #define shoot_laser_on() laser_on() //激光开启宏定义 #define shoot_laser_off() laser_off() //激光关闭宏定义 static const RC_ctrl_t *shoot_rc; //遥控器指针 //static PidTypeDef trigger_motor_pid; //电机PID PidTypeDef push_motor_pid; PidTypeDef shoot_motor_pid; //static Shoot_Motor_t trigger_motor; //射击数据 //Shoot_Motor_t trigger_motor; //射击数据 Shoot_System_t shoot_system; //static shoot_mode_e shoot_mode = SHOOT_STOP; //射击状态机 //shoot_mode_e shoot_mode = SHOOT_STOP; //射击状态机 extern int16_t Push_Can_Set_Current,Shoot_Can_Set_Current; //微动开关IO #define Butten_Trig_Pin GPIO_ReadInputDataBit(GPIOF, GPIO_Pin_10) extern void getTriggerMotorMeasure(motor_measure_t *motor); ///////////////////// static //////////////////////////// //射击状态机设置 static void Shoot_Set_Mode(void); static void Shoot_Mode_Change_Control_Transit(void); //射击数据更新 static void Shoot_Feedback_Update(void); //射击控制量 static void Shoot_Set_Control(void); //PID计算 static void Shoot_Calcualte(void); //射击控制,控制拨弹电机角度,完成一次发射 static void shoot_bullet_control(void); //射击完成控制,判断微动开关一段时间无子弹来判断一次发射 static void shoot_done_control(void); //射击准备控制,将子弹送到微动开关处, static void shoot_ready_control(void); /** * @brief 射击初始化,初始化PID,遥控器指针,电机指针 * @author RM * @param[in] void * @retval 返回空 */ void shoot_init(void) { //拨叉速度PID static const fp32 Shoot_speed_pid[3] = {SHOOT_SPEED_PID_KP, SHOOT_SPEED_PID_KI, SHOOT_SPEED_PID_KD}; //拨轮速度PID static const fp32 Push_speed_pid[3] = { PUSH_SPEED_PID_KP, PUSH_SPEED_PID_KI ,PUSH_SPEED_PID_KD}; //遥控器指针 shoot_system.shoot_rc_ctrl = get_remote_control_point(); shoot_rc = get_remote_control_point(); //拨叉限位开关指针 shoot_system.ShootTrigger = get_switch_point(ShootWheel); //拨轮限位开关指针 shoot_system.PushTrigger = get_switch_point(PushWheel); //拨叉电机指针(2006) shoot_system.shoot_motor.motor_measure = get_Shoot_Motor_Measure_Point(); //模式初始化 shoot_system.push_wheel_motor.mode = SHOOT_STOP; shoot_system.shoot_motor.mode = SHOOT_STOP; //初始化系统时间 shoot_system.sys_time = SysTick_GetTick(); //初始化鼠标模式 shoot_system.mouse.mode = 0; //初始化发射成功标志 shoot_system.shoot_done_flag = 0; //初始化PID PID_Init(&shoot_motor_pid, PID_POSITION, Shoot_speed_pid, SHOOT_SPEED_PID_MAX_OUT, SHOOT_SPEED_PID_MAX_IOUT); PID_Init(&push_motor_pid, PID_POSITION, Push_speed_pid, PUSH_SPEED_PID_MAX_OUT, PUSH_SPEED_PID_MAX_IOUT); //更新数据 Shoot_Feedback_Update(); ramp_init(&shoot_system.fric1_ramp, SHOOT_CONTROL_TIME * 0.001f, Fric_DOWN, Fric_OFF); ramp_init(&shoot_system.fric2_ramp, SHOOT_CONTROL_TIME * 0.001f, Fric_DOWN, Fric_OFF); shoot_system.shoot_motor.ecd_count = 0; shoot_system.shoot_motor.angle = shoot_system.shoot_motor.motor_measure->ecd * Motor_ECD_TO_ANGLE; shoot_system.shoot_motor.given_current = 0; shoot_system.shoot_motor.move_flag = 0; shoot_system.shoot_motor.shoot_count_flag = 0; shoot_system.shoot_motor.set_angle = shoot_system.shoot_motor.angle; shoot_system.shoot_motor.speed = 0.0f; shoot_system.shoot_motor.speed_set = 0.0f; shoot_system.push_wheel_motor.move_flag = 0; // triggshoot_system.pusher_motor.BulletShootCnt = 0; } /** * @brief 射击循环 * @author RM * @param[in] void * @retval 返回can控制值 */ int16_t shoot_control_loop(void) { Shoot_Set_Mode(); //设置状态机 Shoot_Mode_Change_Control_Transit(); Shoot_Feedback_Update(); //更新数据 Shoot_Set_Control(); Shoot_Calcualte(); } /** * @brief 射击状态机设置,遥控器上拨一次开启,再上拨关闭,下拨1次发射1颗,一直处在下,则持续发射,用于3min准备时间清理子弹 * @author RM * @param[in] void * @retval void */ u8 sig = 0; static void Shoot_Set_Mode(void) { //拨下,关闭系统,切换到STOP模式 if((switch_is_down(shoot_system.shoot_rc_ctrl->rc.s[Shoot_RC_Channel]))&& shoot_system.shoot_motor.move_flag == 0) //|| (shoot_system.shoot_rc_ctrl->key.v & SHOOT_OFF_KEYBOARD) { shoot_system.push_wheel_motor.mode = SHOOT_STOP; shoot_system.shoot_motor.mode = SHOOT_STOP; } //拨上或中,启动摩擦轮,拨轮和拨叉不动 if( (switch_is_up(shoot_system.shoot_rc_ctrl->rc.s[Shoot_RC_Channel]) || switch_is_mid(shoot_system.shoot_rc_ctrl->rc.s[Shoot_RC_Channel])) && shoot_system.shoot_motor.move_flag == 0) { shoot_system.push_wheel_motor.mode = SHOOT_WAITING; // 模式切换到等待摩擦轮启动 shoot_system.shoot_motor.mode = SHOOT_WAITING; // 模式切换到等待摩擦轮启动 //启动系统,并切换到空弹模式,启动拨轮开始旋转,转速恒为PUSH_SPEED,拨叉静止不动 if( (shoot_system.fric1_ramp.out == shoot_system.fric1_ramp.max_value && shoot_system.fric2_ramp.out == shoot_system.fric2_ramp.max_value)&& shoot_system.shoot_motor.move_flag == 0 ) { shoot_system.push_wheel_motor.mode = AMMO_OUT; // 模式切换到空载 shoot_system.shoot_motor.mode = AMMO_OUT; // 模式切换到空载 } //系统启动后,若检测到一级弹舱限位开关触发,拨轮立即停止旋转,拨叉开始旋转进弹 if (shoot_system.PushTrigger->trigger_state == 1 && shoot_system.shoot_motor.move_flag == 0 ) { shoot_system.push_wheel_motor.mode = SHOOT_INIT; shoot_system.shoot_motor.mode = SHOOT_INIT; } //二级弹舱限位开关触发后,拨叉立即停止旋转,子弹已经进入二级弹舱就绪,使能鼠标功能,等待发射指令 if (shoot_system.ShootTrigger->trigger_state == 1 && shoot_system.shoot_motor.last_mode != SHOOTING ) { sig = 1; shoot_system.shoot_motor.mode = SHOOT_READY; shoot_system.push_wheel_motor.mode = SHOOT_READY; shoot_system.shoot_motor.set_angle = shoot_system.shoot_motor.angle; shoot_system.shoot_motor.set_angle = rad_format(shoot_system.shoot_motor.set_angle + PI); //shoot_system.mouse.mode = 1; if ( shoot_system.shoot_motor.move_flag == 0 && shoot_system.mouse.press_l == 1 && shoot_system.mouse.last_press_l == 1 // shoot_system.mouse.mode == 1 ) { shoot_system.shoot_motor.mode = SHOOTING; shoot_system.shoot_motor.move_flag = 1; } } } } static void Shoot_Mode_Change_Control_Transit(void) { shoot_system.shoot_motor.last_mode = shoot_system.shoot_motor.mode; shoot_system.push_wheel_motor.last_mode = shoot_system.push_wheel_motor.mode; } static void Shoot_Feedback_Update(void) { //////////////2006电机 拨叉 static fp32 speed_fliter_1 = 0.0f; static fp32 speed_fliter_2 = 0.0f; static fp32 speed_fliter_3 = 0.0f; //拨弹轮电机速度滤波一下 static const fp32 fliter_num[3] = {1.725709860247969f, -0.75594777109163436f, 0.030237910843665373f}; //二阶低通滤波 speed_fliter_1 = speed_fliter_2; speed_fliter_2 = speed_fliter_3; speed_fliter_3 = speed_fliter_2 * fliter_num[0] + speed_fliter_1 * fliter_num[1] + (shoot_system.shoot_motor.motor_measure->speed_rpm * Motor_RMP_TO_SPEED) * fliter_num[2]; shoot_system.shoot_motor.speed = -speed_fliter_3; //电机圈数重置, 因为输出轴旋转一圈, 电机轴旋转 36圈,将电机轴数据处理成输出轴数据,用于控制输出轴角度 if (shoot_system.shoot_motor.motor_measure->ecd - shoot_system.shoot_motor.motor_measure->last_ecd > Half_ecd_range) { shoot_system.shoot_motor.ecd_count--; } else if (shoot_system.shoot_motor.motor_measure->ecd - shoot_system.shoot_motor.motor_measure->last_ecd < -Half_ecd_range) { shoot_system.shoot_motor.ecd_count++; } if (shoot_system.shoot_motor.ecd_count == FULL_COUNT) { shoot_system.shoot_motor.ecd_count = -(FULL_COUNT - 1); } else if (shoot_system.shoot_motor.ecd_count == -FULL_COUNT) { shoot_system.shoot_motor.ecd_count = FULL_COUNT - 1; } //计算输出轴角度 shoot_system.shoot_motor.angle = -((shoot_system.shoot_motor.ecd_count * ecd_range + shoot_system.shoot_motor.motor_measure->ecd) * Motor_ECD_TO_ANGLE); //鼠标按键 shoot_system.mouse.last_press_l = shoot_system.mouse.press_l; shoot_system.mouse.last_press_r = shoot_system.mouse.press_r; shoot_system.mouse.press_l = shoot_system.shoot_rc_ctrl->mouse.press_l; shoot_system.mouse.press_r = shoot_rc->mouse.press_r; //长按计时 if (shoot_system.mouse.press_l) { if (shoot_system.mouse.press_l_time < PRESS_LONG_TIME) { shoot_system.mouse.press_l_time++; } } else { shoot_system.mouse.press_l_time = 0; } if (shoot_system.mouse.press_r) { if (shoot_system.mouse.press_r_time < PRESS_LONG_TIME) { shoot_system.mouse.press_r_time++; } } else { shoot_system.mouse.press_r_time = 0; } //射击开关下档时间计时 if (shoot_system.shoot_motor.mode != SHOOT_STOP && switch_is_down(shoot_system.shoot_rc_ctrl->rc.s[Shoot_RC_Channel])) { if (shoot_system.mouse.rc_s_time < RC_S_LONG_TIME) { shoot_system.mouse.rc_s_time++; } } else { shoot_system.mouse.rc_s_time = 0; } } u8 sisi1 = 0; u8 sisi2 = 0; static void Shoot_Set_Control(void) { if ((shoot_system.push_wheel_motor.mode == SHOOT_STOP && shoot_system.shoot_motor.mode == SHOOT_STOP) || (shoot_system.push_wheel_motor.mode == SHOOT_READY && shoot_system.shoot_motor.mode == SHOOT_READY)) // && shoot_system.shoot_motor.move_flag == 0) { shoot_system.push_wheel_motor.move_flag = 0; shoot_system.shoot_motor.speed_set = 0.0f; //BUGLIST1 if (shoot_system.push_wheel_motor.mode == SHOOT_STOP && shoot_system.shoot_motor.mode == SHOOT_STOP) { shoot_system.fric1_ramp.out = Fric_OFF; shoot_system.fric2_ramp.out = Fric_OFF; } } if (shoot_system.push_wheel_motor.mode == AMMO_OUT && shoot_system.shoot_motor.mode == AMMO_OUT) { shoot_system.push_wheel_motor.move_flag = 1; shoot_system.shoot_motor.speed_set = 0.0f; } if (shoot_system.push_wheel_motor.mode == SHOOT_INIT && shoot_system.shoot_motor.mode == SHOOT_INIT) { shoot_system.push_wheel_motor.move_flag = 0; shoot_system.shoot_motor.speed_set = SHOOT_SPEED; } if( shoot_system.shoot_motor.mode == SHOOTING || shoot_system.shoot_motor.move_flag == 1 ) { shoot_system.shoot_motor.shoot_count_flag++; shoot_system.shoot_motor.speed_set = SHOOT_SPEED; if( shoot_system.shoot_motor.shoot_count_flag >= 1000) { shoot_system.shoot_motor.move_flag = 0; shoot_system.shoot_motor.shoot_count_flag = 0; shoot_system.push_wheel_motor.mode = SHOOT_INIT; shoot_system.shoot_motor.mode = SHOOT_INIT; shoot_system.PushTrigger->trigger_state = 0; shoot_system.ShootTrigger->trigger_state = 0; shoot_system.mouse.mode = 0; //发射完后失能,等待下一个子弹准备就绪 } // if ( shoot_system.shoot_motor.set_angle > shoot_system.shoot_motor.angle) // { // if (shoot_system.shoot_motor.set_angle - shoot_system.shoot_motor.angle > 0.05f) // { // //没到达,因此一直设置旋转速度 // shoot_system.shoot_motor.speed_set = SHOOT_SPEED; // } // else // { // shoot_system.push_wheel_motor.mode = SHOOT_INIT; // shoot_system.shoot_motor.mode = SHOOT_INIT; // shoot_system.shoot_motor.move_flag = 0; // shoot_system.PushTrigger->trigger_state = 0; // shoot_system.ShootTrigger->trigger_state = 0; // //shoot_system.mouse.mode = 0; //发射完后失能,等待下一个子弹准备就绪 // } // } // else if(shoot_system.shoot_motor.set_angle < shoot_system.shoot_motor.angle) // { // if (shoot_system.shoot_motor.angle - shoot_system.shoot_motor.set_angle > 0.05f) // { // //没到达,因此一直设置旋转速度 // sisi2 =1; // shoot_system.shoot_motor.speed_set = SHOOT_SPEED; // } // else // { // sisi2 = 1; // shoot_system.push_wheel_motor.mode = SHOOT_INIT; // shoot_system.shoot_motor.mode = SHOOT_INIT; // shoot_system.shoot_motor.move_flag = 0; // shoot_system.PushTrigger->trigger_state = 0; // shoot_system.ShootTrigger->trigger_state = 0; // //shoot_system.mouse.mode = 0; //发射完后失能,等待下一个子弹准备就绪 // } // } // } } static void Shoot_Calcualte(void) { //摩擦轮pwm static uint16_t fric_pwm1 = Fric_OFF; static uint16_t fric_pwm2 = Fric_OFF; if(shoot_system.push_wheel_motor.mode == SHOOT_STOP && shoot_system.shoot_motor.mode == SHOOT_STOP) { shoot_fric_off(); Push_Wheel_Stop(); Shoot_Can_Set_Current = 0; } else { //shoot_laser_on(); //激光开启 //摩擦轮需要一个个斜波开启,不能同时直接开启,否则可能电机不转 ramp_calc(&shoot_system.fric1_ramp, SHOOT_FRIC_PWM_ADD_VALUE); //第一个摩擦轮开启后,再开启第二个摩擦轮 if(shoot_system.fric1_ramp.out == shoot_system.fric1_ramp.max_value) { ramp_calc(&shoot_system.fric2_ramp, SHOOT_FRIC_PWM_ADD_VALUE); } //摩擦轮还未完全启动或未启动时,拨叉和拨轮停止转动 if( shoot_system.fric2_ramp.out != shoot_system.fric2_ramp.max_value) { shoot_system.shoot_motor.speed_set = 0.0f; shoot_system.push_wheel_motor.move_flag = 0; } fric_pwm1 = (uint16_t)(shoot_system.fric1_ramp.out); fric_pwm2 = (uint16_t)(shoot_system.fric2_ramp.out); shoot_fric1_on(fric_pwm1); shoot_fric2_on(fric_pwm2); // //鼠标右键按下加速摩擦轮,使得左键低速射击, 右键高速射击 // static uint16_t up_time = 0; // if (shoot_system.mouse.press_r) // { // up_time = UP_ADD_TIME; // } // if (up_time > 0) // { // shoot_system.fric1_ramp.max_value = Fric_UP; // shoot_system.fric2_ramp.max_value = Fric_UP; // up_time--; // } // else // { // shoot_system.fric1_ramp.max_value = Fric_DOWN; // shoot_system.fric2_ramp.max_value = Fric_DOWN; // } //计算拨弹轮电机PID PID_Calc(&shoot_motor_pid, shoot_system.shoot_motor.speed, shoot_system.shoot_motor.speed_set); shoot_system.shoot_motor.given_current = (int16_t)(shoot_motor_pid.out); #if SHOOT_MOTOR_TURN Shoot_Can_Set_Current = -shoot_system.shoot_motor.given_current; #else Shoot_Can_Set_Current = shoot_system.shoot_motor.given_current; #endif if(shoot_system.push_wheel_motor.move_flag == 1) { #if PUSH_MOTOR_TURN Push_Wheel_CCW(); #else Push_Wheel_CW(); #endif } else { Push_Wheel_Stop(); } } } /** * @brief 射击控制,控制拨弹电机角度,完成一次发射 * @author RM * @param[in] void * @retval void */ //static void shoot_bullet_control(void) //{ // //子弹射出判断 //// if (trigger_motor.key == SWITCH_TRIGGER_OFF) //// { //// trigger_motor.shoot_done = 1; //// trigger_motor.shoot_done_time = 0; //// shoot_mode = SHOOT_DONE; //// trigger_motor.set_angle = trigger_motor.angle; //// } // //每次拨动 1/4PI的角度 // if (trigger_motor.move_flag == 0 && shoot_mode == SHOOT_BULLET) // { // trigger_motor.set_angle = rad_format(trigger_motor.set_angle + PI_Four); // trigger_motor.cmd_time = SysTick_GetTick(); // trigger_motor.move_flag = 1; // } // //到达角度判断 // if (rad_format(trigger_motor.set_angle - trigger_motor.angle) > 0.05f) // { // //没到达一直设置旋转速度 // trigger_motor.speed_set = TRIGGER_SPEED; // trigger_motor.run_time = SysTick_GetTick(); // //堵转判断 // if (trigger_motor.run_time - trigger_motor.cmd_time > BLOCK_TIME && // trigger_motor.run_time - trigger_motor.cmd_time < REVERSE_TIME + BLOCK_TIME && // fabs(trigger_motor.speed) < REVERSE_SPEED_LIMIT) // { // trigger_motor.speed_set = -TRIGGER_SPEED; // } // else if (trigger_motor.run_time - trigger_motor.cmd_time > REVERSE_TIME + BLOCK_TIME || fabs(trigger_motor.speed) > REVERSE_SPEED_LIMIT) // { // trigger_motor.cmd_time = SysTick_GetTick(); // } // } // else // { // trigger_motor.move_flag = 0; // } //} ///** // * @brief 射击完成控制,判断微动开关一段时间无子弹来判断一次发射 // * @author RM // * @param[in] void // * @retval void // */ //static void shoot_done_control(void) //{ // trigger_motor.speed_set = 0.0f; // //射击完成判断,判断微动开关一段时间无子弹 // if (trigger_motor.key == SWITCH_TRIGGER_OFF) // { // if (trigger_motor.shoot_done_time < SHOOT_DONE_KEY_OFF_TIME) // { // trigger_motor.shoot_done_time++; // } // else if (trigger_motor.shoot_done_time == SHOOT_DONE_KEY_OFF_TIME) // { // trigger_motor.BulletShootCnt++; // shoot_mode = SHOOT_READY; // } // } // else // { // shoot_mode = SHOOT_BULLET; // } //} ///** // * @brief 射击准备控制,将子弹送到微动开关处, // * @author RM // * @param[in] void // * @retval void // */ //static void shoot_ready_control(void) //{ // if (trigger_motor.shoot_done) // { // trigger_motor.shoot_done = 0; // } // if (trigger_motor.key == SWITCH_TRIGGER_ON) // { // //判断子弹到达微动开关处 // trigger_motor.set_angle = trigger_motor.angle; // trigger_motor_pid.out = 0.0f; // trigger_motor_pid.Iout = 0.0f; // trigger_motor.speed_set = 0.0f; // trigger_motor.move_flag = 0; // trigger_motor.key_time = 0; // } // else if (trigger_motor.key == SWITCH_TRIGGER_OFF && trigger_motor.key_time < KEY_OFF_JUGUE_TIME) // { // //判断无子弹一段时间 // trigger_motor.key_time++; // } // else if (trigger_motor.key == SWITCH_TRIGGER_OFF && trigger_motor.key_time == KEY_OFF_JUGUE_TIME) // { // //微动开关一段时间没有子弹,进入拨弹,一次旋转 1/10PI的角度 // if (trigger_motor.move_flag == 0) // { // trigger_motor.set_angle = rad_format(trigger_motor.set_angle + PI_Ten); // trigger_motor.cmd_time = SysTick_GetTick(); // trigger_motor.move_flag = 1; // } // if (rad_format(trigger_motor.set_angle - trigger_motor.angle) > 0.05f) // { // //角度达到判断 // trigger_motor.speed_set = Ready_Trigger_Speed; // trigger_motor.run_time = SysTick_GetTick(); // //堵转判断 // if (trigger_motor.run_time - trigger_motor.cmd_time > BLOCK_TIME && trigger_motor.run_time - trigger_motor.cmd_time < REVERSE_TIME + BLOCK_TIME && fabs(trigger_motor.speed) < REVERSE_SPEED_LIMIT) // { // trigger_motor.speed_set = -Ready_Trigger_Speed; // } // else if (trigger_motor.run_time - trigger_motor.cmd_time > REVERSE_TIME + BLOCK_TIME || fabs(trigger_motor.speed) > REVERSE_SPEED_LIMIT) // { // trigger_motor.cmd_time = SysTick_GetTick(); // } // } // else // { // trigger_motor.move_flag = 0; // } // } //} <file_sep>#ifndef __UART7_H__ #define __UART7_H__ #include "main.h" #include <stm32f4xx.h> void ANO_DT_UART7_Configuration(u32 bound); void Uart7_IRQ ( void ); void UART7_Put_Buf( unsigned char *DataToSend, u8 data_num ); #endif <file_sep>#ifndef ROBOMASTER_PROTOCOL_H #define ROBOMASTER_PROTOCOL_H //#include "struct_typedef.h" #include "stm32f4xx.h" #define HEADER_SOF 0xA5 #define REF_PROTOCOL_FRAME_MAX_SIZE 128 #define REF_PROTOCOL_DATA_MAX_SIZE 113 #define REF_PROTOCOL_HEADER_SIZE sizeof(frame_header_struct_t) #define REF_PROTOCOL_CMD_SIZE 2 #define REF_PROTOCOL_CRC16_SIZE 2 #define REF_HEADER_CRC_LEN (REF_PROTOCOL_HEADER_SIZE + REF_PROTOCOL_CRC16_SIZE) #define REF_HEADER_CRC_CMDID_LEN (REF_PROTOCOL_HEADER_SIZE + REF_PROTOCOL_CRC16_SIZE + sizeof(uint16_t)) #define REF_HEADER_CMDID_LEN (REF_PROTOCOL_HEADER_SIZE + sizeof(uint16_t)) #pragma pack(push, 1) //5字节帧头结构体 typedef __packed struct { uint8_t SOF; uint16_t data_length; uint8_t seq; uint8_t CRC8; } frame_header_struct_t; //5字节帧头,偏移位置 typedef enum { SOF = 0,//起始位 DATA_LENGTH = 1,//帧内数据长度,根据这个来获取数据长度 SEQ = 3,//包序号 CRC8 = 4 //CRC8 }FrameHeaderOffset; typedef enum { FRAME_HEADER = 0, CMD_ID = 5, DATA = 7, }JudgeFrameOffset; /***************命令码ID********************/ /* ID: 0x0001 Byte: 3 比赛状态数据 发送频率 1HZ ID: 0x0002 Byte: 1 比赛结果数据 比赛结束后发送 ID: 0x0003 Byte: 32 比赛机器人存活数据 1Hz发送 ID: 0x0004 Byte: 3 飞镖发射状态 飞镖发射时发送 ID: 0x0101 Byte: 4 场地事件数据 1HZ ID: 0x0102 Byte: 4 场地补给站动作标识数据 动作改变后发送 ID: 0X0104 Byte: 2 裁判警告数据 警告发生后发送 ID: 0X0105 Byte: 1 飞镖发射口倒计时 1HZ ID: 0X0201 Byte: 18 机器人状态数据 10Hz ID: 0X0202 Byte: 16 实时功率热量数据 50Hz ID: 0x0203 Byte: 16 机器人位置数据 10Hz ID: 0x0204 Byte: 1 机器人增益数据 1HZ ID: 0x0205 Byte: 3 空中机器人能量状态数据 10Hz,只有空中机器人主控发送 ID: 0x0206 Byte: 1 伤害状态数据 伤害发生后发送 ID: 0x0207 Byte: 6 实时射击数据 子弹发射后发送 ID: 0x0208 Byte: 2 弹丸剩余发射数 1HZ,仅空中机器人发送 ID: 0x0209 Byte: 4 机器人RFID状态 1HZ ID: 0x020A Byte: 12 飞镖机器人客户端指令数据 10HZ ID: 0x0301 Byte: n 机器人间交互数据 发送方触发发送 */ typedef enum { GAME_STATE_CMD_ID = 0x0001, //比赛状态数据 GAME_RESULT_CMD_ID = 0x0002, //比赛结果数据 GAME_ROBOT_HP_CMD_ID = 0x0003, //比赛机器人存活数据 MISSILE_STATUS = 0x0004, //飞镖发射状态 FIELD_EVENTS_CMD_ID = 0x0101, //场地事件数据 SUPPLY_PROJECTILE_ACTION_CMD_ID = 0x0102, //场地补给站动作标识数据 //Q1:2020/5更新的裁判系统协议里没有0x0103这一项 SUPPLY_PROJECTILE_BOOKING_CMD_ID = 0x0103, REFEREE_WARNING_CMD_ID = 0x0104, //裁判警告数据 MISSILE_SILO_COUNT = 0x0105, //飞镖发射口倒计时 ROBOT_STATE_CMD_ID = 0x0201, //机器人状态数据 POWER_HEAT_DATA_CMD_ID = 0x0202, //实时功率热量数据 ROBOT_POS_CMD_ID = 0x0203, //机器人位置数据 BUFF_MUSK_CMD_ID = 0x0204, //机器人增益数据 AERIAL_ROBOT_ENERGY_CMD_ID = 0x0205, //空中机器人能量状态数据 ROBOT_HURT_CMD_ID = 0x0206, //伤害状态数据 SHOOT_DATA_CMD_ID = 0x0207, //实时射击数据 BULLET_REMAINING_CMD_ID = 0x0208, //弹丸剩余发射数 RFID_STATUS = 0x0209, //机器人RFID状态 MISSILE_LAUCNH_SIGNAL = 0x020A, //飞镖机器人客户端指令数据 STUDENT_INTERACTIVE_DATA_CMD_ID = 0x0301, //机器人间交互数据 IDCustomData, }referee_cmd_id_t; typedef enum { STEP_HEADER_SOF = 0, STEP_LENGTH_LOW = 1, STEP_LENGTH_HIGH = 2, STEP_FRAME_SEQ = 3, STEP_HEADER_CRC8 = 4, STEP_DATA_CRC16 = 5, } unpack_step_e; typedef enum { DELETE_GRAPHIC = 0x0100, DRAW_ONE = 0x0101, DRAW_TWO = 0x0102, DRAW_FIVE = 0x0103, DRAW_SEVEN = 0x0104, DRAW_WORDS = 0x0110, } interactive_client_draw_data_cmd_id_e; typedef struct { frame_header_struct_t *p_header; uint16_t data_len; uint8_t protocol_packet[REF_PROTOCOL_FRAME_MAX_SIZE]; unpack_step_e unpack_step; uint16_t index; } unpack_data_t; /* ID: 0x0001 Byte: 3 比赛状态数据 */ typedef enum { RED_HERO = 1, RED_ENGINEER = 2, RED_STANDARD_1 = 3, RED_STANDARD_2 = 4, RED_STANDARD_3 = 5, RED_AERIAL = 6, RED_SENTRY = 7, RED_RADAR = 9, BLUE_HERO = 101, BLUE_ENGINEER = 102, BLUE_STANDARD_1 = 103, BLUE_STANDARD_2 = 104, BLUE_STANDARD_3 = 105, BLUE_AERIAL = 106, BLUE_SENTRY = 107, BLUE_RADAR = 109, } robot_id_t; typedef enum { RED_HERO_Client = 0x0101, RED_ENGINEER_Client = 0x0102, RED_STANDARD_1_Client = 0x0103, RED_STANDARD_2_Client = 0x0104, RED_STANDARD_3_Client = 0x0105, RED_AERIAL_Client = 0x0106, BLUE_HERO_Client = 0x0165, BLUE_ENGINEER_Client = 0x0166, BLUE_STANDARD_1_Client = 0x0167, BLUE_STANDARD_2_Client = 0x0168, BLUE_STANDARD_3_Client = 0x0169, BLUE_AERIAL_Client = 0x016A, } PC_client_id_t; typedef enum { PROGRESS_UNSTART = 0, PROGRESS_PREPARE = 1, PROGRESS_SELFCHECK = 2, PROGRESS_5sCOUNTDOWN = 3, PROGRESS_BATTLE = 4, PROGRESS_CALCULATING = 5, } game_progress_t; // 数据结构体 typedef __packed struct //0x0001 3字节,24位 { uint8_t game_type : 4; uint8_t game_progress : 4; uint16_t stage_remain_time; } ext_game_state_t; typedef __packed struct //0x0002 1字节 { uint8_t winner; } ext_game_result_t; typedef __packed struct//0x0003 32字节 { uint16_t red_1_robot_HP; uint16_t red_2_robot_HP; uint16_t red_3_robot_HP; uint16_t red_4_robot_HP; uint16_t red_5_robot_HP; uint16_t red_7_robot_HP; uint16_t red_base_HP; uint16_t blue_1_robot_HP; uint16_t blue_2_robot_HP; uint16_t blue_3_robot_HP; uint16_t blue_4_robot_HP; uint16_t blue_5_robot_HP; uint16_t blue_7_robot_HP; uint16_t blue_base_HP; } ext_game_robot_HP_t; typedef __packed struct //0x0101 4字节 { uint32_t event_type; } ext_event_data_t; typedef __packed struct //0x0102 4字节 { uint8_t supply_projectile_id; uint8_t supply_robot_id; uint8_t supply_projectile_step; uint8_t supply_projectile_num; } ext_supply_projectile_action_t; typedef __packed struct //0x0103 { uint8_t supply_projectile_id; uint8_t supply_robot_id; uint8_t supply_num; } ext_supply_projectile_booking_t; typedef __packed struct //0x104 2字节 { uint8_t level; uint8_t foul_robot_id; } ext_referee_warning_t; typedef __packed struct //0x0201 18字节 { uint8_t robot_id; uint8_t robot_level; uint16_t remain_HP; uint16_t max_HP; uint16_t shooter_heat0_cooling_rate; uint16_t shooter_heat0_cooling_limit; uint16_t shooter_heat1_cooling_rate; uint16_t shooter_heat1_cooling_limit; uint8_t mains_power_gimbal_output : 1; uint8_t mains_power_chassis_output : 1; uint8_t mains_power_shooter_output : 1; } ext_game_robot_state_t; typedef __packed struct //0x0202 { uint16_t chassis_volt; uint16_t chassis_current; float chassis_power; uint16_t chassis_power_buffer; uint16_t shooter_heat0; uint16_t shooter_heat1; } ext_power_heat_data_t; typedef __packed struct //0x0203 { float x; float y; float z; float yaw; } ext_game_robot_pos_t; typedef __packed struct //0x0204 { uint8_t power_rune_buff; } ext_buff_musk_t; typedef __packed struct //0x0205 { uint8_t energy_point; uint8_t attack_time; } aerial_robot_energy_t; typedef __packed struct //0x0206 { uint8_t armor_type : 4; uint8_t hurt_type : 4; } ext_robot_hurt_t; typedef __packed struct //0x0207 { uint8_t bullet_type; uint8_t bullet_freq; float bullet_speed; } ext_shoot_data_t; typedef __packed struct { uint8_t bullet_remaining_num; } ext_bullet_remaining_t; typedef __packed struct //0x0301 { uint16_t data_cmd_id; uint16_t send_ID; uint16_t receiver_ID; } ext_student_interactive_header_data_t; typedef __packed struct //0x0301 { ext_student_interactive_header_data_t header_data; uint16_t data_len; uint8_t *data; } ext_student_interactive_data_t; typedef __packed struct { uint8_t data[REF_PROTOCOL_DATA_MAX_SIZE]; }robot_interactive_data_t; typedef __packed struct { uint8_t operate_type; //0:空操作 1:删除图层 2:删除所有 uint8_t layer; //图层0 - 9 }ext_client_custom_graphic_delete_t; typedef __packed struct { uint8_t graphic_name[3]; uint32_t operate_type:3; uint32_t graphic_type:3; uint32_t layer:4; uint32_t color:4; uint32_t start_angle:9; uint32_t end_angle:9; uint32_t width:10; uint32_t start_x:11; uint32_t start_y:11; uint32_t radius:10; uint32_t end_x:11; uint32_t end_y:11; }graphic_data_struct_t; typedef __packed struct { graphic_data_struct_t graphic_data_struct; }ext_client_custom_graphic_single_t; typedef __packed struct { graphic_data_struct_t graphic_data_struct[2]; }ext_client_custom_graphic_double_t; typedef __packed struct { graphic_data_struct_t graphic_data_struct[5]; }ext_client_custom_graphic_five_t; typedef __packed struct { graphic_data_struct_t graphic_data_struct[7]; }ext_client_custom_graphic_seven_t; typedef __packed struct { graphic_data_struct_t graphic_data_struct; uint8_t data[30]; }ext_client_custom_character_t; //机器人交互信息 cmd_id = 0x301,内容id = 0x0200 - 0x02FF typedef __packed struct { frame_header_struct_t txFrameHeader;//帧头 uint16_t CmdID;//命令码 ext_student_interactive_header_data_t dataFrameHeader;//数据段头结构 robot_interactive_data_t interactData;//数据段 uint16_t FrameTail;//帧尾 }ext_RobotCommunication_t; //客户端交互信息 cmd_id = 0x301,内容id = 0x0100 typedef __packed struct { frame_header_struct_t txFrameHeader;//帧头 uint16_t CmdID;//命令码 ext_student_interactive_header_data_t dataFrameHeader;//数据段头结构 ext_client_custom_graphic_single_t interactData;//数据段 uint16_t FrameTail;//帧尾 }ext_Client_Communication_custom_graphic_single_t; typedef __packed struct { float data1; float data2; float data3; uint8_t data4; } custom_data_t; typedef __packed struct { uint8_t data[64]; } ext_up_stream_data_t; typedef __packed struct { uint8_t data[32]; } ext_download_stream_data_t; #pragma pack(pop) #endif //ROBOMASTER_PROTOCOL_H <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file gimbal_task.c/h * @brief 完成云台控制任务,由于云台使用陀螺仪解算出的角度,其范围在(-pi,pi) * 故而设置目标角度均为范围,存在许多对角度计算的函数。云台主要分为2种 * 状态,陀螺仪控制状态是利用板载陀螺仪解算的姿态角进行控制,编码器控制 * 状态是通过电机反馈的编码值控制的校准,此外还有校准状态,停止状态等。 * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2019 BDT**************************** */ /************************* 头文件 ******************************/ #include "Gimbal_Task.h" #include "main.h" #include "arm_math.h" #include "gimbal_behaviour.h" #include "user_lib.h" #include "INS_Task.h" #include "remote_control.h" #include "shoot.h" #include "CAN_Receive.h" #include "Detect_Task.h" #include "pid.h" #include "delay.h" #include "LX_IMU.h" /************************* 宏定义 ******************************************************************/ //电机编码值规整 0—8191 #define ECD_Format(ecd) \ { \ if ((ecd) > ecd_range) \ (ecd) -= ecd_range; \ else if ((ecd) < 0) \ (ecd) += ecd_range; \ } #define gimbal_total_pid_clear(gimbal_clear) \ { \ Gimbal_PID_clear(&(gimbal_clear)->gimbal_yaw_motor.gimbal_motor_absolute_angle_pid); \ Gimbal_PID_clear(&(gimbal_clear)->gimbal_yaw_motor.gimbal_motor_relative_angle_pid); \ PID_clear(&(gimbal_clear)->gimbal_yaw_motor.gimbal_motor_gyro_pid); \ \ Gimbal_PID_clear(&(gimbal_clear)->gimbal_pitch_motor.gimbal_motor_absolute_angle_pid); \ Gimbal_PID_clear(&(gimbal_clear)->gimbal_pitch_motor.gimbal_motor_relative_angle_pid); \ PID_clear(&(gimbal_clear)->gimbal_pitch_motor.gimbal_motor_gyro_pid); \ } /*********************** 全局变量定义 ***************************************************************/ //云台控制所有相关数据 Gimbal_Control_t gimbal_control; //发送的can 指令 //static int16_t Yaw_Can_Set_Current = 0, Pitch_Can_Set_Current = 0, Shoot_Can_Set_Current = 0; int16_t Yaw_Can_Set_Current = 0, Pitch_Can_Set_Current = 0,Shoot_Can_Set_Current = 0; /*********************** 静态函数声明 ***************************************************************/ //云台初始化 static void GIMBAL_Init(Gimbal_Control_t *gimbal_init); //云台pid清零 static void Gimbal_PID_clear(Gimbal_PID_t *gimbal_pid_clear); //云台状态设置 static void GIMBAL_Set_Mode(Gimbal_Control_t *gimbal_set_mode); //云台数据更新 static void GIMBAL_Feedback_Update(Gimbal_Control_t *gimbal_feedback_update); //云台状态切换保存数据,例如从陀螺仪状态切换到编码器状态保存目标值 static void GIMBAL_Mode_Change_Control_Transit(Gimbal_Control_t *gimbal_mode_change); //计算云台电机相对中值的相对角度 static fp32 motor_ecd_to_angle_change(uint16_t ecd, uint16_t offset_ecd); //设置云台控制量 static void GIMBAL_Set_Contorl(Gimbal_Control_t *gimbal_set_control); //云台控制pid计算 static void GIMBAL_Control_loop(Gimbal_Control_t *gimbal_control_loop); static void gimbal_motor_absolute_angle_control(Gimbal_Motor_t *gimbal_motor); static void gimbal_motor_relative_angle_control(Gimbal_Motor_t *gimbal_motor); static void gimbal_motor_raw_angle_control(Gimbal_Motor_t *gimbal_motor); //在陀螺仪角度控制下,对控制的目标值进限制以防超最大相对角度 static void GIMBAL_absolute_angle_limit(Gimbal_Motor_t *gimbal_motor, fp32 add); static void GIMBAL_relative_angle_limit(Gimbal_Motor_t *gimbal_motor, fp32 *add); static void GIMBAL_PID_Init(Gimbal_PID_t *pid, fp32 maxout, fp32 intergral_limit, fp32 kp, fp32 ki, fp32 kd); static fp32 GIMBAL_PID_Calc(Gimbal_PID_t *pid, fp32 get, fp32 set, fp32 error_delta); static void calc_gimbal_cali(const Gimbal_Cali_t *gimbal_cali, uint16_t *yaw_offset, uint16_t *pitch_offset, fp32 *max_yaw, fp32 *min_yaw, fp32 *max_pitch, fp32 *min_pitch); /*********************** 函数定义 *********************************************************************************/ void GIMBAL_Setup(void) { //云台初始化 GIMBAL_Init(&gimbal_control); //判断电机是否都上线 // while (toe_is_error(YawGimbalMotorTOE) || toe_is_error(PitchGimbalMotorTOE) || toe_is_error(TriggerMotorTOE) ) // { // delay_ms(GIMBAL_CONTROL_TIME); // GIMBAL_Feedback_Update(&gimbal_control); //云台数据反馈 // } } void GIMBAL_task(void) { GIMBAL_Set_Mode(&gimbal_control); //设置云台行为状态机 -> 设置云台电机状态机 -> 从而控制运动模式 GIMBAL_Mode_Change_Control_Transit(&gimbal_control); //控制模式切换 控制数据过渡 GIMBAL_Feedback_Update(&gimbal_control); //更新yaw和pitch的absolute_angle绝对角度、relative_angle相对角度、motor_gyro角速度 GIMBAL_Set_Contorl(&gimbal_control); //通过遥控器数据得到yaw和pitch的relative_angle_set/absolute_angle_set GIMBAL_Control_loop(&gimbal_control); //云台yaw和pitch两轴的串级PID计算 shoot_control_loop(); //射击任务控制循环 #if YAW_TURN //YAW电机是否反装 Yaw_Can_Set_Current = -gimbal_control.gimbal_yaw_motor.given_current; #else Yaw_Can_Set_Current = gimbal_control.gimbal_yaw_motor.given_current; #endif #if PITCH_TURN //PITCH电机是否反装 Pitch_Can_Set_Current = -gimbal_control.gimbal_pitch_motor.given_current; #else Pitch_Can_Set_Current = gimbal_control.gimbal_pitch_motor.given_current; #endif //云台在遥控器掉线状态即relax 状态,can指令为0,不使用current设置为零的方法,是保证遥控器掉线一定使得云台停止 // if (!(toe_is_error(YawGimbalMotorTOE) && toe_is_error(PitchGimbalMotorTOE) && toe_is_error(TriggerMotorTOE))) // { // if (toe_is_error(DBUSTOE)) // { // CAN_CMD_GIMBAL(0, 0, 0, 0); // } // else // { // CAN_CMD_GIMBAL(Yaw_Can_Set_Current, Pitch_Can_Set_Current, Shoot_Can_Set_Current, 0); // } // } CAN_CMD_GIMBAL(Yaw_Can_Set_Current, Pitch_Can_Set_Current, Shoot_Can_Set_Current, 0 ); } /** * @brief 云台校准设置,将校准的云台中值以及最小最大机械相对角度 * @author RM * @param[in] yaw 中值 * @param[in] pitch 中值 * @param[in] yaw 最大相对角度 * @param[in] yaw 最小相对角度 * @param[in] pitch 最大相对角度 * @param[in] pitch 最小相对角度 * @retval 返回空 * @waring 这个函数使用到gimbal_control 静态变量导致函数不适用以上通用指针复用 */ void set_cali_gimbal_hook(const uint16_t yaw_offset, const uint16_t pitch_offset, const fp32 max_yaw, const fp32 min_yaw, const fp32 max_pitch, const fp32 min_pitch) { gimbal_control.gimbal_yaw_motor.offset_ecd = yaw_offset; gimbal_control.gimbal_yaw_motor.max_relative_angle = max_yaw; gimbal_control.gimbal_yaw_motor.min_relative_angle = min_yaw; gimbal_control.gimbal_pitch_motor.offset_ecd = pitch_offset; gimbal_control.gimbal_pitch_motor.max_relative_angle = max_pitch; gimbal_control.gimbal_pitch_motor.min_relative_angle = min_pitch; } /** * @brief 云台校准计算,将校准记录的最大 最小值 来计算云台 中值和最大最小机械角度 * @author RM * @param[in] yaw 中值 指针 * @param[in] pitch 中值 指针 * @param[in] yaw 最大相对角度 指针 * @param[in] yaw 最小相对角度 指针 * @param[in] pitch 最大相对角度 指针 * @param[in] pitch 最小相对角度 指针 * @retval 返回1 代表成功校准完毕, 返回0 代表未校准完 * @waring 这个函数使用到gimbal_control 静态变量导致函数不适用以上通用指针复用 */ bool_t cmd_cali_gimbal_hook(uint16_t *yaw_offset, uint16_t *pitch_offset, fp32 *max_yaw, fp32 *min_yaw, fp32 *max_pitch, fp32 *min_pitch) { if (gimbal_control.gimbal_cali.step == 0) { gimbal_control.gimbal_cali.step = GIMBAL_CALI_START_STEP; //保存进入时候的数据,作为起始数据,来判断最大,最小值 gimbal_control.gimbal_cali.max_pitch = gimbal_control.gimbal_pitch_motor.absolute_angle; gimbal_control.gimbal_cali.max_pitch_ecd = gimbal_control.gimbal_pitch_motor.gimbal_motor_measure->ecd; gimbal_control.gimbal_cali.max_yaw = gimbal_control.gimbal_yaw_motor.absolute_angle; gimbal_control.gimbal_cali.max_yaw_ecd = gimbal_control.gimbal_yaw_motor.gimbal_motor_measure->ecd; gimbal_control.gimbal_cali.min_pitch = gimbal_control.gimbal_pitch_motor.absolute_angle; gimbal_control.gimbal_cali.min_pitch_ecd = gimbal_control.gimbal_pitch_motor.gimbal_motor_measure->ecd; gimbal_control.gimbal_cali.min_yaw = gimbal_control.gimbal_yaw_motor.absolute_angle; gimbal_control.gimbal_cali.min_yaw_ecd = gimbal_control.gimbal_yaw_motor.gimbal_motor_measure->ecd; return 0; } else if (gimbal_control.gimbal_cali.step == GIMBAL_CALI_END_STEP) { calc_gimbal_cali(&gimbal_control.gimbal_cali, yaw_offset, pitch_offset, max_yaw, min_yaw, max_pitch, min_pitch); gimbal_control.gimbal_yaw_motor.offset_ecd = *yaw_offset; gimbal_control.gimbal_yaw_motor.max_relative_angle = *max_yaw; gimbal_control.gimbal_yaw_motor.min_relative_angle = *min_yaw; gimbal_control.gimbal_pitch_motor.offset_ecd = *pitch_offset; gimbal_control.gimbal_pitch_motor.max_relative_angle = *max_pitch; gimbal_control.gimbal_pitch_motor.min_relative_angle = *min_pitch; return 1; } else { return 0; } } //校准计算,相对最大角度,云台中值 static void calc_gimbal_cali(const Gimbal_Cali_t *gimbal_cali, uint16_t *yaw_offset, uint16_t *pitch_offset, fp32 *max_yaw, fp32 *min_yaw, fp32 *max_pitch, fp32 *min_pitch) { if (gimbal_cali == NULL || yaw_offset == NULL || pitch_offset == NULL || max_yaw == NULL || min_yaw == NULL || max_pitch == NULL || min_pitch == NULL) { return; } int16_t temp_max_ecd = 0, temp_min_ecd = 0, temp_ecd = 0; #if YAW_TURN temp_ecd = gimbal_cali->min_yaw_ecd - gimbal_cali->max_yaw_ecd; if (temp_ecd < 0) { temp_ecd += ecd_range; } temp_ecd = gimbal_cali->max_yaw_ecd + (temp_ecd / 2); ECD_Format(temp_ecd); *yaw_offset = temp_ecd; *max_yaw = -motor_ecd_to_angle_change(gimbal_cali->max_yaw_ecd, *yaw_offset); *min_yaw = -motor_ecd_to_angle_change(gimbal_cali->min_yaw_ecd, *yaw_offset); #else temp_ecd = gimbal_cali->max_yaw_ecd - gimbal_cali->min_yaw_ecd; if (temp_ecd < 0) { temp_ecd += ecd_range; } temp_ecd = gimbal_cali->max_yaw_ecd - (temp_ecd / 2); ECD_Format(temp_ecd); *yaw_offset = temp_ecd; *max_yaw = motor_ecd_to_angle_change(gimbal_cali->max_yaw_ecd, *yaw_offset); *min_yaw = motor_ecd_to_angle_change(gimbal_cali->min_yaw_ecd, *yaw_offset); #endif #if PITCH_TURN temp_ecd = (int16_t)(gimbal_cali->max_pitch / Motor_Ecd_to_Rad); temp_max_ecd = gimbal_cali->max_pitch_ecd + temp_ecd; temp_ecd = (int16_t)(gimbal_cali->min_pitch / Motor_Ecd_to_Rad); temp_min_ecd = gimbal_cali->min_pitch_ecd + temp_ecd; ECD_Format(temp_max_ecd); ECD_Format(temp_min_ecd); temp_ecd = temp_max_ecd - temp_min_ecd; if (temp_ecd > Half_ecd_range) { temp_ecd -= ecd_range; } else if (temp_ecd < -Half_ecd_range) { temp_ecd += ecd_range; } if (temp_max_ecd > temp_min_ecd) { temp_min_ecd += ecd_range; } temp_ecd = temp_max_ecd - temp_ecd / 2; ECD_Format(temp_ecd); *pitch_offset = temp_ecd; *max_pitch = -motor_ecd_to_angle_change(gimbal_cali->max_pitch_ecd, *pitch_offset); *min_pitch = -motor_ecd_to_angle_change(gimbal_cali->min_pitch_ecd, *pitch_offset); #else temp_ecd = (int16_t)(gimbal_cali->max_pitch / Motor_Ecd_to_Rad); temp_max_ecd = gimbal_cali->max_pitch_ecd - temp_ecd; temp_ecd = (int16_t)(gimbal_cali->min_pitch / Motor_Ecd_to_Rad); temp_min_ecd = gimbal_cali->min_pitch_ecd - temp_ecd; ECD_Format(temp_max_ecd); ECD_Format(temp_min_ecd); temp_ecd = temp_max_ecd - temp_min_ecd; if (temp_ecd > Half_ecd_range) { temp_ecd -= ecd_range; } else if (temp_ecd < -Half_ecd_range) { temp_ecd += ecd_range; } temp_ecd = temp_max_ecd - temp_ecd / 2; ECD_Format(temp_ecd); *pitch_offset = temp_ecd; *max_pitch = motor_ecd_to_angle_change(gimbal_cali->max_pitch_ecd, *pitch_offset); *min_pitch = motor_ecd_to_angle_change(gimbal_cali->min_pitch_ecd, *pitch_offset); #endif } const Gimbal_Motor_t *get_yaw_motor_point(void) { return &gimbal_control.gimbal_yaw_motor; } const Gimbal_Motor_t *get_pitch_motor_point(void) { return &gimbal_control.gimbal_pitch_motor; } u8 chous7 = 0; /************************************ GIMBAL_Init ****************************************************/ //初始化pid 数据指针 static void GIMBAL_Init(Gimbal_Control_t *gimbal_init) { /*** YAW,PITCH的PID参数 ****/ static const fp32 Pitch_speed_pid[3] = {PITCH_SPEED_PID_KP, PITCH_SPEED_PID_KI, PITCH_SPEED_PID_KD}; static const fp32 Yaw_speed_pid[3] = {YAW_SPEED_PID_KP, YAW_SPEED_PID_KI, YAW_SPEED_PID_KD}; /**** 电机数据指针获取 ****/ //motor_yaw结构体变量,存放Yaw云台电机的实时反馈 gimbal_init->gimbal_yaw_motor.gimbal_motor_measure = get_Yaw_Gimbal_Motor_Measure_Point(); //motor_pit结构体变量,存放Pitch云台电机的实时反馈 gimbal_init->gimbal_pitch_motor.gimbal_motor_measure = get_Pitch_Gimbal_Motor_Measure_Point(); /**** 陀螺仪数据指针获取 ****/ //INS_Angle[]存放yaw,pitch,roll的实时值 gimbal_init->gimbal_INT_angle_point = get_LX_IMU_angle_point(); //INS_gyro[]存放三轴角速度实时值 gimbal_init->gimbal_INT_gyro_point = get_LX_IMU_gyro_point(); /**** 遥控器数据指针获取 ****/ //rc_ctrl结构体,存放遥控器实时通道值 gimbal_init->gimbal_rc_ctrl = get_remote_control_point(); /**** 初始化电机模式 ****/ gimbal_init->gimbal_yaw_motor.gimbal_motor_mode = gimbal_init->gimbal_yaw_motor.last_gimbal_motor_mode = GIMBAL_MOTOR_RAW; gimbal_init->gimbal_pitch_motor.gimbal_motor_mode = gimbal_init->gimbal_pitch_motor.last_gimbal_motor_mode = GIMBAL_MOTOR_RAW; /**** 初始化YAW和Pitch的PID 并清除所有PID输出值和期望、反馈 ****/ //初始化yaw电机绝对角度环PID GIMBAL_PID_Init(&gimbal_init->gimbal_yaw_motor.gimbal_motor_absolute_angle_pid, \ YAW_GYRO_ABSOLUTE_PID_MAX_OUT, YAW_GYRO_ABSOLUTE_PID_MAX_IOUT,\ YAW_GYRO_ABSOLUTE_PID_KP,YAW_GYRO_ABSOLUTE_PID_KI, YAW_GYRO_ABSOLUTE_PID_KD); //初始化yaw电机相对角度环PID GIMBAL_PID_Init(&gimbal_init->gimbal_yaw_motor.gimbal_motor_relative_angle_pid,\ YAW_ENCODE_RELATIVE_PID_MAX_OUT, YAW_ENCODE_RELATIVE_PID_MAX_IOUT,\ YAW_ENCODE_RELATIVE_PID_KP,YAW_ENCODE_RELATIVE_PID_KI, YAW_ENCODE_RELATIVE_PID_KD); //初始化yaw电机角速度环PID PID_Init(&gimbal_init->gimbal_yaw_motor.gimbal_motor_gyro_pid, PID_POSITION, Yaw_speed_pid,\ YAW_SPEED_PID_MAX_OUT, YAW_SPEED_PID_MAX_IOUT); //初始化pitch电机绝对角度环PID GIMBAL_PID_Init(&gimbal_init->gimbal_pitch_motor.gimbal_motor_absolute_angle_pid,\ PITCH_GYRO_ABSOLUTE_PID_MAX_OUT, PITCH_GYRO_ABSOLUTE_PID_MAX_IOUT,\ PITCH_GYRO_ABSOLUTE_PID_KP, PITCH_GYRO_ABSOLUTE_PID_KI, PITCH_GYRO_ABSOLUTE_PID_KD); //初始化pitch电机相对角度环PID GIMBAL_PID_Init(&gimbal_init->gimbal_pitch_motor.gimbal_motor_relative_angle_pid,\ PITCH_ENCODE_RELATIVE_PID_MAX_OUT, PITCH_ENCODE_RELATIVE_PID_MAX_IOUT,\ PITCH_ENCODE_RELATIVE_PID_KP, PITCH_ENCODE_RELATIVE_PID_KI, PITCH_ENCODE_RELATIVE_PID_KD); //初始化pitch电机角速度环PID PID_Init(&gimbal_init->gimbal_pitch_motor.gimbal_motor_gyro_pid, PID_POSITION, Pitch_speed_pid,\ PITCH_SPEED_PID_MAX_OUT, PITCH_SPEED_PID_MAX_IOUT); //清除云台PID的期望、反馈、输出值,全部清零,防止开机乱跑 gimbal_total_pid_clear(gimbal_init); /**** 根据实际装配结果来设置偏差offset和最大最小限位 ****/ //设置云台relative angle的offset,根据实际装配结果来调试 gimbal_init->gimbal_yaw_motor.offset_ecd = GIMBAL_YAW_RELATIVE_ANGLE_OFFSET; //去除了校准任务,自行设置校准量 2019-11-21 0:25:25 Stone gimbal_init->gimbal_pitch_motor.offset_ecd = GIMBAL_PITCH_RELATIVE_ANGLE_OFFSET; //去除了校准任务,自行设置校准量 2019-11-21 0:25:25 Stone //设置云台relative angle最大值和最小值 即机械限位最大值 gimbal_init->gimbal_yaw_motor.max_relative_angle = GIMBAL_YAW_MAX_RELATIVE_ANGLE; gimbal_init->gimbal_yaw_motor.min_relative_angle = GIMBAL_YAW_MIN_RELATIVE_ANGLE; gimbal_init->gimbal_pitch_motor.max_relative_angle = GIMBAL_PITCH_MAX_RELATIVE_ANGLE; gimbal_init->gimbal_pitch_motor.min_relative_angle = GIMBAL_PITCH_MIN_RELATIVE_ANGLE; /**** 更新yaw和pitch的absolute_angle绝对角度、relative_angle相对角度、motor_gyro角速度 ****/ GIMBAL_Feedback_Update(gimbal_init); //更新YAW和PITCH期望为现在的反馈 gimbal_init->gimbal_yaw_motor.absolute_angle_set = gimbal_init->gimbal_yaw_motor.absolute_angle; gimbal_init->gimbal_yaw_motor.relative_angle_set = gimbal_init->gimbal_yaw_motor.relative_angle; gimbal_init->gimbal_yaw_motor.motor_gyro_set = gimbal_init->gimbal_yaw_motor.motor_gyro; gimbal_init->gimbal_pitch_motor.absolute_angle_set = gimbal_init->gimbal_pitch_motor.absolute_angle; gimbal_init->gimbal_pitch_motor.relative_angle_set = gimbal_init->gimbal_pitch_motor.relative_angle; gimbal_init->gimbal_pitch_motor.motor_gyro_set = gimbal_init->gimbal_pitch_motor.motor_gyro; chous7 = 1; } /************************************ 1.GIMBAL_Set_Mode ****************************************************/ //第一层GIMBAL_Set_Mode(Gimbal_Control_t *gimbal_set_mode) [gimbal_task.c static] //第二层 gimbal_behaviour_mode_set(gimbal_set_mode) // 根据gimbal_behaviour的值去给gimbal_control->gimbal_yaw_motor.gimbal_motor_mode赋值 [gimbal_behaviour.c global] // 根据gimbal_behaviour的值去给gimbal_control->gimbal_pitch_motor.gimbal_motor_mode赋值 // 如下3种状态值 // GIMBAL_MOTOR_RAW = 0, //电机原始值控制 // GIMBAL_MOTOR_GYRO, //电机陀螺仪角度控制 // GIMBAL_MOTOR_ENCONDE, //电机编码值角度控制 //第三层 gimbal_behaviour_set(gimbal_mode_set) 根据gimbal_control->gimbal_rc_ctrl->rc.s[ModeChannel] // 用于给全局变量gimbal_behaviour赋值 [gimbal_behaviour.c static] // 如下6种状态值 // GIMBAL_ZERO_FORCE = 0, //云台无力 // GIMBAL_INIT=1 //云台初始化 // GIMBAL_CALI=2 //云台校准 // GIMBAL_ABSOLUTE_ANGLE=3 //云台陀螺仪绝对角度控制 // GIMBAL_RELATIVE_ANGLE=4,//云台编码值相对角度控制 // GIMBAL_MOTIONLESS=5 //云台在遥控器无输入一段时间后保持不动,避免陀螺仪漂移 static void GIMBAL_Set_Mode(Gimbal_Control_t *gimbal_set_mode) { //检测是否输入是否为空指针 //如果是,则返回,防止错误设置云台模式 if (gimbal_set_mode == NULL) { return; } gimbal_behaviour_mode_set(gimbal_set_mode); } /**************************** 2.GIMBAL_Mode_Change_Control_Transit 云台状态切换保存,用于状态切换过渡****************************/ static void GIMBAL_Mode_Change_Control_Transit(Gimbal_Control_t *gimbal_mode_change) { //1.检测是否输入是否为空指针 //如果是,则返回,防止错误设置云台模式 if (gimbal_mode_change == NULL) { return; } //2.yaw电机状态机切换保存数据 //RAW模式 保存电流期望,赋值为当前给定电流 if (gimbal_mode_change->gimbal_yaw_motor.last_gimbal_motor_mode != GIMBAL_MOTOR_RAW && gimbal_mode_change->gimbal_yaw_motor.gimbal_motor_mode == GIMBAL_MOTOR_RAW) { gimbal_mode_change->gimbal_yaw_motor.raw_cmd_current = gimbal_mode_change->gimbal_yaw_motor.current_set = gimbal_mode_change->gimbal_yaw_motor.given_current; } //底盘跟随模式 保存绝对角度期望,赋值为当前绝对角度 else if (gimbal_mode_change->gimbal_yaw_motor.last_gimbal_motor_mode != GIMBAL_MOTOR_GYRO && gimbal_mode_change->gimbal_yaw_motor.gimbal_motor_mode == GIMBAL_MOTOR_GYRO) { gimbal_mode_change->gimbal_yaw_motor.absolute_angle_set = gimbal_mode_change->gimbal_yaw_motor.absolute_angle; } //底盘不跟随模式 保存相对角度期望,赋值为当前相对角度 else if (gimbal_mode_change->gimbal_yaw_motor.last_gimbal_motor_mode != GIMBAL_MOTOR_ENCONDE && gimbal_mode_change->gimbal_yaw_motor.gimbal_motor_mode == GIMBAL_MOTOR_ENCONDE) { gimbal_mode_change->gimbal_yaw_motor.relative_angle_set = gimbal_mode_change->gimbal_yaw_motor.relative_angle; } //状态保存 gimbal_mode_change->gimbal_yaw_motor.last_gimbal_motor_mode = gimbal_mode_change->gimbal_yaw_motor.gimbal_motor_mode; //3.pitch电机状态机切换保存数据 //RAW模式 保存电流期望,赋值为当前给定电流 if (gimbal_mode_change->gimbal_pitch_motor.last_gimbal_motor_mode != GIMBAL_MOTOR_RAW && gimbal_mode_change->gimbal_pitch_motor.gimbal_motor_mode == GIMBAL_MOTOR_RAW) { gimbal_mode_change->gimbal_pitch_motor.raw_cmd_current = gimbal_mode_change->gimbal_pitch_motor.current_set = gimbal_mode_change->gimbal_pitch_motor.given_current; } //底盘跟随模式 保存绝对角度期望,赋值为当前绝对角度 else if (gimbal_mode_change->gimbal_pitch_motor.last_gimbal_motor_mode != GIMBAL_MOTOR_GYRO && gimbal_mode_change->gimbal_pitch_motor.gimbal_motor_mode == GIMBAL_MOTOR_GYRO) { gimbal_mode_change->gimbal_pitch_motor.absolute_angle_set = gimbal_mode_change->gimbal_pitch_motor.absolute_angle; } //底盘不跟随模式 保存相对角度期望,赋值为当前相对角度 else if (gimbal_mode_change->gimbal_pitch_motor.last_gimbal_motor_mode != GIMBAL_MOTOR_ENCONDE && gimbal_mode_change->gimbal_pitch_motor.gimbal_motor_mode == GIMBAL_MOTOR_ENCONDE) { gimbal_mode_change->gimbal_pitch_motor.relative_angle_set = gimbal_mode_change->gimbal_pitch_motor.relative_angle; } //状态保存 gimbal_mode_change->gimbal_pitch_motor.last_gimbal_motor_mode = gimbal_mode_change->gimbal_pitch_motor.gimbal_motor_mode; } /********************************** 3.GIMBAL_Feedback_Update 更新yaw和pitch的absolute_angle绝对角度、relative_angle相对角度、motor_gyro角速度 ****************************************************/ static void GIMBAL_Feedback_Update(Gimbal_Control_t *gimbal_feedback_update) { if (gimbal_feedback_update == NULL) { return; } /*************************************** 云台数据更新 ***********************************************************************************************/ //功能解释: //更新yaw和pitch的absolute_angle绝对角度、relative_angle相对角度、motor_gyro角速度 /*****************************************************************************************************************************************************/ //参数解释: //gimbal_feedback_update->gimbal_INT_angle_point == INS_Angle 注:INS_Angle是INS_Angle[]数组首元素地址 //INS_Angle[0]:yaw实时解算值,INS_Angle[1]:pitch实时解算值,INS_Angle[2]:roll实时解算值 //gimbal_feedback_update->gimbal_INT_angle_point + INS_PITCH_ADDRESS_OFFSET = INS_Angle + 1 即INS_Angle[1]的地址 //gimbal_feedback_update->gimbal_INT_gyro_point == INS_gyro 注:INS_gyro是INS_gyro[]数组首元素地址 //INS_gyro[0]:x轴角速度实时值,INS_gyro[1]:y轴角速度实时值,INS_gyro[2]:z轴角速度实时值 //gimbal_feedback_update->gimbal_INT_gyro_point + INS_GYRO_Y_ADDRESS_OFFSET = INS_gyro + 1 即INS_gyro[1]的地址 /*****************************************************************************************************************************************************/ // gimbal_feedback_update->gimbal_pitch_motor.absolute_angle = ((*(gimbal_feedback_update->gimbal_INT_angle_point + INS_PITCH_ADDRESS_OFFSET))/32768.0f) * 180.0f; // gimbal_feedback_update->gimbal_pitch_motor.relative_angle = motor_ecd_to_angle_change(gimbal_feedback_update->gimbal_pitch_motor.gimbal_motor_measure->ecd, // gimbal_feedback_update->gimbal_pitch_motor.offset_ecd); // gimbal_feedback_update->gimbal_pitch_motor.motor_gyro = (*(gimbal_feedback_update->gimbal_INT_gyro_point + INS_GYRO_Y_ADDRESS_OFFSET))/182.0f / 57.3f; // gimbal_feedback_update->gimbal_yaw_motor.absolute_angle = (((*(gimbal_feedback_update->gimbal_INT_angle_point + INS_YAW_ADDRESS_OFFSET))/32768.0f)* 180.0f)/57.3f; // gimbal_feedback_update->gimbal_yaw_motor.relative_angle = motor_ecd_to_angle_change(gimbal_feedback_update->gimbal_yaw_motor.gimbal_motor_measure->ecd, // gimbal_feedback_update->gimbal_yaw_motor.offset_ecd); // gimbal_feedback_update->gimbal_yaw_motor.motor_gyro = (arm_cos_f32(gimbal_feedback_update->gimbal_pitch_motor.relative_angle) * // (((*(gimbal_feedback_update->gimbal_INT_gyro_point + INS_GYRO_Z_ADDRESS_OFFSET))/32768.0f)*2000.0f / 57.3f) // - arm_sin_f32(gimbal_feedback_update->gimbal_pitch_motor.relative_angle) * // (((*(gimbal_feedback_update->gimbal_INT_gyro_point + INS_GYRO_X_ADDRESS_OFFSET))/32768.0f)*2000.0f / 57.3f)); //gimbal_feedback_update->gimbal_yaw_motor.motor_gyro = ((*(gimbal_feedback_update->gimbal_INT_gyro_point + INS_GYRO_Z_ADDRESS_OFFSET))/32768.0f)*2000.0f / 57.3f; gimbal_feedback_update->gimbal_pitch_motor.absolute_angle = (*(gimbal_feedback_update->gimbal_INT_angle_point + INS_PITCH_ADDRESS_OFFSET)); gimbal_feedback_update->gimbal_pitch_motor.relative_angle = motor_ecd_to_angle_change(gimbal_feedback_update->gimbal_pitch_motor.gimbal_motor_measure->ecd, gimbal_feedback_update->gimbal_pitch_motor.offset_ecd); gimbal_feedback_update->gimbal_pitch_motor.motor_gyro = -(*(gimbal_feedback_update->gimbal_INT_gyro_point + INS_GYRO_Y_ADDRESS_OFFSET)); gimbal_feedback_update->gimbal_yaw_motor.absolute_angle = -(*(gimbal_feedback_update->gimbal_INT_angle_point + INS_YAW_ADDRESS_OFFSET)); gimbal_feedback_update->gimbal_yaw_motor.relative_angle = motor_ecd_to_angle_change(gimbal_feedback_update->gimbal_yaw_motor.gimbal_motor_measure->ecd, gimbal_feedback_update->gimbal_yaw_motor.offset_ecd); gimbal_feedback_update->gimbal_yaw_motor.motor_gyro = arm_cos_f32(gimbal_feedback_update->gimbal_pitch_motor.relative_angle) * (*(gimbal_feedback_update->gimbal_INT_gyro_point + INS_GYRO_Z_ADDRESS_OFFSET)) - arm_sin_f32(gimbal_feedback_update->gimbal_pitch_motor.relative_angle) * (*(gimbal_feedback_update->gimbal_INT_gyro_point + INS_GYRO_X_ADDRESS_OFFSET)); } //计算相对角度 //用于GIMBAL_Feedback_Update(Gimbal_Control_t *gimbal_feedback_update) static fp32 motor_ecd_to_angle_change(uint16_t ecd, uint16_t offset_ecd) { int32_t relative_ecd = ecd - offset_ecd; if (relative_ecd > Half_ecd_range) ///电机码盘值中值Half_ecd_range = 4096 { relative_ecd -= ecd_range; ///电机码盘值最大值ecd_range = 8191 } else if (relative_ecd < -Half_ecd_range)//-Half_ecd_range = -4096 { relative_ecd += ecd_range; } return relative_ecd * Motor_Ecd_to_Rad;//电机编码值转化成角度值 rad } /**************************** 4.GIMBAL_Set_Contorl **********************************************************************************/ //云台控制量设置 //第一层GIMBAL_Set_Contorl(Gimbal_Control_t *gimbal_set_control) [gimbal_task.c global] //第二层 gimbal_behaviour_control_set(&add_yaw_angle, &add_pitch_angle, gimbal_set_control) [gimbal_behaviour.c global] // 根据云台行为状态机gimbal_behaviour和遥控器的通道值来计算add_yaw_angle,add_pitch_angle // // 根据云台电机状态机的模式来给yaw和pitch角度期望relative_angle_set/absolute_angle_set限幅 // /**************** 第一层 云台控制量设置 ************************************************************************************/ static void GIMBAL_Set_Contorl(Gimbal_Control_t *gimbal_set_control) { if (gimbal_set_control == NULL) { return; } fp32 add_yaw_angle = 0.0f; //yaw轴角度期望增量 fp32 add_pitch_angle = 0.0f; //pitch轴角度期望增量 /******************第二层 根据云台行为状态机gimbal_behaviour计算yaw和pitch期望add_yaw_angle、add_pitch_angle ***********************************/ gimbal_behaviour_control_set(&add_yaw_angle, &add_pitch_angle, gimbal_set_control); /******************第二层 根据云台电机状态机的模式来给yaw和pitch角度期望relative_angle_set/absolute_angle_set限幅 *******************************************************/ /****************** yaw电机角度期望relative_angle_set/absolute_angle_set限幅 ***************************************/ if (gimbal_set_control->gimbal_yaw_motor.gimbal_motor_mode == GIMBAL_MOTOR_RAW) { //raw模式下,直接发送控制值 gimbal_set_control->gimbal_yaw_motor.raw_cmd_current = add_yaw_angle; } else if (gimbal_set_control->gimbal_yaw_motor.gimbal_motor_mode == GIMBAL_MOTOR_GYRO) { //gyro模式下,陀螺仪角度控制 GIMBAL_absolute_angle_limit(&gimbal_set_control->gimbal_yaw_motor, add_yaw_angle); } else if (gimbal_set_control->gimbal_yaw_motor.gimbal_motor_mode == GIMBAL_MOTOR_ENCONDE) { //enconde模式下,电机编码角度控制 GIMBAL_relative_angle_limit(&gimbal_set_control->gimbal_yaw_motor, &add_yaw_angle); } /****************** pitch电机角度期望relative_angle_set/absolute_angle_set限幅 ***************************************/ if (gimbal_set_control->gimbal_pitch_motor.gimbal_motor_mode == GIMBAL_MOTOR_RAW) { //raw模式下,直接发送控制值 gimbal_set_control->gimbal_pitch_motor.raw_cmd_current = add_pitch_angle; } else if (gimbal_set_control->gimbal_pitch_motor.gimbal_motor_mode == GIMBAL_MOTOR_GYRO) { //gyro模式下,陀螺仪角度控制 GIMBAL_absolute_angle_limit(&gimbal_set_control->gimbal_pitch_motor, add_pitch_angle); } else if (gimbal_set_control->gimbal_pitch_motor.gimbal_motor_mode == GIMBAL_MOTOR_ENCONDE) { //enconde模式下,电机编码角度控制 GIMBAL_relative_angle_limit(&gimbal_set_control->gimbal_pitch_motor, &add_pitch_angle); } } //陀螺仪 控制量限制 static void GIMBAL_absolute_angle_limit(Gimbal_Motor_t *gimbal_motor, fp32 add) { static fp32 bias_angle; static fp32 angle_set; if (gimbal_motor == NULL) { return; } //误差角度 = 绝对角度期望absolute_angle_set - 绝对角度反馈absolute_angle_set bias_angle = rad_format(gimbal_motor->absolute_angle_set - gimbal_motor->absolute_angle); //云台相对角度+ 误差角度 + 新增角度 如果大于 最大机械角度 if (gimbal_motor->relative_angle + bias_angle + add > gimbal_motor->max_relative_angle) { //如果是往最大机械角度控制方向 if (add > 0.0f) { //计算出一个最大的添加角度, add = gimbal_motor->max_relative_angle - gimbal_motor->relative_angle - bias_angle; } } else if (gimbal_motor->relative_angle + bias_angle + add < gimbal_motor->min_relative_angle) { if (add < 0.0f) { add = gimbal_motor->min_relative_angle - gimbal_motor->relative_angle - bias_angle; } } angle_set = gimbal_motor->absolute_angle_set; gimbal_motor->absolute_angle_set = rad_format(angle_set + add); } static void GIMBAL_relative_angle_limit(Gimbal_Motor_t *gimbal_motor, fp32 *add) { if (gimbal_motor == NULL) { return; } gimbal_motor->relative_angle_set += *add; //是否超过最大 最小值 if (gimbal_motor->relative_angle_set > gimbal_motor->max_relative_angle) { gimbal_motor->relative_angle_set = gimbal_motor->max_relative_angle; } else if (gimbal_motor->relative_angle_set < gimbal_motor->min_relative_angle) { gimbal_motor->relative_angle_set = gimbal_motor->min_relative_angle; } } /****************** 5. GIMBAL_Control_loop *******************************************************************************************/ /************* 云台控制状态使用不同控制pid **********/ static void GIMBAL_Control_loop(Gimbal_Control_t *gimbal_control_loop) { if (gimbal_control_loop == NULL) { return; } /************* yaw云台电机不同模式对于不同的控制函数 *************/ if (gimbal_control_loop->gimbal_yaw_motor.gimbal_motor_mode == GIMBAL_MOTOR_RAW) { //raw控制 gimbal_motor_raw_angle_control(&gimbal_control_loop->gimbal_yaw_motor); } else if (gimbal_control_loop->gimbal_yaw_motor.gimbal_motor_mode == GIMBAL_MOTOR_GYRO) { //底盘随动模式 期望为absolute_angle_set,反馈为absolute_angle gimbal_motor_absolute_angle_control(&gimbal_control_loop->gimbal_yaw_motor); } else if (gimbal_control_loop->gimbal_yaw_motor.gimbal_motor_mode == GIMBAL_MOTOR_ENCONDE) { //底盘不随动模式 期望为relative_angle_set,反馈为relative_angle gimbal_motor_relative_angle_control(&gimbal_control_loop->gimbal_yaw_motor); } /************* pitch云台电机不同模式对于不同的控制函数 *************/ if (gimbal_control_loop->gimbal_pitch_motor.gimbal_motor_mode == GIMBAL_MOTOR_RAW) { //raw控制 gimbal_motor_raw_angle_control(&gimbal_control_loop->gimbal_pitch_motor); } else if (gimbal_control_loop->gimbal_pitch_motor.gimbal_motor_mode == GIMBAL_MOTOR_GYRO) { //底盘随动模式 gimbal_motor_absolute_angle_control(&gimbal_control_loop->gimbal_pitch_motor); } else if (gimbal_control_loop->gimbal_pitch_motor.gimbal_motor_mode == GIMBAL_MOTOR_ENCONDE) { //底盘不随动模式 gimbal_motor_relative_angle_control(&gimbal_control_loop->gimbal_pitch_motor); } } /************* GIMBAL_Control_loop()中根据遥控器Switch的值来调用不同的控制函数 **********/ //GIMBAL_MOTOR_GYRO模式时调用 static void gimbal_motor_absolute_angle_control(Gimbal_Motor_t *gimbal_motor) { if (gimbal_motor == NULL) { return; } /******************* yaw轴云台串级pid调试 ***************************/ //角度环外环 位置式 gimbal_motor->motor_gyro_set = GIMBAL_PID_Calc(&gimbal_motor->gimbal_motor_absolute_angle_pid, gimbal_motor->absolute_angle, gimbal_motor->absolute_angle_set, gimbal_motor->motor_gyro); //角速度环内环 位置式 gimbal_motor->current_set = PID_Calc(&gimbal_motor->gimbal_motor_gyro_pid, gimbal_motor->motor_gyro, gimbal_motor->motor_gyro_set); //控制值赋值 gimbal_motor->given_current = (int16_t)(gimbal_motor->current_set); } //GIMBAL_MOTOR_ENCONDE模式时调用 static void gimbal_motor_relative_angle_control(Gimbal_Motor_t *gimbal_motor) { if (gimbal_motor == NULL) { return; } /******************* yaw轴云台串级pid调试 ***************************/ //角度环外环 gimbal_motor->motor_gyro_set = GIMBAL_PID_Calc(&gimbal_motor->gimbal_motor_relative_angle_pid, gimbal_motor->relative_angle, gimbal_motor->relative_angle_set, gimbal_motor->motor_gyro); //角速度环内环 gimbal_motor->current_set = PID_Calc(&gimbal_motor->gimbal_motor_gyro_pid, gimbal_motor->motor_gyro, gimbal_motor->motor_gyro_set); //控制值赋值 gimbal_motor->given_current = (int16_t)(gimbal_motor->current_set); } static void gimbal_motor_raw_angle_control(Gimbal_Motor_t *gimbal_motor) { if (gimbal_motor == NULL) { return; } gimbal_motor->current_set = gimbal_motor->raw_cmd_current; gimbal_motor->given_current = (int16_t)(gimbal_motor->current_set); } static void GIMBAL_PID_Init(Gimbal_PID_t *pid, fp32 maxout, fp32 max_iout, fp32 kp, fp32 ki, fp32 kd) { if (pid == NULL) { return; } pid->kp = kp; pid->ki = ki; pid->kd = kd; pid->err = 0.0f; pid->get = 0.0f; pid->max_iout = max_iout; pid->max_out = maxout; } static fp32 GIMBAL_PID_Calc(Gimbal_PID_t *pid, fp32 get, fp32 set, fp32 error_delta) { fp32 err; if (pid == NULL) { return 0.0f; } pid->get = get; pid->set = set; err = set - get; pid->err = rad_format(err); pid->Pout = pid->kp * pid->err; pid->Iout += pid->ki * pid->err; pid->Dout = pid->kd * error_delta; abs_limit(&pid->Iout, pid->max_iout); pid->out = pid->Pout + pid->Iout + pid->Dout; abs_limit(&pid->out, pid->max_out); return pid->out; } //pid数据清理 static void Gimbal_PID_clear(Gimbal_PID_t *gimbal_pid_clear) { if (gimbal_pid_clear == NULL) { return; } gimbal_pid_clear->err = gimbal_pid_clear->set = gimbal_pid_clear->get = 0.0f; gimbal_pid_clear->out = gimbal_pid_clear->Pout = gimbal_pid_clear->Iout = gimbal_pid_clear->Dout = 0.0f; } <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file chassis.c/h * @brief 完成底盘控制任务。 * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ #ifndef CHASSISTASK_H #define CHASSISTASK_H #include "main.h" #include "CAN_Receive.h" #include "Gimbal_Task.h" #include "pid.h" #include "Remote_Control.h" #include "user_lib.h" //前后的遥控器通道号码 #define CHASSIS_X_CHANNEL 1 //左右的遥控器通道号码 #define CHASSIS_Y_CHANNEL 0 //在特殊模式下,可以通过遥控器控制旋转 #define CHASSIS_WZ_CHANNEL 2 //选择底盘状态 开关通道号 #define MODE_CHANNEL 0 //遥控器前进摇杆(max 660)转化成车体前进速度(m/s)的比例 #define CHASSIS_VX_RC_SEN 0.006f //遥控器左右摇杆(max 660)转化成车体左右速度(m/s)的比例 #define CHASSIS_VY_RC_SEN 0.005f //跟随底盘yaw模式下,遥控器的yaw遥杆(max 660)增加到车体角度的比例 #define CHASSIS_ANGLE_Z_RC_SEN 0.000002f //不跟随云台的时候 遥控器的yaw遥杆(max 660)转化成车体旋转速度的比例 #define CHASSIS_WZ_RC_SEN 0.01f #define CHASSIS_ACCEL_X_NUM 0.1666666667f #define CHASSIS_ACCEL_Y_NUM 0.3333333333f #define CHASSIS_RC_DEADLINE 10 //遥控器通道值死区 #define MOTOR_SPEED_TO_CHASSIS_SPEED_VX 0.25f #define MOTOR_SPEED_TO_CHASSIS_SPEED_VY 0.25f #define MOTOR_SPEED_TO_CHASSIS_SPEED_WZ 0.25f #define MOTOR_DISTANCE_TO_CENTER 0.2f //底盘任务控制间隔 2ms #define CHASSIS_CONTROL_TIME_MS 2 //底盘任务控制间隔 0.002s #define CHASSIS_CONTROL_TIME 0.002 //底盘任务控制频率,尚未使用这个宏 #define CHASSIS_CONTROL_FREQUENCE 500.0f //底盘3508最大can发送电流值 #define MAX_MOTOR_CAN_CURRENT 16000.0f //底盘摇摆按键 #define SWING_KEY KEY_PRESSED_OFFSET_CTRL //底盘前后左右控制按键 #define CHASSIS_FRONT_KEY KEY_PRESSED_OFFSET_W #define CHASSIS_BACK_KEY KEY_PRESSED_OFFSET_S #define CHASSIS_LEFT_KEY KEY_PRESSED_OFFSET_A #define CHASSIS_RIGHT_KEY KEY_PRESSED_OFFSET_D //m3508转化成底盘速度(m/s)的比例,做两个宏 是因为可能换电机需要更换比例 #define M3508_MOTOR_RPM_TO_VECTOR 0.000415809748903494517209f #define CHASSIS_MOTOR_RPM_TO_VECTOR_SEN M3508_MOTOR_RPM_TO_VECTOR //底盘电机最大速度 #define MAX_WHEEL_SPEED 4.0f //底盘运动过程最大前进速度 #define NORMAL_MAX_CHASSIS_SPEED_X 3.0f //底盘运动过程最大平移速度 #define NORMAL_MAX_CHASSIS_SPEED_Y 2.9f //2019.11.28新增,为了使得键入速度降低一点 不然太快了 by MrStone #define KEYBOARD_CHASSIS_SPEED_X 1.3f #define KEYBOARD_CHASSIS_SPEED_Y 1.2f //底盘设置旋转速度,设置前后左右轮不同设定速度的比例分权 0为在几何中心,不需要补偿 #define CHASSIS_WZ_SET_SCALE 0.1f //摇摆原地不动摇摆最大角度(rad) #define SWING_NO_MOVE_ANGLE 0.7f //摇摆过程底盘运动最大角度(rad) #define SWING_MOVE_ANGLE 0.31415926535897932384626433832795f //底盘电机速度环PID #define M3505_MOTOR_SPEED_PID_KP 15000.0f #define M3505_MOTOR_SPEED_PID_KI 10.0f #define M3505_MOTOR_SPEED_PID_KD 0.0f #define M3505_MOTOR_SPEED_PID_MAX_OUT MAX_MOTOR_CAN_CURRENT #define M3505_MOTOR_SPEED_PID_MAX_IOUT 2000.0f //底盘旋转跟随PID #define CHASSIS_FOLLOW_GIMBAL_PID_KP 10.0f //原40 #define CHASSIS_FOLLOW_GIMBAL_PID_KI 0.0f #define CHASSIS_FOLLOW_GIMBAL_PID_KD 0.5f #define CHASSIS_FOLLOW_GIMBAL_PID_MAX_OUT 6.0f #define CHASSIS_FOLLOW_GIMBAL_PID_MAX_IOUT 0.2f typedef enum { CHASSIS_VECTOR_FOLLOW_GIMBAL_YAW, CHASSIS_VECTOR_FOLLOW_CHASSIS_YAW, CHASSIS_VECTOR_NO_FOLLOW_YAW, CHASSIS_VECTOR_RAW, // CHASSIS_AUTO, // CHASSIS_FOLLOW_YAW, // CHASSIS_ENCODER, // CHASSIS_NO_ACTION, // CHASSIS_RELAX, } chassis_mode_e; typedef enum { Waiting = 0, Charging = 1, Discharging, } Power_State_e; typedef struct { const motor_measure_t *chassis_motor_measure; fp32 accel; fp32 speed; fp32 speed_set; int16_t give_current; } Chassis_Motor_t; typedef struct { const extended_mcu_msg_t *super_power_mcu_msg_pointer; Power_State_e charge_cmd_state; //降压模块期望要切换的模式(给超级电容充电) Power_State_e discharge_cmd_state; //升压模块期望要切换的模式(超级电容放电给底盘) Power_State_e charge_current_state; //真实模式 Power_State_e discharge_current_state;//真实模式 float voltage; //超级电容电压 } SuperCap_t; typedef struct { const RC_ctrl_t *chassis_RC; //底盘使用的遥控器指针 const Gimbal_Motor_t *chassis_yaw_motor; //底盘使用到yaw云台电机的相对角度来计算底盘的欧拉角 const Gimbal_Motor_t *chassis_pitch_motor; //底盘使用到pitch云台电机的相对角度来计算底盘的欧拉角 const fp32 *chassis_INS_angle; //获取陀螺仪解算出的欧拉角指针 chassis_mode_e chassis_mode; //底盘控制状态机 chassis_mode_e last_chassis_mode; //底盘上次控制状态机 Chassis_Motor_t motor_chassis[4]; //底盘电机数据 PidTypeDef motor_speed_pid[4]; //底盘电机速度pid PidTypeDef chassis_angle_pid; //底盘跟随角度pid first_order_filter_type_t chassis_cmd_slow_set_vx; first_order_filter_type_t chassis_cmd_slow_set_vy; fp32 vx; //底盘速度 前进方向 前为正,单位 m/s fp32 vy; //底盘速度 左右方向 左为正 单位 m/s fp32 wz; //底盘旋转角速度,逆时针为正 单位 rad/s fp32 vx_set; //底盘设定速度 前进方向 前为正,单位 m/s fp32 vy_set; //底盘设定速度 左右方向 左为正,单位 m/s fp32 wz_set; //底盘设定旋转角速度,逆时针为正 单位 rad/s fp32 chassis_relative_angle; //底盘与云台的相对角度,单位 rad/s fp32 chassis_relative_angle_set; //设置相对云台控制角度 fp32 chassis_yaw_set; fp32 vx_max_speed; //前进方向最大速度 单位m/s fp32 vx_min_speed; //前进方向最小速度 单位m/s fp32 vy_max_speed; //左右方向最大速度 单位m/s fp32 vy_min_speed; //左右方向最小速度 单位m/s fp32 chassis_yaw; //陀螺仪和云台电机叠加的yaw角度 fp32 chassis_pitch; //陀螺仪和云台电机叠加的pitch角度 fp32 chassis_roll; //陀螺仪和云台电机叠加的roll角度 SuperCap_t super_cap; } chassis_move_t; extern const float *get_Voltage_Point(void); extern void chassis_Setup(void); extern void chassis_task(void); extern void chassis_rc_to_control_vector(fp32 *vx_set, fp32 *vy_set, chassis_move_t *chassis_move_rc_to_vector); #endif <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file start_task.c/h * @brief 启动任务,将一个个任务开启,分配资源,给定任务优先级, * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ #ifndef START_TASK_H #define START_TASK_H #include "main.h" #include "Detect_Task.h" #include "Calibrate_Task.h" #include "User_Task.h" #include "INS_Task.h" #include "Chassis_Task.h" #include "Gimbal_Task.h" #include "delay.h" #include "User_Task.h" #include "buzzer.h" #include "referee_usart_task.h" #include "ANO_DT.h" typedef struct { void(*task_func)(void); uint16_t rate_hz; uint16_t interval_ticks; uint32_t last_run; }sched_task_t; //void startTast(void); void Scheduler_Setup(void); void Scheduler_Run(void); #endif <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file INSTask.c/h * @brief 主要利用陀螺仪mpu6500,磁力计ist8310,完成姿态解算,得出欧拉角, * 提供通过mpu6500的data ready 中断完成外部触发,减少数据等待延迟 * 通过DMA的SPI传输节约CPU时间,提供注释对应的宏定义,关闭DMA, * DR的外部中断的方式. * @note SPI 在陀螺仪初始化的时候需要低于2MHz,之后读取数据需低于20MHz * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ #ifndef INS_Task_H #define INS_Task_H #include "main.h" #define USE_IST8310 //是否使用IST8310磁力计,不使用注释定义 #define MPU6500_USE_DATA_READY_EXIT //是否使用MPU6500的外部中断,不使用注释定义 #define MPU6500_USE_SPI_DMA //是否使用SPI的DMA传输,不使用注释定义 //如果用了IST8310,DMA传输23个字节,如果不用,少7个字节,为16个字节 #if defined(USE_IST8310) #define DMA_RX_NUM 23 #else #define DMA_RX_NUM 16 #endif //mpu6500原始数据在缓冲区buf的位置 #ifdef MPU6500_USE_SPI_DMA #define MPU6500_RX_BUF_DATA_OFFSET 1 #else #define MPU6500_RX_BUF_DATA_OFFSET 0 #endif //ist83100原始数据在缓冲区buf的位置 #ifdef MPU6500_USE_SPI_DMA #define IST8310_RX_BUF_DATA_OFFSET 16 #else #define IST8310_RX_BUF_DATA_OFFSET 15 #endif #define MPU6500_TEMPERATURE_PID_KP 1600.0f //温度控制PID的kp #define MPU6500_TEMPERATURE_PID_KI 0.2f //温度控制PID的ki #define MPU6500_TEMPERATURE_PID_KD 0.0f //温度控制PID的kd #define MPU6500_TEMPERATURE_PID_MAX_OUT 4500.0f //温度控制PID的max_out #define MPU6500_TEMPERATURE_PID_MAX_IOUT 4400.0f //温度控制PID的max_iout #define INS_DELTA_TICK 1 //任务调用的间隔 #define INS_TASK_INIT_TIME 7 //任务开始初期 delay 一段时间 #define MPU6500_TEMP_PWM_MAX 5000 //mpu6500控制温度的设置TIM的重载值,即给PWM最大为 MPU6500_TEMP_PWM_MAX - 1 //获取姿态角指针地址后,对应姿态角的地址偏移量 short类型 #define INS_YAW_ADDRESS_OFFSET 0 #define INS_PITCH_ADDRESS_OFFSET 1 #define INS_ROLL_ADDRESS_OFFSET 2 #define INS_GYRO_X_ADDRESS_OFFSET 0 #define INS_GYRO_Y_ADDRESS_OFFSET 1 #define INS_GYRO_Z_ADDRESS_OFFSET 2 #define INS_ACCEL_X_ADDRESS_OFFSET 0 #define INS_ACCEL_Y_ADDRESS_OFFSET 1 #define INS_ACCEL_Z_ADDRESS_OFFSET 2 extern void IMU_Setup(void); extern void IMU_Update(void); extern void INS_cali_gyro(fp32 cali_scale[3], fp32 cali_offset[3], uint16_t *time_count); extern void INS_set_cali_gyro(fp32 cali_scale[3], fp32 cali_offset[3]); extern const fp32 *get_INS_angle_point(void); extern const fp32 *get_MPU6500_Gyro_Data_Point(void); extern const fp32 *get_MPU6500_Accel_Data_Point(void); #endif <file_sep>#ifndef __UART8_H__ #define __UART8_H__ #include "main.h" #include <stm32f4xx.h> #include <stdio.h> void LX_IMU_UART8_Configuration(u32 bound); void Uart8_Send( unsigned char *DataToSend , u8 data_num ); void Usart_SendByte( USART_TypeDef * pUSARTx, uint8_t ch); void Usart_SendString( USART_TypeDef * pUSARTx, char *str); void Usart_SendHalfWord( USART_TypeDef * pUSARTx, uint16_t ch); #endif <file_sep>#include "uart8.h" #include <string.h> #include <stdarg.h> #include "LX_IMU.h" #define UART_REC_LEN 8 //定义最大接收字节数 200 #define EN_UART8_RX 1 //使能(1)/禁止(0)串口1接收 #define UART8_Waiting 0 #define UART8_Receiving 1 #define UART8_Success 2 #define UART8_Failed 3 u8 Tx8Buffer[256]; u8 Tx8Counter = 0; u8 count8 = 0; void LX_IMU_UART8_Configuration(u32 bound) { //GPIO端口设置 GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE,ENABLE); //使能GPIOG时钟 RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART8,ENABLE);//使能UART8时钟 //串口8对应引脚复用映射 GPIO_PinAFConfig(GPIOE,GPIO_PinSource0,GPIO_AF_UART8); GPIO_PinAFConfig(GPIOE,GPIO_PinSource1,GPIO_AF_UART8); //UART8端口配置 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//复用功能 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉 GPIO_Init(GPIOE,&GPIO_InitStructure); //UART8 初始化设置 USART_InitStructure.USART_BaudRate = bound;//波特率设置 USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式 USART_InitStructure.USART_StopBits = USART_StopBits_1;//一个停止位 USART_InitStructure.USART_Parity = USART_Parity_No;//无奇偶校验位 USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制 USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //收发模式 USART_Init(UART8, &USART_InitStructure); //初始化串口8 USART_Cmd(UART8, ENABLE); //使能串口8 USART_ClearFlag(UART8, USART_FLAG_TC); USART_ITConfig(UART8, USART_IT_RXNE, ENABLE);//开启相关中断 //UART8 NVIC 配置 NVIC_InitStructure.NVIC_IRQChannel = UART8_IRQn;//串口8中断通道 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = UART8_NVIC ;//抢占优先级3 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //子优先级3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能 NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器、 } void UART8_IRQHandler(void) //串口6中断服务程序 { u8 com_data; if ( UART8->SR & USART_SR_ORE ) //ORE中断 { com_data = UART5->DR; } //接收中断 if ( USART_GetITStatus ( UART8, USART_IT_RXNE ) ) { USART_ClearITPendingBit ( UART8, USART_IT_RXNE ); //清除中断标志 // com_data = UART8->DR; // ANO_DT_LX_Data_Receive_Prepare(com_data); Usart_SendByte(UART8,com_data); } // //发送(进入移位)中断 // if ( USART_GetITStatus ( UART8, USART_IT_TXE ) ) // { // UART8->DR = Tx8Buffer[Tx8Counter++]; //写DR清除中断标志 // if ( Tx8Counter == count8 ) // { // UART8->CR1 &= ~USART_CR1_TXEIE; //关闭TXE(发送中断)中断 // } // } } void Uart8_Send ( unsigned char *DataToSend , u8 data_num ) { u8 i; for ( i = 0; i < data_num; i++ ) { Tx8Buffer[count8++] = * ( DataToSend + i ); } if ( ! ( UART8->CR1 & USART_CR1_TXEIE ) ) { USART_ITConfig ( UART8, USART_IT_TXE, ENABLE ); //打开发送中断 } } /***************** 发送一个字节 **********************/ void Usart_SendByte( USART_TypeDef * pUSARTx, uint8_t ch) { /* 发送一个字节数据到USART */ USART_SendData(pUSARTx,ch); /* 等待发送数据寄存器为空 */ while (USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET); } /****************** 发送8位的数组 ************************/ void Usart_SendArray( USART_TypeDef * pUSARTx, uint8_t *array, uint16_t num) { uint8_t i; for(i=0; i<num; i++) { /* 发送一个字节数据到USART */ Usart_SendByte(pUSARTx,array[i]); } /* 等待发送完成 */ while(USART_GetFlagStatus(pUSARTx,USART_FLAG_TC)==RESET); } /***************** 发送字符串 **********************/ void Usart_SendString( USART_TypeDef * pUSARTx, char *str) { unsigned int k=0; do { Usart_SendByte( pUSARTx, *(str + k) ); k++; } while(*(str + k)!='\0'); /* 等待发送完成 */ while(USART_GetFlagStatus(pUSARTx,USART_FLAG_TC)==RESET) {} } /***************** 发送一个16位数 **********************/ void Usart_SendHalfWord( USART_TypeDef * pUSARTx, uint16_t ch) { uint8_t temp_h, temp_l; /* 取出高八位 */ temp_h = (ch&0XFF00)>>8; /* 取出低八位 */ temp_l = ch&0XFF; /* 发送高八位 */ USART_SendData(pUSARTx,temp_h); while (USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET); /* 发送低八位 */ USART_SendData(pUSARTx,temp_l); while (USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET); } <file_sep>#ifndef GIMBAL_BEHAVIOUR_H #define GIMBAL_BEHAVIOUR_H /**** gimbal_behaviour_mode_set(Gimbal_Control_t *gimbal_mode_set); gimbal_behavour_set(gimbal_mode_set); /************************* 头文件 ******************************/ #include "main.h" #include "Gimbal_Task.h" /*********** 2. 定义成员 ****************/ typedef enum { GIMBAL_ZERO_FORCE = 0, //云台无力 GIMBAL_INIT, //云台初始化 GIMBAL_CALI, //云台校准 GIMBAL_ABSOLUTE_ANGLE, //云台陀螺仪绝对角度控制 GIMBAL_RELATIVE_ANGLE, //云台电机编码值相对角度控制 GIMBAL_MOTIONLESS, //云台在遥控器无输入一段时间后保持不动,避免陀螺仪漂移 } gimbal_behaviour_e; /************ 3.全局函数声明 ****************/ extern void gimbal_behaviour_mode_set(Gimbal_Control_t *gimbal_mode_set); extern void gimbal_behaviour_control_set(fp32 *add_yaw, fp32 *add_pitch, Gimbal_Control_t *gimbal_control_set); extern bool_t gimbal_cmd_to_chassis_stop(void); extern bool_t gimbal_cmd_to_shoot_stop(void); #endif <file_sep>#include "main.h" #include <stm32f4xx.h> #include "usart6.h" //void Referee_USART6_Configuration(u32 bound){ // //GPIO端口设置 // GPIO_InitTypeDef GPIO_InitStructure; // USART_InitTypeDef USART_InitStructure; // NVIC_InitTypeDef NVIC_InitStructure; // RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOG,ENABLE); //使能GPIOG时钟 // RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6,ENABLE);//使能USART6时钟 // //串口6对应引脚复用映射 // GPIO_PinAFConfig(GPIOG,GPIO_PinSource9,GPIO_AF_USART6); //GPIOA9复用为USART6 // GPIO_PinAFConfig(GPIOG,GPIO_PinSource14,GPIO_AF_USART6); //GPIOA10复用为USART6 // //USART6端口配置 // GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_14; //GPIOG9与GPIOG14 // GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//复用功能 // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz // GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出 // GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉 // GPIO_Init(GPIOG,&GPIO_InitStructure); //初始化GPIOG9与GPIOG14 // //USART6 初始化设置 // USART_InitStructure.USART_BaudRate = bound;//波特率设置 // USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式 // USART_InitStructure.USART_StopBits = USART_StopBits_1;//一个停止位 // USART_InitStructure.USART_Parity = USART_Parity_No;//无奇偶校验位 // USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制 // USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //收发模式 // USART_Init(USART6, &USART_InitStructure); //初始化串口6 // USART_Cmd(USART6, ENABLE); //使能串口6 // USART_ClearFlag(USART6, USART_FLAG_TC); // USART_ITConfig(USART6, USART_IT_RXNE, ENABLE);//开启相关中断 // //USART6 NVIC 配置 // NVIC_InitStructure.NVIC_IRQChannel = USART6_IRQn;//串口6中断通道 // NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3;//抢占优先级3 // NVIC_InitStructure.NVIC_IRQChannelSubPriority =3; //子优先级3 // NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能 // NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器、 // // //} u8 kzsb = 0; void USART6_DMA_Init(uint8_t *rx1_buf, uint8_t *rx2_buf, uint16_t dma_buf_num) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; /* -------------- Enable Module Clock Source ----------------------------*/ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOG | RCC_AHB1Periph_DMA2,ENABLE); //使能GPIOG时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6,ENABLE);//使能USART6时钟 RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART6, ENABLE); RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART6, DISABLE); //串口6对应引脚复用映射 GPIO_PinAFConfig(GPIOG,GPIO_PinSource9,GPIO_AF_USART6); //G9复用为USART6 GPIO_PinAFConfig(GPIOG,GPIO_PinSource14,GPIO_AF_USART6); //G14复用为USART6 /* -------------- Configure GPIO ---------------------------------------*/ { //USART6端口配置 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_14; //GPIOG9与GPIOG14 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//复用功能 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度50MHz GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉 GPIO_Init(GPIOG,&GPIO_InitStructure); //初始化GPIOG9与GPIOG14 //USART_DeInit(USART1); USART_InitStructure.USART_BaudRate = 115200; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_Init(USART6, &USART_InitStructure); USART_DMACmd(USART6, USART_DMAReq_Rx, ENABLE); USART_ClearFlag(USART6, USART_FLAG_IDLE); USART_ITConfig(USART6, USART_IT_IDLE, ENABLE); USART_Cmd(USART6, ENABLE); } /* -------------- Configure NVIC ---------------------------------------*/ { NVIC_InitStructure.NVIC_IRQChannel = USART6_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = USART6_NVIC; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } //DMA2 stream1 ch5 !!!!!!! P206 of the datasheet /* -------------- Configure DMA -----------------------------------------*/ { DMA_InitTypeDef DMA_InitStructure; DMA_DeInit(DMA2_Stream1); DMA_InitStructure.DMA_Channel = DMA_Channel_5; DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t) & (USART6->DR); DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)rx1_buf; DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory; DMA_InitStructure.DMA_BufferSize = 512; DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable; DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte; DMA_InitStructure.DMA_Mode = DMA_Mode_Circular; DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh; DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable; DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_1QuarterFull; DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single; DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; DMA_Init(DMA2_Stream1, &DMA_InitStructure); DMA_DoubleBufferModeConfig(DMA2_Stream1, (uint32_t)rx2_buf, DMA_Memory_0); DMA_DoubleBufferModeCmd(DMA2_Stream1, ENABLE); DMA_Cmd(DMA2_Stream1, DISABLE); //Add a disable DMA_Cmd(DMA2_Stream1, ENABLE); } } <file_sep>/** ****************************(C) COPYRIGHT 2019 DJI**************************** * @file referee_usart_task.c/h * @brief RM referee system data solve. RM裁判系统数据处理 * @note * @history * Version Date Author Modification * V1.0.0 Nov-11-2019 RM 1. done * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2019 DJI**************************** */ #include "main.h" #include "stdbool.h" // 引入以使用bool类型 #include "string.h" #include "uart8.h" #include "usart6.h" #include "detect_task.h" #include "referee_usart_task.h" #include "CRC8_CRC16.h" #include "fifo.h" #define USART_RX_BUF_LENGHT 512 #define REFEREE_FIFO_BUF_LENGTH 1024 #define FALSE 0 #define TRUE 1 #define LEN_HEADER 5 //帧头长 #define LEN_CMDID 2 //命令码长度 #define LEN_TAIL 2 //帧尾CRC16 //起始字节,协议固定为0xA5 #define JUDGE_FRAME_HEADER (0xA5) uint8_t usart6_buf[2][USART_RX_BUF_LENGHT]; fifo_s_t referee_fifo; uint8_t referee_fifo_buf[REFEREE_FIFO_BUF_LENGTH]; /*-------------------------2020--------------------------------*/ /*****************系统数据定义**********************/ ext_game_state_t game_state; //0x0001 ext_game_result_t game_result; //0x0002 ext_game_robot_HP_t game_robot_HP_t; //0x0003 ext_event_data_t field_event; //0x0101 ext_supply_projectile_action_t supply_projectile_action_t; //0x0102 ext_supply_projectile_booking_t supply_projectile_booking_t; //0x0103 ext_referee_warning_t referee_warning_t; //0x0104 //TODO2:添加0x0105,并在.h文件里新建0x0105的结构体 ext_game_robot_state_t robot_state; //0x0201 ext_power_heat_data_t power_heat_data_t; //0x0202 ext_game_robot_pos_t game_robot_pos_t; //0x0203 ext_buff_musk_t buff_musk_t; //0x0204 aerial_robot_energy_t robot_energy_t; //0x0205 ext_robot_hurt_t robot_hurt_t; //0x0206 ext_shoot_data_t shoot_data_t; //0x0207 ext_bullet_remaining_t bullet_remaining_t; //0x0208 ext_student_interactive_data_t student_interactive_data; ext_RobotCommunication_t RobotCommunatianData; //0x0301 ext_Client_Communication_custom_graphic_single_t client_com_graphic_single; /****************************************************/ uint8_t Judge_Self_ID;//当前机器人的ID uint16_t Judge_SelfClient_ID;//发送者机器人对应的客户端ID unpack_data_t referee_unpack_obj; unpack_data_t *judge = &referee_unpack_obj; //裁判系统数据协议头 frame_header_struct_t referee_receive_header; frame_header_struct_t referee_send_header; /* static */ static void init_referee_struct_data(void); static void Judge_Read_Data(void); static void referee_data_solve(uint8_t *frame); void Referee_Task_Init() { init_referee_struct_data(); //初始化结构体数据对象 fifo_s_init(&referee_fifo, referee_fifo_buf, REFEREE_FIFO_BUF_LENGTH); //创建队列FIFO USART6_DMA_Init(usart6_buf[0], usart6_buf[1], USART_RX_BUF_LENGHT); //初始化裁判系统串口6+DMA,开启串口空闲中断 } void referee_usart_task(void) { Judge_Read_Data(); } //TODO:测试TeammateTxBuffer数组和RobotCommunatianData.interactData.data的区别 unsigned char TeammateTxBuffer[REF_PROTOCOL_FRAME_MAX_SIZE]; void referee_tx_task(void) //SOF:A5 data_l:15 00 seq:00 CRC8:BC CMD_ID:0103 data:0101 0100 0101/ 01 00 00/ 49 10 1E 78 C8 D0 87 3E 64 A0 0F 7D frame_tail:3A 40 //A5 00 15 00 D0 03 01 10 10 01 01 01 01 01 00 00 49 10 1E 78 C8 D0 87 3E 64 A0 0F 7D 8C 57 //49 10 1E 78 C8 D0 87 3E 64 A0 0F 7D B1 DF { static u8 datalength,i; //Frame_Header client_com_graphic_single.txFrameHeader.SOF = 0xA5; client_com_graphic_single.txFrameHeader.data_length = sizeof(ext_student_interactive_header_data_t) + sizeof(ext_client_custom_graphic_single_t); //6字节+15字节 client_com_graphic_single.txFrameHeader.seq = 0; memcpy(&TeammateTxBuffer, &client_com_graphic_single.txFrameHeader, sizeof(frame_header_struct_t)); append_CRC8_check_sum(TeammateTxBuffer, sizeof(frame_header_struct_t)); //cmd_id client_com_graphic_single.CmdID = 0x301; //数据段头结构 client_com_graphic_single.dataFrameHeader.send_ID = RED_HERO; client_com_graphic_single.dataFrameHeader.data_cmd_id = DRAW_ONE; client_com_graphic_single.dataFrameHeader.receiver_ID = RED_HERO_Client; client_com_graphic_single.interactData.graphic_data_struct.graphic_name[0] = 1; client_com_graphic_single.interactData.graphic_data_struct.operate_type = 1; client_com_graphic_single.interactData.graphic_data_struct.graphic_type = 2; client_com_graphic_single.interactData.graphic_data_struct.layer = 0; client_com_graphic_single.interactData.graphic_data_struct.color = 4; client_com_graphic_single.interactData.graphic_data_struct.start_angle = 0; client_com_graphic_single.interactData.graphic_data_struct.end_angle = 0; client_com_graphic_single.interactData.graphic_data_struct.width = 3; client_com_graphic_single.interactData.graphic_data_struct.start_x = 1060; client_com_graphic_single.interactData.graphic_data_struct.start_y = 640; client_com_graphic_single.interactData.graphic_data_struct.radius = 60; client_com_graphic_single.interactData.graphic_data_struct.end_x = 0; client_com_graphic_single.interactData.graphic_data_struct.end_y = 0; memcpy(TeammateTxBuffer+5,(uint8_t *)&client_com_graphic_single.CmdID, (sizeof(client_com_graphic_single.CmdID)+sizeof(client_com_graphic_single.dataFrameHeader)+sizeof(client_com_graphic_single.interactData))); append_CRC16_check_sum(TeammateTxBuffer,sizeof(client_com_graphic_single)); datalength = sizeof(client_com_graphic_single); // if( First_Time_Send_Commu == TRUE ) // { for(i = 0;i < datalength;i++) { USART_SendData(USART6,(uint16_t)TeammateTxBuffer[i]); while(USART_GetFlagStatus(USART6,USART_FLAG_TC)==RESET); } // } } static void init_referee_struct_data(void) { memset(&referee_receive_header, 0, sizeof(frame_header_struct_t)); memset(&referee_send_header, 0, sizeof(frame_header_struct_t)); memset(&game_state, 0, sizeof(ext_game_state_t)); memset(&game_result, 0, sizeof(ext_game_result_t)); memset(&game_robot_HP_t, 0, sizeof(ext_game_robot_HP_t)); memset(&field_event, 0, sizeof(ext_event_data_t)); memset(&supply_projectile_action_t, 0, sizeof(ext_supply_projectile_action_t)); memset(&supply_projectile_booking_t, 0, sizeof(ext_supply_projectile_booking_t)); memset(&referee_warning_t, 0, sizeof(ext_referee_warning_t)); memset(&robot_state, 0, sizeof(ext_game_robot_state_t)); memset(&power_heat_data_t, 0, sizeof(ext_power_heat_data_t)); memset(&game_robot_pos_t, 0, sizeof(ext_game_robot_pos_t)); memset(&buff_musk_t, 0, sizeof(ext_buff_musk_t)); memset(&robot_energy_t, 0, sizeof(aerial_robot_energy_t)); memset(&robot_hurt_t, 0, sizeof(ext_robot_hurt_t)); memset(&shoot_data_t, 0, sizeof(ext_shoot_data_t)); memset(&bullet_remaining_t, 0, sizeof(ext_bullet_remaining_t)); memset(&student_interactive_data, 0, sizeof(ext_student_interactive_data_t)); memset(&client_com_graphic_single, 0, sizeof(ext_Client_Communication_custom_graphic_single_t)); } // 裁判系统数据读取并送入解析 static void Judge_Read_Data(void) { uint8_t G_byte = 0; uint8_t sof = HEADER_SOF; //0xA5 while ( fifo_s_used(&referee_fifo) ) //Get FIFO the number of elements { G_byte = fifo_s_get(&referee_fifo); switch(judge->unpack_step) //一共6步 { ////////Step 1 判断帧头 case STEP_HEADER_SOF: { //判断当前字节是否为帧头0xA5 if(G_byte == sof) // sof局部变量 0xA5 { judge->unpack_step = STEP_LENGTH_LOW; // 2 judge->protocol_packet[judge->index++] = G_byte;//将当前帧头按index顺序放入数据包中 } //如果不是0xA5,则数据包序号清零(索引到数据包首位),继续等待0xA5出现 else { judge->index = 0; } }break; ////////Step 2 case STEP_LENGTH_LOW: { judge->data_len = G_byte; judge->protocol_packet[judge->index++] = G_byte; judge->unpack_step = STEP_LENGTH_HIGH; }break; case STEP_LENGTH_HIGH: { judge->data_len |= (G_byte << 8); judge->protocol_packet[judge->index++] = G_byte; if(judge->data_len < (REF_PROTOCOL_FRAME_MAX_SIZE - REF_HEADER_CRC_CMDID_LEN)) { judge->unpack_step = STEP_FRAME_SEQ; } else { judge->unpack_step = STEP_HEADER_SOF; judge->index = 0; } }break; case STEP_FRAME_SEQ: { judge->protocol_packet[judge->index++] = G_byte; judge->unpack_step = STEP_HEADER_CRC8; }break; case STEP_HEADER_CRC8: { judge->protocol_packet[judge->index++] = G_byte; if (judge->index == REF_PROTOCOL_HEADER_SIZE) { if (verify_CRC8_check_sum(judge->protocol_packet, REF_PROTOCOL_HEADER_SIZE) ) { judge->unpack_step = STEP_DATA_CRC16; } else { judge->unpack_step = STEP_HEADER_SOF; judge->index = 0; } } }break; case STEP_DATA_CRC16: { if (judge->index < (REF_HEADER_CRC_CMDID_LEN + judge->data_len)) { judge->protocol_packet[judge->index++] = G_byte; } if (judge->index >= (REF_HEADER_CRC_CMDID_LEN + judge->data_len)) { judge->unpack_step = STEP_HEADER_SOF; judge->index = 0; if (verify_CRC16_check_sum(judge->protocol_packet, REF_HEADER_CRC_CMDID_LEN + judge->data_len) ) { referee_data_solve(judge->protocol_packet); } } }break; default: { judge->unpack_step = STEP_HEADER_SOF; judge->index = 0; }break; } } } static void referee_data_solve(uint8_t *frame) { uint8_t index1 = 0; uint16_t cmd_id = 0; memcpy(&referee_receive_header, frame, sizeof(frame_header_struct_t)); //size为5字节 index1 += sizeof(frame_header_struct_t); //size为5字节 memcpy(&cmd_id, frame + index1, sizeof(uint16_t)); //cmd_id 2字节 index1 += sizeof(uint16_t); // index1索引到数据 // 判断读取到的命令码是对应哪种数据以及数据长度 switch (cmd_id) { case GAME_STATE_CMD_ID: { memcpy(&game_state, frame + index1, sizeof(ext_game_state_t)); } break; case GAME_RESULT_CMD_ID: { memcpy(&game_result, frame + index1, sizeof(game_result)); } break; case GAME_ROBOT_HP_CMD_ID: { memcpy(&game_robot_HP_t, frame + index1, sizeof(ext_game_robot_HP_t)); } break; case FIELD_EVENTS_CMD_ID: { memcpy(&field_event, frame + index1, sizeof(field_event)); } break; case SUPPLY_PROJECTILE_ACTION_CMD_ID: { memcpy(&supply_projectile_action_t, frame + index1, sizeof(supply_projectile_action_t)); } break; case SUPPLY_PROJECTILE_BOOKING_CMD_ID: { memcpy(&supply_projectile_booking_t, frame + index1, sizeof(supply_projectile_booking_t)); } break; case REFEREE_WARNING_CMD_ID: { memcpy(&referee_warning_t, frame + index1, sizeof(ext_referee_warning_t)); } break; case ROBOT_STATE_CMD_ID: { memcpy(&robot_state, frame + index1, sizeof(robot_state)); } break; case POWER_HEAT_DATA_CMD_ID: { memcpy(&power_heat_data_t, frame + index1, sizeof(power_heat_data_t)); } break; case ROBOT_POS_CMD_ID: { memcpy(&game_robot_pos_t, frame + index1, sizeof(game_robot_pos_t)); } break; case BUFF_MUSK_CMD_ID: { memcpy(&buff_musk_t, frame + index1, sizeof(buff_musk_t)); } break; case AERIAL_ROBOT_ENERGY_CMD_ID: { memcpy(&robot_energy_t, frame + index1, sizeof(robot_energy_t)); } break; case ROBOT_HURT_CMD_ID: { memcpy(&robot_hurt_t, frame + index1, sizeof(robot_hurt_t)); } break; case SHOOT_DATA_CMD_ID: { memcpy(&shoot_data_t, frame + index1, sizeof(shoot_data_t)); } break; case BULLET_REMAINING_CMD_ID: { memcpy(&bullet_remaining_t, frame + index1, sizeof(ext_bullet_remaining_t)); } break; case STUDENT_INTERACTIVE_DATA_CMD_ID: { memcpy(&student_interactive_data, frame + index1, sizeof(ext_student_interactive_data_t)); } break; default: { break; } } } void USART6_IRQHandler(void) { if (USART_GetITStatus(USART6, USART_IT_RXNE) != RESET) { USART_ReceiveData(USART6); } else if (USART_GetITStatus(USART6, USART_IT_IDLE) != RESET) { static uint16_t this_time_rx_len = 0; USART_ReceiveData(USART6); if(DMA_GetCurrentMemoryTarget(DMA2_Stream1) == 0) { //重新设置DMA DMA_Cmd(DMA2_Stream1, DISABLE); this_time_rx_len = USART_RX_BUF_LENGHT - DMA_GetCurrDataCounter(DMA2_Stream1); DMA_SetCurrDataCounter(DMA2_Stream1, USART_RX_BUF_LENGHT); DMA2_Stream1->CR |= DMA_SxCR_CT; //清DMA中断标志 DMA_ClearFlag(DMA2_Stream1, DMA_FLAG_TCIF2 | DMA_FLAG_HTIF2); DMA_Cmd(DMA2_Stream1, ENABLE); fifo_s_puts(&referee_fifo, (char*)usart6_buf[0], this_time_rx_len); } else { //重新设置DMA DMA_Cmd(DMA2_Stream1, DISABLE); // this_time_rx_len = USART_RX_BUF_LENGHT - DMA_GetCurrDataCounter(DMA2_Stream1); DMA_SetCurrDataCounter(DMA2_Stream1, USART_RX_BUF_LENGHT); DMA2_Stream1->CR &= ~(DMA_SxCR_CT); //清DMA中断标志 DMA_ClearFlag(DMA2_Stream1, DMA_FLAG_TCIF2 | DMA_FLAG_HTIF2); DMA_Cmd(DMA2_Stream1, ENABLE); fifo_s_puts(&referee_fifo, (char*)usart6_buf[1], this_time_rx_len); } } } <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file INSTask.c/h * @brief 主要利用陀螺仪mpu6500,磁力计ist8310,完成姿态解算,得出欧拉角, * 提供通过mpu6500的data ready 中断完成外部触发,减少数据等待延迟 * 通过DMA的SPI传输节约CPU时间,提供注释对应的宏定义,关闭DMA, * DR的外部中断的方式. * @note SPI 在陀螺仪初始化的时候需要低于2MHz,之后读取数据需低于20MHz * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ /************************* 头文件 ******************************/ #include "INS_Task.h" #include "stm32f4xx.h" #include "buzzer.h" #include "timer.h" #include "spi.h" #include "exit_init.h" #include "IST8310driver.h" #include "mpu6500driver.h" #include "mpu6500reg.h" #include "mpu6500driver_middleware.h" #include "AHRS.h" #include "calibrate_Task.h" #include "pid.h" /************************* 宏定义 ******************************/ #define IMUWarnBuzzerOn() buzzer_on(95, 10000) //开机陀螺仪校准蜂鸣器 #define IMUWarnBuzzerOFF() buzzer_off() //开机陀螺仪校准蜂鸣器关闭 #define MPU6500_TEMPERATURE_PWM_INIT() TIM3_Init(MPU6500_TEMP_PWM_MAX, 1) //陀螺仪温度控制PWM初始化 #define IMUTempPWM(pwm) TIM_SetCompare2(TIM3, (pwm)) //pwm给定 #define INS_GET_CONTROL_TEMPERATURE() get_control_temperate() //获取控制温度的目标值 #if defined(MPU6500_USE_DATA_READY_EXIT) #define MPU6500_DATA_READY_EXIT_INIT() GPIOB_Exti8_GPIO_Init() //初始化mpu6500的 外部中断 使用PB8 外部中断线 8 #define MPU6500_DATA_READY_EXIT_IRQHandler EXTI9_5_IRQHandler //宏定义外部中断函数,使用了line8外部中断 #define MPU6500_DATA_READY_EXIT_Line EXTI_Line8 //宏定义外部中断线 #endif #if defined(MPU6500_USE_SPI) && defined(MPU6500_USE_SPI_DMA) //宏定义初始化SPI的DMA,同时设置SPI为8位,4分频 #define MPU6500_SPI_DMA_Init(txbuf, rxbuf) \ { \ SPI5_DMA_Init((uint32_t)txbuf, (uint32_t)rxbuf, DMA_RX_NUM); \ SPI_I2S_DMACmd(SPI5, SPI_I2S_DMAReq_Rx, ENABLE); \ SPI_I2S_DMACmd(SPI5, SPI_I2S_DMAReq_Tx, ENABLE); \ SPI5SetSpeedAndDataSize(SPI_BaudRatePrescaler_8, SPI_DataSize_8b); \ } #define MPU6500_SPI_DMA_Enable() SPI5_DMA_Enable(DMA_RX_NUM) // 开始一次SPI的DMA传输 //宏定义SPI的DMA传输中断函数以及传输中断标志位 #define MPU6500_DMA_IRQHandler DMA2_Stream5_IRQHandler #define MPU6500_DMA_Stream DMA2_Stream5 #define MPU6500_DMA_FLAG DMA_FLAG_TCIF5 #elif defined(MPU6500_USE_SPI_DMA) #error "the communication of mpu6500 is not SPI, can't use the DMA" #endif //DMA的SPI 发送的buf,以INT_STATUS开始连续读取 DMA_RX_NUM大小地址的值 #if defined(MPU6500_USE_SPI_DMA) static const uint8_t mpu6500_spi_DMA_txbuf[DMA_RX_NUM] = { MPU_INT_STATUS | MPU_SPI_READ_MSB}; #endif #define IMU_BOARD_INSTALL_SPIN_MATRIX \ { 0.0f, 1.0f, 0.0f}, \ {-1.0f, 0.0f, 0.0f}, \ { 0.0f, 0.0f, 1.0f} \ /*********************** 全局变量定义 ***************************/ //处理陀螺仪,加速度计,磁力计数据的线性度,零漂 static void IMU_Cali_Slove(fp32 gyro[3], fp32 accel[3], fp32 mag[3], mpu6500_real_data_t *mpu6500, ist8310_real_data_t *ist8310); static void IMU_temp_Control(fp32 temp); uint8_t mpu6500_spi_rxbuf[DMA_RX_NUM]; //保存接收的原始数据 //static mpu6500_real_data_t mpu6500_real_data; //转换成国际单位的MPU6500数据 mpu6500_real_data_t mpu6500_real_data; //转换成国际单位的MPU6500数据 static fp32 Gyro_Scale_Factor[3][3] = {IMU_BOARD_INSTALL_SPIN_MATRIX}; //陀螺仪校准线性度 //static fp32 gyro_cali_offset[3] ={0.0f, 0.0f, 0.0f}; fp32 gyro_cali_offset[3] ={0.0f, 0.0f, 0.0f}; //static fp32 Gyro_Offset[3] = {0.0f, 0.0f, 0.0f}; //陀螺仪零漂 fp32 Gyro_Offset[3] = {0.0f, 0.0f, 0.0f}; //陀螺仪零漂 static fp32 Accel_Scale_Factor[3][3] = {IMU_BOARD_INSTALL_SPIN_MATRIX}; //加速度校准线性度 static fp32 Accel_Offset[3] = {0.0f, 0.0f, 0.0f}; //加速度零漂 static ist8310_real_data_t ist8310_real_data; //转换成国际单位的IST8310数据 static fp32 Mag_Scale_Factor[3][3] = {{1.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}}; //磁力计校准线性度 //static fp32 Mag_Offset[3] = {0.0f, 0.0f, 0.0f}; //磁力计零漂 fp32 Mag_Offset[3] = {0.0f, 0.0f, 0.0f}; //磁力计零漂 static const float TimingTime = INS_DELTA_TICK * 0.001f; //任务运行的时间 单位 s fp32 INS_gyro[3] = {0.0f, 0.0f, 0.0f}; static fp32 INS_accel[3] = {0.0f, 0.0f, 0.0f}; static fp32 INS_mag[3] = {0.0f, 0.0f, 0.0f}; fp32 INS_Angle[3] = {0.0f, 0.0f, 0.0f}; //欧拉角 单位 rad 为了DEBUG方便,我把Static修饰符删掉了 static fp32 INS_quat[4] = {0.0f, 0.0f, 0.0f, 0.0f}; //四元数 static const fp32 imuTempPID[3] = {MPU6500_TEMPERATURE_PID_KP, MPU6500_TEMPERATURE_PID_KI, MPU6500_TEMPERATURE_PID_KD}; static PidTypeDef imuTempPid; static uint8_t first_temperate = 0; //KZ_Filter()参数 fp32 k = 0; fp32 sum = 0; fp32 Value = 0.; fp32 NewValue; fp32 new_value = 0.000000000001; fp32 kzkz = 0; fp32 sdfor = 1.73e-05;//零漂系数,由flash写入,值越大零漂消除越好,4e-05时消除所有零漂,但是越大越容易导致操作延迟 //平滑度处理 fp32 filter_sum = 0; #define FILTER_N 12 fp32 coe[FILTER_N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // 加权系数表 fp32 sum_coe = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12; // 加权系数和 fp32 filter_buf[FILTER_N + 1]; static fp32 KZ_Filter(void) { kzkz = NewValue - INS_Angle[0]; NewValue = INS_Angle[0]; if((kzkz > sdfor) || (kzkz < ( - sdfor))) { new_value = Value; Value = NewValue - sum; } else sum += kzkz; filter_buf[FILTER_N] = Value; for(uint32_t i = 0; i < FILTER_N; i++) { filter_buf[i] = filter_buf[i + 1]; // 所有数据左移,低位仍掉 filter_sum += filter_buf[i] * coe[i]; } filter_sum /= sum_coe; k = (filter_sum /3.14)*180;//观测值,360度单位 return filter_sum; } /************************ 函数内容 ******************************/ /** * @brief IMU的值更新 * @author Stone * @param[in] void * @retval void */ void IMU_Update(void) { //将读取到的mpu6500原始数据处理成国际单位的数据 mpu6500_read_over((mpu6500_spi_rxbuf + MPU6500_RX_BUF_DATA_OFFSET), &mpu6500_real_data); //将读取到的ist8310原始数据处理成国际单位的数据 ist8310_read_over((mpu6500_spi_rxbuf + IST8310_RX_BUF_DATA_OFFSET), &ist8310_real_data); //减去零漂以及旋转坐标系 IMU_Cali_Slove(INS_gyro, INS_accel, INS_mag, &mpu6500_real_data, &ist8310_real_data); //加速度计低通滤波 static fp32 accel_fliter_1[3] = {0.0f, 0.0f, 0.0f}; static fp32 accel_fliter_2[3] = {0.0f, 0.0f, 0.0f}; static fp32 accel_fliter_3[3] = {0.0f, 0.0f, 0.0f}; static const fp32 fliter_num[3] = {1.929454039488895f, -0.93178349823448126f, 0.002329458745586203f}; //判断是否第一次进入,如果第一次则初始化四元数,之后更新四元数计算角度单位rad static uint8_t updata_count = 0; if( mpu6500_real_data.status & 1 << MPU_DATA_READY_BIT)//#define MPU_DATA_READY_BIT 0 //陀螺仪数据准备 { //判断是否为第一次进入 //如果是,那么进入,第一次初始化温控和四元数 if (updata_count == 0) { /*IMU温控部分,暂时不用*/ //MPU6500_TEMPERATURE_PWM_INIT(); //PID_Init(&imuTempPid, PID_DELTA, imuTempPID, MPU6500_TEMPERATURE_PID_MAX_OUT, MPU6500_TEMPERATURE_PID_MAX_IOUT); /*IMU温控部分,暂时不用*/ //根据加速度的数据INS_accel[],磁力计的数据INS_mag[]进行四元数INS_quat[]初始化 AHRS_init(INS_quat, INS_accel, INS_mag); //根据四元数INS_quat[]大小计算对应的欧拉角yaw(INS_Angle[0]),pitch(INS_Angle[1]),roll(INS_Angle[2]) get_angle(INS_quat, INS_Angle, INS_Angle + 1, INS_Angle + 2); accel_fliter_1[0] = accel_fliter_2[0] = accel_fliter_3[0] = INS_accel[0]; accel_fliter_1[1] = accel_fliter_2[1] = accel_fliter_3[1] = INS_accel[1]; accel_fliter_1[2] = accel_fliter_2[2] = accel_fliter_3[2] = INS_accel[2]; updata_count++; } else { //加速度计低通滤波 accel_fliter_1[0] = accel_fliter_2[0]; accel_fliter_2[0] = accel_fliter_3[0]; accel_fliter_3[0] = accel_fliter_2[0] * fliter_num[0] + accel_fliter_1[0] * fliter_num[1] + INS_accel[0] * fliter_num[2]; accel_fliter_1[1] = accel_fliter_2[1]; accel_fliter_2[1] = accel_fliter_3[1]; accel_fliter_3[1] = accel_fliter_2[1] * fliter_num[0] + accel_fliter_1[1] * fliter_num[1] + INS_accel[1] * fliter_num[2]; accel_fliter_1[2] = accel_fliter_2[2]; accel_fliter_2[2] = accel_fliter_3[2]; accel_fliter_3[2] = accel_fliter_2[2] * fliter_num[0] + accel_fliter_1[2] * fliter_num[1] + INS_accel[2] * fliter_num[2]; //更新四元数 AHRS_update(INS_quat, TimingTime, INS_gyro, accel_fliter_3, INS_mag);//姿态解算+互补滤波 get_angle(INS_quat, INS_Angle, INS_Angle + 1, INS_Angle + 2); KZ_Filter(); //陀螺仪开机校准 { static uint16_t start_gyro_cali_time = 0; if(start_gyro_cali_time == 0) { Gyro_Offset[0] = gyro_cali_offset[0]; Gyro_Offset[1] = gyro_cali_offset[1]; Gyro_Offset[2] = gyro_cali_offset[2]; start_gyro_cali_time++; } // else if (start_gyro_cali_time < GYRO_OFFSET_START_TIME) // { // IMUWarnBuzzerOn(); // // if( first_temperate) // { // //当进入gyro_offset函数,如果无运动start_gyro_cali_time++,如果有运动 start_gyro_cali_time = 0 // gyro_offset(Gyro_Offset, INS_gyro, mpu6500_real_data.status, &start_gyro_cali_time); // } // } // else if (start_gyro_cali_time == GYRO_OFFSET_START_TIME) // { // IMUWarnBuzzerOFF(); // start_gyro_cali_time++; // } } } } //IMU_temp_Control(mpu6500_real_data.temp); } /** * @brief MPU6500和IST8310初始化 * @author Stone * @param[in] void * @retval void */ void IMU_Setup(void) { //初始化mpu6500,失败进入死循环 //SPI5 + DMA while (mpu6500_init() != MPU6500_NO_ERROR) {} //初始化ist8310,失败进入死循环 //模拟IIC while (ist8310_init() != IST8310_NO_ERROR) {} //初始化mpu6500的数据准备的外部中断 MPU6500_DATA_READY_EXIT_INIT(); //初始化SPI的DMA传输的方法 MPU6500_SPI_DMA_Init(mpu6500_spi_DMA_txbuf, mpu6500_spi_rxbuf); } /** * @brief 校准陀螺仪 * @author RM * @param[in] 陀螺仪的比例因子,1.0f为默认值,不修改 * @param[in] 陀螺仪的零漂,采集陀螺仪的静止的输出作为offset * @param[in] 陀螺仪的时刻,每次在gyro_offset调用会加1, * @retval 返回空 */ void INS_cali_gyro(fp32 cali_scale[3], fp32 cali_offset[3], uint16_t *time_count) { if (first_temperate) { if( *time_count == 0) { Gyro_Offset[0] = gyro_cali_offset[0]; Gyro_Offset[1] = gyro_cali_offset[1]; Gyro_Offset[2] = gyro_cali_offset[2]; } gyro_offset(Gyro_Offset, INS_gyro, mpu6500_real_data.status, time_count); cali_offset[0] = Gyro_Offset[0]; cali_offset[1] = Gyro_Offset[1]; cali_offset[2] = Gyro_Offset[2]; } } /** * @brief 校准陀螺仪设置,将从flash或者其他地方传入校准值 * @author RM * @param[in] 陀螺仪的比例因子,1.0f为默认值,不修改 * @param[in] 陀螺仪的零漂 * @retval 返回空 */ void INS_set_cali_gyro(fp32 cali_scale[3], fp32 cali_offset[3]) { gyro_cali_offset[0] = cali_offset[0]; gyro_cali_offset[1] = cali_offset[1]; gyro_cali_offset[2] = cali_offset[2]; } /** * @brief 取得角度值指针 * @author Stone * @param[in] void * @retval INS_Angle[]数组首元素地址 */ const fp32 *get_INS_angle_point(void) { return INS_Angle; } /** * @brief 取得陀螺仪值指针 * @author Stone * @param[in] void * @retval INS_gyro[]数组首元素地址 */ const fp32 *get_MPU6500_Gyro_Data_Point(void) { return INS_gyro; } /** * @brief 取得加速度计值指针 * @author Stone * @param[in] void * @retval INS_accel[]数组首元素地址 */ const fp32 *get_MPU6500_Accel_Data_Point(void) { return INS_accel; } /** * @brief 减去零漂以及旋转坐标系 * @author Stone * @param[in] IMU9轴的值 * @retval void */ //Gyro_Scale_Factor[i][0]陀螺仪校准线性度 static void IMU_Cali_Slove(fp32 gyro[3], fp32 accel[3], fp32 mag[3], mpu6500_real_data_t *mpu6500, ist8310_real_data_t *ist8310) { for (uint8_t i = 0; i < 3; i++) { gyro[i] = mpu6500->gyro[0] * Gyro_Scale_Factor[i][0] + mpu6500->gyro[1] * Gyro_Scale_Factor[i][1] + mpu6500->gyro[2] * Gyro_Scale_Factor[i][2] + Gyro_Offset[i]; accel[i] = mpu6500->accel[0] * Accel_Scale_Factor[i][0] + mpu6500->accel[1] * Accel_Scale_Factor[i][1] + mpu6500->accel[2] * Accel_Scale_Factor[i][2] + Accel_Offset[i]; mag[i] = ist8310->mag[0] * Mag_Scale_Factor[i][0] + ist8310->mag[1] * Mag_Scale_Factor[i][1] + ist8310->mag[2] * Mag_Scale_Factor[i][2] + Mag_Offset[i]; } } /** * @brief IMU恒温控制,控制成比MCU的温度高10度 * @author Stone * @param[in] IMU的实时温度 * @retval void */ static void IMU_temp_Control(fp32 temp) { uint16_t tempPWM; static uint8_t temp_constant_time = 0 ; if (first_temperate) { PID_Calc(&imuTempPid, temp, INS_GET_CONTROL_TEMPERATURE()); if (imuTempPid.out < 0.0f) { imuTempPid.out = 0.0f; } tempPWM = (uint16_t)imuTempPid.out; IMUTempPWM(tempPWM); } else { //在没有达到设置的温度,一直最大功率加热 if (temp > INS_GET_CONTROL_TEMPERATURE()) { temp_constant_time ++; if(temp_constant_time > 200) { //达到设置温度,将积分项设置为一半最大功率,加速收敛 first_temperate = 1; imuTempPid.Iout = MPU6500_TEMP_PWM_MAX / 2.0f; } } IMUTempPWM(MPU6500_TEMP_PWM_MAX - 1); } } //////////////////////////////////////////// #if defined(MPU6500_USE_DATA_READY_EXIT) void MPU6500_DATA_READY_EXIT_IRQHandler(void) { if (EXTI_GetITStatus(MPU6500_DATA_READY_EXIT_Line) != RESET) { EXTI_ClearITPendingBit(MPU6500_DATA_READY_EXIT_Line); //如果开启DMA传输 唤醒任务由DMA中断完成 #if defined(MPU6500_USE_SPI_DMA) mpu6500_SPI_NS_L(); MPU6500_SPI_DMA_Enable(); #endif } } #endif //////////////////////////////////////////// #if defined(MPU6500_USE_SPI) && defined(MPU6500_USE_SPI_DMA) void MPU6500_DMA_IRQHandler(void) { if (DMA_GetFlagStatus(MPU6500_DMA_Stream, MPU6500_DMA_FLAG)) { DMA_ClearFlag(MPU6500_DMA_Stream, MPU6500_DMA_FLAG); mpu6500_SPI_NS_H(); } } #endif <file_sep>#include "GM6020_pwm.h" void GM6020_PWM_configuration(void) //TIM5_CH1 H10 TIM5_CH2 H11 { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; //初始化TIM5 //TIM5 CH1 H10 RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5,ENABLE); //TIM5时钟使能 RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOH, ENABLE); //使能PORTH时钟 GPIO_PinAFConfig(GPIOH,GPIO_PinSource10,GPIO_AF_TIM5); //GPIOH10复用为定时器5 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //GPIOH10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; //复用功能 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度100MHz GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉 GPIO_Init(GPIOH,&GPIO_InitStructure); //初始化GPIOH /* ---------------- PWM信号 周期和占空比的计算--------------- */ // ARR :自动重装载寄存器的值 // CLK_cnt:计数器的时钟,等于 Fck_int / (psc+1) = 72M/(psc+1) // PWM 信号的周期 T = ARR * (1/CLK_cnt) = ARR*(PSC+1) / 72M // 占空比P=CCR/(ARR+1) // 若Period = 19,则+1得20,计一次数的周期为1/CLK_CNT = 71+1/72000000 = 0.000001s,则PWM周期为20x0.000001s=0.00002s=20us=50000HZ=50KHZ //180000 19 //20000/180000000 TIM_TimeBaseStructure.TIM_Prescaler=90-1; //定时器分频 TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up; //向上计数模式 TIM_TimeBaseStructure.TIM_Period=20000 - 1; //自动重装载值 TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM5,&TIM_TimeBaseStructure);//初始化定时器5 TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //选择定时器模式:TIM脉冲宽度调制模式2 TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能 TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性:TIM输出比较极性低 TIM_OC1Init(TIM5, &TIM_OCInitStructure); //根据T指定的参数初始化外设TIM1 4OC1 通道1 TIM_OC1PreloadConfig(TIM5, TIM_OCPreload_Enable); //使能TIM12在CCR1上的预装载寄存器 TIM_ARRPreloadConfig(TIM5,ENABLE);//ARPE使能 TIM_Cmd(TIM5, ENABLE); //使能TIM12 //TIM5 CH2 H11 GPIO_PinAFConfig(GPIOH,GPIO_PinSource11,GPIO_AF_TIM5); //GPIOH11复用为定时器5 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; //GPIOH11 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; //复用功能 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; //速度100MHz GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉 GPIO_Init(GPIOH,&GPIO_InitStructure); //初始化GPIOH TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //选择定时器模式:TIM脉冲宽度调制模式2 TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能 TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性:TIM输出比较极性低 TIM_OC2Init(TIM5, &TIM_OCInitStructure); //根据T指定的参数初始化外设TIM1 4OC2 TIM_OC2PreloadConfig(TIM5, TIM_OCPreload_Enable); //使能TIM12在CCR1上的预装载寄存器 TIM_ARRPreloadConfig(TIM5,ENABLE);//ARPE使能 TIM_Cmd(TIM5, ENABLE); //使能TIM5 TIM_SetCompare1(TIM5,1520); } <file_sep>#ifndef _PUSH_MOTOR_H_ #define _PUSH_MOTOR_H_ #include "stm32f4xx.h" #define PUSH_CW_SPEED 1550 //1520 - 1920 #define PUSH_CCW_SPEED 1400 //1080 - 1480 void Push_Wheel_Stop(void); void Push_Wheel_CCW(void); void Push_Wheel_CW(void); #endif <file_sep>#ifndef USER_TASK_H #define USER_TASK_H extern void UserTask_Setup(void); extern void UserTask(void); #endif <file_sep>#ifndef BUZZER_H #define BUZZER_H #include "main.h" extern void buzzer_init(uint16_t arr, uint16_t psc); extern void buzzer_on(uint16_t psc, uint16_t pwm); extern void buzzer_off(void); extern void BSPInit_CompleteBeep(void); extern void CodeTestSound(void); #endif <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file chassis_behaviour.c/h * @brief 完成底盘行为任务。 * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ #include "chassis_behaviour.h" #include "chassis_task.h" #include "arm_math.h" #include "gimbal_behaviour.h" /** * @brief 底盘无力的行为状态机下,底盘模式是raw,故而设定值会直接发送到can总线上故而将设定值都设置为0 * @author RM * @param[in] vx_set前进的速度 设定值将直接发送到can总线上 * @param[in] vy_set左右的速度 设定值将直接发送到can总线上 * @param[in] wz_set旋转的速度 设定值将直接发送到can总线上 * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_zero_force_control(fp32 *vx_can_set, fp32 *vy_can_set, fp32 *wz_can_set, chassis_move_t *chassis_move_rc_to_vector); /** * @brief 底盘不移动的行为状态机下,底盘模式是不跟随角度, * @author RM * @param[in] vx_set前进的速度 * @param[in] vy_set左右的速度 * @param[in] wz_set旋转的速度,旋转速度是控制底盘的底盘角速度 * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_no_move_control(fp32 *vx_set, fp32 *vy_set, fp32 *wz_set, chassis_move_t *chassis_move_rc_to_vector); /** * @brief 底盘跟随云台的行为状态机下,底盘模式是跟随云台角度,底盘旋转速度会根据角度差计算底盘旋转的角速度 * @author RM * @param[in] vx_set前进的速度 * @param[in] vy_set左右的速度 * @param[in] angle_set底盘与云台控制到的相对角度 * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_infantry_follow_gimbal_yaw_control(fp32 *vx_set, fp32 *vy_set, fp32 *angle_set, chassis_move_t *chassis_move_rc_to_vector); /** * @brief 底盘跟随底盘yaw的行为状态机下,底盘模式是跟随底盘角度,底盘旋转速度会根据角度差计算底盘旋转的角速度 * @author RM * @param[in] vx_set前进的速度 * @param[in] vy_set左右的速度 * @param[in] angle_set底盘设置的yaw,范围 -PI到PI * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_engineer_follow_chassis_yaw_control(fp32 *vx_set, fp32 *vy_set, fp32 *angle_set, chassis_move_t *chassis_move_rc_to_vector); /** * @brief 底盘不跟随角度的行为状态机下,底盘模式是不跟随角度,底盘旋转速度由参数直接设定 * @author RM * @param[in] vx_set前进的速度 * @param[in] vy_set左右的速度 * @param[in] wz_set底盘设置的旋转速度 * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_no_follow_yaw_control(fp32 *vx_set, fp32 *vy_set, fp32 *wz_set, chassis_move_t *chassis_move_rc_to_vector); /** * @brief 底盘开环的行为状态机下,底盘模式是raw原生状态,故而设定值会直接发送到can总线上 * @author RM * @param[in] vx_set前进的速度 * @param[in] vy_set左右的速度 * @param[in] wz_set底盘设置的旋转速度 * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_open_set_control(fp32 *vx_set, fp32 *vy_set, fp32 *wz_set, chassis_move_t *chassis_move_rc_to_vector); //底盘行为状态机 static chassis_behaviour_e chassis_behaviour_mode = CHASSIS_ZERO_FORCE; void chassis_behaviour_mode_set(chassis_move_t *chassis_move_mode) { if (chassis_move_mode == NULL) { return; } //遥控器设置行为模式 //检测遥控器拨扭是否朝中 -》 底盘不跟随云台 // if (switch_is_mid(chassis_move_mode->chassis_RC->rc.s[MODE_CHANNEL])) // { // chassis_behaviour_mode = CHASSIS_NO_FOLLOW_YAW; // } //检测遥控器拨扭是否朝下 -》 底盘不移动 if (switch_is_down(chassis_move_mode->chassis_RC->rc.s[MODE_CHANNEL])) { chassis_behaviour_mode = CHASSIS_NO_MOVE; } //检测遥控器拨扭是否朝上 -》底盘随动 else if (switch_is_up(chassis_move_mode->chassis_RC->rc.s[MODE_CHANNEL])) { chassis_behaviour_mode = CHASSIS_INFANTRY_FOLLOW_GIMBAL_YAW; } else { chassis_behaviour_mode = CHASSIS_NO_MOVE; } //云台进入某些状态的时候,底盘保持不动 if (gimbal_cmd_to_chassis_stop()) { chassis_behaviour_mode = CHASSIS_NO_MOVE; } //根据行为状态机选择底盘状态机 if (chassis_behaviour_mode == CHASSIS_ZERO_FORCE) { chassis_move_mode->chassis_mode = CHASSIS_VECTOR_RAW; //当行为是底盘无力,则设置底盘状态机为 raw,原生状态机。 } else if (chassis_behaviour_mode == CHASSIS_NO_MOVE) { chassis_move_mode->chassis_mode = CHASSIS_VECTOR_NO_FOLLOW_YAW; //当行为是底盘不移动,则设置底盘状态机为 底盘不跟随角度 状态机。 } else if (chassis_behaviour_mode == CHASSIS_INFANTRY_FOLLOW_GIMBAL_YAW) { chassis_move_mode->chassis_mode = CHASSIS_VECTOR_FOLLOW_GIMBAL_YAW; //当行为是正常步兵跟随云台,则设置底盘状态机为 底盘跟随云台角度 状态机。 } else if (chassis_behaviour_mode == CHASSIS_ENGINEER_FOLLOW_CHASSIS_YAW) { chassis_move_mode->chassis_mode = CHASSIS_VECTOR_FOLLOW_CHASSIS_YAW; //当行为是工程跟随底盘角度,则设置底盘状态机为 底盘跟随底盘角度 状态机。 } else if (chassis_behaviour_mode == CHASSIS_NO_FOLLOW_YAW) { chassis_move_mode->chassis_mode = CHASSIS_VECTOR_NO_FOLLOW_YAW; //当行为是底盘不跟随角度,则设置底盘状态机为 底盘不跟随角度 状态机。 } else if (chassis_behaviour_mode == CHASSIS_OPEN) { chassis_move_mode->chassis_mode = CHASSIS_VECTOR_RAW; //当行为是底盘开环,则设置底盘状态机为 底盘原生raw 状态机。 } } void chassis_behaviour_control_set(fp32 *vx_set, fp32 *vy_set, fp32 *angle_set, chassis_move_t *chassis_move_rc_to_vector) { if (vx_set == NULL || vy_set == NULL || angle_set == NULL || chassis_move_rc_to_vector == NULL) { return; } if (chassis_behaviour_mode == CHASSIS_ZERO_FORCE) { chassis_zero_force_control(vx_set, vy_set, angle_set, chassis_move_rc_to_vector); } else if (chassis_behaviour_mode == CHASSIS_NO_MOVE) { chassis_no_move_control(vx_set, vy_set, angle_set, chassis_move_rc_to_vector); } else if (chassis_behaviour_mode == CHASSIS_INFANTRY_FOLLOW_GIMBAL_YAW) { chassis_infantry_follow_gimbal_yaw_control(vx_set, vy_set, angle_set, chassis_move_rc_to_vector); } else if (chassis_behaviour_mode == CHASSIS_ENGINEER_FOLLOW_CHASSIS_YAW) { chassis_engineer_follow_chassis_yaw_control(vx_set, vy_set, angle_set, chassis_move_rc_to_vector); } else if (chassis_behaviour_mode == CHASSIS_NO_FOLLOW_YAW) { chassis_no_follow_yaw_control(vx_set, vy_set, angle_set, chassis_move_rc_to_vector); } else if (chassis_behaviour_mode == CHASSIS_OPEN) { chassis_open_set_control(vx_set, vy_set, angle_set, chassis_move_rc_to_vector); } } /** * @brief 底盘无力的行为状态机下,底盘模式是raw,故而设定值会直接发送到can总线上故而将设定值都设置为0 * @author RM * @param[in] vx_set前进的速度 设定值将直接发送到can总线上 * @param[in] vy_set左右的速度 设定值将直接发送到can总线上 * @param[in] wz_set旋转的速度 设定值将直接发送到can总线上 * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_zero_force_control(fp32 *vx_can_set, fp32 *vy_can_set, fp32 *wz_can_set, chassis_move_t *chassis_move_rc_to_vector) { if (vx_can_set == NULL || vy_can_set == NULL || wz_can_set == NULL || chassis_move_rc_to_vector == NULL) { return; } *vx_can_set = 0.0f; *vy_can_set = 0.0f; *wz_can_set = 0.0f; } /** * @brief 底盘不移动的行为状态机下,底盘模式是不跟随角度, * @author RM * @param[in] vx_set前进的速度 * @param[in] vy_set左右的速度 * @param[in] wz_set旋转的速度,旋转速度是控制底盘的底盘角速度 * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_no_move_control(fp32 *vx_set, fp32 *vy_set, fp32 *wz_set, chassis_move_t *chassis_move_rc_to_vector) { if (vx_set == NULL || vy_set == NULL || wz_set == NULL || chassis_move_rc_to_vector == NULL) { return; } *vx_set = 0.0f; *vy_set = 0.0f; *wz_set = 0.0f; } /** * @brief 底盘跟随云台的行为状态机下,底盘模式是跟随云台角度,底盘旋转速度会根据角度差计算底盘旋转的角速度 * @author RM * @param[in] vx_set前进的速度 * @param[in] vy_set左右的速度 * @param[in] angle_set底盘与云台控制到的相对角度 * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_infantry_follow_gimbal_yaw_control(fp32 *vx_set, fp32 *vy_set, fp32 *angle_set, chassis_move_t *chassis_move_rc_to_vector) { if (vx_set == NULL || vy_set == NULL || angle_set == NULL || chassis_move_rc_to_vector == NULL) { return; } /******1.遥控器的数据处理成底盘的vx_set,vy_set******************/ chassis_rc_to_control_vector(vx_set, vy_set, chassis_move_rc_to_vector); /******2.判断是否摇摆 angle_set********************************************/ //摇摆角度是利用sin函数生成,swing_time 是sin函数的输入值 static fp32 swing_time = 0.0f; //swing_time 是计算出来的角度 static fp32 swing_angle = 0.0f; //max_angle 是sin函数的幅值 static fp32 max_angle = SWING_NO_MOVE_ANGLE; //add_time 是摇摆角度改变的快慢,最大越快 static fp32 const add_time = PI / 250.0f; //使能摇摆标志位 static uint8_t swing_flag = 0; //计算遥控器的原始输入信号 //判断是否要摇摆 if ((chassis_move_rc_to_vector->chassis_RC->rc.s[Swing]) == 1 ) //if (chassis_move_rc_to_vector->chassis_RC->key.v & SWING_KEY) { if (swing_flag == 0) { swing_flag = 1; swing_time = 0.0f; } } else { swing_flag = 0; } //判断键盘输入是不是在控制底盘运动,底盘在运动减小摇摆角度 if (chassis_move_rc_to_vector->chassis_RC->key.v & CHASSIS_FRONT_KEY || chassis_move_rc_to_vector->chassis_RC->key.v & CHASSIS_BACK_KEY || chassis_move_rc_to_vector->chassis_RC->key.v & CHASSIS_LEFT_KEY || chassis_move_rc_to_vector->chassis_RC->key.v & CHASSIS_RIGHT_KEY) { max_angle = SWING_MOVE_ANGLE; } else { max_angle = SWING_NO_MOVE_ANGLE; } //sin函数生成控制角度 if (swing_flag) { swing_angle = max_angle * arm_sin_f32(swing_time); swing_time += add_time; } else { swing_angle = 0.0f; } //sin函数不超过2pi if (swing_time > 2 * PI) { swing_time -= 2 * PI; } *angle_set = swing_angle; } /** * @brief 底盘跟随底盘yaw的行为状态机下,底盘模式是跟随底盘角度,底盘旋转速度会根据角度差计算底盘旋转的角速度 * @author RM * @param[in] vx_set前进的速度 * @param[in] vy_set左右的速度 * @param[in] angle_set底盘设置的yaw,范围 -PI到PI * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_engineer_follow_chassis_yaw_control(fp32 *vx_set, fp32 *vy_set, fp32 *angle_set, chassis_move_t *chassis_move_rc_to_vector) { if (vx_set == NULL || vy_set == NULL || angle_set == NULL || chassis_move_rc_to_vector == NULL) { return; } chassis_rc_to_control_vector(vx_set, vy_set, chassis_move_rc_to_vector); *angle_set = rad_format(chassis_move_rc_to_vector->chassis_yaw_set - CHASSIS_ANGLE_Z_RC_SEN * chassis_move_rc_to_vector->chassis_RC->rc.ch[CHASSIS_WZ_CHANNEL]); } /** * @brief 底盘不跟随角度的行为状态机下,底盘模式是不跟随角度,底盘旋转速度由参数直接设定 * @author RM * @param[in] vx_set前进的速度 * @param[in] vy_set左右的速度 * @param[in] wz_set底盘设置的旋转速度 * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_no_follow_yaw_control(fp32 *vx_set, fp32 *vy_set, fp32 *wz_set, chassis_move_t *chassis_move_rc_to_vector) { if (vx_set == NULL || vy_set == NULL || wz_set == NULL || chassis_move_rc_to_vector == NULL) { return; } chassis_rc_to_control_vector(vx_set, vy_set, chassis_move_rc_to_vector); *wz_set = -CHASSIS_WZ_RC_SEN * chassis_move_rc_to_vector->chassis_RC->rc.ch[CHASSIS_WZ_CHANNEL]; } /** * @brief 底盘开环的行为状态机下,底盘模式是raw原生状态,故而设定值会直接发送到can总线上 * @author RM * @param[in] vx_set前进的速度 * @param[in] vy_set左右的速度 * @param[in] wz_set底盘设置的旋转速度 * @param[in] chassis_move_rc_to_vector底盘数据 * @retval 返回空 */ static void chassis_open_set_control(fp32 *vx_set, fp32 *vy_set, fp32 *wz_set, chassis_move_t *chassis_move_rc_to_vector) { if (vx_set == NULL || vy_set == NULL || wz_set == NULL || chassis_move_rc_to_vector == NULL) { return; } *vx_set = chassis_move_rc_to_vector->chassis_RC->rc.ch[CHASSIS_X_CHANNEL] * CHASSIS_OPEN_RC_SCALE; *vy_set = -chassis_move_rc_to_vector->chassis_RC->rc.ch[CHASSIS_Y_CHANNEL] * CHASSIS_OPEN_RC_SCALE; *wz_set = -chassis_move_rc_to_vector->chassis_RC->rc.ch[CHASSIS_WZ_CHANNEL] * CHASSIS_OPEN_RC_SCALE; return; } <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file chassis.c/h * @brief 完成底盘控制任务。 * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2019 BDT**************************** */ /************************* 头文件 ******************************/ #include "chassis_task.h" #include "rc.h" #include "arm_math.h" #include "CAN_Receive.h" #include "Detect_Task.h" #include "pid.h" #include "Remote_Control.h" #include "INS_Task.h" #include "delay.h" #include "chassis_behaviour.h" #include "referee_API.h" /************************* 宏定义 ******************************************************************/ #define rc_deadline_limit(input, output, dealine) \ { \ if ((input) > (dealine) || (input) < -(dealine)) \ { \ (output) = (input); \ } \ else \ { \ (output) = 0; \ } \ } #define POWER_LIMIT 80.0f #define WARNING_POWER 40.0f #define WARNING_POWER_BUFF 50.0f #define NO_JUDGE_TOTAL_CURRENT_LIMIT 64000.0f //16000 * 4, 在没有裁判系统功率限制下的最大电流限制 #define BUFFER_TOTAL_CURRENT_LIMIT 16000.0f #define POWER_TOTAL_CURRENT_LIMIT 20000.0f /*********************** 全局变量定义 ***************************************************************/ //底盘运动数据结构体定义 //static chassis_move_t chassis_move; chassis_move_t chassis_move; /*********************** 静态函数声明 ***************************************************************/ //底盘初始化,主要是pid初始化 static void chassis_init(chassis_move_t *chassis_move_init); //底盘状态机选择,通过遥控器的开关 static void chassis_set_mode(chassis_move_t *chassis_move_mode); //超级电容控制模式更新 static void super_cap_mode_set(chassis_move_t *chassis_move); //底盘数据更新 static void chassis_feedback_update(chassis_move_t *chassis_move_update); //底盘状态改变后处理控制量的改变static void chassis_mode_change_control_transit(chassis_move_t *chassis_move_transit); //底盘设置根据遥控器控制量 static void chassis_set_contorl(chassis_move_t *chassis_move_control); //底盘PID计算以及运动分解 static void chassis_control_loop(chassis_move_t *chassis_move_control_loop); //底盘功率限制 static void chassis_power_control(chassis_move_t *chassis_power_control); static void super_power_data_transmit(chassis_move_t *chassis_move); /*********************** 函数定义 *********************************************************************************/ const float *get_Voltage_Point(void) { return &chassis_move.super_cap.voltage; } void chassis_Setup(void) { //底盘初始化 chassis_init(&chassis_move); //判断底盘电机是否都在线 // while (toe_is_error(ChassisMotor1TOE) || toe_is_error(ChassisMotor2TOE) || toe_is_error(ChassisMotor3TOE) || toe_is_error(ChassisMotor4TOE) || toe_is_error(DBUSTOE)) // { // delay_ms(CHASSIS_CONTROL_TIME_MS); // } } //主任务 /************************ 主任务 ******************************************************/ void chassis_task(void) { chassis_set_mode(&chassis_move); //遥控器设置状态 chassis_mode_change_control_transit(&chassis_move); //遥控器状态切换数据保存 chassis_feedback_update(&chassis_move);//更新chassis_move -> motor_chassis[i].speed & accel 速度和加速度 // chassis_move -> vx & vy & wz 底盘三轴方向速度 编码器 // chassis_move_update->chassis_yaw & pitch & roll 底盘三轴欧拉角 陀螺仪 chassis_set_contorl(&chassis_move); //底盘控制量设置,设置遥控器输入控制量 chassis_control_loop(&chassis_move); //底盘控制PID计算 super_power_data_transmit(&chassis_move); //这里我把DetectTask的事情全部省略,为了方便程序移植,因此不会检测遥控器是否掉线,会一直有输出即代码104行的CAN_CMD_CHASSIS() // if (!(toe_is_error(ChassisMotor1TOE) || toe_is_error(ChassisMotor2TOE) || toe_is_error(ChassisMotor3TOE) || toe_is_error(ChassisMotor4TOE))) // { // //当遥控器掉线的时候,为relax状态,底盘电机指令为零,为了保证一定发送为零,故而不采用设置give_current的方法 // if (toe_is_error(DBUSTOE)) // { // CAN_CMD_CHASSIS(0, 0, 0, 0); // } // else // { // CAN_CMD_CHASSIS(chassis_move.motor_chassis[0].give_current, chassis_move.motor_chassis[1].give_current, // chassis_move.motor_chassis[2].give_current, chassis_move.motor_chassis[3].give_current); // } // } CAN_CMD_CHASSIS(chassis_move.motor_chassis[0].give_current, chassis_move.motor_chassis[1].give_current, chassis_move.motor_chassis[2].give_current, chassis_move.motor_chassis[3].give_current); } /*********************** 主任务初始化init ************************************************/ static void chassis_init(chassis_move_t *chassis_move_init) { if (chassis_move_init == NULL) { return; } //底盘速度环pid值 const static fp32 motor_speed_pid[3] = {M3505_MOTOR_SPEED_PID_KP, M3505_MOTOR_SPEED_PID_KI, M3505_MOTOR_SPEED_PID_KD}; //底盘角度环pid值 const static fp32 chassis_yaw_pid[3] = {CHASSIS_FOLLOW_GIMBAL_PID_KP, CHASSIS_FOLLOW_GIMBAL_PID_KI, CHASSIS_FOLLOW_GIMBAL_PID_KD}; //底盘一阶滤波参数 const static fp32 chassis_x_order_filter[1] = {CHASSIS_ACCEL_X_NUM}; const static fp32 chassis_y_order_filter[1] = {CHASSIS_ACCEL_Y_NUM}; uint8_t i; //底盘开机状态为停止 chassis_move_init->chassis_mode = CHASSIS_VECTOR_RAW; //CHASSIS_VECTOR_FOLLOW_GIMBAL_YAW //CHASSIS_VECTOR_FOLLOW_CHASSIS_YAW //CHASSIS_VECTOR_NO_FOLLOW_YAW /**** 遥控器数据指针获取 ****/ //CHASSIS_VECTOR_RAW chassis_move_init->chassis_RC = get_remote_control_point(); /**** 陀螺仪数据指针获取 ****/ //获取陀螺仪姿态角指针&INS_Angle[3] chassis_move_init->chassis_INS_angle = get_INS_angle_point(); /**** 电机数据指针获取 ****/ //获取云台电机数据指针 pitch轴和yaw轴的 chassis_move_init->chassis_yaw_motor = get_yaw_motor_point(); chassis_move_init->chassis_pitch_motor = get_pitch_motor_point(); /**** 初始化YAW和Pitch的PID参数 ****/ //初始化PID 运动 for (i = 0; i < 4; i++) { //获取底盘电机m3508的编码器从CAN总线返回的数据 //一共4个m3508因此结构体数组有4个成员 chassis_move_init->motor_chassis[i].chassis_motor_measure = get_Chassis_Motor_Measure_Point(i); //初始化4个电机各自的速度环PID,设置为位置式PID并将motor_speed_pid[3]的Kp,Ki,Kd参数输入,最后限幅 PID_Init(&chassis_move_init->motor_speed_pid[i], PID_POSITION, motor_speed_pid, M3505_MOTOR_SPEED_PID_MAX_OUT, M3505_MOTOR_SPEED_PID_MAX_IOUT); } //初始化角度环PID,设置为位置式PID并将chassis_yaw_pid的Kp,Ki,Kd参数输入,最后限幅 PID_Init(&chassis_move_init->chassis_angle_pid, PID_POSITION, chassis_yaw_pid, CHASSIS_FOLLOW_GIMBAL_PID_MAX_OUT, CHASSIS_FOLLOW_GIMBAL_PID_MAX_IOUT); //用一阶滤波代替斜波函数生成 //初始化后才可以使用一阶低通滤波 first_order_filter_init(&chassis_move_init->chassis_cmd_slow_set_vx, CHASSIS_CONTROL_TIME, chassis_x_order_filter); first_order_filter_init(&chassis_move_init->chassis_cmd_slow_set_vy, CHASSIS_CONTROL_TIME, chassis_y_order_filter); //限幅X方向和Y方向的运动速度【MAX and MIN】 chassis_move_init->vx_max_speed = NORMAL_MAX_CHASSIS_SPEED_X; chassis_move_init->vx_min_speed = -NORMAL_MAX_CHASSIS_SPEED_X; chassis_move_init->vy_max_speed = NORMAL_MAX_CHASSIS_SPEED_Y; chassis_move_init->vy_min_speed = -NORMAL_MAX_CHASSIS_SPEED_Y; chassis_move_init->super_cap.super_power_mcu_msg_pointer = get_SuperPowerMcu_Msg_Point(); chassis_move_init->super_cap.charge_cmd_state = Waiting; chassis_move_init->super_cap.charge_current_state = Waiting; chassis_move_init->super_cap.discharge_cmd_state = Waiting; chassis_move_init->super_cap.discharge_current_state = Waiting; chassis_move_init->super_cap.voltage = 0.0f; //更新一下数据 chassis_feedback_update(chassis_move_init); } /************************************ 1.chassis_Set_Mode ****************************************************/ //第一层chassis_set_mode(chassis_move_t *chassis_move_mode) [chassis_task.c static] //第二层 chassis_behaviour_mode_set(chassis_move_mode) [chassis_behaviour.c global] // 根据遥控器通道值来设置底盘行为状态机,给chassis_behaviour_mode赋值 // 如下6种模式 // CHASSIS_ZERO_FORCE, //底盘无力 // CHASSIS_NO_MOVE, //底盘保持不动 // CHASSIS_INFANTRY_FOLLOW_GIMBAL_YAW, //正常步兵底盘跟随云台 // CHASSIS_ENGINEER_FOLLOW_CHASSIS_YAW, //工程底盘角度控制底盘,由于底盘未有陀螺仪,故而角度是减去云台角度而得到,如果有底盘陀螺仪请更新底盘的yaw,pitch,roll角度 // CHASSIS_NO_FOLLOW_YAW, //底盘不跟随角度,角度是开环的,但前后左右是有速度环 // CHASSIS_OPEN //遥控器的值乘以比例直接发送到can总线上 // // 再根据底盘行为状态机chassis_behaviour_mode的值赋值底盘状态机chassis_move->chassis_mode // 如下3种状态值 // CHASSIS_VECTOR_FOLLOW_GIMBAL_YAW, //底盘随动云台 // CHASSIS_VECTOR_FOLLOW_CHASSIS_YAW, //底盘随动底盘 // CHASSIS_VECTOR_NO_FOLLOW_YAW, //底盘不随动 // CHASSIS_VECTOR_RAW, //原始底盘 static void chassis_set_mode(chassis_move_t *chassis_move_mode) { //检测是否输入是否为空指针 //如果是,则返回,防止错误设置底盘模式 if (chassis_move_mode == NULL) { return; } chassis_behaviour_mode_set(chassis_move_mode); super_cap_mode_set(chassis_move_mode); } u8 move_count_flag = 0; u8 count_flag = 0; static void super_cap_mode_set(chassis_move_t *chassis_move) { static uint16_t last_turn_keyboard = 0; static uint8_t mode_turn_flag = 0; if(chassis_move->chassis_RC->key.v & KEY_PRESSED_OFFSET_SHIFT ) { chassis_move->super_cap.discharge_cmd_state = Discharging; } else { chassis_move->super_cap.discharge_cmd_state = Waiting; } if( (chassis_move->chassis_RC->key.v & KEY_PRESSED_OFFSET_C) && !(last_turn_keyboard & KEY_PRESSED_OFFSET_C)) { if (mode_turn_flag == 0) { mode_turn_flag = 1; } } last_turn_keyboard = chassis_move->chassis_RC->key.v ; if (mode_turn_flag) { static u8 i = 0; if(chassis_move->super_cap.charge_cmd_state == Charging && i == 0 ) { chassis_move->super_cap.charge_cmd_state = Waiting; i++; } if(chassis_move->super_cap.charge_cmd_state == Waiting && i == 0) { chassis_move->super_cap.charge_cmd_state = Charging; i++; } i = 0; mode_turn_flag = 0; } } /**************************** 2.chassis_mode_change_control_transit ****************************/ static void chassis_mode_change_control_transit(chassis_move_t *chassis_move_transit) { //检测是否输入是否为空指针 //如果是,则返回,防止错误设置底盘模式 if (chassis_move_transit == NULL) { return; } if (chassis_move_transit->last_chassis_mode == chassis_move_transit->chassis_mode) { return; } //切入跟随云台模式 if ((chassis_move_transit->last_chassis_mode != CHASSIS_VECTOR_FOLLOW_GIMBAL_YAW) && chassis_move_transit->chassis_mode == CHASSIS_VECTOR_FOLLOW_GIMBAL_YAW) { chassis_move_transit->chassis_relative_angle_set = 0.0f; } //切入跟随底盘角度模式 else if ((chassis_move_transit->last_chassis_mode != CHASSIS_VECTOR_FOLLOW_CHASSIS_YAW) && chassis_move_transit->chassis_mode == CHASSIS_VECTOR_FOLLOW_CHASSIS_YAW) { chassis_move_transit->chassis_yaw_set = chassis_move_transit->chassis_yaw; } //切入不跟随云台模式 else if ((chassis_move_transit->last_chassis_mode != CHASSIS_VECTOR_NO_FOLLOW_YAW) && chassis_move_transit->chassis_mode == CHASSIS_VECTOR_NO_FOLLOW_YAW) { chassis_move_transit->chassis_yaw_set = chassis_move_transit->chassis_yaw; } chassis_move_transit->last_chassis_mode = chassis_move_transit->chassis_mode; } /********************************** 3.chassis_feedback_update ****************************************************/ //更新chassis_move -> motor_chassis[i].speed & accel 速度和加速度 // chassis_move -> vx & vy & wz 底盘三轴方向速度 // chassis_move -> chassis_yaw & pitch & roll 底盘三轴欧拉角 static void chassis_feedback_update(chassis_move_t *chassis_move_update) { if (chassis_move_update == NULL) { return; } /*********** 更新chassis_move->motor_chassis[i].speed和accel ***********/ uint8_t i = 0; for (i = 0; i < 4; i++) { //更新电机反馈的实际速度,加速度是速度的PID微分 chassis_move_update->motor_chassis[i].speed = CHASSIS_MOTOR_RPM_TO_VECTOR_SEN * ( chassis_move_update->motor_chassis[i].chassis_motor_measure->speed_rpm); chassis_move_update->motor_chassis[i].accel = chassis_move_update->motor_speed_pid[i].Dbuf[0] * CHASSIS_CONTROL_FREQUENCE; } /********** 根据更新的chassis_move->motor_chassis[i].speed来计算Vx,Vy,Wz ******************************/ chassis_move_update->vx = (-chassis_move_update->motor_chassis[0].speed + chassis_move_update->motor_chassis[1].speed + chassis_move_update->motor_chassis[2].speed - chassis_move_update->motor_chassis[3].speed )* MOTOR_SPEED_TO_CHASSIS_SPEED_VX; chassis_move_update->vy = (-chassis_move_update->motor_chassis[0].speed - chassis_move_update->motor_chassis[1].speed + chassis_move_update->motor_chassis[2].speed + chassis_move_update->motor_chassis[3].speed ) * MOTOR_SPEED_TO_CHASSIS_SPEED_VY; chassis_move_update->wz = (-chassis_move_update->motor_chassis[0].speed - chassis_move_update->motor_chassis[1].speed - chassis_move_update->motor_chassis[2].speed - chassis_move_update->motor_chassis[3].speed ) * MOTOR_SPEED_TO_CHASSIS_SPEED_WZ / MOTOR_DISTANCE_TO_CENTER; /********** 根据更新的INS_Angle[]和云台的relative angle去计算底盘姿态欧拉角chassis_move_update->chassis_yaw & pitch & roll ******************************/ //计算底盘姿态角度, 如果底盘上有陀螺仪请更改这部分代码 //底盘yaw姿态角度 = INS_Angle[0] - 云台yaw的relative_angle 【rad】 //底盘pitch姿态角度 = INS_Angle[1] - 云台pitch的relative angle 【rad】 //底盘roll姿态角度 = INS_Angle[2] 【rad】 chassis_move_update->chassis_yaw = rad_format(*(chassis_move_update->chassis_INS_angle + INS_YAW_ADDRESS_OFFSET) - chassis_move_update->chassis_yaw_motor->relative_angle); chassis_move_update->chassis_pitch = rad_format(*(chassis_move_update->chassis_INS_angle + INS_PITCH_ADDRESS_OFFSET) - chassis_move_update->chassis_pitch_motor->relative_angle); chassis_move_update->chassis_roll = *(chassis_move_update->chassis_INS_angle + INS_ROLL_ADDRESS_OFFSET); chassis_move_update->super_cap.discharge_current_state = chassis_move_update->super_cap.super_power_mcu_msg_pointer->msg1; chassis_move_update->super_cap.charge_current_state = chassis_move_update->super_cap.super_power_mcu_msg_pointer->msg2; chassis_move_update->super_cap.voltage = (((float)chassis_move_update->super_cap.super_power_mcu_msg_pointer->msg3) / 100.0f); } //遥控器的数据处理成底盘的vx_set,vy_set void chassis_rc_to_control_vector(fp32 *vx_set, fp32 *vy_set, chassis_move_t *chassis_move_rc_to_vector) { if (chassis_move_rc_to_vector == NULL || vx_set == NULL || vy_set == NULL) { return; } //遥控器原始通道值 int16_t vx_channel, vy_channel; fp32 vx_set_channel, vy_set_channel; //死区限制,因为遥控器可能存在差异 摇杆在中间,其值不为0 rc_deadline_limit(chassis_move_rc_to_vector->chassis_RC->rc.ch[CHASSIS_X_CHANNEL], vx_channel, CHASSIS_RC_DEADLINE); rc_deadline_limit(chassis_move_rc_to_vector->chassis_RC->rc.ch[CHASSIS_Y_CHANNEL], vy_channel, CHASSIS_RC_DEADLINE); vx_set_channel = vx_channel * CHASSIS_VX_RC_SEN; vy_set_channel = vy_channel * -CHASSIS_VY_RC_SEN; if (chassis_move_rc_to_vector->chassis_RC->key.v & CHASSIS_FRONT_KEY) { vx_set_channel = KEYBOARD_CHASSIS_SPEED_X; } else if (chassis_move_rc_to_vector->chassis_RC->key.v & CHASSIS_BACK_KEY) { vx_set_channel = -KEYBOARD_CHASSIS_SPEED_X; } if (chassis_move_rc_to_vector->chassis_RC->key.v & CHASSIS_LEFT_KEY) { vy_set_channel = KEYBOARD_CHASSIS_SPEED_Y; } else if (chassis_move_rc_to_vector->chassis_RC->key.v & CHASSIS_RIGHT_KEY) { vy_set_channel = -KEYBOARD_CHASSIS_SPEED_Y; } //一阶低通滤波代替斜波作为底盘速度输入 // In:vx_set_channel Out:chassis_move->chassis_cmd_slow_set_vx // In:vy_set_channel Out:chassis_move->chassis_cmd_slow_set_vy first_order_filter_cali(&chassis_move_rc_to_vector->chassis_cmd_slow_set_vx, vx_set_channel); first_order_filter_cali(&chassis_move_rc_to_vector->chassis_cmd_slow_set_vy, vy_set_channel); //停止信号,不需要缓慢加速,直接减速到零 //拨杆回中立即速度为0 if (vx_set_channel < CHASSIS_RC_DEADLINE * CHASSIS_VX_RC_SEN && vx_set_channel > -CHASSIS_RC_DEADLINE * CHASSIS_VX_RC_SEN) { chassis_move_rc_to_vector->chassis_cmd_slow_set_vx.out = 0.0f; } if (vy_set_channel < CHASSIS_RC_DEADLINE * CHASSIS_VY_RC_SEN && vy_set_channel > -CHASSIS_RC_DEADLINE * CHASSIS_VY_RC_SEN) { chassis_move_rc_to_vector->chassis_cmd_slow_set_vy.out = 0.0f; } *vx_set = chassis_move_rc_to_vector->chassis_cmd_slow_set_vx.out; *vy_set = chassis_move_rc_to_vector->chassis_cmd_slow_set_vy.out; } /**************************** 4.chassis_set_contorl **********************************************************************************/ //底盘控制量设置 //第一层chassis_set_contorl(chassis_move_t *chassis_move_control) [chassis_task.c global] //第二层 chassis_behaviour_control_set(&vx_set, &vy_set, &angle_set, chassis_move_control) [chasssis_behaviour.c static] // 根据底盘行为状态机chassis_behaviour_mode来相应计算vx_set,vy_set,angle_set [local variables] // //第二层 根据底盘控制状态机chassis_move->chassis_mode计算相应的chassis_move->vx_set|vy_set|wz_set期望 // /**************** 第一层 底盘控制量设置 ************************************************************************************/ //设置遥控器输入控制量 static void chassis_set_contorl(chassis_move_t *chassis_move_control) { if (chassis_move_control == NULL) { return; } //设置速度 fp32 vx_set = 0.0f, vy_set = 0.0f, angle_set = 0.0f; /******************第二层 根据底盘行为状态机chassis_behaviour_mode来相应计算vx_set,vy_set,angle_set[local variables] ***********************************/ // 如下6种模式 // CHASSIS_ZERO_FORCE, //底盘无力 // CHASSIS_NO_MOVE, //底盘保持不动 // CHASSIS_INFANTRY_FOLLOW_GIMBAL_YAW, //正常步兵底盘跟随云台 遥控器的数据->底盘的vx_set,vy_set , 扭腰->angle_Set // CHASSIS_ENGINEER_FOLLOW_CHASSIS_YAW, //工程底盘角度控制底盘,由于底盘未有陀螺仪,故而角度是减去云台角度而得到,如果有底盘陀螺仪请更新底盘的yaw,pitch,roll角度 // CHASSIS_NO_FOLLOW_YAW, //底盘不跟随角度,角度是开环的,但前后左右是有速度环 // CHASSIS_OPEN //遥控器的值乘以比例直接发送到can总线上 chassis_behaviour_control_set(&vx_set, &vy_set, &angle_set, chassis_move_control); /******************第二层 根据底盘控制状态机chassis_move->chassis_mode最终得出chassis_move->vx_set|vy_set|wz_set期望 ***********************************/ // 如下3种状态值 // CHASSIS_VECTOR_FOLLOW_GIMBAL_YAW, //底盘随动云台 云台坐标系vx_set,vy_set变换到底盘坐标系的vx_set,vy_set // CHASSIS_VECTOR_FOLLOW_CHASSIS_YAW, //底盘随动底盘 // CHASSIS_VECTOR_NO_FOLLOW_YAW, //底盘不随动 // CHASSIS_VECTOR_RAW, //原始底盘 /******************** 跟随云台YAW模式 CHASSIS_VECTOR_FOLLOW_GIMBAL_YAW ********************************************/ if (chassis_move_control->chassis_mode == CHASSIS_VECTOR_FOLLOW_GIMBAL_YAW) { fp32 sin_yaw = 0.0f, cos_yaw = 0.0f; //旋转控制底盘速度方向,保证前进方向是云台方向,有利于运动平稳 sin_yaw = arm_sin_f32(-chassis_move_control->chassis_yaw_motor->relative_angle); cos_yaw = arm_cos_f32(-chassis_move_control->chassis_yaw_motor->relative_angle); chassis_move_control->vx_set = cos_yaw * vx_set + sin_yaw * vy_set; //云台坐标系变换到底盘坐标系的运动学公式 chassis_move_control->vy_set = -sin_yaw * vx_set + cos_yaw * vy_set; //云台坐标系变换到底盘坐标系的运动学公式 //设置控制相对云台角度 chassis_move_control->chassis_relative_angle_set = rad_format(angle_set); //角速度期望 = 角度环PID输出 chassis_move_control->wz_set = -PID_Calc(&chassis_move_control->chassis_angle_pid, chassis_move_control->chassis_yaw_motor->relative_angle, chassis_move_control->chassis_relative_angle_set); // chassis_move_control->wz_set = 10; //Vx期望,Vy期望限幅 chassis_move_control->vx_set = fp32_constrain(chassis_move_control->vx_set, chassis_move_control->vx_min_speed, chassis_move_control->vx_max_speed); chassis_move_control->vy_set = fp32_constrain(chassis_move_control->vy_set, chassis_move_control->vy_min_speed, chassis_move_control->vy_max_speed); } /******************** 跟随底盘YAW模式 CHASSIS_VECTOR_FOLLOW_CHASSIS_YAW********************************************/ else if (chassis_move_control->chassis_mode == CHASSIS_VECTOR_FOLLOW_CHASSIS_YAW) { fp32 delat_angle = 0.0f; //放弃跟随云台 //设置底盘控制的角度 chassis_move_control->chassis_yaw_set = rad_format(angle_set); delat_angle = rad_format(chassis_move_control->chassis_yaw_set - chassis_move_control->chassis_yaw); //计算旋转的角速度 chassis_move_control->wz_set = PID_Calc(&chassis_move_control->chassis_angle_pid, 0.0f, delat_angle); //设置底盘运动的速度 chassis_move_control->vx_set = fp32_constrain(vx_set, chassis_move_control->vx_min_speed, chassis_move_control->vx_max_speed); chassis_move_control->vy_set = fp32_constrain(vy_set, chassis_move_control->vy_min_speed, chassis_move_control->vy_max_speed); } /******************** 不跟随YAW模式 CHASSIS_VECTOR_NO_FOLLOW_YAW********************************************/ else if (chassis_move_control->chassis_mode == CHASSIS_VECTOR_NO_FOLLOW_YAW) { //放弃跟随云台 //这个模式下,角度设置的为 角速度 fp32 chassis_wz = angle_set; chassis_move_control->wz_set = chassis_wz; chassis_move_control->vx_set = fp32_constrain(vx_set, chassis_move_control->vx_min_speed, chassis_move_control->vx_max_speed); chassis_move_control->vy_set = fp32_constrain(vy_set, chassis_move_control->vy_min_speed, chassis_move_control->vy_max_speed); } /******************** 底盘无力模式 CHASSIS_VECTOR_RAW********************************************/ else if (chassis_move_control->chassis_mode == CHASSIS_VECTOR_RAW) { chassis_move_control->vx_set = vx_set; chassis_move_control->vy_set = vy_set; chassis_move_control->wz_set = angle_set; chassis_move_control->chassis_cmd_slow_set_vx.out = 0.0f; chassis_move_control->chassis_cmd_slow_set_vy.out = 0.0f; } } static void chassis_vector_to_mecanum_wheel_speed(const fp32 vx_set, const fp32 vy_set, const fp32 wz_set, fp32 wheel_speed[4]) { //旋转的时候, 由于云台靠前,所以是前面两轮 0 ,1 旋转的速度变慢, 后面两轮 2,3 旋转的速度变快 wheel_speed[0] = -vx_set - vy_set + (CHASSIS_WZ_SET_SCALE - 1.0f) * MOTOR_DISTANCE_TO_CENTER * wz_set; wheel_speed[1] = vx_set - vy_set + (CHASSIS_WZ_SET_SCALE - 1.0f) * MOTOR_DISTANCE_TO_CENTER * wz_set; wheel_speed[2] = vx_set + vy_set + (-CHASSIS_WZ_SET_SCALE - 1.0f) * MOTOR_DISTANCE_TO_CENTER * wz_set; wheel_speed[3] = -vx_set + vy_set + (-CHASSIS_WZ_SET_SCALE - 1.0f) * MOTOR_DISTANCE_TO_CENTER * wz_set; } /****************** 5. chassis_control_loop *******************************************************************************************/ static void chassis_control_loop(chassis_move_t *chassis_move_control_loop) { fp32 max_vector = 0.0f, vector_rate = 0.0f; fp32 temp = 0.0f; fp32 wheel_speed[4] = {0.0f, 0.0f, 0.0f, 0.0f}; uint8_t i = 0; //麦轮运动分解 chassis_vector_to_mecanum_wheel_speed(chassis_move_control_loop->vx_set, chassis_move_control_loop->vy_set, chassis_move_control_loop->wz_set, wheel_speed); if (chassis_move_control_loop->chassis_mode == CHASSIS_VECTOR_RAW) { //赋值电流值 for (i = 0; i < 4; i++) { chassis_move_control_loop->motor_chassis[i].give_current = (int16_t)(wheel_speed[i]); } //raw控制直接返回 return; } //计算轮子控制最大速度,并限制其最大速度 for (i = 0; i < 4; i++) { chassis_move_control_loop->motor_chassis[i].speed_set = wheel_speed[i]; temp = fabs(chassis_move_control_loop->motor_chassis[i].speed_set); if (max_vector < temp) { max_vector = temp; } } if (max_vector > MAX_WHEEL_SPEED) { vector_rate = MAX_WHEEL_SPEED / max_vector; for (i = 0; i < 4; i++) { chassis_move_control_loop->motor_chassis[i].speed_set *= vector_rate; } } //计算pid for (i = 0; i < 4; i++) { PID_Calc(&chassis_move_control_loop->motor_speed_pid[i], chassis_move_control_loop->motor_chassis[i].speed, chassis_move_control_loop->motor_chassis[i].speed_set); } //功率控制 //chassis_power_control(chassis_move_control_loop); //赋值电流值 for (i = 0; i < 4; i++) { chassis_move_control_loop->motor_chassis[i].give_current = (int16_t)(chassis_move_control_loop->motor_speed_pid[i].out); } } static void chassis_power_control(chassis_move_t *chassis_power_control) { fp32 chassis_power = 0.0f; fp32 chassis_power_buffer = 0.0f; fp32 total_current_limit = 0.0f; fp32 total_current = 0.0f; uint8_t robot_id = get_robot_id(); // if(toe_is_error(REFEREE_TOE)) // { // total_current_limit = NO_JUDGE_TOTAL_CURRENT_LIMIT; // } if(robot_id == RED_ENGINEER || robot_id == BLUE_ENGINEER || robot_id == 0) { total_current_limit = NO_JUDGE_TOTAL_CURRENT_LIMIT; } else { get_chassis_power_and_buffer(&chassis_power, &chassis_power_buffer); // power > 80w and buffer < 60j, because buffer < 60 means power has been more than 80w //功率超过80w 和缓冲能量小于60j,因为缓冲能量小于60意味着功率超过80w if(chassis_power_buffer < WARNING_POWER_BUFF) { fp32 power_scale; if(chassis_power_buffer > 5.0f) { //scale down WARNING_POWER_BUFF //缩小WARNING_POWER_BUFF power_scale = chassis_power_buffer / WARNING_POWER_BUFF; } else { //only left 10% of WARNING_POWER_BUFF power_scale = 5.0f / WARNING_POWER_BUFF; } //scale down //缩小 total_current_limit = BUFFER_TOTAL_CURRENT_LIMIT * power_scale; } else { //power > WARNING_POWER //功率大于WARNING_POWER if(chassis_power > WARNING_POWER) { fp32 power_scale; //power < 80w //功率小于80w if(chassis_power < POWER_LIMIT) { //scale down //缩小 power_scale = (POWER_LIMIT - chassis_power) / (POWER_LIMIT - WARNING_POWER); } //power > 80w //功率大于80w else { power_scale = 0.0f; } total_current_limit = BUFFER_TOTAL_CURRENT_LIMIT + POWER_TOTAL_CURRENT_LIMIT * power_scale; } //power < WARNING_POWER //功率小于WARNING_POWER else { total_current_limit = BUFFER_TOTAL_CURRENT_LIMIT + POWER_TOTAL_CURRENT_LIMIT; } } } total_current = 0.0f; //calculate the original motor current set //计算原本电机电流设定 for(uint8_t i = 0; i < 4; i++) { total_current += fabs(chassis_power_control->motor_speed_pid[i].out); } if(total_current > total_current_limit) { fp32 current_scale = total_current_limit / total_current; chassis_power_control->motor_speed_pid[0].out*=current_scale; chassis_power_control->motor_speed_pid[1].out*=current_scale; chassis_power_control->motor_speed_pid[2].out*=current_scale; chassis_power_control->motor_speed_pid[3].out*=current_scale; } } static void super_power_data_transmit(chassis_move_t *chassis_move) { u8 msg1 = 0; u8 msg2 = 0; u8 msg3 = 0; u8 msg4 = 0; u8 msg5 = 0; u8 msg6 = 0; u8 msg7 = 0; u8 msg8 = 0; msg1 = chassis_move->super_cap.charge_cmd_state; msg2 = chassis_move->super_cap.discharge_cmd_state; SetSuperPowerMcuMsg(msg1,msg2,msg3,msg4,msg5,msg6,msg7,msg8); }<file_sep>#ifndef DELAY_H #define DELAY_H #include "main.h" #include "stm32f4xx.h" #define TICK_PER_SECOND 1000 #define TICK_US (1000000/TICK_PER_SECOND) extern void delay_init(uint32_t TICK_RATE_HZ); extern void delay_us(uint16_t nus); extern void delay_ms(uint16_t nms); extern void sys_time(void); extern uint32_t SysTick_GetTick(void); extern uint32_t GetSysTime_us(void); #endif <file_sep>#include "uart7.h" u8 TxBuffer[256]; u8 TxCounter = 0; u8 count = 0; u8 Rx_Buf[256]; //串口接收缓存 void ANO_DT_UART7_Configuration(u32 bound) { //GPIO端口设置 GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE,ENABLE); //使能GPIOE时钟 RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART7,ENABLE);//使能UART7时钟 //串口8对应引脚复用映射 GPIO_PinAFConfig(GPIOE,GPIO_PinSource7,GPIO_AF_UART8); GPIO_PinAFConfig(GPIOE,GPIO_PinSource8,GPIO_AF_UART8); //UART8端口配置 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7 | GPIO_Pin_8; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//复用功能 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉 GPIO_Init(GPIOE,&GPIO_InitStructure); //UART8 初始化设置 USART_InitStructure.USART_BaudRate = bound;//波特率设置 USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式 USART_InitStructure.USART_StopBits = USART_StopBits_1;//一个停止位 USART_InitStructure.USART_Parity = USART_Parity_No;//无奇偶校验位 USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制 USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //收发模式 USART_Init(UART7, &USART_InitStructure); //初始化串口7 USART_Cmd(UART7, ENABLE); //使能串口7 USART_ClearFlag(UART7, USART_FLAG_TC); USART_ITConfig(UART7, USART_IT_RXNE, ENABLE);//开启相关中断 //UART8 NVIC 配置 NVIC_InitStructure.NVIC_IRQChannel = UART7_IRQn;//串口7中断通道 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = UART7_NVIC ;//抢占优先级 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //子优先级 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能 NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器、 } void Uart7_IRQ ( void ) { u8 com_data; if ( UART7->SR & USART_SR_ORE ) //ORE中断 { //com_data = USART2->DR; USART_ReceiveData(UART7); } //接收中断 if ( USART_GetITStatus ( UART7, USART_IT_RXNE ) ) { USART_ClearITPendingBit ( UART7, USART_IT_RXNE ); //清除中断标志 com_data = UART7->DR; //ANO_DT_Data_Receive_Prepare ( com_data ); //UART7_Put_Char(com_data);//灵活格式帧 //ANODT_GetByte(com_data); //参数读写与返回 } //发送(进入移位)中断 if ( USART_GetITStatus ( UART7, USART_IT_TXE ) ) { UART7->DR = TxBuffer[TxCounter++]; //写DR清除中断标志 if ( TxCounter == count ) { UART7->CR1 &= ~USART_CR1_TXEIE; //关闭TXE(发送中断)中断 } //USART_ClearITPendingBit(USART2,USART_IT_TXE); } } static void UART7_Put_Char(unsigned char DataToSend) { TxBuffer[count++] = DataToSend; USART_ITConfig(UART7, USART_IT_TXE, ENABLE); } void UART7_Put_Buf( unsigned char *DataToSend, u8 data_num ) { for(u8 i = 0;i<data_num;i++) { TxBuffer[count++] = *(DataToSend+i); } if(!(UART7->CR1 & USART_CR1_TXEIE)) USART_ITConfig(UART7, USART_IT_TXE, ENABLE); } //void UART7_Send( unsigned char *DataToSend , u8 data_num ) //{ // u8 i; // for ( i = 0; i < data_num; i++ ) // { // TxBuffer[count++] = * ( DataToSend + i ); // } // if ( ! ( UART7->CR1 & USART_CR1_TXEIE ) ) // { // USART_ITConfig ( UART7, USART_IT_TXE, ENABLE ); //打开发送中断 // } //} void UART7_IRQHandler(void) //串口7中断服务程序 { Uart7_IRQ(); } <file_sep>#ifndef TRIGGER_SWITCH_H #define TRIGGER_SWITCH_H #include "exit_init.h" typedef struct { bool_t trigger_state; }trigger_switch_t; typedef enum { PushWheel = 0, ShootWheel } trigger_switch_list; extern trigger_switch_t *get_switch_point( trigger_switch_list object ); extern void trigger_switch_init(void); extern void trigger_switch_in_PushWheel_detected(void); extern void trigger_switch_in_ShootWheel_detected(void); extern void trigger_switch_StateDelete( trigger_switch_list object ); #endif <file_sep>#include "LX_IMU.h" #include "uart8.h" u8 send_buffer[50]; //发送数据缓存 fp32 Gyro[3] = {0.0f, 0.0f, 0.0f}; fp32 yaw = 0; u8 SHOCK_STA =0; fp32 Angle[3] = {0.0f, 0.0f, 0.0f}; //欧拉角 单位 rad 为了DEBUG方便,我把Static修饰符删掉了 _dt_st dt; static u8 DT_RxBuffer[256],DT_data_cnt = 0; //=================================================================== void LX_ANO_DT_Init(void) { //========定时触发 // dt.fun[0x0d].D_Addr = 0xff; dt.fun[0x0d].fre_ms = 100; //触发发送的周期100ms dt.fun[0x0d].time_cnt_ms = 1;//设置初始相位,单位1ms // dt.fun[0x40].D_Addr = 0xff; dt.fun[0x40].fre_ms = 100; //触发发送的周期100ms dt.fun[0x40].time_cnt_ms = 0;//设置初始相位,单位1ms //========外部触发 // dt.fun[0x30].D_Addr = 0xff; dt.fun[0x30].fre_ms = 0; //0 由外部触发 dt.fun[0x30].time_cnt_ms = 0;//设置初始相位,单位1ms // dt.fun[0x33].D_Addr = 0xff; dt.fun[0x33].fre_ms = 0; //0 由外部触发 dt.fun[0x33].time_cnt_ms = 0;//设置初始相位,单位1ms // dt.fun[0x34].D_Addr = 0xff; dt.fun[0x34].fre_ms = 0; //0 由外部触发 dt.fun[0x34].time_cnt_ms = 0;//设置初始相位,单位1ms // dt.fun[0x41].D_Addr = 0xff; dt.fun[0x41].fre_ms = 0; //0 由外部触发 dt.fun[0x41].time_cnt_ms = 0;//设置初始相位,单位1ms // dt.fun[0xe0].D_Addr = 0xff; dt.fun[0xe0].fre_ms = 0; //0 由外部触发 dt.fun[0xe0].time_cnt_ms = 0;//设置初始相位,单位1ms // dt.fun[0xe2].D_Addr = 0xff; dt.fun[0xe2].fre_ms = 0; //0 由外部触发 dt.fun[0xe2].time_cnt_ms = 0;//设置初始相位,单位1ms } //数据发送接口 static void ANO_DT_LX_Send_Data(u8 *dataToSend , u8 length) { // Uart8_Send(dataToSend, length); } /** * @brief 取得凌霄IMU角度值指针 * @author Stone * @param[in] void * @retval Angle[]数组首元素地址 */ const fp32 *get_LX_IMU_angle_point(void) { return Angle; } /** * @brief 取得凌霄IMU角速度值指针 * @author Stone * @param[in] void * @retval Angle[]数组首元素地址 */ const fp32 *get_LX_IMU_gyro_point(void) { return Gyro; } //=================================================================== //数据接收程序 //=================================================================== void ANO_DT_LX_Data_Receive_Prepare(u8 data) { static u8 _data_len = 0,_data_cnt = 0; static u8 rxstate = 0; if(rxstate==0&&data==0xAA) { rxstate=1; DT_RxBuffer[0]=data; } else if(rxstate==1 && (data == HW_TYPE || data == HW_ALL)) { rxstate=2; DT_RxBuffer[1]=data; } else if(rxstate==2) { rxstate = 3; DT_RxBuffer[2]=data; } else if(rxstate==3&&data<250) { rxstate = 4; DT_RxBuffer[3]=data; _data_len = data; _data_cnt = 0; } else if(rxstate==4&&_data_len>0) { _data_len--; DT_RxBuffer[4+_data_cnt++]=data; if(_data_len==0) rxstate = 5; } else if(rxstate==5) { rxstate = 6; DT_RxBuffer[4+_data_cnt++]=data; } else if(rxstate==6) { rxstate = 0; DT_RxBuffer[4+_data_cnt]=data; DT_data_cnt = _data_cnt+5; //ano_dt_data_ok = 1; ANO_DT_LX_Data_Receive_Anl(DT_RxBuffer,DT_data_cnt); } else { rxstate = 0; } } ///////////////////////////////////////////////////////////////////////////////////// //Data_Receive_Anl函数是协议数据解析函数,函数参数是符合协议格式的一个数据帧,该函数会首先对协议数据进行校验 //校验通过后对数据进行解析,实现相应功能 //此函数可以不用用户自行调用,由函数ANO_Data_Receive_Prepare自动调用 static void ANO_DT_LX_Data_Receive_Anl(u8 *data,u8 len) { u8 check_sum1 = 0,check_sum2 = 0; if(*(data+3) != (len-6)) //判断数据长度是否正确 return; for(u8 i=0; i<len-2; i++) { check_sum1 += *(data+i); check_sum2 += check_sum1; } if((check_sum1 != *(data+len-2)) || (check_sum2 != *(data+len-1))) //判断sum校验 { return; } if(*(data)!=0xAA || (*(data+1)!=HW_TYPE && *(data+1)!=HW_ALL)) return; //============================================================================= // if(*(data+2)==0X20) //PWM数据 // { // pwm_to_esc.pwm_m1 = *((u16 *)(data+4 )); // pwm_to_esc.pwm_m2 = *((u16 *)(data+6 )); // pwm_to_esc.pwm_m3 = *((u16 *)(data+8 )); // pwm_to_esc.pwm_m4 = *((u16 *)(data+10)); // pwm_to_esc.pwm_m5 = *((u16 *)(data+12)); // pwm_to_esc.pwm_m6 = *((u16 *)(data+14)); // pwm_to_esc.pwm_m7 = *((u16 *)(data+16)); // pwm_to_esc.pwm_m8 = *((u16 *)(data+18)); // } // else if(*(data+2)==0X0f)//RGB // { // led.brightness[0] = *(data+4); // led.brightness[1] = *(data+5); // led.brightness[2] = *(data+6); // led.brightness[3] = *(data+7); // } // else if(*(data+2)==0X06) // { // // // fc_sta.fc_mode_sta = *(data+4); // fc_sta.unlock_sta = *(data+5); // fc_sta.cmd_fun.CID = *(data+6); // fc_sta.cmd_fun.CMD_0 = *(data+7); // fc_sta.cmd_fun.CMD_1 = *(data+8); // // // } else if(*(data+2)==0x01)// 加速度Acc|角速度Gyro rad/s|稳定状态SHOCK_STA (正负24g对应s16、角速度正负2000度/秒对应s16(-32768 - 32768) { Gyro[0] = *((s16 *)(data+10 ))* 0.00106f; //X (2000/32768) / 57.3 = 0.00106518597294938917975567190227 Gyro[1] = *((s16 *)(data+12 ))* 0.00106f; //Y (2000/32768) / 57.3 = 0.00106518597294938917975567190227 Gyro[2] = *((s16 *)(data+14 ))* 0.00106f; //Z (2000/32768) / 57.3 = 0.00106518597294938917975567190227 SHOCK_STA = *((s16 *)(data+16 )); } else if(*(data+2)==0X03)//欧拉角 { Angle[2] = (*((s16 *)(data+4 )))/ 100.0f / 57.3f; //Roll Angle[1] = (*((s16 *)(data+6 )))/100.0f / 57.3f; //Pitch Angle[0] = (*((s16 *)(data+8 )))/100.0f / 57.3f; //Yaw // = *((u16 *)(data+10)); } // else if(*(data+2)==0XE0) //命令E0 // { // switch(*(data+4)) //ID // { // case 0x01: // { // // } // break; // case 0x02: // { // // } // break; // case 0x10: // { // // } // break; // case 0x11: // { // // } // break; // default: // break; // } // // // dt.ck_send.ID = *(data+4); // dt.ck_send.SC = check_sum1; // dt.ck_send.AC = check_sum2; // CK_Back(SWJ_ADDR,&dt.ck_send); // } // else if(*(data+2)==0X00) //ck返回 // { // // // if((dt.ck_back.ID == *(data+4)) && (dt.ck_back.SC == *(data+5)) && (dt.ck_back.AC == *(data+6))) // { // dt.wait_ck = 0;//校验成功 // } // else // { //// testCnt++; // } // } // else if(*(data+2)==0XE1) // { // //读取参数 // u16 _par = *(data+4)+*(data+5)*256; // // // dt.par_data.par_id = _par; // dt.par_data.par_val = 0; // PAR_Back(0xff,&dt.par_data); // } // else if(*(data+2)==0xE2) // { //// //写入参数 //// u16 _par = *(data+4)+*(data+5)*256; //// u32 _val = (s32)(((*(data+6))) + ((*(data+7))<<8) + ((*(data+8))<<16) + ((*(data+9))<<24)); // // // dt.ck_send.ID = *(data+4); // dt.ck_send.SC = check_sum1; // dt.ck_send.AC = check_sum2; // CK_Back(0xff,&dt.ck_send); // //赋值参数 // //Parameter_Set(_par,_val); // // } } ////=================================================================== ////数据发送实现程序 ////=================================================================== //static void Add_Send_Data(u8 frame_num,u8 *_cnt,u8 send_buffer[]) //{ // s16 temp_data; // s32 temp_data_32; // switch(frame_num) // { // case 0x00://CHECK返回 // { // send_buffer[(*_cnt)++]=dt.ck_send.ID; // send_buffer[(*_cnt)++]=dt.ck_send.SC; // send_buffer[(*_cnt)++]=dt.ck_send.AC; // } // break; // case 0x0d://电池数据 // { // for(u8 i=0;i<4;i++) // { // send_buffer[(*_cnt)++]=fc_bat.byte_data[i]; // } // } // break; // case 0x30://GPS数据 // { // // // for(u8 i=0;i<23;i++) // { // send_buffer[(*_cnt)++]=ext_sens.fc_gps.byte[i]; // } // } // break; // case 0x33://通用速度测量数据 // { // // // for(u8 i=0;i<6;i++) // { // send_buffer[(*_cnt)++]=ext_sens.gen_vel.byte[i]; // } // } // break; // case 0x34://通用距离测量数据 // { // // // for(u8 i=0;i<7;i++) // { // send_buffer[(*_cnt)++]=ext_sens.gen_dis.byte[i]; // } // } // break; // case 0x40://遥控数据帧 // { // for(u8 i=0;i<20;i++) // { // send_buffer[(*_cnt)++]=rc_in.rc_ch.byte_data[i]; // } // } // break; // case 0x41://实时控制数据帧 // { // for(u8 i=0;i<14;i++) // { // send_buffer[(*_cnt)++]=rt_tar.byte_data[i]; // } // } // break; // case 0xe0://CMD命令帧 // { // send_buffer[(*_cnt)++]=dt.cmd_send.CID; // for(u8 i =0;i<10;i++) // { // send_buffer[(*_cnt)++]=dt.cmd_send.CMD[i]; // } // } // break; // case 0xe2://PARA返回 // { // temp_data = dt.par_data.par_id; // send_buffer[(*_cnt)++]=BYTE0(temp_data); // send_buffer[(*_cnt)++]=BYTE1(temp_data); // temp_data_32 = dt.par_data.par_val; // send_buffer[(*_cnt)++]=BYTE0(temp_data_32); // send_buffer[(*_cnt)++]=BYTE1(temp_data_32); // send_buffer[(*_cnt)++]=BYTE2(temp_data_32); // send_buffer[(*_cnt)++]=BYTE3(temp_data_32); // } // break; // default :break; // } //} ////=================================================================== //static void Frame_Send(u8 frame_num,_dt_frame_st *dt_frame) //{ // u8 _cnt=0; // // send_buffer[_cnt++]=0xAA; // send_buffer[_cnt++]=dt_frame->D_Addr; // send_buffer[_cnt++]=frame_num; // send_buffer[_cnt++]=0; // //== // //add_send_data // Add_Send_Data(frame_num,&_cnt,send_buffer); // //== // send_buffer[3] = _cnt-4; // //== // u8 check_sum1 = 0, check_sum2 = 0; // for(u8 i=0;i<_cnt;i++) // { // check_sum1 += send_buffer[i]; // check_sum2 += check_sum1; // } // send_buffer[_cnt++] = check_sum1; // send_buffer[_cnt++] = check_sum2; // // // if(dt.wait_ck !=0 && frame_num==0xe0) // { // dt.ck_back.ID = frame_num; // dt.ck_back.SC = check_sum1; // dt.ck_back.AC = check_sum2; // } // ANO_DT_LX_Send_Data(send_buffer, _cnt); //} ////=================================================================== //// //static void Check_To_Send(u8 frame_num) //{ // // // if(dt.fun[frame_num].fre_ms) // { // // // if(dt.fun[frame_num].time_cnt_ms<dt.fun[frame_num].fre_ms) // { // dt.fun[frame_num].time_cnt_ms++; // } // else // { // dt.fun[frame_num].time_cnt_ms = 1; // dt.fun[frame_num].WTS = 1;//标记等待发送 // } // } // else // { // //等待外部触发 // } // // // if(dt.fun[frame_num].WTS) // { // dt.fun[frame_num].WTS = 0; // //实际发送 // Frame_Send(frame_num,&dt.fun[frame_num]); // } //} ////=================================================================== //CMD发送 void CMD_Send(u8 dest_addr,_cmd_st *cmd) { dt.fun[0xe0].D_Addr = dest_addr; dt.fun[0xe0].WTS=1;//标记CMD等待发送 dt.wait_ck = 1;//标记等待校验 } //CHECK返回 void CK_Back(u8 dest_addr,_ck_st *ck) { dt.fun[0x00].D_Addr = dest_addr; dt.fun[0x00].WTS=1;//标记CMD等待发送 } //PARA返回 void PAR_Back(u8 dest_addr,_par_st *par) { dt.fun[0xe2].D_Addr = dest_addr; dt.fun[0xe2].WTS=1;//标记CMD等待发送 } ////若指令没发送成功,会持续重新发送,间隔50ms。 //static u8 repeat_cnt; //static inline void CK_Back_Check() //{ // static u8 time_dly; // if(dt.wait_ck == 1) // { // if(time_dly<50)//50ms // { // time_dly++; // } // else // { // time_dly = 0; // repeat_cnt++; // if(repeat_cnt<5) // { // dt.fun[0xe0].WTS = 1;//标记等待发送,重发 // } // else // { // repeat_cnt = 0; // dt.wait_ck = 0; // } // } // } // else // { // time_dly = 0; // repeat_cnt = 0; // } //} ////1ms调用一次,用于通信交换数据 //void ANO_LX_Data_Exchange_Task(float dT_s) //{ // //=====检测CMD是否返回了校验 // CK_Back_Check(); // //=====检测是否触发发送 // Check_To_Send(0x30); // Check_To_Send(0x33); // Check_To_Send(0x34); // Check_To_Send(0x40); // Check_To_Send(0x41); // Check_To_Send(0xe0); // Check_To_Send(0xe2); // Check_To_Send(0x0d); // //}<file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file main.c/h * @brief stm32初始化以及开始任务freeRTOS。 * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ #ifndef MAIN_H #define MAIN_H #include "stm32f4xx.h" typedef signed char int8_t; typedef signed short int int16_t; typedef signed int int32_t; typedef signed long long int64_t; /* exact-width unsigned integer types */ typedef unsigned char uint8_t; typedef unsigned short int uint16_t; typedef unsigned int uint32_t; typedef unsigned long long uint64_t; typedef unsigned char bool_t; typedef float fp32; typedef double fp64; /* 匿名数据类型 */ typedef float vec3_f[3]; //vec3_f a == float a[3] typedef float vec2_f[2]; typedef s32 vec3_s32[3]; typedef s32 vec2_s32[2]; typedef s16 vec3_s16[3]; typedef s16 vec2_s16[2]; /* 大小端数据分解 */ #define BYTE0(dwTemp) ( *( (char *)(&dwTemp) ) ) #define BYTE1(dwTemp) ( *( (char *)(&dwTemp) + 1) ) #define BYTE2(dwTemp) ( *( (char *)(&dwTemp) + 2) ) #define BYTE3(dwTemp) ( *( (char *)(&dwTemp) + 3) ) /* 匿名数据系统标识符 */ #define HW_ALL 0xFF #define SWJ_ADDR 0xAF #define HW_TYPE 0x61 #define HW_VER 1 #define SOFT_VER 17 #define BL_VER 0 #define PT_VER 400 #define ANO_DT_USE_USART2 //开启串口2数传功能 #define ANO_DT_USE_USB_HID //开启飞控USBHID连接上位机功能 //云台电机可能can发送失败的情况,尝试使用 随机延迟发送控制指令的方式解决 #define GIMBAL_MOTOR_6020_CAN_LOSE_SLOVE 0 //选择系统时钟 #define SysCoreClock 180 //选择中断优先级 #define RC_NVIC 4 #define CAN1_NVIC 4 #define CAN2_NVIC 4 #define TIM3_NVIC 5 #define TIM6_NVIC 4 #define SPI5_RX_NVIC 5 #define MPU_INT_NVIC 5 #define PUSH_WHEEL_INT_NVIC 5 #define TRIGGER_WHEEL_INT_NVIC 5 #define UART8_NVIC 1 // 凌霄IMU #define USART6_NVIC 2 // 裁判系统用户接口 #define UART7_NVIC 3 //重要参数修改 #define Latitude_At_ShenZhen 22.57025f #ifndef NULL #define NULL 0 #endif #ifndef PI #define PI 3.14159265358979f #endif #endif /* __MAIN_H */ <file_sep># RoboMasterCode RoboMaster Embeded System Code for STM32F427IIX on Hero Robotics <file_sep>#include "buzzer.h" #include "delay.h" #include "stm32f4xx.h" void buzzer_init(uint16_t arr, uint16_t psc) { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; TIM_OCInitTypeDef TIM_OCInitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM12, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOH, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM12, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM12, DISABLE); GPIO_PinAFConfig(GPIOH, GPIO_PinSource6, GPIO_AF_TIM12); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN; GPIO_Init(GPIOH, &GPIO_InitStructure); TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC1Init(TIM12, &TIM_OCInitStructure); TIM_OC1PreloadConfig(TIM12, TIM_OCPreload_Enable); TIM_ARRPreloadConfig(TIM12, ENABLE); TIM_TimeBaseInitStructure.TIM_Period = arr - 1; TIM_TimeBaseInitStructure.TIM_Prescaler = psc - 1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInit(TIM12, &TIM_TimeBaseInitStructure); TIM_Cmd(TIM12, ENABLE); buzzer_off(); } void buzzer_on(uint16_t psc, uint16_t pwm) { TIM12->PSC = psc; TIM_SetCompare1(TIM12, pwm); } void buzzer_off(void) { TIM_SetCompare1(TIM12, 0); } void BSPInit_CompleteBeep(void) { buzzer_on(90,150); delay_ms(250); buzzer_off(); } void CodeTestSound(void) { }<file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file user_task.c/h * @brief 一个普通心跳程序,如果设备无错误,绿灯1Hz闪烁,然后获取姿态角 * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ #include "User_Task.h" #include "main.h" #include "led.h" #include "Detect_Task.h" #include "INS_Task.h" #define user_is_error() toe_is_error(errorListLength) //姿态角 单位度 //fp32 angle_degree[3] = {0.0f, 0.0f, 0.0f}; fp32 angle_degree2[3] = {0.0f, 0.0f, 0.0f}; //const volatile fp32 *angle; const volatile short *angle2; void UserTask_Setup(void) { //获取姿态角指针 //angle = get_INS_angle_point(); //angle2 = get_WT_angle_point(); } void UserTask(void) { //姿态角 将rad 变成 度,除这里的姿态角的单位为度,其他地方的姿态角,单位均为弧度 // angle_degree[0] = (*(angle + INS_YAW_ADDRESS_OFFSET)) * 57.3f; // angle_degree[1] = (*(angle + INS_PITCH_ADDRESS_OFFSET)) * 57.3f; // angle_degree[2] = (*(angle + INS_ROLL_ADDRESS_OFFSET)) * 57.3f; // //angle_degree2[0] = (*(angle2 + INS_YAW_ADDRESS_OFFSET)) / 182.0f / 57.3f; //PITCH 抬头增大 低头减小 //angle_degree2[1] = (*(angle2 + INS_PITCH_ADDRESS_OFFSET)) / 182.0f/ 57.3f; // //angle_degree2[2] = (*(angle2 + INS_ROLL_ADDRESS_OFFSET)) / 182.0f/ 57.3f; //YAW 左大右小 // if (!user_is_error()) // { // led_green_on(); // } // vTaskDelay(500); // led_green_off(); // vTaskDelay(500); } <file_sep>#ifndef REFEREE_API_H #define REFEREE_API_H #include "main.h" #include "protocol.h" extern void get_chassis_power_and_buffer(fp32 *power, fp32 *buffer); extern uint8_t get_robot_id(void); extern void get_shoot_heat0_limit_and_heat0(uint16_t *heat0_limit, uint16_t *heat0); extern void get_shoot_heat1_limit_and_heat1(uint16_t *heat1_limit, uint16_t *heat1); extern const ext_power_heat_data_t *get_power_heat_data_Point(void); extern const ext_game_robot_state_t *get_robot_state_data_Point(void); #endif <file_sep>/******************** (C) COPYRIGHT 2017 ANO Tech ******************************** * 作者 :匿名科创 * 官网 :www.anotc.com * 淘宝 :anotc.taobao.com * 技术Q群 :190169595 * 描述 :数据传输 **********************************************************************************/ #include "Ano_DT.h" ///////////////////////////////////////////////////////////////////////////////////// //数据拆分宏定义,在发送大于1字节的数据类型时,比如int16、float等,需要把数据拆分成单独字节进行发送 #define BYTE0(dwTemp) ( *( (char *)(&dwTemp) ) ) #define BYTE1(dwTemp) ( *( (char *)(&dwTemp) + 1) ) #define BYTE2(dwTemp) ( *( (char *)(&dwTemp) + 2) ) #define BYTE3(dwTemp) ( *( (char *)(&dwTemp) + 3) ) #define MYHWADDR 0x05 #define SWJADDR 0xAF #define PARNUM 100 s32 ParValList[100]; //参数列表 dt_flag_t f; //需要发送数据的标志 u8 data_to_send[50]; //发送数据缓存 u8 checkdata_to_send,checksum_to_send; /*******************/ // 灵活格式帧 // 格式:帧头0xAA 目标地址0xFF 功能码ID 数据长度1-40(单位为字节) 和校验 附加校验 // ID:0xF1 - 0xFA robot_status_dt_t robot_status_dt_dataset; u8 DataToSend[100]; //定义数据缓存区 static void ANODT_DATA_Init(robot_status_dt_t *robot_status); static void ANODT_DATA_Init(robot_status_dt_t *robot_status) { robot_status->power_heat_data_pointer = get_power_heat_data_Point(); robot_status->robot_state_pointer = get_robot_state_data_Point(); robot_status->voltage_pointer = get_Voltage_Point(); } void ANODT_DATA_Setup(void) { ANODT_DATA_Init(&robot_status_dt_dataset); } void ANODT_DATA_Task(void) { ANODT_SendF2((u16)((robot_status_dt_dataset.power_heat_data_pointer->chassis_power)*100), robot_status_dt_dataset.power_heat_data_pointer->chassis_power_buffer, robot_status_dt_dataset.robot_state_pointer->robot_id, robot_status_dt_dataset.robot_state_pointer->remain_HP, (u16)((*robot_status_dt_dataset.voltage_pointer)*100)); } void ANODT_SendF1(s16 _a, s16 _b, s32 _c) //0xF1的ID demo { u8 _cnt = 0; DataToSend[_cnt++] = 0xAA; //帧头 DataToSend[_cnt++] = 0xFF; //目标地址 DataToSend[_cnt++] = 0xF1; //CMD_ID DataToSend[_cnt++] = 8; //数据长度,字节为单位 //小端模式,数据低字节保存在内存低地址中,高字节在后 DataToSend[_cnt++] = BYTE0(_a); DataToSend[_cnt++] = BYTE1(_a); DataToSend[_cnt++] = BYTE0(_b); DataToSend[_cnt++] = BYTE1(_b); DataToSend[_cnt++] = BYTE0(_c); DataToSend[_cnt++] = BYTE1(_c); DataToSend[_cnt++] = BYTE2(_c); DataToSend[_cnt++] = BYTE3(_c); //计算 和校验 附加校验 u8 sc = 0; u8 ac = 0; for(u8 i = 0; i<DataToSend[3]+4; i++) { sc += DataToSend[i]; ac += sc; } DataToSend[_cnt++] = sc; DataToSend[_cnt++] = ac; UART7_Put_Buf(DataToSend,_cnt); } void ANODT_SendF2(u16 _a, u16 _b, u8 _c,u16 _d,u16 _e) //0xF2的ID demo { u8 _cnt = 0; DataToSend[_cnt++] = 0xAA; //帧头 DataToSend[_cnt++] = 0xFF; //目标地址 DataToSend[_cnt++] = 0xF2; //CMD_ID DataToSend[_cnt++] = 9; //数据长度,字节为单位 //小端模式,数据低字节保存在内存低地址中,高字节在后 DataToSend[_cnt++] = BYTE0(_a); DataToSend[_cnt++] = BYTE1(_a); DataToSend[_cnt++] = BYTE0(_b); DataToSend[_cnt++] = BYTE1(_b); DataToSend[_cnt++] = BYTE0(_c); DataToSend[_cnt++] = BYTE0(_d); DataToSend[_cnt++] = BYTE1(_d); DataToSend[_cnt++] = BYTE0(_e); DataToSend[_cnt++] = BYTE1(_e); //计算 和校验 附加校验 u8 sc = 0; u8 ac = 0; for(u8 i = 0; i<DataToSend[3]+4; i++) { sc += DataToSend[i]; ac += sc; } DataToSend[_cnt++] = sc; DataToSend[_cnt++] = ac; UART7_Put_Buf(DataToSend,_cnt); } /*********************/ // 参数读写返回+匿名安全通信协议 //s32 userPar10 = 123; //void ANODT_SendPar(u16 _id, s32 _val) //{ // u8 _cnt = 0; // u8 check_sum1 = 0, check_sum2 = 0; // // DataToSend[_cnt++] = 0xAA; //帧头 // DataToSend[_cnt++] = 0xFF; //目标地址:广播 // DataToSend[_cnt++] = 0xE2; //CMD_ID:参数读写返回 // DataToSend[_cnt++] = 0; //数据长度,字节为单位 // // //小端模式,数据低字节保存在内存低地址中,高字节在后 // DataToSend[_cnt++] = BYTE0(_id); // DataToSend[_cnt++] = BYTE1(_id); // // DataToSend[_cnt++] = BYTE0(_val); // DataToSend[_cnt++] = BYTE1(_val); // DataToSend[_cnt++] = BYTE2(_val); // DataToSend[_cnt++] = BYTE3(_val); // // DataToSend[3] = _cnt - 4; // //计算 和校验 附加校验 // for(u8 i = 0; i<DataToSend[3]+4; i++) // { // check_sum1 += DataToSend[i]; // check_sum2 += check_sum1; // } // DataToSend[_cnt++] = check_sum1; // DataToSend[_cnt++] = check_sum2; // // Usart2_Put_Buf(DataToSend,_cnt); //} //u8 DataGet[60]; //void ANODT_Anl(void) //{ // u8 sc = 0; // u8 ac = 0; // u8 _datalen = DataGet[3]; // // for(u8 i = 0;i<DataGet[3]+4;i++) // { // sc += DataGet[i]; // ac += sc; // } // //和校验 附加校验判断 // if(sc != DataGet[DataGet[3]+4] || ac != DataGet[DataGet[3]+5]) // return; // // if(DataGet[2] == 0xE1) // { // //小端模式,读取参数 // u16 _id = DataGet[4] + (u16)(DataGet[5]<<8); // switch(_id) // { // case 10: // ANODT_SendPar(_id, userPar10); break; // default: // ANODT_SendPar(_id, 0); break; // } // } //} //void ANODT_GetByte(u8 data) //{ // static u8 _sta = 0; // static u8 _datalen = 0; // static u8 _datacnt = 0; //已经接收到 // // if(_sta == 0) // { // DataGet[0] = data; // if(data == 0xAA) // _sta = 1; // } // else if(_sta == 1) // { // DataGet[1] = data; // _sta = 2; // } // else if(_sta == 2) // { // DataGet[2] = data; // _sta = 3; // } // else if(_sta == 3) // { // if(data > 50) //数据长度大于50的话代表读错了 // _sta = 0; //重新读取 // else // { // _sta = 4; // DataGet[3] = data; // _datalen = data; // } // } // else if(_sta == 4)// // { // DataGet[4+_datacnt++] = data; // if(_datacnt >= _datalen) // _sta = 5; // } // else if(_sta == 5) //和校验 // { // DataGet[4+_datacnt] = data; // _sta = 6; // } // else if(_sta ==6) //附加校验 // { // DataGet[4+_datacnt] = data; // _sta = 0; // ANODT_Anl(); // } //}<file_sep>#include "led.h" #include "stm32f4xx.h" void led_configuration(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF | RCC_AHB1Periph_GPIOE | RCC_AHB1Periph_GPIOG, ENABLE); // GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOF, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; GPIO_Init(GPIOE, &GPIO_InitStructure); led_green_on(); led_red_on(); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_8; GPIO_Init(GPIOG, &GPIO_InitStructure); for(u8 i = 0;i<=8;i++) { flow_led_off(i); } } void led_green_off(void) { GPIO_SetBits(GPIOF, GPIO_Pin_14); } void led_green_on(void) { GPIO_ResetBits(GPIOF, GPIO_Pin_14); } void led_green_toggle(void) { GPIO_ToggleBits(GPIOF, GPIO_Pin_14); } void led_red_off(void) { GPIO_SetBits(GPIOE, GPIO_Pin_11); } void led_red_on(void) { GPIO_ResetBits(GPIOE, GPIO_Pin_11); } extern void led_red_toggle(void) { GPIO_ToggleBits(GPIOE, GPIO_Pin_11); } void flow_led_on(uint16_t num) { GPIO_ResetBits(GPIOG, GPIO_Pin_8 >> num); } void flow_led_off(uint16_t num) { GPIO_SetBits(GPIOG, GPIO_Pin_8 >> num); } void flow_led_toggle(uint16_t num) { GPIO_ToggleBits(GPIOG, GPIO_Pin_8 >> num); } void flow_led_Combo1(void) { static u8 Cnt; static u8 a;Cnt++; if(Cnt==50) { flow_led_toggle(a); a++; if(a==8)a=0; Cnt = 0; } } <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file can_receive.c/h * @brief 完成can设备数据收发函数,该文件是通过can中断完成接收 * @note 该文件不是freeRTOS任务 * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ #ifndef CANTASK_H #define CANTASK_H #include "main.h" #define CHASSIS_CAN CAN1 #define GIMBAL_CAN CAN1 /* CAN send and receive ID */ typedef enum { CAN_CHASSIS_ALL_ID = 0x200, //CAN发送报文标识符 CAN_3508_M1_ID = 0x201, //CAN反馈报文标识符 CAN_3508_M2_ID = 0x202, //CAN反馈报文标识符 CAN_3508_M3_ID = 0x203, //CAN反馈报文标识符 CAN_3508_M4_ID = 0x204, //CAN反馈报文标识符 CAN_YAW_MOTOR_ID = 0x205, //CAN反馈报文标识符 CAN_PIT_MOTOR_ID = 0x206, //CAN反馈报文标识符 CAN_SHOOT_ID = 0x207,//CAN反馈报文标识符 CAN_PUSH_ID = 0x208, CAN_GIMBAL_ALL_ID = 0x1FF, //CAN发送报文标识符 CAN_SetSuperPower_ID = 0x301, CAN_SuperPower_MCU_ID = 0x302, } can_msg_id_e; //rm电机统一数据结构体 typedef struct { uint16_t ecd; //转子机械角度 0-8191对应0-360度 int16_t speed_rpm; //转子转速 单位:RPM int16_t given_current; //控制电流 -16384-0-16384对应-20-0-20A uint8_t temperate; //电机温度 单位:℃ int16_t last_ecd; //上次转子机械角度 } motor_measure_t; typedef struct { uint8_t msg1; uint8_t msg2; uint16_t msg3; uint8_t msg4; uint8_t msg5; uint8_t msg6; uint8_t msg7; uint8_t msg8; } extended_mcu_msg_t; extern void CAN_CMD_CHASSIS_RESET_ID(void); //发送云台控制命令,其中rev为保留字节 extern void CAN_CMD_GIMBAL(int16_t yaw, int16_t pitch, int16_t shoot, int16_t rev); //发送底盘电机控制命令 extern void CAN_CMD_CHASSIS(int16_t motor1, int16_t motor2, int16_t motor3, int16_t motor4); extern void SetSuperPowerMcuMsg(uint8_t msg1 ,uint8_t msg2, uint8_t msg3, uint8_t msg4,uint8_t msg5,uint8_t msg6,uint8_t msg7,uint8_t msg8); //返回yaw电机变量地址,通过指针方式获取原始数据 extern const motor_measure_t *get_Yaw_Gimbal_Motor_Measure_Point(void); //返回pitch电机变量地址,通过指针方式获取原始数据 extern const motor_measure_t *get_Pitch_Gimbal_Motor_Measure_Point(void); //返回Shoot电机变量地址,通过指针方式获取原始数据 extern const motor_measure_t *get_Shoot_Motor_Measure_Point(void); //返回Push电机变量地址,通过指针方式获取原始数据 extern const motor_measure_t *get_Push_Motor_Measure_Point(void); //返回底盘电机变量地址,通过指针方式获取原始数据,i的范围是0-3,对应0x201-0x204, extern const motor_measure_t *get_Chassis_Motor_Measure_Point(uint8_t i); extern const extended_mcu_msg_t *get_SuperPowerMcu_Msg_Point(void); #endif <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file gimbal_task.c/h * @brief 完成云台控制任务,由于云台使用陀螺仪解算出的角度,其范围在(-pi,pi) * 故而设置目标角度均为范围,存在许多对角度计算的函数。云台主要分为2种 * 状态,陀螺仪控制状态是利用板载陀螺仪解算的姿态角进行控制,编码器控制 * 状态是通过电机反馈的编码值控制的校准,此外还有校准状态,停止状态等。 * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * V1.0.1 11-19-2019 Stone 1. 完成 @verbatim ============================================================================== ****************************(C) COPYRIGHT 2019 BDT**************************** */ /********************** 头文件 *******************************************/ #include "gimbal_behaviour.h" #include "arm_math.h" #include "buzzer.h" #include "Detect_Task.h" #include "user_lib.h" /********************** 1. 静态函数声明 *******************************************/ /** * @brief 云台行为状态机设置,因为在cali等模式下使用了return,故而再用了一个函数 * @author RM * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_behavour_set(Gimbal_Control_t *gimbal_mode_set); /** * @brief 云台无力控制,在这个模式下发送的yaw,pitch 是电机控制原始值,云台电机发送can零控制量,使得云台无力 * @author RM * @param[in] 发送yaw电机的原始值,会直接通过can 发送到电机 * @param[in] 发送pitch电机的原始值,会直接通过can 发送到电机 * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_zero_force_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set); /** * @brief 云台初始化控制,电机是陀螺仪角度控制,云台先抬起pitch轴,后旋转yaw轴 * @author RM * @param[in] yaw轴角度控制,为角度的增量 单位 rad * @param[in] pitch轴角度控制,为角度的增量 单位 rad * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_init_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set); /** * @brief 云台校准控制,电机是raw控制,云台先抬起pitch,放下pitch,在正转yaw,最后反转yaw,记录当时的角度和编码值 * @author RM * @param[in] 发送yaw电机的原始值,会直接通过can 发送到电机 * @param[in] 发送pitch电机的原始值,会直接通过can 发送到电机 * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_cali_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set); /** * @brief 云台陀螺仪控制,电机是陀螺仪角度控制, * @author RM * @param[in] yaw轴角度控制,为角度的增量 单位 rad * @param[in] pitch轴角度控制,为角度的增量 单位 rad * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_absolute_angle_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set); /** * @brief 云台编码值控制,电机是相对角度控制, * @author RM * @param[in] yaw轴角度控制,为角度的增量 单位 rad * @param[in] pitch轴角度控制,为角度的增量 单位 rad * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_relative_angle_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set); /** * @brief 云台进入遥控器无输入控制,电机是相对角度控制, * @author RM * @param[in] yaw轴角度控制,为角度的增量 单位 rad * @param[in] pitch轴角度控制,为角度的增量 单位 rad * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_motionless_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set); ////云台校准蜂鸣器响声 //#define GIMBALWarnBuzzerOn() buzzer_on(31, 20000) //#define GIMBALWarnBuzzerOFF() buzzer_off() /********************** 2. 宏定义 *************************************/ #define int_abs(x) ((x) > 0 ? (x) : (-x)) /** * @brief 遥控器的死区判断,因为遥控器的拨杆在中位的时候,不一定是发送1024过来, * @author RM * @param[in] 输入的遥控器值 * @param[in] 输出的死区处理后遥控器值 * @param[in] 死区值 * @retval 返回空 */ #define rc_deadline_limit(input, output, dealine) \ { \ if ((input) > (dealine) || (input) < -(dealine)) \ { \ (output) = (input); \ } \ else \ { \ (output) = 0; \ } \ } /** * @brief 云台校准的通过判断角速度来判断云台是否到达极限位置 * @author RM * @param[in] 对应轴的角速度,单位rad/s * @param[in] 计时时间,到达GIMBAL_CALI_STEP_TIME的时间后归零 * @param[in] 记录的角度 rad * @param[in] 反馈的角度 rad * @param[in] 记录的编码值 raw * @param[in] 反馈的编码值 raw * @param[in] 校准的步骤 完成一次 加一 * @retval 返回空 */ #define GIMBAL_CALI_GYRO_JUDGE(gyro, cmd_time, angle_set, angle, ecd_set, ecd, step) \ { \ if ((gyro) < GIMBAL_CALI_GYRO_LIMIT) \ { \ (cmd_time)++; \ if ((cmd_time) > GIMBAL_CALI_STEP_TIME) \ { \ (cmd_time) = 0; \ (angle_set) = (angle); \ (ecd_set) = (ecd); \ (step)++; \ } \ } \ } /***************** 3. 静态函数和全局函数内容定义 *****************************************/ /** * @brief 云台行为状态机以及电机状态机设置 * @author RM * @param[in] 云台数据指针 * @retval 返回空 */ //云台行为状态机 gimbal_behaviour_e gimbal_behaviour = GIMBAL_ZERO_FORCE; gimbal_motor_mode_e test = GIMBAL_MOTOR_ENCONDE; void gimbal_behaviour_mode_set(Gimbal_Control_t *gimbal_mode_set) { //检测是否输入是否为空指针 //如果是,则返回,防止错误设置云台状态机 if (gimbal_mode_set == NULL) { return; } //云台行为状态机设置,6种模式 gimbal_behavour_set(gimbal_mode_set);/// GIMBAL_ZERO_FORCE = 0, //云台无力 // GIMBAL_INIT=1 //云台初始化 // GIMBAL_CALI=2 //云台校准 // GIMBAL_ABSOLUTE_ANGLE=3 //云台陀螺仪绝对角度控制 // GIMBAL_RELATIVE_ANGLE=4,//云台编码值相对角度控制 // GIMBAL_MOTIONLESS=5 //云台在遥控器无输入一段时间后保持不动,避免陀螺仪漂移 //根据云台行为状态机设置云台电机状态机 if (gimbal_behaviour == GIMBAL_ZERO_FORCE) { gimbal_mode_set->gimbal_yaw_motor.gimbal_motor_mode = GIMBAL_MOTOR_RAW; gimbal_mode_set->gimbal_pitch_motor.gimbal_motor_mode = GIMBAL_MOTOR_RAW; } else if (gimbal_behaviour == GIMBAL_INIT) { gimbal_mode_set->gimbal_yaw_motor.gimbal_motor_mode = GIMBAL_MOTOR_ENCONDE; gimbal_mode_set->gimbal_pitch_motor.gimbal_motor_mode = GIMBAL_MOTOR_ENCONDE; } else if (gimbal_behaviour == GIMBAL_CALI) { gimbal_mode_set->gimbal_yaw_motor.gimbal_motor_mode = GIMBAL_MOTOR_RAW; gimbal_mode_set->gimbal_pitch_motor.gimbal_motor_mode = GIMBAL_MOTOR_RAW; } else if (gimbal_behaviour == GIMBAL_ABSOLUTE_ANGLE) { gimbal_mode_set->gimbal_yaw_motor.gimbal_motor_mode = GIMBAL_MOTOR_GYRO; gimbal_mode_set->gimbal_pitch_motor.gimbal_motor_mode = GIMBAL_MOTOR_GYRO; } else if (gimbal_behaviour == GIMBAL_RELATIVE_ANGLE) { gimbal_mode_set->gimbal_yaw_motor.gimbal_motor_mode = GIMBAL_MOTOR_ENCONDE; gimbal_mode_set->gimbal_pitch_motor.gimbal_motor_mode = GIMBAL_MOTOR_ENCONDE; } else if (gimbal_behaviour == GIMBAL_MOTIONLESS) { gimbal_mode_set->gimbal_yaw_motor.gimbal_motor_mode = GIMBAL_MOTOR_ENCONDE; gimbal_mode_set->gimbal_pitch_motor.gimbal_motor_mode = GIMBAL_MOTOR_ENCONDE; } } /** * @brief 云台行为控制,根据不同行为采用不同控制函数 * @author RM * @param[in] 设置的yaw角度增加值,单位 rad * @param[in] 设置的pitch角度增加值,单位 rad * @param[in] 云台数据指针 * @retval 返回空 */ void gimbal_behaviour_control_set(fp32 *add_yaw, fp32 *add_pitch, Gimbal_Control_t *gimbal_control_set) { if (add_yaw == NULL || add_pitch == NULL || gimbal_control_set == NULL) { return; } static fp32 rc_add_yaw, rc_add_pit; static int16_t yaw_channel = 0, pitch_channel = 0; /********** 遥控器数据处理死区+配合鼠标x和y的值一起赋值给rc_add_yaw,rc_add_pit *******************************************************/ //将gimbal_control->gimbal_rc_ctrl->rc.ch[YawChannel]处理死区, 赋值给yaw_channel 【static】 //将gimbal_control->gimbal_rc_ctrl->rc.ch[PitchChannel]处理死区,赋值给pitch_channel 【static】 rc_deadline_limit(gimbal_control_set->gimbal_rc_ctrl->rc.ch[YawChannel], yaw_channel, RC_deadband); rc_deadline_limit(gimbal_control_set->gimbal_rc_ctrl->rc.ch[PitchChannel], pitch_channel, RC_deadband); //yaw的增量 = k1倍的yaw_channel + k2倍的鼠标x方向值 //pitch的增量 = k1倍的pitch_channel + k2倍的鼠标y方向值 rc_add_yaw = yaw_channel * Yaw_RC_SEN - gimbal_control_set->gimbal_rc_ctrl->mouse.x * Yaw_Mouse_Sen; rc_add_pit = pitch_channel * Pitch_RC_SEN + gimbal_control_set->gimbal_rc_ctrl->mouse.y * Pitch_Mouse_Sen; /*********** 根据云台行为状态机gimbal_behaviour来采取相应控制,并将rc_add_yaw,rc_add_pit赋值进去得到add_yaw_angle和add_pitch_angle ***************/ if (gimbal_behaviour == GIMBAL_ZERO_FORCE) { gimbal_zero_force_control(&rc_add_yaw, &rc_add_pit, gimbal_control_set); } else if (gimbal_behaviour == GIMBAL_INIT) { gimbal_init_control(&rc_add_yaw, &rc_add_pit, gimbal_control_set); } else if (gimbal_behaviour == GIMBAL_CALI) { gimbal_cali_control(&rc_add_yaw, &rc_add_pit, gimbal_control_set); } else if (gimbal_behaviour == GIMBAL_ABSOLUTE_ANGLE) { gimbal_absolute_angle_control(&rc_add_yaw, &rc_add_pit, gimbal_control_set); //掉头程序 } else if (gimbal_behaviour == GIMBAL_RELATIVE_ANGLE) { gimbal_relative_angle_control(&rc_add_yaw, &rc_add_pit, gimbal_control_set); //return } else if (gimbal_behaviour == GIMBAL_MOTIONLESS) { gimbal_motionless_control(&rc_add_yaw, &rc_add_pit, gimbal_control_set); //rc_add_yaw、rc_add_pit置0 } //将控制增加量赋值 *add_yaw = rc_add_yaw; *add_pitch = rc_add_pit; } /** * @brief 云台在某些行为下,需要底盘不动 * @author RM * @param[in] void * @retval 返回空 */ bool_t gimbal_cmd_to_chassis_stop(void) { if (gimbal_behaviour == GIMBAL_INIT || gimbal_behaviour == GIMBAL_CALI || gimbal_behaviour == GIMBAL_MOTIONLESS || gimbal_behaviour == GIMBAL_ZERO_FORCE) { return 1; } else { return 0; } } /** * @brief 云台在某些行为下,需要射击停止 * @author RM * @param[in] void * @retval 返回空 */ bool_t gimbal_cmd_to_shoot_stop(void) { if (gimbal_behaviour == GIMBAL_INIT || gimbal_behaviour == GIMBAL_CALI || gimbal_behaviour == GIMBAL_ZERO_FORCE) { return 1; } else { return 0; } } /************** 云台行为状态机设置 ************************************************************/ /** * @brief 云台行为状态机设置,因为在cali等模式下使用了return,故而再用了一个函数 * @author RM * @param[in] 云台数据指针 * @retval 返回空 **/ // GIMBAL_ZERO_FORCE = 0, //云台无力 // GIMBAL_INIT=1 //云台初始化 // GIMBAL_CALI=2 //云台校准 // GIMBAL_ABSOLUTE_ANGLE=3 //云台陀螺仪绝对角度控制 // GIMBAL_RELATIVE_ANGLE=4,//云台编码值相对角度控制 // GIMBAL_MOTIONLESS=5 //云台在遥控器无输入一段时间后保持不动,避免陀螺仪漂移 static void gimbal_behavour_set(Gimbal_Control_t *gimbal_mode_set) { //检测是否输入是否为空指针 //如果是,则返回,防止错误设置云台状态机 if (gimbal_mode_set == NULL) { return; } // //校准行为,return 不会设置其他的模式 // if (gimbal_behaviour == GIMBAL_CALI && gimbal_mode_set->gimbal_cali.step != GIMBAL_CALI_END_STEP) // { // return; // } // //如果外部使得校准步骤从0 变成 start,则进入校准模式 // if (gimbal_mode_set->gimbal_cali.step == GIMBAL_CALI_START_STEP) // { // gimbal_behaviour = GIMBAL_CALI; // return; // } /*初始化模式进入*/ //初始化模式判断是否到达中值位置 // if (gimbal_behaviour == GIMBAL_INIT) // { // static uint16_t init_time = 0; // static uint16_t init_complete_time = 0; // init_time++; // // //到达中值 计时 // //Note:fabs()返回输入的绝对值 // //通过云台电机编码器返回的相对角度来判断是否到达INIT_YAW_SET角度 // if ((fabs(gimbal_mode_set->gimbal_yaw_motor.relative_angle - INIT_YAW_SET) < GIMBAL_INIT_ANGLE_ERROR && // fabs(gimbal_mode_set->gimbal_pitch_motor.absolute_angle - INIT_PITCH_SET) < GIMBAL_INIT_ANGLE_ERROR)) // { // //到达初始化位置 // if (init_complete_time < GIMBAL_INIT_STOP_TIME) //GIMBAL_INIT_STOP_TIME = 100(ms) // { // init_complete_time++; // } // } // else // { // //没有到达初始化位置,时间计时 // if (init_time < GIMBAL_INIT_TIME)// GIMBAL_INIT_TIME = 6000 (ms) // { // init_time++; // } // } // //超过初始化最大时间,或者已经稳定到中值一段时间,退出初始化状态开关打下档,或者掉线 // if (init_time < GIMBAL_INIT_TIME && init_complete_time < GIMBAL_INIT_STOP_TIME && // !switch_is_down(gimbal_mode_set->gimbal_rc_ctrl->rc.s[ModeChannel]) && !toe_is_error(DBUSTOE)) // { // return; // } // else // { // init_complete_time = 0; // init_time = 0; // } // } /*根据拨杆状态来赋值云台行为状态机*/ //开关控制 云台状态 //ModeChannel = 0 /*最下档位 无力模式*/ if (switch_is_down(gimbal_mode_set->gimbal_rc_ctrl->rc.s[ModeChannel])) { gimbal_behaviour = GIMBAL_ZERO_FORCE; } /*中档位 无力模式*/ else if (switch_is_mid(gimbal_mode_set->gimbal_rc_ctrl->rc.s[ModeChannel])) { gimbal_behaviour = GIMBAL_ZERO_FORCE; } /*最上档位 陀螺仪模式*/ else if (switch_is_up(gimbal_mode_set->gimbal_rc_ctrl->rc.s[ModeChannel])) { gimbal_behaviour = GIMBAL_ABSOLUTE_ANGLE; } //关闭检测错误任务 // if( toe_is_error(DBUSTOE)) // { // gimbal_behaviour = GIMBAL_ZERO_FORCE; // } //判断进入init状态机 // { // static gimbal_behaviour_e last_gimbal_behaviour = GIMBAL_ZERO_FORCE; // if (last_gimbal_behaviour == GIMBAL_ZERO_FORCE && gimbal_behaviour != GIMBAL_ZERO_FORCE) // { // gimbal_behaviour = GIMBAL_INIT; // } // last_gimbal_behaviour = gimbal_behaviour; // } //检测底盘是否进入无力模式 // static uint16_t motionless_time = 0; // if (gimbal_behaviour == GIMBAL_ABSOLUTE_ANGLE) // { // //遥控器 键盘均无输入,进入motionless状态 // if (int_abs(gimbal_mode_set->gimbal_rc_ctrl->rc.ch[0]) < GIMBAL_MOTIONLESS_RC_DEADLINE && int_abs(gimbal_mode_set->gimbal_rc_ctrl->rc.ch[1]) < GIMBAL_MOTIONLESS_RC_DEADLINE && int_abs(gimbal_mode_set->gimbal_rc_ctrl->rc.ch[2]) < GIMBAL_MOTIONLESS_RC_DEADLINE && int_abs(gimbal_mode_set->gimbal_rc_ctrl->rc.ch[3]) < GIMBAL_MOTIONLESS_RC_DEADLINE && int_abs(gimbal_mode_set->gimbal_rc_ctrl->mouse.x) < GIMBAL_MOTIONLESS_RC_DEADLINE && int_abs(gimbal_mode_set->gimbal_rc_ctrl->mouse.y) < GIMBAL_MOTIONLESS_RC_DEADLINE && gimbal_mode_set->gimbal_rc_ctrl->key.v == 0 && gimbal_mode_set->gimbal_rc_ctrl->mouse.press_l == 0 && gimbal_mode_set->gimbal_rc_ctrl->mouse.press_r == 0) // { // if (motionless_time < GIMBAL_MOTIONLESS_TIME_MAX) // { // motionless_time++; // } // } // else // { // motionless_time = 0; // } // if (motionless_time == GIMBAL_MOTIONLESS_TIME_MAX) // { // gimbal_behaviour = GIMBAL_MOTIONLESS; // } // } // else // { // motionless_time = 0; // } } /*************************** 控制模式选用 ***************************/ /** * @brief 云台无力控制,在这个模式下发送的yaw,pitch 是电机控制原始值,云台电机发送can零控制量,使得云台无力 * @author RM * @param[in] 发送yaw电机的原始值,会直接通过can 发送到电机 * @param[in] 发送pitch电机的原始值,会直接通过can 发送到电机 * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_zero_force_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set) { if (yaw == NULL || pitch == NULL || gimbal_control_set == NULL) { return; } *yaw = 0.0f; *pitch = 0.0f; } /** * @brief 云台初始化控制,电机是陀螺仪角度控制,云台先抬起pitch轴,后旋转yaw轴 * @author RM * @param[in] yaw轴角度控制,为角度的增量 单位 rad * @param[in] pitch轴角度控制,为角度的增量 单位 rad * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_init_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set) { if (yaw == NULL || pitch == NULL || gimbal_control_set == NULL) { return; } //初始化状态控制量计算 if (fabs(INIT_PITCH_SET - gimbal_control_set->gimbal_pitch_motor.absolute_angle) > GIMBAL_INIT_ANGLE_ERROR) { *pitch = (INIT_PITCH_SET - gimbal_control_set->gimbal_pitch_motor.absolute_angle) * GIMBAL_INIT_PITCH_SPEED; *yaw = 0.0f; } else { *pitch = (INIT_PITCH_SET - gimbal_control_set->gimbal_pitch_motor.absolute_angle) * GIMBAL_INIT_PITCH_SPEED; *yaw = (INIT_YAW_SET - gimbal_control_set->gimbal_yaw_motor.relative_angle) * GIMBAL_INIT_YAW_SPEED; } } /** * @brief 云台校准控制,电机是raw控制,云台先抬起pitch,放下pitch,在正转yaw,最后反转yaw,记录当时的角度和编码值 * @author RM * @param[in] 发送yaw电机的原始值,会直接通过can 发送到电机 * @param[in] 发送pitch电机的原始值,会直接通过can 发送到电机 * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_cali_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set) { if (yaw == NULL || pitch == NULL || gimbal_control_set == NULL) { return; } static uint16_t cali_time = 0; if (gimbal_control_set->gimbal_cali.step == GIMBAL_CALI_PITCH_MAX_STEP) { *pitch = GIMBAL_CALI_MOTOR_SET; *yaw = 0; //判断陀螺仪数据, 并记录最大最小角度数据 GIMBAL_CALI_GYRO_JUDGE(gimbal_control_set->gimbal_pitch_motor.motor_gyro, cali_time, gimbal_control_set->gimbal_cali.max_pitch, gimbal_control_set->gimbal_pitch_motor.absolute_angle, gimbal_control_set->gimbal_cali.max_pitch_ecd, gimbal_control_set->gimbal_pitch_motor.gimbal_motor_measure->ecd, gimbal_control_set->gimbal_cali.step); } else if (gimbal_control_set->gimbal_cali.step == GIMBAL_CALI_PITCH_MIN_STEP) { *pitch = -GIMBAL_CALI_MOTOR_SET; *yaw = 0; GIMBAL_CALI_GYRO_JUDGE(gimbal_control_set->gimbal_pitch_motor.motor_gyro, cali_time, gimbal_control_set->gimbal_cali.min_pitch, gimbal_control_set->gimbal_pitch_motor.absolute_angle, gimbal_control_set->gimbal_cali.min_pitch_ecd, gimbal_control_set->gimbal_pitch_motor.gimbal_motor_measure->ecd, gimbal_control_set->gimbal_cali.step); } else if (gimbal_control_set->gimbal_cali.step == GIMBAL_CALI_YAW_MAX_STEP) { *pitch = 0; *yaw = GIMBAL_CALI_MOTOR_SET; GIMBAL_CALI_GYRO_JUDGE(gimbal_control_set->gimbal_yaw_motor.motor_gyro, cali_time, gimbal_control_set->gimbal_cali.max_yaw, gimbal_control_set->gimbal_yaw_motor.absolute_angle, gimbal_control_set->gimbal_cali.max_yaw_ecd, gimbal_control_set->gimbal_yaw_motor.gimbal_motor_measure->ecd, gimbal_control_set->gimbal_cali.step); } else if (gimbal_control_set->gimbal_cali.step == GIMBAL_CALI_YAW_MIN_STEP) { *pitch = 0; *yaw = -GIMBAL_CALI_MOTOR_SET; GIMBAL_CALI_GYRO_JUDGE(gimbal_control_set->gimbal_yaw_motor.motor_gyro, cali_time, gimbal_control_set->gimbal_cali.min_yaw, gimbal_control_set->gimbal_yaw_motor.absolute_angle, gimbal_control_set->gimbal_cali.min_yaw_ecd, gimbal_control_set->gimbal_yaw_motor.gimbal_motor_measure->ecd, gimbal_control_set->gimbal_cali.step); } else if (gimbal_control_set->gimbal_cali.step == GIMBAL_CALI_END_STEP) { cali_time = 0; } } /** * @brief 云台陀螺仪控制,电机是陀螺仪角度控制, * @author RM * @param[in] yaw轴角度控制,为角度的增量 单位 rad * @param[in] pitch轴角度控制,为角度的增量 单位 rad * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_absolute_angle_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set) { if (yaw == NULL || pitch == NULL || gimbal_control_set == NULL) { return; } { static uint16_t last_turn_keyboard = 0; static uint8_t gimbal_turn_flag = 0; static fp32 gimbal_end_angle = 0.0f; if ((gimbal_control_set->gimbal_rc_ctrl->key.v & TurnKeyBoard) && !(last_turn_keyboard & TurnKeyBoard)) { if (gimbal_turn_flag == 0) { gimbal_turn_flag = 1; //赋值为当前偏航角的角度+180度,即掉头的偏航角期望角度 gimbal_end_angle = rad_format(gimbal_control_set->gimbal_yaw_motor.absolute_angle + PI); } } last_turn_keyboard = gimbal_control_set->gimbal_rc_ctrl->key.v ; if (gimbal_turn_flag) { //不断控制到掉头的目标值,正转,反装是随机 // if (rad_format(gimbal_end_angle - gimbal_control_set->gimbal_yaw_motor.absolute_angle) > 0.0f) // { // *yaw -= TurnSpeed; //#define TurnSpeed 0.04f // } // else // { // *yaw += TurnSpeed; //#define TurnSpeed 0.04f // } if (rad_format(gimbal_end_angle - gimbal_control_set->gimbal_yaw_motor.absolute_angle) > 0.0f) { *yaw = 2; //#define TurnSpeed 0.04f } else { *yaw = 0 ; //#define TurnSpeed 0.04f } } //到达pi (180°)后停止 if (gimbal_turn_flag && fabs(rad_format(gimbal_end_angle - gimbal_control_set->gimbal_yaw_motor.absolute_angle)) < 0.01f) { gimbal_turn_flag = 0; } } } /** * @brief 云台编码值控制,电机是相对角度控制, * @author RM * @param[in] yaw轴角度控制,为角度的增量 单位 rad * @param[in] pitch轴角度控制,为角度的增量 单位 rad * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_relative_angle_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set) { if (yaw == NULL || pitch == NULL || gimbal_control_set == NULL) { return; } //不需要处理, } /** * @brief 云台进入遥控器无输入控制,电机是相对角度控制, * @author RM * @param[in] yaw轴角度控制,为角度的增量 单位 rad * @param[in] pitch轴角度控制,为角度的增量 单位 rad * @param[in] 云台数据指针 * @retval 返回空 */ static void gimbal_motionless_control(fp32 *yaw, fp32 *pitch, Gimbal_Control_t *gimbal_control_set) { if (yaw == NULL || pitch == NULL || gimbal_control_set == NULL) { return; } *yaw = 0.0f; *pitch = 0.0f; } <file_sep>#include "spi.h" #include "stm32f4xx.h" void SPI5Init(void) { GPIO_InitTypeDef GPIO_InitStructure; SPI_InitTypeDef SPI_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI5, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_Init(GPIOF, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOF, GPIO_PinSource7, GPIO_AF_SPI5); //SCK GPIO_PinAFConfig(GPIOF, GPIO_PinSource8, GPIO_AF_SPI5); //MISO GPIO_PinAFConfig(GPIOF, GPIO_PinSource9, GPIO_AF_SPI5); //MOSI RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI5, ENABLE); RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI5, DISABLE); SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; //双线全双工 SPI_InitStructure.SPI_Mode = SPI_Mode_Master; //主机模式,SCK线信号的时序由主机产生 SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; //SCK在空闲状态时为高电平 SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; //在SCK信号偶数边采集数据 SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; //软件NSS线 SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256; SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; SPI_InitStructure.SPI_CRCPolynomial = 7; SPI_Init(SPI5, &SPI_InitStructure); SPI_Cmd(SPI5, ENABLE); } void SPI5SetSpeedAndDataSize(uint16_t Speed, uint16_t DataSize) { SPI5->CR1 &= 0xF7C7; SPI5->CR1 |= Speed; SPI5->CR1 |= DataSize; SPI5->CR1 |= 1 << 6; } void SPI5_DMA_Init(uint32_t tx_buf, uint32_t rx_buf, uint16_t num) { NVIC_InitTypeDef NVIC_InitStructure; DMA_InitTypeDef DMA_InitStructure; /* -------------- Enable Module Clock Source ----------------------------*/ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE); NVIC_InitStructure.NVIC_IRQChannel = DMA2_Stream5_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = SPI5_RX_NVIC; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); DMA_DeInit(DMA2_Stream5); while (DMA_GetCmdStatus(DMA2_Stream5) != DISABLE) { ; } DMA_InitStructure.DMA_Channel = DMA_Channel_7; DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t) & (SPI5->DR); DMA_InitStructure.DMA_Memory0BaseAddr = rx_buf; DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory; DMA_InitStructure.DMA_BufferSize = num; DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable; DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte; DMA_InitStructure.DMA_Mode = DMA_Mode_Normal; DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh; DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable; DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_1QuarterFull; DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single; DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; DMA_Init(DMA2_Stream5, &DMA_InitStructure); DMA_ITConfig(DMA2_Stream5, DMA_IT_TC, ENABLE); DMA_Cmd(DMA2_Stream5, DISABLE); //Add a disable DMA_DeInit(DMA2_Stream4); while (DMA_GetCmdStatus(DMA2_Stream4) != DISABLE) { ; } DMA_InitStructure.DMA_Channel = DMA_Channel_2; DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t) & (SPI5->DR); DMA_InitStructure.DMA_Memory0BaseAddr = tx_buf; DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral; DMA_InitStructure.DMA_BufferSize = num; DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable; DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte; DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte; DMA_InitStructure.DMA_Mode = DMA_Mode_Normal; DMA_InitStructure.DMA_Priority = DMA_Priority_Medium; DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable; DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_1QuarterFull; DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single; DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; DMA_Init(DMA2_Stream4, &DMA_InitStructure); DMA_Cmd(DMA2_Stream4, DISABLE); //Add a disable } void SPI5_DMA_Enable(uint16_t ndtr) { DMA_Cmd(DMA2_Stream4, DISABLE); DMA_Cmd(DMA2_Stream5, DISABLE); while (DMA_GetCmdStatus(DMA2_Stream4) != DISABLE) { ; } while (DMA_GetCmdStatus(DMA2_Stream5) != DISABLE) { ; } DMA_ClearFlag(DMA2_Stream5, DMA_FLAG_TCIF5 | DMA_FLAG_HTIF5); DMA_ClearFlag(DMA2_Stream4, DMA_FLAG_TCIF4 | DMA_FLAG_HTIF4); DMA_SetCurrDataCounter(DMA2_Stream4, ndtr); DMA_SetCurrDataCounter(DMA2_Stream5, ndtr); DMA_Cmd(DMA2_Stream5, ENABLE); DMA_Cmd(DMA2_Stream4, ENABLE); } <file_sep>#include "timer.h" #include "stm32f4xx.h" void TIM1_Init(uint16_t arr, uint16_t psc) { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; TIM_OCInitTypeDef TIM_OCInitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE); GPIO_PinAFConfig(GPIOA, GPIO_PinSource8, GPIO_AF_TIM1); GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_TIM1); GPIO_PinAFConfig(GPIOE, GPIO_PinSource13, GPIO_AF_TIM1); GPIO_PinAFConfig(GPIOE, GPIO_PinSource14, GPIO_AF_TIM1); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14; GPIO_Init(GPIOE, &GPIO_InitStructure); RCC_APB2PeriphResetCmd(RCC_APB2Periph_TIM1, ENABLE); RCC_APB2PeriphResetCmd(RCC_APB2Periph_TIM1, DISABLE); TIM_TimeBaseInitStructure.TIM_Period = arr - 1; TIM_TimeBaseInitStructure.TIM_Prescaler = psc - 1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStructure); TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OCInitStructure.TIM_Pulse = 1000; TIM_OC1Init(TIM1, &TIM_OCInitStructure); TIM_OC2Init(TIM1, &TIM_OCInitStructure); TIM_OC3Init(TIM1, &TIM_OCInitStructure); TIM_OC4Init(TIM1, &TIM_OCInitStructure); TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable); TIM_OC2PreloadConfig(TIM1, TIM_OCPreload_Enable); TIM_OC3PreloadConfig(TIM1, TIM_OCPreload_Enable); TIM_OC4PreloadConfig(TIM1, TIM_OCPreload_Enable); TIM_ARRPreloadConfig(TIM1, ENABLE); TIM_CtrlPWMOutputs(TIM1, ENABLE); TIM_Cmd(TIM1, ENABLE); } void TIM3_Init(uint16_t arr, uint16_t psc) { TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; GPIO_InitTypeDef GPIO_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; TIM_OCInitTypeDef TIM_OCInitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); GPIO_PinAFConfig(GPIOB, GPIO_PinSource5, GPIO_AF_TIM3); RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM3, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM3, DISABLE); NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = TIM3_NVIC; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); TIM_TimeBaseInitStructure.TIM_Period = arr - 1; TIM_TimeBaseInitStructure.TIM_Prescaler = psc - 1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE); //这个函数会让整个程序跑死在这里,没懂为什么,mlgb,但是在老程序里可以用,我不知道我是不是改了什么东西不记得了 TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure); /* TIM3 */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN; GPIO_Init(GPIOB, &GPIO_InitStructure); TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC2Init(TIM3, &TIM_OCInitStructure); TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable); TIM_ARRPreloadConfig(TIM3, ENABLE); TIM_Cmd(TIM3, ENABLE); } void TIM6_Init(uint16_t arr, uint16_t psc) { TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM6, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM6, DISABLE); TIM_DeInit(TIM6); TIM_TimeBaseInitStructure.TIM_Period = arr - 1; TIM_TimeBaseInitStructure.TIM_Prescaler = psc - 1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInit(TIM6, &TIM_TimeBaseInitStructure); TIM_ITConfig(TIM6, TIM_IT_Update, ENABLE); NVIC_InitStructure.NVIC_IRQChannel = TIM6_DAC_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = TIM6_NVIC; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); TIM_Cmd(TIM6, ENABLE); //ʹ�ܶ�ʱ��6 } void TIM12_Init(uint16_t arr, uint16_t psc) { TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM12, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM12, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_TIM12, DISABLE); TIM_TimeBaseInitStructure.TIM_Period = arr - 1; TIM_TimeBaseInitStructure.TIM_Prescaler = psc - 1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInit(TIM12, &TIM_TimeBaseInitStructure); TIM_Cmd(TIM12, ENABLE); } <file_sep>#ifndef FRIC_H #define FRIC_H #include "main.h" #define Fric_UP 1300 #define Fric_DOWN 1250 #define Fric_OFF 1000 extern void fric_PWM_configuration(void); extern void fric_off(void); extern void fric1_on(uint16_t cmd); extern void fric2_on(uint16_t cmd); #endif <file_sep>#ifndef __GM6020_PWM_H__ #define __GM6020_PWM_H__ #include "stm32f4xx.h" extern void GM6020_PWM_configuration(void); #endif <file_sep>#ifndef _DATA_TRANSFER_H #define _DATA_TRANSFER_H #include "stm32f4xx.h" #include "uart7.h" #include "protocol.h" #include "referee_API.h" #include "chassis_task.h" #define PAR_PID_1_P 1 #define PAR_PID_1_I 2 #define PAR_PID_1_D 3 #define PAR_PID_2_P 4 #define PAR_PID_2_I 5 #define PAR_PID_2_D 6 #define PAR_PID_3_P 7 #define PAR_PID_3_I 8 #define PAR_PID_3_D 9 #define PAR_PID_4_P 10 #define PAR_PID_4_I 11 #define PAR_PID_4_D 12 #define PAR_PID_5_P 13 #define PAR_PID_5_I 14 #define PAR_PID_5_D 15 #define PAR_PID_6_P 16 #define PAR_PID_6_I 17 #define PAR_PID_6_D 18 #define PAR_PID_7_P 19 #define PAR_PID_7_I 20 #define PAR_PID_7_D 21 #define PAR_PID_8_P 22 #define PAR_PID_8_I 23 #define PAR_PID_8_D 24 #define PAR_PID_9_P 25 #define PAR_PID_9_I 26 #define PAR_PID_9_D 27 #define PAR_PID_10_P 28 #define PAR_PID_10_I 29 #define PAR_PID_10_D 30 #define PAR_PID_11_P 31 #define PAR_PID_11_I 32 #define PAR_PID_11_D 33 #define PAR_PID_12_P 34 #define PAR_PID_12_I 35 #define PAR_PID_12_D 36 #define PAR_PID_13_P 37 #define PAR_PID_13_I 38 #define PAR_PID_13_D 39 #define PAR_PID_14_P 40 #define PAR_PID_14_I 41 #define PAR_PID_14_D 42 #define PAR_PID_15_P 43 #define PAR_PID_15_I 44 #define PAR_PID_15_D 45 #define PAR_PID_16_P 46 #define PAR_PID_16_I 47 #define PAR_PID_16_D 48 #define PAR_PID_17_P 49 #define PAR_PID_17_I 50 #define PAR_PID_17_D 51 #define PAR_PID_18_P 52 #define PAR_PID_18_I 53 #define PAR_PID_18_D 54 #define PAR_RCINMODE 61 #define PAR_UNLOCKPWM 62 #define PAR_LVWARN 63 #define PAR_LVRETN 64 #define PAR_LVDOWN 65 #define PAR_CENPOSX 66 #define PAR_CENPOSY 67 #define PAR_CENPOSZ 68 #define PAR_TAKEOFFHIGH 69 #define PAR_TAKEOFFSPEED 70 #define PAR_LANDSPEED 71 #define PAR_HEATSWITCH 72 typedef struct { const ext_power_heat_data_t *power_heat_data_pointer; //IMU角度指针 const ext_game_robot_state_t *robot_state_pointer; const float *voltage_pointer; // 超级电容电压 }robot_status_dt_t; typedef struct { u8 msg_id; u8 msg_data; u8 send_check; u8 send_version; u8 send_status; u8 send_senser; u8 send_senser2; u8 send_rcdata; u8 send_offset; u8 send_motopwm; u8 send_power; u8 send_user; u8 send_speed; u8 send_location; u8 send_vef; u16 send_parame; u16 paraToSend; } dt_flag_t; extern s32 ParValList[100]; extern dt_flag_t f; void ANO_DT_Data_Receive_Anl_Task(void); void ANO_DT_Send_VER(void); void ANO_DT_Data_Exchange(void); void ANO_DT_Data_Receive_Prepare(u8 data); void ANO_DT_Data_Receive_Anl(u8 *data_buf,u8 num); void ANO_DT_Send_Version(u8 hardware_type, u16 hardware_ver,u16 software_ver,u16 protocol_ver,u16 bootloader_ver); void ANO_DT_Send_Status(float angle_rol, float angle_pit, float angle_yaw, s32 alt, u8 fly_model, u8 armed); void ANO_DT_Send_Senser(s16 a_x,s16 a_y,s16 a_z,s16 g_x,s16 g_y,s16 g_z,s16 m_x,s16 m_y,s16 m_z); void ANO_DT_Send_Senser2(s32 bar_alt,s32 csb_alt, s16 sensertmp); void ANO_DT_Send_RCData(u16 thr,u16 yaw,u16 rol,u16 pit,u16 aux1,u16 aux2,u16 aux3,u16 aux4,u16 aux5,u16 aux6); void ANO_DT_Send_Power(u16 votage, u16 current); void ANO_DT_Send_MotoPWM(u16 m_1,u16 m_2,u16 m_3,u16 m_4,u16 m_5,u16 m_6,u16 m_7,u16 m_8); void ANO_DT_Send_PID(u8 group,float p1_p,float p1_i,float p1_d,float p2_p,float p2_i,float p2_d,float p3_p,float p3_i,float p3_d); void ANO_DT_Send_User(void); void ANO_DT_Send_Speed(float,float,float); void ANO_DT_Send_Location(u8 state,u8 sat_num,s32 lon,s32 lat,float back_home_angle,float back_home_dist); void ANO_DT_SendCenterPos(float x,float y,float z); void ANO_DT_SendParame(u16 num); void ANO_DT_GetParame(u16 num,s32 data); void ANO_DT_ParListToParUsed(void); void ANO_DT_ParUsedToParList(void); void ANO_DT_SendCmd(u8 dest, u8 fun, u16 cmd1, u16 cmd2, u16 cmd3, u16 cmd4, u16 cmd5); void ANO_DT_SendString(const char *str); void ANO_DT_SendStrVal(const char *str, s32 val); void ANODT_SendF1(s16 _a, s16 _b, s32 _c); void ANODT_SendF2(u16 _a, u16 _b, u8 _c,u16 _d,u16 _e); void ANODT_GetByte(u8 data); void ANODT_DATA_Setup(void); void ANODT_DATA_Task(void); #endif <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file can_receive.c/h * @brief 完成can设备数据收发函数,该文件是通过can中断完成接收 * @note * @history * Version Date Author Modification * V1.0.0 2019-11-16 Stone 1. 完成 * @verbatim ============================================================================== 程序流程解释: 电调向CAN1总线发送反馈报文 ---->CAN1_RX0_IRQHandler() ----> CAN_hook() ----> get_motor_measure(ptr, rx_message) 或 get_gimbal_motor_measuer(ptr, rx_message) 电调向CAN2总线发送反馈报文 ---->CAN2_RX0_IRQHandler() ----> CAN_hook() ----> get_motor_measure(ptr, rx_message) 或 get_gimbal_motor_measuer(ptr, rx_message) 反馈信息分别存放在motor_yaw, motor_pit, motor_trigger, motor_chassis[4]结构体变量中 ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ /************************* 头文件 ******************************/ #include "CAN_Receive.h" #include "stm32f4xx.h" #include "rng.h" #include "Detect_Task.h" /*********************** 宏定义函数 ****************************/ //底盘电机数据读取 //在CAN_hook()中使用 #define get_motor_measure(ptr, rx_message) \ { \ (ptr)->last_ecd = (ptr)->ecd; \ (ptr)->ecd = (uint16_t)((rx_message)->Data[0] << 8 | (rx_message)->Data[1]); \ (ptr)->speed_rpm = (uint16_t)((rx_message)->Data[2] << 8 | (rx_message)->Data[3]); \ (ptr)->given_current = (uint16_t)((rx_message)->Data[4] << 8 | (rx_message)->Data[5]); \ (ptr)->temperate = (rx_message)->Data[6]; \ } //云台电机数据读取 //CAN_hook()中使用 #define get_gimbal_motor_measuer(ptr, rx_message) \ { \ (ptr)->last_ecd = (ptr)->ecd; \ (ptr)->ecd = (uint16_t)((rx_message)->Data[0] << 8 | (rx_message)->Data[1]); \ (ptr)->given_current = (uint16_t)((rx_message)->Data[2] << 8 | (rx_message)->Data[3]); \ (ptr)->speed_rpm = (uint16_t)((rx_message)->Data[4] << 8 | (rx_message)->Data[5]); \ (ptr)->temperate = (rx_message)->Data[6]; \ } #define get_super_power_mcu_msg(ptr, rx_message) \ { \ (ptr)->msg1 = (rx_message)->Data[0]; \ (ptr)->msg2 = (rx_message)->Data[1]; \ (ptr)->msg3 = (uint16_t)((rx_message)->Data[2] << 8 | (rx_message)->Data[3]); \ (ptr)->msg4 = (rx_message)->Data[3]; \ (ptr)->msg5 = (rx_message)->Data[4]; \ (ptr)->msg6 = (rx_message)->Data[5]; \ (ptr)->msg7 = (rx_message)->Data[6]; \ (ptr)->msg8 = (rx_message)->Data[7]; \ } /************************ 函数定义 ******************************/ //报文解析函数 //CAN1_RX0_IRQHandler()中使用 //CAN2_RX0_IRQHandler()中使用 static void CAN_hook(CanRxMsg *rx_message); /*********************** 全局变量定义 ***************************/ //声明电机变量 motor_measure_t motor_yaw, motor_pit, motor_push, motor_shoot , motor_chassis[4]; //方便Debug查看变量 把静态去掉 extended_mcu_msg_t super_power_mcu_msg; static CanTxMsg GIMBAL_TxMessage; /************************ 函数内容 ******************************/ //can1接收中断服务函数 void CAN1_RX0_IRQHandler(void) { static CanRxMsg rx1_message; if (CAN_GetITStatus(CAN1, CAN_IT_FMP0) != RESET) { CAN_ClearITPendingBit(CAN1, CAN_IT_FMP0); CAN_Receive(CAN1, CAN_FIFO0, &rx1_message); CAN_hook(&rx1_message); } } //can2接收中断服务函数 void CAN2_RX0_IRQHandler(void) { static CanRxMsg rx2_message; if (CAN_GetITStatus(CAN2, CAN_IT_FMP0) != RESET) { CAN_ClearITPendingBit(CAN2, CAN_IT_FMP0); CAN_Receive(CAN2, CAN_FIFO0, &rx2_message); CAN_hook(&rx2_message); } } //发送云台控制命令,其中rev为保留字节 //Gimbal_Task里用 void CAN_CMD_GIMBAL(int16_t yaw, int16_t pitch, int16_t shoot, int16_t rev) { GIMBAL_TxMessage.StdId = CAN_GIMBAL_ALL_ID; GIMBAL_TxMessage.IDE = CAN_ID_STD; GIMBAL_TxMessage.RTR = CAN_RTR_DATA; GIMBAL_TxMessage.DLC = 0x08; GIMBAL_TxMessage.Data[0] = (yaw >> 8); GIMBAL_TxMessage.Data[1] = yaw; GIMBAL_TxMessage.Data[2] = (pitch >> 8); GIMBAL_TxMessage.Data[3] = pitch; GIMBAL_TxMessage.Data[4] = (shoot >> 8); GIMBAL_TxMessage.Data[5] = shoot; GIMBAL_TxMessage.Data[6] = (rev >> 8); GIMBAL_TxMessage.Data[7] = rev; CAN_Transmit( GIMBAL_CAN, &GIMBAL_TxMessage ); } void TIM6_DAC_IRQHandler(void) { if( TIM_GetITStatus( TIM6, TIM_IT_Update )!= RESET ) { TIM_ClearFlag( TIM6, TIM_IT_Update ); #if GIMBAL_MOTOR_6020_CAN_LOSE_SLOVE CAN_Transmit( GIMBAL_CAN, &GIMBAL_TxMessage ); #endif TIM_Cmd(TIM6,DISABLE); } } //CAN 发送 0x700的ID的数据,会引发M3508进入快速设置ID模式 //在任务中没有使用 void CAN_CMD_CHASSIS_RESET_ID(void) { CanTxMsg TxMessage; TxMessage.StdId = 0x700; TxMessage.IDE = CAN_ID_STD; TxMessage.RTR = CAN_RTR_DATA; TxMessage.DLC = 0x08; TxMessage.Data[0] = 0; TxMessage.Data[1] = 0; TxMessage.Data[2] = 0; TxMessage.Data[3] = 0; TxMessage.Data[4] = 0; TxMessage.Data[5] = 0; TxMessage.Data[6] = 0; TxMessage.Data[7] = 0; CAN_Transmit(CAN2, &TxMessage); } //发送底盘电机控制命令 //在chassis_task中使用 void CAN_CMD_CHASSIS(int16_t motor1, int16_t motor2, int16_t motor3, int16_t motor4) { CanTxMsg TxMessage; TxMessage.StdId = CAN_CHASSIS_ALL_ID; TxMessage.IDE = CAN_ID_STD; TxMessage.RTR = CAN_RTR_DATA; TxMessage.DLC = 0x08; TxMessage.Data[0] = motor1 >> 8; TxMessage.Data[1] = motor1; TxMessage.Data[2] = motor2 >> 8; TxMessage.Data[3] = motor2; TxMessage.Data[4] = motor3 >> 8; TxMessage.Data[5] = motor3; TxMessage.Data[6] = motor4 >> 8; TxMessage.Data[7] = motor4; CAN_Transmit(CHASSIS_CAN, &TxMessage); } //返回yaw电机变量地址,通过指针方式获取原始数据 const motor_measure_t *get_Yaw_Gimbal_Motor_Measure_Point(void) { return &motor_yaw; } //返回pitch电机变量地址,通过指针方式获取原始数据 const motor_measure_t *get_Pitch_Gimbal_Motor_Measure_Point(void) { return &motor_pit; } //返回Shoot电机变量地址,通过指针方式获取原始数据 const motor_measure_t *get_Shoot_Motor_Measure_Point(void) { return &motor_shoot; } //返回Push电机变量地址,通过指针方式获取原始数据 const motor_measure_t *get_Push_Motor_Measure_Point(void) { return &motor_push; } //返回底盘电机变量地址,通过指针方式获取原始数据 const motor_measure_t *get_Chassis_Motor_Measure_Point(uint8_t i) { return &motor_chassis[(i & 0x03)];//i & 0000 0011 } const extended_mcu_msg_t *get_SuperPowerMcu_Msg_Point(void) { return &super_power_mcu_msg;//i & 0000 0011 } void SetSuperPowerMcuMsg(uint8_t msg1 ,uint8_t msg2, uint8_t msg3, uint8_t msg4,uint8_t msg5,uint8_t msg6,uint8_t msg7,uint8_t msg8) { unsigned short can_id = 0x000; CanTxMsg tx_message; tx_message.IDE = CAN_ID_STD; //标准帧 tx_message.RTR = CAN_RTR_DATA; //数据帧 tx_message.DLC = 0x08; //帧长度为8 can_id = CAN_SetSuperPower_ID; tx_message.StdId = can_id; //帧ID为传入参数的CAN_ID tx_message.Data[0] = msg1; tx_message.Data[1] = msg2; tx_message.Data[2] = msg3; tx_message.Data[3] = msg4; tx_message.Data[4] = msg5; tx_message.Data[5] = msg6; tx_message.Data[6] = msg7; tx_message.Data[7] = msg8; CAN_Transmit(CAN1,&tx_message); } //CAN总线电调反馈报文解析函数,并且记录发送数据的时间,作为离线判断依据 //临时去掉DetectTask任务 static void CAN_hook(CanRxMsg *rx_message) { switch (rx_message->StdId) { case CAN_YAW_MOTOR_ID: { //处理电机数据宏函数 get_gimbal_motor_measuer(&motor_yaw, rx_message); //记录时间 //DetectHook(YawGimbalMotorTOE); //临时去掉DetectTask任务 break; } case CAN_PIT_MOTOR_ID: { //处理电机数据宏函数 get_gimbal_motor_measuer(&motor_pit, rx_message); //DetectHook(PitchGimbalMotorTOE); break; } case CAN_SHOOT_ID: { //处理电机数据宏函数 get_motor_measure(&motor_shoot, rx_message); //记录时间 //DetectHook(TriggerMotorTOE); //临时去掉DetectTask任务 break; } case CAN_PUSH_ID: { get_gimbal_motor_measuer(&motor_push, rx_message); break; } case CAN_3508_M1_ID: case CAN_3508_M2_ID: case CAN_3508_M3_ID: case CAN_3508_M4_ID: { static uint8_t i = 0; //处理电机ID号 i = rx_message->StdId - CAN_3508_M1_ID; //处理电机数据宏函数 get_motor_measure(&motor_chassis[i], rx_message); //记录时间 //DetectHook(ChassisMotor1TOE + i); //临时去掉DetectTask任务 break; } case CAN_SuperPower_MCU_ID: { get_super_power_mcu_msg(&super_power_mcu_msg, rx_message); break; } default: { break; } } } <file_sep>#include "exit_init.h" #include "trigger_switch.h" #include "stm32f4xx.h" void GPIOB_Exti8_GPIO_Init(void) { NVIC_InitTypeDef NVIC_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOB, EXTI_PinSource8); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_OType = GPIO_OType_OD; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); EXTI_InitStructure.EXTI_Line = EXTI_Line8; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = MPU_INT_NVIC; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } void GPIOF_Exti0_GPIO_Init(void) // 拨叉二级弹仓内限位开关 { NVIC_InitTypeDef NVIC_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOF, EXTI_PinSource0); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_OType = GPIO_OType_OD; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_Init(GPIOF, &GPIO_InitStructure); EXTI_InitStructure.EXTI_Line = EXTI_Line0; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = PUSH_WHEEL_INT_NVIC; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } void GPIOF_Exti1_GPIO_Init(void) // 拨轮弹仓内限位开关 { NVIC_InitTypeDef NVIC_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOF, EXTI_PinSource1); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_OType = GPIO_OType_OD; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_Init(GPIOF, &GPIO_InitStructure); EXTI_InitStructure.EXTI_Line = EXTI_Line1; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); NVIC_InitStructure.NVIC_IRQChannel = EXTI1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = TRIGGER_WHEEL_INT_NVIC; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } void EXTI0_IRQHandler(void) //拨轮弹舱限位开关 { if(EXTI_GetITStatus(EXTI_Line0)!=RESET) { EXTI_ClearITPendingBit(EXTI_Line0); trigger_switch_in_PushWheel_detected(); } } void EXTI1_IRQHandler(void) //拨叉二级弹舱限位开关 { if(EXTI_GetITStatus(EXTI_Line1)!=RESET) { EXTI_ClearITPendingBit(EXTI_Line1); trigger_switch_in_ShootWheel_detected(); } }<file_sep>#include "delay.h" #include "led.h" #include "stm32f4xx.h" static uint8_t fac_us = 0; static uint32_t fac_ms = 0; u32 systime_ms; volatile uint32_t sysTickUptime = 0; void delay_init(uint32_t TICK_RATE_HZ) { uint32_t reload = 0; SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8); // 180/8=22.5mhz fac_us = SystemCoreClock / 8000000; // 180mhz/8mhz =22.5mhz fac_ms = SystemCoreClock / 8000; if (TICK_RATE_HZ == 0) { TICK_RATE_HZ = 1000; } reload = SystemCoreClock / TICK_RATE_HZ / 8; // 180mhz/8/1000 = 22500 reload--; SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk; SysTick->LOAD = reload; SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; } void delay_us(uint16_t nus) { uint32_t ticks = 0; uint32_t told = 0; uint32_t tnow = 0; uint32_t tcnt = 0; uint32_t reload = 0; reload = SysTick->LOAD; ticks = nus * fac_us; told = SysTick->VAL; while (1) { tnow = SysTick->VAL; if (tnow != told) { if (tnow < told) { tcnt += told - tnow; } else { tcnt += reload - tnow + told; } told = tnow; if (tcnt >= ticks) { break; } } } } void delay_ms(uint16_t nms) { uint32_t ticks = 0; uint32_t told = 0; uint32_t tnow = 0; uint32_t tcnt = 0; uint32_t reload = 0; reload = SysTick->LOAD; ticks = nms * fac_ms; told = SysTick->VAL; while (1) { tnow = SysTick->VAL; if (tnow != told) { if (tnow < told) { tcnt += told - tnow; } else { tcnt += reload - tnow + told; } told = tnow; if (tcnt >= ticks) { break; } } } } void sys_time() { systime_ms++; } uint32_t SysTick_GetTick(void) { return systime_ms; } uint32_t GetSysTime_us ( void ) { register uint32_t ms; u32 value; do { ms = sysTickUptime; value = ms * TICK_US + ( SysTick->LOAD - SysTick->VAL ) * TICK_US / SysTick->LOAD; } while(ms != sysTickUptime); return value; } void SysTick_Handler(void) { sysTickUptime++; sys_time(); //sys_time(); //systime_ms±äÁ¿Ã¿1msÀÛ¼Ó1 //LED_1ms_DRV(); flow_led_Combo1(); } <file_sep>#ifndef __USART6_H__ #define __USART6_H__ #include "main.h" #include <stm32f4xx.h> #define USART_REC_LEN 8 //定义最大接收字节数 200 #define EN_USART6_RX 1 //使能(1)/禁止(0)串口1接收 #define UART6_Waiting 0 #define UART6_Receiving 1 #define UART6_Success 2 #define UART6_Failed 3 void Referee_USART6_Configuration(u32 bound); void USART6_DMA_Init(uint8_t *rx1_buf, uint8_t *rx2_buf, uint16_t dma_buf_num); #endif <file_sep>#include "trigger_switch.h" trigger_switch_t trigger_switch_in_PushWheel; //拨轮处的限位开关 trigger_switch_t trigger_switch_in_ShootWheel; //拨叉处的限位开关 void trigger_switch_init(void) { trigger_switch_in_PushWheel.trigger_state = 0; trigger_switch_in_ShootWheel.trigger_state = 0; } trigger_switch_t *get_switch_point( trigger_switch_list object ) { if(object == PushWheel) return &trigger_switch_in_PushWheel; if(object == ShootWheel) return &trigger_switch_in_ShootWheel; } void trigger_switch_in_PushWheel_detected(void) { trigger_switch_in_PushWheel.trigger_state = 1; } void trigger_switch_in_ShootWheel_detected(void) { trigger_switch_in_ShootWheel.trigger_state = 1; } void trigger_switch_StateDelete( trigger_switch_list object ) { if(object == PushWheel) trigger_switch_in_PushWheel.trigger_state = 0; if(object == ShootWheel) trigger_switch_in_ShootWheel.trigger_state = 0; } <file_sep>/** ****************************(C) COPYRIGHT 2016 DJI**************************** * @file shoot.c/h * @brief 射击功能,其中射击的初始化,以及循环都是在云台任务中调用,故而此文件 * 不是freeRTOS任务,射击分关闭状态,准备状态,射击状态,以及完成状态 * 关闭状态是关闭摩擦轮以及激光,准备状态是将子弹拨到微型开关处,射击状 * 态是将子弹射出,判断微型开关值,进入完成状态,完成状态通过判断一定时间 * 微型开关无子弹认为已经将子弹射出。 * @note * @history * Version Date Author Modification * V1.0.0 Dec-26-2018 RM 1. 完成 * @verbatim ============================================================================== ============================================================================== @endverbatim ****************************(C) COPYRIGHT 2016 DJI**************************** */ #ifndef SHOOT_H #define SHOOT_H #include "main.h" #include "push_motor.h" #include "CAN_Receive.h" #include "remote_control.h" #include "user_lib.h" #include "Gimbal_Task.h" #include "trigger_switch.h" #define SHOOT_MOTOR_TURN 1 //0代表正装 1代表反装 #define PUSH_MOTOR_TURN 0 //射击发射开关通道数据 #define Shoot_RC_Channel 1 //云台模式使用的开关通道 #define GIMBAL_ModeChannel 1 #define SHOOT_CONTROL_TIME 1 //1ms控制周期 #define SHOOT_FRIC_PWM_ADD_VALUE 200.0f //射击摩擦轮激光打开 关闭 #define SHOOT_ON_KEYBOARD KEY_PRESSED_OFFSET_Q #define SHOOT_OFF_KEYBOARD KEY_PRESSED_OFFSET_E //射击完成后 子弹弹出去后,判断时间,以防误触发 #define SHOOT_DONE_KEY_OFF_TIME 10 //鼠标长按判断 #define PRESS_LONG_TIME 400 //遥控器射击开关打下档一段时间后 连续发射子弹 用于清单 #define RC_S_LONG_TIME 2000 //摩擦轮高速 加速 时间 #define UP_ADD_TIME 80 //电机反馈码盘值范围 #define Half_ecd_range 4096 #define ecd_range 8191 //2006电机rmp 变化成 旋转速度的比例 #define Motor_RMP_TO_SPEED 0.00290888208665721596153948461415f #define Motor_ECD_TO_ANGLE 0.000021305288720633905968306772076277f // 对于2006 传动比为36 那么该系数 =(10度/8191) *(PI/180) #define FULL_COUNT 18 //拨叉速度 #define SHOOT_SPEED 5.0f #define Ready_Trigger_Speed 6.0f //6020电机RPM 变化成 旋转速度的比例 #define PUSH_Motor_RMP_TO_SPEED -0.1047f // 传动比为1 因此1*2*PI/60 //拨轮速度 #define PUSH_SPEED -10.0f //单位rad/s #define KEY_OFF_JUGUE_TIME 500 #define SWITCH_TRIGGER_ON 0 #define SWITCH_TRIGGER_OFF 1 //卡单时间 以及反转时间 #define BLOCK_TIME 700 #define REVERSE_TIME 500 #define REVERSE_SPEED_LIMIT 13.0f #define PI_TWO 1.5707963267948966192313216916398f #define PI_Four 0.78539816339744830961566084581988f #define PI_Ten 0.314f //拨弹轮电机PID #define SHOOT_SPEED_PID_KP 800.0f #define SHOOT_SPEED_PID_KI 0.5f #define SHOOT_SPEED_PID_KD 0.0f #define TRIGGER_BULLET_PID_MAX_OUT 15000.0f #define TRIGGER_BULLET_PID_MAX_IOUT 5000.0f #define SHOOT_SPEED_PID_MAX_OUT 5000.0f #define SHOOT_SPEED_PID_MAX_IOUT 2500.0f #define PUSH_SPEED_PID_KP 1000.0f #define PUSH_SPEED_PID_KI 0.0f #define PUSH_SPEED_PID_KD 0.0f #define PUSH_SPEED_PID_MAX_OUT 5000.0f #define PUSH_SPEED_PID_MAX_IOUT 2500.0f /* TODO1 完善结构体*/ typedef enum { SHOOT_STOP = 0, SHOOT_WAITING, AMMO_OUT, SHOOT_INIT, SHOOT_READY, SHOOTING, SHOOT_JAMMED, SHOOT_DONE, } shoot_system_motor_mode_e; typedef struct { const motor_measure_t *motor_measure; shoot_system_motor_mode_e mode; shoot_system_motor_mode_e last_mode; bool_t move_flag; fp32 shoot_count_flag; fp32 speed; fp32 speed_set; fp32 angle; fp32 set_angle; int16_t given_current; int8_t ecd_count; } Shoot_System_Shoot_Motor_t; typedef struct { shoot_system_motor_mode_e mode; shoot_system_motor_mode_e last_mode; bool_t move_flag; //fp32 angle; //fp32 set_angle; } Shoot_System_Push_Wheel_t; typedef struct { bool_t mode; // 0或1 是否能作用于发射 bool_t press_l; bool_t press_r; bool_t last_press_l; bool_t last_press_r; uint16_t press_l_time; uint16_t press_r_time; uint16_t rc_s_time; } Mouse_t; typedef struct { const RC_ctrl_t *shoot_rc_ctrl; //遥控器指针 ramp_function_source_t fric1_ramp;//摩擦轮斜波 ramp_function_source_t fric2_ramp; Shoot_System_Shoot_Motor_t shoot_motor; //拨叉 Shoot_System_Push_Wheel_t push_wheel_motor; //波轮 Mouse_t mouse; //鼠标 u32 sys_time; //系统时间T trigger_switch_t *PushTrigger; trigger_switch_t *ShootTrigger; bool_t shoot_done_flag; // bool_t move_flag; // uint32_t cmd_time; // uint32_t run_time; // bool_t key; // uint16_t key_time; // bool_t shoot_done; // uint8_t shoot_done_time; // int16_t BulletShootCnt; // int16_t last_butter_count; } Shoot_System_t; extern void shoot_init(void); extern int16_t shoot_control_loop(void); #endif <file_sep>#include "fric.h" #include "stm32f4xx.h" //摩擦轮电机PWM初始化 TIM8 CH3 CH4 PI7 PI2 void fric_PWM_configuration(void) // { GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; TIM_OCInitTypeDef TIM_OCInitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM8,ENABLE); //TIM8时钟 RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOI, ENABLE); //GPIOI时钟 //// PI5初始化 // GPIO_PinAFConfig(GPIOI,GPIO_PinSource5,GPIO_AF_TIM8); //PI5复用为TIM8外设输出 // GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; // GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; // GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; // GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; // GPIO_Init(GPIOI,&GPIO_InitStructure); // //// PI6初始化 // GPIO_PinAFConfig(GPIOI,GPIO_PinSource6,GPIO_AF_TIM8); // GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; // GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; // GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; // GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; // GPIO_Init(GPIOI,&GPIO_InitStructure); // PI7初始化 GPIO_PinAFConfig(GPIOI,GPIO_PinSource7,GPIO_AF_TIM8); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOI,&GPIO_InitStructure); // PI2初始化 GPIO_PinAFConfig(GPIOI,GPIO_PinSource2,GPIO_AF_TIM8); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOI,&GPIO_InitStructure); // RCC_APB2PeriphResetCmd(RCC_APB2Periph_TIM8, ENABLE); // RCC_APB2PeriphResetCmd(RCC_APB2Periph_TIM8, DISABLE); // /* ---------------- PWM信号 周期和占空比的计算--------------- */ // ARR :自动重装载寄存器的值 // CLK_cnt:计数器的时钟,等于 Fck_int / (psc+1) = 72M/(psc+1) // PWM 信号的周期 T = ARR * (1/CLK_cnt) = ARR*(PSC+1) / 72M // 占空比P=CCR/(ARR+1) // 若Period = 19,则+1得20,计一次数的周期为1/CLK_CNT = 71+1/72000000 = 0.000001s,则PWM周期为20x0.000001s=0.00002s=20us=50000HZ=50KHZ //180000 19 // TIM_TimeBase初始化 TIM_TimeBaseInitStructure.TIM_Period = 2000 - 1; TIM_TimeBaseInitStructure.TIM_Prescaler = 180 - 1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInit(TIM8, &TIM_TimeBaseInitStructure); // TIM_OC初始化 TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Disable; TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low; TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set; TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset; TIM_OCInitStructure.TIM_Pulse = 1000; // TIM_OC1Init(TIM8, &TIM_OCInitStructure); // TIM_OC1PreloadConfig(TIM8, TIM_OCPreload_Enable); //????????? // // TIM_OC2Init(TIM8, &TIM_OCInitStructure); // TIM_OC2PreloadConfig(TIM8, TIM_OCPreload_Enable); //????????? TIM_OC3Init(TIM8, &TIM_OCInitStructure); TIM_OC3PreloadConfig(TIM8, TIM_OCPreload_Enable); //????????? TIM_OC4Init(TIM8, &TIM_OCInitStructure); TIM_OC4PreloadConfig(TIM8, TIM_OCPreload_Enable); //????????? TIM_ARRPreloadConfig(TIM8, ENABLE); TIM_CtrlPWMOutputs(TIM8, ENABLE); TIM_Cmd(TIM8, ENABLE); //fric_off(); // RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE); // GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; // GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; // GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; // GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; // GPIO_Init(GPIOF, &GPIO_InitStructure); // GPIO_SetBits(GPIOF, GPIO_Pin_10); } void fric_off(void) { TIM_SetCompare3(TIM8, Fric_OFF); TIM_SetCompare4(TIM8, Fric_OFF); } void fric1_on(uint16_t cmd) { TIM_SetCompare3(TIM8, cmd); } void fric2_on(uint16_t cmd) { TIM_SetCompare4(TIM8, cmd); } <file_sep>#ifndef EXIT_INIT_H #define EXIT_INIT_H #include "main.h" extern void GPIOB_Exti8_GPIO_Init(void); extern void GPIOF_Exti0_GPIO_Init(void); extern void GPIOF_Exti1_GPIO_Init(void); #endif <file_sep>#include "referee_API.h" extern ext_game_robot_state_t robot_state; //0x0201 extern ext_power_heat_data_t power_heat_data_t; //0x0202 void get_chassis_power_and_buffer(fp32 *power, fp32 *buffer) { *power = power_heat_data_t.chassis_power; *buffer = power_heat_data_t.chassis_power_buffer; } const ext_power_heat_data_t *get_power_heat_data_Point(void) { return &power_heat_data_t; } const ext_game_robot_state_t *get_robot_state_data_Point(void) { return &robot_state; } uint8_t get_robot_id(void) { return robot_state.robot_id; } void get_shoot_heat0_limit_and_heat0(uint16_t *heat0_limit, uint16_t *heat0) { *heat0_limit = robot_state.shooter_heat0_cooling_limit; *heat0 = power_heat_data_t.shooter_heat0; } void get_shoot_heat1_limit_and_heat1(uint16_t *heat1_limit, uint16_t *heat1) { *heat1_limit = robot_state.shooter_heat1_cooling_limit; *heat1 = power_heat_data_t.shooter_heat1; } //²âÊÔ
bb926827651ed3b08b7552b5f9776fe320b72ae6
[ "Markdown", "C" ]
52
C
13651924886/2020SUES_BDT-Hero
c278bb39a3511792f51b5669c3f8deeae4628afe
45364098c594b240d36cf830c727bc72ccd05c11
refs/heads/master
<file_sep>import React, { useState, useContext } from "react"; import "../../styles/index.scss"; import { Link } from "react-router-dom"; import { Card, ButtonToolbar, CardGroup, Button } from "react-bootstrap"; import PropTypes from "prop-types"; import { Context } from "../store/appContext"; export const Planets = props => { const { store, actions } = useContext(Context); const [searchItem, setSearch] = useState(); return ( <div className="container d-flex flex-column text-center"> <div className="Main mt-5 d-flex" style={{ overflowX: "scroll", width: "1100px", height: "550px" }}> {props.info.map((element, index) => { return ( <Card style={{ minWidth: "20rem", margin: "15px" }} key={index}> <Card.Img variant="top h-50" src="https://static2.cbrimages.com/wordpress/wp-content/uploads/2020/07/star-wars-death-star-earth.jpg" /> <Card.Body> <Card.Title className="text-center">{element.name}</Card.Title> <Card.Text> <tr> <td>Population: {element.population}</td> </tr> <tr> <td>Gravity: {element.gravity}</td> </tr> <tr> <td>Terrain: {element.terrain}</td> </tr> </Card.Text> </Card.Body> <Card.Footer> <ButtonToolbar className="justify-content-between" aria-label="Toolbar with Button groups"> <Link to={`/descriptionPlanets/${index}`}> <Button variant="primary">Learn More</Button> </Link> <Link onClick={() => actions.addFavorite(element.name, "planet")}> <Button variant="outline-warning"> <i className="far fa-heart" /> </Button> </Link> </ButtonToolbar> </Card.Footer> </Card> ); })} </div> <div> <Link to="/"> <button className="btn btn-primary mt-4" style={{ top: "15" }}> Back home </button> </Link> </div> </div> ); }; Planets.propTypes = { info: PropTypes.any };
d95f8b761e777b299a0ade2c688e36606ad20ba8
[ "JavaScript" ]
1
JavaScript
YeiDiaz/Star-wars-Swapi
538a9753205277b4264251ec6f86c1052d19c351
fa030f4a6a24f164528a1962abbe496f95faa0ad
refs/heads/master
<file_sep>package sample; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; public class EditProduct { @FXML ComboBox comboProductID; @FXML ComboBox comboCategories; @FXML TextField txtIdValue; @FXML TextField txtNameValue; public String IDSearching; public String CategorySearching; public String oldID; public String categoryValue; public String product; public String category; public String proName; public String categoryname; public void initialize(){ //happen automatically, without calling ObservableList comboIDList = FXCollections.observableArrayList();//get all IDs in collection to the Combobox databaseInitialize.methodDatabaseInt(); DBCollection idSearch = databaseInitialize.inventoryDb.getCollection("Product_Collection"); DBCursor idsearching = idSearch.find(); for (DBObject count : idsearching) { IDSearching = (String) count.get("ProductID"); comboIDList.add(IDSearching); }comboProductID.setItems(comboIDList); ObservableList comboCategoryList = FXCollections.observableArrayList(); //get all categories in collection to the Combobox databaseInitialize.methodDatabaseInt(); DBCollection categorySearch = databaseInitialize.inventoryDb.getCollection("Category_Collection"); DBCursor categorySearching = categorySearch.find(); for (DBObject count : categorySearching) { CategorySearching = (String) count.get("CategoryName"); comboCategoryList.add(CategorySearching); }comboCategories.setItems(comboCategoryList); } public void clickBtnUpdate(){ oldID=(String) comboProductID.getValue(); categoryValue=(String) comboCategories.getValue(); String newID=txtIdValue.getText(); String newProductName=txtNameValue.getText(); newProductName=newProductName.toLowerCase(); Boolean productIDhere=true; if(oldID!="null"&&categoryValue!="null"&&!newID.equals("")&&!newProductName.equals("")){ if(newID.length()>5){ Alert idLengthError = new Alert(Alert.AlertType.NONE); idLengthError.setAlertType(Alert.AlertType.ERROR); idLengthError.setContentText("ERROR...Product ID must be 5 characters or less than 5 "); idLengthError.showAndWait(); }else{ databaseInitialize.methodDatabaseInt(); //ID DBCollection idSearch = databaseInitialize.inventoryDb.getCollection("Product_Collection"); DBCursor searchingID = idSearch.find(); for (DBObject count : searchingID) { IDSearching = (String) count.get("ProductID"); proName = (String) count.get("ProductName"); categoryname = (String) count.get("CategoryNAME"); if (newID.equals(IDSearching)) { productIDhere = false; break; } else { productIDhere = true; } } if (productIDhere) { BasicDBObject updatingProduct = new BasicDBObject(); updatingProduct.put("ProductID", oldID); updatingProduct.put("ProductName", proName); updatingProduct.put("CategoryNAME", categoryname); BasicDBObject updateValue = new BasicDBObject(); updateValue.put("ProductID", newID); updateValue.put("ProductName", newProductName); updateValue.put("CategoryNAME", categoryValue); BasicDBObject newValue = new BasicDBObject(); newValue.put("$set", updateValue); databaseInitialize.inventoryDb.getCollection("Product_Collection").update(updatingProduct, newValue); Alert successful = new Alert(Alert.AlertType.NONE); successful.setAlertType(Alert.AlertType.INFORMATION); successful.setContentText("Product Updated Successfully "); successful.showAndWait(); initialize(); } else { Alert IdAlreadyError = new Alert(Alert.AlertType.NONE); IdAlreadyError.setAlertType(Alert.AlertType.ERROR); IdAlreadyError.setContentText("Given Product ID is already in Database"); IdAlreadyError.showAndWait(); } } }else{ Alert nullError = new Alert(Alert.AlertType.NONE); nullError.setAlertType(Alert.AlertType.ERROR); nullError.setContentText("ERROR...Every fields must be filled and Selected"); nullError.showAndWait(); } } public void methodBack(){ Home.EditProductStage.close(); } } <file_sep>package sample; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.ComboBox; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import java.net.URL; import java.util.ResourceBundle; public class ViewStock <findIterable> implements Initializable { @FXML private TableView<ModelClassViewAllStock> stockTblView; @FXML public TableColumn<ModelClassViewAllStock,String> productIdTblColumn; @FXML public TableColumn<ModelClassViewAllStock,String> productAmountTblColumn; @FXML public TableColumn<ModelClassViewAllStock,String> unitTblColumn; public String IDSearching; @FXML ComboBox comboProductIDs; public String IDValue; @Override public void initialize(URL location, ResourceBundle resources) //happen automatically, without calling { productIdTblColumn.setCellValueFactory(new PropertyValueFactory<>("ProductID")); productAmountTblColumn.setCellValueFactory(new PropertyValueFactory<>("ProductAmount")); unitTblColumn.setCellValueFactory(new PropertyValueFactory<>("Unit")); ObservableList comboCategoryList= FXCollections.observableArrayList(); databaseInitialize.methodDatabaseInt(); DBCollection categorySearch=databaseInitialize.inventoryDb.getCollection("Stock_Collection"); DBCursor searching = categorySearch.find(); for(DBObject count : searching) { IDSearching=(String)count.get("ProductID"); comboCategoryList.add(IDSearching); } comboProductIDs.setItems(comboCategoryList); } public void displayInTable() { IDValue=(String) comboProductIDs.getValue(); if(IDValue!=null){ ObservableList<ModelClassViewAllStock> tableValueSet = FXCollections.observableArrayList(); databaseInitialize.methodDatabaseInt(); DBCollection Check = databaseInitialize.inventoryDb.getCollection("Stock_Collection"); DBCursor searching = Check.find(); for (DBObject count : searching) { if (IDValue.equals(searching)) { ModelClassViewAllStock values = new ModelClassViewAllStock(); values.setProductID((String) count.get(IDValue)); values.setProductAmount((String) count.get("ProductAmount")); values.setUnit((String) count.get("Unit")); tableValueSet.add(values); System.out.print(tableValueSet); break; }else{continue;} }stockTblView.setItems(tableValueSet); System.out.print(tableValueSet); }else{ Alert nullError = new Alert(Alert.AlertType.NONE); nullError.setAlertType(Alert.AlertType.ERROR); nullError.setContentText("ERROR...ID is not selected "); nullError.showAndWait(); } } public void methodBack(){ Home.ViewStockStage.close(); } } <file_sep>package sample; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.TextField; public class EditCategory { @FXML TextField txtExistingCategory; @FXML TextField txtNewCategory; public static String categorySearching; public void clickBtnUpdate() { String categoryExist = txtExistingCategory.getText(); categoryExist = categoryExist.toLowerCase(); String categoryUpdate=txtNewCategory.getText(); categoryUpdate=categoryUpdate.toLowerCase(); Boolean categoryhere = true; if (!categoryExist.equals("") && !categoryUpdate.equals("")) { databaseInitialize.methodDatabaseInt(); DBCollection categorySearch = databaseInitialize.inventoryDb.getCollection("Category_Collection"); DBCursor searching = categorySearch.find(); for (DBObject count : searching) { categorySearching = (String) count.get("CategoryName"); if (categoryExist.equals(categorySearching)) { categoryhere = false; break; }else{ categoryhere = true; } } if (categoryhere) { Alert alreadyExistsError = new Alert(Alert.AlertType.NONE); alreadyExistsError.setAlertType(Alert.AlertType.ERROR); alreadyExistsError.setContentText("Category doesn't Exists to update"); alreadyExistsError.showAndWait(); } else{ for (DBObject count : searching) { categorySearching = (String) count.get("CategoryName"); if (categoryUpdate.equals(categorySearching)) { categoryhere = false; break; }else{ categoryhere = true; } } if(categoryhere) { BasicDBObject updatingCategory = new BasicDBObject(); updatingCategory.put("CategoryName", categoryExist); BasicDBObject updateValue = new BasicDBObject(); updateValue.put("CategoryName", categoryUpdate); BasicDBObject newValue = new BasicDBObject(); newValue.put("$set",updateValue); databaseInitialize.inventoryDb.getCollection("Category_Collection").update(updatingCategory, newValue); Alert updateInfo = new Alert(Alert.AlertType.NONE); updateInfo.setAlertType(Alert.AlertType.INFORMATION); updateInfo.setContentText("Category updated Successfully"); updateInfo.showAndWait(); }else{ Alert alreadyError = new Alert(Alert.AlertType.NONE); alreadyError.setAlertType(Alert.AlertType.ERROR); alreadyError.setContentText(" Can't Update..New Value Already added as a Category"); alreadyError.showAndWait(); } } }else{ Alert nullError = new Alert(Alert.AlertType.NONE); nullError.setAlertType(Alert.AlertType.ERROR); nullError.setContentText("Category Exist field or Category Update field is empty"); nullError.showAndWait(); } } public void methodBack(){ Home.EditCategoryStage.close(); } } <file_sep>package sample; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.TextField; public class AddCategory { @FXML TextField txtCategory; public static String categorySearching; public void clickBtnAdd(){ Boolean categoryhere=true; String category=txtCategory.getText(); category=category.toLowerCase(); if(!category.equals("")){ databaseInitialize.methodDatabaseInt(); DBCollection categorySearch=databaseInitialize.inventoryDb.getCollection("Category_Collection"); DBCursor searching = categorySearch.find(); for(DBObject count : searching){ categorySearching=(String)count.get("CategoryName"); if(category.equals(categorySearching)){ categoryhere=false; }else{ categoryhere=true; } } if(!categoryhere){ Alert alreadyExistsError = new Alert(Alert.AlertType.NONE); alreadyExistsError.setAlertType(Alert.AlertType.ERROR); alreadyExistsError.setContentText("Category already Exists"); alreadyExistsError.showAndWait(); }else{ BasicDBObject categorytoAdd = new BasicDBObject(); categorytoAdd.put("CategoryName", category); databaseInitialize.methodDatabaseInt(); DBCollection collection = databaseInitialize.inventoryDb.getCollection("Category_Collection"); collection.insert(categorytoAdd); Alert successful = new Alert(Alert.AlertType.NONE); successful.setAlertType(Alert.AlertType.INFORMATION); successful.setContentText("Category added Successfully "); successful.showAndWait(); } }else{ Alert nullError = new Alert(Alert.AlertType.NONE); nullError.setAlertType(Alert.AlertType.ERROR); nullError.setContentText("Category field is empty"); nullError.showAndWait(); } } public void methodBack(){ Home.AddCategoryStage.close(); } }<file_sep>package sample; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; public class DeleteCategory { @FXML ComboBox comboCategories; public String silectedCategory; public static String categorySearching; public void initialize() { //happen automatically, without calling ObservableList comboCategoryList= FXCollections.observableArrayList(); databaseInitialize.methodDatabaseInt(); DBCollection categorySearch=databaseInitialize.inventoryDb.getCollection("Category_Collection"); DBCursor searching = categorySearch.find(); for(DBObject count : searching) { categorySearching=(String)count.get("CategoryName"); comboCategoryList.add(categorySearching); } comboCategories.setItems(comboCategoryList); } public void method1Delete(){ ////delete method by using dropbox silectedCategory=(String) comboCategories.getValue(); databaseInitialize.methodDatabaseInt(); DBCollection categorySearch = databaseInitialize.inventoryDb.getCollection("Category_Collection"); DBCursor searching = categorySearch.find(); BasicDBObject catogerytoDelete = new BasicDBObject(); catogerytoDelete.put("CategoryName", silectedCategory); categorySearch.findAndRemove(catogerytoDelete); Alert successful = new Alert(Alert.AlertType.NONE); successful.setAlertType(Alert.AlertType.INFORMATION); successful.setContentText("Category Deleted Successfully "); successful.showAndWait(); initialize(); } @FXML TextField txtDeleteCategory; @FXML public void method2Delete() //if you want type category and delete this method is also working { Boolean categoryhere = true; String categorytoDelete = txtDeleteCategory.getText(); categorytoDelete = categorytoDelete.toLowerCase(); if (!categorytoDelete.equals("")) { databaseInitialize.methodDatabaseInt(); DBCollection categorySearch = databaseInitialize.inventoryDb.getCollection("Category_Collection"); DBCursor searching = categorySearch.find(); for (DBObject count : searching) { categorySearching = (String) count.get("CategoryName"); if (categorytoDelete.equals(categorySearching)) { categoryhere = false; break; } else{ continue; } } if (!categoryhere) { BasicDBObject catogerytoDelete = new BasicDBObject(); catogerytoDelete.put("CategoryName", categorytoDelete); categorySearch.findAndRemove(catogerytoDelete); Alert successful = new Alert(Alert.AlertType.NONE); successful.setAlertType(Alert.AlertType.INFORMATION); successful.setContentText("Category Deleted Successfully "); successful.showAndWait(); } else { Alert alreadyExistsError = new Alert(Alert.AlertType.NONE); alreadyExistsError.setAlertType(Alert.AlertType.ERROR); alreadyExistsError.setContentText("Category not found in Database"); alreadyExistsError.showAndWait(); } } else{ Alert nullError = new Alert(Alert.AlertType.NONE); nullError.setAlertType(Alert.AlertType.ERROR); nullError.setContentText("Category field is empty"); nullError.showAndWait(); } } public void methodBack(){ Home.DeleteCategoryStage.close(); } } <file_sep>package sample; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import java.net.URL; import java.util.ResourceBundle; public class ViewCategory <findIterable> implements Initializable { @FXML private TableView<ModelClassCategory> categoryTblView; @FXML public TableColumn<ModelClassCategory,String> categoryTblColumn; @Override public void initialize(URL location, ResourceBundle resources) { categoryTblColumn.setCellValueFactory(new PropertyValueFactory<>("category")); displayInTable(); } public void displayInTable(){ ObservableList<ModelClassCategory> categoryList = FXCollections.observableArrayList(); databaseInitialize.methodDatabaseInt(); DBCollection categoryCheck = databaseInitialize.inventoryDb.getCollection("Category_Collection"); DBCursor searching = categoryCheck.find(); for (DBObject count : searching) { ModelClassCategory category = new ModelClassCategory ((String) count.get("CategoryName")); category.setCategory((String) count.get("CategoryName")); categoryList.add(category); } categoryTblView.setItems(categoryList); } public void methodBack(){ Home.ViewCategoryStage.close(); } }
81b0964ebb2c653c75336a5490f360ccf7bcce60
[ "Java" ]
6
Java
Saranga99/Java-FX-cw-01--Priyalal-Srores-
d4d6068ae5866bfffff1767ce431e6f2e82934ec
dbd48c1b4ed5883718ab75cc1339452868546f2d
refs/heads/master
<repo_name>huangtiancai/webgl-threejs-thingjs<file_sep>/threejs/2.初识Three.js/app.js // 声明全局变量 var scene, camera, geomerty, material, mesh, renderer, stats; // 调用 init(); animate(); // 初始化 function init() { // 实例化场景 scene = new THREE.Scene(); // 实例化相机 camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); // 移动相机位置 camera.position.set(0, 0, 3); // 创建模型 // width — X轴上面的宽度,默认值为1 // height — Y轴上面的高度,默认值为1 // depth — Z轴上面的深度,默认值为1 全部设置的相同的值,将渲染出一个标准的正立方体 geomerty = new THREE.BoxGeometry(1, 1, 1); // 创建几何体 material = new THREE.MeshNormalMaterial(); // 创建材质 // material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); mesh = new THREE.Mesh(geomerty, material); // 创建网格 => 创建一个网格(模型)需要两种对象:几何体和材质 // 将网格添加到场景 scene.add(mesh); // 实例化渲染器 renderer = new THREE.WebGLRenderer(); // 设置渲染器的尺寸(宽高) renderer.setSize(window.innerWidth, window.innerHeight); // 添加到dom document.body.appendChild(renderer.domElement); // 性能测框 // 实例化一个stats对象 stats = new Stats(); // 把对象内生成的dom添加到页面当中 document.body.appendChild(stats.dom); } // 运行动画 function animate() { // 循环调用函数 requestAnimationFrame(animate); // 使立方体动起来 mesh.rotation.x += 0.005; // 每帧网格模型的沿x轴旋转0.01弧度 mesh.rotation.y += 0.005; // 每帧网格模型的沿y轴旋转0.02弧度 // 更新性能插件 stats.update(); // 渲染器渲染:在循环调用的函数中,每一帧我们都让页面重新渲染相机拍摄下来的内容 renderer.render(scene, camera); } window.onresize = function () { // 设置渲染器宽高 renderer.setSize(window.innerWidth, window.innerHeight); // 设置相机的宽高比 camera.aspect = window.innerWidth / window.innerHeight; // 重新计算投影矩阵 camera.updateProjectionMatrix(); } <file_sep>/threejs/1Three.js-VideoTutorial/README.md 什么是WEBGL? WebGL (Web图形库) 是一种JavaScript API,用于在任何兼容的Web浏览器中呈现交互式3D和2D图形,而无需使用插件。 什么是Three.js? 1. Three.js是一款webGL框架,由于其易用性被广泛应用。Three.js在WebGL的api接口基础上,又进行的一层封装 2. 它是由居住在西班牙巴塞罗那的程序员<NAME>开发的 3. Three.js以简单、直观的方式封装了3D图形编程中常用的对象 4. Three.js在开发中使用了很多图形引擎的高级技巧,极大地提高了性能 5. 由于内置了很多常用对象和极易上手的工具,Three.js的功能也非常强大 6. Three.js还是完全开源的 WEBGL和Three.js的关系 1. WebGL原生的api是一种非常低级的接口,而且还需要一些数学和图形学的相关技术 => 入门难 2. Three.js将入门的门槛降低了整整的一大截,对WebGL进行封装,简化我们创建三维动画场景的过程 功能概述: 1. Three.js掩盖了3D渲染的细节:Three.js将WebGL原生API的细节抽象化,将3D场景拆解为网格、材质和光源(即它内置了图形编程常用的一些对象种类)。 2. 面向对象:开发者可以使用上层的JavaScript对象,而不是仅仅调用JavaScript函数。 3. 功能非常丰富:Three.js除了封装了WebGL原始API之外,Three.js还包含了许多实用的内置对象,可以方便地应用于游戏开发、动画制作、幻灯片制作、髙分辨率模型和一些特殊的视觉效果制作。 4. 速度很快:Three.js采用了3D图形最佳实践来保证在不失可用性的前提下,保持极高的性能。 5. 支持交互:WebGL本身并不提供拾取(picking)功能(即是否知道鼠标正处于某个物体上)。而Three.js则固化了拾取支持,这就使得你可以轻松为你的应用添加交互功能。 6. 包含数学库:Three.js拥有一个强大易用的数学库,你可以在其中进行矩阵、投影和矢量运算。 7. 内置文件格式支持:你可以使用流行的3D建模软件导出文本格式的文件,然后使用Three.js加载;也可以使用Three.js自己的JSON格式或二进制格式。 8. 扩展性很强:为Three.js添加新的特性或进行自定义优化是很容易的事情。如果你需要某个特殊的数据结构,那么只需要封装到Three.js即可。 9. 支持HTML5 canvas:Three.js不但支持WebGL,而且还支持使用Canvas2D、Css3D和SVG进行渲染。在未兼容WebGL的环境中可以回退到其它的解决方案 Three.js与其他库的对比: 随着WebGL的迅速发展,相关的WebGL库也丰富起来,接下来列出几个比较火的WebGL库: - Babylon.js - PlayCanvas - Cesium 总结: - Three.js在其库的扩展性,易用性以及功能方面有很好的优势 - 学习Three.js入门3D开发不但门槛低,而且学习曲线不会太陡,即使以后转向WebGL原生开发,也能通过Three.js学习到很多有用的知识 - 微信小游戏跳一跳也是在Three.js的基础上开发出来的。所以,Three.js是我们必须要学的WebGL框架 入门前准备 1. 浏览器兼容 Three.js可以使用WebGL在所有现代浏览器上渲染场景。对于旧版浏览器,尤其是Internet Explorer 10及更低版本,您可能需要回退到其他渲染器(CSS2DRenderer,CSS3DRenderer,SVGRenderer,CanvasRenderer) 2. 支持的浏览器版本 Google Chrome 9+,Firefox 4+,Opera 15+,Safari 5.1+,Internet Explorer 11和Microsoft Edge 使用three.js创建一个立方体的案例 首先引入了three.js的库文件,就和引入jq一样 1. 创建场景 2. 创建相机,并设置视野,显示的宽高比,近裁剪面,远裁剪面 3. 创建渲染器,并设置属性,放置到dom中 4. 创建一个立方体模型,并放入到场景 5. 设置相机的位置 6. 设置一个动画函数,并使用渲染器把场景和相机渲染出来,每秒60帧,显示出来,就变成了动画 通过模块来引入(Import via modules) 1. 通过npm来安装 Three.js目前已经作为一个npm模块来进行了发布,详情请参阅:npm(https://www.npmjs.com/package/three)。这意味着你只需运行"npm install three"就可以使你的项目包含three.js库。 2. ES6Module规范(必须在最开始引入)引入 或 CommonJS规范(NODE)引入 3. webpack编译打包,再引入 中文文档: http://wjceo.com/three.js/docs/#manual/zh/introduction/Creating-a-scene gitee参考: https://gitee.com/break_egg/Three.js-VideoTutorial 博客参考: https://www.wjceo.com/ https://blog.csdn.net/qq_30100043/article/details/74202841 https://blog.csdn.net/qq_30100043/article/details/82014971 http://www.yanhuangxueyuan.com/<file_sep>/threejs/3Scene场景及页面调试插件/app.js // 声明全局变量 var scene, camera, geomerty, material, mesh, renderer, stats, controls, gui; // 调用 init(); animate(); // 初始化 function init() { // 实例化场景 scene = new THREE.Scene(); // 实例化相机 camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); // 移动相机位置 camera.position.set(0, 0, 3); // 创建模型 // width — X轴上面的宽度,默认值为1 // height — Y轴上面的高度,默认值为1 // depth — Z轴上面的深度,默认值为1 全部设置的相同的值,将渲染出一个标准的正立方体 geomerty = new THREE.BoxGeometry(1, 1, 1); // 创建几何体 material = new THREE.MeshNormalMaterial(); // 创建材质 // material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); mesh = new THREE.Mesh(geomerty, material); // 创建网格 => 创建一个网格(模型)需要两种对象:几何体和材质 scene.add(mesh); // 将网格添加到场景 // 实例化渲染器 renderer = new THREE.WebGLRenderer(); // 设置渲染器的尺寸(宽高) renderer.setSize(window.innerWidth, window.innerHeight); // 添加到dom document.body.appendChild(renderer.domElement); // 性能测框 // 实例化一个stats对象 stats = new Stats(); // 把对象内生成的dom添加到页面当中 document.body.appendChild(stats.dom); // 使用dat.GUI实现页面调试 // 1.设置需要修该的数据/需要控制的数据(对象) controls = { positionX: 0, positionY: 0, positionZ: 0 }; // 2.实例化dat.GUI对象 gui = new dat.GUI(); // 1)生成一个输入框 // dat.GUI能够根据controls值的不同生成不同的操作方法 // 如果值的类型为字符串或者数字类型,则可以生成一个默认的输入框 // gui.add(controls, "positionX"); // gui.add(controls, "positionY"); // gui.add(controls, "positionZ"); // 2)生成一个checkbox // 如果controls的值是一个布尔类型的,使用gui.add()方法就可以生成一个复选框 // true:勾选;false:不勾选 // gui.add(controls, "positionX"); // gui.add(controls, "positionY"); // gui.add(controls, "positionZ"); // 3)生成一个可以滑动的滑块 // 使用gui.add()方法如果值为数字类型传入第三个值(最小值)和第四个值(最大值) => 限制了值的能够取值的范围,就能够生成可以滑动的滑块 // gui.add(controls, "positionX", -1, 1); //设置了最小值和最大值,可以生成滑块 // gui.add(controls, "positionY").max(1); //只设置了最大值,无法生成滑块 // gui.add(controls, "positionZ").min(-1); //只设置了最小值,也无法生成滑块 // 4)通过step()方法来限制每次变化的最小值,也就是你增加或者减少,必须都是这个值的倍数 // gui.add(controls, "positionX", -10, 10).step(1); // 限制必须为整数 // gui.add(controls, "positionY", -10, 10).step(0.1); // 每次变化都是0.1的倍数 // gui.add(controls, "positionZ", -10, 10).step(10); // 每次变化都是10的倍数 // 5)生成一个下拉框 // 在gui.add()的第三个值传入一个对象或者数组,dat.GUI就能够自动匹配生成一个下拉框 // gui.add(controls, "positionX", ["left", "middle", "right"]); // 字符串类型的下拉框 // gui.add(controls, "positionX", ["true", "false"]); // 布尔值类型的下拉框 // gui.add(controls, "positionY", { "left": -10, "middle": 0, "right": 10 }); // 数字类型的下拉框 // 6)生成一个点击事件按钮 // 如果controls的值为一个函数function,dat.GUI会自动生成一个可以点击的按钮,当按下时就会触发这个函数事件 // controls = { // positionX: function () { }, // positionY: function () { }, // positionZ: function () { } // }; // gui.add(controls, "positionX"); // gui.add(controls, "positionY"); // gui.add(controls, "positionZ"); // 7) 修改显示的名称:使用name()事件进行设置显示的名称 // gui.add(controls, "positionX", -1, 1).name("x轴"); // gui.add(controls, "positionX", -1, 1).name("y轴"); // gui.add(controls, "positionX", -1, 1).name("Z轴"); // 8) 颜色选择框 // 实现颜色选择框首先需要值为一种正常的格式,比如css的颜色样式或者RGB格式 // 然后再使用gui.addColor()的方法添加 // controls = { // positionX: '#cccccc', // css样式 // positionY: [0, 255, 255], // RGB格式 // positionZ: [0, 255, 255, 0.6] // RGBA格式 // }; // gui.addColor(controls, "positionX").name("x轴"); // gui.addColor(controls, "positionY").name("y轴"); // gui.addColor(controls, "positionZ").name("z轴"); // 9)监听事件回调 // dat.GUI给我们提供了监听事件回调的方法onChange(),如果值变化就能够触发函数回调 // 将需要修改的配置添加对象中,并监听变化回调 // gui.add(controls, "positionX", -1, 1).onChange(updatePosition).name("x轴"); // gui.add(controls, "positionY", -1, 1).onChange(updatePosition).name("y轴"); // gui.add(controls, "positionZ", -1, 1).onChange(updatePosition).name("z轴"); // 每次都修改对象里面的值以后,都会触发updatePosition回调 => 来更新模型的位置 // function updatePosition() { // mesh.position.set(controls.positionX, controls.positionY, controls.positionZ); // } // 创建分组 // 使用gui.addFolder()方法来创建分组 var first = gui.addFolder("第一个分组"); first.add(controls, "positionX", -1, 1).onChange(updatePosition).name("x轴"); var second = gui.addFolder("第二个分组"); second.add(controls, "positionY", -1, 1).onChange(updatePosition).name("y轴"); second.add(controls, "positionZ", -1, 1).onChange(updatePosition).name("y轴"); function updatePosition() { mesh.position.set(controls.positionX, controls.positionY, controls.positionZ); } } // 运行动画 function animate() { // 循环调用函数 requestAnimationFrame(animate); // 使立方体动起来 mesh.rotation.x += 0.005; // 每帧网格模型的沿x轴旋转0.01弧度 mesh.rotation.y += 0.005; // 每帧网格模型的沿y轴旋转0.02弧度 // 更新性能插件 stats.update(); // 渲染器渲染:在循环调用的函数中,每一帧我们都让页面重新渲染相机拍摄下来的内容 renderer.render(scene, camera); } // 控制浏览器窗口尺寸 window.onresize = function () { // 设置渲染器宽高 renderer.setSize(window.innerWidth, window.innerHeight); // 设置相机的宽高比 camera.aspect = window.innerWidth / window.innerHeight; // 重新计算投影矩阵 camera.updateProjectionMatrix(); } // 测试调用 test(); // 测试 function test() { // 判断一个对象是否是继承至THREE.Object3D 继承返回 true 否则返回false // scene,camera,geomerty,mesh => 继承 // material,renderer,stats => 不继承 console.log(mesh instanceof THREE.Object3D); // 获取一个3d对象 // console.log(scene.getObjectById(1)); //返回id值为1的3d对象 ??? // 隐藏一个3d对象 // mesh.visible = false; // 设置为false,模型将不会被渲染到场景内 // 彻底删除一个3d对象 // scene.remove(mesh); // 获取到所有的子类 => 每一个3d对象都有一个children属性,这是一个数组,里面包含所有添加的3d对象 // console.log(scene.children); // Array // 获取3d对象下面所有的3d对象 // .traverse ( callback : Function ) // scene.traverse(function (child) { // // 打印 scene及scene对象下所有的3d对象 // // console.log(child); // }) // 获取3d对象的父元素 // console.log(mesh.parent); // scene // console.log(mesh.parent == scene); // true // 修改3d对象的位置,大小和转向:position、scale、rotation // 1.修改位置方式 // 通过设置模型的position属性进行修改模型的当前位置,具体方法有以下几种: // 1)单独设置每个方向的属性 // mesh.position.x = 3; // 将模型的位置调整到x正轴距离原点为3的位置 // mesh.position.y += 5; // 将模型的y轴位置以当前的位置向上移动5个单位 // mesh.position.z -= 6; // 2)直接一次性设置所有的 // mesh.position.set(3, 5, -6); // //直接将模型的位置设置在x轴为3,y轴为5,z轴为-6的位置 // 3)Three.js的模型的位置属性是一个THREE.Vector3(三维向量)的对象,可以直接重新赋值一个新的对象 // mesh.position = new THREE.Vector3(3, 5, -6); // ??? // 2.修改大小的方式 // 1) 第一种方式是单独设置每个方向的缩放 // mesh.scale.x = 2; // 模型沿x轴放大一倍 // mesh.scale.y = 0.5; // 模型沿y轴缩小一倍 // mesh.scale.z = 1; //模型沿z轴保持不变 // 2) 第二种是使用set方法 // mesh.scale.set(2, 0.5, 1); // 3) 第三种方式,由于scale属性也是一个三维向量,我们可以通过赋值的方式重新修改 // // mesh.scale = new THREE.Vector3(2, 2, 2); // ?? // 3.修改模型的转向(弧度) // Math.PI 表示一个圆的周长与直径的比例,约为 3.14159 // Math.PI=π≈3.14159 // 1)第一种方式是单独设置每个轴的旋转 // mesh.rotation.x = Math.PI; // 模型沿x旋转180度 // mesh.rotation.y = Math.PI * 2; // 模型沿y轴旋转360度,跟没旋转一样的效果 // mesh.rotation.z = -Math.PI / 2; // 模型沿z轴逆时针旋转90度 // 2)第二种方式就是使用set方法重新赋值 // mesh.rotation.set(Math.PI, 0, -Math.PI / 2); // 旋转效果和第一种显示的效果相同 // 正常模型的旋转方式是按照XYZ依次旋转的,如果想先旋转其他轴,我们可以添加第四项修改:可能为:YZX,ZXY,XZY,YXZ'和 ZYX // mesh.rotation.set(Math.PI, 0, -Math.PI / 2, 'ZYX'); // 3) 第三种方式,模型的rotation属性其实是一个欧拉角对象(THREE.Euler),可以以通过重新赋值一个欧拉角对象来实现旋转调整 // mesh.rotation = new THREE.Euler(Math.PI, 0, -Math.PI / 2, 'ZYX'); }<file_sep>/threejs/1Three.js-VideoTutorial/2npm/src/index-entry.js // 浏览器不能识别ES6Module/CommonJS模块导入导出规范的代码 => 必须编译 // ES6Module规范(必须在最开始引入)引入 import * as THREE from 'three'; // CommonJS规范(NODE)引入 // var THREE = require('three'); // 只导入three.js库中的特定部分,例如Scene // import { Scene } from 'three'; // 场景scene var scene = new THREE.Scene(); // 相机 // three.js里有几种不同的相机,这里使用的是PerspectiveCamera(透视摄像机) Perspective - 透视 // 第一个参数是视野角度(FOV) // 第二个参数是长宽比(aspect ratio) // 第三个参数是近截面(near) // 第四个参数是远截面(far) var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); // 渲染器 // Three.js同时提供了其他几种渲染器,当用户所使用的浏览器过于老旧,或者由于其他原因不支持WebGL时,可以使用这几种渲染器进行降级 var renderer = new THREE.WebGLRenderer(); // 设置渲染器的尺寸 // 渲染器渲染出的场景填充满我们的应用程序 => 因此,我们可以将渲染器宽高设置为浏览器窗口宽高 renderer.setSize(window.innerWidth, window.innerHeight); // 对于性能比较敏感的应用程序来说,你可以使用setSize传入一个较小的值,例如window.innerWidth/2和window.innerHeight/2,这将使得应用程序在渲染时,以一半的长宽尺寸渲染场景 // renderer.setSize(window.innerWidth / 2, window.innerHeight / 2); // 保持你的应用程序的尺寸,但是以较低的分辨率来渲染,你可以在调用setSize时,将updateStyle(第三个参数)设为false // 前提<canvas> 标签现在已经具有了100%的宽和高 // 下面的渲染器将使得你的应用程序以一半的分辨率来进行渲染。 // renderer.setSize(window.innerWidth / 2, window.innerHeight / 2, false); // 将renderer(渲染器)的dom元素(renderer.domElement)添加到我们的HTML文档中 // 这就是渲染器用来显示场景给我们看的<canvas>元素 document.body.appendChild(renderer.domElement); // 创建一个立方体 // 创建一个立方体,需要一个BoxGeometry(立方体)对象 => 这个对象包含了一个立方体中所有的顶点(vertices)和面(faces) // Geometry:几何 // var geometry = new THREE.BoxGeometry(1, 1, 1); // 材质 => 颜色 // Mesh:网格; Material:材料、材质 // 这里设置绿色 var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); // Mesh(网格) // 网格包含一个几何体以及作用在此几何体上的材质 var cube = new THREE.Mesh(geometry, material); // 将网格对象放入到我们的场景中,并让它在场景中自由移动 scene.add(cube); // 默认情况下,当我们调用scene.add()的时候,物体将会被添加到(0,0,0)坐标 // 但将使得摄像机和立方体彼此在一起,为了防止这种情况的发生,只需要将摄像机稍微向外移动一些即可 camera.position.z = 3; // 2.渲染场景 // 渲染循环”(render loop)或者“动画循环”(animate loop) // 这里创建了一个使渲染器能够在每次屏幕刷新时对场景进行绘制的循环(在大多数屏幕上,刷新率一般是60次/秒) function animate() { // setInterval 也可以实现刷新,但是要指定时间 // requestAnimationFrame 优点: // 1.不需要指定时间,默认60次 / 秒执行一次回调函数 // 2.当用户切换到其它的标签页时,它会暂停,因此不会浪费用户宝贵的处理器资源,也不会损耗电池的使用寿命 requestAnimationFrame(animate); // 使立方体动起来 // 这段代码每帧都会执行(正常情况下是60次/秒) cube.rotation.x += 0.01; cube.rotation.y += 0.01; // 使用渲染器渲染 renderer.render(scene, camera); } // 调用 animate(); // 1.位置随浏览器窗口变化而变化 // 2.不随滚轮滚动放大或缩小 // 将函数赋予window.onresize window.onresize = function () { // 设置渲染器宽高 renderer.setSize(window.innerWidth, window.innerHeight); // 设置相机的宽高比 camera.aspect = window.innerWidth / window.innerHeight; // 重新计算投影矩阵 camera.updateProjectionMatrix(); } // 注意: // 1.渲染器最后渲染出来的是<canvas>元素 // 2.每次操作都要渲染一次(每次场景、相机改变或者想要移动都要重新渲染) // 将执行移动的代码加入“动画循环”循环函数中 => 每次执行“移动代码” 都会重新渲染 => 避免重复的代码 // 3.本机电脑刷新频率(Hz) 60Hz 60次/秒 => 1/60秒刷新一次 // 帧率fps 由显卡的性能来决定 // 刷新率Hz 由显示器的物理条件<file_sep>/threejs/4Geometry几何体/README.md 前面代码案例是立方体 => 更多的几何体形状 THree.js内置几何体种类:立方体、三棱锥、球、八面体、十二面体、二十面体等等 模型 = 几何体Geometry + 材质material 1. Geometry和BufferGeometry BufferGeometry - 性能高,一般不需要额外操作 Geometry - 易于阅读和编辑,但效率低于BufferGeometry使用的类型化数组 BufferGeometry - 中大型的项目 Geometry - 小项目 这里使用作为简单的Geometry来实现案例: Geometry:是对 BufferGeometry 的用户有好替代。Geometry 利用 Vector3 或 Color 存储了几何体的相关 attributes(如顶点位置,面信息,颜色等)比起 BufferGeometry 更容易读写,但是运行效率不如有类型的队列 2. Geometry和BufferGeometry互转 BufferGeometry => Geometry ```javascript // 实例化一个Geometry对象 Geometry geo = new THREE.Geometry(); // 调用对象的fromBufferGeometry方法,并将需要转换的bufferGeometry传入 geo.fromBufferGeometry(bufferGeometry); // => geo则为转换成的Geometry ``` Geometry => BufferGeometry ```javascript // 实例化一个BufferGeometry对象 BufferGeometry buf = new THREE.BufferGeometry(); // 调用对象的fromGeometry方法,并将需要转换的geometry传入 buf.fromGeometry(geometry); // buf则为转换成的的BufferGeometry ``` Three.js内置几何体 1. BoxGeometry 立方体 构造函数: BoxGeometry( width : 浮点类型, height : 浮点类型, depth : 浮点类型, widthSegments : 整数类型, heightSegments : 整数类型, depthSegment: 整数类型) 2. <file_sep>/threejs/3Scene场景及页面调试插件/README.md 使用dat.GUI实现页面调试 如需要调整场景内模型位置或者大小可以常用的插件dat.GUI 使用插件之前学习一些必要的知识点 1. 场景 - 放置项目内容的容器 - 可以拥有多个场景进行切换展示 - 可以在场景内放置你的模型,灯光和照相机 - 可以通过调整场景的位置,让场景内的所有内容都一起跟着调整位置 ... 2. 场景的结构 - javascript => 操作dom => dom的结构都是树形结构 => Three.js遵循这个的理念 => 将所有可以添加到场景内的结构梳理成了一种树形的结构,方便我们能够更好的理解Three.js - 场景scene类比如一个body => body内可以添加dom对象 => scene内也可以添加它的3d对象 => 嵌套 在Three.js中,为了方便操作,将所有`3d对象`共同的内容抽象成了一个`基类`,就是`THREE.Object3D` ... 3. 使用dat.GUI插件实现页面调试 目前共使用两款插件: - stats - dat.gui 将插件的源码引入到页面当中,cdn 或 直接引入js ```javascript <script src="../build/three.js"></script> <script src="../build/stats.min.js"></script> <script src="../build/dat.gui.min.js"></script> ``` 在浏览器中使用ES module ```javascript <script type="module"> import * as THREE from '../build/three.module.js'; import Stats from '../build/stats.module.js'; import { GUI } from '../build/dat.gui.module.js'; // JS代码 </script> ``` stats、 dat.gui两款插件具体使用 => [index](./index.html) <file_sep>/Canvas/README.md HTML元素参考:<canvas> https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/canvas Web API 接口参考Canvas: https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API Web API 接口参考CanvasCanvas教程: https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial 其他的Web APIs: WebGL:用于渲染交互式3D图形的API. https://developer.mozilla.org/zh-CN/docs/Web/API/WebGL_API SVG:可缩放矢量图形(简称SVG)允许你使用矢量线,矢量图形,确保无论图片大小都可以比例平滑地显示. https://developer.mozilla.org/zh-CN/docs/Web/SVG ...<file_sep>/threejs/3ES-Module/READE.md 原生ES-Module在浏览器中的尝试 使用方式: 首先在使用上,唯一的区别就是需要在script标签上添加一个type="module"的属性来表示这个文件是作为module的方式来运行的。 ```javascript <script type="module"> import message from './message.js'; console.log(message); </script> ``` message.js ```javascript export default 'hello'; ``` 注意: 1. 浏览器原生提供的,在使用方法上与webpack的版本肯定还是会有一些区别的。(至少一个是运行时解析的、一个是本地编译) 2. 有效的module路径定义 - 因为是在浏览器端的实现,不会像在node中,有全局module一说(全局对象都在window里了) - from 'XXX'这个路径的定义会与之前你所熟悉的稍微有些出入 ```javascript // 被支持的几种路径写法 import module from 'http://XXX/module.js' import module from '/XXX/module.js' import module from './XXX/module.js' import module from '../XXX/module.js' // 不被支持的写法 import module from 'XXX' import module from 'XXX/module.js' ``` - 在webpack打包的文件中,引用全局包是通过import module from 'XXX'来实现的 => 这个实际是一个简写,webpack会根据这个路径去node_modules中找到对应的module并引入进来 - 原生支持的module是不存在node_modules一说的 所以,在使用原生module的时候一定要切记,from后边的路径一定要是一个有效的URL,以及一定不能省略文件后缀(是的,即使是远端文件也是可以使用的,而不像webpack需要将本地文件打包到一起) 3. THREE.js中的模块和插件引入 ```javascript import * as THREE from '../build/three.module.js'; import Stats from '../build/stats.module.js'; import { GUI } from '../build/dat.gui.module.js'; ``` 下面的项目均以这种模式开发 参考: https://www.cnblogs.com/jiasm/p/9160691.html https://zhuanlan.zhihu.com/p/39641701<file_sep>/threejs/1Three.js-VideoTutorial/2npm/webpack.config.development.js // 使用node.js的path模块 const path = require('path'); // export一个对象 module.exports = { // 模式 mode: 'development', // 入口 entry: './src/index-entry.js', // 出口 output: { // 输出的文件名 filename: 'boundle.js', // 输出的目录(必须是绝对路径) path: path.resolve(__dirname, './build') }, // webpack-dev-server配置 devServer: { // 指定当前服务处理资源目录 contentBase: './build', // 创建服务指定的端口 port: 8080, // 启动服务器压缩 compress: true, // 编译完自动打开浏览器 open: true, // 显示打包编译进度 progress: true }, module: {}, // 模块配置 plugins: [], // 插件配置 resolve: {} // 配置解析 }<file_sep>/threejs/2.初识Three.js/README.md 创建第一个Three App 1. 初始化函数 - init() + Three.js 三大件:场景、相机、渲染器 + 构建场景:THREE.Scene(); + 创建相机 + THREE.PerspectiveCamera + 设置相机的位置 => WebGL的坐标系 + 创建渲染器 + THREE.WebGLRenderer <= 基于WebGL渲染的渲染器 + setSize => 设置要显示的窗口大小 + 渲染器渲染界面生成的内容在画布上显示 => renderer.domElement(在实例化渲染器时生成的一个canvas画布) => 添加到dom + 创建模型 2. 运行动画 - animate() 3. 调用 - init(); - animate(); 4. Three.js的性能检测插件 Three.js里面,遇到的最多的问题就是性能问题 => 需要时刻检测当前的Three.js的性能 => Three.js常使用的一款插件叫stats ``` stats = new Stats(); document.body.appendChild(stats.dom); stats.update(); ``` 在场景当中,我们能够看到左上角会有一个性能检测的小框 前面的数值代表当前`每秒的渲染帧率`,后面的括号内的值是当前的场景渲染的`帧率范围`
8f33506ab545c2f74af35bf3f3cd822fee13d621
[ "JavaScript", "Markdown" ]
10
JavaScript
huangtiancai/webgl-threejs-thingjs
40cdab8074f8a3443e211221aca0a027a429e39c
ccc81da8542878fdf902df76c8c8cdc4b2a009fa
refs/heads/master
<repo_name>StanleyGoldman/NRules<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TwoFactOneForAllCheckRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class TwoFactOneForAllCheckRuleTest : BaseRuleTestFixture { [Test] public void Fire_MatchingFactOfTypeOneNothigOfTypeTwo_FiresOnce() { //Arrange var fact1 = new FactType1 { TestProperty = "Valid Value 1" }; Session.Insert(fact1); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingFacts_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingFactOfTypeOneMultipleOfTypeTwo_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingFactsOfTypeOneMultipleOfTypeTwo_FiresTwice() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; var fact3 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; var fact4 = new FactType2 {TestProperty = "Valid Value 4", JoinProperty = fact2.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); //Act Session.Fire(); //Assert AssertFiredTwice(); } [Test] public void Fire_MatchingFactsOfTypeOneOnlyOneOfTypeTwo_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; var fact3 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; var fact4 = new FactType2 {TestProperty = "Valid Value 4", JoinProperty = fact1.TestProperty}; var fact5 = new FactType2 {TestProperty = "Valid Value 5", JoinProperty = fact2.TestProperty}; var fact6 = new FactType2 {TestProperty = "Invalid Value 6", JoinProperty = fact2.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); Session.Insert(fact5); Session.Insert(fact6); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingFactOfTypeOneNotAllMatchingOfTypeTwo_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Invalid Value 4", JoinProperty = fact1.TestProperty}; var fact4 = new FactType2 {TestProperty = "Valid Value 5", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingFactsInvalidFactOfTypeTwoInsertedRetracted_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Invalid Value 4", JoinProperty = fact1.TestProperty}; var fact4 = new FactType2 {TestProperty = "Valid Value 5", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); Session.Retract(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingFactsInvalidFactOfTypeTwoInsertedUpdatedToValid_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Invalid Value 4", JoinProperty = fact1.TestProperty}; var fact4 = new FactType2 {TestProperty = "Valid Value 5", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); fact3.TestProperty = "Valid Value 4"; Session.Update(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); } protected override void SetUpRules() { SetUpRule<TwoFactOneForAllCheckRule>(); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/OneFactRepeatableRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class OneFactRepeatableRuleTest : BaseRuleTestFixture { [Test] public void Fire_OneMatchingFactEligibleForOneIncrement_FiresOnce() { //Arrange var fact = new FactType5 {TestProperty = "Valid Value 1", TestCount = 2}; Session.Insert(fact); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_OneMatchingFactEligibleForTwoIncrements_FiresTwice() { //Arrange var fact = new FactType5 {TestProperty = "Valid Value 1", TestCount = 1}; Session.Insert(fact); //Act Session.Fire(); //Assert AssertFiredTwice(); } protected override void SetUpRules() { SetUpRule<OneFactRepeatableRule>(); } } }<file_sep>/src/NRules/NRules.RuleModel/Builders/AggregateBuilder.cs using System; namespace NRules.RuleModel.Builders { /// <summary> /// Builder to compose an aggregate element. /// </summary> public class AggregateBuilder : RuleElementBuilder, IBuilder<AggregateElement> { private readonly Type _resultType; private Type _aggregateType; private PatternBuilder _sourceBuilder; internal AggregateBuilder(Type resultType, SymbolTable scope) : base(scope.New("Aggregate")) { _resultType = resultType; } /// <summary> /// Sets aggregate type. /// </summary> /// <param name="aggregateType">Type that implements <see cref="IAggregate"/> that aggregates facts.</param> public void AggregateType(Type aggregateType) { if (!typeof(IAggregate).IsAssignableFrom(aggregateType)) { throw new InvalidOperationException("Aggregate type must implement IAggregate interface"); } _aggregateType = aggregateType; } /// <summary> /// Sets aggregate type to the collection aggregate. /// </summary> /// <param name="elementType">Type of element to aggregate.</param> public void CollectionOf(Type elementType) { Type aggregateType = typeof (CollectionAggregate<>).MakeGenericType(elementType); AggregateType(aggregateType); } /// <summary> /// Creates a pattern builder that builds the source of the aggregate. /// </summary> /// <param name="type">Type of the element the pattern matches.</param> /// <param name="name">Pattern name (optional).</param> /// <returns>Pattern builder.</returns> public PatternBuilder Pattern(Type type, string name = null) { Declaration declaration = Scope.Declare(type, name); return Pattern(declaration); } /// <summary> /// Creates a pattern builder that builds the source of the aggregate. /// </summary> /// <param name="declaration">Pattern declaration.</param> /// <returns>Pattern builder.</returns> public PatternBuilder Pattern(Declaration declaration) { AssertSingleSource(); var sourceBuilder = new PatternBuilder(Scope, declaration); _sourceBuilder = sourceBuilder; return sourceBuilder; } AggregateElement IBuilder<AggregateElement>.Build() { Validate(); IBuilder<PatternElement> sourceBuilder = _sourceBuilder; PatternElement sourceElement = sourceBuilder.Build(); var aggregateElement = new AggregateElement(Scope.VisibleDeclarations, _resultType, _aggregateType, sourceElement); return aggregateElement; } private void Validate() { if (_aggregateType == null) { throw new InvalidOperationException("Aggregate type not specified"); } if (_sourceBuilder == null) { throw new InvalidOperationException("Aggregate source is not provided"); } } private void AssertSingleSource() { if (_sourceBuilder != null) { throw new InvalidOperationException("Aggregate element can only have a single source"); } } } }<file_sep>/src/NRules/NRules/Rete/AlphaNode.cs using System.Collections.Generic; using System.Diagnostics; namespace NRules.Rete { internal abstract class AlphaNode : IObjectSink { protected AlphaNode() { ChildNodes = new List<AlphaNode>(); } public AlphaMemoryNode MemoryNode { get; set; } [DebuggerDisplay("Count = {ChildNodes.Count}")] public IList<AlphaNode> ChildNodes { get; private set; } public abstract bool IsSatisfiedBy(IExecutionContext context, Fact fact); public void PropagateAssert(IExecutionContext context, Fact fact) { if (IsSatisfiedBy(context, fact)) { foreach (var childNode in ChildNodes) { childNode.PropagateAssert(context, fact); } if (MemoryNode != null) { MemoryNode.PropagateAssert(context, fact); } } } public void PropagateUpdate(IExecutionContext context, Fact fact) { if (IsSatisfiedBy(context, fact)) { foreach (var childNode in ChildNodes) { childNode.PropagateUpdate(context, fact); } if (MemoryNode != null) { MemoryNode.PropagateUpdate(context, fact); } } else { UnsatisfiedFactUpdate(context, fact); } } protected virtual void UnsatisfiedFactUpdate(IExecutionContext context, Fact fact) { ForceRetract(context, fact); } public void PropagateRetract(IExecutionContext context, Fact fact) { if (IsSatisfiedBy(context, fact)) { foreach (var childNode in ChildNodes) { childNode.PropagateRetract(context, fact); } if (MemoryNode != null) { MemoryNode.PropagateRetract(context, fact); } } } public void ForceRetract(IExecutionContext context, Fact fact) { foreach (var childNode in ChildNodes) { childNode.ForceRetract(context, fact); } if (MemoryNode != null) { MemoryNode.PropagateRetract(context, fact); } } public abstract void Accept<TContext>(TContext context, ReteNodeVisitor<TContext> visitor); } }<file_sep>/src/NRules/NRules/Rete/NotNode.cs using System.Linq; namespace NRules.Rete { internal class NotNode : BetaNode { public NotNode(ITupleSource leftSource, IObjectSource rightSource) : base(leftSource, rightSource) { } public override void PropagateAssert(IExecutionContext context, Tuple tuple) { var matchingFacts = MatchingFacts(context, tuple); tuple.Quantifier(this).Value = matchingFacts.Count(); if (tuple.Quantifier(this).Value == 0) { AssertTuple(context, tuple); } } public override void PropagateUpdate(IExecutionContext context, Tuple tuple) { if (tuple.Quantifier(this).Value == 0) { UpdateTuple(context, tuple); } } public override void PropagateRetract(IExecutionContext context, Tuple tuple) { if (tuple.Quantifier(this).Value == 0) { RetractTuple(context, tuple); } } public override void PropagateAssert(IExecutionContext context, Fact fact) { var matchingTuples = MatchingTuples(context, fact); foreach (var tuple in matchingTuples) { tuple.Quantifier(this).Value++; if (tuple.Quantifier(this).Value == 1) { RetractTuple(context, tuple); } } } public override void PropagateUpdate(IExecutionContext context, Fact fact) { //Do nothing } public override void PropagateRetract(IExecutionContext context, Fact fact) { var matchingTuples = MatchingTuples(context, fact); foreach (var tuple in matchingTuples) { tuple.Quantifier(this).Value--; if (tuple.Quantifier(this).Value == 0) { AssertTuple(context, tuple); } } } public override void Accept<TContext>(TContext context, ReteNodeVisitor<TContext> visitor) { visitor.VisitNotNode(context, this); } private void AssertTuple(IExecutionContext context, Tuple tuple) { MemoryNode.PropagateAssert(context, tuple, null); } private void UpdateTuple(IExecutionContext context, Tuple tuple) { MemoryNode.PropagateUpdate(context, tuple, null); } private void RetractTuple(IExecutionContext context, Tuple tuple) { MemoryNode.PropagateRetract(context, tuple, null); } } }<file_sep>/src/NRules/NRules/Rete/Network.cs using System; namespace NRules.Rete { internal interface INetwork { void PropagateAssert(IExecutionContext context, object factObject); void PropagateUpdate(IExecutionContext context, object factObject); void PropagateRetract(IExecutionContext context, object factObject); void Activate(IExecutionContext context); void Visit<TContext>(TContext context, ReteNodeVisitor<TContext> visitor); } internal class Network : INetwork { private readonly RootNode _root; private readonly DummyNode _dummyNode; public Network(RootNode root, DummyNode dummyNode) { _root = root; _dummyNode = dummyNode; } public void PropagateAssert(IExecutionContext context, object factObject) { if (factObject == null) { throw new ArgumentNullException("factObject"); } Fact fact = context.WorkingMemory.GetFact(factObject); if (fact != null) { throw new ArgumentException("Fact for insert already exists", "factObject"); } fact = new Fact(factObject); context.EventAggregator.RaiseFactInserting(context.Session, fact); context.WorkingMemory.SetFact(fact); _root.PropagateAssert(context, fact); context.EventAggregator.RaiseFactInserted(context.Session, fact); } public void PropagateUpdate(IExecutionContext context, object factObject) { if (factObject == null) { throw new ArgumentNullException("factObject"); } Fact fact = context.WorkingMemory.GetFact(factObject); if (fact == null) { throw new ArgumentException("Fact for update does not exist", "factObject"); } context.EventAggregator.RaiseFactUpdating(context.Session, fact); _root.PropagateUpdate(context, fact); context.EventAggregator.RaiseFactUpdated(context.Session, fact); } public void PropagateRetract(IExecutionContext context, object factObject) { if (factObject == null) { throw new ArgumentNullException("factObject"); } Fact fact = context.WorkingMemory.GetFact(factObject); if (fact == null) { throw new ArgumentException("Fact for retract does not exist", "factObject"); } context.EventAggregator.RaiseFactRetracting(context.Session, fact); _root.PropagateRetract(context, fact); context.WorkingMemory.RemoveFact(fact); context.EventAggregator.RaiseFactRetracted(context.Session, fact); } public void Activate(IExecutionContext context) { _dummyNode.Activate(context); } public void Visit<TContext>(TContext context, ReteNodeVisitor<TContext> visitor) { visitor.Visit(context, _root); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestRules/ParentRuleWithMetadata.cs using NRules.Fluent.Dsl; using NRules.IntegrationTests.TestAssets; namespace NRules.IntegrationTests.TestRules { [Tag("ParentTag"), Tag("ParentMetadata")] public abstract class ParentRuleWithMetadata : BaseRule { } } <file_sep>/src/NRules/NRules/Rete/AlphaMemoryNode.cs using System.Collections.Generic; namespace NRules.Rete { internal interface IAlphaMemoryNode : IObjectSource { IEnumerable<IObjectSink> Sinks { get; } } internal class AlphaMemoryNode : IObjectSink, IAlphaMemoryNode { private readonly List<IObjectSink> _sinks = new List<IObjectSink>(); public IEnumerable<IObjectSink> Sinks { get { return _sinks; } } public void PropagateAssert(IExecutionContext context, Fact fact) { IAlphaMemory memory = context.WorkingMemory.GetNodeMemory(this); foreach (var sink in _sinks) { sink.PropagateAssert(context, fact); } memory.Add(fact); } public void PropagateUpdate(IExecutionContext context, Fact fact) { IAlphaMemory memory = context.WorkingMemory.GetNodeMemory(this); if (memory.Contains(fact)) { foreach (var sink in _sinks) { sink.PropagateUpdate(context, fact); } } else { PropagateAssert(context, fact); } } public void PropagateRetract(IExecutionContext context, Fact fact) { IAlphaMemory memory = context.WorkingMemory.GetNodeMemory(this); foreach (var sink in _sinks) { sink.PropagateRetract(context, fact); } memory.Remove(fact); } public IEnumerable<Fact> GetFacts(IExecutionContext context) { IAlphaMemory memory = context.WorkingMemory.GetNodeMemory(this); return memory.Facts; } public void Attach(IObjectSink sink) { _sinks.Add(sink); } public void Accept<TContext>(TContext context, ReteNodeVisitor<TContext> visitor) { visitor.VisitAlphaMemoryNode(context, this); } } }<file_sep>/src/NRules/NRules/Rete/FactIndexMap.cs using System.Collections.Generic; using System.Diagnostics; using System.Linq; using NRules.RuleModel; using NRules.Utilities; namespace NRules.Rete { [DebuggerDisplay("[{string.Join(\" \",_map)}]")] internal class FactIndexMap { private readonly int[] _map; public FactIndexMap(int[] map) { _map = map; } public int Map(int index) { return (index >= 0) ? _map[index] : index; } public static void SetElementAt(ref object[] target, int index, int offset, object value) { if (index >= 0) { target[index + offset] = value; } } public static FactIndexMap CreateMap(IEnumerable<Declaration> declarations, IEnumerable<Declaration> baseDeclarations) { var positionMap = declarations.ToIndexMap(); var map = baseDeclarations .Select(positionMap.IndexOrDefault).ToArray(); return new FactIndexMap(map); } } } <file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestRules/TwoFactSameTypeRule.cs using NRules.IntegrationTests.TestAssets; namespace NRules.IntegrationTests.TestRules { public class TwoFactSameTypeRule : BaseRule { public override void Define() { FactType4 fact1 = null; FactType4 fact2 = null; When() .Match<FactType4>(() => fact1, f => f.TestProperty.StartsWith("Valid")) .Match<FactType4>(() => fact2, f => f.TestProperty.StartsWith("Valid"), f => f.Parent == fact1); Then() .Do(ctx => Action()); } } } <file_sep>/src/NRules/NRules.Fluent/ExpressionBuilderDecorator.cs using System; using System.Collections.Generic; using System.Linq.Expressions; using NRules.Fluent.Dsl; namespace NRules.Fluent { internal abstract class ExpressionBuilderDecorator : ILeftHandSide { protected ExpressionBuilder Builder { get; private set; } protected ExpressionBuilderDecorator(ExpressionBuilder builder) { Builder = builder; } public ILeftHandSide Match<T>(Expression<Func<T>> alias, params Expression<Func<T, bool>>[] conditions) { return Builder.Match(alias, conditions); } public ILeftHandSide Match<T>(Expression<Func<T, bool>> condition, params Expression<Func<T, bool>>[] conditions) { return Builder.Match(condition, conditions); } public ILeftHandSide Match<T>() { return Builder.Match<T>(); } public ICollectPattern<IEnumerable<T>> Collect<T>(Expression<Func<IEnumerable<T>>> alias, params Expression<Func<T, bool>>[] itemConditions) { return Builder.Collect(alias, itemConditions); } public ILeftHandSide Exists<T>(params Expression<Func<T, bool>>[] conditions) { return Builder.Exists(conditions); } public ILeftHandSide Not<T>(params Expression<Func<T, bool>>[] conditions) { return Builder.Not(conditions); } public ILeftHandSide All<T>(Expression<Func<T, bool>> baseCondition, params Expression<Func<T, bool>>[] conditions) { return Builder.All(baseCondition, conditions); } public ILeftHandSide All<T>(Expression<Func<T, bool>> condition) { return Builder.All(condition); } public ILeftHandSide And(Action<ILeftHandSide> builder) { return Builder.And(builder); } public ILeftHandSide Or(Action<ILeftHandSide> builder) { return Builder.Or(builder); } } }<file_sep>/src/NRules/NRules.RuleModel/IAggregate.cs namespace NRules.RuleModel { /// <summary> /// Result of an aggregation, based on added/modified/removed facts. /// </summary> public enum AggregationResults { /// <summary> /// No changes at the aggregate level. /// </summary> None = 0, /// <summary> /// New aggregate created. /// </summary> Added = 1, /// <summary> /// Existing aggregate modified. /// </summary> Modified = 2, /// <summary> /// Existing aggregate removed. /// </summary> Removed = 3, } /// <summary> /// Base interface for aggregate types. /// </summary> public interface IAggregate { /// <summary> /// Add is called by the rules engine when a new fact enters corresponding aggregation node. /// </summary> /// <param name="fact">New fact to add to the aggregate.</param> /// <returns>Result of the aggregation, based on the added fact.</returns> AggregationResults Add(object fact); /// <summary> /// Modify is called by the rules engine when an existing fact is updated in the corresponding aggregation node. /// </summary> /// <param name="fact">Existing fact to update in the aggregate.</param> /// <returns>Result of the aggregation, based on the modified fact.</returns> AggregationResults Modify(object fact); /// <summary> /// Remove is called by the rules engine when an existing fact is removed from the corresponding aggregation node. /// </summary> /// <param name="fact">Existing fact to remove from the aggregate.</param> /// <returns>Result of the aggregation, based on the removed fact.</returns> AggregationResults Remove(object fact); /// <summary> /// Result of the aggregation. /// </summary> object Result { get; } } }<file_sep>/src/NRules/NRules/Diagnostics/FactInfo.cs using System; using NRules.Rete; namespace NRules.Diagnostics { /// <summary> /// Fact in the working memory. /// </summary> public class FactInfo { private readonly Fact _fact; internal FactInfo(Fact fact) { _fact = fact; } /// <summary> /// Fact type. /// </summary> public Type Type { get { return _fact.FactType; } } /// <summary> /// Actual fact object. /// </summary> public object Value { get { return _fact.Object; } } } }<file_sep>/src/NRules/NRules/Rete/Tuple.cs using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace NRules.Rete { [DebuggerDisplay("Tuple ({Count})")] [DebuggerTypeProxy(typeof(TupleDebugView))] internal class Tuple { private Dictionary<INode, object> _stateMap; public Tuple() { Count = 0; } public Tuple(Tuple left, Fact right) { RightFact = right; LeftTuple = left; Count = left.Count; if (right != null) Count++; } public Fact RightFact { get; private set; } public Tuple LeftTuple { get; private set; } public int Count { get; private set; } public T GetState<T>(INode node) { object value; if (_stateMap != null && _stateMap.TryGetValue(node, out value)) { return (T) value; } return default(T); } public void SetState(INode node, object value) { if (_stateMap == null) _stateMap = new Dictionary<INode, object>(); _stateMap[node] = value; } public void Clear() { RightFact = null; LeftTuple = null; } /// <summary> /// Facts contained in the tuple in reverse order (fast iteration over linked list). /// Reverse collection to get facts in their actual order. /// </summary> public IEnumerable<Fact> Facts { get { if (RightFact != null) yield return RightFact; if (LeftTuple == null) yield break; foreach (var leftFact in LeftTuple.Facts) { yield return leftFact; } } } internal class TupleDebugView { public readonly string Facts; public TupleDebugView(Tuple tuple) { Facts = string.Format("[{0}]", string.Join(" || ", tuple.Facts.Reverse().Select(f => f.Object).ToArray())); } } } }<file_sep>/src/NRules/NRules/Rete/ITupleSink.cs namespace NRules.Rete { internal interface ITupleSink: INode { void PropagateAssert(IExecutionContext context, Tuple tuple); void PropagateUpdate(IExecutionContext context, Tuple tuple); void PropagateRetract(IExecutionContext context, Tuple tuple); } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestAssets/FactType3.cs namespace NRules.IntegrationTests.TestAssets { public class FactType3 { public string TestProperty { get; set; } public string JoinProperty { get; set; } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestRules/OneFactRepeatableRule.cs using NRules.Fluent.Dsl; using NRules.IntegrationTests.TestAssets; using NRules.RuleModel; namespace NRules.IntegrationTests.TestRules { [Repeatability(RuleRepeatability.Repeatable)] public class OneFactRepeatableRule : BaseRule { public override void Define() { FactType5 fact = null; When() .Match<FactType5>(() => fact, f => f.TestProperty.StartsWith("Valid"), f => f.TestCount <= 2); Then() .Do(ctx => fact.IncrementCount()) .Do(ctx => ctx.Update(fact)) .Do(ctx => Action()); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/OneFactOneCollectionRuleTest.cs using System.Collections.Generic; using System.Linq; using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class OneFactOneCollectionRuleTest : BaseRuleTestFixture { [Test] public void Fire_TwoMatchingFactsAndOneInvalid_FiresOnceWithTwoFactsInCollection() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; var fact3 = new FactType1 {TestProperty = "Invalid Value 3"}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); Assert.AreEqual(2, GetFiredFact<IEnumerable<FactType1>>().Count()); } [Test] public void Fire_TwoMatchingFactsInsertedOneRetracted_FiresOnceWithOneFactInCollection() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; Session.Insert(fact1); Session.Insert(fact2); Session.Retract(fact2); //Act Session.Fire(); //Assert AssertFiredOnce(); Assert.AreEqual(1, GetFiredFact<IEnumerable<FactType1>>().Count()); } [Test] public void Fire_TwoMatchingFactsInsertedTwoRetracted_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; Session.Insert(fact1); Session.Insert(fact2); Session.Retract(fact1); Session.Retract(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } protected override void SetUpRules() { SetUpRule<OneFactOneCollectionRule>(); } } }<file_sep>/src/NRules/Tests/NRules.Tests/AgendaTest.cs using Moq; using NRules.Rete; using NUnit.Framework; namespace NRules.Tests { [TestFixture] public class AgendaTest { [Test] public void Activate_NotCalled_ActivationQueueEmpty() { // Arrange // Act var target = CreateTarget(); // Assert Assert.False(target.HasActiveRules()); } [Test] public void Activate_Called_ActivationEndsUpInQueue() { // Arrange var ruleMock = new Mock<ICompiledRule>(); var activation = new Activation(ruleMock.Object, new Tuple(), null); var target = CreateTarget(); // Act target.Activate(activation); // Assert Assert.True(target.HasActiveRules()); Assert.AreEqual(ruleMock.Object, target.NextActivation().Rule); } [Test] public void Deactivate_CalledAfterActivation_ActivationQueueEmpty() { // Arrange var ruleMock = new Mock<ICompiledRule>(); var activation = new Activation(ruleMock.Object, new Tuple(), null); var target = CreateTarget(); target.Activate(activation); // Act target.Deactivate(activation); // Assert Assert.False(target.HasActiveRules()); } [Test] public void Activate_CalledWithMultipleRules_RulesAreQueuedInOrder() { // Arrange var ruleMock1 = new Mock<ICompiledRule>(); var ruleMock2 = new Mock<ICompiledRule>(); var activation1 = new Activation(ruleMock1.Object, new Tuple(), null); var activation2 = new Activation(ruleMock2.Object, new Tuple(), null); var target = CreateTarget(); // Act target.Activate(activation1); target.Activate(activation2); // Assert Assert.True(target.HasActiveRules()); Assert.AreEqual(ruleMock1.Object, target.NextActivation().Rule); Assert.True(target.HasActiveRules()); Assert.AreEqual(ruleMock2.Object, target.NextActivation().Rule); } private Agenda CreateTarget() { return new Agenda(); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/OneFactOneNotRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class OneFactOneNotRuleTest : BaseRuleTestFixture { [Test] public void Fire_MatchingNotPatternFact_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingNotPatternFactAssertedThenRetracted_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); Session.Retract(fact1); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingNotPatternFactAssertedThenUpdatedToInvalid_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); fact1.TestProperty = "Invalid Value 1"; Session.Update(fact1); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_NoFactMatchingNotPattern_FiresOnce() { //Arrange //Act Session.Fire(); //Assert AssertFiredOnce(); } protected override void SetUpRules() { SetUpRule<OneFactOneNotRule>(); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/CollectionWithConditionsRuleTest.cs using System.Collections.Generic; using System.Linq; using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class CollectionWithConditionsRuleTest : BaseRuleTestFixture { [Test] public void Fire_TwoMatchingFacts_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_ThreeMatchingFacts_FiresOnceWithThreeFacts() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; var fact3 = new FactType1 {TestProperty = "Valid Value 3"}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); Assert.AreEqual(3, GetFiredFact<IEnumerable<FactType1>>().Count()); } [Test] public void Fire_ThreeMatchingFactsOneRetracted_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; var fact3 = new FactType1 {TestProperty = "Valid Value 3"}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Retract(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } protected override void SetUpRules() { SetUpRule<CollectionWithConditionsRule>(); } } }<file_sep>/src/NRules/NRules/RuleActionEvaluationException.cs using System; using System.Runtime.Serialization; using System.Security; namespace NRules { /// <summary> /// Represents errors that occur while evaluating rule action. /// </summary> [Serializable] public class RuleActionEvaluationException : RuleExpressionEvaluationException { internal RuleActionEvaluationException(string message, string expression, Exception innerException) : base(message, expression, innerException) { } [SecuritySafeCritical] protected RuleActionEvaluationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/ForwardChainingTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class ForwardChainingTest : BaseRuleTestFixture { [Test] public void Fire_OneMatchingFact_FiresFirstRuleAndChainsSecond() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); //Act Session.Fire(); //Assert AssertFiredOnce<ForwardChainingFirstRule>(); AssertFiredOnce<ForwardChainingSecondRule>(); } [Test] public void Fire_OneMatchingFactOfOneKindAndOneOfAnotherKind_FiresSecondRuleDirectlyAndChained() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2"}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertFiredOnce<ForwardChainingFirstRule>(); AssertFiredTwice<ForwardChainingSecondRule>(); } protected override void SetUpRules() { SetUpRule<ForwardChainingFirstRule>(); SetUpRule<ForwardChainingSecondRule>(); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/CoJoinedCollectAndExistsRulesTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class CoJoinedCollectAndExistsRulesTest : BaseRuleTestFixture { [Test] public void Fire_MatchingFactOfFirstKindNoFactsOfOtherKind_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); //Act Session.Fire(); //Assert AssertDidNotFire<TwoFactOneCollectionRule>(); AssertDidNotFire<TwoFactOneExistsCheckRule>(); } [Test] public void Fire_MatchingFactOfFirstKindAndMatchingFactOfOtherKind_EachFiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertFiredOnce<TwoFactOneCollectionRule>(); AssertFiredOnce<TwoFactOneExistsCheckRule>(); } protected override void SetUpRules() { SetUpRule<TwoFactOneExistsCheckRule>(); SetUpRule<TwoFactOneCollectionRule>(); } } } <file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestAssets/FactType4.cs namespace NRules.IntegrationTests.TestAssets { public class FactType4 { public string TestProperty { get; set; } public FactType4 Parent { get; set; } } }<file_sep>/src/NRules/Tests/NRules.Tests/Rete/TupleTest.cs using System.Linq; using NRules.Rete; using NUnit.Framework; namespace NRules.Tests.Rete { [TestFixture] public class TupleTest { [Test] public void Ctor_WhenFactPassed_ExposedAsRightFact() { //Arrange var fact = new Fact(1); //Act var target = new Tuple(new Tuple(), fact); //Assert Assert.AreEqual(fact, target.RightFact); } [Test] public void Ctor_WhenTuplePassed_ExposedAsLeftTuple() { //Arrange var tuple1 = new Tuple(new Tuple(), new Fact(1)); //Act var tuple2 = new Tuple(tuple1, new Fact(2)); //Assert Assert.AreEqual(tuple1, tuple2.LeftTuple); } [Test] public void Enumerator_WhenEnumeratesNTuple_WalksTuplesInReverseOrder() { //Arrange var tuple0 = new Tuple(); var tuple1 = new Tuple(tuple0, new Fact(1)); var tuple2 = new Tuple(tuple1, new Fact(2)); var tuple3 = new Tuple(tuple2, new Fact(3)); //Act var target = tuple3.Facts.ToArray(); //Assert Assert.AreEqual(3, target.Length); Assert.AreEqual(tuple1.RightFact, target[2]); Assert.AreEqual(tuple2.RightFact, target[1]); Assert.AreEqual(tuple3.RightFact, target[0]); } [Test] public void Enumerator_WhenEnumerated_ReturnsUnderlyingFactObjectsInReverseOrder() { //Arrange var tuple0 = new Tuple(); var tuple1 = new Tuple(tuple0, new Fact(1)); var tuple2 = new Tuple(tuple1, new Fact(2)); var tuple3 = new Tuple(tuple2, new Fact(3)); //Act var target = tuple3.Facts.Select(f => f.Object).ToArray(); //Assert Assert.AreEqual(3, target.Length); Assert.AreEqual(1, target[2]); Assert.AreEqual(2, target[1]); Assert.AreEqual(3, target[0]); } [Test] public void Enumerator_WhenEnumerates1Tuple_ReturnsSelf() { //Arrange var tuple = new Tuple(new Tuple(), new Fact(1)); //Act var target = tuple.Facts.ToArray(); //Assert Assert.AreEqual(1, target.Length); Assert.AreEqual(tuple.RightFact, target[0]); } [Test] public void Enumerator_WhenEnumerates0Tuple_ReturnsEmpty() { //Arrange var tuple = new Tuple(); //Act var target = tuple.Facts.ToArray(); //Assert Assert.AreEqual(0, target.Length); } [Test] public void Clear_WhenCalled_ClearsItself() { //Arrange var fact = new Fact(1); var target = new Tuple(new Tuple(), fact); //Act target.Clear(); //Assert Assert.IsNull(target.RightFact); Assert.IsNull(target.LeftTuple); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TwoFactSameTypeRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class TwoFactSameTypeRuleTest : BaseRuleTestFixture { [Test] public void Fire_MatchingFacts_FiresOnce() { //Arrange var fact1 = new FactType4 {TestProperty = "Valid Value 1"}; var fact2 = new FactType4 {TestProperty = "Valid Value 2", Parent = fact1}; var fact3 = new FactType4 {TestProperty = "Invalid Value 3", Parent = fact1}; var fact4 = new FactType4 {TestProperty = "Valid Value 4", Parent = null}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_FirstMatchingFactSecondInvalid_DoesNotFire() { //Arrange var fact1 = new FactType4 {TestProperty = "Valid Value 1"}; var fact2 = new FactType4 {TestProperty = "Valid Value 2"}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } protected override void SetUpRules() { SetUpRule<TwoFactSameTypeRule>(); } } }<file_sep>/src/NRules/NRules/Rete/Fact.cs using System; using System.Diagnostics; namespace NRules.Rete { [DebuggerDisplay("Fact {Object}")] internal class Fact { private readonly Type _factType; private readonly object _object; public Fact() { } public Fact(object @object) { _object = @object; _factType = @object.GetType(); } public virtual Type FactType { get { return _factType; } } public object RawObject { get { return _object; } } public virtual object Object { get { return _object; } } } internal class WrapperFact : Fact { public WrapperFact(Tuple tuple) : base(tuple) { } public override Type FactType { get { return WrappedTuple.RightFact.FactType; } } public override object Object { get { return WrappedTuple.RightFact.Object; } } public Tuple WrappedTuple { get { return (Tuple) RawObject; } } } }<file_sep>/src/NRules/NRules.Fluent/RuleTypeScanner.cs using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using NRules.Fluent.Dsl; namespace NRules.Fluent { /// <summary> /// Assembly scanner that finds fluent rule classes. /// </summary> public class RuleTypeScanner { private readonly List<Type> _ruleTypes = new List<Type>(); private Func<IRuleMetadata, bool> _filter; /// <summary> /// Finds rule types in the specified assemblies. /// </summary> /// <param name="assemblies">Assemblies to scan.</param> /// <returns>Rule type scanner to continue scanning specification.</returns> public RuleTypeScanner Assembly(params Assembly[] assemblies) { var ruleTypes = assemblies.SelectMany(a => a.GetTypes().Where(IsRuleType)); _ruleTypes.AddRange(ruleTypes); return this; } /// <summary> /// Finds rule types in the assembly of the specified type. /// </summary> /// <typeparam name="T">Type, whose assembly to scan.</typeparam> /// <returns>Rule type scanner to continue scanning specification.</returns> public RuleTypeScanner AssemblyOf<T>() { return AssemblyOf(typeof(T)); } /// <summary> /// Finds rule types in the assembly of the specified type. /// </summary> /// <param name="type">Type, whose assembly to scan.</param> /// <returns>Rule type scanner to continue scanning specification.</returns> public RuleTypeScanner AssemblyOf(Type type) { return Assembly(type.Assembly); } /// <summary> /// Finds rule types in the specifies types. /// </summary> /// <param name="types">Types to scan.</param> /// <returns>Rule type scanner to continue scanning specification.</returns> public RuleTypeScanner Type(params Type[] types) { var ruleTypes = types.Where(IsRuleType); _ruleTypes.AddRange(ruleTypes); return this; } /// <summary> /// Filters rule types down based on rules' metadata. /// </summary> /// <param name="filter">Filter condition based on rule's metadata.</param> /// <returns>Rule type scanner to continue scanning specification.</returns> public RuleTypeScanner Where(Func<IRuleMetadata, bool> filter) { if (_filter != null) { throw new InvalidOperationException("Rule type scanner can only have a single 'Where' clause"); } _filter = filter; return this; } /// <summary> /// Retrieves found types. /// </summary> /// <returns>Rule types.</returns> public Type[] GetTypes() { var ruleTypes = _ruleTypes; if (IsFilterSet()) { var metadata = _ruleTypes.Select(ruleType => new RuleMetadata(ruleType)); var filteredTypes = metadata.Where(x => _filter(x)).Select(x => x.RuleType); ruleTypes = filteredTypes.ToList(); } return ruleTypes.ToArray(); } /// <summary> /// Determines if a given CLR type is a rule type. /// </summary> /// <param name="type">Type.</param> /// <returns>Result of the check.</returns> public static bool IsRuleType(Type type) { if (IsPublicConcrete(type) && typeof(Rule).IsAssignableFrom(type)) return true; return false; } private static bool IsPublicConcrete(Type type) { if (!type.IsPublic) return false; if (type.IsAbstract) return false; if (type.IsInterface) return false; if (type.IsGenericTypeDefinition) return false; return true; } internal bool IsFilterSet() { return _filter != null; } } }<file_sep>/src/NRules/NRules.Fluent/GroupBuilderChain.cs using System; using System.Collections.Generic; using NRules.RuleModel.Builders; namespace NRules.Fluent { internal sealed class GroupBuilderChain { private readonly Stack<GroupBuilder> _groupBuilders = new Stack<GroupBuilder>(); public GroupBuilderChain(GroupBuilder rootGroupBuilder) { _groupBuilders.Push(rootGroupBuilder); } public GroupBuilder Current { get { return _groupBuilders.Peek(); } } public IDisposable BeginGroup(GroupType groupType) { var newGroupBuilder = Current.Group(groupType); _groupBuilders.Push(newGroupBuilder); return new GroupScope(this); } private void EndGroup() { _groupBuilders.Pop(); } private class GroupScope : IDisposable { private readonly GroupBuilderChain _builderChain; public GroupScope(GroupBuilderChain builderChain) { _builderChain = builderChain; } public void Dispose() { _builderChain.EndGroup(); } } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/HaltRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class HaltRuleTest : BaseRuleTestFixture { [Test] public void Fire_TwoMatchingFacts_FiresOnceAndHalts() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_TwoMatchingFactsFireCalledTwice_FiresOnceThenHaltsThenResumesAndFiresAgain() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); Session.Fire(); //Assert AssertFiredTwice(); } protected override void SetUpRules() { SetUpRule<HaltRule>(); } } }<file_sep>/src/NRules/NRules/Rete/BetaMemoryNode.cs using System.Collections.Generic; namespace NRules.Rete { internal interface IBetaMemoryNode : ITupleSource, INode { IEnumerable<ITupleSink> Sinks { get; } void PropagateAssert(IExecutionContext context, Tuple tuple, Fact fact); void PropagateUpdate(IExecutionContext context, Tuple tuple, Fact fact); void PropagateRetract(IExecutionContext context, Tuple tuple, Fact fact); } internal class BetaMemoryNode : IBetaMemoryNode { private readonly List<ITupleSink> _sinks = new List<ITupleSink>(); public IEnumerable<ITupleSink> Sinks { get { return _sinks; } } public void PropagateAssert(IExecutionContext context, Tuple tuple, Fact fact) { IBetaMemory memory = context.WorkingMemory.GetNodeMemory(this); var childTuple = new Tuple(tuple, fact); foreach (var sink in _sinks) { sink.PropagateAssert(context, childTuple); } memory.Add(childTuple); } public void PropagateUpdate(IExecutionContext context, Tuple tuple, Fact fact) { IBetaMemory memory = context.WorkingMemory.GetNodeMemory(this); Tuple childTuple = memory.FindTuple(tuple, fact); if (childTuple == null) { PropagateAssert(context, tuple, fact); } else { foreach (var sink in _sinks) { sink.PropagateUpdate(context, childTuple); } } } public void PropagateRetract(IExecutionContext context, Tuple tuple, Fact fact) { IBetaMemory memory = context.WorkingMemory.GetNodeMemory(this); Tuple childTuple = memory.FindTuple(tuple, fact); if (childTuple != null) { foreach (var sink in _sinks) { sink.PropagateRetract(context, childTuple); } memory.Remove(childTuple); childTuple.Clear(); } } public IEnumerable<Tuple> GetTuples(IExecutionContext context) { IBetaMemory memory = context.WorkingMemory.GetNodeMemory(this); return memory.Tuples; } public void Attach(ITupleSink sink) { _sinks.Add(sink); } public void Accept<TContext>(TContext context, ReteNodeVisitor<TContext> visitor) { visitor.VisitBetaMemoryNode(context, this); } } }<file_sep>/src/NRules/NRules.Fluent/RuleLoadSpec.cs using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using NRules.RuleModel; namespace NRules.Fluent { /// <summary> /// Fluent specification to load rule definitions via reflection. /// </summary> public interface IRuleLoadSpec { /// <summary> /// Specifies to load all rule definitions from a given collection of assemblies. /// </summary> /// <param name="assemblies">Assemblies to load from.</param> /// <returns>Spec to continue fluent configuration.</returns> IRuleLoadSpec From(params Assembly[] assemblies); /// <summary> /// Specifies to load rule definitions from a given collection of types. /// </summary> /// <param name="types">Types that represent rule definitions.</param> /// <returns>Spec to continue fluent configuration.</returns> IRuleLoadSpec From(params Type[] types); /// <summary> /// Specifies which rules to load by filtering on rule's metadata. /// </summary> /// <param name="filter">Filter condition based on rule's metadata.</param> /// <returns>Spec to continue fluent configuration.</returns> IRuleLoadSpec Where(Func<IRuleMetadata, bool> filter); /// <summary> /// Specifies the name of the rule set where the rules are loaded to. /// If not provided, loads rules into default rule set. /// </summary> /// <param name="ruleSetName">Name of the rule set to load rules to.</param> /// <returns>Spec to continue fluent configuration.</returns> IRuleLoadSpec To(string ruleSetName); } internal class RuleLoadSpec : IRuleLoadSpec { private readonly IRuleActivator _activator; private readonly RuleTypeScanner _typeScanner = new RuleTypeScanner(); private string _ruleSetName; public RuleLoadSpec(IRuleActivator activator) { _activator = activator; } public string RuleSetName { get { return _ruleSetName; } } public IRuleLoadSpec From(params Assembly[] assemblies) { _typeScanner.Assembly(assemblies); return this; } public IRuleLoadSpec From(params Type[] types) { _typeScanner.Type(types); return this; } public IRuleLoadSpec Where(Func<IRuleMetadata, bool> filter) { if (_typeScanner.IsFilterSet()) { throw new InvalidOperationException("Rule load specification can only have a single 'Where' clause"); } _typeScanner.Where(filter); return this; } public IRuleLoadSpec To(string ruleSetName) { if (_ruleSetName != null) { throw new InvalidOperationException("Rule load specification can only have a single 'To' clause"); } _ruleSetName = ruleSetName; return this; } public IEnumerable<IRuleDefinition> Load() { var ruleDefinitions = _typeScanner .GetTypes() .Select(t => _activator.Activate(t)) .Select(r => r.GetDefinition()); return ruleDefinitions; } } } <file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestAssets/FactType1.cs namespace NRules.IntegrationTests.TestAssets { public class FactType1 { public string TestProperty { get; set; } } }<file_sep>/src/NRules/Tests/NRules.Tests/Utilities/ExpressionComparerTest.cs using System; using System.Linq; using System.Linq.Expressions; using NRules.Utilities; using NUnit.Framework; namespace NRules.Tests.Utilities { [TestFixture] public class ExpressionComparerTest { [Test] public void AreEqual_BothNull_True() { AssertEqual(null, null); } [Test] public void AreEqual_EquivalentBinary_True() { //Arrange Expression<Func<int, int, bool>> first = (i1, i2) => i1 == i2; Expression<Func<int, int, bool>> second = (ii1, ii2) => ii1 == ii2; AssertEqual(first, second); } [Test] public void AreEqual_TwoNonEquivalentBinary_False() { //Arrange Expression<Func<int, int, bool>> first = (i1, i2) => i1 == i2; Expression<Func<int, int, bool>> second = (ii1, ii2) => ii1 != ii2; AssertNotEqual(first, second); } [Test] public void AreEqual_EquivalentUnary_True() { //Arrange Expression<Func<int, int>> first = i => -i; Expression<Func<int, int>> second = i => -i; AssertEqual(first, second); } [Test] public void AreEqual_EquivalentMember_True() { //Arrange Expression<Func<DateTime, DayOfWeek>> first = d => d.DayOfWeek; Expression<Func<DateTime, DayOfWeek>> second = d => d.DayOfWeek; AssertEqual(first, second); } [Test] public void AreEqual_EquivalentMethodCall_True() { //Arrange Expression<Func<DateTime, DateTime>> first = d => d.ToLocalTime(); Expression<Func<DateTime, DateTime>> second = d => d.ToLocalTime(); AssertEqual(first, second); } [Test] public void AreEqual_EquivalentStaticField_True() { //Arrange Expression<Func<SomeFact, bool>> first = f => f.Value == StaticField; Expression<Func<SomeFact, bool>> second = f => f.Value == StaticField; AssertEqual(first, second); } [Test] public void AreEqual_EquivalentStaticProperty_True() { //Arrange Expression<Func<SomeFact, bool>> first = f => f.Value == StaticProperty; Expression<Func<SomeFact, bool>> second = f => f.Value == StaticProperty; AssertEqual(first, second); } [Test] public void AreEqual_EquivalentStaticMethod_True() { //Arrange Expression<Func<SomeFact, bool>> first = f => f.Value == StaticMethod(); Expression<Func<SomeFact, bool>> second = f => f.Value == StaticMethod(); AssertEqual(first, second); } [Test] public void AreEqual_EquivalentMethodWithArguments_True() { //Arrange Expression<Func<SomeFact, bool>> first = f => f.Value == StaticMethod("one"); Expression<Func<SomeFact, bool>> second = f => f.Value == StaticMethod("one"); AssertEqual(first, second); } [Test] public void AreEqual_NonEquivalentMethodWithArguments_False() { //Arrange Expression<Func<SomeFact, bool>> first = f => f.Value == StaticMethod("one"); Expression<Func<SomeFact, bool>> second = f => f.Value == StaticMethod("two"); AssertNotEqual(first, second); } [Test] public void AreEqual_EquivalentMemberAccessExtension_True() { //Arrange Expression<Func<SomeFact, bool>> first = f => f.Child.Values.Contains("sdlkjf"); Expression<Func<SomeFact, bool>> second = f => f.Child.Values.Contains("sdlkjf"); AssertEqual(first, second); } [Test] public void AreEqual_EquivalentMemberAccess_True() { //Arrange Expression<Func<SomeFact, bool>> first = f => f.Child.Values.GetLength(0) == 0; Expression<Func<SomeFact, bool>> second = f => f.Child.Values.GetLength(0) == 0; AssertEqual(first, second); } [Test] public void AreEqual_EquivalentMemberAccessIndexer_True() { //Arrange Expression<Func<SomeFact, bool>> first = f => f.Child.Values[0] == "1"; Expression<Func<SomeFact, bool>> second = f => f.Child.Values[0] == "1"; AssertEqual(first, second); } [Test] public void AreEqual_NonEquivalentMemberAccessIndexer_False() { //Arrange Expression<Func<SomeFact, bool>> first = f => f.Child.Values[0] == "1"; Expression<Func<SomeFact, bool>> second = f => f.Child.Values[1] == "1"; AssertNotEqual(first, second); } private static void AssertEqual(Expression first, Expression second) { //Act bool result = ExpressionComparer.AreEqual(first, second); //Assert Assert.That(result, Is.True); } private static void AssertNotEqual(Expression first, Expression second) { //Act bool result = ExpressionComparer.AreEqual(first, second); //Assert Assert.That(result, Is.False); } // A few fields and classes for some more advanced tests. public static int StaticField = 1; public static int StaticProperty { get { return 1; } } public static int StaticMethod() { return 1; } public static int StaticMethod(string param1) { return param1.GetHashCode(); } public class SomeFact { public int Value = 1; public SomeClass Child = new SomeClass(); } public class SomeClass { public string[] Values = { "blop" }; } } }<file_sep>/src/NRules/NRules/SessionFactory.cs using NRules.Diagnostics; using NRules.Rete; namespace NRules { /// <summary> /// Represents compiled production rules that can be used to create rules sessions. /// Created by <see cref="RuleCompiler"/> by compiling rule model into an executable form. /// </summary> /// <remarks> /// Session factory is expensive to create (because rules need to be compiled into an executable form). /// Therefore there needs to be only a single instance of session factory for a given set of rules for the lifetime of the application. /// If repeatedly running rules for different sets of facts, don't create a new session factory for each rules run. /// Instead, have a single session factory and create a new rules session for each independent universe of facts. /// </remarks> /// <seealso cref="ISession"/> /// <threadsafety instance="true" /> public interface ISessionFactory { /// <summary> /// Creates a new rules session. /// </summary> /// <returns>New rules session.</returns> ISession CreateSession(); } internal class SessionFactory : ISessionFactory { private readonly INetwork _network; public SessionFactory(INetwork network) { _network = network; } public ISession CreateSession() { var agenda = new Agenda(); var workingMemory = new WorkingMemory(); var eventAggregator = new EventAggregator(); var session = new Session(_network, agenda, workingMemory, eventAggregator); return session; } } }<file_sep>/src/NRules/NRules.RuleModel/AggregateElement.cs using System; using System.Collections.Generic; namespace NRules.RuleModel { /// <summary> /// Rule element that creates new facts (aggregates) based on matching facts it receives as input. /// </summary> public class AggregateElement : PatternSourceElement { private readonly Type _aggregateType; private readonly PatternElement _source; /// <summary> /// Type of the aggregate. Must implement <see cref="IAggregate"/> interface. /// </summary> public Type AggregateType { get { return _aggregateType; } } /// <summary> /// Fact source of the aggregate. /// </summary> public PatternElement Source { get { return _source; } } internal AggregateElement(IEnumerable<Declaration> declarations, Type resultType, Type aggregateType, PatternElement source) : base(declarations, resultType) { _aggregateType = aggregateType; _source = source; } internal override void Accept<TContext>(TContext context, RuleElementVisitor<TContext> visitor) { visitor.VisitAggregate(context, this); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TwoFactOneExistsCheckRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class TwoFactOneExistsCheckRuleTest : BaseRuleTestFixture { [Test] public void Fire_MatchingFacts_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingFactsMultipleOfTypeTwo_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingFactsTwoOfTypeOneMultipleOfTypeTwo_FiresTwice() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; var fact3 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; var fact4 = new FactType2 {TestProperty = "Valid Value 4", JoinProperty = fact2.TestProperty}; var fact5 = new FactType2 {TestProperty = "Valid Value 5", JoinProperty = fact2.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); Session.Insert(fact5); //Act Session.Fire(); //Assert AssertFiredTwice(); } [Test] public void Fire_FactOneValidFactTwoAssertedAndRetracted_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Retract(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_FactOneValidFactTwoAssertedAndUpdatedToInvalid_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2"}; Session.Insert(fact1); Session.Insert(fact2); fact2.TestProperty = "Invalid Value 2"; Session.Update(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_FactTwoDoesNotExist_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_TwoMatchingFactsAndOneFactExists_FiresOnce() { //Arrange var fact11 = new FactType1 { TestProperty = "Valid Value 1" }; var fact12 = new FactType1 { TestProperty = "Valid Value 2" }; var fact21 = new FactType2 { TestProperty = "Valid Value 3", JoinProperty = fact11.TestProperty}; Session.Insert(fact11); Session.Insert(fact12); Session.Insert(fact21); //Act Session.Fire(); //Assert AssertFiredOnce(); } protected override void SetUpRules() { SetUpRule<TwoFactOneExistsCheckRule>(); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestRules/TwoFactOneCollectionRule.cs using System.Collections.Generic; using System.Linq; using NRules.IntegrationTests.TestAssets; namespace NRules.IntegrationTests.TestRules { public class TwoFactOneCollectionRule : BaseRule { public override void Define() { FactType1 fact1 = null; IEnumerable<FactType2> collection2 = null; When() .Match<FactType1>(() => fact1, f => f.TestProperty.StartsWith("Valid")) .Collect<FactType2>(() => collection2, f => f.TestProperty.StartsWith("Valid"), f => f.JoinProperty == fact1.TestProperty); Then() .Do(ctx => Action()) .Do(ctx => collection2.ToList().ForEach(x => x.TestProperty.Normalize())); } } } <file_sep>/src/NRules/Tests/NRules.IntegrationTests/RuleMetadataTest.cs using System.Linq; using NRules.Fluent; using NRules.IntegrationTests.TestRules; using NRules.RuleModel; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class RuleMetadataTest { private RuleRepository _repository; [SetUp] public void SetUp() { _repository = new RuleRepository(); } [Test] public void Name_NameAttributePresent_CustomValue() { //Arrange _repository.Load(x => x.From(typeof(RuleWithMetadata))); IRuleDefinition rule = _repository.GetRules().Single(); //Act string actual = rule.Name; //Assert Assert.AreEqual("Rule with metadata", actual); } [Test] public void Description_DescriptionAttributePresent_CustomValue() { //Arrange _repository.Load(x => x.From(typeof(RuleWithMetadata))); IRuleDefinition rule = _repository.GetRules().Single(); //Act string actual = rule.Description; //Assert Assert.AreEqual("Rule description", actual); } [Test] public void Tags_TagAttributesPresent_CustomValues() { //Arrange _repository.Load(x => x.From(typeof(RuleWithMetadata))); IRuleDefinition rule = _repository.GetRules().Single(); //Act string[] actual = rule.Tags.ToArray(); //Assert Assert.AreEqual(2, actual.Length); Assert.Contains("Test", actual); Assert.Contains("Metadata", actual); } [Test] public void Tags_TagAttributesAndParentAttributesPresent_CustomValues() { //Arrange _repository.Load(x => x.From(typeof(RuleWithMetadataAndParentMetadata))); IRuleDefinition rule = _repository.GetRules().Single(); //Act string[] actual = rule.Tags.ToArray(); //Assert Assert.AreEqual(4, actual.Length); Assert.Contains("ChildTag", actual); Assert.Contains("ChildMetadata", actual); Assert.Contains("ParentTag", actual); Assert.Contains("ParentMetadata", actual); } [Test] public void Name_NoAttributes_TypeName() { //Arrange _repository.Load(x => x.From(typeof(RuleWithoutMetadata))); IRuleDefinition rule = _repository.GetRules().Single(); //Act string actual = rule.Name; //Assert Assert.AreEqual(typeof(RuleWithoutMetadata).FullName, actual); } [Test] public void Description_NoAttributes_Empty() { //Arrange _repository.Load(x => x.From(typeof(RuleWithoutMetadata))); IRuleDefinition rule = _repository.GetRules().Single(); //Act string actual = rule.Description; //Assert Assert.AreEqual(string.Empty, actual); } [Test] public void Tags_NoAttributes_Empty() { //Arrange _repository.Load(x => x.From(typeof(RuleWithoutMetadata))); IRuleDefinition rule = _repository.GetRules().Single(); //Act string[] actual = rule.Tags.ToArray(); //Assert Assert.AreEqual(0, actual.Length); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/EvaluationExceptionRuleTest.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using NRules.Diagnostics; using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class EvaluationExceptionRuleTest : BaseRuleTestFixture { [Test] public void Insert_ErrorInCondition_Throws() { //Arrange Expression expression = null; IList<FactInfo> facts = null; Session.Events.ConditionFailedEvent += (sender, args) => expression = args.Condition; Session.Events.ConditionFailedEvent += (sender, args) => facts = args.Facts.ToList(); var fact = new FactType1 {TestProperty = null}; //Act - Assert var ex = Assert.Throws<RuleConditionEvaluationException>(() => Session.Insert(fact)); Assert.IsNotNull(expression); Assert.AreEqual(1, facts.Count()); Assert.AreSame(fact, facts.First().Value); Assert.IsInstanceOf<NullReferenceException>(ex.InnerException); } [Test] public void Fire_ErrorInActionNoErrorHandler_Throws() { //Arrange Expression expression = null; IList<FactInfo> facts = null; Session.Events.ActionFailedEvent += (sender, args) => expression = args.Action; Session.Events.ActionFailedEvent += (sender, args) => facts = args.Facts.ToList(); var fact = new FactType1 { TestProperty = "Valid value" }; Session.Insert(fact); GetRuleInstance<OneFactRule>().Action = null; //Act - Assert var ex = Assert.Throws<RuleActionEvaluationException>(() => Session.Fire()); Assert.IsNotNull(expression); Assert.AreEqual(1, facts.Count()); Assert.AreSame(fact, facts.First().Value); Assert.IsInstanceOf<NullReferenceException>(ex.InnerException); } [Test] public void Fire_ErrorInActionErrorHandler_DoesNotThrow() { //Arrange Session.Events.ActionFailedEvent += (sender, args) => args.IsHandled = true; var fact = new FactType1 { TestProperty = "Valid value" }; Session.Insert(fact); GetRuleInstance<OneFactRule>().Action = null; //Act - Assert Assert.DoesNotThrow(() => Session.Fire()); } protected override void SetUpRules() { SetUpRule<OneFactRule>(); } } }<file_sep>/src/NRules/NRules/Rete/ObjectInputAdapter.cs using System.Collections.Generic; using System.Linq; namespace NRules.Rete { internal class ObjectInputAdapter : ITupleSink, IAlphaMemoryNode { private readonly ITupleSource _source; private readonly List<IObjectSink> _sinks = new List<IObjectSink>(); public IEnumerable<IObjectSink> Sinks { get { return _sinks; } } public ObjectInputAdapter(IBetaMemoryNode source) { _source = source; source.Attach(this); } public void PropagateAssert(IExecutionContext context, Tuple tuple) { var wrapperFact = new WrapperFact(tuple); context.WorkingMemory.SetFact(wrapperFact); foreach (var sink in _sinks) { sink.PropagateAssert(context, wrapperFact); } } public void PropagateUpdate(IExecutionContext context, Tuple tuple) { var wrapperFact = context.WorkingMemory.GetFact(tuple); foreach (var sink in _sinks) { sink.PropagateUpdate(context, wrapperFact); } } public void PropagateRetract(IExecutionContext context, Tuple tuple) { var wrapperFact = context.WorkingMemory.GetFact(tuple); foreach (var sink in _sinks) { sink.PropagateRetract(context, wrapperFact); } context.WorkingMemory.RemoveFact(wrapperFact); } public IEnumerable<Fact> GetFacts(IExecutionContext context) { return _source.GetTuples(context).Select(t => context.WorkingMemory.GetFact(t)); } public void Attach(IObjectSink sink) { _sinks.Add(sink); } public void Accept<TContext>(TContext context, ReteNodeVisitor<TContext> visitor) { visitor.VisitObjectInputAdapter(context, this); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/ThreeFactTwoExistsRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class ThreeFactTwoExistsRuleTest : BaseRuleTestFixture { [Test] public void Fire_MatchingFacts_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_NoMatchingFactsBothKind_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_NoMatchingFactsFirstKind_DoesNotFire() { //Arrange var fact1 = new FactType1 { TestProperty = "Valid Value 1" }; var fact3 = new FactType3 { TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty }; Session.Insert(fact1); Session.Insert(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_NoMatchingFactsSecondKind_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingFactsInsertedThenRetracted_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Retract(fact2); Session.Retract(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingFactsTwoInsertedThenFirstRetracted_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Retract(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingFactsTwoInsertedThenSecondRetracted_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Retract(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_InvalidFactsInsertedThenUpdated_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Invalid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Invalid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); fact2.TestProperty = "Valid Value 2"; Session.Update(fact2); fact3.TestProperty = "Valid Value 3"; Session.Update(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingFactsInsertedThenUpdated_DoesNotFire() { //Arrange var fact1 = new FactType1 { TestProperty = "Valid Value 1" }; var fact2 = new FactType2 { TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty }; var fact3 = new FactType3 { TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty }; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); fact2.TestProperty = "Invalid Value 2"; Session.Update(fact2); fact3.TestProperty = "Invalid Value 3"; Session.Update(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingFactsTwoInsertedThenFirstUpdated_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); fact2.TestProperty = "Invalid Value 2"; Session.Update(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingFactsTwoInsertedThenSecondUpdated_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); fact3.TestProperty = "Invalid Value 3"; Session.Update(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } protected override void SetUpRules() { SetUpRule<ThreeFactTwoExistsRule>(); } } }<file_sep>/src/NRules/NRules/Rete/BetaNode.cs using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace NRules.Rete { internal abstract class BetaNode : ITupleSink, IObjectSink { public ITupleSource LeftSource { get; private set; } public IObjectSource RightSource { get; private set; } public IBetaMemoryNode MemoryNode { get; set; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public IList<IBetaCondition> Conditions { get; private set; } protected BetaNode(ITupleSource leftSource, IObjectSource rightSource) { LeftSource = leftSource; RightSource = rightSource; LeftSource.Attach(this); RightSource.Attach(this); Conditions = new List<IBetaCondition>(); } public abstract void PropagateAssert(IExecutionContext context, Tuple tuple); public abstract void PropagateUpdate(IExecutionContext context, Tuple tuple); public abstract void PropagateRetract(IExecutionContext context, Tuple tuple); public abstract void PropagateAssert(IExecutionContext context, Fact fact); public abstract void PropagateUpdate(IExecutionContext context, Fact fact); public abstract void PropagateRetract(IExecutionContext context, Fact fact); public abstract void Accept<TContext>(TContext context, ReteNodeVisitor<TContext> visitor); protected IEnumerable<Fact> MatchingFacts(IExecutionContext context, Tuple tuple) { return RightSource.GetFacts(context).Where(fact => MatchesConditions(context, tuple, fact)); } protected IEnumerable<Tuple> MatchingTuples(IExecutionContext context, Fact fact) { return LeftSource.GetTuples(context).Where(tuple => MatchesConditions(context, tuple, fact)); } protected bool MatchesConditions(IExecutionContext context, Tuple left, Fact right) { return Conditions.All(joinCondition => joinCondition.IsSatisfiedBy(context, left, right)); } } }<file_sep>/src/NRules/NRules.Fluent/Dsl/Rule.cs using System; using NRules.RuleModel; using NRules.RuleModel.Builders; namespace NRules.Fluent.Dsl { /// <summary> /// Base class for inline rule definitions. /// To create a rule using internal DSL, create a class that inherits from <c>NRules.Fluent.Dsl.Rule</c> /// and override <see cref="Define"/> method. /// Use <see cref="When"/> and <see cref="Then"/> methods to define rule's conditions and actions correspondingly. /// </summary> public abstract class Rule { private readonly Lazy<IRuleDefinition> _definition; private readonly RuleBuilder _builder; protected Rule() { _builder = new RuleBuilder(); _definition = new Lazy<IRuleDefinition>(BuildDefinition); } /// <summary> /// Returns expression builder for rule's left hand side (conditions). /// </summary> /// <returns>Left hand side expression builder.</returns> protected ILeftHandSide When() { return new ExpressionBuilder(_builder); } /// <summary> /// Returns expression builder for rule's right hand side (actions). /// </summary> /// <returns>Right hand side expression builder.</returns> protected IRightHandSide Then() { return new ExpressionBuilder(_builder); } /// <summary> /// Method called by the rules engine to define the rule. /// </summary> public abstract void Define(); internal IRuleDefinition GetDefinition() { return _definition.Value; } private IRuleDefinition BuildDefinition() { var metadata = new RuleMetadata(GetType()); _builder.Name(metadata.Name); _builder.Description(metadata.Description); _builder.Tags(metadata.Tags); if (metadata.Priority.HasValue) { _builder.Priority(metadata.Priority.Value); } if (metadata.Repeatability.HasValue) { _builder.Repeatability(metadata.Repeatability.Value); } Define(); return _builder.Build(); } } }<file_sep>/src/NRules/NRules/Diagnostics/AgendaEventArgs.cs using System; using System.Collections.Generic; using System.Linq; using NRules.RuleModel; using Tuple = NRules.Rete.Tuple; namespace NRules.Diagnostics { /// <summary> /// Information related to agenda events. /// </summary> public class AgendaEventArgs : EventArgs { private readonly ICompiledRule _rule; private readonly Tuple _tuple; internal AgendaEventArgs(ICompiledRule rule, Tuple tuple) { _rule = rule; _tuple = tuple; } /// <summary> /// Rule related to the event. /// </summary> public IRuleDefinition Rule { get { return _rule.Definition; } } /// <summary> /// Tuple related to the event. /// </summary> public IEnumerable<FactInfo> Facts { get { return _tuple.Facts.Reverse().Select(t => new FactInfo(t)).ToArray(); } } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TwoFactOrGroupRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class TwoFactOrGroupRuleTest : BaseRuleTestFixture { [Test] public void Fire_NoMatchingFacts_DoesNotFire() { //Arrange //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_FactMatchingFirstPartOfOrGroup_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_FactsMatchingSecondPartOfOrGroup_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Invalid Value 1"}; var fact2 = new FactType2 { TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty }; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_FactsMatchingBothPartsOfOrGroup_FiresTwice() { //Arrange var fact11 = new FactType1 {TestProperty = "Valid Value 1"}; var fact12 = new FactType1 {TestProperty = "Invalid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact12.TestProperty}; Session.Insert(fact11); Session.Insert(fact12); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertFiredTwice(); } protected override void SetUpRules() { SetUpRule<TwoFactOrGroupRule>(); } } }<file_sep>/src/NRules/NRules/ActionOperation.cs namespace NRules { internal enum ActionOperationType { Insert, Update, Retract } internal class ActionOperation { public object Fact { get; private set; } public ActionOperationType OperationType { get; private set; } public ActionOperation(object fact, ActionOperationType operationType) { Fact = fact; OperationType = operationType; } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestAssets/INotifier.cs namespace NRules.IntegrationTests.TestAssets { public interface INotifier { void RuleActivated(); } }<file_sep>/src/NRules/NRules/RuleAction.cs using System; using System.Linq.Expressions; using NRules.Rete; using NRules.RuleModel; using NRules.Utilities; using Tuple = NRules.Rete.Tuple; namespace NRules { internal interface IRuleAction { void Invoke(IExecutionContext executionContext, IContext actionContext, Tuple tuple, FactIndexMap tupleFactMap); } internal class RuleAction : IRuleAction { private readonly LambdaExpression _expression; private readonly FactIndexMap _actionFactMap; private readonly FastDelegate<Action<object[]>> _compiledAction; public RuleAction(LambdaExpression expression, FactIndexMap actionFactMap) { _expression = expression; _actionFactMap = actionFactMap; _compiledAction = FastDelegate.Create<Action<object[]>>(expression); } public void Invoke(IExecutionContext context, IContext actionContext, Tuple tuple, FactIndexMap tupleFactMap) { var args = new object[_compiledAction.ParameterCount]; args[0] = actionContext; int index = tuple.Count - 1; foreach (var fact in tuple.Facts) { var mappedIndex = _actionFactMap.Map(tupleFactMap.Map(index)); FactIndexMap.SetElementAt(ref args, mappedIndex, 1, fact.Object); index--; } try { _compiledAction.Delegate.Invoke(args); } catch (Exception e) { bool isHandled; context.EventAggregator.RaiseActionFailed(context.Session, e, _expression, tuple, out isHandled); if (!isHandled) { throw new RuleActionEvaluationException("Failed to evaluate rule action", _expression.ToString(), e); } } } } }<file_sep>/src/NRules/NRules.RuleModel/CollectionAggregate.cs using System.Collections.Generic; namespace NRules.RuleModel { /// <summary> /// Aggregate that folds matching facts into a collection. /// </summary> /// <typeparam name="T">Type of facts to collect.</typeparam> internal class CollectionAggregate<T> : IAggregate { private readonly List<T> _items = new List<T>(); private bool _initialized; public AggregationResults Add(object fact) { _items.Add((T) fact); if (!_initialized) { _initialized = true; return AggregationResults.Added; } return AggregationResults.Modified; } public AggregationResults Modify(object fact) { return AggregationResults.None; } public AggregationResults Remove(object fact) { _items.Remove((T) fact); if (_items.Count > 0) { return AggregationResults.Modified; } return AggregationResults.Removed; } public object Result { get { return _items; } } } }<file_sep>/README.md # NRules NRules is an open source production rules engine for .NET, based on the [Rete](http://www.wikipedia.org/wiki/Rete_algorithm) matching algorithm. Rules are authored in C# using internal DSL. ## Installing NRules First, [install NuGet](http://docs.nuget.org/docs/start-here/installing-nuget). Then, install [NRules](https://www.nuget.org/packages/NRules) from the Package Manager Console: PM> Install-Package NRules ## Getting Started Use the following resources to get up and running with NRules. - [Getting Started Guide](https://github.com/NRules/NRules/wiki/Getting-Started) - [Wiki Documentation](https://github.com/NRules/NRules/wiki) - [API Documentation](http://nrules.net/api/index.html) - [Discussion Group](http://groups.google.com/group/nrules-users) -- Copyright &copy; 2012-2015 [<NAME>](https://github.com/snikolayev) under the [MIT license](LICENSE.txt). <file_sep>/src/NRules/Tests/NRules.IntegrationTests/TwoFactOneCollectionRuleTest.cs using System.Collections.Generic; using System.Linq; using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class TwoFactOneCollectionRuleTest : BaseRuleTestFixture { [Test] public void Fire_OneMatchingFactOfOneKindAndTwoOfAnother_FiresOnceWithTwoFactsInCollection() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = null}; var fact4 = new FactType2 {TestProperty = "Invalid Value 4", JoinProperty = fact1.TestProperty}; var fact5 = new FactType2 {TestProperty = "Valid Value 5", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); Session.Insert(fact5); //Act Session.Fire(); //Assert AssertFiredOnce(); Assert.AreEqual(2, GetFiredFact<IEnumerable<FactType2>>().Count()); } [Test] public void Fire_OneMatchingFactOfOneKindAndTwoOfAnotherThenFireThenAnotherMatchingFactThenFire_FiresOnceWithTwoFactsInCollectionThenFiresAgainWithThreeFacts() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact21 = new FactType2 {TestProperty = "Valid Value 21", JoinProperty = fact1.TestProperty}; var fact22 = new FactType2 {TestProperty = "Valid Value 22", JoinProperty = fact1.TestProperty}; var fact23 = new FactType2 {TestProperty = "Valid Value 23", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact21); Session.Insert(fact22); //Act Session.Fire(); var actualCount1 = GetFiredFact<IEnumerable<FactType2>>().Count(); Session.Insert(fact23); Session.Fire(); var actualCount2 = GetFiredFact<IEnumerable<FactType2>>().Count(); //Assert AssertFiredTwice(); Assert.AreEqual(2, actualCount1); Assert.AreEqual(3, actualCount2); } [Test] public void Fire_OneMatchingFactOfOneKindAndTwoOfAnotherThenAnotherMatchingFactThenFire_FiresOnceWithThreeFactsInCollection() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact21 = new FactType2 {TestProperty = "Valid Value 21", JoinProperty = fact1.TestProperty}; var fact22 = new FactType2 {TestProperty = "Valid Value 22", JoinProperty = fact1.TestProperty}; var fact23 = new FactType2 {TestProperty = "Valid Value 23", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact21); Session.Insert(fact22); Session.Insert(fact23); //Act Session.Fire(); var actualCount = GetFiredFact<IEnumerable<FactType2>>().Count(); //Assert AssertFiredOnce(); Assert.AreEqual(3, actualCount); } [Test] public void Fire_FactOfOneKindIsValidAndTwoOfAnotherKindAreAssertedThenOneRetracted_FiresOnceWithOneFactInCollection() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Retract(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); Assert.AreEqual(1, GetFiredFact<IEnumerable<FactType2>>().Count()); } [Test] public void Fire_FactOfOneKindIsValidAndTwoOfAnotherKindAreAssertedThenRetracted_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Retract(fact2); Session.Retract(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_FactOfOneKindIsInvalidAndTwoOfAnotherKindAreValid_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Invalid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Invalid Value 3", JoinProperty = fact1.TestProperty}; var fact4 = new FactType2 {TestProperty = "Valid Value 4", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_FactOfOneKindIsAssertedThenRetractedAndTwoOfAnotherKindAreValid_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Invalid Value 3", JoinProperty = fact1.TestProperty}; var fact4 = new FactType2 {TestProperty = "Valid Value 4", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); Session.Retract(fact1); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_FactOfOneKindIsAssertedThenUpdatedToInvalidAndTwoOfAnotherKindAreValid_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Invalid Value 3", JoinProperty = fact1.TestProperty}; var fact4 = new FactType2 {TestProperty = "Valid Value 4", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); fact1.TestProperty = "Invalid Value 1"; Session.Update(fact1); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_TwoFactsOfOneKindAndAggregatedFactsMatchingOneOfTheFacts_FiresOnce() { //Arrange var fact11 = new FactType1 {TestProperty = "Valid Value 1"}; var fact12 = new FactType1 {TestProperty = "Valid Value 2"}; var fact21 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact11.TestProperty}; var fact22 = new FactType2 {TestProperty = "Valid Value 4", JoinProperty = fact11.TestProperty}; Session.Insert(fact11); Session.Insert(fact12); Session.Insert(fact21); Session.Insert(fact22); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_TwoFactsOfOneKindAndAggregatedFactsMatchingBothOfTheFacts_FiresTwiceWithCorrectCounts() { //Arrange var fact11 = new FactType1 {TestProperty = "Valid Value 1"}; var fact12 = new FactType1 {TestProperty = "Valid Value 2"}; var fact21 = new FactType2 {TestProperty = "Valid Value 3", JoinProperty = fact11.TestProperty}; var fact22 = new FactType2 {TestProperty = "Valid Value 4", JoinProperty = fact11.TestProperty}; var fact23 = new FactType2 {TestProperty = "Valid Value 5", JoinProperty = fact12.TestProperty}; Session.Insert(fact11); Session.Insert(fact12); Session.Insert(fact21); Session.Insert(fact22); Session.Insert(fact23); //Act Session.Fire(); //Assert AssertFiredTwice(); Assert.AreEqual(2, GetFiredFact<IEnumerable<FactType2>>(0).Count()); Assert.AreEqual(1, GetFiredFact<IEnumerable<FactType2>>(1).Count()); } protected override void SetUpRules() { SetUpRule<TwoFactOneCollectionRule>(); } } }<file_sep>/src/NRules/NRules/Rete/JoinNode.cs using System.Collections.Generic; namespace NRules.Rete { internal class JoinNode : BetaNode { public JoinNode(ITupleSource leftSource, IObjectSource rightSource) : base(leftSource, rightSource) { } public override void PropagateAssert(IExecutionContext context, Tuple tuple) { IEnumerable<Fact> facts = RightSource.GetFacts(context); foreach (Fact fact in facts) { if (MatchesConditions(context, tuple, fact)) { MemoryNode.PropagateAssert(context, tuple, fact); } } } public override void PropagateUpdate(IExecutionContext context, Tuple tuple) { IEnumerable<Fact> facts = RightSource.GetFacts(context); foreach (Fact fact in facts) { if (MatchesConditions(context, tuple, fact)) { MemoryNode.PropagateUpdate(context, tuple, fact); } else { MemoryNode.PropagateRetract(context, tuple, fact); } } } public override void PropagateRetract(IExecutionContext context, Tuple tuple) { IEnumerable<Fact> facts = RightSource.GetFacts(context); foreach (Fact fact in facts) { MemoryNode.PropagateRetract(context, tuple, fact); } } public override void PropagateAssert(IExecutionContext context, Fact fact) { IEnumerable<Tuple> tuples = LeftSource.GetTuples(context); foreach (Tuple tuple in tuples) { if (MatchesConditions(context, tuple, fact)) { MemoryNode.PropagateAssert(context, tuple, fact); } } } public override void PropagateUpdate(IExecutionContext context, Fact fact) { IEnumerable<Tuple> tuples = LeftSource.GetTuples(context); foreach (Tuple tuple in tuples) { if (MatchesConditions(context, tuple, fact)) { MemoryNode.PropagateUpdate(context, tuple, fact); } else { MemoryNode.PropagateRetract(context, tuple, fact); } } } public override void PropagateRetract(IExecutionContext context, Fact fact) { IEnumerable<Tuple> tuples = LeftSource.GetTuples(context); foreach (Tuple tuple in tuples) { MemoryNode.PropagateRetract(context, tuple, fact); } } public override void Accept<TContext>(TContext context, ReteNodeVisitor<TContext> visitor) { visitor.VisitJoinNode(context, this); } } }<file_sep>/src/NRules/NRules.Fluent/CollectExpressionBuilder.cs using System; using System.Linq.Expressions; using NRules.Fluent.Dsl; using NRules.Fluent.Expressions; using NRules.RuleModel.Builders; namespace NRules.Fluent { internal class CollectExpressionBuilder<TCollection> : ExpressionBuilderDecorator, ICollectPattern<TCollection> { private readonly PatternBuilder _patternBuilder; public CollectExpressionBuilder(ExpressionBuilder builder, PatternBuilder patternBuilder) : base(builder) { _patternBuilder = patternBuilder; } public ILeftHandSide Where(params Expression<Func<TCollection, bool>>[] conditions) { foreach (var condition in conditions) { var rewriter = new ConditionRewriter(_patternBuilder.Declaration, _patternBuilder.Declarations); var rewrittenCondition = rewriter.Rewrite(condition); _patternBuilder.Condition(rewrittenCondition); } return Builder; } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestRules/CollectionWithConditionsRule.cs using System.Collections.Generic; using System.Linq; using NRules.IntegrationTests.TestAssets; namespace NRules.IntegrationTests.TestRules { public class CollectionWithConditionsRule : BaseRule { public override void Define() { IEnumerable<FactType1> collection1 = null; When() .Collect<FactType1>(() => collection1, f => f.TestProperty.StartsWith("Valid")).Where(x => x.Count() > 2); Then() .Do(ctx => Action()); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/ThreeFactOrGroupRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class ThreeFactOrGroupRuleTest : BaseRuleTestFixture { [Test] public void Fire_MatchingMainFactAndNoneOfOrGroup_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingMainFactAndFirstPartOfOrGroup_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingMainFactAndSecondPartOfOrGroup_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 { TestProperty = "Invalid Value 2", JoinProperty = fact1.TestProperty }; var fact3 = new FactType3 { TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty }; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingMainFactAndBothPartsOfOrGroup_FiresTwice() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType2 {TestProperty = "Invalid Value 3", JoinProperty = fact1.TestProperty}; var fact4 = new FactType3 {TestProperty = "Valid Value 4", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Insert(fact4); //Act Session.Fire(); //Assert AssertFiredTwice(); } [Test] public void Fire_MatchingMainFactAndOnePartOfOrGroupAndMainFactRetracted_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Retract(fact1); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingMainFactAndOnePartOfOrGroupAndMainFactUpdatedToInvalid_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); fact1.TestProperty = "Invalid Value"; Session.Update(fact1); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingMainFactAndOnePartOfOrGroupAndGroupFactRetracted_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Retract(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingMainFactAndOnePartOfOrGroupAndGroupFactUpdatedToInvalid_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); fact2.TestProperty = "Invalid Value"; Session.Update(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } protected override void SetUpRules() { SetUpRule<ThreeFactOrGroupRule>(); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/PriorityTest.cs using System.Collections.Generic; using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class PriorityTest : BaseRuleTestFixture { [Test] public void Fire_LowPriorityActivatesTwiceTriggersHighPriority_HighPriorityPreemptsLowPriority() { //Arrange var invokedRules = new List<string>(); Session.Events.RuleFiredEvent += (sender, args) => invokedRules.Add(args.Rule.Name); var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert //low priority activates twice //it runs once, activates high priority rule, which preempts low priority and fires once //low priority fires second time, which activates high priority which also fires second time Assert.AreEqual(4, invokedRules.Count); Assert.AreEqual("NRules.IntegrationTests.TestRules.PriorityLowRule", invokedRules[0]); Assert.AreEqual("NRules.IntegrationTests.TestRules.PriorityHighRule", invokedRules[1]); Assert.AreEqual("NRules.IntegrationTests.TestRules.PriorityLowRule", invokedRules[2]); Assert.AreEqual("NRules.IntegrationTests.TestRules.PriorityHighRule", invokedRules[3]); } protected override void SetUpRules() { SetUpRule<PriorityLowRule>(); SetUpRule<PriorityHighRule>(); } } }<file_sep>/src/NRules/Tests/NRules.Tests/Collections/OrderedPriorityQueueTest.cs using NRules.Collections; using NUnit.Framework; namespace NRules.Tests.Collections { [TestFixture] public class OrderedPriorityQueueTest { [Test] public void Queue_Enqueue_DequeueReturnsByPriority() { //Arrange var queue = new OrderedPriorityQueue<int, string>(); //Act queue.Enqueue(1, "e"); queue.Enqueue(2, "d"); queue.Enqueue(3, "c"); queue.Enqueue(5, "a"); queue.Enqueue(4, "b"); //Assert Assert.AreEqual("a", queue.Dequeue()); Assert.AreEqual("b", queue.Dequeue()); Assert.AreEqual("c", queue.Dequeue()); Assert.AreEqual("d", queue.Dequeue()); Assert.AreEqual("e", queue.Dequeue()); } [Test] public void Queue_EnqueueWithDupPriorities_DequeueReturnsByPriorityThenByOrderOfInsertion() { //Arrange var queue = new OrderedPriorityQueue<int, string>(); //Act queue.Enqueue(1, "h"); queue.Enqueue(2, "e"); queue.Enqueue(2, "f"); queue.Enqueue(2, "g"); queue.Enqueue(3, "d"); queue.Enqueue(5, "a"); queue.Enqueue(4, "b"); queue.Enqueue(4, "c"); //Assert Assert.AreEqual("a", queue.Dequeue()); Assert.AreEqual("b", queue.Dequeue()); Assert.AreEqual("c", queue.Dequeue()); Assert.AreEqual("d", queue.Dequeue()); Assert.AreEqual("e", queue.Dequeue()); Assert.AreEqual("f", queue.Dequeue()); Assert.AreEqual("g", queue.Dequeue()); Assert.AreEqual("h", queue.Dequeue()); } } }<file_sep>/src/NRules/NRules/Rete/IObjectSink.cs namespace NRules.Rete { internal interface IObjectSink : INode { void PropagateAssert(IExecutionContext context, Fact fact); void PropagateUpdate(IExecutionContext context, Fact fact); void PropagateRetract(IExecutionContext context, Fact fact); } }<file_sep>/src/NRules/Tests/NRules.Tests/SessionTest.cs using Moq; using NRules.Diagnostics; using NRules.Rete; using NUnit.Framework; namespace NRules.Tests { [TestFixture] public class SessionTest { private Mock<IAgenda> _agenda; private Mock<INetwork> _network; private Mock<IWorkingMemory> _workingMemory; private Mock<IEventAggregator> _eventAggregator; [SetUp] public void Setup() { _agenda = new Mock<IAgenda>(); _network = new Mock<INetwork>(); _workingMemory = new Mock<IWorkingMemory>(); _eventAggregator = new Mock<IEventAggregator>(); } [Test] public void Insert_Always_PropagatesAssert() { // Arrange var fact = new object(); var target = CreateTarget(); // Act target.Insert(fact); // Assert _network.Verify(x => x.PropagateAssert(It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), fact), Times.Exactly(1)); } private Session CreateTarget() { return new Session(_network.Object, _agenda.Object, _workingMemory.Object, _eventAggregator.Object); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestAssets/FactType5.cs namespace NRules.IntegrationTests.TestAssets { public class FactType5 { public string TestProperty { get; set; } public int TestCount { get; set; } public void IncrementCount() { TestCount++; } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestRules/RuleWithMetadata.cs using NRules.Fluent.Dsl; using NRules.IntegrationTests.TestAssets; namespace NRules.IntegrationTests.TestRules { [Name("Rule with metadata"), Description("Rule description")] [Tag("Test"), Tag("Metadata")] public class RuleWithMetadata : BaseRule { public override void Define() { FactType1 fact1 = null; When() .Match<FactType1>(() => fact1, f => f.TestProperty.StartsWith("Valid")); Then() .Do(ctx => Action()); } } }<file_sep>/src/NRules/NRules/Agenda.cs using NRules.Rete; namespace NRules { internal interface IAgenda { bool HasActiveRules(); Activation NextActivation(); void Activate(Activation activation); void Deactivate(Activation activation); } internal class Agenda : IAgenda { private readonly ActivationQueue _activationQueue = new ActivationQueue(); public bool HasActiveRules() { return _activationQueue.HasActive(); } public Activation NextActivation() { Activation activation = _activationQueue.Dequeue(); return activation; } public void Activate(Activation activation) { _activationQueue.Enqueue(activation.Rule.Priority, activation); } public void Deactivate(Activation activation) { _activationQueue.Remove(activation); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/NodeSharingTest.cs using System.Linq; using NRules.Diagnostics; using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class NodeSharingTest : BaseRuleTestFixture { [Test] public void Fire_AlphaSelectionNodes_OnePerIntaCondition() { //Arrange var snapshotProvider = (ISessionSnapshotProvider) Session; var snapshot = snapshotProvider.GetSnapshot(); //Act var alphaNodesCount = snapshot.Nodes.Count(x => x.NodeType == NodeType.Selection); //Assert Assert.AreEqual(2, alphaNodesCount); } [Test] public void Fire_BetaJoinNodes_OnePerPattern() { //Arrange var snapshotProvider = (ISessionSnapshotProvider) Session; var snapshot = snapshotProvider.GetSnapshot(); //Act var betaJoinNodesCount = snapshot.Nodes.Count(x => x.NodeType == NodeType.Join); //Assert Assert.AreEqual(2, betaJoinNodesCount); } protected override void SetUpRules() { SetUpRule<TwinRuleOne>(); SetUpRule<TwinRuleTwo>(); } } }<file_sep>/src/NRules/NRules/Session.cs using System; using System.Linq; using NRules.Diagnostics; using NRules.Rete; namespace NRules { /// <summary> /// Represents a rules engine session. Created by <see cref="ISessionFactory"/>. /// Each session has its own working memory, and exposes operations that /// manipulate facts in it, as well as fire matching rules. /// </summary> /// <event cref="IEventProvider.FactInsertingEvent">Before processing fact insertion.</event> /// <event cref="IEventProvider.FactInsertedEvent">After processing fact insertion.</event> /// <event cref="IEventProvider.FactUpdatingEvent">Before processing fact update.</event> /// <event cref="IEventProvider.FactUpdatedEvent">After processing fact update.</event> /// <event cref="IEventProvider.FactRetractingEvent">Before processing fact retraction.</event> /// <event cref="IEventProvider.FactRetractedEvent">After processing fact retraction.</event> /// <event cref="IEventProvider.ActivationCreatedEvent">When a set of facts matches a rule.</event> /// <event cref="IEventProvider.ActivationDeletedEvent">When a set of facts no longer matches a rule.</event> /// <event cref="IEventProvider.RuleFiringEvent">Before rule's actions are executed.</event> /// <event cref="IEventProvider.RuleFiredEvent">After rule's actions are executed.</event> /// <event cref="IEventProvider.ConditionFailedEvent">When there is an error during condition evaluation, /// before throwing exception to the client.</event> /// <event cref="IEventProvider.ActionFailedEvent">When there is an error during action evaluation, /// before throwing exception to the client.</event> /// <exception cref="RuleConditionEvaluationException">Error while evaluating any of the rules' conditions. /// This exception can also be observed as an event <see cref="IEventProvider.ConditionFailedEvent"/>.</exception> /// <exception cref="RuleActionEvaluationException">Error while evaluating any of the rules' actions. /// This exception can also be observed as an event <see cref="IEventProvider.ActionFailedEvent"/>.</exception> /// <threadsafety instance="false" /> public interface ISession { /// <summary> /// Provider of rule session events. Use it to subscribe to various rules engine lifecycle events. /// </summary> IEventProvider Events { get; } /// <summary> /// Adds a new fact to the rules engine memory. /// </summary> /// <param name="fact">Fact to add.</param> /// <exception cref="ArgumentException">If fact already exists in working memory.</exception> void Insert(object fact); /// <summary> /// Updates existing fact in the rules engine memory. /// </summary> /// <param name="fact">Fact to update.</param> /// <exception cref="ArgumentException">If fact does not exist in working memory.</exception> void Update(object fact); /// <summary> /// Removes existing fact from the rules engine memory. /// </summary> /// <param name="fact">Fact to remove.</param> /// <exception cref="ArgumentException">If fact does not exist in working memory.</exception> void Retract(object fact); /// <summary> /// Starts rules execution cycle. /// This method blocks until there are no more rules to fire. /// </summary> void Fire(); /// <summary> /// Creates a LINQ query to retrieve facts of a given type from the rules engine's memory. /// </summary> /// <typeparam name="TFact">Type of facts to query. Use <see cref="object"/> to query all facts.</typeparam> /// <returns>Queryable working memory of the rules engine.</returns> IQueryable<TFact> Query<TFact>(); } /// <summary> /// See <see cref="ISession"/>. /// </summary> public sealed class Session : ISession, ISessionSnapshotProvider { private readonly IAgenda _agenda; private readonly INetwork _network; private readonly IWorkingMemory _workingMemory; private readonly IEventAggregator _eventAggregator; private readonly IExecutionContext _executionContext; internal Session(INetwork network, IAgenda agenda, IWorkingMemory workingMemory, IEventAggregator eventAggregator) { _network = network; _workingMemory = workingMemory; _agenda = agenda; _eventAggregator = eventAggregator; _executionContext = new ExecutionContext(this, _workingMemory, _agenda, _eventAggregator); _network.Activate(_executionContext); } public IEventProvider Events { get { return _eventAggregator; } } public void Insert(object fact) { _network.PropagateAssert(_executionContext, fact); } public void Update(object fact) { _network.PropagateUpdate(_executionContext, fact); } public void Retract(object fact) { _network.PropagateRetract(_executionContext, fact); } public void Fire() { while (_agenda.HasActiveRules()) { Activation activation = _agenda.NextActivation(); ICompiledRule rule = activation.Rule; var actionContext = new ActionContext(rule.Definition); _eventAggregator.RaiseRuleFiring(this, activation); foreach (IRuleAction action in rule.Actions) { action.Invoke(_executionContext, actionContext, activation.Tuple, activation.TupleFactMap); ApplyActionOperations(actionContext); } _eventAggregator.RaiseRuleFired(this, activation); if (actionContext.IsHalted) break; } } private void ApplyActionOperations(ActionContext actionContext) { while (actionContext.Operations.Count > 0) { var operation = actionContext.Operations.Dequeue(); switch (operation.OperationType) { case ActionOperationType.Insert: Insert(operation.Fact); break; case ActionOperationType.Update: Update(operation.Fact); break; case ActionOperationType.Retract: Retract(operation.Fact); break; } } } public IQueryable<TFact> Query<TFact>() { return _workingMemory.Facts.Select(x => x.Object).OfType<TFact>().AsQueryable(); } SessionSnapshot ISessionSnapshotProvider.GetSnapshot() { var builder = new SnapshotBuilder(); var visitor = new SessionSnapshotVisitor(_workingMemory); _network.Visit(builder, visitor); return builder.Build(); } } }<file_sep>/src/NRules.Debugger.Visualizer/NRules.Debugger.Visualizer/Properties/AssemblyInfo.cs using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using NRules.Debugger.Visualizer; [assembly: AssemblyTitle("NRules.Debugger.Visualizer")] [assembly: AssemblyDescription("Visual Studio Debugger Visualizer for NRules")] [assembly: ComVisible(false)] [assembly: DebuggerVisualizer( typeof(SessionVisualizer), typeof(SessionObjectSource), Target = typeof (NRules.Session), Description = "NRules Session Visualizer")]<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestRules/OneFactOneNotRule.cs using NRules.IntegrationTests.TestAssets; namespace NRules.IntegrationTests.TestRules { public class OneFactOneNotRule : BaseRule { public override void Define() { When() .Not<FactType1>(f => f.TestProperty.StartsWith("Valid")); Then() .Do(ctx => Action()); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/OneFactRuleTest.cs using System; using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class OneFactRuleTest : BaseRuleTestFixture { [Test] public void Fire_OneMatchingFact_FiresOnce() { //Arrange var fact = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_TwoMatchingFacts_FiresTwice() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertFiredTwice(); } [Test] public void Fire_ConditionDoesNotMatch_DoesNotFire() { //Arrange var fact = new FactType1 {TestProperty = "Invalid Value 1"}; Session.Insert(fact); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_OneMatchingFactAssertedAndRetracted_DoesNotFire() { //Arrange var fact = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact); Session.Retract(fact); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_OneFactUpdatedFromInvalidToMatching_FiresOnce() { //Arrange var fact = new FactType1 {TestProperty = "Invalid Value 1"}; Session.Insert(fact); fact.TestProperty = "Valid Value 1"; Session.Update(fact); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_OneMatchingFactAssertedAndRetractedAndAssertedAgain_FiresOnce() { //Arrange var fact = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact); Session.Retract(fact); Session.Insert(fact); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_OneMatchingFactAssertedAndUpdatedToInvalid_DoesNotFire() { //Arrange var fact = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact); fact.TestProperty = "Invalid Value 1"; Session.Update(fact); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test, Ignore("TODO: Rework retract logic to not re-evaluate conditions")] public void Fire_OneMatchingFactAssertedAndModifiedAndRetracted_DoesNotFire() { //Arrange var fact = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact); fact.TestProperty = "Invalid Value 1"; Session.Retract(fact); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_DuplicateInsert_Throws() { //Arrange var fact = new FactType1 {TestProperty = "Valid Value 1"}; //Act - Assert Session.Insert(fact); Assert.Throws<ArgumentException>(() => Session.Insert(fact)); } [Test] public void Fire_UpdateWithoutInsert_Throws() { //Arrange var fact = new FactType1 {TestProperty = "Valid Value 1"}; //Act - Assert Assert.Throws<ArgumentException>(() => Session.Update(fact)); } [Test] public void Fire_RetractWithoutInsert_Throws() { //Arrange var fact = new FactType1 {TestProperty = "Valid Value 1"}; //Act - Assert Assert.Throws<ArgumentException>(() => Session.Retract(fact)); } protected override void SetUpRules() { SetUpRule<OneFactRule>(); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/RulesLoadTest.cs using System.Linq; using System.Reflection; using NRules.Fluent; using NRules.IntegrationTests.TestRules; using NRules.RuleModel; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class RulesLoadTest { [Test] public void Load_AssemblyWithoutRules_Empty() { //Arrange RuleRepository target = CreateTarget(); //Act target.Load(x => x.From(typeof (string).Assembly)); IRuleSet ruleSet = target.GetRuleSets().First(); //Assert Assert.AreEqual(0, ruleSet.Rules.Count()); } [Test] public void Load_InvalidTypes_Empty() { //Arrange RuleRepository target = CreateTarget(); //Act target.Load(x => x.From(typeof (string))); IRuleSet ruleSet = target.GetRuleSets().First(); //Assert Assert.AreEqual(0, ruleSet.Rules.Count()); } [Test] public void Load_AssemblyWithRulesToNamedRuleSet_RuleSetNameMatches() { //Arrange RuleRepository target = CreateTarget(); //Act target.Load(x => x.From(ThisAssembly).To("Test")); IRuleSet ruleSet = target.GetRuleSets().First(); //Assert Assert.AreEqual("Test", ruleSet.Name); } [Test] public void Load_AssemblyWithRulesToDefaultRuleSet_DefaultRuleSetName() { //Arrange RuleRepository target = CreateTarget(); //Act target.Load(x => x.From(ThisAssembly)); IRuleSet ruleSet = target.GetRuleSets().First(); //Assert Assert.AreEqual("default", ruleSet.Name); } [Test] public void Load_FilterRuleByName_MatchingRule() { //Arrange RuleRepository target = CreateTarget(); //Act target.Load(x => x.From(ThisAssembly).Where(r => r.Name.Contains("PriorityLowRule"))); IRuleSet ruleSet = target.GetRuleSets().First(); //Assert Assert.AreEqual(1, ruleSet.Rules.Count()); Assert.AreEqual(typeof (PriorityLowRule).FullName, ruleSet.Rules.First().Name); } [Test] public void Load_FilterRuleByTag_MatchingRule() { //Arrange RuleRepository target = CreateTarget(); //Act target.Load(x => x.From(ThisAssembly).Where(r => r.IsTagged("Test"))); IRuleSet ruleSet = target.GetRuleSets().First(); //Assert Assert.AreEqual(1, ruleSet.Rules.Count()); Assert.AreEqual("Rule with metadata", ruleSet.Rules.First().Name); } private static Assembly ThisAssembly { get { return Assembly.GetExecutingAssembly(); } } public RuleRepository CreateTarget() { return new RuleRepository(); } } }<file_sep>/src/NRules/NRules/ExecutionContext.cs using NRules.Diagnostics; namespace NRules { internal interface IExecutionContext { ISession Session { get; } IWorkingMemory WorkingMemory { get; } IAgenda Agenda { get; } IEventAggregator EventAggregator { get; } } internal class ExecutionContext : IExecutionContext { public ExecutionContext(ISession session, IWorkingMemory workingMemory, IAgenda agenda, IEventAggregator eventAggregator) { Session = session; WorkingMemory = workingMemory; Agenda = agenda; EventAggregator = eventAggregator; } public ISession Session { get; private set; } public IWorkingMemory WorkingMemory { get; private set; } public IAgenda Agenda { get; private set; } public IEventAggregator EventAggregator { get; private set; } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TwoFactOneNotRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class TwoFactOneNotRuleTest : BaseRuleTestFixture { [Test] public void Fire_MatchingNotPatternFacts_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingNotPatternFactAssertedThenRetracted_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Retract(fact2); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingNotPatternFactAssertedThenUpdatedToInvalid_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); fact2.TestProperty = "Invalid Value 2"; Session.Update(fact2); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingFactAndNoFactsMatchingNotPattern_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_TwoMatchingFactsAndNoFactsMatchingNotPattern_FiresTwice() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType1 {TestProperty = "Valid Value 2"}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertFiredTwice(); } [Test] public void Fire_TwoMatchingFactsAndOneFactMatchingNotPattern_FiresOnce() { //Arrange var fact11 = new FactType1 { TestProperty = "Valid Value 1" }; var fact12 = new FactType1 { TestProperty = "Valid Value 2" }; var fact21 = new FactType2 { TestProperty = "Valid Value 3", JoinProperty = fact11.TestProperty}; Session.Insert(fact11); Session.Insert(fact12); Session.Insert(fact21); //Act Session.Fire(); //Assert AssertFiredOnce(); } protected override void SetUpRules() { SetUpRule<TwoFactOneNotRule>(); } } }<file_sep>/src/NRules/NRules/Rete/SelectionNode.cs using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace NRules.Rete { internal class SelectionNode : AlphaNode { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public IList<IAlphaCondition> Conditions { get; private set; } public SelectionNode(IAlphaCondition condition) { Conditions = new List<IAlphaCondition>(); Conditions.Add(condition); } public override bool IsSatisfiedBy(IExecutionContext context, Fact fact) { return Conditions.All(c => c.IsSatisfiedBy(context, fact)); } public override void Accept<TContext>(TContext context, ReteNodeVisitor<TContext> visitor) { visitor.VisitSelectionNode(context, this); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/SessionQueryTest.cs using System.Linq; using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class SessionQueryTest : BaseRuleTestFixture { [Test] public void Query_NoFacts_Empty() { //Arrange //Act var query = Session.Query<object>(); var facts = query.ToList(); //Assert Assert.AreEqual(0, facts.Count); } [Test] public void Query_OneFact_RetrievesFactFromQuery() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); //Act var query = Session.Query<object>(); var facts = query.ToList(); //Assert Assert.AreEqual(1, facts.Count); Assert.AreSame(fact1, facts[0]); } [Test] public void Query_RuleInsertsSecondFact_TwoFactsInMemory() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); Session.Fire(); //Act var query = Session.Query<object>(); var facts = query.ToList(); //Assert Assert.AreEqual(2, facts.Count); } [Test] public void Query_QueryFactsByType_OnlyReturnsFactsOfThatType() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); Session.Fire(); //Act var query = Session.Query<FactType2>(); var facts = query.ToList(); //Assert Assert.AreEqual(1, facts.Count); Assert.AreEqual(fact1.TestProperty, facts[0].JoinProperty); } protected override void SetUpRules() { SetUpRule<ForwardChainingFirstRule>(); } } }<file_sep>/src/NRules/NRules/Properties/AssemblyInfo.cs using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; [assembly: AssemblyTitle("NRules")] [assembly: AssemblyDescription("Business rules engine for .NET")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("NRules.Tests")] [assembly: InternalsVisibleTo("NRules.IntegrationTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]<file_sep>/src/NRules/NRules/RuleExecutionException.cs using System; using System.Runtime.Serialization; using System.Security; namespace NRules { /// <summary> /// Represents errors that occur during rules execution. /// </summary> [Serializable] public class RuleExecutionException : Exception { internal RuleExecutionException(string message, Exception innerException) : base(message, innerException) { } [SecuritySafeCritical] protected RuleExecutionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/IdentityMatchRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class IdentityMatchRuleTest : BaseRuleTestFixture { [Test] public void Fire_MatchingFact_FiresOnce() { //Arrange var fact = new FactType1 {TestProperty = "Valid value"}; Session.Insert(fact); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_TwoMatchingFacts_FiresTwice() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid value"}; Session.Insert(fact1); var fact2 = new FactType1 {TestProperty = "Valid value"}; Session.Insert(fact2); //Act Session.Fire(); //Assert AssertFiredTwice(); } [Test] public void Fire_MatchingFactInsertedAndRetracted_DoesNotFire() { //Arrange var fact = new FactType1 { TestProperty = "Valid value" }; Session.Insert(fact); Session.Retract(fact); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingFactInsertedAndUpdatedToInvalid_DoesNotFire() { //Arrange var fact = new FactType1 { TestProperty = "Valid value" }; Session.Insert(fact); fact.TestProperty = "Invalid value"; Session.Update(fact); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_NoMatchingFact_DoesNotFire() { //Arrange //Act Session.Fire(); //Assert AssertDidNotFire(); } protected override void SetUpRules() { SetUpRule<IdentityMatchRule>(); } } }<file_sep>/src/NRules/NRules.Fluent/RuleActivator.cs using System; using NRules.Fluent.Dsl; namespace NRules.Fluent { /// <summary> /// Rule activator that instantiates rules based on the .NET types. /// Default activator uses .NET reflection activator. /// </summary> public interface IRuleActivator { /// <summary> /// Creates an instance of a rule from a .NET type. /// </summary> /// <param name="type">Rule type.</param> /// <returns>Rule instance.</returns> Rule Activate(Type type); } internal class RuleActivator : IRuleActivator { public Rule Activate(Type type) { return (Rule) Activator.CreateInstance(type); } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/ThreeFactTwoNotRuleTest.cs using NRules.IntegrationTests.TestAssets; using NRules.IntegrationTests.TestRules; using NUnit.Framework; namespace NRules.IntegrationTests { [TestFixture] public class ThreeFactTwoNotRuleTest : BaseRuleTestFixture { [Test] public void Fire_NotMatchingNotPatternFacts_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; Session.Insert(fact1); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingNotPatternFactsBothKind_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingNotPatternFactsFirst_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingNotPatternFactsSecondKind_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingNotPatternFactsInsertedThenRetracted_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Retract(fact2); Session.Retract(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingNotPatternFactsTwoInsertedThenFirstRetracted_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Retract(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingNotPatternFactsTwoInsertedThenSecondRetracted_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); Session.Retract(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_InvalidNotPatternFactsInsertedThenUpdated_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Invalid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Invalid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); fact2.TestProperty = "Valid Value 2"; Session.Update(fact2); fact3.TestProperty = "Valid Value 3"; Session.Update(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingNotPatternFactsInsertedThenUpdated_FiresOnce() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); fact2.TestProperty = "Invalid Value 2"; Session.Update(fact2); fact3.TestProperty = "Invalid Value 3"; Session.Update(fact3); //Act Session.Fire(); //Assert AssertFiredOnce(); } [Test] public void Fire_MatchingNotPatternFactsTwoInsertedThenFirstUpdated_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); fact2.TestProperty = "Invalid Value 2"; Session.Update(fact2); //Act Session.Fire(); //Assert AssertDidNotFire(); } [Test] public void Fire_MatchingNotPatternFactsTwoInsertedThenSecondUpdated_DoesNotFire() { //Arrange var fact1 = new FactType1 {TestProperty = "Valid Value 1"}; var fact2 = new FactType2 {TestProperty = "Valid Value 2", JoinProperty = fact1.TestProperty}; var fact3 = new FactType3 {TestProperty = "Valid Value 3", JoinProperty = fact1.TestProperty}; Session.Insert(fact1); Session.Insert(fact2); Session.Insert(fact3); fact3.TestProperty = "Invalid Value 3"; Session.Update(fact3); //Act Session.Fire(); //Assert AssertDidNotFire(); } protected override void SetUpRules() { SetUpRule<ThreeFactTwoNotRule>(); } } }<file_sep>/src/NRules/NRules.Fluent/Properties/AssemblyInfo.cs using System; using System.Reflection; using System.Runtime.InteropServices; using System.Security; [assembly: AssemblyTitle("NRules.Fluent")] [assembly: AssemblyDescription("Internal DSL for NRules")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] [assembly: AllowPartiallyTrustedCallers]<file_sep>/src/NRules/NRules/Rete/AggregateNode.cs using System; using NRules.RuleModel; namespace NRules.Rete { internal class AggregateNode : BetaNode { private readonly Func<IAggregate> _aggregateFactory; public Type AggregateType { get; private set; } public AggregateNode(ITupleSource leftSource, IObjectSource rightSource, Type aggregateType) : base(leftSource, rightSource) { AggregateType = aggregateType; _aggregateFactory = () => (IAggregate) Activator.CreateInstance(aggregateType); } public override void PropagateAssert(IExecutionContext context, Tuple tuple) { IAggregate aggregate = GetAggregate(tuple); var matchingFacts = MatchingFacts(context, tuple); foreach (var matchingFact in matchingFacts) { var result = aggregate.Add(matchingFact.Object); HandleAggregateResult(context, result, tuple, aggregate); } } public override void PropagateUpdate(IExecutionContext context, Tuple tuple) { IAggregate aggregate = GetAggregate(tuple); Fact aggregateFact = context.WorkingMemory.GetFact(aggregate.Result); PropagateAggregateUpdate(context, tuple, aggregateFact); } public override void PropagateRetract(IExecutionContext context, Tuple tuple) { IAggregate aggregate = GetAggregate(tuple); Fact aggregateFact = context.WorkingMemory.GetFact(aggregate.Result); PropagateAggregateRetract(context, tuple, aggregateFact); } public override void PropagateAssert(IExecutionContext context, Fact fact) { var tuples = MatchingTuples(context, fact); foreach (var tuple in tuples) { IAggregate aggregate = GetAggregate(tuple); var result = aggregate.Add(fact.Object); HandleAggregateResult(context, result, tuple, aggregate); } } public override void PropagateUpdate(IExecutionContext context, Fact fact) { var tuples = MatchingTuples(context, fact); foreach (var tuple in tuples) { IAggregate aggregate = GetAggregate(tuple); var result = aggregate.Modify(fact.Object); HandleAggregateResult(context, result, tuple, aggregate); } } public override void PropagateRetract(IExecutionContext context, Fact fact) { var tuples = MatchingTuples(context, fact); foreach (var tuple in tuples) { IAggregate aggregate = GetAggregate(tuple); var result = aggregate.Remove(fact.Object); HandleAggregateResult(context, result, tuple, aggregate); } } public override void Accept<TContext>(TContext context, ReteNodeVisitor<TContext> visitor) { visitor.VisitAggregateNode(context, this); } private void HandleAggregateResult(IExecutionContext context, AggregationResults result, Tuple leftTuple, IAggregate aggregate) { Fact aggregateFact = GetAggregateFact(context, aggregate); switch (result) { case AggregationResults.Added: PropagateAggregateAssert(context, leftTuple, aggregateFact); break; case AggregationResults.Modified: PropagateAggregateUpdate(context, leftTuple, aggregateFact); break; case AggregationResults.Removed: PropagateAggregateRetract(context, leftTuple, aggregateFact); break; } } private void PropagateAggregateAssert(IExecutionContext context, Tuple tuple, Fact aggregateFact) { if (aggregateFact != null) { MemoryNode.PropagateAssert(context, tuple, aggregateFact); } } private void PropagateAggregateUpdate(IExecutionContext context, Tuple tuple, Fact aggregateFact) { if (aggregateFact != null) { MemoryNode.PropagateUpdate(context, tuple, aggregateFact); } } private void PropagateAggregateRetract(IExecutionContext context, Tuple tuple, Fact aggregateFact) { if (aggregateFact != null) { MemoryNode.PropagateRetract(context, tuple, aggregateFact); } } private IAggregate GetAggregate(Tuple tuple) { var aggregate = tuple.GetState<IAggregate>(this); if (aggregate == null) { aggregate = _aggregateFactory(); tuple.SetState(this, aggregate); } return aggregate; } private Fact GetAggregateFact(IExecutionContext context, IAggregate aggregate) { if (aggregate.Result == null) return null; Fact fact = context.WorkingMemory.GetFact(aggregate.Result); if (fact == null) { fact = new Fact(aggregate.Result); context.WorkingMemory.SetFact(fact); } return fact; } } }<file_sep>/src/NRules/NRules/Rete/RuleNode.cs namespace NRules.Rete { internal interface IRuleNode : INode { void Activate(IExecutionContext context, Tuple tuple, FactIndexMap tupleFactMap); void Deactivate(IExecutionContext context, Tuple tuple, FactIndexMap tupleFactMap); } internal class RuleNode : IRuleNode { public ICompiledRule Rule { get; private set; } public RuleNode(ICompiledRule rule) { Rule = rule; } public void Activate(IExecutionContext context, Tuple tuple, FactIndexMap tupleFactMap) { var activation = new Activation(Rule, tuple, tupleFactMap); context.Agenda.Activate(activation); context.EventAggregator.RaiseActivationCreated(context.Session, activation); } public void Deactivate(IExecutionContext context, Tuple tuple, FactIndexMap tupleFactMap) { var activation = new Activation(Rule, tuple, tupleFactMap); context.Agenda.Deactivate(activation); context.EventAggregator.RaiseActivationDeleted(context.Session, activation); } public void Accept<TContext>(TContext context, ReteNodeVisitor<TContext> visitor) { visitor.VisitRuleNode(context, this); } } }<file_sep>/samples/SimpleRules/SimpleRules/Rules/MultipleOrdersRule.cs using System; using System.Collections.Generic; using System.Linq; using NRules.Fluent.Dsl; using NRules.Samples.SimpleRules.Domain; namespace NRules.Samples.SimpleRules.Rules { public class MultipleOrdersRule : Rule { public override void Define() { Customer customer = null; IEnumerable<Order> orders = null; When() .Match<Customer>(() => customer, c => c.IsPreferred) .Collect<Order>(() => orders, o => o.Customer == customer, o => o.IsOpen) .Where(x => x.Count() >= 3); Then() .Do(ctx => Console.WriteLine("Customer {0} has over 3 open orders", customer.Name)); } } }<file_sep>/src/NRules/NRules.RuleModel/IContext.cs namespace NRules.RuleModel { /// <summary> /// Rules engine execution context. /// Can be used by rules to interact with the rules engine, i.e. insert, update, retract facts. /// </summary> public interface IContext { /// <summary> /// Current rule definition. /// </summary> IRuleDefinition Rule { get; } /// <summary> /// Halts rules execution. The engine continues execution of the current rule and exits the execution cycle. /// </summary> void Halt(); /// <summary> /// Inserts a new fact into the rules engine's memory. /// </summary> /// <param name="fact">New fact to insert.</param> void Insert(object fact); /// <summary> /// Updates existing fact in the rules engine's memory. /// </summary> /// <param name="fact">Existing fact to update.</param> void Update(object fact); /// <summary> /// Removes existing fact from the rules engine's memory. /// </summary> /// <param name="fact">Existing fact to remove.</param> void Retract(object fact); } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestAssets/BaseRule.cs using System; using NRules.Fluent.Dsl; namespace NRules.IntegrationTests.TestAssets { public abstract class BaseRule : Rule { protected BaseRule() { Action = () => { }; } public Action Action { get; set; } } }<file_sep>/src/NRules/NRules.Fluent/Dsl/ICollectPattern.cs using System; using System.Linq.Expressions; namespace NRules.Fluent.Dsl { /// <summary> /// Expression builder for optional additional conditions on collection pattern. /// </summary> /// <typeparam name="TCollection">Type of collection.</typeparam> public interface ICollectPattern<TCollection> : ILeftHandSide { /// <summary> /// Optional conditions on the collection pattern. /// </summary> /// <param name="conditions">Collection conditions.</param> /// <returns>Left hand side expression builder.</returns> ILeftHandSide Where(params Expression<Func<TCollection, bool>>[] conditions); } }<file_sep>/src/NRules/NRules/Utilities/FastDelegate.cs using System; using System.Collections.Generic; using System.Linq.Expressions; namespace NRules.Utilities { internal abstract class FastDelegate { public static FastDelegate<TDelegate> Create<TDelegate>(LambdaExpression expression) where TDelegate : class { if (!typeof(TDelegate).IsSubclassOf(typeof(Delegate))) { throw new InvalidOperationException( string.Format("Type {0} is not a delegate", typeof(TDelegate).FullName)); } var optimizer = new ExpressionOptimizer<TDelegate>(); Expression<TDelegate> optimizedExpression = optimizer.CompactParameters(expression); TDelegate @delegate = optimizedExpression.Compile(); var fastDelegate = new FastDelegate<TDelegate>(@delegate, expression.Parameters.Count); return fastDelegate; } private class ExpressionOptimizer<TDelegate> : ExpressionVisitor { private ParameterExpression _arrayParameter; private Dictionary<ParameterExpression, int> _indexMap; /// <summary> /// Transforms expression from multi-parameter to single array parameter, /// which allows execution w/o reflection. /// </summary> /// <param name="expression">Expression to transform.</param> /// <returns>Transformed expression.</returns> public Expression<TDelegate> CompactParameters(LambdaExpression expression) { _arrayParameter = Expression.Parameter(typeof (object[])); _indexMap = expression.Parameters.ToIndexMap(); Expression body = Visit(expression.Body); Expression<TDelegate> optimizedLambda = Expression.Lambda<TDelegate>(body, _arrayParameter); return optimizedLambda; } protected override Expression VisitParameter(ParameterExpression node) { int index = _indexMap.IndexOrDefault(node); if (index >= 0) { BinaryExpression arrayLookup = Expression.ArrayIndex(_arrayParameter, Expression.Constant(index)); UnaryExpression parameterValue = Expression.Convert(arrayLookup, node.Type); return parameterValue; } return node; } } } internal class FastDelegate<TDelegate> : FastDelegate where TDelegate : class { private readonly TDelegate _delegate; private readonly int _parameterCount; public TDelegate Delegate { get { return _delegate; } } public int ParameterCount { get { return _parameterCount; } } internal FastDelegate(TDelegate @delegate, int parameterCount) { _delegate = @delegate; _parameterCount = parameterCount; } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestAssets/FactType2.cs namespace NRules.IntegrationTests.TestAssets { public class FactType2 { public string TestProperty { get; set; } public string JoinProperty { get; set; } } }<file_sep>/src/NRules/NRules/RuleConditionEvaluationException.cs using System; using System.Runtime.Serialization; using System.Security; namespace NRules { /// <summary> /// Represents errors that occur while evaluating rule condition. /// </summary> [Serializable] public class RuleConditionEvaluationException : RuleExpressionEvaluationException { internal RuleConditionEvaluationException(string message, string expression, Exception innerException) : base(message, expression, innerException) { } [SecuritySafeCritical] protected RuleConditionEvaluationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }<file_sep>/src/NRules/NRules/Diagnostics/RecoverableErrorEventArgs.cs using System; namespace NRules.Diagnostics { /// <summary> /// Information related to failure events that allow observer to mark error as handled. /// </summary> public class RecoverableErrorEventArgs : ErrorEventArgs { internal RecoverableErrorEventArgs(Exception exception) : base(exception) { IsHandled = false; } /// <summary> /// Flag indicating whether the exception was handled. /// If handler sets this to <c>true</c> then engine continues execution, /// otherwise exception is rethrown and terminates engine's execution. /// </summary> public bool IsHandled { get; set; } } }<file_sep>/src/NRules/NRules.Fluent/ExpressionBuilder.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using NRules.Fluent.Dsl; using NRules.Fluent.Expressions; using NRules.RuleModel; using NRules.RuleModel.Builders; namespace NRules.Fluent { internal class ExpressionBuilder : ILeftHandSide, IRightHandSide { private readonly RuleBuilder _builder; private readonly GroupBuilderChain _groupBuilders; public ExpressionBuilder(RuleBuilder builder) { _builder = builder; _groupBuilders = new GroupBuilderChain(_builder.LeftHandSide()); } public ILeftHandSide Match<T>(Expression<Func<T>> alias, params Expression<Func<T, bool>>[] conditions) { var patternSymbol = ExtractSymbol(alias); return Match(patternSymbol, conditions); } public ILeftHandSide Match<T>(Expression<Func<T, bool>> condition, params Expression<Func<T, bool>>[] conditions) { var patternSymbol = Expression.Parameter(typeof (T)); return Match(patternSymbol, Enumerable.Repeat(condition, 1).Union(conditions)); } public ILeftHandSide Match<T>() { var patternSymbol = Expression.Parameter(typeof(T)); return Match(patternSymbol, new Expression<Func<T, bool>>[] {}); } private ILeftHandSide Match<T>(ParameterExpression symbol, IEnumerable<Expression<Func<T, bool>>> conditions) { var groupBuilder = _groupBuilders.Current; var patternBuilder = groupBuilder.Pattern(symbol.Type, symbol.Name); foreach (var condition in conditions) { var rewriter = new ConditionRewriter(patternBuilder.Declaration, groupBuilder.Declarations); var rewrittenCondition = rewriter.Rewrite(condition); patternBuilder.Condition(rewrittenCondition); } return this; } public ICollectPattern<IEnumerable<T>> Collect<T>(Expression<Func<IEnumerable<T>>> alias, params Expression<Func<T, bool>>[] itemConditions) { var collectionSymbol = ExtractSymbol(alias); var groupBuilder = _groupBuilders.Current; var outerPatternBuilder = groupBuilder.Pattern(collectionSymbol.Type, collectionSymbol.Name); var aggregateBuilder = outerPatternBuilder.Aggregate(); aggregateBuilder.CollectionOf(typeof (T)); var patternBuilder = aggregateBuilder.Pattern(typeof (T)); foreach (var condition in itemConditions) { var rewriter = new ConditionRewriter(patternBuilder.Declaration, groupBuilder.Declarations); var rewrittenCondition = rewriter.Rewrite(condition); patternBuilder.Condition(rewrittenCondition); } return new CollectExpressionBuilder<IEnumerable<T>>(this, outerPatternBuilder); } public ILeftHandSide Exists<T>(params Expression<Func<T, bool>>[] conditions) { var groupBuilder = _groupBuilders.Current; var existsBuilder = groupBuilder.Exists(); var patternBuilder = existsBuilder.Pattern(typeof (T)); foreach (var condition in conditions) { var rewriter = new ConditionRewriter(patternBuilder.Declaration, groupBuilder.Declarations); var rewrittenCondition = rewriter.Rewrite(condition); patternBuilder.Condition(rewrittenCondition); } return this; } public ILeftHandSide Not<T>(params Expression<Func<T, bool>>[] conditions) { var groupBuilder = _groupBuilders.Current; var notBuilder = groupBuilder.Not(); var patternBuilder = notBuilder.Pattern(typeof(T)); foreach (var condition in conditions) { var rewriter = new ConditionRewriter(patternBuilder.Declaration, groupBuilder.Declarations); var rewrittenCondition = rewriter.Rewrite(condition); patternBuilder.Condition(rewrittenCondition); } return this; } public ILeftHandSide All<T>(Expression<Func<T, bool>> condition) { return All(x => true, new [] {condition}); } public ILeftHandSide And(Action<ILeftHandSide> builder) { using (_groupBuilders.BeginGroup(GroupType.And)) { builder(this); } return this; } public ILeftHandSide Or(Action<ILeftHandSide> builder) { using (_groupBuilders.BeginGroup(GroupType.Or)) { builder(this); } return this; } public ILeftHandSide All<T>(Expression<Func<T, bool>> baseCondition, params Expression<Func<T, bool>>[] conditions) { return ForAll(baseCondition, conditions); } public IRightHandSide Do(Expression<Action<IContext>> action) { var rightHandSide = _builder.RightHandSide(); var rewriter = new ActionRewriter(rightHandSide.Declarations); var rewrittenAction = rewriter.Rewrite(action); rightHandSide.Action(rewrittenAction); return this; } private ILeftHandSide ForAll<T>(Expression<Func<T, bool>> baseCondition, IEnumerable<Expression<Func<T, bool>>> conditions) { var leftHandSide = _builder.LeftHandSide(); var forallBuilder = leftHandSide.ForAll(); var basePatternBuilder = forallBuilder.BasePattern(typeof(T)); { var rewriter = new ConditionRewriter(basePatternBuilder.Declaration, leftHandSide.Declarations); var rewrittenCondition = rewriter.Rewrite(baseCondition); basePatternBuilder.Condition(rewrittenCondition); } var patternBuilder = forallBuilder.Pattern(typeof(T)); foreach (var condition in conditions) { var rewriter = new ConditionRewriter(patternBuilder.Declaration, leftHandSide.Declarations); var rewrittenCondition = rewriter.Rewrite(condition); patternBuilder.Condition(rewrittenCondition); } return this; } private static ParameterExpression ExtractSymbol<T>(Expression<Func<T>> alias) { if (alias == null) { throw new ArgumentNullException("alias", "Pattern alias is null"); } var fieldMember = alias.Body as MemberExpression; if (fieldMember == null) { throw new ArgumentException( string.Format("Invalid pattern alias expression. Expected={0}, Actual={1}", typeof(MemberExpression), alias.Body.GetType())); } return Expression.Parameter(fieldMember.Type, fieldMember.Member.Name); } } }<file_sep>/src/NRules/NRules/ActionContext.cs using System.Collections.Generic; using NRules.RuleModel; namespace NRules { internal class ActionContext : IContext { public ActionContext(IRuleDefinition rule) { Rule = rule; IsHalted = false; Operations = new Queue<ActionOperation>(); } public IRuleDefinition Rule { get; private set; } public bool IsHalted { get; private set; } public Queue<ActionOperation> Operations { get; set; } public void Insert(object fact) { Operations.Enqueue(new ActionOperation(fact, ActionOperationType.Insert)); } public void Update(object fact) { Operations.Enqueue(new ActionOperation(fact, ActionOperationType.Update)); } public void Retract(object fact) { Operations.Enqueue(new ActionOperation(fact, ActionOperationType.Retract)); } public void Halt() { IsHalted = true; } } }<file_sep>/src/NRules/NRules/Diagnostics/ActionErrorEventArgs.cs using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Tuple = NRules.Rete.Tuple; namespace NRules.Diagnostics { /// <summary> /// Information related to error events raised during action execution. /// </summary> public class ActionErrorEventArgs : RecoverableErrorEventArgs { private readonly Tuple _tuple; internal ActionErrorEventArgs(Exception exception, Expression expression, Tuple tuple) : base(exception) { _tuple = tuple; Action = expression; } /// <summary> /// Action that caused exception. /// </summary> public Expression Action { get; private set; } /// <summary> /// Facts that caused exception. /// </summary> public IEnumerable<FactInfo> Facts { get { return _tuple.Facts.Reverse().Select(x => new FactInfo(x)).ToArray(); } } } }<file_sep>/src/NRules/NRules/Rete/Activation.cs using System; namespace NRules.Rete { internal class Activation : IEquatable<Activation> { private readonly ICompiledRule _rule; private readonly Tuple _tuple; private readonly FactIndexMap _tupleFactMap; public Activation(ICompiledRule rule, Tuple tuple, FactIndexMap tupleFactMap) { _rule = rule; _tuple = tuple; _tupleFactMap = tupleFactMap; } public ICompiledRule Rule { get { return _rule; } } public Tuple Tuple { get { return _tuple; } } public FactIndexMap TupleFactMap { get { return _tupleFactMap; } } public bool Equals(Activation other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.Rule, Rule) && Equals(other.Tuple, Tuple); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (Activation)) return false; return Equals((Activation) obj); } public override int GetHashCode() { unchecked { return (Rule.GetHashCode()*397) ^ Tuple.GetHashCode(); } } } }<file_sep>/src/NRules/Tests/NRules.IntegrationTests/TestRules/PriorityLowRule.cs using NRules.Fluent.Dsl; using NRules.IntegrationTests.TestAssets; namespace NRules.IntegrationTests.TestRules { [Priority(10)] public class PriorityLowRule : BaseRule { public override void Define() { FactType1 fact1 = null; When() .Match<FactType1>(() => fact1, f => f.TestProperty.StartsWith("Valid")); Then() .Do(ctx => Action()) .Do(ctx => ctx.Insert(new FactType2() { TestProperty = "Valid Value", JoinProperty = fact1.TestProperty })); } } }<file_sep>/src/NRules/Tests/NRules.Tests/TestAssets/TestRules.cs using NRules.Fluent.Dsl; namespace NRules.Tests.TestAssets { public class TestRule1 : Rule { private readonly string _a; private readonly string _b; public string Results { get; private set; } public TestRule1() { _a = "a"; _b = "b"; Results = string.Empty; } public TestRule1(string a, string b) { _a = a; _b = b; Results = string.Empty; } public override void Define() { TestFact1 fact1 = null; TestFact2 fact2 = null; When() .Match<TestFact1>(() => fact1, f => f.Name == "Hello") .Match<TestFact2>(() => fact2, f => f.Fact1 == fact1); Then() .Do(ctx => SaveResult(_a)) .Do(ctx => SaveResult(_b)); } private void SaveResult(string result) { Results += result; } } public class TestFact1 { public string Name { get; set; } } public class TestFact2 { public TestFact1 Fact1 { get; set; } public int Amount { get; set; } } }
bcbe17a923cd2040bc04b14b586a709c4a1caf98
[ "Markdown", "C#" ]
96
C#
StanleyGoldman/NRules
c9547bd9e2c55e933ba902b6a7897f884833aa2a
ef189d225c36e03eb69a3005c147ca1c2f51ec8d
refs/heads/main
<repo_name>GirishKaradas/firebase-lyo4-1<file_sep>/src/Pages/MiddlePage/ListUsers.jsx import { v4 as uuid } from 'uuid'; import moment from 'moment'; import { Avatar, Box, Button, Card, CardHeader, Divider, IconButton, List, ListItem, ListItemAvatar, ListItemText, Typography } from '@material-ui/core'; import MoreVertIcon from '@material-ui/icons/MoreVert'; import ArrowRightIcon from '@material-ui/icons/ArrowRight'; import PeopleAltIcon from '@material-ui/icons/PeopleAlt'; import { useEffect, useState } from 'react'; import { db } from '../../firebase'; import { firebaseLooper } from '../../utils/tools'; const ListUsers = (props) =>{ const [users, setUsers] = useState([]) useEffect(() => { db.collection('users').get().then(snapshot => { const user = firebaseLooper(snapshot); setUsers(user) }).catch(err => { console.log(err) }) }, []) return ( <Card style={{padding: 10}} {...props}> <br /> <Typography style={{marginLeft:'24px' ,color:'#43425D',opacity: 0.68}} variant='h2' align='left' gutterBottom><b style={{marginLeft:'24px',color:'#43425D'}}>Users</b></Typography> <CardHeader subheader={`${users.length} in total`} /> <Divider /> <List> {users.slice(0,10).map((user, i) => ( <ListItem divider={i < users.length - 1} key={user.id} > <Avatar style={{ background: '#E8E7FF 0% 0% no-repeat padding-box'}} src={user.url} ></Avatar> <ListItemText style={{marginLeft: '2%'}} primary={user.firstName} /> {user.email} </ListItem> ))} </List> <Divider /> <Box p={2} style={{ display: 'flex', justifyContent: 'flex-end', }} > <Button href='/users' style={{color: '#0C03EB', font: 'var(--unnamed-font-style-normal) normal bold 16px/16px var(--unnamed-font-family-roboto)'}} endIcon={<ArrowRightIcon />} size="small" variant="text" > View all </Button> </Box> </Card> )}; export default ListUsers<file_sep>/src/components/ModuleSidebar/ModuleDashboardLayout.jsx import { Card, Container, makeStyles } from '@material-ui/core'; import { useState } from 'react'; import DashboardNavbar from './DashboardNavbar'; import DashboardSidebar from './DashboardSidebar'; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'white', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', background:'linear-gradient(#f3f3f3, #e7e7e7)' }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, background:'linear-gradient(#f3f3f3, #e7e7e7)' }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', background:'linear-gradient(#f3f3f3, #e7e7e7)' , flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); const ModuleDashboardLayout = ({ match}) => { const classes = useStyles() const [isMobileNavOpen, setMobileNavOpen] = useState(false); return ( <div > <DashboardNavbar onMobileNavOpen={() => setMobileNavOpen(true)} /> <DashboardSidebar match={match} onMobileClose={() => setMobileNavOpen(false)} openMobile={isMobileNavOpen} /> {/* <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> </Card> </div> </div> */} </div> ); }; export default ModuleDashboardLayout;<file_sep>/src/Pages/brands/DQBrands.jsx import { Dialog, Paper, TableCell, TableContainer, TableHead, TableRow, Typography,Toolbar, DialogContent, DialogActions, Button, TextField, Select } from "@material-ui/core"; import { useEffect } from "react"; import { useState } from "react"; import { Table } from "react-bootstrap"; import { db } from "../../firebase"; import { firebaseLooper } from "../../utils/tools"; import BrandView from "./brandsComp/BrandView"; function DQBrands({match}) { const [contents, setContents] = useState([]) const [contents1, setContents1] = useState([]) const [open, setOpen] = useState(false) const [title, setTitle] = useState('') const [desc, setDesc] = useState('') const [type, setType] = useState(0) useEffect(() => { db.collection('DQNew').doc(match.params.id) .collection('content').doc('config') .collection('module') .where('type', '==', 2) .onSnapshot(snapshot => { const data = firebaseLooper(snapshot) data.sort(function(a,b){ return (a.index - b.index) }) setContents(data) }) }, []) function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleSubmit(){ const index = contents.length db.collection('DQNew').doc(match.params.id) .collection('content').doc('config') .collection('module').add({title,desc,index}) } return ( <> { contents.map(module => ( <> <BrandView module={module} match={match} key={module.id}/> </> ))} </> ) } export default DQBrands <file_sep>/src/Pages/user_manual/ManualView.jsx import React, { useEffect, useState } from "react"; import { db } from "../../firebase"; import ViewData from "./ViewData"; import {firebaseLooper} from "../../utils/tools" import { Button, Dialog, DialogActions, DialogContent, FormHelperText, TextField, Toolbar, Typography } from "@material-ui/core"; import { storage } from "../../firebase"; import { Alert } from "react-bootstrap"; function ManualView() { const [manual, setManual] = useState([]); const [open, setOpen] = useState(false); const [title, setTitle] = useState('') const [desc, setDesc] = useState('') const [images, setImages] = useState([]); const [urls, setUrls] = useState([]); const [activate, setActivate] = useState(false) const [progress, setProgress] = useState(0); const handleChange = (e) => { for (let i = 0; i < e.target.files.length; i++) { const newImage = e.target.files[i]; newImage["id"] = Math.random(); setImages((prevState) => [...prevState, newImage]); } }; const handleUpload = () => { const promises = []; images.map((image) => { const uploadTask = storage.ref(`images/${image.name}`).put(image); promises.push(uploadTask); uploadTask.on( "state_changed", (snapshot) => { const progress = Math.round( (snapshot.bytesTransferred / snapshot.totalBytes) * 100 ); setProgress(progress); }, (error) => { console.log(error); }, async () => { await storage .ref("images") .child(image.name) .getDownloadURL() .then((urls) => { setUrls((prevState) => [...prevState, urls]); }); } ); setActivate(true) }); Promise.all(promises) .then(() => alert("All images uploaded. Please click 'OK' to see preview")) .catch((err) => console.log(err)); }; function handleOpen(){ setOpen(true); } function handleClose(){ setOpen(false); } useEffect(() => { db.collection('userManual').onSnapshot((snapshot) => { const data = firebaseLooper(snapshot) setManual(data) }) }, []) function handleSubmit(e){ e.preventDefault(); const index = manual.length db.collection('userManual').add({title, desc, urls, index}).then(() => { setTitle("") setDesc('') setUrls([]) setOpen(false) setImages([]) }) } return ( <> <div className="flex flex-col w-full items-center justify-center pt-6 lg:pt-15 f-f-l"> <h1 className="text-2xl md:text-6xl xl:text-8xl font-black text-center text-indigo-700 md:leading-tight"> User Manual </h1> </div> <div style={{display: 'flex', justifyContent: 'flex-end'}}> <Button onClick={handleOpen} variant="contained" >Add new</Button> </div> <div className="mx-auto container px-4 xl:px-0 pt-8 lg:pt-20"> <div className="flex flex-col w-full items-center justify-center f-f-l"> {/* <ViewData title="Authentication" desc="The application is protected by Firebase Authentication and all your data is stored in firestore. Login with your credentials" url="https://firebasestorage.googleapis.com/v0/b/lyodata.appspot.com/o/userManual%2FScreenshot%202021-07-26%20at%2011.13.51%20AM.png?alt=media&token=<PASSWORD>" /> <ViewData title="Dashboard" desc="This is the page you enter after login. You'll find an overview of all the data available in the application." url="https://firebasestorage.googleapis.com/v0/b/lyodata.appspot.com/o/userManual%2FScreenshot%202021-07-26%20at%2011.16.47%20AM.png?alt=media&token=<PASSWORD>"/> <ViewData title="ADD Details " desc={`Add any data by clicking on the "Add __" Button and filling in a form like the given.`} url="https://firebasestorage.googleapis.com/v0/b/lyodata.appspot.com/o/userManual%2Fadd-content.PNG?alt=media&token=<PASSWORD>"/> <ViewData title="Update Details " desc={`Update any data by clicking the "Pen" icon available on any component and changing the necessary fields`} url="https://firebasestorage.googleapis.com/v0/b/lyodata.appspot.com/o/userManual%2Fedit-content.PNG?alt=media&token=<PASSWORD>"/> <ViewData title="Delete Data " desc={`Delete any data by clicking on "delete" icon available on any component which will give you a warning like this `} url="https://firebasestorage.googleapis.com/v0/b/lyodata.appspot.com/o/userManual%2Fdel.PNG?alt=media&token=<PASSWORD>"/> <ViewData title="Machines" desc={`From sidebar you have "Machines" menu which is the root document of all the available data in the application`} url="https://firebasestorage.googleapis.com/v0/b/lyodata.appspot.com/o/userManual%2Fmachines.png?alt=media&token=<PASSWORD>"/> <ViewData title="File Manager" desc={"A CMS to manage OR store files for references - All formats supported "} url="https://firebasestorage.googleapis.com/v0/b/lyodata.appspot.com/o/userManual%2Ffile-manager.PNG?alt=media&token=<PASSWORD>"/> <ViewData title="Users" desc={`From sidebar you have Users menu where "Admins" can change certain data of an authenticated user"`} url="https://firebasestorage.googleapis.com/v0/b/lyodata.appspot.com/o/userManual%2Fusers.PNG?alt=media&token=<PASSWORD>"/> <ViewData title="Account" desc={`from Sidebar you have Accounts menu where you can change your authentication credentials like Email Password and Avatar`} url="https://firebasestorage.googleapis.com/v0/b/lyodata.appspot.com/o/userManual%2Facco.PNG?alt=media&token=<PASSWORD>"/> */} { manual.map((data) => ( <ViewData d_id={data.id} key={data.id} title={data.title} desc={data.desc} images={data.urls} /> )) } </div> <Dialog fullWidth open={open} onClose={handleClose}> <Toolbar> <Button onClick={handleClose}>Close</Button> </Toolbar> <DialogContent> <form onSubmit={handleSubmit}> <Typography variant='h1' align='center' gutterBottom>Add Manual Data</Typography> <TextField required value={title} label='Title' onChange={(e) => setTitle(e.target.value)} style={{marginBottom: '3%'}} variant='outlined' fullWidth/> <TextField required value={desc} label="Description" onChange={(e) => setDesc(e.target.value)}style={{marginBottom: '3%'}} rows={4} multiline variant='outlined' fullWidth/> <input multiple onChange={handleChange} style={{marginBottom: '3%'}} type="file" variant='outlined' fullWidth/> <Button onClick={handleUpload} variant='contained' color="primary" disabled={title === '' || desc === ''} fullWidth >Add </Button> <FormHelperText>Please enter above details to unblock</FormHelperText> <Dialog fullWidth onClose={() => setActivate(!activate)} open={activate}> <DialogContent> <Alert severity="success">New Data has been added . To confirm please click on "Confirm"</Alert> </DialogContent> <DialogActions> <Button onClick={(e)=> {handleSubmit(e); setActivate(!activate) } } variant="contained" style={{background: 'green', color: 'white'}}>Confirm</Button> </DialogActions> </Dialog> </form> <br /> <br /> {urls.map((url, i) => ( <img key={i} style={{ width: "500px" }} src={url || "http://via.placeholder.com/300"} alt="firebase-image" /> ))} </DialogContent> </Dialog> </div> </> ); } export default ManualView; <file_sep>/src/Pages/JobsData/JobsList.jsx import React, { useEffect, useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import { db } from '../../firebase'; import { firebaseLooper } from '../../utils/tools'; import ContentDashboardLayout from '../../components/ContentSidebar/ContentDashboardLayout'; import { Card, Checkbox, TextField, Typography, Button, Select, FormControl, InputLabel, MenuItem } from '@material-ui/core'; import DatePicker from 'react-date-picker'; import SearchIcon from '@material-ui/icons/Search'; import JobView from './JobView' import Page from '../../components/Page'; const useStyles = makeStyles((theme) => ({ table: { minWidth: 650, }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); function createData(name, calories, fat, carbs, protein) { return { name, calories, fat, carbs, protein }; } export default function JobsList({match}) { const [job, setJob] = useState([]) const [mTitle, setMTitle] = useState('') const [date, setDate] = useState('') const [users, setUsers] = useState([]) const [title, setTitle] = useState('') const [user, setUser] = useState('') useEffect(() => { db.collection('machineData') .doc(match.params.id) .onSnapshot(doc => { setMTitle(doc.data().title) }) db.collection('users').onSnapshot(snap => { const data = firebaseLooper(snap) setUsers(data) }) db.collection('jobData').where('mid', '==', `${match.params.id}`).onSnapshot(doc => { const data = firebaseLooper(doc) data.sort(function(a,b){ return(b.date - a.date) }) setJob(data) }) }, []) const classes = useStyles(); function userHandleChange(e){ const temp = e.target.value if(temp === ""){ db.collection('jobData').where('mid', '==', `${match.params.id}`).onSnapshot(doc => { const data = firebaseLooper(doc) data.sort(function(a,b){ return(b.date - a.date) }) setJob(data) }) }else { db.collection('jobData').where('mid', '==', `${match.params.id}`).where('email', '==', `${temp}`).onSnapshot(doc => { const data = firebaseLooper(doc) data.sort(function(a,b){ return(b.date - a.date) }) setJob(data) }) } } function pendingCheck(e){ const temp = e.target.value if(temp === ""){ db.collection('jobData').where('mid', '==', `${match.params.id}`).onSnapshot(doc => { const data = firebaseLooper(doc) data.sort(function(a,b){ return(b.date - a.date) }) setJob(data) }) }else{ db.collection('jobData').where('mid', '==', `${match.params.id}`).where('status', '==', temp).onSnapshot(doc => { const data = firebaseLooper(doc) data.sort(function(a,b){ return(b.date - a.date) }) setJob(data) }) } } const handleClick = () => { db.collection('jobData').where('mid', '==', `${match.params.id}`).onSnapshot(doc => { const data = firebaseLooper(doc) data.sort(function(a,b){ return(b.date - a.date) }) setJob(data) }) } // function handleChange(event) { // db.collection('jobData').where('mid', '==', `${match.params.id}`).onSnapshot(doc => { // const data = firebaseLooper(doc) // data.sort(function(a,b){ // return(b.date - a.date) // }) // data.filter(data => { // if(data.date.toDate().toString().substring(0,15) === date.toDateString()){ // return data // } // }) // setJob(data) // }) // } return ( <Page title='Jobs | LyoIms'> <ContentDashboardLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div> <div style={{display: 'flex', justifyContent: 'space-between'}}> {/* <Typography style={{marginRight: '15px'}} variant='h1' align='center'><b>{mTitle} : </b></Typography> */} <div> <Typography variant='h1' align='center'><b>JOBS</b></Typography> <Typography align='center' variant='body2' >- These are all the Job status -</Typography> </div> <div> <div style={{display: 'flex', justifyContent: 'flex-end', marginBottom: '30px'}}> <div className="relative mr-3"> <input style={{ border: '2px solid whitesmoke'}} onChange={(e) => setTitle(e.target.value)} type="text" className="h-14 w-96 pr-8 pl-5 rounded z-0 focus:shadow focus:outline-none" placeholder="Search Jobs..."/> <div className="absolute top-4 right-3"><SearchIcon style={{opacity: '0.5'}}/> </div> </div> <FormControl style={{width: '140px', marginRight: '2%'}} variant='outlined'> <InputLabel variant='outlined'>Assignee</InputLabel> <Select onChange={userHandleChange} label="Assignee"> <MenuItem value="">All</MenuItem> {users.map((data) => ( <MenuItem value={data.email}>{data.firstName} {data.lastName}</MenuItem> ))} </Select> </FormControl> <FormControl style={{width: '140px'}} variant='outlined'> <InputLabel variant='outlined'>Status</InputLabel> <Select onChange={pendingCheck} label="Status"> <MenuItem value="">All</MenuItem> <MenuItem value={true}>Completed</MenuItem> <MenuItem value={false}>Pending</MenuItem> </Select> </FormControl> {/* <DatePicker onChange={onChange} value={value} /> <b>{value?.toString().substring(0,15)}</b> <Button onClick={handleClick}>Reset</Button> */} </div> </div> </div> </div> <br/> <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{backgroundColor: '#d8e3e7'}}><b>Title</b></TableCell> <TableCell style={{backgroundColor: '#d8e3e7'}} align="left"><b>Description</b></TableCell> <TableCell style={{backgroundColor: '#d8e3e7'}} align="left"><b>Assignee</b></TableCell> <TableCell style={{backgroundColor: '#d8e3e7'}} align="left"><b>Date</b></TableCell> <TableCell style={{backgroundColor: '#d8e3e7'}} align="right"><b>Status</b></TableCell> <TableCell style={{backgroundColor: '#d8e3e7'}} align="right"><b>Actions</b></TableCell> </TableRow> </TableHead> <TableBody> {job.filter((row) => { if(title === "" ){ return row } else if (row.title.toLowerCase().includes(title.toLocaleLowerCase())){ return row } }).map((row) => ( <JobView key={row.id} row={row} match={match} /> ))} </TableBody> </Table> </TableContainer> </Card> </div> </div> </Page> ); }<file_sep>/src/Pages/DQNew/DQComponents/AddMaterial.jsx import { FormHelperText, TextField } from '@material-ui/core'; import { Button, Typography } from '@material-ui/core'; import { Alert } from '@material-ui/lab'; import React, { useState } from 'react' import { db } from '../../../firebase'; const AddMaterial = ({match}) => { const [name, setName] = useState('') const [desc, setDesc] = useState('') const [ message, setMessage] = useState('') const [error, setError] = useState('') const [mid, setMid] = useState(`${match.params.id}`) function handleSubmit(e){ e.preventDefault() if(name?.trim().length === 0 || desc?.trim().length === 0){ return setError("Empty strings are not valid inputs ! Please try again with a valid input") } db.collection('DQNew').add({name,desc,mid}).then(data => { const key= data.id setMessage("Added successfully! You can close the window or add another") setName("") setDesc("") db.collection('DQNew').doc(data.id).update({key}).then(() => { setMessage("Added successfully! You can close the window or add another") setName("") setDesc("") setError("") }) }) } return ( <div> <div class="container items-center px-4 py-12 "> <form class="flex flex-col w-full transition duration-500 ease-in-out transform rounded-lg " onSubmit={handleSubmit}> <Typography variant='h3' align='center'><b>Add New report</b></Typography> { message && <Alert severity='success'>{message}</Alert> } {error && <Alert severity='error'>{error}</Alert>} <div class="relative pt-4"> <TextField variant='outlined' required fullWidth label="Name" value={name} error={name.length > 40} onChange={(e) => setName(e.target.value)} type="text" placeholder="Enter Name" /> <FormHelperText style={{marginBottom: '25px'}}>Name must be {name.length}/40 characters maximum</FormHelperText> </div> <TextField value={desc} error={desc > 300 } label="Description" fullWidth rows={5} variant="outlined" multiline onChange={(e) => setDesc(e.target.value)} /> <FormHelperText>Description must be {desc.length}/300 characters maximum</FormHelperText> <div class="flex items-center w-full pt-4"> <Button disabled={ desc>300 || name > 40} fullWidth style={{background: 'orange', color: 'white'}} type="submit" > Add DQ </Button> </div> </form> </div> </div> ) } export default AddMaterial <file_sep>/src/Pages/MiddlePage/MiddlePage.jsx import { Helmet } from 'react-helmet'; import { Box, Button, Container, Fab, fade, FormControl, Grid, InputLabel, makeStyles, MenuItem, Paper, Select, Typography } from '@material-ui/core'; import { Redirect, useHistory } from 'react-router-dom'; import { useEffect, useState } from 'react'; import { useAuth } from '../../components/context/AuthContext'; import ListMachines from './ListMachines'; import LineDemo from '../../components/LineDemo'; import ListUsers from './ListUsers'; import CustomerListView from '../../components/LogsData/Logs'; import LogsList from './LogsList'; import RecipeeList from './Graph/RecipeeList'; import JobGraph from './JobGraph'; import WorkFlow from './WorkFlow'; import MachineBox from './MachineBox'; import UsersBox from './UsersBox'; import JobsBox from './JobsBox'; import ManualBox from './ManualBox'; import { db } from '../.././firebase' import { firebaseLooper } from '../.././utils/tools' import TestData from '../Tests/TestData'; import GraphData from './Graph/GraphData'; import Skeleton from '@material-ui/lab/Skeleton'; import TestHome from '../Tests/TestHome'; import GraphDataRecipee from './Graph/GraphDataRecipee'; import TestGraph from '../../TestGraph/TestGraph'; import ChatBot from 'react-simple-chatbot'; import { ThemeProvider } from 'styled-components'; import DQtable from './subcomponents/DQtable'; const useStyles = makeStyles((theme) => ({ grow: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), }, title: { display: 'none', [theme.breakpoints.up('sm')]: { display: 'block', }, }, search: { position: 'relative', borderRadius: theme.shape.borderRadius, backgroundColor: fade(theme.palette.common.white, 0.15), '&:hover': { backgroundColor: fade(theme.palette.common.white, 0.25), }, marginRight: theme.spacing(2), marginLeft: 0, width: '100%', [theme.breakpoints.up('sm')]: { marginLeft: theme.spacing(3), width: 'auto', }, }, searchIcon: { padding: theme.spacing(0, 2), height: '100%', position: 'absolute', pointerEvents: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', }, inputRoot: { color: 'inherit', }, inputInput: { padding: theme.spacing(1, 1, 1, 0), // vertical padding + font size from searchIcon paddingLeft: `calc(1em + ${theme.spacing(4)}px)`, transition: theme.transitions.create('width'), width: '100%', [theme.breakpoints.up('md')]: { width: '20ch', }, }, sectionDesktop: { display: 'none', [theme.breakpoints.up('md')]: { display: 'flex', }, }, sectionMobile: { display: 'flex', [theme.breakpoints.up('md')]: { display: 'none', }, }, })); const updateChart = (title) => { let gData = [] console.log(gData) return( <TestData data={gData}/> ) } const MiddlePage = () =>{ const dqOptions = [] const options = [] var x; const [rData, setRData] = useState([]) const {currentUser} = useAuth() const [title, setTitle] = useState('') const [machines, setMachines] = useState([]) const [users, setUsers] = useState([]) const history = useHistory() useEffect(() => { db.collection('users').where('email', '==', `${currentUser.email}`).onSnapshot(doc => { const data = firebaseLooper(doc) setUsers(data) }) db.collection('machineData').onSnapshot(doc => { const data = firebaseLooper(doc) console.log(data) for (var i = 0; i<data.length; i++){ x = {value: data[i].id, label: data[i].title, trigger: '5'} options.push(x) } console.log(options) }) db.collection('recipeeData').onSnapshot(doc => { const data = firebaseLooper(doc) setRData(data) }) },[]) const theme = { background: '#f5f8fb', fontFamily: 'Montserrat', headerBgColor: '#EF6C00', headerFontColor: '#fff', headerFontSize: '15px', botBubbleColor: '#EF6C00', botFontColor: '#fff', userBubbleColor: '#fff', userFontColor: '#4a4a4a', }; function handleEnd({ steps, values }) { // console.log(steps); // console.log(values); history.push(`/machine-data/${values[1]}/DQ-New-Reports`) } const getOptions = (previousValue) => { db.collection('DQReport').where('mid', '==', `${previousValue}`).onSnapshot(doc => { const data = firebaseLooper(doc) console.log(data) for(var i = 0; i<data.length; i++){ const x = {value: data[i].id, label: data[i].title, trigger: '5'} dqOptions.push(x) } }) return dqOptions } return ( <Paper className='bg-gray-200'> <Helmet> <title>Dashboard | LyoIMS</title> </Helmet> <Box className='bg-gray-50' py={3} style={{ backgroundColor: 'background.default', minHeight: '100%', }} > <Container className='bg-gray-50' maxWidth={false}> <Typography variant='h2' align='left' gutterBottom><b className='uppercase' style={{font: 'var(--unnamed-font-style-normal) normal 600 34px/46px Montserrat', color: '#43425D'}}>Welcome to the Dashboard</b></Typography> <Typography style={{font: 'var(--unnamed-font-style-normal) normal medium 23px/25px var(--unnamed-font-family-roboto)', color: '#43425D', marginBottom: '3%'}} variant='caption' align='left'>Here's an overview of the available data</Typography> <br /> <Grid container spacing={3} className='bg-grey-100' > <Grid style={{height: '100%'}} item lg={3} sm={6} xl={3} xs={12} className='bg-grey-100' > <MachineBox /> {/* */} </Grid> <Grid style={{height: '100%'}} item lg={3} sm={6} xl={3} xs={12} className='bg-grey-100' > <UsersBox/> </Grid> <Grid style={{height: '100%'}} item lg={3} sm={6} xl={3} xs={12} className='bg-grey-100' > <JobsBox/> </Grid> <Grid className='bg-grey-100' item lg={3} sm={6} xl={3} xs={12} > <ManualBox/> </Grid> <Grid item lg={8} md={12} xl={9} xs={12} className='bg-grey-100' > <TestGraph/> {/* <GraphDataRecipee data={gData}/> */} </Grid> <Grid item lg={4} md={6} xl={3} xs={12} className='bg-grey-100' > <JobGraph/> </Grid> <Grid item lg={8} md={12} xl={9} xs={12} className='bg-grey-100' > {/* <WorkFlow/> */} <LogsList/> </Grid> <Grid item lg={4} md={6} xl={3} xs={12} className='bg-grey-100' > <ListUsers style={{height: "100%"}}/> </Grid> </Grid> </Container> <ThemeProvider theme={theme}> <ChatBot handleEnd={handleEnd} floating={true} headerTitle="Arizon Chatbot" placeholder="" cache={true} hideSubmitButton={true} steps={[ { id: '1', message: `Hi, What Activity would you like to execute?`, trigger: '2', }, { id: '2', options: [ { value: 'machine-data', label: 'Machines', trigger: '3' }, { value: 'Reports', label: 'Download Reports', trigger: '4' }, ], trigger: '3' }, { id: '3', options: options, }, { id: '4', component: <DQtable/>, asMessage: false }, { id: '5', message: 'Redirecting to Reports Page ', trigger: '6' }, { id: '6', message: 'Thanks', end: true }, ]} /> </ThemeProvider> </Box> </Paper> ) } export default MiddlePage <file_sep>/src/components/VideoCall/VideoCall.jsx import React from 'react'; import { OTSession, OTPublisher, OTStreams, OTSubscriber } from 'opentok-react'; import { Button, Typography } from '@material-ui/core'; import VideocamOffIcon from '@material-ui/icons/VideocamOff'; export default class VideoCall extends React.Component { constructor(props) { super(props); this.state = { message: '', error: null, connection: 'Connecting', publishVideo: true, }; this.sessionEventHandlers = { sessionConnected: () => { this.setState({ connection: 'Connected' }); }, sessionDisconnected: () => { this.setState({ connection: 'Disconnected' }); }, sessionReconnected: () => { this.setState({ connection: 'Reconnected' }); }, sessionReconnecting: () => { this.setState({ connection: 'Reconnecting' }); }, }; this.publisherEventHandlers = { accessDenied: () => { console.log('User denied access to media source'); }, streamCreated: () => { console.log('Publisher stream created'); }, streamDestroyed: ({ reason }) => { console.log(`Publisher stream destroyed because: ${reason}`); }, }; this.subscriberEventHandlers = { videoEnabled: () => { console.log('Subscriber video enabled'); }, videoDisabled: () => { console.log('Subscriber video disabled'); }, }; } onSessionError = error => { this.setState({ error }); }; onPublish = () => { console.log('Publish Success'); }; onPublishError = error => { this.setState({ error }); }; onSubscribe = () => { console.log('Subscribe Success'); }; onSubscribeError = error => { this.setState({ error }); }; toggleVideo = () => { this.setState(state => ({ publishVideo: !state.publishVideo, })); }; render() { const { apiKey, sessionId, token } = this.props.credentials; const { error, connection, publishVideo } = this.state; return ( <div> <Typography variant='h3' align='center' id="sessionStatus"><b>Session Status:</b> {connection}</Typography> {error ? ( <div className="error"> <strong>Error:</strong> {error} </div> ) : null} <OTSession apiKey={apiKey} sessionId={sessionId} token={token} onError={this.onSessionError} eventHandlers={this.sessionEventHandlers} > <div style={{display: 'flex', flexDirection: 'column', justifyContent: 'center', marginBottom: '20px'}}> <Button startIcon={<VideocamOffIcon/>} style={{marginBottom: '2%',marginLeft: '10%',backgroundImage: 'linear-gradient(to left bottom, #420ffa, #004dff, #006eff, #238aff, #59a3ff)', color: 'white', width: '15%'}}id="videoButton" onClick={this.toggleVideo}> {publishVideo ? 'Disable' : 'Enable'} Video </Button> <OTPublisher properties={{ publishVideo, width: 500, height: 300, }} onPublish={this.onPublish} onError={this.onPublishError} eventHandlers={this.publisherEventHandlers} /> </div> <OTStreams> <div style={{ marginRight: '5%', marginTop: '2%'}}> <OTSubscriber properties={{ width: 400, height: 250 }} onSubscribe={this.onSubscribe} onError={this.onSubscribeError} eventHandlers={this.subscriberEventHandlers} /> </div> </OTStreams> </OTSession> </div> ); } }<file_sep>/src/Pages/DQNew/DQNew.jsx import { Button, Card, Toolbar, Dialog, Typography } from "@material-ui/core"; import { makeStyles } from "@material-ui/core"; import { useEffect, useState } from "react" import ContentDashboardLayout from "../../components/ContentSidebar/ContentDashboardLayout"; import {db} from '../../firebase' import {firebaseLooper} from '../../utils/tools' import AddMaterial from "./DQComponents/AddMaterial"; import DQNewView from "./DQComponents/DQNewView"; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'white', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', background:'linear-gradient(#f3f3f3, #e7e7e7)' }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, table: { minWidth: 500, }, })); function DQNew({match}) { const [reports, setReports] = useState([]) const [open, setOpen] = useState(false) const classes = useStyles() useEffect(() => { db.collection('DQNew').where('mid', '==', `${match.params.id}`).onSnapshot(snapshot => { const data = firebaseLooper(snapshot) setReports(data) }) }, []) const handleOpen = () => { setOpen(true) } const handleClose = () => { setOpen(false) } return ( <> <ContentDashboardLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div style={{paddingLeft: '16%', paddingTop: '3%', display: 'flex', justifyContent: 'space-between', paddingRight: '15%'}}> <div> <Typography variant='h2' align='left'>DQ Master Copy </Typography> <Typography variant='body1' align='left'>Master Copy of all the DQ reports</Typography> </div> <Toolbar style={{display: 'flex', justifyContent: 'flex-end'}}> <Button onClick={handleOpen} color='primary' variant='contained' style={{ color: 'white', width: '150px' }}>Add New</Button> </Toolbar> </div> <div> <div className="container mx-auto py-10"> <div className="shadow bg-white dark:bg-gray-800 rounded"> { reports.map(data => ( <> <DQNewView key={data.id} report={data}/> </> )) } </div> </div> </div> <Dialog onClose={handleClose} open={open} fullWidth> <Toolbar style={{display: 'flex', justifyContent: 'flex-start'}}> <Button onClick={handleClose} style={{backgroundColor:'orange', color: 'white', width: '10%' }}>close</Button> </Toolbar> <AddMaterial match={match}/> </Dialog> </Card> </div> </div> </> ) } export default DQNew <file_sep>/src/Pages/DQNewReports/DQRSpecs.jsx import { Typography , Card, makeStyles, TableContainer, Paper, TableHead, TableRow, TableCell, TableBody, Button} from "@material-ui/core" import { useEffect } from "react" import { useState } from "react" import { Table } from "react-bootstrap" import DQRLayout from "../../components/DQRLayout/DQRLayout" import { db } from "../../firebase" import ArrowForwardIcon from '@material-ui/icons/ArrowForward' import { firebaseLooper } from "../../utils/tools" import DQRSpecView from "./DQRSpecView" const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'whitesmoke', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 250 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); function DQRSpecs({match}) { const [purpose, setPurpose] = useState({}) const [configData, setConfigData] = useState([]) const [input, setInput] = useState('') const classes = useStyles() useEffect(() => { db.collection('DQNewReport') .doc(match.params.id) .collection('content') .doc('specifications') .onSnapshot(snapshot => { const data = snapshot.data() setPurpose(data) }) db.collection('DQNewReport') .doc(match.params.id) .collection('content') .doc('specifications') .collection('specDetails') .onSnapshot(snapshot => { const data = firebaseLooper(snapshot) data.sort(function (a,b) { return(a.index-b.index) }) setConfigData(data) }) }, []) return ( <div> <DQRLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div> {purpose && <Typography variant='h1' align='center' gutterBottom><b>{purpose.name}</b></Typography> }<hr /> <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}>Title</TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right">Input(Glass)</TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right">Actions</TableCell> </TableRow> </TableHead> <TableBody> {configData.map((row) => ( <DQRSpecView key={row.id} match={match} row={row}/> ))} </TableBody> </Table> </TableContainer> </div> </Card> </div> </div> </div> ) } export default DQRSpecs <file_sep>/src/components/DropZone/imageElement.js import React from "react"; import { Paper, Grid, CircularProgress, Box, TextField, IconButton, } from "@material-ui/core"; import { IoIosArrowUp, IoIosArrowDown } from "react-icons/io"; import { RiDeleteBin5Line } from "react-icons/ri"; export default function ImageElement({ image, index, isFirstElement, isLastElement, handleChangeOrderUp, handleChangeOrderDown, handleDeleteImage, changeImageField, }) { return ( <Box my={2} width={600}> <Paper> <Grid container direction="row" justify="center" spacing={2}> <Grid item container alignItems="center" justify="center" xs={6}> {image.downloadURL ? ( <img src={image.downloadURL} alt={`Upload Preview ${index + 1}`} style={{ maxHeight: "100%", maxWidth: "100%", }} /> ) : ( <Box p={2}> <CircularProgress /> </Box> )} </Grid> <Grid item container alignItems="center" xs={4}> <TextField multiline size="small" rows={4} fullWidth variant="outlined" value={image.description} onChange={(event) => { changeImageField( index, "description", event.target.value ); }} /> </Grid> <Grid container direction="column" alignItems="center" justify="center" item xs={2} > <Grid item container alignItems="center" justify="center"> {!isFirstElement && ( <IconButton aria-label="Image up" onClick={() => handleChangeOrderUp(index)} > <IoIosArrowUp /> </IconButton> )} </Grid> <Grid item container alignItems="center" justify="center" xs={4} > <IconButton aria-label="Delete Image" onClick={() => handleDeleteImage(index)} > <RiDeleteBin5Line /> </IconButton> </Grid> <Grid item container alignItems="center" justify="center"> {!isLastElement && ( <IconButton aria-label="Image down" onClick={() => handleChangeOrderDown(index)} > <IoIosArrowDown /> </IconButton> )} </Grid> </Grid> </Grid> </Paper> </Box> ); }<file_sep>/src/Pages/DQNew/DQComponents.jsx function DQComponents() { return ( <div> DQ -- Content -- Modules -- Components </div> ) } export default DQComponents <file_sep>/src/Pages/IQ/IQPages.jsx/IQSoftwarePage.jsx import { Dialog, Paper, TableCell, TableContainer, TableHead, TableRow, Typography,Toolbar, DialogContent, DialogActions, Button, TextField } from "@material-ui/core"; import { DropzoneArea } from "material-ui-dropzone"; import { useEffect } from "react"; import { useState } from "react"; import { Table } from "react-bootstrap"; import { db } from "../../../firebase"; import { firebaseLooper } from "../../../utils/tools"; import { useStorage } from "../../../utils/useStorage"; import ControlView from "../IQComponents/ControlView"; import DrawView from "../IQComponents/DrawView"; import IQConfigView from "../IQComponents/IQConfigView"; import IQHeader from "../IQComponents/IQHeader"; import PanelView from "../IQComponents/PanelView"; import SoftDetailView from "../IQComponents/SOftDetailsView"; function IQSoftwarePage({match, sid}) { const [contents, setContents] = useState([]) const [open, setOpen] = useState(false) const [title, setTitle] = useState('') const [desc, setDesc] = useState('') const [make, setMake] = useState('') const [tag_no, setTag] = useState('') const [type, setType] = useState('') const [serial_no, setSerial] = useState('') const [dno, setDno] = useState('') const [file, setFile] = useState(null) const handleChange = (loadedFiles) => { let selectedFile = loadedFiles[0] setFile(selectedFile) } const { progress, url } = useStorage(file); useEffect(() => { db.collection('IQ').doc(match.params.id) .collection('content').doc('software') .collection('softwareDetails') .where('sid', '==', `${sid}`) .onSnapshot(snapshot => { const data = firebaseLooper(snapshot) data.sort(function(a,b){ return (a.index - b.index) }) setContents(data) }) }, []) function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleSubmit(){ const index = contents.length db.collection('IQ').doc(match.params.id) .collection('content').doc('software') .collection('softwareDetails').add({title,desc,index,make,type,serial_no,sid,url}) } return ( <div> <Toolbar style={{display: 'flex', justifyContent: 'flex-end'}}> <Button onClick={handleOpen} style={{background: 'orange', color: 'white'}}>Add Items</Button> </Toolbar> <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell><b className='text-lg font-bold italic'>Title</b></TableCell> <TableCell align="left"><b className='text-lg font-bold italic'>Description</b></TableCell> <TableCell align="left"><b className='text-lg font-bold italic'>Model/Serial No.</b></TableCell> <TableCell align="left"><b className='text-lg font-bold italic'>Make</b></TableCell> <TableCell align="left"><b className='text-lg font-bold italic'>Type</b></TableCell> <TableCell align="center"><b className='text-lg font-bold italic'>Image</b></TableCell> <TableCell align="right"><b className='text-lg font-bold italic'>Actions</b></TableCell> </TableRow> </TableHead> { contents.map(module => ( <> <SoftDetailView module={module} match={match} key={module.id}/> </> )) } </Table> </TableContainer> <Dialog open={open} onClose={handleClose} fullWidth> <Typography variant='h3' align='center' gutterBottom><b>Add new items</b></Typography> <DialogContent> <TextField style={{marginBottom: '3%'}} variant='outlined' label='Title' fullWidth onChange={(e) => setTitle(e.target.value)}/> <TextField style={{marginBottom: '3%'}} variant='outlined' label='Version/Serial No.' fullWidth onChange={(e) => setSerial(e.target.value)}/> <TextField style={{marginBottom: '3%'}} variant='outlined' label='Type/Rating' fullWidth onChange={(e) => setType(e.target.value)}/> <TextField style={{marginBottom: '3%'}} variant='outlined' label='Make/Vendor' fullWidth onChange={(e) => setMake(e.target.value)}/> <TextField multiLine rows={7} variant='outlined' label='Description' fullWidth onChange={(e) => setDesc(e.target.value)}/> <DropzoneArea showPreviews={true} showFileNames onChange={(loadedFiles) => handleChange(loadedFiles)} dropzoneText="Drag and Drop / Click to Add Files" showPreviewsInDropzone={false} useChipsForPreview showAlerts={false} filesLimit={1} /> <h5>{progress}% Uploaded</h5> <div style={{display: 'flex', justifyContent: 'center'}}> {url && <img width='300' height='200' src={url} alt='image'/>} </div> </DialogContent> <DialogActions> <Button color='secondary' onClick={handleClose} variant='contained'>Cancel</Button> <Button disabled={title === '' || desc==='' || url === null} onClick={handleSubmit} style={{background: 'orange', color: 'white'}}>Add New</Button> </DialogActions> </Dialog> </div> ) } export default IQSoftwarePage <file_sep>/src/Pages/settings/Settings.jsx import { Button, Typography } from "@material-ui/core" import { useEffect, useState } from "react" import { database, db } from "../../firebase" import { firebaseLooper, firebaseLooperTwo } from "../../utils/tools" import GetAppIcon from '@material-ui/icons/GetApp'; import EditNavbar from "./EditNavbar"; import EditVideoCall from "./EditVideoCall"; import Page from "../../components/Page"; import AddApk from "./AddApk"; import { useAuth } from "../../components/context/AuthContext"; const Settings = () => { const [mobile, setMobile] = useState({}) const [glass, setGlass] = useState({}) const {currentUser} = useAuth() const [user, setUser] = useState([]) useEffect(()=> { db.collection('apks').doc('mobile').onSnapshot(snapshot => { const data = snapshot.data() setMobile(data) }) db.collection('apks').doc('glass').onSnapshot(snapshot => { const data = snapshot.data() setGlass(data) }) db.collection('users').where('email', '==', `${currentUser.email}`).onSnapshot(snapshot => { const data = firebaseLooper(snapshot) setUser(data[0]) console.log(data) }) } ,[]) return ( <Page title='Settings | LyoIms'> { user.role === 'Admin'? <section class="text-gray-600 body-font"> <div style={{display: 'flex', justifyContent: 'space-between'}}> <Typography variant='h3' gutterBottom align='left'><b>Settings</b></Typography> <Typography variant='body1' gutterBottom align='right'>Web app Version : 1.6.6</Typography> </div> <section class="text-gray-600 body-font"> <div class="container px-5 py-24 mx-auto flex items-center md:flex-row flex-col"> <div class="flex flex-col md:pr-10 md:mb-0 mb-6 pr-0 w-full md:w-auto md:text-left text-center"> <h2 class="text-xs text-yellow-800 tracking-widest font-medium title-font mb-1">Lyodata APKS</h2> <h1 class="md:text-3xl text-2xl font-medium title-font text-gray-900">Mobile and Glass APK Downloads</h1> </div> <div class="flex md:ml-auto md:mr-0 mx-auto items-center flex-shrink-0 space-x-4"> <a href={mobile.url}> <button class="bg-gray-100 inline-flex py-3 px-5 rounded-lg items-center hover:bg-gray-200 focus:outline-none"> <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="w-6 h-6" viewBox="0 0 512 512"> <path d="M99.617 8.057a50.191 50.191 0 00-38.815-6.713l230.932 230.933 74.846-74.846L99.617 8.057zM32.139 20.116c-6.441 8.563-10.148 19.077-10.148 30.199v411.358c0 11.123 3.708 21.636 10.148 30.199l235.877-235.877L32.139 20.116zM464.261 212.087l-67.266-37.637-81.544 81.544 81.548 81.548 67.273-37.64c16.117-9.03 25.738-25.442 25.738-43.908s-9.621-34.877-25.749-43.907zM291.733 279.711L60.815 510.629c3.786.891 7.639 1.371 11.492 1.371a50.275 50.275 0 0027.31-8.07l266.965-149.372-74.849-74.847z"></path> </svg> <span class="ml-4 flex items-start flex-col leading-none"> <span class="text-xs text-gray-600 mb-1">Mobile {mobile.version}</span> <span class="title-font font-medium">Download Apk</span> </span> </button> </a> <a href={glass.url}> <button class="bg-gray-100 inline-flex py-3 px-5 rounded-lg items-center hover:bg-gray-200 focus:outline-none"> <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="w-6 h-6" viewBox="0 0 512 512"> <path d="M99.617 8.057a50.191 50.191 0 00-38.815-6.713l230.932 230.933 74.846-74.846L99.617 8.057zM32.139 20.116c-6.441 8.563-10.148 19.077-10.148 30.199v411.358c0 11.123 3.708 21.636 10.148 30.199l235.877-235.877L32.139 20.116zM464.261 212.087l-67.266-37.637-81.544 81.544 81.548 81.548 67.273-37.64c16.117-9.03 25.738-25.442 25.738-43.908s-9.621-34.877-25.749-43.907zM291.733 279.711L60.815 510.629c3.786.891 7.639 1.371 11.492 1.371a50.275 50.275 0 0027.31-8.07l266.965-149.372-74.849-74.847z"></path> </svg> <span class="ml-4 flex items-start flex-col leading-none"> <span class="text-xs text-gray-600 mb-1">Glass {glass.version}</span> <span class="title-font font-medium">Download Apk</span> </span> </button> </a> </div> </div> </section> <AddApk/> <hr /> <EditNavbar/> <br /> <EditVideoCall/> { } </section> : <div> No Access </div> } </Page> ) } export default Settings <file_sep>/src/components/Sidebar/Sidebar.jsx import React, { useState } from 'react'; import styled from 'styled-components'; import {Link, useHistory} from 'react-router-dom'; import MenuIcon from '@material-ui/icons/Menu'; import {SidebarData} from './SidebarData' import SubMenu from './SubMenu'; import CloseIcon from '@material-ui/icons/Close'; import { Button, Container } from '@material-ui/core'; import { useAuth } from '../context/AuthContext'; import PowerSettingsNewIcon from '@material-ui/icons/PowerSettingsNew'; import HomeIcon from '@material-ui/icons/Home'; import BuildIcon from '@material-ui/icons/Build'; const Nav = styled.div` background: #15171c; height: 80px; display: flex; justify-content: flex-start; align-items: center; `; const NavIcon = styled(Link)` margin-left: 2rem; font-size: 2rem; height: 80px; display: flex; justify-content: flex-start; align-items: center; `; const SidebarNav = styled.nav` background: #15171c; width: 250px; height: 100vh; display: flex; justify-content: center; position: fixed; top: 0; left: ${({ sidebar }) => (sidebar ? '0' : '-100%')}; transition: 200ms; z-index: 10; `; const SidebarWrap = styled.div` width: 100%; `; const Sidebar = ({match}) => { const [sidebar, setSidebar] = useState(false); const showSidebar = () => setSidebar(!sidebar); const { currentUser, logout } = useAuth() const history = useHistory() async function handleLogout() { try { await logout() history.push("/login") } catch { } } return ( <> <div style={{display: "flex", width: "100%"}}> <Nav style={{width: "50%"}}> <NavIcon to="#"> <MenuIcon style={{color: "white"}} onClick={showSidebar}/> </NavIcon> <img style={{marginLeft: "20px"}} src="http://arizonsystems.com/img/arizon.webp"/> </Nav> <Nav style={{width: "50%", display: "flex", justifyContent: "flex-end"}}> <Button startIcon={<BuildIcon/>} style={{marginLeft: "40px", borderRadius: "15px", width: "150px" }} href="/machine-data"variant="contained" color="primary">Machines</Button> <Button startIcon={<HomeIcon/>} style={{marginLeft: "40px", borderRadius: "15px", width: "130px"}} href="/"variant="contained" color="primary">Home</Button> <Button startIcon={<PowerSettingsNewIcon/>} onClick={handleLogout} variant="contained" style={{borderRadius: "15px", marginLeft:"40px",width:"130px", color: "white" , backgroundColor: "#fa1e0e"}}>Logout</Button> </Nav> </div> <SidebarNav sidebar={sidebar}> <SidebarWrap> <NavIcon to='#'> <CloseIcon style={{color: "white"}} onClick={showSidebar} /> <img style={{marginLeft: "20px"}} src="http://arizonsystems.com/img/arizon.webp"/> </NavIcon> {SidebarData.map((item, index) => { return <SubMenu match={match} item={item} key={index} />; })} </SidebarWrap> </SidebarNav> </> ) } export default Sidebar <file_sep>/src/Pages/DQPages/DQCOnfigDetails/DQComponentsView.jsx import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, TableBody, TableCell, TableRow, TextField, Typography } from "@material-ui/core" import EditIcon from "@material-ui/icons/Edit" import DeleteForeverIcon from "@material-ui/icons/DeleteForever" import { Alert, AlertTitle } from "@material-ui/lab" import { useState } from "react" import { db } from "../../../firebase" function DQComponentsView({components, match, module_id}) { const [title, setTitle] = useState(components.title) const [value, setValue] = useState(components.value) const [open, setOpen] = useState(false) const [openDel, setOpenDel] = useState(false) function handleOpenDel(){ setOpenDel(true) } function handleCloseDel(){ setOpenDel(false) } function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleUpdate(){ db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('config') .collection('components') .doc(components.id) .update({title, value}) .then(() => {setOpen(false)}) } function handleDelete(id){ db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('config') .collection('components') .doc(id) .delete() } return ( <> <TableBody> <TableRow key={components.id}> <TableCell style={{background: '#E8F6EF'}} component="th" scope="row" align='left'> {components.title} </TableCell> <TableCell align='left'> {components.value} </TableCell> <TableCell align="right"> <div> <Button onClick={handleOpen}><EditIcon className='animate-bounce'/></Button> <Button onClick={handleOpenDel}><DeleteForeverIcon className='hover:text-red-600'/></Button> </div> </TableCell> </TableRow> </TableBody> <Dialog style={{alignItems: 'center'}} fullWidth open={open} onClose={handleClose}> <DialogContent> <Typography variant='h4' align='center' gutterBottom><b>Edit Details</b></Typography> <form > <TextField style={{marginBottom: '3%'}} value={title} variant='outlined' fullWidth onChange={(e) => setTitle(e.target.value)}/> <TextField style={{marginBottom: '3%'}} value={value} variant='outlined' fullWidth onChange={(e) => setValue(e.target.value)}/> </form> </DialogContent> <DialogActions> <Button variant='contained' color='secondary' onClick={handleClose}>Cancel</Button> <Button onClick={handleUpdate} style={{backgroundColor: 'orange', color: 'whitesmoke'}}>Update</Button> </DialogActions> </Dialog> {/* Open delete dialog */} <Dialog open={openDel} onClose={handleCloseDel} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <Alert severity="error" variant="filled"> <AlertTitle><strong>Delete</strong></AlertTitle> <DialogTitle id="alert-dialog-title">{"Are You Sure You Want To Delete?"}</DialogTitle> <DialogContent> <DialogContentText color="white" id="alert-dialog-description"> Deleting will be a permanent action and data pervailing will be permanently deleted and can not be retrieved back. </DialogContentText> </DialogContent> </Alert> <DialogActions> <Button onClick={handleCloseDel} color="primary" variant="outlined"> Disagree </Button> <Button onClick={(e) => handleDelete(components.id)} color="secondary" variant="outlined" autoFocus> Agree </Button> </DialogActions> </Dialog> </> ) } export default DQComponentsView <file_sep>/src/Pages/Design-Specs/DScomps/SpecDetails.jsx import { TextField, Button, IconButton } from "@material-ui/core" import { useState } from "react" import { useEffect } from "react" import { db } from "../../../firebase" import { firebaseLooper } from "../../../utils/tools" import DeleteSweepIcon from '@material-ui/icons/DeleteSweep'; import { Alert } from "@material-ui/lab" function SpecDetails({match, tid}) { const [descs, setDescs] = useState([]) const [desc, setDesc] = useState('') const [error, setError] = useState('') useEffect(() => { db.collection('DQNew').doc(match.params.id) .collection('content').doc('designSpecs').collection('points') .where('tid', '==', `${tid}`).onSnapshot(snap => { const data = firebaseLooper(snap) data.sort(function(a,b){ return(a.index-b.index) }) setDescs(data) }) }, []) function handleChange(id, data){ const desc = data db.collection('DQNew').doc(match.params.id) .collection('content').doc('designSpecs').collection('points') .doc(id).update({desc}).then(() => {setError("")}) } function handleDelete (id){ db.collection('DQNew').doc(match.params.id) .collection('content').doc('designSpecs').collection('points') .doc(id).delete() } function handleSubmit(){ if(desc?.trim().length === 0){ return setError("Can not add blank spaces as input!") } db.collection('DQNew').doc(match.params.id) .collection('content').doc('designSpecs').collection('points') .add({desc,tid,index: descs.length}).then(() => {setError("")}) } return ( <div> {error && <Alert severity="error">{error}</Alert>} { descs.map(data => ( <div style={{display: 'flex', justifyContent: 'space-between'}}> <p className='text-2xl mr-3'>⦿</p> <TextField multiline className='mb-5' variant='outlined' fullWidth key={data.id} defaultValue={data.desc} onChange={handleChange(data.id,data.desc)}/> <IconButton onClick={(e) =>handleDelete(data.id)}><DeleteSweepIcon className='hover:text-red-600' /></IconButton> </div> )) } <div className='p-10' style={{display: 'flex', justifyContent: 'space-evenly'}}> <TextField className='mr-5 mb-10' variant='outlined' fullWidth label='Add new Data' onChange={(e) => setDesc(e.target.value)}/> <Button onClick={handleSubmit} disabled={desc===''} style={{color: 'orange'}} >Add </Button> </div> </div> ) } export default SpecDetails <file_sep>/src/Pages/Reports/BatchData/Results.jsx import React, { useEffect, useState } from 'react'; import clsx from 'clsx'; import PropTypes from 'prop-types'; import moment from 'moment'; import PerfectScrollbar from 'react-perfect-scrollbar'; import { Avatar, Box, Card, Checkbox, Table, TableBody, TableCell, TableHead, TablePagination, TableRow, Typography, makeStyles, Button, Dialog, DialogTitle, DialogContent, DialogActions, Container } from '@material-ui/core'; import getInitials from './getInitials'; import { database } from '../../../firebase'; import { firebaseLooperTwo } from '../../../utils/tools'; import { Alert, AlertTitle } from '@material-ui/lab'; import TestHome from '../../Tests/TestHome'; import TestData from '../../Tests/TestData'; const useStyles = makeStyles((theme) => ({ root: {}, avatar: { marginRight: theme.spacing(2) } })); const Results = ({values, className, customers, ...rest }) => { const classes = useStyles(); const [selectedCustomerIds, setSelectedCustomerIds] = useState([]); const [limit, setLimit] = useState(10); const [page, setPage] = useState(0); const [open, setOpen] = useState(false) const [openGraph, setOpenGraph] = useState(false) const [batch, setBatch] = useState([]); useEffect(() => { database.ref('recipes/').get().then((snapshot) => { const data = firebaseLooperTwo(snapshot) console.log(data) setBatch(data) }) }, []) const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const handleGraphOpen = () => { setOpenGraph(true) } const handleGraphClose = () => { setOpenGraph(false) } return ( <Card className={clsx(classes.root, className)} {...rest} > <PerfectScrollbar> <Table > <TableRow hover key={values.key} > <TableCell padding="checkbox"> <Checkbox defaultChecked color="primary" disabled /> </TableCell> <TableCell align="left"> <Box alignItems="center" display="flex" > <Typography color="textPrimary" variant="h4" > {values.title} </Typography> </Box> </TableCell> <TableCell align="right"> <Button onClick={handleClickOpen} style={{color: "white", backgroundColor: "blue", borderRadius: "15px", marginRight: "20px"}}>Show Data</Button> <Button onClick={handleGraphOpen} style={{color: "white", backgroundColor: "rebeccapurple", borderRadius: "15px"}}>Show Graph</Button> </TableCell> {/* Dialog box data */} <Dialog open={open} onClose={handleClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">{`Details for ${values.title}`}</DialogTitle> <DialogContent> <Alert severity="info" variant="standard"> <AlertTitle> Batch Details </AlertTitle> </Alert> <form > <Table> <TableHead> <TableRow> <TableCell align="center"> <strong>CB </strong> </TableCell> <TableCell align="center"> <strong>Step </strong> </TableCell> <TableCell align="center"> <strong>Temp</strong> </TableCell> <TableCell align="center"> <strong>Time</strong> </TableCell> <TableCell align="center"> <strong>Keep Time</strong> </TableCell> <TableCell align="center"> <strong>Pressure</strong> </TableCell> </TableRow> </TableHead> <TableBody> {values.arrayList.map((data) => ( <TableRow hover > <TableCell padding="checkbox"> <Checkbox defaultChecked /> </TableCell> <TableCell> <Box alignItems="center" display="flex" > <Typography color="textPrimary" variant="body1" > {data.step} </Typography> </Box> </TableCell> <TableCell> <Typography color="textPrimary" variant="body1" > {data.temp1} </Typography> </TableCell> <TableCell> {data.time1} </TableCell> <TableCell> {data.time2} </TableCell> <TableCell> {data.pressure} </TableCell> </TableRow> ))} </TableBody> </Table> </form> <DialogActions> <Button onClick={handleClose} color="primary" variant="outlined"> Close </Button> </DialogActions> </DialogContent> </Dialog> {/* Dialog for Graph */} <Dialog style={{ }} open={openGraph} onClose={handleGraphClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">{`Details for ${values.title}`}</DialogTitle> <DialogContent> <Alert severity="info" variant="standard"> <AlertTitle> Graph for {values.title} </AlertTitle> </Alert> <Box mt={3} minWidth={550}> <TestData data={values.arrayList}/> </Box> <DialogActions> <Button onClick={handleGraphClose} color="primary" variant="outlined"> Close </Button> </DialogActions> </DialogContent> </Dialog> </TableRow> </Table> </PerfectScrollbar> </Card> ); }; Results.propTypes = { className: PropTypes.string, }; export default Results<file_sep>/src/components/AddUser/UserItem.jsx import React, { useState } from 'react'; import { Avatar, Button, Card, Container, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Grid, InputLabel, makeStyles, Select, TextField, Typography } from '@material-ui/core'; import { useHistory } from 'react-router-dom'; import Alert from '@material-ui/lab/Alert'; import {db} from '../../firebase' import VisibilityIcon from '@material-ui/icons/Visibility'; import EditIcon from '@material-ui/icons/Edit'; import DeleteForeverIcon from '@material-ui/icons/DeleteForever'; const useStyles = makeStyles((theme) => ({ root: { borderBottomColor: "black", backgroundColor: theme.palette.background.dark, }, statsItem: { alignItems: 'center', display: 'flex' }, statsIcon: { marginRight: theme.spacing(1) }, dataBox:{ marginBottom: "50px", alignItems: "center" }, divButton: { color: "#32e0c4", borderRadius: "10px", width: "100px", }, del:{ color: "red", borderRadius:"10px" }, large: { marginRight: '5%', width: 70, height: 70, }, })); export default function UserItem({ users}) { const classes = useStyles() const [open, setOpen] = useState(false) const [openEdit, setOpenEdit] = useState(false) const [openView, setOpenView] = useState(false) const [firstName, setFirstName] = useState(users.firstName) const [lastName, setLastName] = useState(users.lastName) const [password, setPassword] = useState(users.password) const [email, setEmail] = useState(users.email); const [phone, setPhone] = useState(users.phone) const [role, setRole] = useState(users.role) const [loading, setLoading] = useState(false); const [error,setError] = useState("") const history = useHistory() const handleView = () => { setOpenView(true) } const handleViewClose = () => { setOpenView(false) } const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const handleEdit = () => { setOpenEdit(true) } const handleEditClose = () => { setOpenEdit(false) } const handleDelete = (id) => { db.collection('users').doc(id).delete().then(() => { }) } const updateUser=(id) => { const updatedUser = {firstName,lastName,phone,role,email,password} db.collection('users').doc(id).update(updatedUser) } return ( <> <> {/* <Grid xs={12}> <Avatar className={classes.large} src={users.url}></Avatar> <Typography align="center" variant="h6">{users.firstName} {users.lastName}</Typography> <Typography align="center" variant="body2">{users.email} || {users.phone}</Typography> <Grid className={classes.statsItem} item > <Typography color="textSecondary" display="inline" variant="body2" > {users.role} </Typography> </Grid> </Grid> */} <Card style={{width: '45%', marginRight: '4%', marginBottom: '2%', justifyContent:'space-between'}}> <div style={{display: 'flex', justifyContent: 'flex-end', marginRight: '2%', padding: '20px'}}> <Button style={{opacity: 0.5}} startIcon={<EditIcon/>} onClick={handleEdit} ></Button> <Button style={{opacity: 0.5}} startIcon={<DeleteForeverIcon/>} onClick={handleClickOpen} ></Button> </div> <div style={{display: 'flex', margin: '15px', marginTop: '0px'}}> <Avatar src={users.url} className={classes.large}/> <div > < > <Typography align="left" variant="h6" style={{opacity: 1, font: 'var(--unnamed-font-style-normal) normal bold var(--unnamed-font-size-18)/13px var(--unnamed-font-family-roboto)', color: '#4D4F5C'}}><b>{users.firstName} {users.lastName}</b></Typography> </> <Typography align="left" variant="body2" style={{opacity: 0.5, font: 'normal normal normal 15px/25px Roboto'}}>{users.role}</Typography> <Typography style={{opacity: 0.5, color: '#43425D'}} align="left" >Email : {users.email}</Typography> <Typography style={{opacity: 0.5, color: '#43425D'}} align="left" >Phone: {users.phone}</Typography> </div> </div> </Card> <Dialog open={open} onClose={handleClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">{"Are You Sure You Want To Delete?"}</DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> Deleting will be a permanent action and data pervailing will be permanently deleted and can not be retrieved back. </DialogContentText> </DialogContent> <DialogActions> <Button onClick={handleClose} color="secondary"> Disagree </Button> <Button onClick={(e)=>{ handleDelete(users.id); handleClose()}} color="primary" autoFocus> Agree </Button> </DialogActions> </Dialog> {/* Edit dialog */} <Dialog open={openEdit} onClose={handleEditClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">{`Edit Details of ${users.firstName}`}</DialogTitle> <DialogContent> <form className={classes.form} > <Grid container spacing={2}> <Grid item xs={12} sm={6}> <TextField value={firstName} autoComplete="fname" name="firstName" variant="outlined" required fullWidth id="firstName" label="<NAME>" autoFocus onChange={(e) => setFirstName(e.target.value)} /> </Grid> <Grid item xs={12} sm={6}> <TextField value={lastName} variant="outlined" required fullWidth id="lastName" label="<NAME>" name="lastName" autoComplete="lname" onChange={(e) => setLastName(e.target.value)} /> </Grid> <Grid item xs={12}> </Grid> <Grid item xs={12}> <TextField value={phone} variant="outlined" error={phone?.length <10 || phone?.length > 10} required fullWidth name="password" label="Phone Number" type="Number" id="phone" autoComplete="current-password" onChange={(e) => setPhone(e.target.value)} /> </Grid> <Grid item xs={12}> <InputLabel htmlFor="role-native-simple">Role</InputLabel> <Select native fullWidth value={role} onChange={(e)=> setRole(e.target.value)} inputProps={{ name: 'roles', id: 'role-native-simple', }} > <option value="Admin">Admin</option> <option value="Trainee">Trainee</option> <option value="Operator">Operator</option> <option value="Supervisor">Supervisor</option> <option value="Validator">Validator</option> <option value="Maintenance">Maintenance</option> </Select> </Grid> </Grid> <DialogActions> <Button color="secondary" onClick={handleEditClose}>Close</Button> <Button variant="outlined" color="primary" disabled={phone?.length <10 || phone?.length > 10} onClick={(e)=> {updateUser(users.id); handleEditClose() } } > Update </Button> </DialogActions> </form> </DialogContent> </Dialog> {/* Edit Dialog close */} {/* View Dialog */} <Dialog open={openView} onClose={handleViewClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">{`Details for ${users.firstName}`}</DialogTitle> <DialogContent> <form className={classes.form} > <Grid container spacing={2}> <Grid item xs={12} sm={6}> <TextField value={firstName} autoComplete="fname" name="firstName" variant="outlined" required fullWidth id="firstName" label="<NAME>" autoFocus disabled /> </Grid> <Grid item xs={12} sm={6}> <TextField value={lastName} variant="outlined" required fullWidth id="lastName" label="<NAME>" name="lastName" autoComplete="lname" disabled /> </Grid> <Grid item xs={12}> <TextField value={email} variant="outlined" required fullWidth id="email" label="Email Address" name="email" autoComplete="email" disabled /> </Grid> <Grid item xs={12}> <TextField value={phone} variant="outlined" required fullWidth name="password" label="Phone Number" type="Number" id="phone" autoComplete="current-password" disabled /> </Grid> <Grid item xs={12}> <InputLabel htmlFor="role-native-simple">Role</InputLabel> <Select native fullWidth value={role} disabled inputProps={{ name: 'roles', id: 'role-native-simple', }} > <option value="Admin">Admin</option> <option value="Trainee">Trainee</option> <option value="Operator">Operator</option> <option value="Supervisor">Supervisor</option> <option value="Validator">Validator</option> <option value="Maintenance">Maintenance</option> </Select> </Grid> </Grid> <DialogActions> <Button color="secondary" onClick={handleViewClose}>Cancel</Button> </DialogActions> </form> </DialogContent> </Dialog> </> </> ) } <file_sep>/src/Pages/VideoCallPage/RenderCall.jsx import React from 'react' import OpenTokPage from './OpenTokPage' import config from './config'; const RenderCall = () => { return ( <OpenTokPage apiKey={config.API_KEY} sessionId={config.SESSION_ID} token={config.TOKEN} /> ) } export default RenderCall <file_sep>/src/Pages/MiddlePage/Graph/RecipeeList.jsx import { Button, Container, FormControl, Grid, InputLabel, Menu, MenuItem, NativeSelect, Select } from '@material-ui/core' import { Title } from '@material-ui/icons' import React, { useEffect, useState } from 'react' import { db } from '../../../firebase' import { firebaseLooper } from '../../../utils/tools' import TestData from '../../Tests/TestData' import FetchRecipee from './FetchRecipee' import GraphData from './GraphData' import GraphDataRecipee from './GraphDataRecipee' const RecipeeList = () => { const [recipeeData, setRecipeeData] = useState([]) const [title, setTitle] = useState('') useEffect(() => { db.collection('recipes').onSnapshot(doc => { const data = firebaseLooper(doc) setRecipeeData(data) }) }, [recipeeData]) const handleChange = (event) => { setTitle(event.target.value); }; return ( <Container> <Grid item xs={12}> <InputLabel color="secondary" variant="outlined"></InputLabel> <FormControl> <Select fullWidth variant="outlined" native value={title} required onChange={(e) => setTitle(e.target.value)} > { recipeeData.map(data => ( <option key={data.title} value={data.id}>{data.title}</option> )) } </Select> </FormControl> </Grid> <h1>{title}</h1> <FetchRecipee title={title}/> </Container> ) } export default RecipeeList <file_sep>/src/Pages/Reports/BatchLogs/BatchLog.jsx import { Button, makeStyles, Typography } from '@material-ui/core'; import React, { useEffect, useState } from 'react' import Sidebar from '../../../components/Sidebar/Sidebar'; import BatchLogList from './BatchLogList'; const useStyles = makeStyles((theme) =>( { add: { background:'#141256', borderRadius: '20px', margin: theme.spacing(3, 0, 2), } })) const BatchLogs = ({match}) => { const classes = useStyles(); const [isLoading, setIsLoading] = useState(true); const [batch, setBatch] = useState(null); const [error, setError] = useState(null) useEffect(() => { database.ref('recipes/' ).get().then((snapshot) => { const data = firebaseLooperTwo(snapshot) console.log(data) setBatch(data) }) }, []) return ( <> <Sidebar match={match}/> {error && <Typography variant="h6">{error}</Typography>} {isLoading && <Typography variant="h3">Loading...</Typography>} {batch && <BatchLogList batch={batch} />} </> ) } export default BatchLogs;<file_sep>/src/components/DropZone/Dropzone.jsx import React, { useState, useEffect } from "react"; import { Grid, Box } from "@material-ui/core"; import ImagesDropzone from "./imagesDropzone"; import ImageElement from "./imageElement"; import { db } from "../../firebase"; export default function Dropzone() { const [imageList, setImageList] = useState([]); const changeImageField = (index, parameter, value) => { const newArray = [...imageList]; newArray[index][parameter] = value; setImageList(newArray); }; const handleChangeOrderUp = (index) => { // If first, ignore if (index !== 0) { const newArray = [...imageList]; const intermediate = newArray[index - 1]; newArray[index - 1] = newArray[index]; newArray[index] = intermediate; setImageList(newArray); } }; const handleChangeOrderDown = (index) => { // If last, ignore if (index < imageList.length - 1) { const newArray = [...imageList]; const intermediate = newArray[index + 1]; newArray[index + 1] = newArray[index]; newArray[index] = intermediate; setImageList(newArray); } }; const handleDeleteImage = (index) => { imageList[index].storageRef .delete() .then(() => { const newArray = [...imageList]; newArray.splice(index, 1); setImageList(newArray); }) .catch((error) => { console.log("Error deleting file:", error); }); }; useEffect(() => { imageList.forEach((image, index) => { if (image.status === "FINISH" || image.status === "UPLOADING") return; changeImageField(index, "status", "UPLOADING"); const uploadTask = image.storageRef.put(image.file); uploadTask.on( "state_changed", null, function error(err) { console.log("Error Image Upload:", err); }, async function complete() { const downloadURL = await uploadTask.snapshot.ref.getDownloadURL(); db.collection('stepData') changeImageField(index, "downloadURL", downloadURL); changeImageField(index, "status", "FINISH"); } ); }); }); return ( <Grid container direction="column" alignItems="center" spacing={2}> <Box border={1} margin={4} padding={3}> <Grid item container direction="column" alignItems="center" xs={12} spacing={1} > <Grid item container xs={12} justify="center"> <ImagesDropzone setImageList={setImageList} /> </Grid> </Grid> </Box> {imageList.length > 0 && ( <Box bgcolor="primary.light" p={4}> {imageList.map((image, index) => { return ( <Grid item key={image.file.size + index}> <ImageElement image={image} index={index} isFirstElement={index === 0} isLastElement={index === imageList.length - 1} handleChangeOrderUp={handleChangeOrderUp} handleChangeOrderDown={handleChangeOrderDown} handleDeleteImage={handleDeleteImage} changeImageField={changeImageField} /> </Grid> ); })} </Box> )} </Grid> ); }<file_sep>/src/Pages/Reports/BatchData/data.js import { v4 as uuid } from 'uuid'; import faker from 'faker' export default [ { id: uuid(), avatarUrl: faker.image.image(), createdAt: faker.time.recent(), email: faker.internet.email(), name: faker.name.findName(), operator: faker.name.findName(), phone: faker.phone.phoneNumber() }, { id: uuid(), operator: faker.name.findName(), avatarUrl: faker.image.image(), createdAt: faker.time.recent(), email: faker.internet.email(), name: faker.name.findName(), phone: faker.phone.phoneNumber() }, { id: uuid(), operator: faker.name.findName(), avatarUrl: faker.image.image(), createdAt: faker.time.recent(), email: faker.internet.email(), name: faker.name.findName(), phone: faker.phone.phoneNumber() }, { id: uuid(), operator: faker.name.findName(), avatarUrl: faker.image.image(), createdAt: faker.time.recent(), email: faker.internet.email(), name: faker.name.findName(), phone: faker.phone.phoneNumber() }, { id: uuid(), operator: faker.name.findName(), avatarUrl: faker.image.image(), createdAt: faker.time.recent(), email: faker.internet.email(), name: faker.name.findName(), phone: faker.phone.phoneNumber() }, { id: uuid(), operator: faker.name.findName(), avatarUrl: faker.image.image(), createdAt: faker.time.recent(), email: faker.internet.email(), name: faker.name.findName(), phone: faker.phone.phoneNumber() }, { id: uuid(), operator: faker.name.findName(), avatarUrl: faker.image.image(), createdAt: faker.time.recent(), email: faker.internet.email(), name: faker.name.findName(), phone: faker.phone.phoneNumber() }, { id: uuid(), operator: faker.name.findName(), avatarUrl: faker.image.image(), createdAt: faker.time.recent(), email: faker.internet.email(), name: faker.name.findName(), phone: faker.phone.phoneNumber() }, { id: uuid(), operator: faker.name.findName(), avatarUrl: faker.image.image(), createdAt: faker.time.recent(), email: faker.internet.email(), name: faker.name.findName(), phone: faker.phone.phoneNumber() }, { id: uuid(), operator: faker.name.findName(), avatarUrl: faker.image.image(), createdAt: faker.time.recent(), email: faker.internet.email(), name: faker.name.findName(), phone: faker.phone.phoneNumber() }, ];<file_sep>/src/Pages/Approval/ApprovalPrint.jsx import { Card, DialogContent, makeStyles, Typography } from "@material-ui/core" import { Dialog } from "@material-ui/core" import { Paper, Table, TableCell, TableContainer, TableHead, TableRow, Toolbar } from "@material-ui/core" import { useEffect, useState } from "react" import { Button } from "react-bootstrap" import { NavLink } from "react-router-dom" import DQLayout from "../../components/DQNewSidebar/DQLayout" import DQRLayout from "../../components/DQRLayout/DQRLayout" import { db } from "../../firebase" import { firebaseLooper } from "../../utils/tools" import AddApproval from "./AddApproval" import ApprovalCView from "./ApprovalCView" import ApprovalView from "./ApprovalView" import PrintView from "./PrintView" const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'whitesmoke', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 250 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); function ApprovalPrint({match}) { const [checked, setChecked] = useState(false) const [approvalC, setApprovalC] = useState([]) const [approvalV, setApprovalV] = useState([]) const [open, setOpen] = useState(false) const classes = useStyles() function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } useEffect(() => { db.collection('DQNewReport') .doc(match.params.id) .collection('content') .doc('approval') .collection('customer') .onSnapshot(snap => { const data = firebaseLooper(snap) setApprovalC(data) }) db.collection('DQNewReport') .doc(match.params.id) .collection('content') .doc('approval') .collection('vendor') .onSnapshot(snap => { const data = firebaseLooper(snap) setApprovalV(data) }) },[]) return (<> <div > <div > <Card > <div> <Typography variant='h2' align='center' gutterBottom>PROTOCOL PREPARED AND REVIEWED BY</Typography> <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}><b className='text-lg font-bold italic'>Name</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-lg font-bold italic'>Sign</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-lg font-bold italic'>Date / Time</b></TableCell> </TableRow> </TableHead> { approvalV.map(data => ( <> <PrintView data={data} match={match} key={data.id}/> </> )) } </Table> </TableContainer> <br /> <hr /> <Typography variant='h2' align='center' gutterBottom>CUSTOMER DETAILS</Typography> <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}><b className='text-lg font-bold italic'>Name</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-lg font-bold italic'>Sign</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-lg font-bold italic'>Date / Time</b></TableCell> </TableRow> </TableHead> { approvalC.map(data => ( <> <PrintView data={data} match={match} key={data.id}/> </> )) } </Table> </TableContainer> <Dialog open={open} onClose={handleClose} fullWidth > <DialogContent> <AddApproval match={match}/> </DialogContent> </Dialog> </div> </Card> </div> </div> </> ) } export default ApprovalPrint <file_sep>/src/components/AddUser/Users.jsx import { Button, CircularProgress, Container, Fade, makeStyles, Paper, Typography } from '@material-ui/core'; import React, { useEffect, useState } from 'react' import UserList from './UserList'; import {Link, NavLink, useHistory} from 'react-router-dom'; import { db } from '../../firebase'; import {firebaseLooper} from '../../utils/tools' import AddIcon from '@material-ui/icons/Add'; import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import { useAuth } from '../context/AuthContext'; import LogIn from '../LogIn/LogIn'; import UserItem from './UserItem'; import Page from '../Page'; const useStyles = makeStyles((theme) =>( { add: { backgroundImage: 'linear-gradient(to left bottom, #fa630f, #fc8218, #fd9d29, #feb63f, #ffce59)', margin: theme.spacing(3, 0, 2), marginRight: '10%', }, backButton: { backgroundColor: "#A997DF", color: "white", borderRadius: "20px", } })) const Users = () => { const count = 0 const classes = useStyles(); const [isLoading, setIsLoading] = useState(true); const [users, setUsers] = useState([{}]); const {currentUser} = useAuth() const [admin, setAdmin] = useState(false) const [error, setError] = useState(null) const [searchTerm, setSearchTerm] = useState('') const history = useHistory() useEffect(() => { db.collection('users').orderBy('role', 'asc').onSnapshot(snapshot => { const userData = firebaseLooper(snapshot) setUsers(userData) setIsLoading(false) }) }, []) const handleReturn = () => { history.push('/') } return ( <Page title='Users | LyoIms'> <Paper style={{backgroundColor: '#FFFFFF'}}> <Container style={{background: ' 0% 0% no-repeat padding-box', boxShadow: '0px 2px 6px #0000000A'}}> <div style={{display: 'flex', justifyContent: 'space-between'}}> <div> <Typography style={{color: '#43425D'}} variant='h1'><b>Users</b></Typography> <Typography variant='h5' style={{color: '#43425D'}}>List of available users</Typography> </div> {error && <Typography variant="h6">{error}</Typography>} </div> <div style={{display: 'flex', justifyContent: 'flex-end'}}> <div className="relative"> <input style={{ border: '2px solid whitesmoke',}} onChange={(e) => setSearchTerm(e.target.value)} type="text" className="h-14 w-96 pr-5 pl-5 rounded z-0 focus:shadow focus:outline-none" placeholder="Search Users..."/> <div className="absolute top-4 right-3"> <i className="fa fa-search text-gray-400 z-20 hover:text-gray-500"></i> </div> </div> <Button component={NavLink} to={`/users/add-user`} style={{width: '15%', marginLeft: '4%', marginRight: '3%',color: 'white', backgroundColor: 'orange'}}>Add User</Button> </div> <br className='bg-gray-100'/> <br className='bg-gray-100'/> <section class="text-gray-700 "> <div className=" "> <div class="flex flex-wrap text-left"> { users. filter((data) => { if(searchTerm === ""){ return data } else if (data.email.toLowerCase().includes(searchTerm.toLowerCase())){ return data }else if (data.firstName.toLowerCase().includes(searchTerm.toLowerCase())){ return data } else if (data.lastName.toLowerCase().includes(searchTerm.toLowerCase())){ return data }else if (data.phone.toLowerCase().includes(searchTerm.toLowerCase())){ return data } }).map((users) => ( <> <UserItem key={users.id} users={users} /> <br /> <br /> </> )) } </div> </div> </section> {isLoading && <CircularProgress /> } </Container> </Paper> </Page> ) } export default Users <file_sep>/src/Pages/MiddlePage/Graph/FetchRecipee.jsx import React, { useEffect, useState } from 'react' import { db } from '../../../firebase' import { firebaseLooper } from '../../../utils/tools' import TestData from '../../Tests/TestData' import GraphData from './GraphData' import GraphDataRecipee from './GraphDataRecipee' const FetchRecipee = ({title}) => { const [rData, setRData] = useState([]) const rid =`${title}` console.log(rid) useEffect(() => { db.collection('recipeeData').where('rid', '==', rid).onSnapshot(doc => { const data = firebaseLooper(doc) setRData(data) }) },[]) return ( <div> <h1>{rid}</h1> <GraphData data={rData}/> </div> ) } export default FetchRecipee <file_sep>/src/TestGraph/TestGraph.jsx import React, { useEffect, useRef, useState } from "react"; import { db } from "../firebase"; import FetchRecipee from "./FetchRecipee"; import { firebaseLooper } from "../utils/tools"; import { Button, Card, FormControl, FormHelperText, Grid, Input, InputLabel, MenuItem, Select } from "@material-ui/core"; import GraphSelect from "./GraphSelect"; import Chartjs from "chart.js"; const chartConfig = { type: "line", data: { labels: [], datasets: [ { fill: 'false', label: "Temperature", yAxisID: "y-axis-0", data: [], borderWidth: 1, lineTension: 0.1, backgroundColor: 'yellow', borderColor: 'yellow', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'yellow', pointBackgroundColor: 'yellow', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: '#ff7a00', pointHoverBorderColor: '#7868e6', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, }, { fill: 'false', yAxisID: "y-axis-1", label: "Pressure", data: [], lineTension: 0.1, backgroundColor: 'orangered', borderColor: 'orangered', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'orangered', pointBackgroundColor: 'orangered', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: '#ff7a00', pointHoverBorderColor: '#7868e6', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, borderWidth: 1 }, { yAxisID: "y2", label: 'RealTime', fill: false, lineTension: 0.1, backgroundColor: 'green', borderColor: 'green', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'green', pointBackgroundColor: 'green', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: 'green', pointHoverBorderColor: '#7868e6', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [] }, ] }, options: { legend: { position: 'bottom', labels: { fontColor: 'white' } }, title: { display: true, text: "Select/Change The Required to Showcase Data" }, tooltips: { mode: 'label' }, interaction: { mode: 'index', intersect: false, }, responsive: true, scales: { xAxes: [{ display: true, stacked: false, ticks: { autoSkip: true, maxTicksLimit: 15, fontColor: 'white', fontSize: 10, animation: { easing: 'linear' } } }], ticks: { major: { fontStyle: 'bold', fontColor: '#FF0000' } }, yAxes: [{ stacked: true, position: "left", id: "y-axis-0", title: 'Temp Set Point', ticks: { steps: 10, max: 50, fontColor: 'white', fontSize: 14, min: -100 }, }, { stacked: false, display: false, position: "left", id: "y2", title: 'Realtime', ticks: { steps: 10, max: 50, fontColor: 'white', fontSize: 14, min: -100 }, }, { stacked: false, position: "right", id: "y-axis-1", fontColor: 'white', ticks: { steps: 100, fontColor: 'white', fontSize: 14 }, }, ] } } }; const TestGraph = () => { const [recipes, setRecipes] = useState([]) const [rid, setRid] = useState('') const [machines, setMachines] = useState([]) const [rData, setRdata] = useState([]) const [realData, setRealData] = useState([]) const [batch, setBatch] = useState([]) const [batchId, setBatchId] = useState([]) const [mid, setMid] = useState('') let time = [] let temp = [] let stillTime = [] let pressure = [] let delta = [] let deltaP =[] const [stillTimeData, setStillTimeData] = useState([]) const [deltaTemp, setDeltaTemp] = useState([]) const [deltaPressure, setDeltaP] = useState([]) const [tempData, setTempData] = useState([]) const [pressureData, setPressureData] = useState([]) const chartContainer = useRef(null); const [chartInstance, setChartInstance] = useState(null); useEffect(() => { db.collection('machineData').onSnapshot(doc => { const data = firebaseLooper(doc) setMachines(data) }) if (chartContainer && chartContainer.current) { const newChartInstance = new Chartjs(chartContainer.current, chartConfig); setChartInstance(newChartInstance); } }, [chartContainer]); const updateDataset = (time, newData, pressure) => { chartInstance.data.labels = time chartInstance.data.datasets[0].data = newData; chartInstance.data.datasets[1].data = pressure; chartInstance.data.datasets[2].data = realData; chartInstance.update(); }; const onButtonClick = (e) => { e.preventDefault() var x, y, z; var randomTemp, randomPressure; let currTemp=0; let currPressure= 800; let currTime = 0; for (let index = 0; index < rData.length; index++) { x = (rData[index].temp1 - currTemp)/rData[index].time1 y = (rData[index].pressure - currPressure)/rData[index].time1 for (let j = 0; j < rData[index].time1 ; j++) { currTime++; currTemp = currTemp + x; randomTemp = currTemp + Math.floor(Math.random() * x) currPressure = currPressure + y randomPressure = currPressure+ Math.floor(Math.random() * y) time.push(currTime) temp.push(currTemp) pressure.push(currPressure) delta.push(randomTemp) deltaP.push(randomPressure) } for (let k = 0; k < rData[index].time2; k++) { currTime++ time.push(currTime) delta.push(randomTemp + Math.random() * x) deltaP.push (randomPressure + Math.random()*y) temp.push(currTemp) pressure.push(currPressure) } } setTempData(temp) setStillTimeData(stillTime) setPressureData(pressure) setDeltaP(deltaP) setDeltaTemp(delta) updateDataset(time, temp, pressure); }; function handleChange(e){ setRid(e.target.value) const recipe_id = e.target.value db.collection('realtimeData').where('recipe_id', '==',`${recipe_id}`).onSnapshot(doc => { const data = firebaseLooper(doc) setBatch(data) }) } function handleBatchChange(e){ setBatchId(e.target.value) let batch_id = e.target.value db.collection('realtimeData').where('recipe_id','==', `${rid}`).where('time', '==', `${batch_id}`).onSnapshot(doc => { const data = firebaseLooper(doc) setRealData(data[0].temp_points) }) db.collection('recipeeData').where('rid', '==', `${rid}`).onSnapshot(doc => { const data = firebaseLooper(doc) data.sort(function(a,b) { return(a.index-b.index) }) setRdata(data) }) } function handleSetChange(e){ let mid = e.target.value db.collection('recipes').where('mid', '==',`${mid}`).onSnapshot(doc => { const data = firebaseLooper(doc) setRecipes(data) }) } return ( <Card > <form onSubmit={onButtonClick}> <Grid container spacing={3} style={{display: 'flex', justifyContent: 'space-evenly', marginLeft: '3%', marginBottom: '12px', marginTop: '5px'}} > <Grid item lg={3} sm={6} xl={3} xs={12} > <FormControl className='form-select mt-1 block w-full' fullWidth variant="outlined"> <InputLabel id="demo-simple-select-outlined-label">Select Machine</InputLabel> <Select label='Select Machine' required onChange={handleSetChange} > <MenuItem value=""> <em>None</em> </MenuItem> { machines.map(data => ( <MenuItem value={data.id}>{data.title}</MenuItem> )) } </Select> </FormControl> </Grid> <Grid item lg={3} sm={6} xl={3} xs={12} > <FormControl className='form-select mt-1 block w-full' fullWidth variant="outlined"> <InputLabel id="demo-simple-select-outlined-label">Select Recipes</InputLabel> <Select required label="Select Recipes" variant='outlined' fullWidth onChange={handleChange} > { recipes.map(data => ( <MenuItem value={data.id}>{data.title}</MenuItem> )) } </Select> </FormControl> </Grid> <Grid item lg={3} sm={6} xl={3} xs={12}> <FormControl className='form-select mt-1 block w-full' fullWidth variant="outlined"> <InputLabel id="demo-simple-select-outlined-label">Select Batch</InputLabel> <Select required label='Select Batch' fullWidth variant='outlined' onChange={(e) => {handleBatchChange(e) }}> { batch.map(data => ( <MenuItem value={data.time}>{data.time}</MenuItem> )) } </Select> </FormControl> </Grid> <Grid item lg={3} sm={6} xl={3} xs={12} > <Button type="submit" className=' mt-3 block ' style={{backgroundColor: 'orange', color: 'white'}}>Show Graph</Button> </Grid> </Grid> </form> <Card style={{padding: '15px'}}> <canvas style={{background: 'black'}} ref={chartContainer} /> </Card> </Card> ); } export default TestGraph;<file_sep>/src/Pages/DQNew/forms/AddType1.jsx import { TextField } from "@material-ui/core" function AddType1({match}) { return ( <div> <TextField variant='outlined' fullWidth lablel='Title' style={{marginBottom: '25px'}} /> <TextField variant='outlined' fullWidth lablel='Description' style={{marginBottom: '25px'}} /> </div> ) } export default AddType1 <file_sep>/src/Pages/IQ/IQ.jsx import { Dialog, Toolbar } from "@material-ui/core"; import { Typography } from "@material-ui/core"; import { Button, DialogContent, DialogActions, TextField } from "@material-ui/core"; import { makeStyles, Card } from "@material-ui/core"; import { SettingsOutlined } from "@material-ui/icons"; import { useEffect, useState } from "react"; import ContentDashboardLayout from "../../components/ContentSidebar/ContentDashboardLayout"; import { db } from "../../firebase"; import { firebaseLooper } from "../../utils/tools"; import IQHeader from "./IQComponents/IQHeader"; import IQView from "./IQComponents/IQView"; import { v4 as uuidv4 } from 'uuid'; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'whitesmoke', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 250 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); function IQ({match}) { const classes = useStyles() const [iq, setIq] = useState([]) const [open, setOpen] = useState(false) const [name, setName] = useState('') const [ desc, setDesc] = useState('') const uid = uuidv4() const [mid, setMid] = useState(match.params.id) useEffect(() => { db.collection('IQ') .where('mid', '==', `${match.params.id}`) .onSnapshot(snapshot => { const data = firebaseLooper(snapshot) setIq(data) }) }, []) function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleSubmit(){ db.collection('IQ').add({name,desc,mid}).then((data) => { const key = data.id db.collection('IQ').doc(data.id).update({key}) }) } return ( <div> <ContentDashboardLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <Toolbar style={{display: 'flex', justifyContent: 'flex-end'}}> <Button onClick={handleOpen} style={{background: 'orange', color: 'whitesmoke'}}>Add IQ</Button> </Toolbar> <section class="text-gray-600 body-font"> <div class="container px-5 py-24 mx-auto"> <div class="flex flex-wrap -m-4"> { iq.map(data => ( <IQView match={match} data={data} key={data.id}/> )) } <Dialog open={open} onClose={handleClose} fullWidth> <Typography variant='h3' align='center'><b>Add new IQ</b></Typography> <DialogContent> <TextField variant='outlined' label='Title' fullWidth onChange={(e) => setName(e.target.value)}/> <TextField multiLine rows={7} variant='outlined' label='Description' fullWidth onChange={(e) => setDesc(e.target.value)}/> </DialogContent> <DialogActions> <Button color='secondary' onClick={handleClose} variant='contained'>Cancel</Button> <Button disabled={name === '' || desc===''} onClick={handleSubmit} style={{background: 'orange', color: 'white'}}>Add IQ</Button> </DialogActions> </Dialog> </div> </div> </section> </Card> </div> </div> </div> ) } export default IQ <file_sep>/src/Pages/ContentsData/ComponentData/AddComponents.jsx import { Button, Card, Container, makeStyles, TextField, Typography } from '@material-ui/core' import Alert from '@material-ui/lab/Alert'; import React, { useState } from 'react'; import {useHistory} from 'react-router-dom' import ModuleDashboardLayout from '../../../components/ModuleSidebar/ModuleDashboardLayout'; import { db } from '../../../firebase'; const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, form: { alignItems: "center", justifyContent: "center", width: '90%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { backgroundImage: 'linear-gradient(to left bottom, #fa630f, #fc8218, #fd9d29, #feb63f, #ffce59)', color: "white", borderRadius: '20px', margin: theme.spacing(3, 0, 2), }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); const AddComponent = ({match}) => { const classes= useStyles(); const [title, setContentName] = useState('') const [value, setValue] = useState('') const [loading, setLoading] = useState(false); const [module_id, setMid] = useState(match.params.id) const history = useHistory(); const handleSubmit = (e) => { e.preventDefault(); const content = {title,value, module_id}; setLoading(true); db.collection('componentData').add(content).then((data) =>{ console.log(data) history.push(`/Module/${match.params.id}/Components`) }) } return ( <> <ModuleDashboardLayout match={match}/> <div> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div className={classes.paper}> <Alert severity="info">You are currently adding a new Module</Alert> <br/> <Typography component="h1" variant="h4"> Add Components </Typography> <form className={classes.form} onSubmit={handleSubmit}> <TextField value={module_id} fullWidth variant="outlined" margin="normal" label="Machine id" disabled onChange ={(e) => setMid(e.target.value)} /> <TextField value={title} variant="outlined" margin="normal" required fullWidth id="content_name" label="Title" name="content_name" autoFocus onChange={(e) => setContentName(e.target.value)} /> <TextField value={value} variant="outlined" margin="normal" required fullWidth id="content_name" label="Expected Value" name="content_name" autoFocus onChange={(e) => setValue(e.target.value)} /> {!loading && <Button type="submit" fullWidth variant="contained" className={classes.submit} > Add Component </Button>} { loading && <Button type="submit" fullWidth variant="contained" disabled className={classes.submit} >Adding Component...</Button> } </form> </div> </Card> </div> </div> </div> </> ) } export default AddComponent <file_sep>/src/Pages/Manuals/Manuals.jsx import React, { Fragment, useEffect, useState } from 'react'; import './Manuals.css' import { Grid, Card, CardContent, Button, makeStyles, Typography, Container, TextField } from '@material-ui/core'; import { db } from '../../firebase'; import { firebaseLooper } from '../../utils/tools'; import ContentDashboardLayout from '../../components/ContentSidebar/ContentDashboardLayout'; import ManualItem from './ManualItem'; import Page from '../../components/Page'; import { NavLink } from 'react-router-dom'; import SearchIcon from '@material-ui/icons/Search'; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'white', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', background:'linear-gradient(#f3f3f3, #e7e7e7)' }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); export default function Manuals({match}) { const classes = useStyles() const [manuals, setManuals] = useState([]) const [searchTerm, setSearchTerm] = useState('') const [mTitle, setMTitle] = useState('') useEffect(() => { db.collection('machineData') .doc(match.params.id) .onSnapshot(doc => { setMTitle(doc.data().title) }) db.collection('manualData').where('mid', '==', `${match.params.id}`).onSnapshot(doc => { const data = firebaseLooper(doc) setManuals(data) }) },[]) return ( <Page title='Manuals | LyoIms'> <ContentDashboardLayout match={match}/> <Container maxWidth={false} className={classes.wrapper}> <div className={classes.container}> <div className={classes.content}> {/* <div style={{display: 'flex', justifyContent: 'space-between'}}> <div style={{paddingLeft: "2.5rem"}}> <Typography variant='h1' align='left'><b>Manuals Data</b></Typography> <Typography variant='body2' align='left' gutterBottom >These are all your Manuals</Typography> </div> <div style={{display: 'flex', justifyContent: 'flex-end'}}> <div className="relative"> <input style={{ border: '2px solid whitesmoke'}} onChange={(e) => setSearchTerm(e.target.value)} type="text" className="h-14 w-96 pr-8 pl-5 rounded z-0 focus:shadow focus:outline-none" placeholder="Search Manuals..."/> <div className="absolute top-4 right-3"> <SearchIcon style={{opacity: '0.5'}}/> </div> </div> <Button component={NavLink} to={`/machine-data/${match.params.id}/Add-Manuals`} color='primary' variant='contained' style={{width: '150px', marginLeft: '4%', marginRight: '6%',color: 'white'}}>Add </Button> </div> </div> */} <div style={{display: 'flex', justifyContent: 'space-between'}}> {/* <Typography style={{marginRight: '15px'}} variant='h1' align='center'><b>{mTitle} : </b></Typography> */} <div style={{paddingLeft: '2.5rem'}} > <Typography variant='h1' align='left'><b>Manuals</b></Typography> <Typography align='left' variant='body2' > These are all the required Manuals and data </Typography> </div> <div> <div style={{display: 'flex', justifyContent: 'flex-end'}}> <div className="relative"> <input style={{ border: '2px solid whitesmoke'}} onChange={(e) => setSearchTerm(e.target.value)} type="text" className="h-14 w-96 pr-8 pl-5 rounded z-0 focus:shadow focus:outline-none" placeholder="Search Manuals..."/> <div className="absolute top-4 right-3"><SearchIcon style={{opacity: '0.5'}}/> </div> </div> <Button color='primary' variant='contained' style={{width: '150px', marginLeft: '4%', marginRight: '2%', color: 'white'}} component={NavLink} to={`/machine-data/${match.params.id}/Add-Manuals`}>ADD New </Button> <hr/> </div> </div> </div> <br/> {/* <b>{searchTerm}</b> */} <Grid container spacing={3}> <> { manuals .filter((data) => { if(searchTerm === ""){ return data } else if (data.title.toLowerCase().includes(searchTerm.toLocaleLowerCase())){ return data } else if (data.desc.toLowerCase().includes(searchTerm.toLocaleLowerCase())){ return data } }) .map((data) => ( <ManualItem key={data.id} data={data}/> )) } </> </Grid> </div> </div> </Container> </Page> ); }<file_sep>/src/Pages/JobsData/JobView.jsx import { Button, Checkbox, Dialog, DialogActions, DialogContent, FormControl, FormHelperText, IconButton, InputLabel, MenuItem, Select, TableCell, TableRow, TextField, Typography } from "@material-ui/core" import DoneIcon from '@material-ui/icons/Done'; import ErrorOutlineIcon from '@material-ui/icons/ErrorOutline'; import { useEffect, useState } from "react"; import { db } from "../../firebase"; import EditIcon from '@material-ui/icons/Edit'; import { firebaseLooper } from "../../utils/tools"; import DeleteSweepIcon from '@material-ui/icons/DeleteSweep'; import { Alert, AlertTitle } from "@material-ui/lab"; function JobView({row, match}) { const [users, setUsers] = useState([]) const [status, setStatus] = useState(row.status) const [email, setEmail] = useState(row.email) const [title, setTitle] = useState(row.title) const [desc, setDesc] = useState(row.desc) const [open, setOpen] = useState(false) const [openEdit, setOpenEdit] = useState(false) useEffect(() => { db.collection('users').onSnapshot((snap) => { const data = firebaseLooper(snap) setUsers(data) }) }, []) function handleSubmit(e){ e.preventDefault() db.collection('jobData').doc(row.id).update({email,title,desc,status}).then(() => setOpenEdit(false)) } function handleDelete(e){ db.collection('jobData').doc(row.id).delete() } return ( <> <TableRow key={row.id}> <TableCell style={{width: 160, backgroundColor: '#e8ffff'}} component="th" scope="row"> <b> {row.title}</b> </TableCell> <TableCell align="left">{row.desc}</TableCell> <TableCell align="left">{row.email}</TableCell> <TableCell align="left">{row.date.toDate().toString().substring(0,15)}</TableCell> <TableCell align="right">{row.status ? <b style={{color: '#9ede73', display: 'flex', justifyContent: 'flex-end'}}><DoneIcon style={{color: '#9ede73'}}/>Completed</b> : <b style={{color: 'orange', display: 'flex', justifyContent: 'flex-end'}}><ErrorOutlineIcon style={{color: '#ff7a00d'}}/> Pending</b>} </TableCell> <TableCell align="right"> <IconButton> <EditIcon onClick={(e) => setOpenEdit(!openEdit)} /> </IconButton> <IconButton> <DeleteSweepIcon onClick={(e) => setOpen(!open)}/> </IconButton> </TableCell> </TableRow> <Dialog fullWidth open={openEdit} onClose={(e) => setOpenEdit(false)} > <Typography style={{marginTop:'15px'}} variant="h3" align="center" gutterBottom ><b>Edit {title}</b></Typography> <form action="" onSubmit={handleSubmit}> <DialogContent> <TextField required label="Title" value={title} onChange={(e) => setTitle(e.target.value)} fullWidth variant="outlined" /> <FormHelperText style={{marginBottom: '3%'}}>Title should be max {title.length}/40</FormHelperText> <TextField value={desc} onChange={(e) => setDesc(e.target.value)} style={{marginBottom: '3%'}} required label=" Description " fullWidth variant="outlined" /> <FormControl required style={{marginBottom: '3%'}} variant='outlined' fullWidth> <InputLabel variant='outlined'> Select Assignee</InputLabel> <Select value={email} onChange={(e) => setEmail(e.target.value)} label='Select Assignee'> { users.map((user) => ( <MenuItem value={user.email}>{user.firstName} {user.lastName}</MenuItem> )) } </Select> </FormControl> <div style={{display: 'flex'}}> <Checkbox checked={status} onChange={(e) => setStatus(!status)}/> <Typography>{status ? <b style={{color: 'green'}}> Completed</b> : <b className='text-yellow-800'>Pending</b>} </Typography> </div> </DialogContent> <DialogActions> <Button onClick={(e) => setOpenEdit(false)}>Cancel</Button> <Button type="submit" style={{color: 'white', backgroundColor: 'orange'}}> Update</Button> </DialogActions> </form> </Dialog> <Dialog fullWidth open={open} onClose={(e) => setOpen(false)} > <DialogContent> <Alert variant="filled" severity='error'> <AlertTitle> Delete </AlertTitle> Are you sure you want to delete this Job ? Once deleted can't be recovered. </Alert> </DialogContent> <DialogActions> <Button onClick={(e) => setOpen(false)}color='primary' >Cancel</Button> <Button onClick={handleDelete} style={{backgroundColor: 'red' , color: 'white'}}>Delete</Button> </DialogActions> </Dialog> </> ) } export default JobView <file_sep>/src/Pages/VideoCallPage/OpenTokPage.jsx import React from 'react'; import './OpenTok.css'; import { OTSession, OTStreams, preloadScript } from 'opentok-react'; import ConnectionStatus from './components/ConnectionStatus'; import Publisher from './components/Publisher'; import Subscriber from './components/Subscriber'; import { Container, Grid, makeStyles } from '@material-ui/core'; const useStyles = makeStyles((theme) => ({ root: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', overflow: 'hidden', backgroundColor: theme.palette.background.paper, }, gridList: { width: 500, height: 450, }, icon: { color: 'rgba(255, 255, 255, 0.54)', }, })); class OpenTokPage extends React.Component { constructor(props) { super(props); this.state = { error: null, connected: false }; this.sessionEvents = { sessionConnected: () => { this.setState({ connected: true }); }, sessionDisconnected: () => { this.setState({ connected: false }); } }; } onError = (err) => { this.setState({ error: `Failed to connect: ${err.message}` }); } render() { return ( <Container style={{display: 'flex'}}> <div> <OTSession apiKey={this.props.apiKey} sessionId={this.props.sessionId} token={this.props.token} eventHandlers={this.sessionEvents} onError={this.onError} > {this.state.error ? <b id="error">{this.state.error}</b> : null} <ConnectionStatus connected={this.state.connected} /> <Grid container > <Grid item lg={4} sm={6} xl={3} xs={12}> <Publisher /> </Grid> </Grid> <OTStreams> <Grid container > <Grid item lg={3} sm={6} xl={3} xs={12}> <Subscriber /> </Grid> </Grid> </OTStreams> </OTSession> </div> </Container> ); } } export default preloadScript(OpenTokPage);<file_sep>/src/Pages/VideoCallPage/components/Subscriber.jsx import React from 'react'; import '../OpenTok.css' import { OTSubscriber } from 'opentok-react'; import CheckBox from './CheckBox'; import { Button, Card, Container, Dialog, Grid } from '@material-ui/core'; import screenfull from 'screenfull'; import Toolbar from '@material-ui/core/Toolbar'; import IconButton from '@material-ui/core/IconButton'; import CloseIcon from '@material-ui/icons/Close' import '../OpenTok.css'; class Subscriber extends React.Component { constructor(props) { super(props); this.state = { error: null, audio: true, video: true, open: false }; } setAudio = (audio) => { this.setState({ audio }); } setVideo = (video) => { this.setState({ video }); } onError = (err) => { this.setState({ error: `Failed to subscribe: ${err.message}` }); } handleMode = () => { this.setState({open: true}) } handleClose = () => { this.setState({open: false}) } render() { return ( <> <Grid item lg={4} sm={6} xl={3} xs={12} > { this.state.open? <Dialog fullScreen open={this.state.open} onClose={this.handleClose} > <Toolbar> <IconButton edge="start" color="inherit" onClick={this.handleClose} aria-label="close"> <CloseIcon /> </IconButton> </Toolbar> <OTSubscriber properties={ { width: 1080, height:726, subscribeToAudio: false, subscribeToVideo: this.state.video }} onError={this.onError} /> </Dialog> : <OTSubscriber properties={ { width: 500, height:350, subscribeToAudio: this.state.audio, subscribeToVideo: this.state.video, showControls: true }} onError={this.onError} /> } <Card style={{width:'500px', display: 'flex', justifyContent: 'space-between'}}> <div> <CheckBox label="Subscribe to Audio" initialChecked={this.state.audio} onChange={this.setAudio} /> </div> <div> <CheckBox label="Subscribe to Video" initialChecked={this.state.video} onChange={this.setVideo} /> </div> <div> <Button onClick={this.handleMode}>Change Mode</Button> </div> </Card> </Grid> <div> {this.state.error ? <div id="error">{this.state.error}</div> : null} </div> </> ); } } export default Subscriber; <file_sep>/src/Pages/MiddlePage/subcomponents/DQtable.jsx import React, { useEffect, useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import { db } from '../../../firebase'; import { firebaseLooper } from '../../../utils/tools'; import { Button, Card, Container, Dialog, DialogActions, DialogContent, DialogTitle, FormControl, Grid, InputLabel, MenuItem, Select, TablePagination, TextField, Typography } from '@material-ui/core'; import StepDashboardLayout from '../../../components/StepSidebar/StepDashboardLayout' import TestData from '../../../Pages/Tests/TestData' import { NavLink } from 'react-router-dom'; import { Alert } from '@material-ui/lab'; import DateRangeIcon from '@material-ui/icons/DateRange'; const useStyles = makeStyles((theme) => ({ table: { minWidth: 650, }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); export default function DQtable() { const classes = useStyles(); const [recipeeData, setRecipeeData] = useState([]) const [open, setOpen] = useState(false) const [machines, setMachines] = useState([]) const [title, setTitle] = useState("") useEffect(() => { db.collection("machineData").onSnapshot(snap => { const data = firebaseLooper(snap) setMachines(data) }) db.collection('DQNewReport').onSnapshot(doc => { const data = firebaseLooper(doc) console.log(data) setRecipeeData(data) }) }, []) function handleChange(e){ const rep = e.target.value db.collection('DQNewReport') .where('mid', '==', rep) .onSnapshot(doc => { const data = firebaseLooper(doc) console.log(data) setRecipeeData(data) }) } return ( <div> <FormControl variant='outlined' fullWidth > <InputLabel>Select</InputLabel> <Select onChange={handleChange} label="Select"> {machines.map(data => ( <MenuItem key={data.id} value={data.id}>{data.title}</MenuItem> )) } </Select> </FormControl> <Alert severity='info'>Select Machine to sort by Machines</Alert> {recipeeData && recipeeData . filter((row) => { if(title === null || title === ""){ return row } else if (row.title.toLowerCase().includes(title.toLocaleLowerCase())){ return row } else if (row.desc.toLowerCase().includes(title.toLocaleLowerCase())){ return row } return row }) .map((row) => ( <div style={{width: '100%', display: 'flex', justifyContent: 'space-evenly'}}> <NavLink className='text-md text-gray-800 hover:text-gray-600' to={`/DQR/${row.id}/Approval`}>{row.name}</NavLink> <Typography variant='body2' align='left' className='text-sm text-gray-800 hover:text-gray-600'><DateRangeIcon style={{width: '15px'}} />{row.timestamp.toDate().toString().substring(0,15)}</Typography> </div> ))} </div> ) } <file_sep>/src/Pages/DQNewReports/DQRpurpose.jsx import { Typography , Card, makeStyles} from "@material-ui/core" import { useEffect } from "react" import { useState } from "react" import DQRLayout from "../../components/DQRLayout/DQRLayout" import { db } from "../../firebase" const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'whitesmoke', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 250 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); function DQRpurpose({match}) { const [purpose, setPurpose] = useState({}) const classes = useStyles() useEffect(() => { db.collection('DQNewReport') .doc(match.params.id) .collection('content') .doc('purpose') .onSnapshot(snapshot => { const data = snapshot.data() setPurpose(data) }) }, []) return ( <div> <DQRLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div style={{height: '100vh'}}> {purpose && <Typography variant='h1' align='center' gutterBottom><b>{purpose.title}</b></Typography> }<hr /> {purpose && <Typography variant='body1' align='left' gutterBottom><p className='italic'>{purpose.desc}</p></Typography> }<hr /> </div> </Card> </div> </div> </div> ) } export default DQRpurpose <file_sep>/src/Pages/Attachments/AttachView/AttachView.jsx import { Button, Dialog, DialogActions,Toolbar, DialogContent, DialogContentText, DialogTitle, TableBody, TableCell, TableRow, TextField, Typography, FormHelperText } from "@material-ui/core" import { Alert, AlertTitle } from "@material-ui/lab" import { useState } from "react" import { db } from "../../../firebase" import EditIcon from '@material-ui/icons/Edit'; import DeleteIcon from '@material-ui/icons/Delete'; function AttachView({module, match}) { const [title, setTitle] = useState(module.title) const [dno, setDno] = useState(module.dno) const [rev, setRev] = useState(module.rev) const [desc, setDesc] = useState(module.desc) const [open, setOpen] = useState(false) const [error, setError] = useState("") const [openDel, setOpenDel] = useState(false) const [openC, setOpenC] = useState(false) function handleOpenDel(){ setOpenDel(true) } function handleCloseDel(){ setOpenDel(false) } function openComponent(){ setOpenC(true) } function closeComponent(){ setOpenC(false) } function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleUpdate(e){ e.preventDefault() if(desc?.trim().length === 0 || rev?.trim().length === 0){ return setError("Empty spaces are not valid inputs ! please try again with a valid input") } db.collection('DQNew').doc(match.params.id) .collection('content').doc('attachments') .collection('details') .doc(module.id) .update({ desc,rev,dno}) .then(() =>{setOpen(false)}) } function handleDelete(id){ db.collection('DQNew').doc(match.params.id) .collection('content').doc('attachments') .collection('details') .doc(id) .delete() } return ( <> <TableBody> <TableRow key={module.id}> <TableCell className='text-3xl' scope="row"> ⚫ </TableCell> <TableCell align="left">{module.desc}</TableCell> <TableCell align="left">{module.dno}</TableCell> <TableCell align="left">{module.rev}</TableCell> <TableCell align="right"> <div> <Button onClick={handleOpen}><EditIcon/></Button> <Button onClick={handleOpenDel}><DeleteIcon/></Button> </div> </TableCell> </TableRow> </TableBody> <Dialog style={{alignItems: 'center'}} fullWidth open={open} onClose={handleClose}> <form onSubmit={handleUpdate} > <DialogContent> <Typography variant='h4' align='center' gutterBottom><b>Edit Details</b></Typography> {error && <Alert severity="error" >{error}</Alert>} <TextField label="Description" required multiline rows={5} value={desc} variant='outlined' error={desc.length > 150} fullWidth onChange={(e) => setDesc(e.target.value)}/> <FormHelperText style={{marginBottom: '3%'}}>Description should be max {desc.length}/150</FormHelperText> <TextField label="Drawing Number" style={{marginBottom: '3%'}} value={dno} variant='outlined' fullWidth onChange={(e) => setDno(e.target.value)}/> <TextField label="Revision" required style={{marginBottom: '3%'}} value={rev} variant='outlined' fullWidth onChange={(e) => setRev(e.target.value)}/> </DialogContent> <DialogActions> <Button onClick={handleClose}>Cancel</Button> <Button type="submit" disabled={desc.length > 150} style={{backgroundColor: 'orange', color: 'whitesmoke'}}>Update</Button> </DialogActions> </form> </Dialog> {/* Open delete dialog */} <Dialog open={openDel} onClose={handleCloseDel} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <Alert severity="error" variant="filled"> <AlertTitle><strong>Delete</strong></AlertTitle> <DialogTitle id="alert-dialog-title">{"Are You Sure You Want To Delete?"}</DialogTitle> <DialogContent> <DialogContentText color="white" id="alert-dialog-description"> Deleting will be a permanent action and data pervailing will be permanently deleted and can not be retrieved back. </DialogContentText> </DialogContent> </Alert> <DialogActions> <Button onClick={handleCloseDel} color="primary" variant="outlined"> Disagree </Button> <Button onClick={(e) => handleDelete(module.id)} color="secondary" variant="outlined" autoFocus> Agree </Button> </DialogActions> </Dialog> </> ) } export default AttachView<file_sep>/src/App.js import LogIn from "./components/LogIn/LogIn" import {BrowserRouter as Router, Switch, Route, BrowserRouter} from 'react-router-dom'; //import Sidebar from "./components/Sidebar/Sidebar"; import { Process, Reports } from "./Pages/Reports/Reports"; import './App.css' import Machines from "./components/Machines/Machines"; import AddMachines from "./components/Machines/AddMachines"; import AddUser from "./components/AddUser/AddUser"; import CustomerListView from "./components/LogsData/Logs"; import Steps from "./Pages/Steps/Steps"; import AddContent from "./Pages/MachineContents/AddContent"; import AddSteps from "./Pages/Steps/AddSteps"; import BatchListView from './Pages/Reports/BatchData/Logs' import MiddlePage from "./Pages/MiddlePage/MiddlePage"; import AppRoute from "./routes/AppRoute"; import MainLayout from "./layouts/MainLayout/MainLayout"; import Users from "./components/AddUser/Users"; import { AuthProvider, useAuth } from "./components/context/AuthContext"; import ForgotPass from "./components/ForgotPass/ForgotPass"; import ContentsData from "./Pages/ContentsData/ContentsData"; import Page from "./components/Page"; import Tests from "./Pages/Tests/Tests"; import AccountDetails from "./components/Account/AccountDetails"; import NotFoundView from "./Pages/Error/NotFoundView"; import BatchInfo from "./Pages/BatchInfo/BatchInfo"; import RenderVc from "./components/VideoCall/RenderVc"; import DashboardLayout from './Demo/DashboardLayout' import { ThemeProvider } from "@material-ui/styles"; import theme from "./theme/index"; import GlobalStyles from "./components/GlobalStyles"; import Recipes from "./Pages/Recipee/Recipes"; import AddRecipe from "./Pages/Recipee/AddRecipe"; import RecipeeValuesView from "./Pages/Recipee/RecipeeValues/RecipeeValuesView"; import AddRecipeeValues from "./Pages/Recipee/RecipeeValues/AddRecipeeValues"; import JobsList from "./Pages/JobsData/JobsList"; import ModuleComponents from "./Pages/ContentsData/ComponentData/ModuleComponents"; import Manuals from "./Pages/Manuals/Manuals"; import AddManuals from "./Pages/Manuals/AddManuals"; import AddComponent from "./Pages/ContentsData/ComponentData/AddComponents"; import DQReport from "./Pages/DQReport/DQReport"; import BatchReport from "./Pages/BatchInfo/BatchInfo"; import QualityReport from './Pages/QualityReport/QualityReport' import CallLogs from "./Pages/CallLogs/CallLogs"; import TestGraph from "./TestGraph/TestGraph"; import Settings from "./Pages/settings/Settings"; import OpenTokPage from "./Pages/VideoCallPage/OpenTokPage"; import RenderCall from "./Pages/VideoCallPage/RenderCall"; import { Paper } from "@material-ui/core"; import NewVideoCall from "./components/VideoCall/NewVideoCall"; import FileManagerView from "./Pages/FileManager/FileManagerView"; import AddFiles from "./Pages/FileManager/AddFiles"; import UserManual from "./Pages/user_manual/UserManual"; import WorkFlow from "./Pages/MiddlePage/WorkFlow"; import Whiteboard from "./components/Whiteboard/Whiteboard"; import ModelThreeD from "./components/3DModel/ModelThreeD"; import TestVideo from "./VideoCallModel/TestVideo"; import EntryPage from "./VideoCallModel/EntryPage"; import DQNew from "./Pages/DQNew/DQNew"; import DQContent from "./Pages/DQNew/DQContent"; import DQPurpose from "./Pages/DQPages/DQPurpose"; import DQGeneral from "./Pages/DQPages/DQGeneral"; import DQConfigD from "./Pages/DQConfig/DQConfig"; import DQSpecs from "./Pages/DQPages/DQSpecs"; import DQRnew from "./Pages/DQNewReports/DQRnew"; import DQRpurpose from "./Pages/DQNewReports/DQRpurpose"; import DQRgeneral from "./Pages/DQNewReports/DQRgeneral"; import DQRConfig from "./Pages/DQNewReports/DQRConfig"; import DQRSpecs from "./Pages/DQNewReports/DQRSpecs"; import IQ from "./Pages/IQ/IQ"; import IQIndex from "./Pages/IQ/IQPages.jsx/IQIndex"; import IQScope from "./Pages/IQ/IQPages.jsx/IQScope"; import IQDrawing from "./Pages/IQ/IQPages.jsx/IQDrawing"; import IQControlPanel from "./Pages/IQ/IQPages.jsx/IQControlPanel"; import IQSoftware from "./Pages/IQ/IQPages.jsx/IQSoftware"; import Approval from "./Pages/Approval/Approval"; import DesignSpecs from "./Pages/Design-Specs/DesignSpecs"; import Safety from "./Pages/safety/Safety"; import Attachments from "./Pages/Attachments/Attachments"; import Abbreviations from "./Pages/abbreviations/Abbreviations"; import DQRSafety from "./Pages/DQNewReports/DQRSafety"; import DQRSpecsd from "./Pages/DQNewReports/DQRSpecsd"; import DQRAttachments from "./Pages/DQNewReports/DQRAttachments"; import DQRApproval from "./Pages/DQNewReports/DQRApproval"; import PrintScreen from "./Pages/printComponent/PrintScreen"; function App() { return ( <div style={{color: '#43425D'}}> <GlobalStyles/> <AuthProvider> <Page title="Lyo Ims" > <ThemeProvider theme={theme}> <BrowserRouter> <Router> <Switch> <Route path="/login" exact component={LogIn} /> <AppRoute path='/machine-data/:id/Reports' exact component={Reports} layout={MainLayout}/> <AppRoute path='/machine-data/:id/Call-Logs' exact component={CallLogs} layout={MainLayout} /> <AppRoute path='/machine-data/Reports/:id/Recipes' exact component={Recipes} layout={MainLayout} /> <AppRoute path='/machine-data/Reports/:id/Add-Recipes' exact component={AddRecipe} layout={MainLayout} /> <AppRoute path='/machine-data/reports/:id/process' exact component={Process} layout={MainLayout} /> <AppRoute path='/Recipe/:id/Recipe-values' exact component={RecipeeValuesView} layout={MainLayout} /> <AppRoute path='/Recipe/:id/Add-Recipee-Data' exact component={AddRecipeeValues} layout={MainLayout} /> <AppRoute path='/machine-data/:id/Module' exact component={ContentsData} layout={MainLayout} /> <AppRoute path="/machine-data/:id/Add-module" exact component={AddContent} layout={MainLayout}/> <AppRoute path="/machine-data" exact component={Machines} layout={DashboardLayout}/> <AppRoute path="/settings" exact component={Settings} layout={DashboardLayout}/> <AppRoute path="/add-machine" exact component={AddMachines} layout={DashboardLayout} /> <Route path="/forgotPass" exact component={ForgotPass}/> <AppRoute path="/machine-data/Job/:id/Job" exact component={JobsList} layout={MainLayout} /> <AppRoute path="/DQ/:id/content" exact component={DQContent} layout={MainLayout} /> <AppRoute path="/DQ/:id" exact component={QualityReport} layout={MainLayout} /> <AppRoute path="/Module/:id/Components" exact component={ModuleComponents} layout={MainLayout} /> <AppRoute path="/users/add-user" exact component={AddUser} layout={DashboardLayout}/> <AppRoute path="/account" exact component={AccountDetails} layout={DashboardLayout}/> <AppRoute path="/Manuals/:id/Steps" exact component={Steps} layout={MainLayout}/> <AppRoute path="/Manuals/:id/Add-Step" exact component={AddSteps} layout={MainLayout}/> <AppRoute path="/" exact component={MiddlePage} layout={DashboardLayout}/> <AppRoute path="/users" exact component={Users} layout={DashboardLayout}/> <AppRoute path="/machine-data/Batch/:id/Batch" exact component={BatchReport} layout={MainLayout}/> <AppRoute path="/machine-data/:id/Add-Manuals" exact component={AddManuals} layout={MainLayout} /> <AppRoute path="/Module/:id/Add-Component" exact component={AddComponent} layout={MainLayout} /> {/*/machine-data/Reports/BXLmS3MAwjf25qEdubL6/Recipes*/} <AppRoute path="/machine-data/Manuals/:id/Manuals" exact component={Manuals} layout={MainLayout} /> <AppRoute path="/video-call" exact component={EntryPage} layout={DashboardLayout} /> <Route path="/video-call/:id" exact component={EntryPage} layout={MainLayout} /> <AppRoute path="/machine-data/DQ-Reports/:id/DQ-Reports" exact component={DQReport} layout={MainLayout} /> <AppRoute path="/Manuals/:id/3D-Model" exact component={ModelThreeD} layout={MainLayout}/> <AppRoute path="/Add-files" exact component={AddFiles} layout={DashboardLayout}/> <AppRoute path="/file-manager" exact component={FileManagerView} layout={DashboardLayout}/> <AppRoute path="/user-manual" exact component={UserManual} layout={DashboardLayout}/> <Route path='/whiteboard' exact component={Whiteboard} layout={MainLayout}/> <AppRoute path='/machine-data/:id/DQ-New' exact component={DQNew} layout={MainLayout} /> <AppRoute path='/machine-data/:id/DQ-New-Reports' exact component={DQRnew} layout={MainLayout} /> <AppRoute path='/DQ/:id/Purpose' exact component={DQPurpose} layout={MainLayout} /> <AppRoute path='/DQR/:id/Purpose' exact component={DQRpurpose} layout={MainLayout} /> <AppRoute path='/DQ/:id/General-Information' exact component={DQGeneral} layout={MainLayout} /> <AppRoute path='/DQR/:id/General-Information' exact component={DQRgeneral} layout={MainLayout} /> <AppRoute path='/DQ/:id/Equipment-Config' exact component={DQConfigD} layout={MainLayout} /> <AppRoute path='/DQR/:id/Equipment-Config' exact component={DQRConfig} layout={MainLayout} /> <AppRoute path='/DQR/:id/Specifications' exact component={DQRSpecs} layout={MainLayout} /> <AppRoute path='/DQ/:id/Specifications' exact component={DQSpecs} layout={MainLayout} /> <AppRoute path='/machine-data/:id/IQ' exact component={IQ} layout={MainLayout} /> <AppRoute path='/IQ/:id/index' exact component={IQIndex} layout={MainLayout} /> <AppRoute path='/IQ/:id/scope' exact component={IQScope} layout={MainLayout} /> <AppRoute path='/IQ/:id/drawing' exact component={IQDrawing} layout={MainLayout} /> <AppRoute path='/IQ/:id/control' exact component={IQControlPanel} layout={MainLayout} /> <AppRoute path='/IQ/:id/software' exact component={IQSoftware} layout={MainLayout} /> <AppRoute path='/DQ/:id/Approval' exact component={Approval} layout={MainLayout} /> <AppRoute path='/DQR/:id/Approval' exact component={DQRApproval} layout={MainLayout} /> <AppRoute path='/DQ/:id/Design-Specs' exact component={DesignSpecs} layout={MainLayout} /> <AppRoute path='/DQR/:id/Design-Specs' exact component={DQRSpecsd} layout={MainLayout} /> <AppRoute path='/DQ/:id/Safety' exact component={Safety} layout={MainLayout} /> <AppRoute path='/DQ/:id/Attachments' exact component={Attachments} layout={MainLayout} /> <AppRoute path='/DQR/:id/Attachments' exact component={DQRAttachments} layout={MainLayout} /> <AppRoute path='/DQ/:id/Abbreviations' exact component={Abbreviations} layout={MainLayout} /> <AppRoute path='/DQR/:id/Safety' exact component={DQRSafety} layout={MainLayout} /> <AppRoute path='/DQR/:id/Print' exact component={PrintScreen} layout={MainLayout} /> </Switch> </Router> </BrowserRouter> </ThemeProvider> </Page> </AuthProvider> </div> ); } export default App; <file_sep>/src/Pages/settings/EditVideoCall.jsx import { Container, Switch, TextField } from '@material-ui/core' import React, { useEffect, useState } from 'react' import { db } from '../../firebase' const EditVideoCall = () => { const [api_key, setApiKey] = useState('') const [session_id, setSessionId] = useState('') const [token, setToken] = useState('') const [config, setConfig] = useState([]) const [disabled, setDisabled] = useState(true) useEffect(() => { db.collection('OpenTokConfig').doc('BkEGCdgSefXrFkEmzcCG').onSnapshot(snapshot => { const data = snapshot.data() setConfig(data) setApiKey(data.api_key) setSessionId(data.session_id) setToken(data.token) }) }, []) const handleUpdate = () => { db.collection('OpenTokConfig').doc('BkEGCdgSefXrFkEmzcCG').update({api_key,session_id,token}) } return ( <Container> <div class="flex bg-white-200 items-center justify-center mt-7 mb-7"> <div class="grid bg-white rounded-lg shadow-xl w-11/12 md:w-9/12 lg:w-1/2"> <div class="flex justify-center"> <div class="flex"> <h1 class="text-gray-600 font-bold md:text-2xl text-xl">Change Video Call Configuration</h1> <Switch onChange={(e) => setDisabled(!disabled)}/> </div> </div> <form style={{padding: '25px'}} action=""> <TextField disabled={disabled} onChange={(e) => setApiKey(e.target.value)} value={api_key} style={{marginBottom: '20px'}} fullWidth type="text" variant='outlined' placeholder='API key' /> <TextField disabled={disabled} onChange={(e) => setSessionId(e.target.value)} value={session_id} style={{marginBottom: '20px'}} fullWidth type="text" variant='outlined' placeholder='Session ID' /> <TextField disabled={disabled} onChange={(e) => setToken(e.target.value)} value={token} style={{marginBottom: '20px'}} fullWidth type="text" variant='outlined' placeholder='Token' /> </form> <div class='flex items-center justify-center md:gap-8 gap-4 pt-3 pb-5'> <button disabled={disabled} onClick={(e) => handleUpdate(e)} class='w-auto bg-yellow-800 hover:bg-yellow-900 rounded-lg shadow-xl font-medium text-white px-4 py-2'>Update</button> </div> </div> </div> </Container> ) } export default EditVideoCall <file_sep>/src/Pages/IQ/IQPages.jsx/IQScope.jsx import { Typography, Toolbar, TextField, Dialog, DialogContent, DialogActions, Button } from "@material-ui/core"; import { setGridPageSizeActionCreator } from "@material-ui/data-grid"; import { useEffect } from "react"; import { useState } from "react"; import { db } from "../../../firebase"; import { firebaseLooper } from "../../../utils/tools"; import IQHeader from "../IQComponents/IQHeader"; import ScopeView from "../IQComponents/ScopeView"; function IQScope({match}) { const [scope, setScope] = useState([]) const [open, setOpen] = useState(false) const [desc, setDesc] = useState('') function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleSubmit(){ var index = scope.length db.collection('IQ').doc(match.params.id) .collection('content').doc('scope') .collection('details') .add({index, desc}) } useEffect(() => { db.collection('IQ').doc(match.params.id) .collection('content').doc('scope') .collection('details') .onSnapshot(snap => { const data = firebaseLooper(snap) data.sort(function(a,b){ return(a.index-b.index) }) setScope(data) }) }, []) return ( <div> <IQHeader match={match}/> <Toolbar> <Button onClick={handleOpen}>Add New</Button> </Toolbar> <Typography variant='h1' align='center' gutterBottom ><b>SCOPE</b></Typography> <hr /> { scope.map(data => ( <ScopeView key={data.id} data={data}/> )) } <Dialog open={open} onClose={handleClose} fullWidth> <DialogContent> <TextField variant='outlined' fullWidth label='Description' onChange={(e) => setDesc(e.target.value)} /> </DialogContent> <DialogActions> <Button color='secondary' onClick={handleClose} variant='contained'>Cancel</Button> <Button disabled={ desc===''} onClick={handleSubmit} style={{background: 'orange', color: 'white'}}>Add New</Button> </DialogActions> </Dialog> </div> ) } export default IQScope <file_sep>/src/Pages/DQConfig/components/DQConfigView.jsx import { Table,Button, Dialog, DialogActions,Toolbar, DialogContent, DialogContentText, DialogTitle, TableBody, TableCell, TableRow, TextField, Typography, Collapse, Box, TableHead } from "@material-ui/core" import { Alert, AlertTitle } from "@material-ui/lab" import { useEffect, useState } from "react" import { db } from "../../../firebase" import EditIcon from '@material-ui/icons/Edit'; import DeleteIcon from '@material-ui/icons/Delete'; import { firebaseLooper } from "../../../utils/tools"; import DQComponentsView from "../../DQPages/DQCOnfigDetails/DQComponentsView"; import DQComponents from "../../DQPages/DQCOnfigDetails/DQComponents"; import BrandView from "../../brands/brandsComp/BrandView"; import ServiceView from "../../servicesreq/ServiceComp/ServiceView"; import ExpandLessIcon from '@material-ui/icons/ExpandLess'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; function DQConfigView({module, match,type}) { const [title, setTitle] = useState(module.title) const[length,setLength] = useState(0) const [desc, setDesc] = useState(module.desc) const [open, setOpen] = useState(false) const [openDel, setOpenDel] = useState(false) const [openC, setOpenC] = useState(false) const [components, setComponents] = useState([]) useEffect(() => { db.collection('DQNew').doc(match.params.id) .collection('content').doc('config') .collection('components') .where('module_id', '==', module.id) .onSnapshot(snap => { const data = firebaseLooper(snap) data.sort(function(a,b){ return(a.index-b.index) }) setComponents(data) setLength(data.length) }) }, []) function handleOpenDel(){ setOpenDel(true) } function handleCloseDel(){ setOpenDel(false) } function openComponent(){ setOpenC(true) } function closeComponent(){ setOpenC(false) } function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleUpdate(){ db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('config') .collection('module') .doc(module.id) .update({title, desc}) } function handleDelete(id){ db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('config') .collection('module') .doc(id) .delete() } return ( <> <TableBody> <TableRow key={module.id}> <TableCell style={{background: '#E8F6EF'}} component="th" scope="row"> {module.title} </TableCell> <TableCell align="left">{module.desc}</TableCell> <TableCell align="right"> <div> <Button onClick={handleOpen}><EditIcon className='animate-bounce'/></Button> <Button onClick={handleOpenDel}><DeleteIcon className='hover:text-red-600'/></Button> <Button onClick={(e) => setOpenC(!openC)}>{!openC ? <ExpandMoreIcon/> : <ExpandLessIcon/>}</Button> </div> </TableCell> </TableRow> <Collapse in={openC} timeout="auto" unmountOnExit> <DQComponents index={length} type={type} match={match} module_id={module.id}/> { type ===0 && <div style={{display: 'flex', justifyContent: 'center'}} > <br /> <Table align aria-label="purchases"> <TableHead> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}><b className='text-md font-bold italic'>Title</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-md font-bold italic'>Value</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right"><b className='text-md font-bold italic'>Actions</b></TableCell> </TableHead> <> { components.map(data => ( <DQComponentsView match={match} key={data.id} components={data}/> )) } </> </Table> </div>} { type===1 && <div style={{display: 'flex', justifyContent: 'center'}} > <br /> <Table align aria-label="purchases"> <TableHead> <> <TableRow> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}><b className='text-md font-bold italic'>Description</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-md font-bold italic'>Required Parameters</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-md font-bold italic'>Instrument/Gauges</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-md font-bold italic'>Preferred Pipe & Connection</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right"><b className='text-md font-bold italic'>Options</b></TableCell> </TableRow> </> </TableHead> <> { components.map(data => ( <ServiceView match={match} key={data.id} module={data}/> )) } </> </Table> </div> } </Collapse> </TableBody> <Dialog style={{alignItems: 'center'}} fullWidth open={open} onClose={handleClose}> <DialogContent> <Typography variant='h4' align='center' gutterBottom><b>Edit Details</b></Typography> <form > <TextField style={{marginBottom: '3%'}} value={title} variant='outlined' fullWidth onChange={(e) => setTitle(e.target.value)}/> <TextField multiline rows={7} value={desc} variant='outlined' fullWidth onChange={(e) => setDesc(e.target.value)}/> </form> </DialogContent> <DialogActions> <Button onClick={handleClose}>Cancel</Button> <Button disabled={title===''|| desc ==='' } onClick={handleUpdate} style={{backgroundColor: 'orange', color: 'whitesmoke'}}>Update</Button> </DialogActions> </Dialog> {/* Open delete dialog */} <Dialog open={openDel} onClose={handleCloseDel} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <Alert severity="error" variant="filled"> <AlertTitle><strong>Delete</strong></AlertTitle> <DialogTitle id="alert-dialog-title">{"Are You Sure You Want To Delete?"}</DialogTitle> <DialogContent> <DialogContentText color="white" id="alert-dialog-description"> Deleting will be a permanent action and data pervailing will be permanently deleted and can not be retrieved back. </DialogContentText> </DialogContent> </Alert> <DialogActions> <Button onClick={handleCloseDel} color="primary" variant="outlined"> Disagree </Button> <Button onClick={(e) => handleDelete(module.id)} color="secondary" variant="outlined" autoFocus> Agree </Button> </DialogActions> </Dialog> </> ) } export default DQConfigView <file_sep>/src/Pages/DQNewReports/ApprovalCView.jsx import { Button, Dialog, DialogActions,Toolbar, DialogContent, DialogContentText, DialogTitle, TableBody, TableCell, TableRow, TextField, Typography } from "@material-ui/core" import { Alert, AlertTitle } from "@material-ui/lab" import { useState } from "react" import EditIcon from '@material-ui/icons/Edit'; import DeleteIcon from '@material-ui/icons/Delete'; import { db } from "../../firebase"; import { useStorage } from "../../utils/useStorage"; import moment from "moment"; function ApprovalCView({data, match}) { const [name, setTitle] = useState(data.name) const [error, setError] = useState('') const types = ["image/png", "image/jpeg", "image/jpg"]; const [file, setFile] = useState(null) const [open, setOpen] = useState(false) const [openDel, setOpenDel] = useState(false) function handleOpenDel(){ setOpenDel(true) } function handleCloseDel(){ setOpenDel(false) } function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleUpdate(){ db.collection('DQNewReport') .doc(match.params.id) .collection('content') .doc('approval') .collection('customer') .doc(data.id) .update({name}) } function handleDelete(id){ db.collection('DQNewReport') .doc(match.params.id) .collection('content') .doc('approval') .collection('customer') .doc(id) .delete() } const handleChange = (e) => { let selectedFile = e.target.files[0]; if (selectedFile) { if (types.includes(selectedFile.type)) { setError(null) setFile(selectedFile); } else { setFile(null); setError("Please select an image file (png or jpg)"); } } } const {progress, url} = useStorage(file) return ( <> <TableBody> <TableRow key={data.id}> <TableCell style={{background: '#E8F6EF'}} component="th" scope="row"> {data.name} </TableCell> <TableCell align="left"><img src={data.url} width='350px' height='250px'/></TableCell> <TableCell align="left">{data.timestamp.toDate().toString().substring(0,15)}</TableCell> <TableCell align="right"> <div> <Button onClick={handleOpen}><EditIcon className='animate-bounce'/></Button> <Button onClick={handleOpenDel}><DeleteIcon className='hover:text-red-600'/></Button> </div> </TableCell> </TableRow> </TableBody> <Dialog style={{alignItems: 'center'}} fullWidth open={open} onClose={handleClose}> <DialogContent> <Typography variant='h4' align='center' gutterBottom><b>Edit Details</b></Typography> <form > <TextField style={{marginBottom: '3%'}} value={name} variant='outlined' fullWidth onChange={(e) => setTitle(e.target.value)}/> <div> <img src={data.url} height='350px' width="450px" /> <br /> <input type="file" onChange={handleChange}/> </div> </form> </DialogContent> <DialogActions> <Button onClick={handleClose}>Cancel</Button> <Button onClick={handleUpdate} style={{backgroundColor: 'orange', color: 'whitesmoke'}}>Update</Button> </DialogActions> </Dialog> {/* Open delete dialog */} <Dialog open={openDel} onClose={handleCloseDel} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <Alert severity="error" variant="filled"> <AlertTitle><strong>Delete</strong></AlertTitle> <DialogTitle id="alert-dialog-title">{"Are You Sure You Want To Delete?"}</DialogTitle> <DialogContent> <DialogContentText color="white" id="alert-dialog-description"> Deleting will be a permanent action and data pervailing will be permanently deleted and can not be retrieved back. </DialogContentText> </DialogContent> </Alert> <DialogActions> <Button onClick={handleCloseDel} color="primary" variant="outlined"> Disagree </Button> <Button onClick={(e) => handleDelete(data.id)} color="secondary" variant="outlined" autoFocus> Agree </Button> </DialogActions> </Dialog> </> ) } export default ApprovalCView <file_sep>/src/TestGraph/FetchRecipee.jsx import { Button, Grid } from '@material-ui/core' import { Alert } from '@material-ui/lab' import React, { useEffect, useState } from 'react' import { db } from '../firebase' import TestData from '../Pages/Tests/TestData' import { firebaseLooper } from '../utils/tools' import GraphSelect from './GraphSelect' import UpdateIcon from '@material-ui/icons/Update'; const FetchRecipee = ({batchId, recipes, rid}) => { const [rData, setRdata] = useState([]) const [realData, setRealData] = useState([]) const updateData = () => { db.collection('realtimeData').where('recipe_id','==', `${rid}`).where('time', '==', `${batchId}`).onSnapshot(doc => { const data = firebaseLooper(doc) setRealData(data[0].temp_points) }) db.collection('recipeeData').where('rid', '==', `${rid}`).onSnapshot(doc => { const data = firebaseLooper(doc) data.sort(function(a,b) { return(a.index-b.index) }) setRdata(data) }) } function showData (){ return( <> <GraphSelect realData={realData} rData={rData}/> </> ) } console.log(rData) return ( <div> <div style={{display: 'flex', jstifyContent: 'space-evenly'}}> <Button startIcon={<UpdateIcon/>} style={{color: 'orangered'}} onClick={updateData}>Update</Button> <Alert style={{marginLeft: '40%'}} severity='info'>Click <b>'Update'</b> and <b>'Set Graph'</b> after selecting </Alert> </div> {showData()} </div> ) } export default FetchRecipee <file_sep>/src/VideoCallModel/TestVideo.jsx import { OTSession, OTPublisher, OTStreams, OTSubscriber } from 'opentok-react'; import Page from '../components/Page.js'; import ConnectionStatus from '../Pages/VideoCallPage/components/ConnectionStatus.jsx'; import Publisher from '../Pages/VideoCallPage/components/Publisher.jsx'; function TestVideo({config}) { return ( <Page title='Video Call | LyoIms'> <div style={{background: 'black', height: '200vh'}}> <OTSession apiKey={config.api_key} sessionId={config.session_id} token={config.token}> <div style={{width: '80%', marginRight: '2%'}}> <OTStreams> <OTSubscriber properties={{ showControls: true, insertMode: 'append', width:500, height: 270 }} /> </OTStreams> </div> <div> <Publisher/> </div> </OTSession> </div> </Page> ) } export default TestVideo <file_sep>/src/Pages/ContentsData/ComponentData/ModuleComponents.jsx import React, {useEffect, useState} from 'react' import { Button, Card, Container, makeStyles, TableCell, TableFooter, TablePagination, TableRow, Typography, useTheme } from '@material-ui/core'; import IconButton from '@material-ui/core/IconButton'; import FirstPageIcon from '@material-ui/icons/FirstPage'; import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft'; import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight'; import LastPageIcon from '@material-ui/icons/LastPage'; import PropTypes from 'prop-types'; import { useHistory } from 'react-router-dom'; import { db } from '../../../firebase'; import { firebaseLooper } from '../../../utils/tools'; import ComponentDataBox from './ComponentDataBox'; import { Skeleton } from '@material-ui/lab'; import ModuleDashboardLayout from '../../../components/ModuleSidebar/ModuleDashboardLayout' const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'white', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, table: { minWidth: 500, }, root: { flexShrink: 0, marginLeft: theme.spacing(2.5), }, })); TablePaginationActions.propTypes = { count: PropTypes.number.isRequired, onChangePage: PropTypes.func.isRequired, page: PropTypes.number.isRequired, rowsPerPage: PropTypes.number.isRequired, }; function TablePaginationActions(props) { const classes = useStyles(); const theme = useTheme(); const { count, page, rowsPerPage, onChangePage } = props; const handleFirstPageButtonClick = (event) => { onChangePage(event, 0); }; const handleBackButtonClick = (event) => { onChangePage(event, page - 1); }; const handleNextButtonClick = (event) => { onChangePage(event, page + 1); }; const handleLastPageButtonClick = (event) => { onChangePage(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1)); }; return ( <div className={classes.root}> <IconButton onClick={handleFirstPageButtonClick} disabled={page === 0} aria-label="first page" > {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />} </IconButton> <IconButton onClick={handleBackButtonClick} disabled={page === 0} aria-label="previous page"> {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />} </IconButton> <IconButton onClick={handleNextButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="next page" > {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />} </IconButton> <IconButton onClick={handleLastPageButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="last page" > {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />} </IconButton> </div> ); } const ModuleComponents = ({match}) => { const [mTitle, setMTitle] = useState('') const [content, setContent] = useState([{}]) const history = useHistory() const classes = useStyles() useEffect (() => { db.collection('moduleData') .doc(match.params.id) .onSnapshot(doc => { setMTitle(doc.data().title) }) db.collection('componentData') .where('module_id' , '==' , `${match.params.id}`) .onSnapshot(doc => { const data = firebaseLooper(doc) setContent(data) }) }, []) const [page, setPage] = React.useState(0); const [rowsPerPage, setRowsPerPage] = React.useState(5); const emptyRows = rowsPerPage - Math.min(rowsPerPage, content.length - page * rowsPerPage); const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; return ( <div style={{display: 'flex'}}> <ModuleDashboardLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <Container > <Typography variant='h4' align='left'><b>{mTitle}</b></Typography> <Typography variant='h2' align='center' gutterBottom><b>Modules Components</b> </Typography> <br/> <div className={classes.container}> <Card className={classes.content}> {(rowsPerPage > 0 ? content.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : content ).map((data) => ( <ComponentDataBox key={data.id} data={data} match={match} /> ))} {emptyRows > 0 && ( <TableRow style={{ height: 53 * emptyRows }}> <TableCell colSpan={6} /> </TableRow> )} <TableFooter style={{display: 'flex', justifyContent: 'flex-end'}}> <TableRow> <TablePagination rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]} colSpan={3} count={content.length} rowsPerPage={rowsPerPage} page={page} SelectProps={{ inputProps: { 'aria-label': 'rows per page' }, native: true, }} onChangePage={handleChangePage} onChangeRowsPerPage={handleChangeRowsPerPage} ActionsComponent={TablePaginationActions} /> </TableRow> </TableFooter> </Card> </div> </Container> </Card> </div> </div> </div> ) } export default ModuleComponents<file_sep>/src/components/Machines/Machines.jsx import { Box, Button, CircularProgress, Container, Grid, makeStyles, TextField, Typography } from '@material-ui/core'; import React, { useEffect, useState } from 'react' import MachineList from './MachineList'; import {Link, NavLink} from 'react-router-dom'; import Machine from './Machine'; import {db} from '../../firebase'; import {firebaseLooper} from '../../utils/tools' import AddIcon from '@material-ui/icons/Add'; import HomeIcon from '@material-ui/icons/Home'; import Page from '../Page'; import Autocomplete from '@material-ui/lab/Autocomplete'; const useStyles = makeStyles((theme) =>( { add: { backgroundImage: 'linear-gradient(to left bottom, #fa630f, #fc8218, #fd9d29, #feb63f, #ffce59)', borderRadius: '20px', margin: theme.spacing(3, 0, 2), marginLeft: '5%' }, backButton: { backgroundColor: "black", width: "100px", color: "white", borderRadius: "15px", }, })) const Machines = () => { const classes = useStyles(); const [searchTerm, setSearchTerm] = useState('') const [isLoading, setIsLoading] = useState(true); const [machines, setMachines] = useState([{ title: '', desc: '', location: '' }]); const [error, setError] = useState(null) useEffect(() => { db.collection('machineData').onSnapshot(doc => { const data = firebaseLooper(doc) setMachines(data) setIsLoading(false); }) }, []) return ( <Page className='bg-gray-50' title="Machines | LyoIms"> <div className='bg-gray-50 ' > <div style={{display: 'flex', paddingTop: '20px', justifyContent:'space-between', paddingRight: '4.5rem', paddingLeft: '4.5rem'}}> <div > <Typography variant='h1' style={{ color: '#43425D', marginBottom: '20px'}}><>Machines</></Typography> <Typography style={{color: '#43425D'}} variant='h5'>These are the available Machines</Typography> </div> <div style={{display: 'flex', justifyContent: 'flex-end' }}> <div className="relative"> <div className="absolute top-4 right-3"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill='gray' class="bi bi-search" viewBox="0 0 16 16"> <path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/> </svg> </div> <input style={{width: '570px', height: '52px', border: '2px solid whitesmoke'}} onChange={(e) => setSearchTerm(e.target.value)} type="text" className=" pl-5 rounded z-0 focus:shadow focus:outline-none" placeholder="Search Machines..."/> </div> <Button component={NavLink} to={`/add-machine`} color='primary' variant='contained' style={{width: '129px', height: '52px', marginLeft: '4%', color: 'white'}}>Add </Button> </div> </div> {isLoading && <Typography variant="h3"> Loading...<CircularProgress size={50}/> </Typography>} <Box pt={3}> <Grid container spacing={3} > { machines && machines. filter((data) => { if(searchTerm === ""){ return data } else if (data.title.toLowerCase().includes(searchTerm.toLocaleLowerCase())){ return data } }) .map((data) => ( <Grid key={data.id} lg={4} md={6} xs={12} > <Machine key={data.id} data={data}/> </Grid> )) } </Grid> </Box> </div> </Page> ) } export default Machines <file_sep>/src/Pages/ContentsData/ComponentData/ComponentDataBox.jsx import { Button, Container, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Grid, makeStyles, TextField, Typography } from '@material-ui/core'; import React, { useEffect, useState } from 'react' import { Link, useHistory } from 'react-router-dom' import DeleteIcon from '@material-ui/icons/Delete'; import AccountTreeIcon from '@material-ui/icons/AccountTree'; import EditIcon from '@material-ui/icons/Edit'; import ArrowForwardIosIcon from '@material-ui/icons/ArrowForwardIos'; import { Alert, AlertTitle } from '@material-ui/lab'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import { db } from '../../../firebase'; import Page from '../../../components/Page'; const useStyles = makeStyles((theme) => ({ root: { borderBottomColor: "black", backgroundColor: theme.palette.background.dark, }, statsItem: { alignItems: 'center', display: 'flex' }, statsIcon: { marginRight: theme.spacing(1) }, dataBox:{ borderRadius: "20px", boxShadow: "10px 20px 30px #f8f1f1", marginBottom: "50px", alignItems: "center", justifyContent: "center", justifyItems: "center" }, divButton: { backgroundColor: "#32e0c4", marginRight: "20px", color: "white", borderRadius: "10px" }, paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { border: "#141256", borderRadius: '20px', margin: theme.spacing(3, 0, 2), } })); const ComponentDataBox = ({data}) => { const classes = useStyles(); const [open, setOpen] = useState(false) const [openEdit, setOpenEdit] = useState(false) const [title, setContentName] = useState(data.title) const [value, setValue] = useState(data.value); const [createdAt, setCreatedAt] = useState(data.createdAt); const [loading, setLoading] = useState(false); const [message, setMessage] = useState() const history = useHistory(); const handleEdit = () => { setOpenEdit(true) } const handleEditClose = () => { setOpenEdit(false) } const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const handleDelete = (id) => { db.collection('componentData').doc(id).delete() } const updateContent=(id) => { setLoading(true) db.collection('componentData').doc(id).update({title, value}).then((data) => { console.log(data) window.location.reload() setLoading(false) }) } return ( <Page title='Components data'> <div className={classes.dataBox}> <Container maxWindth="sm" sm={12}> <TableContainer component={Paper}> <Table style={{minWidth: 500}} aria-label="custom pagination table"> <TableBody> <TableRow key={data.id}> <TableCell component="th" scope="row"> <b> {data.title} </b> </TableCell> <TableCell style={{ width: 160 }} align="right"> {data.value} </TableCell> <TableCell style={{ width: 160 }} align="right"> <Button style={{ marginRight: "20%", marginTop: '0', marginBottom: '0'}} startIcon={<EditIcon/>} onClick={handleEdit} color="primary">Edit</Button> </TableCell> <TableCell style={{ width: 160 }} align="right"> <Button style={{ marginLeft: "20%"}} onClick={handleClickOpen} color="secondary" startIcon={<DeleteIcon/>}>Delete</Button> </TableCell> </TableRow> </TableBody> </Table> </TableContainer> <div style={{marginLeft: '25%'}}> {/* <Button style={{marginRight: "20%"}} startIcon={<AccountTreeIcon/>} variant="contained" className={classes.divButton}><Link to={`/Content/${data.id}/Steps`} style={{color: "white" ,textDecoration: "none"}}> Steps</Link></Button> */} </div> {/* Dialogs */} <Dialog open={open} onClose={handleClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <Alert severity="error" variant="filled"> <AlertTitle><strong>Delete</strong></AlertTitle> <DialogTitle id="alert-dialog-title">{"Are You Sure You Want To Delete?"}</DialogTitle> <DialogContent> <DialogContentText color="white" id="alert-dialog-description"> Deleting will be a permanent action and data pervailing will be permanently deleted and can not be retrieved back. </DialogContentText> </DialogContent> </Alert> <DialogActions> <Button onClick={handleClose} variant="outlined" color="primary"> Disagree </Button> <Button variant="outlined" onClick={(e)=>{ handleDelete(data.id); handleClose()}} color="secondary" autoFocus> Agree </Button> </DialogActions> </Dialog> <Dialog open={openEdit} onClose={handleEditClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">{`Edit ${title}`}</DialogTitle> <DialogContent> <Alert severity="info" variant="standard">You are currently editing Contents data</Alert> <form className={classes.form} > <TextField label="Content Name" defaultValue={title} variant="outlined" margin="normal" required fullWidth id="title" name="title" autoFocus onChange={(e) => setContentName(e.target.value)} /> <TextField label="Expected Value" defaultValue={value} variant="outlined" margin="normal" required fullWidth id="title" name="title" autoFocus onChange={(e) => setValue(e.target.value)} /> <DialogActions> <Button color="secondary" onClick={handleEditClose}>Cancel</Button> {!loading && <Button type="submit" fullWidth variant="outlined" color="primary" className={classes.submit} onClick={(e)=> updateContent(data.id)} > Update </Button>} { loading && <Button type="submit" fullWidth variant="outlined" color="primary" disabled className={classes.submit} >Updating values...</Button> } </DialogActions> </form> </DialogContent> </Dialog> </Container> </div> </Page> ) } export default ComponentDataBox <file_sep>/src/Pages/DQNewReports/DQRApproval.jsx import { Card, DialogContent, makeStyles, Typography } from "@material-ui/core" import { Dialog } from "@material-ui/core" import { Paper, Table, TableCell, TableContainer, TableHead, TableRow, Toolbar } from "@material-ui/core" import { useEffect, useState } from "react" import { Button } from "react-bootstrap" import { NavLink } from "react-router-dom" import DQRLayout from "../../components/DQRLayout/DQRLayout" import { db } from "../../firebase" import { firebaseLooper } from "../../utils/tools" import AddApproval from "./AddApproval" import ApprovalCView from "./ApprovalCView" import ApprovalView from "./ApprovalView" const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'whitesmoke', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 250 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); function DQRApproval({match}) { const [checked, setChecked] = useState(false) const [approvalC, setApprovalC] = useState([]) const [approvalV, setApprovalV] = useState([]) const [open, setOpen] = useState(false) const classes = useStyles() function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } useEffect(() => { db.collection('DQNewReport') .doc(match.params.id) .collection('content') .doc('approval') .collection('customer') .onSnapshot(snap => { const data = firebaseLooper(snap) setApprovalC(data) }) db.collection('DQNewReport') .doc(match.params.id) .collection('content') .doc('approval') .collection('vendor') .onSnapshot(snap => { const data = firebaseLooper(snap) setApprovalV(data) }) },[]) return (<> <DQRLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div> <Toolbar style={{display: 'flex', justifyContent: 'flex-end'}}> <Button onClick={handleOpen} style={{background: 'orange', color: 'white', marginBottom: '25px'}}>Add New Data</Button> </Toolbar> <Typography variant='h2' align='center' gutterBottom>PROTOCOL PREPARED AND REVIEWED BY</Typography> <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}><b className='text-lg font-bold italic'>Name</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-lg font-bold italic'>Sign</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-lg font-bold italic'>Date / Time</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right"><b className='text-lg font-bold italic'>Actions</b></TableCell> </TableRow> </TableHead> { approvalV.map(data => ( <> <ApprovalView data={data} match={match} key={data.id}/> </> )) } </Table> </TableContainer> <br /> <hr /> <Typography variant='h2' align='center' gutterBottom>CUSTOMER DETAILS</Typography> <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}><b className='text-lg font-bold italic'>Name</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-lg font-bold italic'>Sign</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-lg font-bold italic'>Date / Time</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right"><b className='text-lg font-bold italic'>Actions</b></TableCell> </TableRow> </TableHead> { approvalC.map(data => ( <> <ApprovalCView data={data} match={match} key={data.id}/> </> )) } </Table> </TableContainer> <Dialog open={open} onClose={handleClose} fullWidth > <DialogContent> <AddApproval match={match}/> </DialogContent> </Dialog> </div> </Card> </div> </div> <div style={{display: 'flex', justifyContent: 'flex-end'}}> <Button component={NavLink} to={`/DQ/${match.params.id}/Abbreviations`} style={{background: 'blue', color: 'white', marginLeft: '25px', marginRight: '4%'}}> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-90deg-left" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1.146 4.854a.5.5 0 0 1 0-.708l4-4a.5.5 0 1 1 .708.708L2.707 4H12.5A2.5 2.5 0 0 1 15 6.5v8a.5.5 0 0 1-1 0v-8A1.5 1.5 0 0 0 12.5 5H2.707l3.147 3.146a.5.5 0 1 1-.708.708l-4-4z"/> </svg> </Button> <Button component={NavLink} to={`/DQ/${match.params.id}/Purpose`} style={{background: 'blue', color: 'white', marginLeft: '25px'}}> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-90deg-right" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M14.854 4.854a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 4H3.5A2.5 2.5 0 0 0 1 6.5v8a.5.5 0 0 0 1 0v-8A1.5 1.5 0 0 1 3.5 5h9.793l-3.147 3.146a.5.5 0 0 0 .708.708l4-4z"/> </svg> </Button> </div> </> ) } export default DQRApproval <file_sep>/src/Pages/MiddlePage/Graph/GraphData.jsx import { Container } from '@material-ui/core'; import React, { useEffect, useState } from 'react' import { Line } from "react-chartjs-2"; const GraphData = ({ data}) => { let time = [] let temp = [] let stillTime = [] let pressure = [] let delta = [] let deltaP =[] const [timeData, setTimeData] = useState([]) const [stillTimeData, setStillTimeData] = useState([]) const [deltaTemp, setDeltaTemp] = useState([]) const [deltaPressure, setDeltaP] = useState([]) const [tempData, setTempData] = useState([]) const [pressureData, setPressureData] = useState([]) const totalDuration = 10000; const delayBetweenPoints = totalDuration / data.length; useEffect(() => { var x, y, z; var randomTemp, randomPressure; let currTemp=25; let currPressure= 800; let currTime = 0; for (let index = 0; index < data.length; index++) { x = (data[index].temp1 - currTemp)/data[index].time1 y = (data[index].pressure - currPressure)/data[index].time1 for (let j = 0; j < data[index].time1 ; j++) { currTime++; currTemp = currTemp + x; randomTemp = currTemp + Math.floor(Math.random() * x) currPressure = currPressure + y randomPressure = currPressure+ Math.floor(Math.random() * y) time.push(currTime) temp.push(currTemp) pressure.push(currPressure) delta.push(randomTemp) deltaP.push(randomPressure) } for (let k = 0; k < data[index].time2; k++) { currTime++ time.push(currTime) temp.push(currTemp) pressure.push(currPressure) delta.push(randomTemp) deltaP.push(randomPressure) } } setTimeData(time) setTempData(temp) setStillTimeData(stillTime) setPressureData(pressure) setDeltaP(deltaP) setDeltaTemp(delta) },[data] ) const dataTwo = { labels: timeData, datasets: [ { yAxisID: "y-axis-0", label: 'Temprature', fill: false, lineTension: 0.1, backgroundColor: 'yellow', borderColor: 'yellow', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'yellow', pointBackgroundColor: 'yellow', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: '#ff7a00', pointHoverBorderColor: '#7868e6', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: tempData }, { yAxisID: "y-axis-1", position: "right", label: 'Pressure', fill: false, lineTension: 0.1, backgroundColor: 'orange', borderColor: 'orange', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'orange', pointBackgroundColor: 'orange', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: 'orange', pointHoverBorderColor: '#7868e6', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: pressureData }, { yAxisID: "y2", label: 'Expected Temp', fill: false, lineTension: 0.1, backgroundColor: 'green', borderColor: 'green', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'green', pointBackgroundColor: 'green', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: 'green', pointHoverBorderColor: '#7868e6', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: deltaTemp }, { yAxisID: "y3", label: 'Expected Pressure', fill: false, lineTension: 0.1, backgroundColor: 'red', borderColor: 'red', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'red', pointBackgroundColor: 'red', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: 'red', pointHoverBorderColor: 'red', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: deltaPressure } ] }; const options = { legend: { position: 'bottom', labels: { fontColor: 'white' } }, title: { display: true, text: "Graph Data for The respective Batch" }, tooltips: { mode: 'label' }, interaction: { mode: 'index', intersect: false, }, responsive: true, scales: { xAxes: [{ display: true, stacked: true, ticks: { autoSkip: true, maxTicksLimit: 12, fontColor: 'white', fontSize: 10, animation: { duration: delayBetweenPoints, easing: 'linear' } } }], ticks: { major: { fontStyle: 'bold', fontColor: '#FF0000' } }, yAxes: [{ stacked: true, position: "left", id: "y-axis-0", ticks: { autoSkip: true, maxTicksLimit: 12, fontColor: 'white', fontSize: 14 }, }, { stacked: true, display: false, position: "left", id: "y2", ticks: { autoSkip: true, maxTicksLimit: 12, fontColor: 'white', fontSize: 14 }, }, { stacked: false, display: false, position: "right", id: "y3", ticks: { autoSkip: true, maxTicksLimit: 12, fontColor: 'white', fontSize: 14 }, }, { stacked: false, position: "right", id: "y-axis-1", fontColor: 'white', ticks: { autoSkip: true, maxTicksLimit: 12, fontColor: 'white', fontSize: 14 }, }] } } return ( <Container style={{ background: "black", color: "white", marginBottom: "20px" }} > <Line data={dataTwo} options={options}/> {/* <Line data={dataOne}/> */} {/* <FetchRecipee time={timeData} pressure={pressureData} temp={tempData}/> */} </Container> ) } export default GraphData <file_sep>/src/components/3DModel/ModelThreeD.js import { Card, makeStyles, Typography } from '@material-ui/core'; import {GLTFModel,AmbientLight,DirectionLight} from 'react-3d-viewer' import {OBJModel} from 'react-3d-viewer' import ManualDashboardLayout from '../ManualSidebar/ManualDashboardLayout.jsx' import { Carousel } from "react-responsive-carousel"; import "react-responsive-carousel/lib/styles/carousel.min.css" const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'whitesmoke', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 250 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { backgroundColor: '#edeef7', padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); function ModelThreeD({match}) { const classes = useStyles() return ( <> <ManualDashboardLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <> <div > <Typography variant='h1' align='center'><b>3D Models</b></Typography> <Carousel interval={5000} > <div style={{display:'flex', justifyContent: 'center'}}> <GLTFModel src="https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/Buggy/glTF/Buggy.gltf" > <AmbientLight color={0xffffff}/> <DirectionLight color={0xffffff} position={{x:100,y:200,z:100}}/> <DirectionLight color={0xff00ff} position={{x:-100,y:200,z:-100}}/> </GLTFModel> </div> <div style={{display:'flex', justifyContent: 'center'}} > <GLTFModel width={500} texPath ="" src="https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/2CylinderEngine/glTF/2CylinderEngine.gltf" > <AmbientLight color={0xffffff}/> <DirectionLight color={0xffffff} position={{x:100,y:200,z:100}}/> <DirectionLight color={0xff00ff} position={{x:-100,y:200,z:-100}}/> </GLTFModel> </div> <div style={{display:'flex', justifyContent: 'center'}} > <GLTFModel src="https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/DamagedHelmet/glTF/DamagedHelmet.gltf" > <AmbientLight color={0xffffff}/> <DirectionLight color={0xffffff} position={{x:100,y:200,z:100}}/> <DirectionLight color={0xff00ff} position={{x:-100,y:200,z:-100}}/> </GLTFModel> </div> <div style={{display:'flex', justifyContent: 'center'}} > <GLTFModel src="https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/FlightHelmet/glTF/FlightHelmet.gltf" > <AmbientLight color={0xffffff}/> <DirectionLight color={0xffffff} position={{x:100,y:200,z:100}}/> <DirectionLight color={0xff00ff} position={{x:-100,y:200,z:-100}}/> </GLTFModel> </div> <div style={{display:'flex', justifyContent: 'center'}} > <OBJModel width="400" height="400" position={{x:0,y:-100,z:0}} src="https://raw.githubusercontent.com/alecjacobson/common-3d-test-models/master/data/xyzrgb_dragon.obj" onLoad={()=>{ //... }} onProgress={xhr=>{ //... }} /> </div> </Carousel> </div> </> </Card> </div> </div> </> ) } export default ModelThreeD <file_sep>/src/TestGraph/GraphSelect.jsx import React, { useEffect, useRef, useState } from "react"; import Chartjs from "chart.js"; import { db } from "../firebase"; import { firebaseLooper } from "../utils/tools"; import { Button, Container } from "@material-ui/core"; import TimelineIcon from '@material-ui/icons/Timeline'; const chartConfig = { type: "line", data: { labels: [], datasets: [ { fill: 'false', label: "Temprature", yAxisID: "y-axis-0", data: [], borderWidth: 1, lineTension: 0.1, backgroundColor: 'yellow', borderColor: 'yellow', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'yellow', pointBackgroundColor: 'yellow', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: '#ff7a00', pointHoverBorderColor: '#7868e6', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, }, { fill: 'false', yAxisID: "y-axis-1", label: "Pressure", data: [], lineTension: 0.1, backgroundColor: 'orangered', borderColor: 'orangered', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'orangered', pointBackgroundColor: 'orangered', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: '#ff7a00', pointHoverBorderColor: '#7868e6', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, borderWidth: 1 }, { yAxisID: "y2", label: 'RealTime', fill: false, lineTension: 0.1, backgroundColor: 'green', borderColor: 'green', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'green', pointBackgroundColor: 'green', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: 'green', pointHoverBorderColor: '#7868e6', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [] }, ] }, options: { legend: { position: 'bottom', labels: { fontColor: 'white' } }, title: { display: true, text: "Select/Change The Required to Showcase Data" }, tooltips: { mode: 'label' }, interaction: { mode: 'index', intersect: false, }, responsive: true, scales: { xAxes: [{ display: true, stacked: false, ticks: { autoSkip: true, maxTicksLimit: 15, fontColor: 'white', fontSize: 10, animation: { easing: 'linear' } } }], ticks: { major: { fontStyle: 'bold', fontColor: '#FF0000' } }, yAxes: [{ stacked: true, position: "left", id: "y-axis-0", title: 'Temp Set Point', ticks: { steps: 10, max: 50, fontColor: 'white', fontSize: 14, min: -100 }, }, { stacked: false, display: false, position: "left", id: "y2", title: 'Realtime', ticks: { steps: 10, max: 50, fontColor: 'white', fontSize: 14, min: -100 }, }, { stacked: false, position: "right", id: "y-axis-1", fontColor: 'white', ticks: { steps: 100, fontColor: 'white', fontSize: 14 }, }, // { // stacked: false, // display: false, // position: "right", // id: "y3", // ticks: { // autoSkip: true, // maxTicksLimit: 12, // fontColor: 'white', // fontSize: 14 // }, // }, ] } } }; const GraphSelect = ({realData,rData}) => { let time = [] let temp = [] let stillTime = [] let pressure = [] let delta = [] let deltaP =[] const [stillTimeData, setStillTimeData] = useState([]) const [deltaTemp, setDeltaTemp] = useState([]) const [deltaPressure, setDeltaP] = useState([]) const [tempData, setTempData] = useState([]) const [pressureData, setPressureData] = useState([]) const chartContainer = useRef(null); const [chartInstance, setChartInstance] = useState(null); useEffect(() => { if (chartContainer && chartContainer.current) { const newChartInstance = new Chartjs(chartContainer.current, chartConfig); setChartInstance(newChartInstance); } }, [chartContainer]); const updateDataset = (time, newData, pressure) => { chartInstance.data.labels = time chartInstance.data.datasets[0].data = newData; chartInstance.data.datasets[1].data = pressure; chartInstance.data.datasets[2].data = realData; chartInstance.update(); }; const onButtonClick = (e) => { var x, y, z; var randomTemp, randomPressure; let currTemp=0; let currPressure= 800; let currTime = 0; for (let index = 0; index < rData.length; index++) { x = (rData[index].temp1 - currTemp)/rData[index].time1 y = (rData[index].pressure - currPressure)/rData[index].time1 for (let j = 0; j < rData[index].time1 ; j++) { currTime++; currTemp = currTemp + x; randomTemp = currTemp + Math.floor(Math.random() * x) currPressure = currPressure + y randomPressure = currPressure+ Math.floor(Math.random() * y) time.push(currTime) temp.push(currTemp) pressure.push(currPressure) delta.push(randomTemp) deltaP.push(randomPressure) } for (let k = 0; k < rData[index].time2; k++) { currTime++ time.push(currTime) delta.push(randomTemp + Math.random() * x) deltaP.push (randomPressure + Math.random()*y) temp.push(currTemp) pressure.push(currPressure) } } setTempData(temp) setStillTimeData(stillTime) setPressureData(pressure) setDeltaP(deltaP) setDeltaTemp(delta) updateDataset(time, temp, pressure); }; return ( <Container style={{marginTop: '10px'}}> <div> <Button startIcon={<TimelineIcon/>} style={{color:'white', backgroundImage: 'linear-gradient(to right top, #6b75d1, #6373d3, #5a70d6, #4f6ed8, #426cdb, #3d66d1, #3960c7, #345abd, #364fa5, #35448e, #323a78, #2d3063)', marginBottom: '7px'}} onClick={onButtonClick}>Set Graph</Button> </div> <canvas style={{background: 'black'}} ref={chartContainer} /> </Container> ); }; export default GraphSelect;<file_sep>/src/Pages/DQNewReports/DQRConfigView.jsx import { Button, Dialog, TableCell, TableRow, Toolbar, Collapse } from "@material-ui/core" import ArrowUpwardIcon from '@material-ui/icons/ArrowUpward'; import { useGridState } from "@material-ui/data-grid" import { useState } from "react" import DQRComponents from "./DQRComponents" import ArrowForwardIcon from '@material-ui/icons/ArrowForward' function DQRConfigView({row, match}) { const [open, setOpen] = useState(false) function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } return ( <> <TableRow key={row.name}> <TableCell style={{background: '#E8F6EF'}} component="th" scope="row"> {row.title} </TableCell> <TableCell align="right">{row.desc}</TableCell> <TableCell align="right"><Button className='animate-pulse' onClick={() => setOpen(!open)}>{!open ? <ArrowForwardIcon/> : <ArrowUpwardIcon/>}</Button></TableCell> </TableRow> <Collapse in={open}> <br /> <DQRComponents type={row.type} key={row.id} moduleId={row.id} match={match}/> <br /> </Collapse> </> ) } export default DQRConfigView <file_sep>/src/VideoCallModel/EntryPage.jsx import { Button, Dialog, FormHelperText, Select, TextField, Toolbar } from "@material-ui/core"; import { useEffect, useState } from "react"; import Page from "../components/Page"; import RenderVc from "../components/VideoCall/RenderVc"; import { db } from "../firebase"; import WebcamComponent from "./WebComponent"; import CloseIcon from '@material-ui/icons/Close'; function EntryPage() { const [open, setOpen] = useState(false) const [mode, setMode] = useState('relayed') const [configData, setConfigData] = useState({ api_key: '47244624', session_id: '2_MX40NzI0NDYyNH5-MTYyMjYyNDk5NTkzNX5IdmpYQkhkc214N0J6cXYvdnR4YjFDeFp-UH4', token: '<KEY> }) useEffect(() => { db.collection('OpenTokConfig').doc('relayed').onSnapshot(snapshot => { setConfigData(snapshot.data()) console.log(snapshot.data()) }) }, []) const handleOpen = () => { setOpen(true) } const handleClose = () => { setOpen(false) } function handleChange() { } return ( <Page title='Video Call | LyoIms'> <div style={{height: '100vh'}}> <section className="text-gray-700 "> <div className="container flex flex-col items-center px-5 py-16 mx-auto md:flex-row lg:px-24"> <div className="w-full lg:w-5/6 lg:max-w-lg md:w-1/2 mr-5"> {/* <img className="object-cover object-center rounded-lg " alt="hero" src="https://dummyimage.com/720x600/F3F4F7/8693ac"/> */} <WebcamComponent/> </div> <div className="flex flex-col items-start mb-16 text-left lg:flex-grow md:w-1/2 lg:pr-24 md:pr-16 md:mb-0"> <h2 className="mb-8 text-xs font-semibold tracking-widest text-black uppercase title-font"> VIDEO CALL</h2> <h1 className="mb-8 text-2xl font-black tracking-tighter text-black md:text-5xl title-font"> Join or Create a new Session</h1> <p className="mb-8 text-base leading-relaxed text-left text-blueGray-600 "> Join Meetings with end users and more. </p> {/* <Select onChange={(e) => setMode(e.target.value)} fullWidth variant='outlined'> <option value="relayed">Relayed</option> <option value="routed">Routed</option> </Select> */} {/* <FormHelperText>Select the mode to be used</FormHelperText> <Button onClick={handleChange}>Set mode</Button> */} <br /> <div className="flex flex-col justify-evenly lg:flex-row"> <button onClick={(e) => handleOpen()} className="flex items-center px-6 py-2 mt-auto font-semibold text-white transition duration-500 ease-in-out transform bg-yellow-900 rounded-lg hover:bg-yellow-700 focus:shadow-outline focus:outline-none focus:ring-2 ring-offset-current ring-offset-2"> Instant Meeting</button> </div> </div> </div> </section> <Dialog style={{background: 'black'}} open={open} fullScreen> <Toolbar style={{background: 'black'}}> <button className='text-lg w-40 text-yellow-800 hover:text-yellow-600' onClick={(e) => handleClose()}><CloseIcon/></button> </Toolbar> <RenderVc config={configData}/> </Dialog> </div> </Page> ) } export default EntryPage <file_sep>/src/Pages/VideoCallPage/components/Publisher.jsx import React, { useState } from 'react'; import { OTPublisher } from 'opentok-react'; import CheckBox from './CheckBox'; import '../OpenTok.css' import { Button, Card, Container, Grid, Hidden, Toolbar } from '@material-ui/core'; import ScreenShareIcon from '@material-ui/icons/ScreenShare'; class Publisher extends React.Component { constructor(props) { super(props); this.state = { publishScreen: false, error: null, audio: true, video: true, videoSource: 'camera', showControls: true }; this.publisherScreenEventHandlers = { accessDenied: () => { console.log("User denied access to media Screen source"); }, streamCreated: () => { console.log("Publisher SCreen created"); }, mediaStopped: () => { this.setState({ publishScreen: false }); }, streamDestroyed: ({ reason }) => { console.log(`Publisher Screen destroyed because: ${reason}`); }, }; } setAudio = (audio) => { this.setState({ audio }); } setVideo = (video) => { this.setState({ video }); } changeVideoSource = (videoSource) => { (this.state.videoSource !== 'camera') ? this.setState({videoSource: 'camera'}) : this.setState({ videoSource: 'screen' }) } onError = (err) => { this.setState({ error: `Failed to publish: ${err.message}` }); } onPublishScreen = () => { console.log("Publish Screen Success"); this.setState({ error: null }); }; toggleScreenshare = () => { this.setState((state) => ({ publishScreen: !state.publishScreen, })); }; render() { const { publishScreen } = this.state; return ( <div className='bg-black mx-10 mb-10 p-10'> <Container className="bg-black"> <Grid container spacing={3} > <Grid item > { publishScreen && (<OTPublisher properties={{ width: 800, height: 350, publishAudio: this.state.audio, publishVideo: this.state.video, videoSource: 'screen' , showControls: true, }} onPublish={this.onPublishScreen} eventHandlers={this.publisherScreenEventHandlers} onError={this.onError} />) } </Grid> </Grid> </Container> <div style={{display: 'flex', flexDirection: 'column', justifyContent: 'flex-end'}}> <div style={{display: 'flex',background: 'black', justifyContent: 'flex-end'}}> <OTPublisher properties={{ showControls: true, insertMode: 'append', publishAudio: true, publishVideo: this.state.video, width:500, height: 270 }} /> </div> <Toolbar style={{display: 'flex',background: 'black', justifyContent: 'flex-end'}}> <div style={{marginRight: '20px'}}> <Button style={{color: 'orange'}} variant='outlined' onClick={this.toggleScreenshare}><ScreenShareIcon/></Button> </div> <div className='bg-black'> <CheckBox label="Video" initialChecked={this.state.video} onChange={this.setVideo} /> </div> <div> </div> </Toolbar> </div> <div> {this.state.error ? <b id="error">{this.state.error}</b> : null} </div> </div> ); } } export default Publisher; <file_sep>/src/Pages/Tests/TestHome.jsx import { Container } from '@material-ui/core'; import React, { Fragment, useEffect, useState } from 'react'; import Chart from 'react-apexcharts' const TestHome = ({data}) => { let time = [] let temp = [] let stillTime = [] let pressure = [] let delta = [] let deltaP =[] const [timeData, setTimeData] = useState([]) const [stillTimeData, setStillTimeData] = useState([]) const [deltaTemp, setDeltaTemp] = useState([]) const [deltaPressure, setDeltaP] = useState([]) const [tempData, setTempData] = useState([]) const [pressureData, setPressureData] = useState([]) useEffect(() => { var x, y, z; var randomTemp, randomPressure; let currTemp=25; let currPressure= 800; let currTime = 0; for (let index = 0; index < data.length; index++) { x = (data[index].temp1 - currTemp)/data[index].time1 y = (data[index].pressure - currPressure)/data[index].time1 for (let j = 0; j < data[index].time1 ; j++) { currTime++; currTemp = currTemp + x; randomTemp = currTemp + Math.floor(Math.random() * x) currPressure = currPressure + y randomPressure = currPressure+ Math.floor(Math.random() * y) time.push(currTime) temp.push(currTemp) pressure.push(currPressure) delta.push(randomTemp) deltaP.push(randomPressure) } for (let k = 0; k < data[index].time2; k++) { currTime++ time.push(currTime) delta.push(randomTemp + Math.random() * x) deltaP.push (randomPressure + Math.random()*y) temp.push(currTemp) pressure.push(currPressure) } } setTimeData(time) setTempData(temp) setStillTimeData(stillTime) setPressureData(pressure) setDeltaP(deltaP) setDeltaTemp(delta) }, []) const options = { chart: { foreColor: "#fff", toolbar: { show: false }}, fill: { type: "gradient", gradient: { gradientToColors: ["#F55555", "e84545", "#6094ea"] } }, stroke: { curve: 'smooth' }, markers: { size: 0 }, colors: ["#ffcc29", "#f58634", "#f02fc2"], xaxis: { axisTicks: { color: "#333" }, labels: { show: false }, categories: timeData }, animations: { enabled: true, easing: 'linear', speed: 800, animateGradually: { enabled: true, delay: 150 }, animateGradually: { enabled: true, delay: 200, }, dynamicAnimation: { enabled: true, speed: 350 } }, dropShadow: { enabled: true, opacity: 0.3, blur: 5, left: -7, top: 22 }, yaxis: [ { tickAmount: 6, min: -50, max: 40, fontColor:'#f8f5f1', title: { text: "Temprature" }, }, { fontColor:'#f8f5f1', tickAmount: 6, min: 500, opposite: true, title: { text: "Pressure" } }] }; const series = [ { name: 'Temprature', data: tempData }, { name: 'Pressure', data: pressureData } ]; return ( <Container style={{background: '#132c33'}}> <Chart options={options} series={series} type="line" /> </Container> ) } export default TestHome <file_sep>/src/Pages/DQPages/DQSpecs.jsx import { DialogContent, Fab, makeStyles, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from "@material-ui/core"; import { Button, Dialog, Typography, TextField, DialogActions, Card } from "@material-ui/core" import { Alert } from "@material-ui/lab" import { useEffect } from "react" import { useState } from "react" import DQLayout from "../../components/DQNewSidebar/DQLayout"; import { db } from "../../firebase" import { firebaseLooper } from "../../utils/tools"; import DQmodules from "../DQNew/DQmodules"; import DQConfigView from "./DQCOnfigDetails/DQConfigView"; import DQSpecsView from "./DQCOnfigDetails/DQSpecsView"; import DQModule from "./DQModule/DQModule"; import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight'; import KeyboardArrowLeftIcon from '@material-ui/icons/KeyboardArrowLeft'; import { NavLink as RouterLink, matchPath, useLocation, NavLink } from 'react-router-dom'; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'whitesmoke', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, fab: { position: 'fixed', bottom: theme.spacing(2), right: theme.spacing(2), }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 250 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); function DQSpecs({match}) { const [purpose, setPurpose] = useState({}) const [name, setName] = useState('') const [review, setReview] = useState('') const [specs,setSpecs] = useState([]) const [ desc, setDesc] = useState('') const [open, setOpen] = useState(false) const [openEdit, setOpenEdit] = useState(false) const [openAdd, setOpenAdd] = useState(false) const [index, setIndex] = useState(0) const [error, setError] = useState('') const [opendelete, setOpenDelete] = useState(false) const [titleModule, setTitleModule] = useState('') const [ descModule, setDescModule] = useState('') const classes = useStyles() function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleOpenEdit(){ setOpenEdit(true) } function handleCloseEdit(){ setOpenEdit(false) } function handleOpenAdd(){ setOpenAdd(true) } function handleCloseAdd(){ setOpenAdd(false) } function handleOpenDel(){ setOpenDelete(true) } function handleCloseDel(){ setOpenDelete(false) } function handleUpdate(id){ db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('specifications') .update({name, desc}) } function handleSubmit(e){ e.preventDefault() if(desc?.trim().length === 0){ return setError("Empty spaces are not accepted as a valid input! Please enter a valid input") } db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('specifications') .collection('specDetails') .add({ desc,index}).then(() => {setOpenAdd(false)}) } function handleSubmitNew(e){ e.preventDefault() db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('specifications') .set({name, desc}) } useEffect(() => { db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('specifications') .onSnapshot(snapshot => { const data = snapshot.data() setPurpose(data) if(data){ setName(data.name) setDesc(data.desc) } }) db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('specifications') .collection('specDetails') .onSnapshot(snapshot => { const data = firebaseLooper(snapshot) data.sort(function(a,b){ return(a.index-b.index) }) setSpecs(data) setIndex(data.length) }) }, []) return ( <div> <> <DQLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div > { purpose ? <> <Typography variant='h1' align='center' gutterBottom><b>{purpose.name}</b></Typography> <hr /> <div style={{display: 'flex', paddingRight: '3%',marginBottom: '30px', justifyContent: 'flex-end'}}> {/* <Button component={RouterLink} to={`/DQ/${match.params.id}/Equipment-Config`} style={{background: 'blue', color: 'white', marginLeft: '25px', marginRight: '4%'}}> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-90deg-left" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1.146 4.854a.5.5 0 0 1 0-.708l4-4a.5.5 0 1 1 .708.708L2.707 4H12.5A2.5 2.5 0 0 1 15 6.5v8a.5.5 0 0 1-1 0v-8A1.5 1.5 0 0 0 12.5 5H2.707l3.147 3.146a.5.5 0 1 1-.708.708l-4-4z"/> </svg> </Button> */} <Button style={{color: 'white', background: 'black', marginRight: '4%'}} onClick={handleOpenAdd}>Add Specs</Button> {/* <Button component={RouterLink} to={`/DQ/${match.params.id}/Design-Specs`} style={{background: 'blue', color: 'white', marginLeft: '25px'}}> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-90deg-right" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M14.854 4.854a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 4H3.5A2.5 2.5 0 0 0 1 6.5v8a.5.5 0 0 0 1 0v-8A1.5 1.5 0 0 1 3.5 5h9.793l-3.147 3.146a.5.5 0 0 0 .708.708l4-4z"/> </svg> </Button> */} </div> <Dialog style={{alignItems: 'center'}} fullWidth open={open} onClose={handleClose}> <DialogContent> <Typography variant='h4' align='center' gutterBottom><b>Edit Details</b></Typography> <form > <TextField style={{marginBottom: '3%'}} value={name} variant='outlined' fullWidth onChange={(e) => setName(e.target.value)}/> <TextField multiline rows={7} value={desc} variant='outlined' fullWidth onChange={(e) => setDesc(e.target.value)}/> </form> </DialogContent> <DialogActions> <Button onClick={handleClose}>Cancel</Button> <Button onClick={handleUpdate} style={{backgroundColor: 'orange', color: 'whitesmoke'}}>Update</Button> </DialogActions> </Dialog> { <> <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align='left' ><b className='text-lg font-bold italic'>Description</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right"><b className='text-lg font-bold italic'>Actions</b></TableCell> </TableRow> </TableHead> { specs.map(specs => ( <> <DQSpecsView specs={specs} match={match} key={specs.id}/> </> )) } </Table> </TableContainer> <div className={classes.fab}> <Fab component={NavLink} to={`/DQ/${match.params.id}/General-Information`} style={{marginRight: '20px'}} color="primary" aria-label="add"> <KeyboardArrowLeftIcon/> </Fab> <Fab component={NavLink} to={`/DQ/${match.params.id}/Equipment-Config`} color="primary" aria-label="add"> <KeyboardArrowRightIcon/> </Fab> </div> </> } </> : <form onSubmit={handleSubmitNew}> <div style={{padding: '10%', paddingTop: '0'}} > <Typography variant='h1' align='center' gutterBottom><b>Add New Specification Details</b></Typography> <TextField style={{marginBottom: '20px'}} label='Title' variant='outlined' fullWidth onChange={(e) => setName(e.target.value)}/> <TextField style={{marginBottom: '5%'}} label='Description' multiLine rows={7} variant='outlined' fullWidth onChange={(e) => setDesc(e.target.value)}/> <Button type="submit" disabled={ desc>300 || name > 35} fullWidth style={{background: 'orange', color: 'white'}} >Add New</Button> </div> </form> } </div> </Card> </div> </div> </> <Dialog open={openAdd} fullWidth onClose={handleCloseAdd}> <form onSubmit={handleSubmit}> <Typography variant='h4' align='center' gutterBottom><b>Add New Specifications</b></Typography> <Alert severity='info'>Reviews are generally added from glass</Alert> <DialogContent> <> <TextField required label='Description' style={{marginBottom: '20px'}} multiLine rows={5} variant='outlined' fullWidth onChange={(e) => setDesc(e.target.value)}/> {error && <Alert severity='error'>{error}</Alert>} </> </DialogContent> <DialogActions> <Button type="submit" style={{background: 'orange', color:'white'}} >Add New</Button> </DialogActions> </form> </Dialog> <br /> <br /> <br /> </div> )} export default DQSpecs <file_sep>/src/Pages/MiddlePage/Graph/GraphDataRecipee.jsx import { Button } from '@material-ui/core' import React, { useEffect, useState } from 'react' import { db } from '../../../firebase' import { firebaseLooper } from '../../../utils/tools' import TestData from '../../Tests/TestData' import TestHome from '../../Tests/TestHome' const GraphDataRecipee = ({data}) => { console.log(data) const [graphData, setGraphData] = useState([]) return ( <div> <TestHome data={data} /> </div> ) } export default GraphDataRecipee <file_sep>/src/Pages/Steps/StepItem.jsx import React, { useEffect, useState } from 'react'; import { Button, Container, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, FormControl, Grid, InputLabel, makeStyles, Select, Snackbar, TextField, Typography } from '@material-ui/core'; import { useHistory } from 'react-router-dom'; import AccessTimeIcon from '@material-ui/icons/AccessTime'; import { db, storageRef } from '../../firebase'; import { Alert, AlertTitle } from '@material-ui/lab'; import VisibilityIcon from '@material-ui/icons/Visibility'; import EditIcon from '@material-ui/icons/Edit'; import DeleteForeverIcon from '@material-ui/icons/DeleteForever'; import { useStepStorage } from '../../utils/useStepStorage'; const useStyles = makeStyles((theme) => ({ root: { borderBottomColor: "black", backgroundColor: 'white', }, statsItem: { alignItems: 'center', display: 'flex' }, statsIcon: { marginRight: theme.spacing(1) }, dataBox:{ borderRadius: "20px", background: 'white', alignItems: "center" }, divButton: { color: "#32e0c4", } })); const StepItem = ({ data}) => { const classes = useStyles() const [open, setOpen] = useState(false) const [openEdit, setOpenEdit] = useState(false) const [openView, setOpenView] = useState(false) const [title, setTitle] = useState(data.title) const [desc, setDesc] = useState(data.desc) const [file, setFile] = useState(null) const [format, setFormat] = useState(data.format) const [createdAt, setCreatedAt] = useState(data.createdAt) const [type, setType] = useState(data.type); const [error,setError] = useState('') const [disabled, setDisabled] = useState(true) const [loading, setLoading] = useState(false); const types = ["image/png", "image/jpeg", "image/jpg"]; const videoTypes = ["video/mp4", "video/mkv", "video/mov"]; const audioTypes = ["audio/mp3", "audio/mpeg"] const handleChange = (e) => { let selectedFile = e.target.files[0] setDisabled(false) if (selectedFile) { if(format === 'image'){ if (types.includes(selectedFile.type)) { setError(null); setFile(selectedFile); } else { setFile(null); setError("Please select an image file (png or jpg)"); } }else if(format === 'video'){ if (videoTypes.includes(selectedFile.type)) { setError(null); setFile(selectedFile); } else { setFile(null); setError("Please select a video file (mp4 or mkv)"); } }else if(format === 'audio'){ if (audioTypes.includes(selectedFile.type)) { setError(null); setFile(selectedFile); } else { setFile(null); setError("Please select an audio file (mp3 )"); } } } } const { progress, url } = useStepStorage(file); function getMedia(){ if (data.format === 'image'){ return <img className="h-64 bg-cover lg:rounded-lg lg:h-full" src={data.url}/> }else if(data.format === 'video'){ return ( <div className="h-64 bg-cover lg:rounded-lg lg:h-full"> <video style={{width: '100%', height: 'auto'}} controls> <source src={data.url}/> </video> </div> ) }else if(data.format === 'audio'){ return ( <div className="h-64 bg-cover lg:rounded-lg lg:h-full"> <audio style={{marginTop: '15%', marginRight: '50px'}} controls> <source src={data.url}/> </audio> </div> ) } } const handleView = () => { setOpenView(true) } const handleViewClose = () => { setOpenView(false) } const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const handleEdit = () => { setOpenEdit(true) } const handleEditClose = () => { setOpenEdit(false) } const handleDelete = (id) => { db.collection('stepData').doc(id).delete().then((data) => { return( <Snackbar ></Snackbar> ) }) } const handleImageUpdate = (id) => { const reqData = {url} db.collection('stepData').doc(id).update(reqData).then((data)=>{ setLoading(false) console.log(data) }) } const updateStep=(id) => { setLoading(true) const reqData = {title,desc,type,format} db.collection('stepData').doc(id).update(reqData).then((data)=>{ setLoading(false) console.log(data) }) } function getType() { if(type === 'info'){ return( <div class="flex-shrink-0 w-24 h-24 text-blue-900 rounded-full inline-flex items-center justify-center"> <svg class="bi bi-info-square w-12 h-12" viewBox="0 0 24 24" fill="currentColor" > <path d="M14 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h12zM2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z"/> <path d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533L8.93 6.588zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/> </svg> </div> ) }else if (type === 'critical'){ return( <div class="flex-shrink-0 w-24 h-24 text-yellow-900 rounded-full inline-flex items-center justify-center"> <svg fill="currentColor" class="w-12 h-12" viewBox="0 0 24 24"> <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/> <path d="M7.002 11a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.1 4.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 4.995z"/> </svg> </div> ) }else if ( type === 'normal'){ return( <div class="flex-shrink-0 w-24 h-24 text-yellow-900 rounded-full inline-flex items-center justify-center"> <svg fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-12 h-12" viewBox="0 0 24 24"> <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path> </svg> </div> ) }else if (type === 'camera'){ return( <div class="flex-shrink-0 w-24 h-24 text-green-700 rounded-full inline-flex items-center justify-center"> <svg fill="currentColor" class="w-12 h-12" viewBox="0 0 24 24" > <path d="M10.5 8.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0z"/> <path d="M2 4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-1.172a2 2 0 0 1-1.414-.586l-.828-.828A2 2 0 0 0 9.172 2H6.828a2 2 0 0 0-1.414.586l-.828.828A2 2 0 0 1 3.172 4H2zm.5 2a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1zm9 2.5a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0z"/> </svg> </div> ) } } return ( <Container> <div className={classes.dataBox}> <Grid xs={12}> <section class="text-gray-600 body-font"> <div class="container mx-auto flex flex-wrap"> <div class="flex relative pt-10 pb-20 sm:items-center md:w-2/3 mx-auto"> <div class="h-full w-6 absolute inset-0 flex items-center justify-center"> <div class="h-full w-1 bg-gray-200 pointer-events-none"></div> </div> <div class="flex-shrink-0 w-6 h-6 rounded-full mt-10 sm:mt-0 inline-flex items-center justify-center bg-yellow-800 text-white relative z-10 title-font font-medium text-sm">{data.index + 1}</div> <div class="flex-grow md:pl-8 pl-6 flex sm:items-center items-start flex-col sm:flex-row"> {getType()} <div class="w-1/2 flex-grow sm:pl-6 mt-6 sm:mt-0"> <h2 class="font-medium title-font text-gray-900 mb-1 text-xl">{data.title}</h2> <div className='w-64 truncate'> <Typography className='' >{data.desc?.slice(0,150)}...</Typography> </div> </div> <Button startIcon={<EditIcon/>} onClick={handleEdit} color="primary"></Button> <Button startIcon={<VisibilityIcon/>} onClick={() => {handleView()}} className={classes.divButton}></Button> <Button startIcon={<DeleteForeverIcon/>} onClick={handleClickOpen} color="secondary"></Button> </div> </div> </div> </section> </Grid> <Dialog open={open} onClose={handleClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <Alert severity="error" variant="filled"> <AlertTitle><strong>Delete</strong></AlertTitle> <DialogTitle id="alert-dialog-title">{"Are You Sure You Want To Delete?"}</DialogTitle> <DialogContent> <DialogContentText color="white" id="alert-dialog-description"> Deleting will be a permanent action and data pervailing will be permanently deleted and can not be retrieved back. </DialogContentText> </DialogContent> </Alert> <DialogActions> <Button onClick={handleClose} color="primary" variant="outlined"> Disagree </Button> <Button onClick={(e)=>{ handleDelete(data.id); handleClose()}} color="secondary" variant="outlined" autoFocus> Agree </Button> </DialogActions> </Dialog> <Dialog open={openEdit} onClose={handleEditClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">{<b>Edit {title}</b>}</DialogTitle> <DialogContent> <form className={classes.form} > {error && <Alert severity='error'>{error}</Alert>} <TextField defaultValue={title} error={title === ""} variant="outlined" margin="normal" label="Title" required fullWidth id="title" name="title" autoFocus onChange={(e) => setTitle(e.target.value)} /> <TextField defaultValue={desc} error={desc === ""} variant="outlined" margin="normal" required label="Description" fullWidth name="desc" onChange={(e) => setDesc(e.target.value)} id="desc" multiline style={{marginBottom: '20px'}} /> <FormControl required variant='outlined' fullWidth style={{marginBottom: '20px'}} > <InputLabel>Select Type</InputLabel> <Select required label="Select type" variant='outlined' value={type} fullWidth InputLabelProps={{ shrink: true, }} onChange={(e) => setType(e.target.value)} style={{marginBottom: '15px'}} > <option value='info'>Info</option> <option value='camera'>Camera</option> <option value='critical'>Critical</option> <option value='normal'>Normal</option> </Select> </FormControl> <br/> <FormControl required variant='outlined' fullWidth style={{marginBottom: '20px'}} > <InputLabel >Select Format </InputLabel> <Select required variant='outlined' label="Select Format" value={format} fullWidth InputLabelProps={{ shrink: true, }} onChange={(e) => setFormat(e.target.value)} > <option value='image'>Image</option> <option value='video'>Video</option> <option value='audio'>Audio</option> </Select> </FormControl> {getMedia()} <Alert>To Update Media Click <b>'Update Media'</b> After uploading a new Media file</Alert> <InputLabel>Replace the current Media file</InputLabel> <input type="file" onChange={handleChange} /> { <div> <h4>{progress}% uploaded</h4> </div> } <Button disabled={disabled || progress < 100 || type==='' || file=== null} style={{color: 'orangered'}} variant='outlined' fullWidth onClick={() => handleImageUpdate(data.id)}>Update Media</Button> <DialogActions> <Button color="secondary" onClick={handleEditClose}>Cancel</Button> {!loading && <Button type="submit" disabled={title==="" || desc==="" || desc?.length > 300 || title?.length > 30} variant="outlined" color="primary" className={classes.submit} onClick={(e)=> {updateStep(data.id); handleEditClose(); }} > Update </Button>} { loading && <Button type="submit" variant="outlined" color="primary" disabled className={classes.submit} >Updating values...</Button> } </DialogActions> </form> </DialogContent> </Dialog> <Dialog open={openView} onClose={handleViewClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">{"View Data"}</DialogTitle> <DialogContent> <form className={classes.form} > <TextField defaultValue={title} variant="outlined" margin="normal" required fullWidth id="title" name="title" autoFocus disabled /> <TextField defaultValue={desc} variant="outlined" margin="normal" required fullWidth name="desc" disabled id="desc" multiline /> {getMedia()} <DialogActions> <Button color="secondary" onClick={handleViewClose}>Cancel</Button> </DialogActions> </form> </DialogContent> </Dialog> </div> </Container> ) } export default StepItem<file_sep>/src/Pages/CallLogs/CallLogs.jsx import React, { useEffect, useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import SearchIcon from '@material-ui/icons/Search'; import { Button, Card, Container, Dialog, Grid, InputLabel, Select, TablePagination, TextField, Typography } from '@material-ui/core'; import ContentDashboardLayout from '../../components/ContentSidebar/ContentDashboardLayout'; import { db } from '../../firebase'; import { firebaseLooper } from '../../utils/tools'; import Page from '../../components/Page'; const useStyles = makeStyles((theme) => ({ table: { minWidth: 650, }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); export default function CallLogs({match}) { const classes = useStyles(); const [title, setTitle] = useState('') const [mTitle, setMTitle] = useState('') const [open, setOpen] = useState(false) const [batch, setBatch] = useState([]) useEffect(() => { db.collection('machineData') .doc(match.params.id) .onSnapshot(doc => { setMTitle(doc.data().title) }) db.collection('CallLogData').where('machine_id', '==', `${match.params.id}`).onSnapshot(doc => { const data = firebaseLooper(doc) data.sort(function(a,b){ return(b.time - a.time) }) setBatch(data) console.log(data) }) }, []) const handleOpen = () => { setOpen(true) } const handleClose = () => { setOpen(false) } return ( <Page title='Call Logs | LyoIms'> <ContentDashboardLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div style={{display: 'flex', justifyContent: 'space-between'}}> <div> <Typography variant='h2' align='left'><b>Call logs</b></Typography> <Typography variant='body-2' align='left'>These are all the call history</Typography> </div> <div> <div style={{display: 'flex', justifyContent: 'flex-end'}}> <div className="relative"> <input style={{ border: '2px solid whitesmoke'}} onChange={(e) => setTitle(e.target.value)} type="text" className="h-14 w-96 pr-8 pl-5 rounded z-0 focus:shadow focus:outline-none" placeholder="Search Batch..."/> <div className="absolute top-4 right-3"> <SearchIcon style={{opacity: '0.5'}}/> </div> </div> </div> </div> </div> <br/> <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell><b>Manual</b></TableCell> <TableCell align="right"><b>User</b></TableCell> <TableCell align="right"><b>Step</b></TableCell> <TableCell align="right"><b>Date & Time</b></TableCell> </TableRow> </TableHead> <TableBody> {batch. filter((data) => { if(title === ""){ return data } else if (data.manual_name.toLowerCase().includes(title.toLocaleLowerCase())){ return data }else if (data.user_id.toLowerCase().includes(title.toLocaleLowerCase())){ return data }else if (data.step.toLowerCase().includes(title.toLocaleLowerCase())){ return data } }) .map((row) => ( <TableRow key={row.id}> <TableCell component="th" scope="row"> {row.manual_name} </TableCell> <TableCell align="right">{row.user_id}</TableCell> <TableCell align="right">{row.step}</TableCell> <TableCell align="right">{row.time.toDate().toString().substring(0,15)}</TableCell> </TableRow> ))} </TableBody> </Table> <div style={{display: 'flex', justifyContent: 'flex-end'}}> </div> <div style={{width: '100%'}}> </div> </TableContainer> </Card> </div> </div> </Page> ) } <file_sep>/src/Pages/MachineContents/ContentList.jsx import { Button, Container, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Grid, makeStyles, Typography } from '@material-ui/core' import React, { useEffect, useState } from 'react' import { firebaseLooper } from '../../utils/tools'; import ContentItem from './ContentItem'; import {db} from '../../firebase' const useStyles = makeStyles((theme) => ({ root: { borderBottomColor: "black", backgroundColor: theme.palette.background.dark, }, })); const ContentList = ({key, content}) => { const classes = useStyles(); const handleData = (machine) => ( machine? machine.map((data, i) =>( <div key={i}> <ContentItem content={data}/> </div> )) :null ) return ( <Container className={classes.root} > {handleData(machines)} </Container> ) } export default ContentList <file_sep>/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { BrowserRouter } from 'react-router-dom'; import { ContextProvider } from './components/ChatApp/VideoCallFeature/Context'; import './style.css' import $ from 'jquery'; import Popper from 'popper.js'; import 'bootstrap/dist/js/bootstrap.bundle.min'; import 'bootstrap/dist/css/bootstrap.min.css'; import { Paper } from '@material-ui/core'; import AOS from 'aos'; import 'aos/dist/aos.css'; AOS.init(); ReactDOM.render( <BrowserRouter> <Paper> <App /> </Paper> </BrowserRouter> , document.getElementById('root') );<file_sep>/README.md # Firestore Clone and make new app 1. npm install -g node-firestore-import-export 2. Export : firestore-export --accountCredentials path/to/credentials/file.json --backupFile /backups/myDatabase.json 3. Import: firestore-import --accountCredentials path/to/credentials/file.json --backupFile /backups/myDatabase.json 4. Authentication : 4.1 Enable Authentication from Firebase project (Email, Pass) 4.2 Enable Firestore --> Change rules Read/Write --> true 4.3 Enable Storage --> Read/Write True 5. Project Settings --> Web --> Config 6. Copy and Paste Credentials to firebase.js file in "src" folder 7. Create New User From Firebase Authentication and Add it's credential to firestore in "users" collection # install in local 1. "npm install" to install node modules 2. "npm start" to run the development server in localhost:3000 3. "npm run build" to make a production build # Database --> firebase commands 1. "firebase login" to login to connected project account 2. "firebase init" to initialize new firebase log (Not required) 3. "firebase deploy" to deploy the build folder ("npm run build" --> run this command before deploying) 4. "firebase deploy --only functions" to deploy functions folder for 'REST API" calls (if any) # Sprint 2 major updates 1. Video Call build (& Redesign) 2. Steps having different views (Carousel and step view) 3. Filters for all Page 4. Redesign users Page 5. Whiteboard 6. Share media from web to glass 7. Chatbot integration 8. Chatbox for Video call 9. File management system 10. Invite users outside the app from VC model 11. Added Relayed and Routed for Video Call 12. Added settings to different modules(Video call , Update company name and logo, download web and android app from web) 13. 3D Model (Pending build) <file_sep>/src/Pages/DQNewReports/DQRSpecView.jsx import { Button, TableCell, TableRow, TextField, Dialog, DialogContent, DialogActions } from "@material-ui/core" import { SettingsInputAntenna } from "@material-ui/icons"; import EditIcon from '@material-ui/icons/Edit'; import { useState } from "react"; import { db } from "../../firebase"; function DQRSpecView({row, match}) { const [open, setOpen] = useState(false) const [input, setInput] = useState(row.input) function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleUpdate(){ db.collection('DQNewReport') .doc(match.params.id) .collection('content') .doc('specifications') .collection('specDetails') .doc(row.id) .update({input}) } return ( <> <TableRow key={row.name}> <TableCell style={{background: '#E8F6EF'}} component="th" scope="row"> {row.title} </TableCell> <TableCell align="right">{row.input}</TableCell> <TableCell align="right"><Button className='animate-bounce' onClick={handleOpen}><EditIcon/></Button></TableCell> </TableRow> <Dialog open={open} onClose={handleClose}> <DialogContent> <TextField fullWidth variant='outlined' value={input} onChange={(e) => setInput(e.target.value)}/> </DialogContent> <DialogActions> <Button variant='contained' color='secondary' onClick={handleClose}>Cancel</Button> <Button onClick={handleUpdate} style={{background: 'orange', color: 'white'}}>Update</Button> </DialogActions> </Dialog> </> ) } export default DQRSpecView <file_sep>/src/components/ContentSidebar/DashboardNavbar.jsx import { useEffect, useRef, useState } from 'react'; import { Link as RouterLink, NavLink, Redirect } from 'react-router-dom'; import PropTypes from 'prop-types'; import VideoLabelIcon from '@material-ui/icons/VideoLabel'; import { AppBar, Avatar, Badge, Box, Button, Hidden, IconButton, Menu, MenuItem, Toolbar, Typography } from '@material-ui/core'; import { init } from "ityped"; import MenuIcon from '@material-ui/icons/Menu'; import NotificationsIcon from '@material-ui/icons/NotificationsOutlined'; import BuildIcon from '@material-ui/icons/Build'; import PhoneInTalkIcon from '@material-ui/icons/PhoneInTalk'; import AllOutIcon from '@material-ui/icons/AllOut'; import PhonelinkEraseIcon from '@material-ui/icons/PhonelinkErase'; import { useAuth } from '../context/AuthContext'; import { db } from '../../firebase'; import { firebaseLooper } from '../../utils/tools'; const useStyles = theme => ({ customBadge: { backgroundColor: "#00AFD7", color: "white" } }); const DashboardNavbar = ({avatar, match, onMobileNavOpen, ...rest }) => { const classes = useStyles() const [open, setOpen] = useState(false) const [anchorE1, setAnchorE1] = useState(null) const {currentUser} = useAuth() const [anchorE2, setAnchorE2] = useState(null) const [notifications, setNotifications] = useState([]) const [videoData, setVideoData] = useState([]) const [status, setStatus] = useState('') const [userData, setUserData] = useState([]) const textRef = useRef(); const [machineData, setMachineData] = useState([]) useEffect(() => { if (currentUser){ db.collection('users').where('email', '==', `${currentUser.email}`).onSnapshot(doc => { const data = firebaseLooper(doc) setUserData(data[0]) console.log(data[0]) }) db.collection("machineData").doc(match.params.id).onSnapshot(snap => { const data = snap.data() setMachineData(data) }) }else { <Redirect to='/login'/> } if(currentUser){ db.collection('notifications').orderBy('index', 'desc').onSnapshot(doc => { const data = firebaseLooper(doc) setNotifications(data) }) db.collection('videoCallData').where('receiverId', '==', `${currentUser.email}`).onSnapshot(doc => { const data = firebaseLooper(doc) data.sort(function(a,b) { return(b.index-a.index) }) setVideoData(data) }) }else{ <Redirect to='/login'/> } }, []) function updateStatus(id){ db.collection('videoCallData').doc(id).update({status: 'ended'}) } function getStatus(status, id,d_id){ if(status === 'waiting'){ return(<Button onClick={() => updateStatus(d_id)} href={`/video-call/${id}`} style={{color: 'darkseagreen'}}><PhoneInTalkIcon/>Join</Button>) } if(status === 'accepted'){ return(<b>Accepted </b>) } if(status === 'ended'){ return(<b>Ended </b>) } } function handleOpen(e){ setAnchorE1(e.currentTarget) } function handleVideoOpen(e){ setAnchorE2(e.currentTarget) } function handleVideoClose(e){ setAnchorE2(null) } function handleClose(){ setAnchorE1(null) } return ( <> <AppBar style={{backgroundColor: "white"}} elevation={1} {...rest} > <Toolbar > <Box style={{marginLeft: 256}}> <Typography align='left' variant='h3' style={{color: 'black'}}>Machine Name : {machineData.title}</Typography> </Box> <Box style={{ flexGrow: 1 }} /> <Hidden smDown> {/* <IconButton aria-controls='simple-menu' aria-haspopup="true" onClick={handleOpen} color="default"> <Badge badgeContent={notifications.length} color="primary" variant="dot" > <NotificationsIcon /> </Badge> </IconButton> */} <IconButton color="default" aria-controls='simple-menu' aria-haspopup="true" onClick={handleVideoOpen} > <Badge badgeContent={videoData.length} color="secondary" anchorOrigin={{ vertical: 'bottom', horizontal: 'left', }} variant="dot" > <VideoLabelIcon /> </Badge> </IconButton> <IconButton component={NavLink} color="default" aria-controls='simple-menu' aria-haspopup="true" to='/account' > <span className="ml-2 text-sm font-medium">{userData.firstName} {userData.lastName}</span> <Avatar style={{marginLeft: '10px'}} src={userData.url} /> </IconButton> </Hidden> <Hidden lgUp> {/* <IconButton color="default" aria-controls='simple-menu' aria-haspopup="true" onClick={handleOpen}> <Badge badgeContent={notifications.length} color="primary" variant="dot" > <NotificationsIcon /> </Badge> </IconButton> */} <IconButton color="default" aria-controls='simple-menu' aria-haspopup="true" onClick={handleVideoOpen} > <Badge badgeContent={videoData.length} color="secondary" variant="dot" anchorOrigin={{ vertical: 'bottom', horizontal: 'left', }} > <VideoLabelIcon /> </Badge> </IconButton> <IconButton color="default" aria-controls='simple-menu' aria-haspopup="true" href='/account' > <Avatar src={userData.url} /> </IconButton> <IconButton color="default" onClick={onMobileNavOpen} > <MenuIcon /> </IconButton> </Hidden> </Toolbar> </AppBar> <Menu anchorEl={anchorE1} id="simple-menu" keepMounted open={Boolean(anchorE1)} onClose={handleVideoClose} >{ notifications.slice(0, 6).map(data => ( <div style={{display: 'flex', justifyContent: 'space-between'}} key={data.id}> <MenuItem>{data.notification} </MenuItem> <Button color="primary" href={`/${data.link}`}>Open <AllOutIcon/></Button> </div> )) } <Button onClick={handleClose} color='secondary'>Close</Button> </Menu> <Menu anchorEl={anchorE2} id="simple-menu" keepMounted open={Boolean(anchorE2)} onClose={handleClose} >{ videoData.map(data => ( <div style={{display: 'flex', justifyContent: 'space-between'}} key={data.id}> <MenuItem onClick={handleVideoClose}>{data.callerId} {data.message} </MenuItem> <div >{getStatus(data.status, data.call_id, data.id)}</div> </div> )) } <Button onClick={handleVideoClose} color='secondary'>Close</Button> </Menu> </> ); }; DashboardNavbar.propTypes = { onMobileNavOpen: PropTypes.func }; export default DashboardNavbar<file_sep>/src/components/DemoChart.jsx import ApexChart from 'react-apexcharts' import React, { useEffect, useState } from 'react' const DemoChart = ({data}) => { let time = [] let temp = [] let stillTime = [] let pressure = [] let delta = [] let deltaP =[] const [timeData, setTimeData] = useState([]) const [stillTimeData, setStillTimeData] = useState([]) const [tempData, setTempData] = useState([]) const [pressureData, setPressureData] = useState([]) const [deltaData, setDeltaData] = useState([]) const [deltaDataPressure, setDeltaDataPressure] = useState([]) useEffect(() => { var x, y, z; var randomTemp; let currTemp=25; let currPressure= 800; let currTime = 0; for (let index = 0; index < data.length; index++) { x = (data[index].temp1 - currTemp)/data[index].time1 y = (data[index].pressure - currPressure)/data[index].time1 for (let j = 0; j < data[index].time1 ; j++) { currTime++; currTemp = currTemp + x; currPressure = currPressure + y time.push(currTime) temp.push(currTemp) pressure.push(currPressure) } for (let k = 0; k < data[index].time2; k++) { currTime++ time.push(currTime) temp.push(currTemp) pressure.push(currPressure) } } setTimeData(time) setTempData(temp) setStillTimeData(stillTime) setPressureData(pressure) setDeltaData(delta) setDeltaDataPressure(deltaP) }) const [chartValues, setChartValues] = useState( { series: [{ name: 'Income', type: 'column', data: tempData }, { name: 'Cashflow', type: 'column', data: [1.1, 3, 3.1, 4, 4.1, 4.9, 6.5, 8.5] }, { name: 'Revenue', type: 'line', data: [20, 29, 37, 36, 44, 45, 50, 58] }], options: { chart: { height: 350, type: 'line', stacked: false }, dataLabels: { enabled: false }, stroke: { width: [1, 1, 4] }, title: { text: 'XYZ - Stock Analysis (2009 - 2016)', align: 'left', offsetX: 110 }, xaxis: { categories: timeData, }, yaxis: [ { axisTicks: { show: true, }, axisBorder: { show: true, color: '#008FFB' }, labels: { style: { colors: '#008FFB', } }, title: { text: "Income (thousand crores)", style: { color: '#008FFB', } }, tooltip: { enabled: true } }, { seriesName: 'Income', opposite: true, axisTicks: { show: true, }, axisBorder: { show: true, color: '#00E396' }, labels: { style: { colors: '#00E396', } }, title: { text: "Operating Cashflow (thousand crores)", style: { color: '#00E396', } }, }, { seriesName: 'Revenue', opposite: true, axisTicks: { show: true, }, axisBorder: { show: true, color: '#FEB019' }, labels: { style: { colors: '#FEB019', }, }, title: { text: "Revenue (thousand crores)", style: { color: '#FEB019', } } }, ], tooltip: { fixed: { enabled: true, position: 'topLeft', // topRight, topLeft, bottomRight, bottomLeft offsetY: 30, offsetX: 60 }, }, legend: { horizontalAlign: 'left', offsetX: 40 } }, } ) return ( <div> <ApexChart height={400} width={500} options={chartValues.options} series={chartValues.series}/> </div> ) } export default DemoChart <file_sep>/src/Pages/DQNewReports/DQRnew.jsx import { Button, Card, makeStyles, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow , Typography} from "@material-ui/core" import { useEffect, useState } from "react" import { db } from "../../firebase" import { firebaseLooper } from "../../utils/tools" import ArrowForwardIcon from '@material-ui/icons/ArrowForward'; import ContentDashboardLayout from "../../components/ContentSidebar/ContentDashboardLayout"; import moment from "moment"; import { NavLink } from "react-router-dom"; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'whitesmoke', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 250 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); function DQRnew({match}) { const [reports, setReports] = useState([]) const classes = useStyles() useEffect(() => { db.collection('DQNewReport') .where('mid', '==', `${match.params.id}`) .onSnapshot(snapshot => { const data = firebaseLooper(snapshot) data.sort(function(a,b){ return(b.timestamp - a.timestamp) }) setReports(data) }) }, []) return (<> <ContentDashboardLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <br /> <Typography variant='h1' align='center' gitterBottom><b>DQ Reports</b></Typography> <hr /> <br /> <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}>Name</TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right">Description</TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right">Date</TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right">Actions</TableCell> </TableRow> </TableHead> <TableBody> {reports.map((row) => ( <TableRow key={row.name}> <TableCell style={{background: '#E8F6EF'}} component="th" scope="row"> {row.name} </TableCell> <TableCell align="right">{row.desc}</TableCell> <TableCell align="right">{row.timestamp.toDate().toString().substring(0,15)}</TableCell> <TableCell align="right"><Button className='animate-bounce' component={NavLink} to={`/DQR/${row.id}/Approval`}><ArrowForwardIcon/></Button></TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </Card> </div> </div> </> ) } export default DQRnew <file_sep>/src/Pages/settings/AddApk.jsx import { Button, FormHelperText, Switch} from "@material-ui/core"; import { useState } from "react"; import { db } from "../../firebase"; import { useStorage } from "../../utils/useStorage"; function AddApk() { const [apk, setApk] = useState(false) const [file,setFile] = useState(null) const [version, setVersion] = useState("") const handleChange = (e) => { let selectedFile = e.target.files[0]; setFile(selectedFile) } const {url, progress} = useStorage(file) function updateMobile(){ db.collection("apks").doc('mobile').update({url,version}) } function updateGlass(){ db.collection("apks").doc('glass').update({url,version}) } return ( <> <div style={{display: 'flex', justifyContent: 'center', marginBottom: '20px', marginTop: '20px'}}> <input style={{ border: '2px solid'}} placeholder="Enter version" type="Text" onChange={(e) => setVersion(e.target.value)} /> </div> <div style={{display: 'flex', justifyContent: 'center', flexDirection: 'row'}}> <Switch onChange={(e) => {setApk(!apk); setFile(null)}}/> { !apk && <div> <input onChange={handleChange} type="file"/> <FormHelperText>Mobile Apk Here</FormHelperText> </div> } { apk && <div> <input onChange={handleChange} type="file"/> <FormHelperText>Glass Apk Here</FormHelperText> </div> } <br /> <br /> {!apk? <Button onClick={updateMobile} disabled={progress < 100 || file === null} >Update Mobile Apk</Button> : <Button onClick={updateGlass} disabled={progress < 100 || file=== null }>Update Glass Apk</Button>} </div> </> ) } export default AddApk <file_sep>/src/Pages/MachineContents/Content.jsx import { Button, makeStyles, Typography } from '@material-ui/core'; import React, { useEffect, useState } from 'react' import ContentItem from './ContentItem'; import {Link, useHistory} from 'react-router-dom'; import {db} from '../../firebase' import { firebaseLooper } from '../../utils/tools'; const useStyles = makeStyles((theme) =>( { add: { background:'#141256', borderRadius: '20px', margin: theme.spacing(3, 0, 2), marginLeft: "20px" } })) const Content = ({match}) => { const classes = useStyles(); const [isLoading, setIsLoading] = useState(false); const [content, setContent] = useState([{ contents: [], content1: {} }]); const [error, setError] = useState(null) useEffect (() => { db.collection('machines').doc(match.params.id).get().then((snapshot) => { const contentData = snapshot.data() setContent(contentData) }); }) const [open, setOpen] = useState(false) const [openEdit, setOpenEdit] = useState(false) const [title, setContentName] = useState() const [desc, setContentDescription] = useState(); const [createdAt, setCreatedAt] = useState(); const [loading, setLoading] = useState(false); const history = useHistory(); const handleEdit = () => { setOpenEdit(true) } const handleEditClose = () => { setOpenEdit(false) } const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const updateContent=(id) => { setLoading(true) const data = {title,desc,createdAt} fetch(`http://localhost:5000/content/${id}`,{ method: 'PUT', headers: { 'Accept': 'application/json', "Content-Type": "application/json" }, body: JSON.stringify(data) }).then((res) => { res.json().then((resp) => { setLoading(false) window.location.reload() history.push('/machine-content') }) }) } return ( <div> {error && <Typography variant="h6">{error}</Typography>} {isLoading && <Typography variant="h3">Loading...</Typography>} <Button variant="contained" color="primary" className={classes.add}> <Link style={{color: "white" ,textDecoration: "none"}} to="/add-content"> Add Content </Link> </Button> <Typography variant="h1">{content.title}</Typography> <ContentItem content={content} /> </div> ) } export default Content<file_sep>/src/Pages/DQNewReports/DQRComponents.jsx import { TextField } from "@material-ui/core" import { Button, Card,Toolbar, makeStyles,Dialog,DialogContent, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow , Typography} from "@material-ui/core" import { useEffect, useState } from "react" import { db } from "../../firebase" import { firebaseLooper } from "../../utils/tools" function DQRComponents({match, moduleId,type}) { const [reports, setReports] = useState([]) const [open, setOpen] = useState(false) const [issuecomment, setIssueComment] = useState('') const [activeId, setActiveId] = useState('') function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } useEffect(() => { db.collection('DQNewReport') .doc(match.params.id) .collection('content') .doc('config') .collection('components') .where('module_id', '==', `${moduleId}`) .onSnapshot(snapshot => { const data = firebaseLooper(snapshot) setReports(data) }) }, []) function handleComment(id){ db.collection('issueData').doc(id).onSnapshot(snapshot => { const data = snapshot.data() setIssueComment(data.content ) }) } function activateId(id){ setActiveId(id) } function handleCommentChange(id){ db.collection('issueData').doc(id).update({content: issuecomment}) } function getResponse(res) { if(res === 1){ return( <b style={{background: '#BBE5B3 0% 0% no-repeat padding-box', borderRadius: '100px', border: '2px solid var(--unnamed-color-ffffff)'}}>Accepted</b> ) }else if(res === 2){ return( <b style={{background: '#FF616D 0% 0% no-repeat padding-box', borderRadius: '100px', border: '2px solid var(--unnamed-color-ffffff)'}}>Rejected</b> ) }else if (res === 3){ return( <b style={{background: '#FFEAC9 0% 0% no-repeat padding-box', borderRadius: '100px', border: '2px solid var(--unnamed-color-ffffff)'}}>Issued</b> ) }else { return( <b style={{background: '#CDF0EA 0% 0% no-repeat padding-box', borderRadius: '100px', border: '2px solid var(--unnamed-color-ffffff)'}}>Not Updated</b> ) } } return ( <> <hr /> <div style={{paddingRight: '5%', paddingLeft: '5%'}}> {type===0 && <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}>Name</TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right">Expected Value</TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right">Response</TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right">Issue </TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right">Actions</TableCell> </TableRow> </TableHead> <TableBody> {reports.map((row) => ( <TableRow key={row.name}> <TableCell style={{background: '#E8F6EF'}} component="th" scope="row"> {row.title} </TableCell> <TableCell align="right">{row.value}</TableCell> <TableCell align="right">{getResponse(row.response)}</TableCell> <TableCell align="right">{row.issue_id ? <b>{row.issue_id}</b> : <b>N/A</b>}</TableCell> <TableCell align="right"> {row.issue_id !== ""? <Button style={{background: 'orange', color: 'white'}} onClick={(e) => { handleOpen(e); handleComment(row.issue_id) activateId(row.issue_id) }}>Check</Button> : <p>N/A</p>} </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> } {type===1 &&<TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}><b className='text-md font-bold italic'>Description</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-md font-bold italic'>Required Parameters</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-md font-bold italic'>Instrument/Gauges</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-md font-bold italic'>Preferred Pipe & Connection</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-md font-bold italic'>Response</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right">Issue </TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right"><b className='text-md font-bold italic'>Options</b></TableCell> </TableRow> </TableHead> <TableBody> {reports.map((row) => ( <TableRow key={row.name}> <TableCell style={{background: '#E8F6EF'}} component="th" scope="row"> {row.desc} </TableCell> <TableCell align="left">{row.req}</TableCell> <TableCell align="left">{row.inst}</TableCell> <TableCell align="left">{row.connection}</TableCell> <TableCell align="left">{getResponse(row.response)}</TableCell> <TableCell align="left">{row.issue_id ? <b>{row.issue_id}</b> : <b>N/A</b>}</TableCell> <TableCell align="right"> {row.issue_id !== ""? <Button style={{background: 'orange', color: 'white'}} onClick={(e) => { handleOpen(e); handleComment(row.issue_id); activateId(row.issue_id) }}>Check</Button> : <p>N/A</p>} </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer>} <Dialog fullWidth onClose={handleClose} open={open}> <Toolbar> <Button onClick={handleClose}>Close</Button> </Toolbar> <b className='text-xl underline text-bold text-center mb-3'>Comment</b> <TextField variant='outlined' onChange={(e) => setIssueComment(e.target.value)} value={issuecomment} className='text-xl text-blue-gray-500 text-center'/> <Button onClick={(e) => {handleCommentChange(activeId); handleClose()}}>Update</Button> </Dialog> </div> </> ) } export default DQRComponents <file_sep>/src/Pages/DQNew/DQComponents/DQNewView.jsx import { DialogActions, DialogTitle, FormHelperText } from "@material-ui/core" import { DialogContent } from "@material-ui/core" import { DialogContentText } from "@material-ui/core" import { Button, Dialog, Typography,TextField } from "@material-ui/core" import { useState } from "react" import { db } from "../../../firebase" import EditIcon from '@material-ui/icons/Edit'; import DeleteIcon from '@material-ui/icons/Delete'; import { NavLink } from "react-router-dom" import { Alert, AlertTitle } from "@material-ui/lab" function DQNewView({report}) { const [name, setName] = useState(report.name) const [desc, setDesc] = useState(report.desc) const [open, setOpen] = useState(false) const [error, setError] = useState('') const [openDelete, setOpenDelete] = useState(false) function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleOpenDelete (){ setOpenDelete(true) } function handleCloseDelete(){ setOpenDelete(false) } function handleDelete(id){ db.collection('DQNew').doc(id).delete() } function handleSubmit(e){ e.preventDefault() if(name?.trim().length === 0 || desc?.trim().length === 0){ return setError("Empty Strings are not valid input! Please try again with a valid input") } db.collection('DQNew').doc(report.id).update({name, desc}).then(() => {setOpen(false)}) } console.log(report) return ( <div> <div> {/* <div className="p-6 mx-auto bg-white border rounded-lg shadow-xl lg:w-1/2"> <div className="flex flex-col items-start py-2 rounded-lg lg:flex-row"> <div className="flex flex-col w-full text-blueGray-500 lg:ml-4"> <div style={{display: 'flex' , justifyContent: 'space-evenly'}}> <h2 className="mt-4 mb-8 text-lg font-semibold tracking-widest text-black uppercase lg:mt-0 title-font"> {report.name}</h2> <Button onClick={handleOpen}><EditIcon/></Button> <Button onClick={handleOpenDelete}><DeleteIcon/></Button> </div> <p className="mb-3 text-base leading-relaxed text-blueGray-500"> {report.desc}</p> <Button component={NavLink} to={`/DQ/${report.id}/Approval`} fullWidth style={{backgroundColor: 'orange', color: 'white', margintop:'3%'}}>Content</Button> </div> </div> </div> */} <Dialog fullWidth open={open} onClose={handleClose}> <form action="" onSubmit={handleSubmit}> {error && <Alert severity='error'>{error}</Alert>} <div> < > <Typography style={{marginTop: '15px'}} variant='h3' align='center' gutterBottom><b>Update {name}</b></Typography> <DialogContent > <TextField label="Name" required error={name.length > 40} variant='outlined' fullWidth value={name} onChange={(e) => setName(e.target.value)} type="text" placeholder="Enter Name" /> <FormHelperText style={{marginBottom: '20px'}}>Name should be max {name.length}/40</FormHelperText> <TextField label="Description" required error={desc.length> 300} fullWidth multiline rows={5} variant='outlined' value={desc} onChange={(e) => setDesc(e.target.value)} required/> <FormHelperText>Desc should be max {desc.length}/300</FormHelperText> </DialogContent> </> <DialogActions > <Button onClick={handleClose}>Cancel</Button> <Button type="submit" disabled={ desc>300 || name > 35} style={{background: 'orange', color: 'white'}} > Update </Button> </DialogActions> </div> </form> </Dialog> </div> <Dialog open={openDelete} onClose={handleCloseDelete} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <Alert severity="error" variant="filled"> <AlertTitle><strong>Delete</strong></AlertTitle> <DialogTitle id="alert-dialog-title">{"Are You Sure You Want To Delete?"}</DialogTitle> <DialogContent> <DialogContentText color="white" id="alert-dialog-description"> Deleting will be a permanent action and data pervailing will be permanently deleted and can not be retrieved back. </DialogContentText> </DialogContent> </Alert> <DialogActions> <Button onClick={handleCloseDelete} color="primary" variant="outlined"> Disagree </Button> <Button onClick={(e)=>{ handleDelete(report.id); handleCloseDelete()}} color="secondary" variant="outlined" autoFocus> Agree </Button> </DialogActions> </Dialog> <div className="xl:w-full w-11/12 mx-auto flex flex-wrap items-center justify-between xl:px-8 md:px-8 lg:px-8 mb-2 xl:mb-0 lg:mb-0 border-b border-gray-300 dark:border-gray-700"> <div className="xl:w-3/5 lg:w-2/4 w-full pt-6 xl:pb-6 lg:pb-8 md:pb-8 sm:pb-8"> <p className="text-lg font-bold text-gray-800 dark:text-gray-100 pb-1">{report.name}</p> <p className="text-xs font-normal text-gray-600 dark:text-gray-400">{report.desc}</p> </div> <div className="xl:w-1/5 lg:w-1/4 w-full pt-6 pb-8"> <div className="flex items-center w-full justify-between"> <Button component={NavLink} to={`/DQ/${report.id}/Approval`} className="text-gray-400 hover:text-gray-500 cursor-pointer"> Open <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-chevron-right" width={20} height={20} viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor" fill="none" strokeLinecap="round" strokeLinejoin="round"> <path stroke="none" d="M0 0h24v24H0z" /> <polyline points="9 6 15 12 9 18" /> </svg> </Button> </div> </div> <div className="xl:w-1/5 lg:w-1/4 w-full pt-6 xl:pb-8 lg:pb-8 md:pb-8 sm:pb-8"> <div className="flex items-center xl:-ml-10"> <Button onClick={handleOpen}><EditIcon/></Button> <Button onClick={handleOpenDelete}><DeleteIcon/></Button> </div> </div> </div> </div> ) } export default DQNewView <file_sep>/src/Pages/MachinesPage.jsx import { Helmet } from 'react-helmet'; import { Box, Container, Grid, TablePagination } from '@material-ui/core'; import Machines from '../components/Machines/Machines'; const MachinesPage = () => ( <> <Helmet> <title>Machines | LyoIMS</title> </Helmet> <Box py={3} style={{ backgroundColor: 'background.default', minHeight: '100%', }} > <Container maxWidth={false}> <Box pt={3} > <Grid container spacing={3} > <Grid item lg={4} md={6} xs={12} > <Machines/> </Grid> </Grid> </Box> </Container> </Box> </> ); export default MachinesPage;<file_sep>/src/Pages/DQPages/DQGeneral.jsx import { DialogContent, Fab, makeStyles } from "@material-ui/core"; import { Button, Dialog, Typography, TextField, DialogActions, Card } from "@material-ui/core" import { useEffect } from "react" import { useState } from "react" import DQLayout from "../../components/DQNewSidebar/DQLayout"; import { db } from "../../firebase" import { NavLink as RouterLink, matchPath, useLocation, NavLink } from 'react-router-dom'; import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight'; import KeyboardArrowLeftIcon from '@material-ui/icons/KeyboardArrowLeft'; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'whitesmoke', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, fab: { position: 'absolute', bottom: theme.spacing(2), right: theme.spacing(2), }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 250 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); function DQGeneral({match}) { const [purpose, setPurpose] = useState({}) const [title, setTitle] = useState('') const [ desc, setDesc] = useState('') const [open, setOpen] = useState(false) const [opendelete, setOpenDelete] = useState(false) const classes = useStyles() function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleOpenDel(){ setOpenDelete(true) } function handleCloseDel(){ setOpenDelete(false) } function handleUpdate(e){ db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('general') .update({title, desc}) } function handleSubmit(){ db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('general') .set({title, desc}) } useEffect(() => { db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('general') .onSnapshot(snapshot => { const data = snapshot.data() setPurpose(data) if(data){ setTitle(data.title) setDesc(data.desc) } }) }, []) return ( <> {purpose ? (<> <DQLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div > <Typography variant='h1' align='center' gutterBottom><b>{purpose.title}</b></Typography> <hr /> <Typography variant='body1' align='left' gutterBottom><p className='italic'>{purpose.desc}</p></Typography> <hr /> <div className={classes.fab}> <Fab component={NavLink} to={`/DQ/${match.params.id}/Purpose`} style={{marginRight: '20px'}} color="primary" aria-label="add"> <KeyboardArrowLeftIcon/> </Fab> <Fab component={NavLink} to={`/DQ/${match.params.id}/Specifications`} color="primary" aria-label="add"> <KeyboardArrowRightIcon/> </Fab> </div> <div style={{display: 'flex', marginBottom: 'auto', paddingRight: '3%', justifyContent: 'flex-end'}}> {/* <Button component={RouterLink} to={`/DQ/${match.params.id}/Purpose`} style={{background: 'blue', color: 'white', marginLeft: '25px', marginRight: '25px'}}> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-90deg-left" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1.146 4.854a.5.5 0 0 1 0-.708l4-4a.5.5 0 1 1 .708.708L2.707 4H12.5A2.5 2.5 0 0 1 15 6.5v8a.5.5 0 0 1-1 0v-8A1.5 1.5 0 0 0 12.5 5H2.707l3.147 3.146a.5.5 0 1 1-.708.708l-4-4z"/> </svg> </Button> */} <Button style={{color: 'white', background: 'orange'}} onClick={handleOpen}>Edit</Button> {/* <Button component={RouterLink} to={`/DQ/${match.params.id}/Equipment-Config`} style={{background: 'blue', color: 'white', marginLeft: '25px'}}> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-90deg-right" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M14.854 4.854a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 4H3.5A2.5 2.5 0 0 0 1 6.5v8a.5.5 0 0 0 1 0v-8A1.5 1.5 0 0 1 3.5 5h9.793l-3.147 3.146a.5.5 0 0 0 .708.708l4-4z"/> </svg> </Button> */} </div> <Dialog style={{alignItems: 'center'}} fullWidth open={open} onClose={handleClose}> <DialogContent> <Typography variant='h4' align='center' gutterBottom><b>Edit Details</b></Typography> <form > <TextField style={{marginBottom: '3%'}} value={title} variant='outlined' fullWidth onChange={(e) => setTitle(e.target.value)}/> <TextField multiline rows={7} value={desc} variant='outlined' fullWidth onChange={(e) => setDesc(e.target.value)}/> </form> </DialogContent> <DialogActions> <Button onClick={handleClose}>Cancel</Button> <Button onClick={handleUpdate} style={{backgroundColor: 'orange', color: 'whitesmoke'}}>Update</Button> </DialogActions> </Dialog> </div> </Card> </div> </div> </>) : <> <DQLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div style={{padding: '10%', paddingTop: '0'}} > <Typography variant='h1' align='center' gutterBottom><b>Add New Information</b></Typography> <TextField style={{marginBottom: '20px'}} label='Title' variant='outlined' fullWidth onChange={(e) => setTitle(e.target.value)}/> <TextField style={{marginBottom: '5%'}} label='Description' multiLine rows={7} variant='outlined' fullWidth onChange={(e) => setDesc(e.target.value)}/> <Button disabled={title === '' || desc === '' || desc>300 || title > 35} fullWidth style={{background: 'orange', color: 'white'}} onClick={handleSubmit}>Add New</Button> </div> </Card> </div> </div> </>} </> ) } export default DQGeneral <file_sep>/src/components/VideoCall/ListUsers.jsx import { v4 as uuid } from 'uuid'; import moment from 'moment'; import { Avatar, Box, Button, Card, CardHeader, Divider, IconButton, List, ListItem, ListItemAvatar, ListItemText, TextField } from '@material-ui/core'; import MoreVertIcon from '@material-ui/icons/MoreVert'; import ArrowRightIcon from '@material-ui/icons/ArrowRight'; import PeopleAltIcon from '@material-ui/icons/PeopleAlt'; import { useEffect, useState } from 'react'; import { db } from '../../firebase'; import { firebaseLooper } from '../../utils/tools'; import PageUser from './PageUser'; const ListUsers = ({call_id}) =>{ const [users, setUsers] = useState([]) const [searchTerm, setSearchTerm] = useState('') useEffect(() => { db.collection('users').get().then(snapshot => { const user = firebaseLooper(snapshot); setUsers(user) }).catch(err => { console.log(err) }) }, []) return ( <Card > <CardHeader subheader={`${users.length} in total`} title="Users" /> <Divider /> <TextField fullWidth onChange={(e) => setSearchTerm(e.target.value)} label='Search User'/> <List> {users. filter((data) => { if(searchTerm === ""){ return data } else if (data.email.toLowerCase().includes(searchTerm.toLowerCase())){ return data }else if (data.firstName.toLowerCase().includes(searchTerm.toLowerCase())){ return data } else if (data.lastName.toLowerCase().includes(searchTerm.toLowerCase())){ return data }else if (data.phone.toLowerCase().includes(searchTerm.toLowerCase())){ return data } }) .slice(0,10).map((user, i) => ( <PageUser user={user} callId={call_id}/> ))} </List> <Divider /> <Box p={2} style={{ display: 'flex', justifyContent: 'flex-end', }} > </Box> </Card> )}; export default ListUsers;<file_sep>/src/Pages/Steps/Steps.jsx import { Button, Card, Container, Dialog, DialogContent, makeStyles, Switch, Typography } from '@material-ui/core'; import React, { useEffect, useState } from 'react' import StepItem from './StepItem'; import {Link, useHistory} from 'react-router-dom'; import {db, storageRef } from '../../firebase' import { firebaseLooper } from '../../utils/tools'; import AddIcon from '@material-ui/icons/Add'; import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import Page from '../../components/Page'; import ManualDashboardLayout from '../../components/ManualSidebar/ManualDashboardLayout' import OutlinedTimeline from './Timeline'; import StepCarousel from './StepCarousel'; import Carousel from 'react-bootstrap/Carousel' import AddSteps from './AddSteps'; const useStyles = makeStyles((theme) =>( { add: { backgroundImage: 'linear-gradient(to left bottom, #fa630f, #fc8218, #fd9d29, #feb63f, #ffce59)', borderRadius: '20px', margin: theme.spacing(3, 0, 2), }, backButton: { backgroundColor: "black", color: "white", borderRadius: "20px", marginRight: "30px", marginLeft: "20px", }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })) const Steps = ({match}) => { const classes = useStyles(); const history=useHistory() const [mTitle, setMTitle] = useState('') const [steps, setSteps] = useState([{}]) const [checked, setChecked] = useState(true) const [open, setOpen] = useState(false) const dbRef = db.collection('stepData').where('manual_id', '==', `${match.params.id}`) const handleReturn = () => { history.push('/machine-data') } useEffect(() => { db.collection('manualData') .doc(match.params.id) .onSnapshot(doc => { setMTitle(doc.data().title) }) dbRef.onSnapshot((snapshot) => { const stepData = firebaseLooper(snapshot) stepData.sort(function(a,b) { return(a.index-b.index) }) setSteps(stepData) }) }, []) return ( <Page title="Steps"> <ManualDashboardLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div style={{display: 'flex', justifyContent: 'space-between'}}> <Typography variant='h4' align='center' gutterBottom><b>{mTitle}</b></Typography> <div> <b>SWITCH MODE</b> <Switch onChange={(e) => setChecked(!checked)} checked={checked} color='primary'/> </div> <Button onClick={() => setOpen(!open)}>Add Steps</Button> </div> { checked? <Container> { steps&& steps.map((data) => ( <StepItem key={data.id} data={data} /> )) } </Container> : <Carousel nextIcon ={<span className=" flex items-center w-full px-6 py-2 font-semibold text-white transition duration-500 ease-in-out transform bg-black rounded-lg lg:w-auto focus:shadow-outline focus:outline-none focus:ring-2 ring-offset-current ring-offset-2 ">Next</span>} prevIcon={<span className="flex items-center w-full px-6 py-2 font-semibold text-white transition duration-500 ease-in-out transform bg-black rounded-lg lg:w-auto focus:shadow-outline focus:outline-none focus:ring-2 ring-offset-current ring-offset-2">Prev</span>} > { steps.map((data) => ( <Carousel.Item style={{height: '80vh', width: '75%', marginLeft: '14%'}}> <> <div style={{backgroundColor: 'black', opacity: 0.5}}> <Typography variant='h3' align='center' style={{color: 'orange'}}><b>{data.title}</b></Typography> <Typography variant='body1' align='center' style={{color: 'orange'}}>{data.desc}</Typography> </div> </> { data.format === 'image'? <img style={{width: '100%', height: '75vh'}} src={data.url} alt="First slide" /> : data.format === 'video'? <div> <video style={{width: '100%', height: '75vh'}} controls src={data.url} alt="First slide" /> </div> : data.format === 'audio'? <audio style={{ margin: '30%', marginTop: '5%', marginBottom: '20%'}} controls src={data.url}/> : <b>Not Available</b> } </Carousel.Item> )) } </Carousel> } </Card> <Dialog open={open} onClose={() => setOpen(false)}> <DialogContent> <AddSteps match={match}/> </DialogContent> </Dialog> </div> </div> </Page> ) } export default Steps<file_sep>/src/Pages/Recipee/AddRecipe.jsx import { Button, Card, CardActions, CardContent, FormHelperText, makeStyles, TextField, Typography } from '@material-ui/core'; import { Alert } from '@material-ui/lab'; import React, { useEffect, useState } from 'react' import { useHistory } from 'react-router-dom'; import ContentDashboardLayout from '../../components/ContentSidebar/ContentDashboardLayout'; import { useAuth } from '../../components/context/AuthContext'; import { db } from '../../firebase'; import { firebaseLooper } from '../../utils/tools'; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'white', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 } }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', height: '100%' }, content: { margin: '15%', flex: '1 1 auto', width: '75%', overflow: 'auto' }, })); const AddRecipe = ({match}) => { const {currentUser} = useAuth() const classes = useStyles() const [title, setTitle] = useState('') const [error, setError] = useState('') const [mid, setMid] = useState(`${match.params.id}`) const [recipe, setRecipe] = useState([]) const history = useHistory() useEffect (() => { db.collection('recipes').where('mid', '==', `${match.params.id}`).onSnapshot(doc => { const data = firebaseLooper(doc) setRecipe(data) }) }, []) function handleChange(e){ const titleD = e.target.value if(recipe.length === 0){ return setTitle(titleD) } for (let index = 0; index < recipe.length; index++) { const element = recipe[index].title; if(titleD === element){ setTitle(titleD) return setError("Recipe already exists! Please try again with another name") }else { setError("") setTitle(titleD) } } } const handleSubmit = (e) => { e.preventDefault() if(title?.trim().length === 0){ return setError("Empty Strings are not valid inputs ! Please try again with a valid input") } if(!error){ const createdBy = `${currentUser.email}` const data = {title, mid, createdBy} db.collection('recipes').add(data) history.push(`/machine-data/Reports/${match.params.id}/Recipes`) } } return ( <> <ContentDashboardLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <CardContent > <Typography variant='button' component='h1' align='center'><b>Add Recipe</b></Typography> <form style={{width: '100%', alignItems: "center"}} onSubmit={handleSubmit}> {error && <Alert severity='error'>{error}</Alert>} <TextField variant="outlined" margin="normal" required fullWidth label='Title' value={title} error={title.length > 40 } onChange={handleChange} /> <FormHelperText>Title length should be maximum {title.length}/40</FormHelperText> <TextField variant="outlined" margin="normal" label='mid' value={mid} disabled fullWidth onChange={(e) => setMid(e.target.value)} /> <CardActions> <Button disabled={title.length>40} fullWidth variant='outlined' color="primary" type="submit">Add New Recipe</Button> </CardActions> </form> </CardContent> </Card> </div> </div> </> ) } export default AddRecipe <file_sep>/src/components/InviteForm/InviteForm.jsx import React, { useState } from 'react' import emailjs from 'emailjs-com'; import { v4 as uuidv4 } from 'uuid'; const InviteForm = () => { const [toEmail, setToEmail] = useState('') const [message, setMessage] = useState('') const [disabled, setDisabled] = useState(false) function sendEmail(e) { e.preventDefault(); //This is important, i'm not sure why, but the email won't send without it emailjs.send("gmail","template_3a12ff8",{ to_name: `${toEmail}` , from_name: "Arizon", message: `You have been invited to join the video call : https://lyodata.web.app/video-call/${uuidv4()}`, reply_to: "<EMAIL>", to_email: toEmail, }, "user_gqmHsTLEHxh06fhWlDnqq").then(() => { setMessage('Invited Successfully') setDisabled(true) setToEmail('') }) } return ( <section className="w-full max-w-2xl px-6 py-4 mx-auto bg-white rounded-md shadow-md dark:bg-gray-800"> <h2 className="text-3xl font-semibold text-center text-gray-800 dark:text-white">Invite Participants </h2> <p className="mt-3 text-center text-gray-600 dark:text-gray-400">Invite partcipants by entering their Email</p> <div className="mt-6 "> <div className="items-center -mx-2 md:flex"> <div className="w-full mx-2 mt-4 md:mt-0"> <label className="block mb-2 text-sm font-medium text-gray-600 dark:text-gray-200">E-mail</label> <input value={toEmail} onChange={(e) =>setToEmail(e.target.value)} className="block w-full px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-md dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600 focus:border-blue-500 dark:focus:border-blue-500 focus:outline-none focus:ring" type="email"/> </div> </div> <div className="flex justify-center mt-6"> <button disabled={disabled} onClick={sendEmail} className="px-4 py-2 text-white transition-colors duration-200 transform bg-gray-700 rounded-md hover:bg-gray-600 focus:outline-none focus:bg-gray-600">Send Invite</button> </div> {message && <p className="mt-3 text-center text-green-600 dark:text-gray-400">{message}</p>} </div> </section> ) } export default InviteForm <file_sep>/src/Pages/DQNewReports/AddApproval.jsx import { useState } from "react" import * as admin from 'firebase-admin' import { db } from "../../firebase" import {useStorage} from '../../utils/useStorage' import { FormHelperText, TextField, Button, Switch } from "@material-ui/core" import { Typography } from "@material-ui/core" function AddApproval({match}) { const [name, setName] = useState('') const [file, setFile] = useState(null) const {prograss, url} = useStorage(file) const types = ["image/png", "image/jpeg", "image/jpg"]; const [error, setError] = useState('') const [change, setChange] = useState(false) const handleChange = (e) => { let selectedFile = e.target.files[0]; if (selectedFile) { if (types.includes(selectedFile.type)) { setError(null) setFile(selectedFile); } else { setFile(null); setError("Please select an image file (png or jpg)"); } } } function handleSubmitC(){ db.collection('DQNewReport'). doc(match.params.id) .collection('content') .doc('approval') .collection('customer') .add({name,url, timestamp: new Date()}) .then(() => { setName('') setFile(null) } ) } function handleSubmitV(){ db.collection('DQNewReport'). doc(match.params.id) .collection('content') .doc('approval') .collection('vendor') .add({name,url, timestamp: new Date()}) } return ( <div> <Typography variant='h3'align='center' gutterBottom >Add Details</Typography> <div> <TextField variant='outlined' fullWidth label='Name' style={{marginBottom: '25px'}} value={name} onChange={(e) => setName(e.target.value)} /> <input type='file' onChange={handleChange} /> <FormHelperText>Put you Signature here (Image Formats only)</FormHelperText> </div> <div> <Switch onClick={(e) => setChange(!change)}></Switch> <FormHelperText>Set For customer/Reviewer</FormHelperText> { change? <div style={{display: 'flex', justifyContent: 'center'}}> <Button onClick={handleSubmitC} style={{background: 'orange', color: 'white'}}>Add for Customer</Button> </div> : <div style={{display: 'flex', justifyContent: 'center'}}> <Button disabled={process < 100 || name === '' } onClick={handleSubmitV} style={{background: 'orange', color: 'white'}} >Add for Reviewer</Button> </div> } </div> { url && <div style={{align:'center', display: 'flex', justifyContent: 'center'}}> <img src={url} width='350px' height='250px'/> </div> } </div> ) } export default AddApproval <file_sep>/src/components/DropZone/imagesDropzone.js import React from "react"; import { app } from "../../firebase"; import { useDropzone } from "react-dropzone"; import { Grid, Typography, Button } from "@material-ui/core"; export default function ImagesDropzone({ setImageList }) { const onDrop = (acceptedFiles) => { if (acceptedFiles.length > 0) { const newImages = Array.from(acceptedFiles).map((file) => { return { file: file, fileName: file.name, status: "CREATED", storageRef: app.storage().ref().child(file.name), downloadURL: "", description: "", }; }); setImageList((prevState) => [...prevState, ...newImages]); } }; const { getRootProps, getInputProps, isDragActive, open } = useDropzone({ onDrop, accept: "image/png, image/jpeg", noClick: true, noKeyboard: true, }); return ( <div {...getRootProps()}> <input {...getInputProps()} /> <Grid container direction="column" spacing={2}> <Grid item container direction="column" alignItems="center" spacing={1} > <Grid item> <Typography align="center"> {isDragActive ? "Drop Images here ..." : "Drag 'n' drop Images here, or:"} </Typography> </Grid> <Grid item> <Button onClick={open} variant="contained" color="primary"> Select Images... </Button> </Grid> </Grid> </Grid> </div> ); }<file_sep>/src/components/AddUser/UserList.jsx import React, {useEffect, useState} from 'react' import { Button, Card, Container, makeStyles, TableCell, TableFooter, TablePagination, TableRow, TextField, Typography, useTheme } from '@material-ui/core'; import { db } from '../../firebase'; import { firebaseLooper } from '../../utils/tools'; import IconButton from '@material-ui/core/IconButton'; import FirstPageIcon from '@material-ui/icons/FirstPage'; import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft'; import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight'; import LastPageIcon from '@material-ui/icons/LastPage'; import PropTypes from 'prop-types'; import { useHistory } from 'react-router-dom'; import UserItem from './UserItem'; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'white', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', background:'linear-gradient(#f3f3f3, #e7e7e7)' }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, background:'white' }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { background:'white', flex: '1 1 auto', height: '100%', overflow: 'auto' }, table: { minWidth: 500, }, root: { flexShrink: 0, marginLeft: theme.spacing(2.5), }, })); TablePaginationActions.propTypes = { count: PropTypes.number.isRequired, onChangePage: PropTypes.func.isRequired, page: PropTypes.number.isRequired, rowsPerPage: PropTypes.number.isRequired, }; function TablePaginationActions(props) { const classes = useStyles(); const theme = useTheme(); const { count, page, rowsPerPage, onChangePage } = props; const handleFirstPageButtonClick = (event) => { onChangePage(event, 0); }; const handleBackButtonClick = (event) => { onChangePage(event, page - 1); }; const handleNextButtonClick = (event) => { onChangePage(event, page + 1); }; const handleLastPageButtonClick = (event) => { onChangePage(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1)); }; return ( <div className={classes.root}> <IconButton onClick={handleFirstPageButtonClick} disabled={page === 0} aria-label="first page" > {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />} </IconButton> <IconButton onClick={handleBackButtonClick} disabled={page === 0} aria-label="previous page"> {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />} </IconButton> <IconButton onClick={handleNextButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="next page" > {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />} </IconButton> <IconButton onClick={handleLastPageButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="last page" > {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />} </IconButton> </div> ); } const UserList = ({users}) => { const [searchTerm, setSearchTerm] = useState('') const [userData, setUserData] = useState([{}]) const history = useHistory() const classes = useStyles() useEffect (() => { db.collection('users') .onSnapshot(doc => { const data = firebaseLooper(doc) setUserData(data) }) }, []) const [page, setPage] = React.useState(0); const [rowsPerPage, setRowsPerPage] = React.useState(5); const emptyRows = rowsPerPage - Math.min(rowsPerPage, users.length - page * rowsPerPage); const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; return ( <> <Container > <div > <Card className={classes.content}> <div style={{display: 'flex', justifyContent: 'flex-end'}}> <TextField onChange={(e) => setSearchTerm(e.target.value)} label="Search User" margin="normal" variant="outlined" /> <br/> </div> {(rowsPerPage > 0 ? users.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : users ). filter((data) => { if(searchTerm === ""){ return data } else if (data.email.toLowerCase().includes(searchTerm.toLowerCase())){ return data }else if (data.firstName.toLowerCase().includes(searchTerm.toLowerCase())){ return data } else if (data.lastName.toLowerCase().includes(searchTerm.toLowerCase())){ return data }else if (data.phone.toLowerCase().includes(searchTerm.toLowerCase())){ return data } }) .map((data) => ( <UserItem key={data.id} users={data} /> ))} {emptyRows > 0 && ( <TableRow style={{ height: 53 * emptyRows }}> <TableCell colSpan={6} /> </TableRow> )} <TableFooter style={{display: 'flex', justifyContent: 'flex-end'}}> <TableRow> <TablePagination rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]} colSpan={3} count={users.length} rowsPerPage={rowsPerPage} page={page} SelectProps={{ inputProps: { 'aria-label': 'rows per page' }, native: true, }} onChangePage={handleChangePage} onChangeRowsPerPage={handleChangeRowsPerPage} ActionsComponent={TablePaginationActions} /> </TableRow> </TableFooter> </Card> </div> </Container> </> ) } export default UserList<file_sep>/src/Pages/IQ/IQComponents/ControlView.jsx import { Button, Dialog, DialogActions,Toolbar, DialogContent, DialogContentText, DialogTitle, TableBody, TableCell, TableRow, TextField, Typography } from "@material-ui/core" import { Alert, AlertTitle } from "@material-ui/lab" import { useState } from "react" import { db } from "../../../firebase" import EditIcon from '@material-ui/icons/Edit'; import DeleteIcon from '@material-ui/icons/Delete'; import IQPanelPage from "../IQPages.jsx/IQPanelPage"; function ControlView({module, match}) { const [title, setTitle] = useState(module.title) const [desc, setDesc] = useState(module.desc) const [open, setOpen] = useState(false) const [openDel, setOpenDel] = useState(false) const [openC, setOpenC] = useState(false) function handleOpenDel(){ setOpenDel(true) } function handleCloseDel(){ setOpenDel(false) } function openComponent(){ setOpenC(true) } function closeComponent(){ setOpenC(false) } function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleUpdate(){ db.collection('IQ').doc(match.params.id) .collection('content').doc('control') .collection('tables') .doc(module.id) .update({title, desc}) } function handleDelete(id){ db.collection('IQ').doc(match.params.id) .collection('content').doc('control') .collection('tables') .doc(id) .delete() } return ( <> <TableBody> <TableRow key={module.id}> <TableCell component="th" scope="row"> {module.title} </TableCell> <TableCell align="left">{module.desc}</TableCell> <TableCell align="right"> <div> <Button onClick={handleOpen}><EditIcon/></Button> <Button onClick={handleOpenDel}><DeleteIcon/></Button> <Button onClick={openComponent}>Open</Button> </div> </TableCell> </TableRow> </TableBody> <Dialog style={{alignItems: 'center'}} fullWidth open={open} onClose={handleClose}> <DialogContent> <Typography variant='h4' align='center' gutterBottom><b>Edit Details</b></Typography> <form > <TextField style={{marginBottom: '3%'}} value={title} variant='outlined' fullWidth onChange={(e) => setTitle(e.target.value)}/> <TextField multiline rows={7} value={desc} variant='outlined' fullWidth onChange={(e) => setDesc(e.target.value)}/> </form> </DialogContent> <DialogActions> <Button onClick={handleClose}>Cancel</Button> <Button onClick={handleUpdate} style={{backgroundColor: 'orange', color: 'whitesmoke'}}>Update</Button> </DialogActions> </Dialog> {/* Open delete dialog */} <Dialog open={openDel} onClose={handleCloseDel} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <Alert severity="error" variant="filled"> <AlertTitle><strong>Delete</strong></AlertTitle> <DialogTitle id="alert-dialog-title">{"Are You Sure You Want To Delete?"}</DialogTitle> <DialogContent> <DialogContentText color="white" id="alert-dialog-description"> Deleting will be a permanent action and data pervailing will be permanently deleted and can not be retrieved back. </DialogContentText> </DialogContent> </Alert> <DialogActions> <Button onClick={handleCloseDel} color="primary" variant="outlined"> Disagree </Button> <Button onClick={(e) => handleDelete(module.id)} color="secondary" variant="outlined" autoFocus> Agree </Button> </DialogActions> </Dialog> <Dialog fullScreen open={openC}> <Toolbar> <Button onClick={closeComponent}>Close</Button> </Toolbar> <IQPanelPage match={match} tid={module.id}/> </Dialog> </> ) } export default ControlView <file_sep>/src/components/ChatApp/VideoChat.jsx import { Button } from '@material-ui/core'; import { ChatEngine } from 'react-chat-engine'; import ChatFeed from './ChatFeed'; import LoginForm from './Login'; import './VideoChat.css'; const projectID = '7f0f3b51-017b-477f-9207-b2417cd258f1'; const VideoChat = () => { if (!localStorage.getItem('username')) return <LoginForm />; return ( <> <ChatEngine height="100vh" projectID={projectID} userName={localStorage.getItem('username')} userSecret={localStorage.getItem('password')} renderChatFeed={(chatAppProps) => <ChatFeed {...chatAppProps} />} onNewMessage={() => new Audio('https://chat-engine-assets.s3.amazonaws.com/click.mp3').play()} /> </> ); }; // infinite scroll, logout, more customizations... export default VideoChat;<file_sep>/src/Pages/Reports/Reports.jsx import { Container, Typography } from '@material-ui/core'; import React, { useEffect, useState } from 'react'; import LineDemo from '../../components/LineDemo'; import Sidebar from '../../components/Sidebar/Sidebar'; import {db} from '../../firebase' export const Reports = ({match}) => { const [reportData, setReportData] = useState([]) useEffect(() => { db.collection('machines').doc(match.params.id).get().then(snapshot => { const data = snapshot.data() setReportData(data) }) }) console.log(match) return ( <> <Sidebar match={match}/> <div className="reports"> <Typography variant="h5">{reportData.title}</Typography> <Typography variant="body2">({reportData.location})</Typography> </div> </> ); }; export const Process = ({match}) => { return ( <> <Sidebar match={match}/> <div style={{display: "flex", flexDirection: "column", justifyContent: "center"}}> <Typography gutterBottom align="center" component="h1" variant="h4">ONGOING PROCESSES</Typography> <Container xs><LineDemo/></Container> </div> </> ); };<file_sep>/src/Pages/DQConfig/DQConfig.jsx import { useEffect, useState } from "react" import { db } from "../../firebase" import { firebaseLooper } from "../../utils/tools" import DQConfigView from "./components/DQConfigView" import { DialogContent, Fab, FormHelperText, makeStyles, Paper, Select, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from "@material-ui/core"; import { Button, Dialog, Typography, TextField, DialogActions, Card } from "@material-ui/core" import DQLayout from "../../components/DQNewSidebar/DQLayout"; import { NavLink } from "react-router-dom"; import DQBrands from "../brands/DQBrands"; import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight'; import KeyboardArrowLeftIcon from '@material-ui/icons/KeyboardArrowLeft'; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'whitesmoke', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, fab: { position: 'fixed', bottom: theme.spacing(2), right: theme.spacing(2), }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 250 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); export default function DQConfigD({match}) { const classes = useStyles() const [config, setConfig] = useState([]) const [title, setTitle] = useState('') const [desc, setDesc] = useState('') const [openAdd, setOpenAdd] = useState(false) const [type, setType] = useState(0) useEffect(() => { db.collection('DQNew').doc(match.params.id).collection('content').doc('config') .collection('module').onSnapshot(snap => { const data = firebaseLooper(snap) data.sort(function(a,b){ return(a.index-b.index) }) setConfig(data) }) },[]) function handleOpenAdd(){ setOpenAdd(true) } function handleCloseAdd(){ setOpenAdd(false) } function handleSubmit(e){ e.preventDefault() const index = config.length db.collection('DQNew') .doc(match.params.id) .collection('content') .doc('config') .collection('module') .add({title, desc, index,type}) .then(() => {setTitle('') setDesc(" ") } ) } return ( <> <DQLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <Typography variant='h1' align='center' gutterBottom ><b>Equipment Configuration</b></Typography> <hr /> <div style={{display: 'flex', marginBottom: '3%', paddingRight: '3%', justifyContent: 'flex-end'}}> {/* <Button component={NavLink} to={`/DQ/${match.params.id}/General-Information`} style={{background: 'blue', color: 'white', marginLeft: '25px', marginRight: '4%'}}> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-90deg-left" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1.146 4.854a.5.5 0 0 1 0-.708l4-4a.5.5 0 1 1 .708.708L2.707 4H12.5A2.5 2.5 0 0 1 15 6.5v8a.5.5 0 0 1-1 0v-8A1.5 1.5 0 0 0 12.5 5H2.707l3.147 3.146a.5.5 0 1 1-.708.708l-4-4z"/> </svg> </Button> */} <Button style={{color: 'white', background: 'black', marginRight: '4%'}} onClick={handleOpenAdd}>Add Module</Button> {/* <Button component={NavLink} to={`/DQ/${match.params.id}/Specifications`} style={{background: 'blue', color: 'white'}}> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-90deg-right" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M14.854 4.854a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 4H3.5A2.5 2.5 0 0 0 1 6.5v8a.5.5 0 0 0 1 0v-8A1.5 1.5 0 0 1 3.5 5h9.793l-3.147 3.146a.5.5 0 0 0 .708.708l4-4z"/> </svg> </Button> */} <br /> </div> <div> <div component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}}><b className='text-lg font-bold italic'>Title</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="left"><b className='text-lg font-bold italic'>Description</b></TableCell> <TableCell style={{background: '#4C4C6D', color: 'white', font: 'bold'}} align="right"><b className='text-lg font-bold italic'>Actions</b></TableCell> </TableRow> </TableHead> { config&& config.map(data => ( <> <DQConfigView type={data.type} match={match} key={data.id} module={data}/> </> )) } </Table> </div> <div className={classes.fab}> <Fab component={NavLink} to={`/DQ/${match.params.id}/Specifications`} style={{marginRight: '20px'}} color="primary" aria-label="add"> <KeyboardArrowLeftIcon/> </Fab> <Fab component={NavLink} to={`/DQ/${match.params.id}/Design-Specs`} color="primary" aria-label="add"> <KeyboardArrowRightIcon/> </Fab> </div> <Dialog open={openAdd} fullWidth onClose={handleCloseAdd}> <form onSubmit={handleSubmit}> <Typography variant='h4' align='center' gutterBottom style={{marginTop: '15px'}}><b>Add New Modules</b></Typography> <DialogContent> <TextField error={title.length > 30} required label='Title' variant='outlined' fullWidth onChange={(e) => setTitle(e.target.value)}/> <FormHelperText style={{marginBottom: '5%'}}>Title should be {title.length}/30</FormHelperText> <TextField error={desc.length>100} required rows={5} multiline label='Description' variant='outlined' fullWidth onChange={(e) => setDesc(e.target.value)}/> <FormHelperText style={{marginBottom: '5%'}}>Description should be max {desc.length}/100</FormHelperText> <Select required onChange={(e) => setType(e.target.value)} value={type} variant='outlined' fullWidth> <option selected value={0}>2 Row (Type 0)</option> <option value={1}>SERVICES REQUIRED FROM CUSTOMER END</option> </Select> <FormHelperText className='italic'>Select Type Before Adding Module</FormHelperText> </DialogContent> <DialogActions> <Button onClick={handleCloseAdd} variant='contained' color='secondary'>Cancel</Button> <Button type="submit" style={{background:'orange', color:'white'}} >Add New</Button> </DialogActions> </form> </Dialog> <br /> <div> </div> <br /> <div> </div> <br /> </div> </Card> </div> </div> </> ) } <file_sep>/src/Pages/user_manual/ViewData.jsx import { useState } from "react" import "react-responsive-carousel/lib/styles/carousel.min.css"; // requires a loader import { Carousel } from 'react-responsive-carousel'; import { db } from "../../firebase"; import { Button } from "@material-ui/core"; function ViewData({title,desc,images,d_id}) { const [show, setShow] = useState(false) console.log(images) function handleDelete(){ db.collection('userManual').doc(d_id).delete() } return ( <div className="bg-white w-full xl:w-11/12 mt-5 px-6 py-8 xl:px-16 lg:py-16 shadow-lg"> <div className="flex w-full justify-between lg:justify-start items-center"> <h1 className="text-color font-black text-3xl lg:text-5xl lg:mr-8">{title}</h1> <button className="w-10 h-10 bg-gray-100 focus:outline-none flex items-center justify-center rounded-full" onClick={() => setShow(!show)}> {show ? ( <svg id="andicators1" xmlns="http://www.w3.org/2000/svg" width={18} height={12} viewBox="0 0 18 12" fill="none"> <path d="M9.00002 4.73399L2.40001 11.334L0.514683 9.44865L9.00002 0.963319L17.4854 9.44865L15.6 11.334L9.00002 4.73399Z" fill="#4A5568" /> </svg> ) : ( <svg id="andicators" className xmlns="http://www.w3.org/2000/svg" width={32} height={32} viewBox="0 0 32 32" fill="none"> <path d="M16 17.5626L22.6 10.9626L24.4853 12.848L16 21.3333L7.51465 12.848L9.39998 10.9626L16 17.5626Z" fill="#4A5568" /> </svg> )} </button> </div> <div className="pt-3"> <p className="text-2xl f-f-r lg:w-10/12">{desc}</p> </div> {show && ( <div> <Carousel> { images.map((data) => ( <div> <img src={data} /> </div> )) } </Carousel> </div> )} <div> <Button onClick={handleDelete}>delete</Button> </div> </div> ) } export default ViewData <file_sep>/src/Pages/IQ/IQComponents/IQHeader.jsx import { Button } from "@material-ui/core" import { useEffect, useState } from "react" import { NavLink } from "react-router-dom" import { db } from "../../../firebase" import { firebaseLooper } from "../../../utils/tools" function IQHeader({match}) { const [key, setKey] = useState('') useEffect(() =>{ db.collection('IQ') .where('key', '==', `${match.params.id}`) .onSnapshot(snap => { const data = firebaseLooper(snap) setKey(data[0].mid) }) }, []) return ( <div> <nav className="bg-white shadow dark:bg-gray-800"> <div className="container flex items-center justify-center p-6 mx-auto text-gray-600 capitalize dark:text-gray-300"> <Button component={NavLink} to={`/IQ/${match.params.id}/index`} className="text-gray-800 dark:text-gray-200 border-b-2 border-blue-500 mx-1.5 sm:mx-6 hover:text-yellow-900">Index</Button> <Button component={NavLink} to={`/IQ/${match.params.id}/scope`} className="border-b-2 border-transparent hover:text-gray-800 dark:hover:text-gray-200 hover:text-yellow-900 mx-1.5 sm:mx-6">Scope</Button> <Button component={NavLink} to={`/IQ/${match.params.id}/drawing`} className="border-b-2 border-transparent dark:hover:text-gray-200 hover:text-yellow-900 mx-1.5 sm:mx-6">Electrical Drawing</Button> <Button component={NavLink} to={`/IQ/${match.params.id}/control`} className="border-b-2 border-transparent dark:hover:text-gray-200 hover:text-yellow-900 mx-1.5 sm:mx-6">Control Panel</Button> <Button component={NavLink} to={`/IQ/${match.params.id}/software`} className="border-b-2 border-transparent hover:text-gray-800 dark:hover:text-gray-200 hover:text-yellow-900mx-1.5 sm:mx-6">Software</Button> <Button component={NavLink} to={`/machine-data/${key}/IQ`} className="border-b-2 border-transparent dark:hover:text-gray-200 hover:text-indigo-900 mx-1.5 sm:mx-6"> <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="currentColor" class="bi bi-arrow-bar-left" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M12.5 15a.5.5 0 0 1-.5-.5v-13a.5.5 0 0 1 1 0v13a.5.5 0 0 1-.5.5zM10 8a.5.5 0 0 1-.5.5H3.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L3.707 7.5H9.5a.5.5 0 0 1 .5.5z"/> </svg> </Button> </div> </nav> </div> ) } export default IQHeader <file_sep>/src/Pages/MiddlePage/LogsList.jsx import React, { useEffect, useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import { Button, Card, Container, Dialog, Grid, InputLabel, Select, TablePagination, TextField, Typography } from '@material-ui/core'; import ContentDashboardLayout from '../../components/ContentSidebar/ContentDashboardLayout'; import { db } from '../../firebase'; import { firebaseLooper } from '../../utils/tools'; const useStyles = makeStyles((theme) => ({ table: { minWidth: 650, }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); export default function CallLogs() { const classes = useStyles(); const [title, setTitle] = useState('') const [open, setOpen] = useState(false) const [batch, setBatch] = useState([]) const [machines, setMachines] = useState([]) useEffect(() => { db.collection('machineData').onSnapshot(doc => { const data = firebaseLooper(doc) setMachines(data) console.log(data) }) db.collection('CallLogData').onSnapshot(doc => { const data = firebaseLooper(doc) setBatch(data) console.log(data) }) }, []) const handleOpen = () => { setOpen(true) } const handleClose = () => { setOpen(false) } const handleChange = (e) => { const mid = e.target.value db.collection('CallLogData').where('machine_id', '==', `${mid}`).onSnapshot(doc => { const data = firebaseLooper(doc) setBatch(data) console.log(data) }) } return ( <div style={{boxShadow: '0px 2px 6px #0000000A', background: '#FFFFFF 0% 0% no-repeat padding-box'}}> <div > <div > <Card className={classes.content}> <br/> <Typography style={{marginLeft:'24px' ,color:'#43425D', opacity: 0.68}} variant='h2' align='left' gutterBottom><b style={{marginLeft:'24px',color:'#43425D'}}>Call Logs</b></Typography> <div style={{display: 'flex', justifyContent: 'space-evenly'}}> <select style={{width:"280px", border: '2px solid whitesmoke' }} onChange={handleChange} > <option value="" disabled selected hidden>Select Machine</option> { machines.map(data => ( <option value={data.id}>{data.title}</option> )) } </select> <div className="relative"> <input style={{width: '388px', border: '2px solid whitesmoke'}} onChange={(e) => setTitle(e.target.value)} type="text" className="h-14 w-96 pr-8 pl-5 rounded z-0 focus:shadow focus:outline-none" placeholder="Search anything..."/> <div className="absolute top-4 right-3"> <i className="fa fa-search text-gray-400 z-20 hover:text-gray-500"></i> </div> </div> </div> <TableContainer style={{padding: '15px'}} > <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell style={{backgroundColor: '#43425D', color: 'white'}}><b>Manual</b></TableCell> <TableCell style={{backgroundColor: '#43425D', color: 'white'}} align="left"><b>User</b></TableCell> <TableCell style={{backgroundColor: '#43425D', color: 'white'}} align="left"><b>Step</b></TableCell> <TableCell style={{backgroundColor: '#43425D', color: 'white'}} align="right"><b>Date & Time</b></TableCell> </TableRow> </TableHead> <TableBody> {batch. filter((data) => { if(title === ""){ return data } else if (data.manual_name.toLowerCase().includes(title.toLocaleLowerCase())){ return data }else if (data.user_id.toLowerCase().includes(title.toLocaleLowerCase())){ return data }else if (data.step.toLowerCase().includes(title.toLocaleLowerCase())){ return data } }) .slice(0,7).map((row) => ( <TableRow style={{font: 'normal normal normal 16px/20px Roboto'}} key={row.id}> <TableCell style={{backgroundColor: 'whitesmoke', color: '#4D4F5C'}} component="th" scope="row"> {row.manual_name} </TableCell> <TableCell style={{color: '#4D4F5C'}} align="left">{row.user_id}</TableCell> <TableCell style={{color: '#4D4F5C'}} align="left">{row.step}</TableCell> <TableCell style={{color: '#4D4F5C'}}align="right">{row.time.toDate().toString().substring(0,15)}</TableCell> </TableRow> ))} </TableBody> </Table> <div style={{display: 'flex', justifyContent: 'flex-end'}}> </div> <div style={{width: '100%'}}> </div> </TableContainer> </Card> </div> </div> </div> ) } <file_sep>/src/Pages/DQNew/DQComponents/AddContent.jsx import { Chip, FormHelperText } from '@material-ui/core'; import { Button, Select, Typography } from '@material-ui/core'; import { Alert } from '@material-ui/lab'; import React, { useState } from 'react' import { db } from '../../../firebase'; const AddContent = ({match}) => { const [title, setTitle] = useState('') const [desc, setDesc] = useState('') const [ message, setMessage] = useState('') const [type, setType] = useState(0) const [key, setMid] = useState(`${match.params.id}`) const [specs, setSpecs] = useState('') const [ specifications, setSpecifications] = useState([]) function handleSubmit(){ db.collection('DQNew').doc(match.params.id).collection('content').add({title,desc,key, specifications, type}).then(() => { setMessage('Added Successfully !') }) } function handleSpecs(){ specifications.push(specs) setSpecs('') console.log(specifications) } return ( <div> <div class="container items-center px-4 py-12 lg:px-15"> <form class="flex flex-col w-full p-10 px-8 pt-6 mx-auto my-6 mb-4 transition duration-500 ease-in-out transform bg-white border rounded-lg lg:w-1/2 "> <Typography variant='h3' align='center'><b>Add New report</b></Typography> { message &&<Typography variant='h6' align='center'><b style={{color: 'blue'}}>{message}</b></Typography> } <div class="relative pt-4"> <label for="name" class="text-base leading-7 text-gray-500">Name</label> <input onChange={(e) => setTitle(e.target.value)} type="text" placeholder="Enter Name" class="w-full px-4 py-2 mt-2 mr-4 text-base text-black transition duration-500 ease-in-out transform rounded-lg bg-blueGray-100 focus:border-blueGray-500 focus:bg-white focus:outline-none focus:shadow-outline focus:ring-2 ring-offset-current ring-offset-2"/> </div> <div class="flex flex-wrap mb-6 -mx-3"> <div class="w-full px-3"> <label class="text-base leading-7 text-gray-500" for="description"> Description </label> <textarea onChange={(e) => setDesc(e.target.value)} class="w-full h-32 px-4 py-2 text-base text-gray-500 transition duration-500 ease-in-out transform bg-white border rounded-lg focus:border-blue-500 focus:outline-none focus:shadow-outline focus:ring-2 ring-offset-current ring-offset-2 apearance-none autoexpand" id="description" type="text" name="description" placeholder="Describe your material...." required=""></textarea> </div> </div> <br /> <Alert severity='info'>To add multiple specs , Click "Add specs" after writing it </Alert> <div class="relative pt-4"> <label for="name" class="text-base leading-7 text-gray-500">Enter design specs here ..</label> <input disabled={type!==3} onChange={(e) => setSpecs(e.target.value)} type="text" placeholder="Specs" class="w-full px-4 py-2 mt-2 mr-4 text-base text-black transition duration-500 ease-in-out transform rounded-lg bg-blueGray-100 focus:border-blueGray-500 focus:bg-white focus:outline-none focus:shadow-outline focus:ring-2 ring-offset-current ring-offset-2"/> </div> <FormHelperText>Enable by selectiong design sepcs the selector </FormHelperText> <br /> <Button onClick={handleSpecs} disabled={type!==3 || specs===""} fullWidth variant='contained' color='primary'>Add Specs</Button> <br /> <Select value={type} onChange={(e) => setType(e.target.value)} variant='outlined' fullWidth> <option value={0}>Manual Text</option> <option value={3}>Design Specs</option> <option value={4}>Configuration</option> </Select> <div class="flex items-center w-full pt-4"> <Button onClick={handleSubmit} class="w-full py-3 text-base text-white transition duration-500 ease-in-out transform bg-yellow-900 border-yellow-900 rounded-md focus:shadow-outline focus:outline-none focus:ring-2 ring-offset-current ring-offset-2 hover:bg-yellow-800 "> Add New </Button> </div> { specifications && specifications.map(data => ( <Chip label={data} /> )) } </form> </div> </div> ) } export default AddContent <file_sep>/src/components/VideoCall/RenderVc.jsx import { useEffect, useState } from 'react'; import '@opentok/client'; // import './index.css'; // import './polyfills'; // import { // API_KEY, // SESSION_ID, // TOKEN // } from './config'; import VideoCall from './VideoCall'; import { Button, Card, Container, Dialog, DialogActions, DialogContent, DialogTitle, Grid, InputLabel, Select, TextField, Toolbar } from '@material-ui/core'; import { db } from '../../firebase'; import { useAuth } from '../context/AuthContext'; import { firebaseLooper } from '../../utils/tools'; import { useVideoStorage } from '../../utils/useVideoStorage'; import OpenTokPage from '../../Pages/VideoCallPage/OpenTokPage'; import config from '../../Pages/VideoCallPage/config'; import { SettingsBackupRestoreSharp } from '@material-ui/icons'; import ListUsers from './ListUsers'; import screenfull from 'screenfull'; import Chatbox from '../../Pages/VideoCallPage/components/Chatbox'; import React from 'react'; import clsx from 'clsx'; import { makeStyles, useTheme } from '@material-ui/core/styles'; import Drawer from '@material-ui/core/Drawer'; import AppBar from '@material-ui/core/AppBar'; import CssBaseline from '@material-ui/core/CssBaseline'; import List from '@material-ui/core/List'; import Typography from '@material-ui/core/Typography'; import Divider from '@material-ui/core/Divider'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; import ChevronRightIcon from '@material-ui/icons/ChevronRight'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemText from '@material-ui/core/ListItemText'; import InboxIcon from '@material-ui/icons/MoveToInbox'; import MailIcon from '@material-ui/icons/Mail'; import AttachFileIcon from '@material-ui/icons/AttachFile'; import QuestionAnswerIcon from '@material-ui/icons/QuestionAnswer'; import OpenInBrowserIcon from '@material-ui/icons/OpenInBrowser'; import { API_KEY, SESSION_ID, TOKEN } from './config'; import Whiteboard from '../Whiteboard/Whiteboard'; import InviteForm from '../InviteForm/InviteForm'; import AddIcon from '@material-ui/icons/Add'; import TestVideo from '../../VideoCallModel/TestVideo'; import EntryPage from '../../VideoCallModel/EntryPage'; import Page from '../Page'; const drawerWidth = 550; const useStyles = makeStyles((theme) => ({ root: { background: 'black', display: 'flex', }, appBar: { transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), }, appBarShift: { width: `calc(100% - ${drawerWidth}px)`, transition: theme.transitions.create(['margin', 'width'], { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), marginRight: drawerWidth, }, title: { flexGrow: 1, }, hide: { display: 'none', }, drawer: { width: drawerWidth, flexShrink: 0, }, drawerPaper: { width: drawerWidth, }, drawerHeader: { display: 'flex', alignItems: 'center', padding: theme.spacing(0, 1), // necessary for content to be below app bar ...theme.mixins.toolbar, justifyContent: 'flex-start', }, content: { flexGrow: 1, padding: theme.spacing(3), transition: theme.transitions.create('margin', { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), marginRight: -drawerWidth, }, contentShift: { transition: theme.transitions.create('margin', { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), marginRight: 0, }, })); export default function RenderVc({config}) { const classes = useStyles(); const theme = useTheme(); const [openDrawer, setOpenDrawer] = React.useState(false); const [file, setFile] = useState(null); const [error, setError] = useState("") const [call_id, setCallId] = useState('') const [currentCall, setCurrentCall] = useState([]) const [whiteboardOpen, setWhiteboardOpen] = useState(false) const [format, setFormat] = useState('') const [configData, setConfigData] = useState([]) const [disabled, setDisabled] = useState(true) const [open, setOpen] = useState(false) const [openInvite, setOpenInvite] = useState(false) const [token, setToken] = useState(`${config.TOKEN}`) const [session_id, setSessionId] = useState(`${config.SESSION_ID}`) const types = ["image/png", "image/jpeg", "image/jpg"]; const videoTypes = ["video/mp4", "video/mkv", "video/mov"]; const audioTypes = ["audio/mp3", "audio/mpeg"] const [message, setMessage] = useState('') const {currentUser} = useAuth() useEffect(() => { db.collection('OpenTokConfig').get().then(snapshot => { const data = firebaseLooper(snapshot) console.log(data[0]) setConfigData(data[0]) }) db.collection('CallCurrent').onSnapshot(snapshot => { const callData = firebaseLooper(snapshot) callData.sort(function(a,b){ return(a.index-b.index) }) setCurrentCall(callData[callData.length -1]) setCallId(callData[callData.length-1].call_id) }) }, []) const handleChange = (e) => { let selectedFile = e.target.files[0]; if (selectedFile) { if(format === 'image'){ if (types.includes(selectedFile.type)) { setError(null); setFile(selectedFile); setDisabled(false) } else { setFile(null); setError("Please select an image file (png or jpg)"); } }else if(format === 'video'){ if (videoTypes.includes(selectedFile.type)) { setError(null); setFile(selectedFile); setDisabled(false) } else { setFile(null); setError("Please select a video file (mp4 or mkv)"); } }else if(format === 'audio'){ if (audioTypes.includes(selectedFile.type)) { setError(null); setFile(selectedFile); setDisabled(false) } else { setFile(null); setError("Please select an audio file (mp3 )"); } } } } let { progress, url } = useVideoStorage(file); const handleSubmit = () => { db.collection('CallMedia').add({call_id,url, format}).then(() => { setFile(null) setDisabled(true) setMessage('The File has been sent, If you wish to send another file repeat the same') }) } const handleSession = () => { setSessionId(configData.session_id) setToken(configData.token) } const handleClickOpen = () => { setOpen(true) } const handleClose = () => { setOpen(false) } const openInviteBox = () => { setOpenInvite(true) } const closeInvite = () => { setOpenInvite(false) } const handleWhiteboardOpen = () => { setWhiteboardOpen(true) } const handleWhiteboardClose = () => { setWhiteboardOpen(false) } const handleDrawerOpen = () => { setOpenDrawer(true); }; const handleDrawerClose = () => { setOpenDrawer(false); }; return ( <Page title='Video Call | LyoIms'> <div className={classes.root}> <CssBaseline /> <AppBar position="absolute" style={{top: 64, background: 'black'}} className={clsx(classes.appBar, { [classes.appBarShift]: openDrawer, })} > <Toolbar> <Typography variant="h6" noWrap className={classes.title}> </Typography> <IconButton href="/"> <Button style={{background: 'red', color: 'white'}}>Disconnect</Button> </IconButton> <IconButton target="_blank" href="/machine-data"> <Button style={{background: 'blue', color: 'white'}}>Machines</Button> </IconButton> <IconButton style={{color: 'orange'}} onClick={openInviteBox}> <AddIcon/> </IconButton> <IconButton target="_blank" href='/whiteboard' style={{color: 'orange'}} > <OpenInBrowserIcon/> </IconButton> <IconButton style={{color: 'orange'}} onClick={handleClickOpen}> <AttachFileIcon/> </IconButton> <IconButton style={{color: 'orange'}} aria-label="open drawer" edge="end" onClick={handleDrawerOpen} className={clsx(openDrawer && classes.hide)} > <QuestionAnswerIcon/> </IconButton> </Toolbar> </AppBar> <main className={clsx(classes.content, { [classes.contentShift]: openDrawer, })} > <div className={classes.drawerHeader} /> <TestVideo config={config}/> </main> <Drawer className={classes.drawer} variant="persistent" anchor="right" open={openDrawer} classes={{ paper: classes.drawerPaper, }} > <div className={classes.drawerHeader}> <IconButton onClick={handleDrawerClose}> {theme.direction === 'rtl' ? <ChevronLeftIcon /> : <ChevronRightIcon />} </IconButton> </div> {currentUser ? <Chatbox call_id={call_id}/> : <b>You need to <a href='/login'>Login</a> to enable chat</b>} </Drawer> <Dialog fullWidth open={open} onClose={handleClose}> <Toolbar> <Button onClick={handleClose}>Close</Button> </Toolbar> <h2 className="text-2xl font-bold text-gray-800 dark:text-white md:text-3xl">Share Media </h2> <select style={{ border: '2px solid whitesmoke', margin: '2%'}} value={format} required fullWidth InputLabelProps={{ shrink: true, }} onChange={(e) => setFormat(e.target.value)} > <option value='' selected hidden>Select a Format</option> <option value='image'>Image</option> <option value='video'>Video</option> <option value='audio'>Audio</option> </select> <label className="w-full flex flex-col items-center px-4 py-6 bg-white text-black rounded-lg shadow-lg tracking-wide uppercase border border-blue cursor-pointer hover:bg-black hover:text-black"> <svg className="w-8 h-8" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> <path d="M16.88 9.1A4 4 0 0 1 16 17H5a5 5 0 0 1-1-9.9V7a3 3 0 0 1 4.52-2.59A4.98 4.98 0 0 1 17 8c0 .38-.04.74-.12 1.1zM11 11h3l-4-4-4 4h3v3h2v-3z" /> </svg> <span className="mt-2 text-base leading-normal">Select a file</span> <input onChange={handleChange} type='file' class="hidden" /> </label> {file && <p>{progress}% uploaded</p>} <p className="mt-2 text-gray-600 dark:text-gray-400"></p> <button onClick={handleSubmit} style={{backgroundColor: 'orange', marginLeft: '25%'}} disabled={disabled} href="#" className="px-5 py-2 w-50 mb-10 font-semibold text-gray-100 transition-colors duration-200 transform bg-gray-900 rounded-md hover:bg-gray-700">Send Now</button> {message && <b style={{color: 'green'}}>{message}</b>} </Dialog> <Dialog fullScreen open={whiteboardOpen} onClose={handleWhiteboardClose}> <Toolbar> <Button onClick={handleWhiteboardClose}>Close</Button> </Toolbar> <Whiteboard/> </Dialog> <Dialog open={openInvite} onClose={closeInvite} fullWidth> <Toolbar> <Button onClick={closeInvite}>Close</Button> </Toolbar> <InviteForm/> </Dialog> </div> </Page> ); }<file_sep>/src/Pages/VideoCallPage/components/Chatbox.jsx import { Button, Container, TextField } from '@material-ui/core' import React, { useEffect, useRef, useState } from 'react' import { useAuth } from '../../../components/context/AuthContext' import { db } from '../../../firebase' import { firebaseLooper } from '../../../utils/tools' import './Chatbox.css' const Chatbox = ({call_id}) => { const [chat, setChat] = useState([]) const {currentUser} = useAuth() const [userData, setUserData] = useState([]) const [message, setMessage] = useState('') // const [call_id, setCallId] = useState('') const url = userData.url const username = userData.username const email = userData.email const index = chat.length const messageEl = useRef(null); useEffect(() => { if (messageEl) { messageEl.current.addEventListener('DOMNodeInserted', event => { const { currentTarget: target } = event; target.scroll({ top: target.scrollHeight, behavior: 'smooth' }); }); } db.collection('users').where('email','==', `${currentUser.email}`).onSnapshot(doc => { const data = firebaseLooper(doc) setUserData(data[0]) }) db.collection('CallMessages').onSnapshot(doc => { const data = firebaseLooper(doc) data.sort(function(a,b){ return(a.index-b.index) }) setChat(data) console.log(data) }) }, []) const getReply = (username,email,message,url,callId) => { if(callId === call_id){ if(email != currentUser.email){ return( <div class="chat-message"> <div class="flex m-2 items-end"> <img class="w-6 h-6 rounded-full order-2" src={url}/> <div class="flex flex-col space-y-2 text-xs max-w-xs mx-2 order-2 items-start"> <div><span class="px-4 py-2 rounded-lg inline-block rounded-bl-none bg-gray-300 text-gray-600">{message}</span></div> </div> </div> </div> ) }else if (email === currentUser.email){ return( <div class="chat-message"> <div class="flex m-2 items-end justify-end"> <div class="flex flex-col space-y-2 text-xs max-w-xs mx-2 order-1 items-end"> <div><span class="px-4 py-2 rounded-lg inline-block rounded-br-none bg-yellow-900 text-white ">{message}</span></div> </div> <img src={url} alt="My profile" class="w-6 h-6 rounded-full order-2"/> </div> </div> ) } } } function handleKeyDown(e) { if (e.key === 'Enter') { handleSubmit(e) } } const handleSubmit = (e) => { e.preventDefault() if (message.length === 0 || message.trim().length === 0) return; const messageData = {url,username,email,message,index} db.collection('CallMessages').add({url,username,email,message,index,call_id}) setMessage('') } return ( <Container style={{backgroundColor: 'white', border: '2px solid gray',height: '100vh'}}> <div className="chat"> <div className="chat__header"> <h1>ChatBox</h1> </div> <div className="chat__body" ref={messageEl}> {chat.filter((message) =>{ if(message.call_id == call_id){ return message } } ).map((message) => ( <p className={`chat__message ${ message.email === currentUser.email && "chat__receiver" }`} > <div class="flex m-2 items-end justify-end"> <div class="flex flex-col space-y-2 text-xs max-w-xs mx-2 order-1 items-end"> <div className='mx-auto '> <span className="chat__name">{message.username}</span> <span className="chat__messageText">{message.message}</span> </div> </div> <img src={message.url} alt="My profile" class="w-6 h-6 rounded-full order-2"/> </div> </p> ))} </div> <div className="chat__footer" > <TextField fullWidth multiLine variant='outlined' type="text" value={message} id="chatInput" onKeyPress={handleKeyDown} onChange={(e) => setMessage(e.target.value)} placeholder="Type a message" /> <Button type="submit" onClick={handleSubmit}> Send </Button> </div> </div> </Container> ) } export default Chatbox <file_sep>/src/Pages/MiddlePage/JobGraph.jsx import { Card, Container, FormControl, InputLabel, MenuItem, Select, Typography } from '@material-ui/core'; import { Alert } from '@material-ui/lab'; import React, { useEffect, useState } from 'react' import { Doughnut, Pie } from 'react-chartjs-2'; import { db } from '../../firebase'; import { firebaseLooper } from '../../utils/tools'; import LinearIndeterminate from './LinearInderminate'; const JobGraph = () => { const [pending, setPending] = useState([]) const [machines, setMachines] = useState([]) const [completed, setCompleted] = useState([]) useEffect(() => { db.collection('machineData').onSnapshot(doc => { const data = firebaseLooper(doc) setMachines(data) }) db.collection('jobData').where('status', '==', false).onSnapshot(doc => { const data = firebaseLooper(doc) setPending(data) }) db.collection('jobData').where('status', '==', true).onSnapshot(doc => { const data = firebaseLooper(doc) setCompleted(data) }) },[]) const handleChange = (e) => { let mid = e.target.value db.collection('jobData').where('status', '==', false).where('mid', '==', `${mid}`).onSnapshot(doc => { const data = firebaseLooper(doc) setPending(data) }) db.collection('jobData').where('status', '==', true).where('mid', '==', `${mid}`).onSnapshot(doc => { const data = firebaseLooper(doc) setCompleted(data) }) } const data = { labels: [ 'Completed', 'Pending', ], datasets: [ { fill: false, lineTension: 0.1, backgroundColor: [ '#10B90A', '#FF9A40' ], hoverOffset: 4, borderColor: 'white', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'white', pointBackgroundColor: 'white', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: '#ff7a00', pointHoverBorderColor: '#7868e6', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [completed.length, pending.length] }, ] } return ( <div style={{boxShadow: '0px 2px 6px #0000000A'}} className='bg-grey-50'> <Card > <br /> <Typography style={{ color:'#43425D', opacity: 0.68}} variant='h2' align='center' gutterBottom><b style={{color:'#43425D'}}>Jobs Data</b></Typography> <div style={{display: 'flex', justifyContent: 'center'}}> <FormControl variant='outlined' style={{width: '70%'}}> <InputLabel>Select Machine</InputLabel> <Select label="Select Machine" onChange={handleChange} > { machines.map(data => ( <MenuItem value={data.id}>{data.title}</MenuItem> // <Button style={{color: 'orangered'}} href={`/machine-data/Job/${data.id}/Job`}><LaunchIcon/></Button> )) } </Select> </FormControl> </div> <Doughnut data={data}/> <br/> <Alert severity='warning'>Pending Jobs</Alert> <br/> <Alert severity='success'>Completed Jobs</Alert> <br/> <Alert severity='info'>Change Machines for individual data</Alert> </Card> </div> ) } export default JobGraph <file_sep>/src/Pages/IQ/IQPages.jsx/IQPanelPage.jsx import { Dialog, Paper, TableCell, TableContainer, TableHead, TableRow, Typography,Toolbar, DialogContent, DialogActions, Button, TextField } from "@material-ui/core"; import { useEffect } from "react"; import { useState } from "react"; import { Table } from "react-bootstrap"; import { db } from "../../../firebase"; import { firebaseLooper } from "../../../utils/tools"; import ControlView from "../IQComponents/ControlView"; import DrawView from "../IQComponents/DrawView"; import IQConfigView from "../IQComponents/IQConfigView"; import IQHeader from "../IQComponents/IQHeader"; import PanelView from "../IQComponents/PanelView"; function IQPanelPage({match, tid}) { const [contents, setContents] = useState([]) const [open, setOpen] = useState(false) const [title, setTitle] = useState('') const [desc, setDesc] = useState('') const [make, setMake] = useState('') const [tag_no, setTag] = useState('') const [type, setType] = useState('') const [serial_no, setSerial] = useState('') const [dno, setDno] = useState('') useEffect(() => { db.collection('IQ').doc(match.params.id) .collection('content').doc('control') .collection('panels') .where('tid', '==', `${tid}`) .onSnapshot(snapshot => { const data = firebaseLooper(snapshot) data.sort(function(a,b){ return (a.index - b.index) }) setContents(data) }) }, []) function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleSubmit(){ const index = contents.length db.collection('IQ').doc(match.params.id) .collection('content').doc('control') .collection('panels').add({title,desc,index,make,type,serial_no,tag_no,tid}) } return ( <div> <Toolbar style={{display: 'flex', justifyContent: 'flex-end'}}> <Button onClick={handleOpen} style={{background: 'orange', color: 'white'}}>Add Items</Button> </Toolbar> <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell><b className='text-lg font-bold italic'>Title</b></TableCell> <TableCell align="left"><b className='text-lg font-bold italic'>Tag No.</b></TableCell> <TableCell align="left"><b className='text-lg font-bold italic'>Description</b></TableCell> <TableCell align="left"><b className='text-lg font-bold italic'>Model/Serial No.</b></TableCell> <TableCell align="left"><b className='text-lg font-bold italic'>Make</b></TableCell> <TableCell align="left"><b className='text-lg font-bold italic'>Type</b></TableCell> <TableCell align="right"><b className='text-lg font-bold italic'>Actions</b></TableCell> </TableRow> </TableHead> { contents.map(module => ( <> <PanelView module={module} match={match} key={module.id}/> </> )) } </Table> </TableContainer> <Dialog open={open} onClose={handleClose} fullWidth> <Typography variant='h3' align='center' gutterBottom><b>Add new items</b></Typography> <DialogContent> <TextField style={{marginBottom: '3%'}} variant='outlined' label='Title' fullWidth onChange={(e) => setTitle(e.target.value)}/> <TextField style={{marginBottom: '3%'}} variant='outlined' label='Tag no.' fullWidth onChange={(e) => setTag(e.target.value)}/> <TextField style={{marginBottom: '3%'}} variant='outlined' label='Model/Serial No.' fullWidth onChange={(e) => setSerial(e.target.value)}/> <TextField style={{marginBottom: '3%'}} variant='outlined' label='Type/Rating' fullWidth onChange={(e) => setType(e.target.value)}/> <TextField style={{marginBottom: '3%'}} variant='outlined' label='Make/Vendor' fullWidth onChange={(e) => setMake(e.target.value)}/> <TextField multiLine rows={7} variant='outlined' label='Description' fullWidth onChange={(e) => setDesc(e.target.value)}/> </DialogContent> <DialogActions> <Button color='secondary' onClick={handleClose} variant='contained'>Cancel</Button> <Button disabled={title === '' || desc===''} onClick={handleSubmit} style={{background: 'orange', color: 'white'}}>Add New</Button> </DialogActions> </Dialog> </div> ) } export default IQPanelPage <file_sep>/src/components/Whiteboard/Whiteboard.jsx import { Button, Typography } from '@material-ui/core'; import React from 'react' import { useState } from 'react'; import {SketchField, Tools} from 'react-sketch2'; import { useVideoStorage } from '../../utils/useVideoStorage'; import Page from '../Page'; const Whiteboard = () => { const [selectedTool, setSelectedTool] = useState(Tools.Pencil) const [lineColor, setLineColor] = useState('black') const [file, setFile] = useState(null) const [lineWidth, setLineWidth] = useState(3) const [imageUrl, setImageUrl] = useState(``) const [steps, setSteps] = useState(15) const [disabled, setDisabled] = useState(true) const types = ["image/png", "image/jpeg", "image/jpg"]; const [error, setError] = useState('') const handleErase = () => { setLineColor('white') setLineWidth(10) } const handleChange = (e) => { let selectedFile = e.target.files[0]; if (selectedFile) { if (types.includes(selectedFile.type)) { setError(null); setFile(selectedFile); setDisabled(false) } else { setFile(null); setError("Please select an image file (png or jpg)"); } } } let { progress, url } = useVideoStorage(file); return ( <Page title='Whiteboard App | LyoIms'> <div style={{display: 'flex', width:'100%', height: '100%'}}> <Typography variant='h4' align='center'>Whiteboard</Typography> { url? <div style={{width: '100%',height: '100vh', backgroundImage: `url("${url}")`, backgroundSize: 'cover', resize: 'both', overflow: 'scroll'}}> <SketchField width='100%' height='100%' tool={selectedTool} lineColor={lineColor} lineWidth={3} undoSteps={steps} /> </div> : <div style={{width: '100%', height: '100vh'}}> <SketchField width='100%' height='100vh' tool={selectedTool} lineColor={lineColor} lineWidth={3} undoSteps={steps} /> </div> } <div> <select onChange={(e) => {setSelectedTool(e.target.value); setLineColor('black'); setLineWidth(3)}}> <option value={Tools.Pencil}>Pen</option> <option value={Tools.Pan}>Pan</option> <option value={Tools.Line}>Line</option> <option value={Tools.Rectangle}>Rectangle</option> </select> <br /> <br /> <label className="w-full flex flex-col items-center px-4 py-6 bg-white text-black rounded-lg shadow-lg tracking-wide uppercase border border-blue cursor-pointer hover:bg-black hover:text-black"> <svg className="w-8 h-8" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> <path d="M16.88 9.1A4 4 0 0 1 16 17H5a5 5 0 0 1-1-9.9V7a3 3 0 0 1 4.52-2.59A4.98 4.98 0 0 1 17 8c0 .38-.04.74-.12 1.1zM11 11h3l-4-4-4 4h3v3h2v-3z" /> </svg> <span className="mt-2 text-base leading-normal">Select a file</span> <input onChange={handleChange} type='file' class="hidden" /> </label> { url? <b>photo exists</b> : <b>No image selected</b> } </div> </div> </Page> ) } export default Whiteboard <file_sep>/src/Demo/DashboardSidebar.jsx import { useEffect, useState } from 'react'; import { Link as RouterLink, NavLink, Redirect, useHistory, useLocation } from 'react-router-dom'; import PropTypes from 'prop-types'; import { Avatar, Box, Button, Divider, Drawer, Hidden, IconButton, List, ListItem, Typography } from '@material-ui/core'; import { AlertCircle as AlertCircleIcon, BarChart as BarChartIcon, Lock as LockIcon, Settings as SettingsIcon, ShoppingBag as ShoppingBagIcon, User as UserIcon, UserPlus as UserPlusIcon, Users as UsersIcon, PhoneCall as PhoneIcon, Video as VideoIcon, LogOut as LogOutIcon, Book as Book } from 'react-feather'; import VideoCallIcon from '@material-ui/icons/VideoCall' import NavItem from './NavItem'; import { useAuth } from '../components/context/AuthContext'; import { db } from '../firebase'; import { firebaseLooper } from '../utils/tools'; import ListAltOutlinedIcon from '@material-ui/icons/ListAltOutlined'; import DashboardIcon from '@material-ui/icons/Dashboard'; const items = [ { href: '/', icon: DashboardIcon, title: 'Dashboard' }, { href: '/machine-data', icon: ShoppingBagIcon, title: 'Machines' }, { href: '/video-call', icon: VideoIcon, title: 'Video Call' }, { href: '/file-manager', icon: Book, title: 'Files' }, ]; const itemSecond = [ { href: '/users', icon: UsersIcon, title: 'Users' }, { href: '/account', icon: UserIcon, title: 'Account' }, { href: '/settings', icon: SettingsIcon, title: 'Settings' }, { href: '/user-manual', icon: ListAltOutlinedIcon, title: 'User Manual' } ] const DashboardSidebar = ({ onMobileClose, openMobile }) => { const location = useLocation(); const {currentUser, logout} = useAuth() const [userData, setUserData] = useState([]) const [navbar, setNavbar] = useState([]) const [error, setError] = useState('') const history = useHistory() async function handleLogout() { setError("") try { await logout() history.push("/login") } catch { setError("Failed to log out") } } useEffect(() => { db.collection('company').doc('navbar').onSnapshot(snapshot => { const data = snapshot.data() setNavbar(data) }) if (openMobile && onMobileClose) { onMobileClose(); } if(currentUser){ db.collection('users').where('email', '==', `${currentUser.email}`).onSnapshot(doc => { const data = firebaseLooper(doc) setUserData(data[0]) }) } else { <Redirect to='/login'/> } }, [location.pathname]); const content = ( <Box style={{ display: 'flex', flexDirection: 'column', height: '100%' }} > <a style={{textDecoration: 'none', color:'white', backgroundColor: 'black'}} className="flex items-center w-full px-3 mt-3" href="#"> <img alt="Logo" width="50px" src={navbar.url} /> <span className="ml-2 text-sm font-bold uppercase ">{navbar.name}</span> </a> <Divider /> <Box m={2} > <List className="flex flex-col items-center w-full mt-3 border-t border-gray-700"> <> {/* <Button component={NavLink} style={{textDecoration: 'none', color:'orange'}} className="flex items-center w-full h-12 px-3 mt-2 text-gray-200 bg-black rounded" to="/"> <svg className="w-6 h-6 stroke-current" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" /> </svg> <span className="ml-2 text-sm font-medium">DASHBOARD</span> </Button> */} <div className="flex items-center w-full h-12 mt-2 rounded"> {/* <ListItem disableGutters style={{ display: 'flex', }} > <Button component={RouterLink} style={{ background: 'orange', color: 'white', fontWeight: 'medium', justifyContent: 'flex-start', letterSpacing: 0, py: 1.25, textTransform: 'none', width: '100%', }} to='/' > <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-bar-chart-fill" viewBox="0 0 16 16"> <path d="M1 11a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1v-3zm5-4a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v7a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V7zm5-5a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1h-2a1 1 0 0 1-1-1V2z"/> </svg> <span> <b className='ml-2'>Dashboard</b> </span> </Button> </ListItem> */} </div> </> {items.map((item) => ( <div key={item.title} className="flex items-center w-full h-12 mt-2 "> <NavItem href={`${item.href}`} key={item.title} title={item.title} icon={item.icon} /> </div> ))} <div className='flex flex-col items-center w-full mt-2 border-t border-gray-700'> {itemSecond.map((item) => ( <div key={item.title} className="flex items-center w-full h-12 mt-2 "> <NavItem href={`${item.href}`} key={item.title} title={item.title} icon={item.icon} /> </div> ))} </div> </List> </Box> <Box style={{ flexGrow: 1 }} /> {/* <Box m={2} p={2} style={{ backgroundColor: 'whitesmoke', }} > <Typography align="center" gutterBottom variant="h4" > Want to Logout? </Typography> </Box> */} <Box pt= {2} style={{ display: 'flex', justifyContent: 'center', paddingBottom: '4.2rem' }} > <div className="flex items-center w-full p-3 mt-2 "> <ListItem disableGutters style={{ display: 'flex', color: 'white', fontWeight: 'medium', justifyContent: 'flex-start', background: 'orange', borderRadius: "0.25rem" }} > <Button fullWidth style={{backgroundColor: "orange", color: "white", fontWeight: 'medium', justifyContent: 'flex-start', letterSpacing: 0, py: 1.25, display: 'flex', textTransform: 'none', width: '100%',}} onClick={handleLogout} > <LogOutIcon style={{color: 'white', marginLeft: '5px'}}/> <b className="ml-2">Log Out</b> </Button> </ListItem> </div> </Box> </Box> ); return ( <> <Hidden lgUp> <Drawer anchor="left" onClose={onMobileClose} open={openMobile} variant="temporary" PaperProps={{ style: { width:250, backgroundColor: '#43425D' } }} > {content} </Drawer> </Hidden> <Hidden mdDown> <Drawer anchor="left" variant="persistent" open PaperProps={{ style: { width: 250, backgroundColor: '#43425D' } }} > {content} </Drawer> </Hidden> </> ); }; DashboardSidebar.propTypes = { onMobileClose: PropTypes.func, openMobile: PropTypes.bool }; DashboardSidebar.defaultProps = { onMobileClose: () => { }, openMobile: false }; export default DashboardSidebar;<file_sep>/src/Pages/DQNew/DQComponents/DQContentView.jsx import { Button, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from "@material-ui/core"; import { Card, makeStyles } from "@material-ui/core" import Paper from '@material-ui/core/Paper'; import { useEffect } from "react"; import { db } from "../../../firebase"; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'white', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', background:'linear-gradient(#f3f3f3, #e7e7e7)' }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, table: { minWidth: 650, }, })); function DQContentView({content}) { const classes = useStyles() return ( <> <div > <div > <Card > <section class="text-blueGray-700 "> <div class="container flex flex-col items-center px-5 py-8 mx-auto"> <div class="flex flex-col w-full mb-12 text-left "> <div class="w-full mx-auto lg:w-1/2"> <div style={{display: 'flex' , justifyContent: 'space-evenly'}}> {content.title && <h1 class="mx-auto mb-12 text-2xl font-semibold leading-none tracking-tighter text-black lg:text-3xl title-font"> <b>{" -"} {" "} {content.title}</b> </h1>} <Button>Edit</Button> <Button>Delete</Button> </div> <h2 class="mx-auto mb-4 text-xl font-semibold leading-none tracking-tighter text-black title-font"> {content.desc} </h2> <p class="mx-auto text-base font-medium leading-relaxed text-blueGray-700 "> </p> </div> </div> { content.specifications && ( <> <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell><b className='text-lg font-bold italic'>Description</b></TableCell> <TableCell align="right"><b className='text-lg font-bold italic'>Review / Comment</b></TableCell> </TableRow> </TableHead> { content.specifications.map(data => ( <> <TableBody> <TableRow key={data}> <TableCell component="th" scope="row"> {data} </TableCell> <TableCell align="right"></TableCell> </TableRow> </TableBody> </> )) } </Table> </TableContainer> </> ) } { } </div> </section> </Card> </div> </div> </> ) } export default DQContentView <file_sep>/src/Pages/Design-Specs/DesignSpecs.jsx import { Typography, Toolbar, TextField, Button,Card,makeStyles, IconButton, Fab } from "@material-ui/core" import { useEffect } from "react" import { useState } from "react" import { NavLink } from "react-router-dom" import DQLayout from "../../components/DQNewSidebar/DQLayout" import { db } from "../../firebase" import { firebaseLooper } from "../../utils/tools" import SpecDetails from "./DScomps/SpecDetails" import DeleteSweepIcon from '@material-ui/icons/DeleteSweep'; import { Alert } from "@material-ui/lab" import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight'; import KeyboardArrowLeftIcon from '@material-ui/icons/KeyboardArrowLeft'; const useStyles = makeStyles((theme) => ({ layoutRoot: { backgroundColor: 'whitesmoke', display: 'flex', height: '100%', overflow: 'hidden', width: '100%', }, fab: { position: 'fixed', bottom: theme.spacing(2), right: theme.spacing(2), }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 250 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { padding: '20px', flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); function DesignSpecs({match}) { const [titles, setTitles] = useState([]) const [title, setTitle] = useState('') const [error, setError] = useState('') const classes = useStyles() useEffect(() => { db.collection('DQNew').doc(match.params.id) .collection('content').doc('designSpecs') .collection('title').onSnapshot(snap => { const data = firebaseLooper(snap) data.sort(function(a,b){ return(a.index-b.index) }) setTitles(data) }) }, []) function handleSubmit(e){ if(title?.trim().length === 0){ return setError("Empty Spaces are not valid input!") } // /DQ/HeceUekdaKAgLQvwFKc5/Design-Specs db.collection('DQNew').doc(match.params.id) .collection('content').doc('designSpecs') .collection('title').add({title,index: titles.length}).then(() => {setError("")}) } function handleDelete(id){ db.collection('DQNew').doc(match.params.id) .collection('content').doc('designSpecs') .collection('title').doc(id).delete() } return ( <> <DQLayout match={match}/> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div> <div className={classes.fab}> <Fab component={NavLink} to={`/DQ/${match.params.id}/Equipment-Config`} style={{marginRight: '20px'}} color="primary" aria-label="add"> <KeyboardArrowLeftIcon/> </Fab> <Fab component={NavLink} to={`/DQ/${match.params.id}/Safety`} color="primary" aria-label="add"> <KeyboardArrowRightIcon/> </Fab> </div> <Typography variant='h1' align='center' gutterBottom >Design Specifications</Typography> {error && <Alert severity='error'>{error}</Alert>} <Toolbar style={{display: 'flex', justifyContent: 'space-between', marginBottom: '30px'}}> <TextField className='mr-5' label='Add new Specification' variant='outlined' fullWidth value={title} onChange={(e) => setTitle(e.target.value)} /> <Button onClick={handleSubmit} disabled={title===''}>Submit</Button> </Toolbar> { titles.map(data => ( <div key={data.id}> <div style={{display: 'flex', justifyContent: 'space-between'}}> <Typography variant='h4' align='left' style={{paddingLeft: '30px'}} ><b>{data.title}</b> </Typography> <IconButton onClick={(e) =>handleDelete(data.id)}><DeleteSweepIcon className='hover:text-red-600' /></IconButton> </div> <br /> <div className='px-10'> <SpecDetails key={data.id} match={match} tid={data.id}/> </div> </div> )) } {/* <div style={{display: 'flex', justifyContent: 'flex-end'}}> <Button component={NavLink} to={`/DQ/${match.params.id}/Specifications`} style={{background: 'blue', color: 'white', marginLeft: '25px', marginRight: '4%'}}> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-90deg-left" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M1.146 4.854a.5.5 0 0 1 0-.708l4-4a.5.5 0 1 1 .708.708L2.707 4H12.5A2.5 2.5 0 0 1 15 6.5v8a.5.5 0 0 1-1 0v-8A1.5 1.5 0 0 0 12.5 5H2.707l3.147 3.146a.5.5 0 1 1-.708.708l-4-4z"/> </svg> </Button> <Button component={NavLink} to={`/DQ/${match.params.id}/Safety`} style={{background: 'blue', color: 'white', marginLeft: '25px'}}> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-arrow-90deg-right" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M14.854 4.854a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 4H3.5A2.5 2.5 0 0 0 1 6.5v8a.5.5 0 0 0 1 0v-8A1.5 1.5 0 0 1 3.5 5h9.793l-3.147 3.146a.5.5 0 0 0 .708.708l4-4z"/> </svg> </Button> </div> */} </div> </Card> </div> </div> </> ) } export default DesignSpecs <file_sep>/src/Pages/IQ/IQPages.jsx/IQControlPanel.jsx import { Dialog, Paper, TableCell, TableContainer, TableHead, TableRow, Typography,Toolbar, DialogContent, DialogActions, Button, TextField } from "@material-ui/core"; import { useEffect } from "react"; import { useState } from "react"; import { Table } from "react-bootstrap"; import { db } from "../../../firebase"; import { firebaseLooper } from "../../../utils/tools"; import ControlView from "../IQComponents/ControlView"; import DrawView from "../IQComponents/DrawView"; import IQConfigView from "../IQComponents/IQConfigView"; import IQHeader from "../IQComponents/IQHeader"; function IQControlPanel({match}) { const [contents, setContents] = useState([]) const [open, setOpen] = useState(false) const [title, setTitle] = useState('') const [desc, setDesc] = useState('') const [dno, setDno] = useState('') useEffect(() => { db.collection('IQ').doc(match.params.id) .collection('content').doc('control') .collection('tables') .onSnapshot(snapshot => { const data = firebaseLooper(snapshot) data.sort(function(a,b){ return (a.index - b.index) }) setContents(data) }) }, []) function handleOpen(){ setOpen(true) } function handleClose(){ setOpen(false) } function handleSubmit(){ const index = contents.length db.collection('IQ').doc(match.params.id) .collection('content').doc('control') .collection('tables').add({title,desc,index}) } return ( <div> <IQHeader match={match}/> <Toolbar style={{display: 'flex', justifyContent: 'flex-end'}}> <Button onClick={handleOpen} style={{background: 'orange', color: 'white'}}>Add Items</Button> </Toolbar> <TableContainer component={Paper}> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell><b className='text-lg font-bold italic'>Title</b></TableCell> <TableCell align="left"><b className='text-lg font-bold italic'>Description</b></TableCell> <TableCell align="right"><b className='text-lg font-bold italic'>Actions</b></TableCell> </TableRow> </TableHead> { contents.map(module => ( <> <ControlView module={module} match={match} key={module.id}/> </> )) } </Table> </TableContainer> <Dialog open={open} onClose={handleClose} fullWidth> <Typography variant='h3' align='center' gutterBottom><b>Add new items</b></Typography> <DialogContent> <TextField style={{marginBottom: '3%'}} variant='outlined' label='Title' fullWidth onChange={(e) => setTitle(e.target.value)}/> <TextField multiLine rows={7} variant='outlined' label='Description' fullWidth onChange={(e) => setDesc(e.target.value)}/> </DialogContent> <DialogActions> <Button color='secondary' onClick={handleClose} variant='contained'>Cancel</Button> <Button disabled={title === '' || desc===''} onClick={handleSubmit} style={{background: 'orange', color: 'white'}}>Add to Index</Button> </DialogActions> </Dialog> </div> ) } export default IQControlPanel <file_sep>/src/Pages/FileManager/AddFiles.jsx import { Box, Button, Card, Container, Grid, InputLabel, makeStyles, Select, TextField, Typography } from '@material-ui/core' import React, { useEffect, useState } from 'react'; import {useHistory} from 'react-router-dom' import {useDropzone} from 'react-dropzone'; import {db, storage, storageRef} from '../../firebase' import { DropzoneArea } from 'material-ui-dropzone'; import Alert from '@material-ui/lab/Alert'; import { v4 as uuid } from 'uuid' import ManualDashboardLayout from '../../components/ManualSidebar/ManualDashboardLayout' import StepDashboardLayout from '../../components/StepSidebar/StepDashboardLayout'; import { useStorage } from '../../utils/useStorage'; import { firebaseLooper } from '../../utils/tools'; import moment from 'moment'; const useStyles = makeStyles((theme) => ({ paper: { }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, form: { width:"100%", marginTop: theme.spacing(1), }, submit: { maxWidth: "50%", background: "#ff7a00", borderRadius: '20px', margin: theme.spacing(3, 0, 2), }, drag: { border: "4px dashed #fff", }, drop: { textAlign: "center", color: "#4a47a3", fontFamily: "roboto" }, backButton: { margiinTop: "30px", backgroundColor: "#A997DF", color: "white", }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); const AddFiles = ({match}) => { const [title, setTitle] = useState('') const [desc, setDesc] = useState(''); const [createdAt, setCreatedAt] = useState(''); const [format, setFormat] = useState('') const [type, setType] = useState(''); const date= moment(new Date()).format('DD/MM/YYYY') const [file, setFile] = useState(null); const [error, setError] = useState('') const [media, setMedia] = useState({ mediaData: null }) const types = ["image/png", "image/jpeg", "image/jpg"]; const videoTypes = ["video/mp4", "video/mkv", "video/mov"]; const audioTypes = ["audio/mp3", 'audio/mpeg'] const [loading, setLoading] = useState(false); const [message, setMessage] = useState('') const history = useHistory(); const handleReturn = () => { history.go(-1) } const [indexD, setIndex] = useState([]) useEffect(() => { }, []) const handleChange = (loadedFiles) => { let selectedFile = loadedFiles[0] setFile(selectedFile) } const { progress, url } = useStorage(file); const handleSubmit = (e) => { e.preventDefault(); const index = indexD.length const steps = {title, desc, url, date}; if(title?.trim().length===0 || desc?.trim().length === 0 ){ return setError("Empty spaces can't be added as input ! Please try again with valid data!") } setLoading(true); db.collection('FileManager').add(steps).then(()=>{ setLoading(false) setMessage('Step Added successfully !') setError("") history.push('/file-manager') }) } const classes= useStyles(); return ( <> <div > <div > <Card > <Box py={3} style={{ backgroundColor: 'background.default', minHeight: '100%', }} > <Container maxWidth={false}> <div className={classes.paper}> <Alert severity="info">You are currently Adding New Files </Alert> <br/> <Typography component="h1" variant="h3" align='center'> <b>Add New File</b> </Typography> <form className={classes.form} onSubmit={handleSubmit}> {error && <Alert severity='error'>{error}</Alert>} <div style={{display: 'flex'}}> <Grid container spacing={3} style={{marginRight: "50px"}} > <Grid item lg={12} sm={12} xl={6} xs={12} > <TextField value={title} error={title.length > 30} variant="outlined" margin="normal" required fullWidth id="title" label="Document Name" name="title" autoFocus onChange={(e) => setTitle(e.target.value)} /> <TextField value={desc} variant="outlined" margin="normal" required fullWidth rows={7} name="step_description" label="Description" onChange={(e) => setDesc(e.target.value)} id="step_description" multiline style={{marginBottom: '20px'}} /> </Grid> <Grid xs={12} lg={12} sm={12} > <Alert severity="warning">Don't leave Media Field empty !</Alert> <br/> <InputLabel variant="contained">Add the New File</InputLabel> <DropzoneArea showPreviews={true} dropzoneClass={classes.drop} showFileNames onChange={(loadedFiles) => handleChange(loadedFiles)} dropzoneText="Drag and Drop / Click to Add Files" showPreviewsInDropzone={false} useChipsForPreview showAlerts={false} filesLimit={1} maxFileSize={6000000} /> <h5>{progress}% Uploaded</h5> </Grid> </Grid> </div> {!loading && <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit} disabled={title.length > 30} > Add File </Button>} { loading && <Button type="submit" fullWidth variant="contained" color="primary" disabled className={classes.submit} >Adding Files, Please Wait...</Button> } </form> </div> </Container> </Box> </Card> </div> </div> </> ) } export default AddFiles<file_sep>/src/Pages/Manuals/AddManuals.jsx import { Button, Card, Container, FormHelperText, makeStyles, TextField, Typography } from '@material-ui/core' import Alert from '@material-ui/lab/Alert'; import React, { useState } from 'react'; import {useHistory} from 'react-router-dom' import ContentDashboardLayout from '../../components/ContentSidebar/ContentDashboardLayout'; import {db} from '../../firebase' const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, form: { alignItems: "center", justifyContent: "center", width: '90%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { backgroundImage: 'linear-gradient(to left bottom, #fa630f, #fc8218, #fd9d29, #feb63f, #ffce59)', color: "white", borderRadius: '20px', margin: theme.spacing(3, 0, 2), }, wrapper: { display: 'flex', flex: '1 1 auto', overflow: 'hidden', paddingTop: 64, [theme.breakpoints.up('lg')]: { paddingLeft: 256 }, }, container: { display: 'flex', flex: '1 1 auto', overflow: 'hidden' }, content: { flex: '1 1 auto', height: '100%', overflow: 'auto' }, })); const AddManuals = ({match}) => { const classes= useStyles(); const [title, setContentName] = useState('') const [error, setError] = useState('') const [desc, setDesc] = useState('') const [loading, setLoading] = useState(false); const [mid, setMid] = useState(match.params.id) const history = useHistory(); const handleSubmit = (e) => { e.preventDefault(); if(title?.trim().length===0 || desc?.trim().length===0){ return setError("Empty Spaces are not accepted as inputs! Please try again with a valid input!") } const manuals = {title, mid, desc} setLoading(true); db.collection('manualData').add(manuals).then((data) =>{ console.log(data) history.push(`/machine-data/Manuals/${match.params.id}/Manuals`) }) } return ( <> <ContentDashboardLayout match={match}/> <div> <div className={classes.wrapper}> <div className={classes.container}> <Card className={classes.content}> <div className={classes.paper}> <Alert severity="info">You are currently adding a new Manual</Alert> <br/> <Typography align='center' component="h1" variant="h2"> <b>Add Manuals</b> </Typography> <form className={classes.form} onSubmit={handleSubmit}> {error && <Alert severity='error'>{error}</Alert>} <TextField value={mid} fullWidth variant="outlined" margin="normal" label="Machine id" disabled onChange ={(e) => setMid(e.target.value)} /> <TextField value={title} error={title.length > 30} variant="outlined" margin="normal" required fullWidth id="content_name" label="Manual Title" name="content_name" autoFocus onChange={(e) => setContentName(e.target.value)} /> <FormHelperText>Title should be max {title.length}/ 30 characters</FormHelperText> <TextField rows={5} multiline value={desc} variant="outlined" margin="normal" required fullWidth id="content_name" label="Manual Description" name="content_name" error={desc.length > 150} onChange={(e) => setDesc(e.target.value)} /> <FormHelperText>Description should be max {desc.length}/150 characters </FormHelperText> {!loading && <Button type="submit" fullWidth variant="contained" disabled={desc.length > 150 || title.length > 30} className={classes.submit} > Add Manual </Button>} { loading && <Button type="submit" fullWidth variant="contained" disabled className={classes.submit} >Adding Manual...</Button> } </form> </div> </Card> </div> </div> </div> </> ) } export default AddManuals<file_sep>/src/components/Machines/AddMachines.jsx import { Button, Card, CardContent, Container, FormHelperText, makeStyles, TextField, Typography } from '@material-ui/core' import Alert from '@material-ui/lab/Alert'; import React, { useEffect, useState } from 'react'; import {useHistory} from 'react-router-dom' import {db} from '../../firebase' import {firebaseLooper} from '../../utils/tools' import { useAuth } from '../context/AuthContext'; import faker from 'faker' const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', borderRadius: "20px" }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(1), alignItems: "center" }, submit: { backgroundImage: 'linear-gradient(to left bottom, #fa630f, #fc8218, #fd9d29, #feb63f, #ffce59)', align: "center", color: "white", width: "100%", borderRadius: '20px', margin: theme.spacing(3, 0, 2), } })); const AddMachines = () => { const { currentUser } = useAuth() const [title, setMachineName] = useState('') const [location, setMachineLocation] = useState(''); const [createdBy, setCreatedBy] = useState(currentUser.email); const [desc, setDesc] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState('') const notification = `${currentUser.email} has created a new Machine!` const link = 'machine-data' const history = useHistory(); const [notifyData, setNotifyData] = useState([]) const handleSubmit = (e) => { e.preventDefault(); var result = {title,location,createdBy,desc } if(title?.trim().length===0 || desc?.trim().length===0 || location?.trim().length===0){ return setError("Empty Spaces can't be added as input! Please try again with a valid input") } db.collection('machineData').add(result).then(data => { history.push('/machine-data') console.log(data) setLoading(true) setError("") }) } const classes= useStyles(); return ( <Container component="main" style={{ marginBottom: "100px"}}> <Container className={classes.paper}> <Alert severity="info">You are currently adding a new Machine</Alert> <br/> <Typography component="h1" variant="h4"> Add Machine </Typography> <form onSubmit={handleSubmit} className={classes.form} > {error && <Alert severity='error'>{error}</Alert>} <Card > <CardContent> <TextField value={title} variant="outlined" margin="normal" required fullWidth error={title.length > 30} id="machine_name" label="Machine Name" name="machine_name" autoFocus onChange={(e) => setMachineName(e.target.value)} /> <FormHelperText>Title should be max 30 Char</FormHelperText> <TextField value={location} variant="outlined" margin="normal" required fullWidth error={location.length > 30} name="location" label="Location" onChange={(e) => setMachineLocation(e.target.value)} id="machine_location" /> <FormHelperText style={{marginBottom:"20px"}}>Location should be max 30 char long</FormHelperText> <TextField fullWidth value={createdBy} variant="outlined" id="user" label="Created By" type="text" disabled onChange ={(e) => setCreatedBy(e.target.value)} style={{marginBottom: '20px'}} /> <TextField fullWidth value={desc} variant="outlined" id="desc" label="Description" type="text" multiline rows={7} onChange ={(e) => setDesc(e.target.value)} /> <FormHelperText>Description should be min {desc.length}/150</FormHelperText> {!loading && <Button type="submit" variant="contained" className={classes.submit} disabled={title.length > 30 || desc.length < 150 || location.length > 30} > Add Machine </Button>} { loading && <Button type="submit" variant="contained" disabled className={classes.submit} >Adding Machine...</Button> } </CardContent> </Card> </form> </Container> </Container> ) } export default AddMachines <file_sep>/src/Pages/MachineContents/EditContent.jsx import { Button, Container, makeStyles, TextField, Typography } from '@material-ui/core' import React, { useState } from 'react'; import {useHistory} from 'react-router-dom' const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: '#141256', }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { background: "#141256", borderRadius: '20px', margin: theme.spacing(3, 0, 2), } })); const EditContent = () => { const [content_name, setContentName] = useState('') const [content_description, setContentDescription] = useState(''); const [createdAt, setCreatedAt] = useState(''); const [loading, setLoading] = useState(false); const history = useHistory(); const handleSubmit = (e, id) => { const content = {content_name, content_description, createdAt}; setLoading(true); fetch(`http://localhost:5000/content/${id}`, { method: 'PUT', headers: {"Content-Type": "application/json" }, body: JSON.stringify(content) }).then((res) => { res.json() setLoading(false) history.go(-1) }) } const classes= useStyles(); return ( <Container maxWidth="xs" component="main"> <div className={classes.paper}> <Typography component="h1" variant="h5"> Edit Content </Typography> <form className={classes.form} onSubmit={handleSubmit}> <TextField value={content_name} variant="outlined" margin="normal" required fullWidth id="content_name" label="Content Name" name="content_name" autoFocus onChange={(e) => setContentName(e.target.value)} /> <TextField value={content_description} variant="outlined" margin="normal" required fullWidth name="content_description" label="Description" onChange={(e) => setContentDescription(e.target.value)} id="content_description" multiline /> <TextField value={createdAt} id="date" label="Created At" type="date" InputLabelProps={{ shrink: true, }} onChange={(e) => setCreatedAt(e.target.value)} /> {!loading && <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit} > Update </Button>} { loading && <Button type="submit" fullWidth variant="contained" color="primary" disabled className={classes.submit} >Updating values...</Button> } </form> </div> </Container> ) } export default EditContent
c68c54b7c9b31c9d1ddce2cdb91bbc86ef7f2395
[ "JavaScript", "Markdown" ]
101
JavaScript
GirishKaradas/firebase-lyo4-1
39aeecd4d021b72aadfa70cb1fb5790c588711cc
7a7a9b64ca661c99230b31e0ff1bec07744434af
refs/heads/master
<file_sep>## Put comments here that give an overall description of what your ## functions do ## Write a short comment describing this function -- OK ## The 'makeCacheMatrix' function creates a special "matrix" object ## that can cache its inverse. Per the assignment instructions, we ## are to assume matrix supplied is always invertible and we can ## use the 'solve' function to calculate the inverse of a matrix. ## In general, the function receives a matrix as input and creates ## a special "matrix" object that for storing the inverse of the ## provided matrix. makeCacheMatrix <- function(x = matrix()) { inv_matrix <- NULL set <- function(y) { x <<- y inv_matrix <<- NULL } get <- function() x set_inverse <- function(solve) inv_matrix <<- solve get_inverse <- function() inv_matrix list(set = set, get = get, set_inverse = set_inverse, get_inverse = get_inverse) } ## Write a short comment describing this function -- OK ## The 'cacheSolve' function checks to to see if the inverse ## of the provided special "matrix" object, created using the ## 'makeCachedMatrix' function above, has already been ## calclulated. If it has been previously calculated, it will ## get the inverse from cache and skip the computation. If ## the inverse has not been previously calculated, it will ## calculate the inverse and set the value of the inverse in ## the cache via the 'set_inverse' function. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' m_inverse <- x$get_inverse() if(!is.null(m_inverse)) { message("getting cached matrix") return(m_inverse) } data <- x$get() m_inverse <- solve(data, ...) x$set_inverse(m_inverse) m_inverse }
3d3591540070a07e7bec5313772da9720ed35bc5
[ "R" ]
1
R
jmasih/ProgrammingAssignment2
cfc81798540087856b88675ea9ef2ca3586c0a2b
d74b6a378d4131fe2e7fb2137986d131913a2bf7
refs/heads/master
<file_sep>#include <iostream> using namespace std; void PrintSpiral(int arr[10][10],int r,int c){ int startCol=0,startRow=0,endCol=c-1,endRow=r-1; while(startCol<=endCol && startRow<=endRow){ //print first row for(int i=startCol;i<=endCol;i++) cout<<arr[startRow][i]<<" "; startRow++; //print end column for(int i=startRow;i<=endRow;i++) cout<<arr[i][endCol]<<" "; endCol--; //print end row if(endRow>startRow){ for(int i=endCol;i>=startCol;i--) cout<<arr[endRow][i]<<" "; endRow--; } //print first column if(startCol<endCol){ for(int i=endRow;i>=startRow;i--) cout<<arr[i][startCol]<<" "; startCol++; } } } int main() { int arr[10][10],r,c; cout<<"Enter the number of rows and columns you want in your array :"; cin>>r>>c; cout<<"\nEnter the elements of the array\n"; for(int i=0;i<r;i++){ for(int j=0;j<c;j++) cin>>arr[i][j]; } cout<<"\nThe spiral print of the above given array is :"<<endl; PrintSpiral(arr,r,c); }
fa4f744e887ac0b62cb138f65553d5ed89ad883a
[ "C++" ]
1
C++
Manit1/2d-Spiral-print
b8a06b0dc78fe90d13b7517f845a7167ebb6a3b6
86015d4322b27385c84e9f8690560768bdb609c1
refs/heads/master
<repo_name>JJMo22/Spoon-Knife<file_sep>/cacheSolve.R cacheSolve <- function(x, ...){ s <- x$getsol() if (!is.null(s)){ message("Boo ya") return(s) } data <- x$get() s <- solve(data,...) x$setsol(s) s }
fbc38824a1dba8e8d29fec8b30a721b273b560da
[ "R" ]
1
R
JJMo22/Spoon-Knife
ee8bb1dbf67054bff567f27da2e671b087fb9f4a
8c6d27723ada100e6bfe63eabdc7e896e473106a
refs/heads/master
<file_sep># i'm a comment import urllib2 import json import googlemaps gmaps = googlemaps.Client(key='') def get_html(url): """ Does a thing :param url: a URL :return: the URL (opened) """ return urllib2.urlopen(url).read() def api_call(origins, destinations): gmaps.distance_matrix(origins, destinations, mode="transit", language="en-US") def main(): pass if __name__ == "__main__": main()
69afb00756d39390a39af321502752e824bb9777
[ "Python" ]
1
Python
armsnyder/where-should-we-live
5290dfb544595cfd4ee7841e5fd8be573c21f463
2c7c574669a35b033ad362b8e05a3935059c3442
refs/heads/master
<repo_name>santerinogelainen/osu<file_sep>/osu.Game.Tests/Visual/Editing/TestSceneEditorSamplePlayback.cs // Copyright (c) p<NAME> <<EMAIL>>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Graphics.Audio; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Tests.Visual.Editing { public class TestSceneEditorSamplePlayback : EditorTestScene { protected override Ruleset CreateEditorRuleset() => new OsuRuleset(); [Test] public void TestSlidingSampleStopsOnSeek() { DrawableSlider slider = null; DrawableSample[] samples = null; AddStep("get first slider", () => { slider = Editor.ChildrenOfType<DrawableSlider>().OrderBy(s => s.HitObject.StartTime).First(); samples = slider.ChildrenOfType<DrawableSample>().ToArray(); }); AddStep("start playback", () => EditorClock.Start()); AddUntilStep("wait for slider sliding then seek", () => { if (!slider.Tracking.Value) return false; if (!samples.Any(s => s.Playing)) return false; EditorClock.Seek(20000); return true; }); AddAssert("slider samples are not playing", () => samples.Length == 5 && samples.All(s => s.Played && !s.Playing)); } } } <file_sep>/osu.Game/IO/OsuStorage.cs // Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using JetBrains.Annotations; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Game.Configuration; namespace osu.Game.IO { public class OsuStorage : WrappedStorage { /// <summary> /// Indicates the error (if any) that occurred when initialising the custom storage during initial startup. /// </summary> public readonly OsuStorageError Error; /// <summary> /// The custom storage path as selected by the user. /// </summary> [CanBeNull] public string CustomStoragePath => storageConfig.Get<string>(StorageConfig.FullPath); /// <summary> /// The default storage path to be used if a custom storage path hasn't been selected or is not accessible. /// </summary> [NotNull] public string DefaultStoragePath => defaultStorage.GetFullPath("."); private readonly GameHost host; private readonly StorageConfigManager storageConfig; private readonly Storage defaultStorage; public static readonly string[] IGNORE_DIRECTORIES = { "cache" }; public static readonly string[] IGNORE_FILES = { "framework.ini", "storage.ini" }; public OsuStorage(GameHost host, Storage defaultStorage) : base(defaultStorage, string.Empty) { this.host = host; this.defaultStorage = defaultStorage; storageConfig = new StorageConfigManager(defaultStorage); if (!string.IsNullOrEmpty(CustomStoragePath)) TryChangeToCustomStorage(out Error); } /// <summary> /// Resets the custom storage path, changing the target storage to the default location. /// </summary> public void ResetCustomStoragePath() { storageConfig.Set(StorageConfig.FullPath, string.Empty); storageConfig.Save(); ChangeTargetStorage(defaultStorage); } /// <summary> /// Attempts to change to the user's custom storage path. /// </summary> /// <param name="error">The error that occurred.</param> /// <returns>Whether the custom storage path was used successfully. If not, <paramref name="error"/> will be populated with the reason.</returns> public bool TryChangeToCustomStorage(out OsuStorageError error) { Debug.Assert(!string.IsNullOrEmpty(CustomStoragePath)); error = OsuStorageError.None; Storage lastStorage = UnderlyingStorage; try { Storage userStorage = host.GetStorage(CustomStoragePath); if (!userStorage.ExistsDirectory(".") || !userStorage.GetFiles(".").Any()) error = OsuStorageError.AccessibleButEmpty; ChangeTargetStorage(userStorage); } catch { error = OsuStorageError.NotAccessible; ChangeTargetStorage(lastStorage); } return error == OsuStorageError.None; } protected override void ChangeTargetStorage(Storage newStorage) { base.ChangeTargetStorage(newStorage); Logger.Storage = UnderlyingStorage.GetStorageForDirectory("logs"); } public void Migrate(string newLocation) { var source = new DirectoryInfo(GetFullPath(".")); var destination = new DirectoryInfo(newLocation); // using Uri is the easiest way to check equality and contains (https://stackoverflow.com/a/7710620) var sourceUri = new Uri(source.FullName + Path.DirectorySeparatorChar); var destinationUri = new Uri(destination.FullName + Path.DirectorySeparatorChar); if (sourceUri == destinationUri) throw new ArgumentException("Destination provided is already the current location", nameof(newLocation)); if (sourceUri.IsBaseOf(destinationUri)) throw new ArgumentException("Destination provided is inside the source", nameof(newLocation)); // ensure the new location has no files present, else hard abort if (destination.Exists) { if (destination.GetFiles().Length > 0 || destination.GetDirectories().Length > 0) throw new ArgumentException("Destination provided already has files or directories present", nameof(newLocation)); deleteRecursive(destination); } copyRecursive(source, destination); ChangeTargetStorage(host.GetStorage(newLocation)); storageConfig.Set(StorageConfig.FullPath, newLocation); storageConfig.Save(); deleteRecursive(source); } private static void deleteRecursive(DirectoryInfo target, bool topLevelExcludes = true) { foreach (System.IO.FileInfo fi in target.GetFiles()) { if (topLevelExcludes && IGNORE_FILES.Contains(fi.Name)) continue; attemptOperation(() => fi.Delete()); } foreach (DirectoryInfo dir in target.GetDirectories()) { if (topLevelExcludes && IGNORE_DIRECTORIES.Contains(dir.Name)) continue; attemptOperation(() => dir.Delete(true)); } if (target.GetFiles().Length == 0 && target.GetDirectories().Length == 0) attemptOperation(target.Delete); } private static void copyRecursive(DirectoryInfo source, DirectoryInfo destination, bool topLevelExcludes = true) { // based off example code https://docs.microsoft.com/en-us/dotnet/api/system.io.directoryinfo Directory.CreateDirectory(destination.FullName); foreach (System.IO.FileInfo fi in source.GetFiles()) { if (topLevelExcludes && IGNORE_FILES.Contains(fi.Name)) continue; attemptOperation(() => fi.CopyTo(Path.Combine(destination.FullName, fi.Name), true)); } foreach (DirectoryInfo dir in source.GetDirectories()) { if (topLevelExcludes && IGNORE_DIRECTORIES.Contains(dir.Name)) continue; copyRecursive(dir, destination.CreateSubdirectory(dir.Name), false); } } /// <summary> /// Attempt an IO operation multiple times and only throw if none of the attempts succeed. /// </summary> /// <param name="action">The action to perform.</param> /// <param name="attempts">The number of attempts (250ms wait between each).</param> private static void attemptOperation(Action action, int attempts = 10) { while (true) { try { action(); return; } catch (Exception) { if (attempts-- == 0) throw; } Thread.Sleep(250); } } } public enum OsuStorageError { /// <summary> /// No error. /// </summary> None, /// <summary> /// Occurs when the target storage directory is accessible but does not already contain game files. /// Only happens when the user changes the storage directory and then moves the files manually or mounts a different device to the same path. /// </summary> AccessibleButEmpty, /// <summary> /// Occurs when the target storage directory cannot be accessed at all. /// </summary> NotAccessible, } } <file_sep>/osu.Game.Tests/Beatmaps/BeatmapDifficultyManagerTest.cs // Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu.Mods; namespace osu.Game.Tests.Beatmaps { [TestFixture] public class BeatmapDifficultyManagerTest { [Test] public void TestKeyEqualsWithDifferentModInstances() { var key1 = new BeatmapDifficultyManager.DifficultyCacheLookup(1234, 0, new Mod[] { new OsuModHardRock(), new OsuModHidden() }); var key2 = new BeatmapDifficultyManager.DifficultyCacheLookup(1234, 0, new Mod[] { new OsuModHardRock(), new OsuModHidden() }); Assert.That(key1, Is.EqualTo(key2)); } [Test] public void TestKeyEqualsWithDifferentModOrder() { var key1 = new BeatmapDifficultyManager.DifficultyCacheLookup(1234, 0, new Mod[] { new OsuModHardRock(), new OsuModHidden() }); var key2 = new BeatmapDifficultyManager.DifficultyCacheLookup(1234, 0, new Mod[] { new OsuModHidden(), new OsuModHardRock() }); Assert.That(key1, Is.EqualTo(key2)); } } } <file_sep>/osu.Game/Screens/Play/SaveScoreButton.cs // Copyright (c) p<NAME> <<EMAIL>>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Graphics.UserInterface; using osu.Game.Online; namespace osu.Game.Screens.Play { public class SaveScoreButton : DownloadButton { public Action OnSave; [BackgroundDependencyLoader] private void load() { State.BindValueChanged(updateTooltip, true); Action = saveScore; } private void saveScore() { if (State.Value != DownloadState.LocallyAvailable) OnSave?.Invoke(); State.Value = DownloadState.LocallyAvailable; } private void updateTooltip(ValueChangedEvent<DownloadState> state) { switch (state.NewValue) { case DownloadState.LocallyAvailable: TooltipText = @"Score saved"; break; default: TooltipText = @"Save score"; break; } } } }
7cc2775a9b4dcff27e6de3097a7b4f33e647d2b5
[ "C#" ]
4
C#
santerinogelainen/osu
eb47eb150519b6c28e71f2a7588eb4c5c39e2a59
571d8d8d90255cc997ad4f6af32982e68f4ad495
refs/heads/master
<repo_name>sd-2019-30238/assignment-1-lucadanadrian<file_sep>/assignment3/src/main/java/com/books/assignment3/handler/impl/BookRequestHandler.java package com.books.assignment3.handler.impl; import com.books.assignment3.handler.RequestHandler; import com.books.assignment3.model.command.BookCommandDTO; import com.books.assignment3.request.Request; import com.books.assignment3.service.command.BookCommandService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class BookRequestHandler implements RequestHandler { @Autowired private BookCommandService bookCommandService; // @Autowired // public BookRequestHandler(BookCommandService bookCommandService){ // this.bookCommandService=bookCommandService; // } @Override public void handleRequest(Request request) { BookCommandDTO bookCommandDTO = new BookCommandDTO(); bookCommandDTO.setTitle(((BookCommandDTO) request.getRequestObject()).getTitle()); bookCommandDTO.setAuthor(((BookCommandDTO) request.getRequestObject()).getAuthor()); bookCommandDTO.setGenre(((BookCommandDTO) request.getRequestObject()).getGenre()); bookCommandDTO.setReleaseDate(((BookCommandDTO) request.getRequestObject()).getReleaseDate()); bookCommandDTO.setPrice(((BookCommandDTO) request.getRequestObject()).getPrice()); bookCommandDTO.setNumberOfBooks(((BookCommandDTO) request.getRequestObject()).getNumberOfBooks()); bookCommandService.addBook(bookCommandDTO); } } <file_sep>/assignment2/src/main/java/com/assignment2/demo/dao/StaffDAO.java package com.assignment2.demo.dao; import com.assignment2.demo.model.Staff; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.transaction.Transactional; import java.util.List; @Transactional @Component public class StaffDAO { @Autowired private SessionFactory sessionFactory; public Staff selectStaffById(int id){ return sessionFactory.getCurrentSession().get(Staff.class,id); } public List<Staff> selectAll(){ return sessionFactory.getCurrentSession().createSQLQuery("Select * from staff").addEntity(Staff.class).list(); } public void insertStaff(Staff staff){ sessionFactory.getCurrentSession().save(staff); } public void updateStaff(Staff staff){ sessionFactory.getCurrentSession().saveOrUpdate(staff); } public void deleteStaff(int id){ sessionFactory.getCurrentSession().createSQLQuery("Delete from staff where staff_id =:id ").setParameter("id",id).executeUpdate(); } } <file_sep>/assignment1/src/main/java/presentation/BookManagement.java package presentation; import bll.BookBLL; import connection.Connection; import dao.BookDAO; import dao.UserDAO; import model.Book; import model.User; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class BookManagement extends JFrame{ static LogIn logIn = new LogIn(); private JPanel panel; private JComboBox comboBox1; private JTextArea textArea1; private JTextField textField1; private JButton showAllButton; private JTextField textField2; private JButton deleteButton; private JButton insertButton; private JTextField titleField; private JTextField authorField; private JTextField genreField; private JTextField yearField; private JTextField priceField; private JTextField numberOfBooksField; private JButton logOutButton; private JButton showUsersButton; // ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Connection.class); // BookDAO book = applicationContext.getBean("bookDAO", BookDAO.class); BookBLL books = new BookBLL(); public BookManagement(){ setTitle("BookManagement"); setContentPane(panel); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); pack(); setSize(1000,400); comboBox1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { selectFilter(e); } }); showAllButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showAllBooks(e); } }); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { books.deleteBook(Integer.parseInt(textField2.getText())); textField2.setText(""); } }); insertButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { books.insertBook(new Book(1, titleField.getText(), authorField.getText(), genreField.getText(), Integer.parseInt(yearField.getText()), Integer.parseInt(priceField.getText()), Integer.parseInt(numberOfBooksField.getText()) )); titleField.setText(""); authorField.setText(""); genreField.setText(""); yearField.setText(""); priceField.setText(""); numberOfBooksField.setText(""); } }); logOutButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { goToLogOut(e); } }); showUsersButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ApplicationContext appContext = new AnnotationConfigApplicationContext(Connection.class); UserDAO users= appContext.getBean("userDAO",UserDAO.class); String text=""; for(User u: users.selectAll()){ text += u.getId() + " " +u.getEmail()+ " "+ u.getLastName()+ " "+u.getFirstName() + "\n"; } textArea1.setText(text); } }); } protected void goToLogOut(ActionEvent e){ this.setVisible(false); logIn.setVisible(true); } protected void selectFilter(ActionEvent e){ // System.out.println(comboBox1.getSelectedItem().toString()); if(comboBox1.getSelectedItem().toString().equals("Author")){ textArea1.setText(books.selectBookByAuthor(textField1.getText().toLowerCase()).toString()); } if(comboBox1.getSelectedItem().toString().equals("Title")){ textArea1.setText(books.selectBookByTitle(textField1.getText().toLowerCase()).toString()); } if(comboBox1.getSelectedItem().toString().equals("Genre")){ textArea1.setText(books.selectBookByGenre(textField1.getText().toLowerCase()).toString()); } if(comboBox1.getSelectedItem().toString().equals("Release Year")){ textArea1.setText(books.selectBookByYear(Integer.parseInt(textField1.getText())).toString()); } } protected void showAllBooks(ActionEvent e){ String text=""; for(Book b : books.selectAllBooks()){ text +=b.toString(); } textArea1.setText(text); } public static void main(String[] args){ EventQueue.invokeLater( () -> {BookManagement bm = new BookManagement(); bm.setVisible(true);}); } } <file_sep>/assignment2/src/main/java/com/assignment2/demo/controller/BookOrderController.java package com.assignment2.demo.controller; import com.assignment2.demo.service.BookService; import com.assignment2.demo.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; @Controller public class BookOrderController { private OrderService orderService; private BookService bookService; @Autowired public BookOrderController(OrderService orderService, BookService bookService) { this.orderService = orderService; this.bookService = bookService; } @GetMapping("/bookOrders/currentUser") public ModelAndView getOrdersForAuthenticatedUser(Authentication authentication) { ModelAndView modelAndView = new ModelAndView("seeOrders"); modelAndView.addObject("bookOrders", orderService.getOrdersForAnUserByEmail(authentication.getName())); return modelAndView; } @PostMapping("/booksU/{id}") public ModelAndView orderBook(@PathVariable("id") int id, Authentication authentication) { ModelAndView modelAndView = new ModelAndView("redirect:/booksU"); bookService.orderBook(id, authentication.getName()); return modelAndView; } @PutMapping("/booksU/return") public ModelAndView returnBook(@RequestParam("orderId") int orderId, Authentication authentication) { ModelAndView modelAndView = new ModelAndView("redirect:/bookOrders/currentUser"); bookService.returnBook(orderId); return modelAndView; } } <file_sep>/assignment1/src/main/java/bll/UserBLL.java package bll; import connection.Connection; import dao.UserDAO; import model.User; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.List; public class UserBLL { ApplicationContext appContext = new AnnotationConfigApplicationContext(Connection.class); UserDAO users = appContext.getBean("userDAO",UserDAO.class); public UserBLL(){ } public User findById(int id){ return users.selectById(id); } public List<User> selectAllClients(){ return users.selectAll(); } public void insertUser(User user){ users.insertTable(user); } public void updateUser(User user){ users.insertTable(user); } public void deleteUser(int id){ users.deleteFromTable(id); } } <file_sep>/assignment3/src/main/java/com/books/assignment3/decorator/BookDecoratorInterface.java package com.books.assignment3.decorator; public interface BookDecoratorInterface { void setNumberOfBooks(int numberOfBooks); } <file_sep>/assignment1/src/main/java/bll/BookOrderBLL.java package bll; import connection.Connection; import dao.OrderDAO; import model.Book; import model.BookOrder; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.List; public class BookOrderBLL { ApplicationContext appContext = new AnnotationConfigApplicationContext(Connection.class); OrderDAO orders =appContext.getBean("orderDAO",OrderDAO.class); public BookOrderBLL(){ } public BookOrder selectById(int id){ return orders.selectByOrderId(id); } public List<BookOrder> selectAllOrers(){ return orders.selecOrders(); } public void insertBookOrder(BookOrder order){ orders.insertOrder(order); } public void updateOrder(BookOrder order){ orders.updateOrder(order); } public void deleteOrder(int id){ orders.deleteOrder(id); } } <file_sep>/assignment3/src/main/java/com/books/assignment3/request/Request.java package com.books.assignment3.request; public class Request { private String requestName; private Object requestObject; public Request() { } public Request(String requestName, Object requestObject) { this.requestName = requestName; this.requestObject = requestObject; } public String getRequestName() { return requestName; } public void setRequestName(String requestName) { this.requestName = requestName; } public Object getRequestObject() { return requestObject; } public void setRequestObject(Object requestObject) { this.requestObject = requestObject; } } <file_sep>/assignment1/src/main/java/bll/BookBLL.java package bll; import connection.Connection; import dao.BookDAO; import model.Book; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.List; public class BookBLL { ApplicationContext appContext = new AnnotationConfigApplicationContext(Connection.class); BookDAO books = appContext.getBean("bookDAO",BookDAO.class); public BookBLL(){ } public Book selectBookById(int id){ return books.selectById(id); } public List<Book> selectAllBooks(){ return books.selectAll(); } public List<Book> selectBookByAuthor(String author){ return books.selectByAuthor(author); } public List<Book> selectBookByTitle(String title){ return books.selectByTitle(title); } public List<Book> selectBookByYear(int year){ return books.selectByDate(year); } public List<Book> selectBookByGenre(String genre){ return books.selectByGenre(genre); } public List<Book> selectBooksByNumber(int number){ return books.selectByNumberOfBooks(number); } public void insertBook(Book book){ books.insertTable(book); } public void updateBook(Book book){ books.updateTable(book); } public void deleteBook(int id){ books.deleteFromTable(id); } } <file_sep>/assignment3/src/main/java/com/books/assignment3/dao/OrderDAO.java package com.books.assignment3.dao; import com.books.assignment3.model.database.BookOrder; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.transaction.Transactional; import java.util.List; @Transactional @Component public class OrderDAO { @Autowired private SessionFactory sessionFactory; public BookOrder selectByOrderId(int id) { return sessionFactory.getCurrentSession().get(BookOrder.class, id); } public List<BookOrder> selecOrders() { return (List<BookOrder>) sessionFactory.getCurrentSession().createSQLQuery("Select * from bookorder").addEntity(BookOrder.class).list(); } public List<BookOrder> selectOrdersByUsersEmail(String email) { return sessionFactory.getCurrentSession().createQuery("from " + BookOrder.class.getName() + " b where b.user.email =:email").setParameter("email", email).list(); } public void insertOrder(BookOrder order) { sessionFactory.getCurrentSession().save(order); } public void updateOrder(BookOrder order) { sessionFactory.getCurrentSession().saveOrUpdate(order); } public void deleteOrder(int id) { sessionFactory.getCurrentSession().createSQLQuery("Delete From bookorder where order_id = :id").setParameter("id", id).executeUpdate(); } } <file_sep>/assignment3/src/main/java/com/books/assignment3/controller/Query/UserQueryController.java package com.books.assignment3.controller.Query; import com.books.assignment3.model.command.UserCommandDTO; import com.books.assignment3.service.query.UserQueryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class UserQueryController { @Autowired private UserQueryService userQueryService; @GetMapping("/signUp") public ModelAndView displaySignUpPage() { ModelAndView modelAndView = new ModelAndView("signupPage"); modelAndView.addObject("userCommandDTO", new UserCommandDTO()); return modelAndView; } @GetMapping("/users") public ModelAndView displayAllUsers() { ModelAndView modelAndView = new ModelAndView("seeAllUsers"); modelAndView.addObject("users", userQueryService.seeAllUsers()); return modelAndView; } @GetMapping("/login") public ModelAndView showLogIn() { ModelAndView modelAndView = new ModelAndView("loginPage"); // modelAndView.addObject("user", userService.logInUser(email)); // @RequestParam(required = false, value = "email") String email return modelAndView; } } <file_sep>/assignment2/src/main/java/com/assignment2/demo/service/UserService.java package com.assignment2.demo.service; import com.assignment2.demo.dao.UserDAO; import com.assignment2.demo.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; @Transactional @Service public class UserService { @Autowired private UserDAO userDAO; @Autowired private PasswordEncoder passwordEncoder; public void addUser(User user) { user.setPassword(passwordEncoder.encode(user.getPassword())); userDAO.insertTable(user); } public List<User> seeAllUsers() { return userDAO.selectAll(); } public User selectUserByEmail(String email) { return userDAO.selectByEmail(email); } public void deleteUser(int id) { userDAO.deleteFromTable(id); } public void acceptUser(int id) { User user = userDAO.selectById(id); user.setSubscribed("subbed"); userDAO.updateTable(user); } } <file_sep>/assignment3/src/main/java/com/books/assignment3/service/query/BookQueryService.java package com.books.assignment3.service.query; import com.books.assignment3.dao.BookDAO; import com.books.assignment3.model.database.Book; import com.books.assignment3.model.query.BookQueryDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.ArrayList; import java.util.List; @Transactional @Service public class BookQueryService { @Autowired private BookDAO bookDAO; public List<BookQueryDTO> seeAllBooks() { List<BookQueryDTO> bookQueryDTOS = new ArrayList<>(); List<Book> books = bookDAO.selectAll(); for (Book book : books) { BookQueryDTO bookQueryDTO = new BookQueryDTO(); bookQueryDTO.setId(book.getId()); bookQueryDTO.setTitle(book.getTitle()); bookQueryDTO.setAuthor(book.getAuthor()); bookQueryDTO.setGenre(book.getGenre()); bookQueryDTO.setReleaseDate(book.getReleaseDate()); bookQueryDTO.setPrice(book.getPrice()); bookQueryDTO.setNumberOfBooks(book.getNumberOfBooks()); bookQueryDTOS.add(bookQueryDTO); } return bookQueryDTOS; } } <file_sep>/assignment3/src/main/java/com/books/assignment3/service/command/UserCommandService.java package com.books.assignment3.service.command; import com.books.assignment3.dao.UserDAO; import com.books.assignment3.model.command.UserCommandDTO; import com.books.assignment3.model.database.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import javax.transaction.Transactional; @Transactional @Service public class UserCommandService { @Autowired private UserDAO userDAO; @Autowired private PasswordEncoder passwordEncoder; public void addUser(UserCommandDTO dto){ User user = new User(); user.setEmail(dto.getEmail()); user.setLastName(dto.getLastName()); user.setFirstName(dto.getFirstName()); user.setPassword(passwordEncoder.encode(dto.getPassword())); user.setSubscriptionMonths(dto.getSubscriptionMonth()); user.setSubscribed(dto.getSubscribed()); userDAO.insertTable(user); } public void deleteUser(int id){ userDAO.deleteFromTable(id); } public void acceptUser(int id){ User user = userDAO.selectById(id); user.setSubscribed("subbed"); userDAO.updateTable(user); } } <file_sep>/assignment3/src/main/java/com/books/assignment3/service/query/OrderQueryService.java package com.books.assignment3.service.query; import com.books.assignment3.dao.OrderDAO; import com.books.assignment3.model.database.BookOrder; import com.books.assignment3.model.database.User; import com.books.assignment3.model.query.BookOrderQueryDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.ArrayList; import java.util.List; @Service @Transactional public class OrderQueryService { private OrderDAO orderDAO; @Autowired public OrderQueryService(OrderDAO orderDAO) { this.orderDAO = orderDAO; } public List<BookOrderQueryDTO> getOrdersForAnUserByEmail(String email){ List<BookOrder> bookOrders = orderDAO.selectOrdersByUsersEmail(email); List<BookOrderQueryDTO> bookOrderQueryDTOS = new ArrayList<>(); for(BookOrder bookOrder: bookOrders){ BookOrderQueryDTO bookOrderQueryDTO = new BookOrderQueryDTO(); bookOrderQueryDTO.setId(bookOrder.getId()); bookOrderQueryDTO.setBook(bookOrder.getBook()); bookOrderQueryDTO.setUser(bookOrder.getUser()); bookOrderQueryDTOS.add(bookOrderQueryDTO); } return bookOrderQueryDTOS; } } <file_sep>/assignment3/src/main/java/com/books/assignment3/decorator/BookDecorator.java package com.books.assignment3.decorator; import com.books.assignment3.model.database.Book; public abstract class BookDecorator implements BookDecoratorInterface { protected Book bookToDecorate; public BookDecorator(Book bookToDecorate) { this.bookToDecorate = bookToDecorate; } @Override public void setNumberOfBooks(int numberOfBooks) { bookToDecorate.setNumberOfBooks(numberOfBooks); } } <file_sep>/assignment2/src/main/java/com/assignment2/demo/model/BookOrder.java package com.assignment2.demo.model; import javax.persistence.*; @Entity @Table public class BookOrder { @Id @Column(name="order_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private int Id; @ManyToOne @JoinColumn(name="user") private User user; @ManyToOne @JoinColumn(name="book") private Book book; @Column(name="book_quantity") private int bookNumber; public BookOrder(){ } public BookOrder(int id, User user, Book book,int bookNumber) { Id = id; this.user = user; this.book = book; this.bookNumber=bookNumber; } @Override public String toString() { return "BookOrder{" + "Id=" + Id + ", userID=" + user + ", bookID=" + book + ", bookNumber=" + bookNumber + '}'+'\n'; } public int getId() { return Id; } public void setId(int id) { Id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public int getBookNumber() { return bookNumber; } public void setBookNumber(int bookNumber) { this.bookNumber = bookNumber; } } <file_sep>/assignment2/src/main/java/com/assignment2/demo/controller/BookController.java package com.assignment2.demo.controller; import com.assignment2.demo.model.Book; import com.assignment2.demo.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; @Controller public class BookController { @Autowired private BookService bookService; @PostMapping("/addBook") public ModelAndView addBook(Book book) { ModelAndView modelAndView = new ModelAndView("insertBookPage"); bookService.addBook(book); return modelAndView; } @GetMapping("/addBook") public ModelAndView displayInsertBookPage() { ModelAndView modelAndView = new ModelAndView("insertBookPage"); modelAndView.addObject("book", new Book()); return modelAndView; } @GetMapping("/books") public ModelAndView displayAllBooks() { ModelAndView modelAndView = new ModelAndView("seeAllBooks"); modelAndView.addObject("books", bookService.seeAllBooks()); return modelAndView; } @GetMapping("/books/author") public ModelAndView selectBookByAuthor(@RequestParam(value = "author") String author) { ModelAndView modelAndView = new ModelAndView("seeBooksByAuthor"); modelAndView.addObject("booksByAuthor", bookService.seeBooksByAuthor(author)); return modelAndView; } @GetMapping("/books/title") public ModelAndView selectBookByTitle(@RequestParam(value = "title") String title) { ModelAndView modelAndView = new ModelAndView("seeBooksByTitle"); modelAndView.addObject("booksByTitle", bookService.seeBooksByTitle(title)); return modelAndView; } @GetMapping("/books/genre") public ModelAndView selectBooksByGenre(@RequestParam(value = "genre") String genre) { ModelAndView modelAndView = new ModelAndView("seeBooksByGenre"); modelAndView.addObject("booksByGenre", bookService.seeBooksByGenre(genre)); return modelAndView; } @GetMapping("/books/year") public ModelAndView selectBooksByYear(@RequestParam(value = "year") int year) { ModelAndView modelAndView = new ModelAndView("seeBooksByYear"); modelAndView.addObject("booksByYear", bookService.seeBooksByRelease(year)); return modelAndView; } @DeleteMapping("/books/{id}") public ModelAndView deleteBook(@PathVariable("id") long id) { ModelAndView modelAndView = new ModelAndView("redirect:/books"); bookService.deleteBook((int) id); return modelAndView; } @GetMapping("/booksU") public ModelAndView displayBooksForUsers() { ModelAndView modelAndView = new ModelAndView("booksSeenByUsers"); modelAndView.addObject("booksSeenByUsers", bookService.seeAllBooks()); return modelAndView; } } <file_sep>/assignment1/src/main/java/bll/StaffBLL.java package bll; import connection.Connection; import dao.BookDAO; import dao.OrderDAO; import dao.StaffDAO; import dao.UserDAO; import model.Staff; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.List; public class StaffBLL { ApplicationContext appContext = new AnnotationConfigApplicationContext(Connection.class); StaffDAO staffs = appContext.getBean("staffDAO", StaffDAO.class); public StaffBLL() { } public Staff selectStaffById(int id){ return staffs.selectStaffById(id); } public List<Staff> selectAllStaff(){ return staffs.selectAll(); } public void insertStaff(Staff staff){ staffs.insertStaff(staff); } public void updateStaff(Staff staff){ staffs.updateStaff(staff); } public void deleteStaffById(int id){ staffs.deleteStaff(id); } } <file_sep>/assignment1/src/main/java/Factory/RecommendationFactory.java package Factory; public class RecommendationFactory { public Recommendations makeRecommendations(String recommendationType){ if(recommendationType==null){ return null; } if(recommendationType.equalsIgnoreCase("trends")){ return new Trends(); } if(recommendationType.equalsIgnoreCase("genres")){ return new Genres(); } return null; } // public static void main(String[] args) { // RecommendationFactory rf = new RecommendationFactory(); // Recommendations obj1 = rf.makeRecommendations("trends"); // Recommendations obj2 = rf.makeRecommendations("genres"); // System.out.println(obj1.getRecommendtation()); // System.out.println(obj2.getRecommendtation()); // } } <file_sep>/assignment3/src/main/java/com/books/assignment3/controller/Query/BookQueryController.java package com.books.assignment3.controller.Query; import com.books.assignment3.model.query.BookQueryDTO; import com.books.assignment3.service.query.BookQueryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class BookQueryController { @Autowired private BookQueryService bookQueryService; @GetMapping("/books") public ModelAndView displayAllBooks() { ModelAndView modelAndView = new ModelAndView("seeAllBooks"); modelAndView.addObject("books", bookQueryService.seeAllBooks()); return modelAndView; } @GetMapping("/addBook") public ModelAndView displayInsertBookPage() { ModelAndView modelAndView = new ModelAndView("insertBookPage"); modelAndView.addObject("book", new BookQueryDTO()); return modelAndView; } @GetMapping("/booksU") public ModelAndView displayBooksForUsers() { ModelAndView modelAndView = new ModelAndView("booksSeenByUsers"); modelAndView.addObject("booksSeenByUsers", bookQueryService.seeAllBooks()); return modelAndView; } }
749868ee6f3a74d7ec0f10c0c7fd7c2d6fd52d8a
[ "Java" ]
21
Java
sd-2019-30238/assignment-1-lucadanadrian
59c9f093e4090ff9a7c8fa172499d8b288203a45
c99e0e206b7cfb2c3f004a7e8c86a475a3fd71cb
refs/heads/master
<repo_name>alexishiniker/NasaImages-Starter<file_sep>/README.md # NasaImages-Starter Add your API key retrieved from: https://api.nasa.gov/ <file_sep>/app/src/main/java/edu/washington/recyclednasaimages/NasaContentDownloader.kt package edu.washington.recyclednasaimages import android.content.Context import android.graphics.Bitmap import android.util.LruCache import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.ImageLoader import com.android.volley.toolbox.Volley class NasaContentDownloader { companion object { private var mRequestQueue: RequestQueue? = null fun requestQueue(c: Context): RequestQueue { if (mRequestQueue == null) { mRequestQueue = Volley.newRequestQueue(c) } return mRequestQueue as RequestQueue } } }<file_sep>/app/src/main/java/edu/washington/recyclednasaimages/MainActivity.kt package edu.washington.recyclednasaimages import android.content.Context import android.graphics.Bitmap import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import android.widget.Toast import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.toolbox.ImageRequest import com.android.volley.toolbox.JsonObjectRequest import kotlinx.android.synthetic.main.activity_main.* import java.text.DateFormat import java.text.SimpleDateFormat import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.* const val NUMBER_OF_DAYS = 30 class MainActivity : AppCompatActivity() { var astronomyItems = mutableListOf<AstronomyData>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) populateAstronomyDates() } private fun populateAstronomyDates() { for (i in 1..NUMBER_OF_DAYS) { // Accommodate NASA APOD date formatting var dateString = getString(R.string.date_base) + i.toString().padStart(2, '0') val request = JsonObjectRequest( Request.Method.GET, nasaUriBuilder(dateString), null, Response.Listener { response -> astronomyItems.add(parseAstronomyData(response)) (list_view_astronomy_data.adapter as ArrayAdapter<AstronomyData>).notifyDataSetChanged()}, Response.ErrorListener { error -> val toast = Toast.makeText(this, "$error: ${error.message.toString()}", Toast.LENGTH_SHORT) toast.show() }) NasaContentDownloader.requestQueue(applicationContext).add(request) } list_view_astronomy_data.adapter = AstronomyAdapter(this, astronomyItems) } private fun nasaUriBuilder(date: String): String? { val builder = Uri.Builder() builder.scheme("https").authority(getString(R.string.url_base)) for (s in resources.getStringArray(R.array.url_paths)) { builder.appendPath(s) } builder.appendQueryParameter("api_key", getString(R.string.api_key)) .appendQueryParameter("date", date) return builder.toString() } inner class AstronomyAdapter(c: Context, data: MutableList<AstronomyData>) : ArrayAdapter<AstronomyData>(c, R.layout.astronomy_item, data) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var updatedView = convertView if (updatedView == null) { updatedView = layoutInflater.inflate(R.layout.astronomy_item, parent, false) } updatedView!!.findViewById<TextView>(R.id.title)!!.text = (getItem(position) as AstronomyData).title return updatedView as View } } } <file_sep>/app/src/main/java/edu/washington/recyclednasaimages/AstronomyData.kt package edu.washington.recyclednasaimages import android.webkit.URLUtil import org.json.JSONObject data class AstronomyData( val title: String, val urlString: String?, val explanation: String) fun parseAstronomyData(astronomyJson: JSONObject): AstronomyData { var urlString: String? = astronomyJson.getString("url") if (urlString == "null" || !URLUtil.isValidUrl(urlString)) { urlString = null } var title = astronomyJson.getString("title") var explanation = astronomyJson.getString("explanation") return AstronomyData(title, urlString, explanation) }
9964c30e0e7b765fab1d6c6a07b44d17d727ffd6
[ "Markdown", "Kotlin" ]
4
Markdown
alexishiniker/NasaImages-Starter
240372e697de23ca604bc195f238072091814105
ec66d772e21bd0e4bfc8a91d64358df97c47cb5a
refs/heads/master
<repo_name>sjwoods/python-challenge<file_sep>/PyBank/main.py import csv import os budget_data = os.path.join('..', 'PyBank', 'budget_data.csv') total_months = [] total_profit = [] monthly_profit = [] with open(budget_data, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter= ",") csv_header = next(csvreader) for row in csvreader: total_months.append(row[0]) total_profit.append(int(row[1])) for i in range(len(total_profit)-1): monthly_profit.append(total_profit[i+1]-total_profit[i]) max_increase_value = max(monthly_profit) max_decrease_value = min(monthly_profit) max_increase_month = monthly_profit.index(max(monthly_profit)) + 1 max_decrease_month = monthly_profit.index(min(monthly_profit)) + 1 print("Financial Analysis") print("----------------------------------") print(f"Total Months: {len(total_months)}") print(f"Total: ${sum(total_profit)}") print(f"Average Change: {round(sum(monthly_profit)/len(monthly_profit),2)}") print(f"Greatest Increase in Profits: {total_months[max_increase_month]} (${(str(max_increase_value))})") print(f"Greatest Decrease in Profits: {total_months[max_decrease_month]} (${(str(max_decrease_value))})") output_file = ("Financial_Analysis.txt") with open(output_file, "w") as file: file.write("Financial Analysis") file.write("/n") file.write(f"Total Months: {len(total_months)}") file.write("/n") file.write("Total: ${sum(total_profit)}") file.write("/n") file.write("Average Change: {round(sum(monthly_profit)/len(monthly_profit),2)}") file.write("/n") file.write("Greatest Increase in Profits: {total_months[max_increase_month]} (${(str(max_increase_value))})") file.write("/n") file.write(f"Greatest Decrease in Profits: {total_months[max_decrease_month]} (${(str(max_decrease_value))})") <file_sep>/PyPoll/main.py import csv import os election_data = os.path.join('..', 'PyPoll', 'election_data.csv') total_votes = 0 khan_votes = 0 correy_votes = 0 li_votes = 0 otooley_votes = 0 with open(election_data, newline= "") as csvfile: csvreader = csv.reader(csvfile, delimiter= ",") csv_header = next(csvreader) for row in csvreader: total_votes +=1 if row[2] == "Khan": khan_votes +=1 elif row[2] == "Correy": correy_votes +=1 elif row[2] == "Li": li_votes +=1 elif row [2] == "O'Tooley": otooley_votes +=1 candidates = ["Khan", "Correy", "Li", "O'Tooley"] votes = [khan_votes, correy_votes, li_votes, otooley_votes] candidates_and_votes = dict(zip(candidates, votes)) key = max(candidates_and_votes, key = candidates_and_votes.get) khan_percent = (khan_votes/total_votes) *100 correy_percent = (correy_votes/total_votes) *100 li_percent = (li_votes/total_votes) *100 otooley_percent = (otooley_votes/total_votes) *100 print(f"Election Results") print(f"---------------------------") print(f"Total Votes: {total_votes}") print(f"---------------------------") print(f"Khan: {khan_percent:.3f}% ({khan_votes})") print(f"Correy: {correy_percent:.3f}% ({correy_votes})") print(f"Li: {li_percent:.3f}% ({li_votes})") print(f"O'Tooley:{otooley_percent:.3f}% ({otooley_votes})") print(f"---------------------------") print(f"Winner: {key}") print(f"---------------------------")
b1de7b41835aae2da02d2beba65aa99628a976d8
[ "Python" ]
2
Python
sjwoods/python-challenge
d92a041858fdac38d63255feddd570adccb1a3ca
56eda441ddd80a0d45004eb845bc2124bdc4d933
refs/heads/main
<repo_name>luronava/portafolio-progra-II<file_sep>/Ejercicios/src/Parte4/main.java package Parte4; public class main { public static void main(String[] args) { for (int i = 0; i < 20; i++) { System.out.println(Random.getValor()); } } } <file_sep>/Ejercicios/src/Parte5/BalónDeFútbolAmericano.java package Parte5; public class BalónDeFútbolAmericano extends Bola { private String equipo; public BalónDeFútbolAmericano() { forma ="ovalado"; } } <file_sep>/Ejercicios/src/Parte7/CuentaCheque.java package Parte7; public class CuentaCheque extends Cuenta { public CuentaCheque(int numeroCuenta, String cliente) { super(numeroCuenta, cliente); } public boolean retirar(double cantidad) { balance -= cantidad; return true; } } <file_sep>/Ejercicios/src/Parte1/Cuenta.java package Parte1; public class Cuenta { private double saldo; public double getSaldo() { return saldo; } public void setSaldo(double saldo) { this.saldo = saldo; } public double depositar(double cantidad) { return saldo+=cantidad; } public boolean retirar(double cantidad) { if(saldo-cantidad>=0) { saldo-=cantidad; return true; }else { return false; } } } <file_sep>/Ejercicios/src/Parte2/Tanteador.java package Parte2; public class Tanteador { private int puntuacion; public Tanteador() { puntuacion = 0; } public int getPuntuacion() { return puntuacion; } public void setPuntuacion(int puntuacion) { this.puntuacion = puntuacion; } public void mostrarPuntuacion() { System.out.println("Puntuacion: "+puntuacion); } public void incrementrar() { puntuacion++; } public void decrementar() { puntuacion--; } public void reiniciar() { puntuacion=0; } } <file_sep>/Ejercicios/src/Parte6/Pelota.java package Parte6; public class Pelota{ protected double size; protected String color; protected String forma ; protected String material; protected String tipo; protected String peso; public Pelota() { } public double getSize() { return size; } public void setSize(double size) { this.size = size; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getForma() { return forma; } public void setForma(String forma) { this.forma = forma; } public String getMaterial() { return material; } public void setMaterial(String material) { this.material = material; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public String getPeso() { return peso; } public void setPeso(String peso) { this.peso = peso; } }
81caf82995ad2ff0c9819f8972256e3d02e23ecc
[ "Java" ]
6
Java
luronava/portafolio-progra-II
fc7a3362ce0c12e252b59c21153b059d696d0a56
56bf2773945fdc149c9076e8ed2c5a79b4efd7a3
refs/heads/master
<file_sep>import React from 'react' export default function AppFocusLog(props) { if (props.isLoading) return null if (!props.log) return null // const lines = props.log.split('\n').map((line, idx) => <p key={idx}>{line}</p>) return ( <div className="container"> <h3>Logs</h3> <div className="Codeblock"> {lines} </div> </div> ) }<file_sep>import React from 'react' import Tooltip from '@material-ui/core/Tooltip' import { StatusIcon, StatusIconList } from '../components/StatusIcon' import LastBuild from '../components/LastBuild' import Duration from '../components/Duration' export default function AppFocusTable (props) { if (props.isLoading) return null if (!props.app) return null // const name = props.app.appName const status = props.app.status.applicationState.state function getNbExecutorsLabel () { if (!props.app.status.executorState) return '' const count = Object.keys(props.app.status.executorState).length if (count > 1) return `${count} executors` return `${count} executor` } return ( <div className="table"> <div className="table__row"> <div className="table__row__cell table__row__cell--label"> Status: </div> <div className="table__row__cell table__row__cell--value"> <StatusIcon status={status} name={name} /> </div> </div> <div className="table__row"> <div className="table__row__cell table__row__cell--label"> Executors: </div> <Tooltip title={getNbExecutorsLabel()} arrow> <div className="table__row__cell table__row__cell--value"> <StatusIconList value={props.app.status.executorState} /> </div> </Tooltip> </div> <div className="table__row"> <div className="table__row__cell table__row__cell--label"> Duration: </div> <div className="table__row__cell table__row__cell--value"> <Duration startAt={props.app.status.lastSubmissionAttemptTime} endAt={props.app.status.terminationTime} /> </div> </div> <div className="table__row"> <div className="table__row__cell table__row__cell--label"> Last build: </div> <div className="table__row__cell table__row__cell--value"> <LastBuild value={props.app.status.lastSubmissionAttemptTime} /> </div> </div> </div> ) }<file_sep>import React from 'react' import Tooltip from '@material-ui/core/Tooltip' import { StatusIcon, StatusIconList } from './StatusIcon' import LastBuild from './LastBuild' import Duration from './Duration' import Button from './Button' import { COMPLETED, RUNNING, PENDING, FAILED } from '../utils' class AppRow extends React.Component { constructor(props) { super(props) this.handleClick = this.handleClick.bind(this) this.state = { isLoading: false } } getCTA() { if ([RUNNING, PENDING].includes(this.props.app.status.applicationState.state)) { return <Button title="Stop" icon="StopIcon" onClick={this.handleClick.bind(this)} /> } if ([COMPLETED, FAILED].includes(this.props.app.status.applicationState.state)) { return <Button title="Delete" icon="DeleteIcon" onClick={this.handleClick.bind(this)} /> } } handleClick(action) { if (action === 'stop') this.props.onStop() else if (action === 'delete') { this.setState({ isDeleting: true }) this.props.onDelete() } } getNbExecutorsLabel() { if (!this.props.app.status.executorState) return '' const count = Object.keys(this.props.app.status.executorState).length if (count > 1) return `${count} executors` return `${count} executor` } render() { const name = this.props.app.appName const status = this.props.app.status.applicationState.state // return ( <div className="table__row"> <div className="table__row__cell table__row__cell--status"> <StatusIcon to={`/apps/${name}`} status={status} name={name} /> </div> <Tooltip title={this.getNbExecutorsLabel()} arrow> <div className="table__row__cell table__row__cell--executors"> <StatusIconList value={this.props.app.status.executorState} /> </div> </Tooltip> <div className="table__row__cell table__row__cell--duration"> <Duration startAt={this.props.app.status.lastSubmissionAttemptTime} endAt={this.props.app.status.terminationTime} /> <LastBuild value={this.props.app.status.lastSubmissionAttemptTime} /> </div> <div className="table__row__cell table__row__cell--cta"> {this.getCTA()} </div> </div> ) } } export default class AppsTable extends React.Component { constructor(props) { super(props) this.handleStop = this.handleStop.bind(this) this.handleDelete = this.handleDelete.bind(this) } handleStop(appName) { this.props.onStop(appName) } handleDelete(appName) { this.props.onDelete(appName) } render() { if (this.props.isLoading) { return null } // const tableRows = this.props.apps.filter(app => { if (this.props.statusFilter === '') return true // return all if not set return app.status.applicationState.state === this.props.statusFilter // only return the ones we want }).map((app) => <AppRow key={app.appName} app={app} status={app.status.applicationState.state} onStop={this.handleStop.bind(this, app.appName)} onDelete={this.handleDelete.bind(this, app.appName)} /> ) return ( <React.Fragment> <div className="table__row table__row--header"> <div className="table__row__cell table__row__cell--status"> <span>Status</span> </div> <div className="table__row__cell table__row__cell--executors"> <span>Executors</span> </div> <div className="table__row__cell table__row__cell--duration"></div> <div className="table__row__cell table__row__cell--cta"></div> </div> {tableRows} </React.Fragment> ) } }<file_sep>import React from 'react' import Spinner from 'react-loader-spinner' import 'react-loader-spinner/dist/loader/css/react-spinner-loader.css' export default class Loader extends React.Component { render() { if (!this.props.isLoading) return null // return ( <div className="container container--center"><h3> <Spinner type="TailSpin" color="#282c34" height={40} width={100} /></h3> </div> ) } }<file_sep>import React from 'react' import { NavLink } from 'react-router-dom' import HourglassEmptyIcon from '@material-ui/icons/HourglassEmpty' import CloseIcon from '@material-ui/icons/Close' import CheckIcon from '@material-ui/icons/Check' import TimelapseIcon from '@material-ui/icons/Timelapse' import Tooltip from '@material-ui/core/Tooltip' import { COMPLETED, RUNNING, PENDING, FAILED } from '../utils' export const StatusIcon = function (props) { let icon; if (props.status === COMPLETED) icon = <CheckIcon fontSize="small" /> else if (props.status === RUNNING) icon = <TimelapseIcon fontSize="small" /> else if (props.status === PENDING) icon = <HourglassEmptyIcon fontSize="small" /> else if (props.status === FAILED) icon = <CloseIcon fontSize="small" /> // if (props.to == null) return ( <div className={`StatusIcon StatusIcon--slim StatusIcon--${props.status.toLowerCase()}`}> <Tooltip title={props.name.toLowerCase()} arrow>{icon}</Tooltip> </div> ) // return ( <div className={`StatusIcon StatusIcon--${props.status.toLowerCase()}`}> <Tooltip title={props.name.toLowerCase()} arrow> <NavLink to={props.to}> {icon}<span>{props.status.toLowerCase()}</span> </NavLink> </Tooltip> </div> ) } export const StatusIconList = function (props) { if (props.value == null) return null // const executors = Object.keys(props.value).map(key => { const status = props.value[key] return <StatusIcon key={key} name={key} status={status} /> }) return ( <React.Fragment> {executors} </React.Fragment> ) } <file_sep>import React from 'react' import { COMPLETED, RUNNING, PENDING, FAILED } from '../utils' export default class Filters extends React.Component { constructor(props) { super(props) this.handleClick = this.handleClick.bind(this) this.state = { statuses: [COMPLETED, RUNNING, PENDING, FAILED] } } handleClick(status) { this.props.onFilter(status) } getNbApps(status) { return this.props.apps.filter(x => x.status.applicationState.state === status).length } getClass(status) { if (this.props.statusFilter === status) return 'Button Button--active' return 'Button' } render() { if (this.props.isLoading) { return null } // const filters = this.state.statuses.map(status => { return <button className={this.getClass(status)} onClick={this.handleClick.bind(this, status)} key={status}>{status.toLowerCase()} <em className="Button__badge">{this.getNbApps(status)}</em></button> }) return ( <div className="Filters"> <button className={this.getClass('')} onClick={this.handleClick.bind(this, '')}>All <em className="Button__badge">{this.props.apps.length}</em></button> {filters} </div> ) } }<file_sep>import React from 'react' import StopIcon from '@material-ui/icons/Stop' import DeleteOutlineIcon from '@material-ui/icons/DeleteOutline'; import RefreshIcon from '@material-ui/icons/Refresh' import Tooltip from '@material-ui/core/Tooltip' export default class Button extends React.Component { constructor(props) { super(props) this.handleClick = this.handleClick.bind(this) } handleClick(action) { this.props.onClick(action) } render() { let icon let eventName if (this.props.icon === 'StopIcon') { icon = <StopIcon /> eventName = 'stop' } else if (this.props.icon === 'DeleteIcon') { icon = <DeleteOutlineIcon /> eventName = 'delete' } else if (this.props.icon === 'RefreshIcon') { icon = <RefreshIcon /> eventName = 'refresh' } const button = <button className="Button" onClick={this.handleClick.bind(this, eventName)}>{icon}</button> if (!this.props.title) return button // return ( <Tooltip title={this.props.title} arrow> {button} </Tooltip> ) } } <file_sep>// react import React from 'react' import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom' import CssBaseline from '@material-ui/core/CssBaseline' // styles import './App.scss' // home-brewed import AppsList from './pages/AppsList.js' import AppFocus from './pages/AppFocus.js' import Nav from './layouts/Nav.js' function App() { return ( <div className="App"> <CssBaseline /> <Router> <header> <Nav /> </header> <main className="App-main"> <Switch> <Route exact path="/apps/:appName" component={AppFocus} /> <Route exact path="/apps" component={AppsList} /> <Route exact path="/"> <Redirect to="/apps" /> </Route> <Route> <Redirect to="/apps/" /> </Route> </Switch> </main> </Router> </div> ) } export default App <file_sep>import React from 'react' import moment from 'moment' import Tooltip from '@material-ui/core/Tooltip' import EventIcon from '@material-ui/icons/Event' export default function LastBuild (props) { const text = moment(props.value).fromNow() // return ( <React.Fragment> <Tooltip title={props.value} arrow> <div className="LastBuild"> <EventIcon /><span>{text}</span> </div> </Tooltip> </React.Fragment> ) } <file_sep>import React from 'react' import TimerIcon from '@material-ui/icons/Timer' import { getHumanDuration } from '../utils' export default function Duration (props) { let text = '' const { startAt, endAt } = props if (endAt) { text = getHumanDuration({ startAt, endAt }) } // return ( <React.Fragment> <div className="Duration"> <TimerIcon /><span>{text}</span> </div> </React.Fragment> ) }
13644c6326b837d1990860ce8261b32a79899efc
[ "JavaScript" ]
10
JavaScript
MichaelTSS/data-mechanics
80123347f8fdf13436a1f3313b2fd2e24a891776
3654d5d1ab8bf37499067be0473de4b9223077a9
refs/heads/master
<repo_name>cquito2/recentCode<file_sep>/README.md # recentCode this is repository to display all the current code I have worked on <file_sep>/BST/Node.java //=========================================================== // <NAME> 9.16.2019 // Node class to be used in BTS class //=========================================================== public class Node { private int data; private Node right; private Node left; public Node (int val) { this.data = val; } public int getData() { return this.data; } public Node getRight() { return this.right; } public Node getLeft() { return this.left; } public void setLeft(Node lAdd) { //Node lAdd = new Node (val); this.left = lAdd; } public void setRight(Node rAdd) { //Node rAdd = new Node (val); this.right = rAdd; } }<file_sep>/LinkedList/Node.java //================================================================ //<NAME> // basic implementation of a integer Node class //================================================================ package LinkedList; public class Node { int data; Node next; public Node() {}; public Node(int toSet){ //set instance variable // next can be left alone as it should be null this.data = toSet; } public int getNode() { return this.data; } }
3372d5caa5ceff2c02f782f06c783a578e488e7d
[ "Markdown", "Java" ]
3
Markdown
cquito2/recentCode
b2dfab68aa0392c7a601f8dae9d830b8205aff33
87b2bf17bfa40c5cff892d1dae8225637ed54411
refs/heads/main
<repo_name>trinhhungfischer/GEP<file_sep>/Cart-pole-v0/Cart_pole_v0.py """ ||========================================================|| || This is my label for every program which coded by Hung || ||========================================================|| """ import gym import random import matplotlib.pyplot as plt from statistics import mean env = gym.make("CartPole-v0") env.reset() # Some constant in this program NUM_GENS = 1000 TIMESTEP_LIMIT = 1000 class GeneticOperator: def __init__(self, pm=.1, pc=.1, pc1=.4, pc2=.7, pis=.4, pris=.4, pi=.1): self.pm = pm self.pi = pi self.pc = pc self.pc1 = pc1 self.pc2 = pc2 self.pis = pis self.pris = pris def mutation(self, population=[]): NP = len(population) for i in range(NP): mutated = list(population[i]) # Mutated each chromosome in population for j in range(len(mutated)): r = random.random() if r < self.pm: mutated[j] = random.choice(['0', '1']) population.append(''.join(mutated)) return population def inversion(self, population=[]): NP = len(population) for i in range(NP): if random.random() < self.pi: position = random.choices(range(len(population[i])), k=2) crack1, crack2 = min(position), max(position) new_gene = population[i][:crack1] + population[i][crack2:crack1:-1] \ + population[i][crack2:] population.append(new_gene) return population def is_transportation(self, population=[]): NP = len(population) for i in range(NP): if random.random() < self.pis: j = random.choice(range(NP)) # i-th individual is the trans gene which received IS # j-th individual is the ori gene which cut its IS position = random.choices(range(len(population[j])), k=2) crack1, crack2 = min(position), max(position) k = crack2 - crack1 # Find pos trans in the receive gene to insert pos_trans = random.randint(1, len(population[i]) - k) new_gene = population[i][0:pos_trans] + population[j][crack1:crack2] + \ population[i][pos_trans + k:] population.append(new_gene) return population def ris_transportation(self, population=[]): NP = len(population) for i in range(NP): if random.random() < self.pris: j = random.choice(range(NP)) # i-th individual is the trans gene which received IS # j-th individual is the ori gene which cut its IS crack1, k = random.choices(range(int(len(population[j]) / 2)), k=2) crack1 = random.choice(range(int(len(population[j]) / 2))) new_gene = population[j][crack1:crack1 + k] + population[i][k:] population.append(new_gene) return population def crossover_1point(self, population=[]): NP = len(population) for i in range(int(NP / 2)): cr1 = random.random() if cr1 < self.pc: chrome1, chrome2 = random.choices(population, k=2) crack = random.randint(0, len(chrome1)) c1_new = chrome1[:crack] + chrome2[crack:] c2_new = chrome2[:crack] + chrome1[crack:] population.append(c1_new) population.append(c2_new) return population def crossover(self, population=[], best=''): NP = len(population) for i in range(int(NP / 2)): cr1 = random.random() if cr1 < self.pc1: chrome1 = best chrome2 = random.choice(population) crack = random.randint(0, len(chrome1)) c1_new = chrome1[:crack] + chrome2[crack:] c2_new = chrome2[:crack] + chrome1[crack:] population.append(c1_new) population.append(c2_new) return population def crossover_2point(self, population=[]): NP = len(population) for i in range(int(NP / 2)): cr2 = random.random() if cr2 < self.pc2: chrome1, chrome2 = random.choices(population, k=2) position = random.choices(range(len(chrome1)), k=2) crack1, crack2 = min(position), max(position) c1_new = chrome1[:crack1] + chrome2[crack1:crack2] + chrome1[crack2:] c2_new = chrome2[:crack1] + chrome1[crack1:crack2] + chrome2[crack2:] population.append(c1_new) population.append(c2_new) return population def pause(population=[]): list = fitness(population) for i in range(len(population)): if (list[i] == 1500): return True, i, '', 0 max1 = max(list) i_max = list.index(max1) return False, max1, population[i_max], mean(list) def init_population(NP=50): pop = [] for i in range(NP): ind = '' for j in range(TIMESTEP_LIMIT): ind += random.choice(['0', '1']) pop.append(ind) return pop def evaluate_fitness(ind=''): observation = env.reset() score = 0 env.seed(0) for t in range(TIMESTEP_LIMIT): observation, reward, done, info = env.step(int(ind[t])) if done: break score += reward return score # First we will evaluate of fitness function of all individual in # this generation which will store in list def fitness(population=[]): fitness = [] for i in range(len(population)): fitness.append(evaluate_fitness(population[i])) return fitness def roulette_selection(population=[], num=50): fit_list = fitness(population) s = sum(fit_list) l = len(fit_list) # probability chosen of individual p_chosen = list(ind / s for ind in fit_list) q_list = [] for i in range(len(population)): q_list.append(sum(p_chosen[:i])) new = [] # This list is to store new generations it = 0 # Number of iteration of roulette wheel while it < num: r = random.random() for id in range(l): if q_list[id] > r: break new.append(population[id - 1]) it += 1 return new def rank_selection(population=[], NP=50): Y = fitness(population) zip_list = zip(Y, population) sorted_pairs = sorted(zip_list, reverse=True) tuples = zip(*sorted_pairs) Y, Z = [list(tuple) for tuple in tuples] return Z[:NP] """ This function is main of this program to demonstrate Genetic Expression Programming in real life """ # Statistic def GA_model(): GA = GeneticOperator(0.5, 0.01) population = init_population(500) gen = 1 fitness_history_max = [] fitness_history_mean = [] while (gen <= NUM_GENS): parent = rank_selection(population, 100) done, fit_max, best, fit_mean = pause(population) if done: break fitness_history_max.append(fit_max) fitness_history_mean.append(fit_mean) print('This is gen {} has best ind {} has mean {}'.format(gen, fit_max, fit_mean)) # env.reset() # for t in range(TIMESTEP_LIMIT): # observation, reward, done, info = env.step(int(best[t])) # env.render() # if done: # break mutant = GA.mutation(parent) off_string = GA.crossover_1point(mutant) population = off_string gen += 1 return fitness_history_max, fitness_history_mean if __name__ == '__main__': fitness_history_max, fitness_history_mean = GA_model() plt.plot(list(range(NUM_GENS)), fitness_history_mean, label='Mean Fitness') plt.plot(list(range(NUM_GENS)), fitness_history_max, label='Max Fitness') plt.legend() plt.title('Fitness through the generations') plt.xlabel('Generations') plt.ylabel('Fitness') plt.show() <file_sep>/README.md # GEP Gene Expression Programming - This is all file of GEP to solve Symbolic Regression with individual benchmark. The main program is GEP to perform algorithms in Symbolic Regression The other of this repo is the GEP which used to solve cart pole problem <file_sep>/Traditional/Selection.py """ ||========================================================|| || This is my label for every program which coded by Hung || ||========================================================|| """ from Encode_Evaluate import RMSE, valid_chromosome from Initialization import init_population from random import random # Some constants in this program population = init_population(50) NP = 50 # First we will evaluate of fitness function of all individual in # this generation which will store in list def fitness(population = []): fitness = [] i = 0 while i < len(population): try: fitness.append(RMSE(population[i])) i += 1 except Exception as error: population.pop(i) return fitness def one_minus_similarity(chrome1 = '', chrome2 = ''): s1, l1 = valid_chromosome(chrome1) s2, l2 = valid_chromosome(chrome2) overlap = sum(1 for i in range(min(l1, l2)) if s1[i] == s2[i]) return 1 - 2.0 * overlap / (l1 + l2) def q_roulette_wheel(population = []): fit = fitness(population) best = fit[0] i_best = 0 for i in range(len(fit)): if fit[i] < best: best = fit[i] i_best = i p = [] s = 0 for i in range(len(fit)): # Make iteration of roulette wheel is NP pi = one_minus_similarity(population[i_best], population[i]) s += pi p.append(pi) for i in range(len(fit)): p[i] /= s q = [] for i in range(len(fit)): # Make iteration of roulette wheel is NP q.append(sum(p[:i+1])) return q def roulette_wheel_selection(population = []): q_list = q_roulette_wheel(population) l = len(q_list) new = [] it = 0 while it < NP: r = random() for i in range(l): if q_list[i] > r: break new.append(population[i-1]) it += 1 return new def rank_selection(population = []): Y = fitness(population) Z = [x for _, x in sorted(zip(Y, population))] if len(Z) <= 50: K = Z return Z else: K = Z[:50] return Z[:50] # This function decide kind of select to choose def selection(population = []): return roulette_wheel_selection(population) if __name__ == '__main__': pass<file_sep>/Traditional/Initialization.py """ ||========================================================|| || This is my label for every program which coded by Hung || ||========================================================|| """ # Python program to create random chromosome import random # Function node set is {+,-,*,/,sqrt(Q),exp(E),sin(s)} # Terminal node set is {x, y} head_set = list('+-*/QEsx') ter_set = ['x'] # Make a seed to reuse a random population random.seed(7) # Traditional method to randomly assign to each element of chromosome # Depend on its position in chromosome (head, tail) def init_one(h = 10): str = [] for i in range (h): ele = random.choice(head_set) str.append(ele) for i in range (h + 1): ele = random.choice(ter_set) str.append(ele) return ''.join(str) def init_population(NP = 50, h = 10): pop = [] for i in range (NP): pop.append(init_one(h)) return pop <file_sep>/Traditional/GEP.py """ ||========================================================|| || This is my label for every program which coded by Hung || ||========================================================|| """ from Encode_Evaluate import RMSE from Initialization import init_population from Reproduction import reproduction from time import time start_time = time() NR = 100 # Number of run NG = 2000 # Number of generation # Defining some constant of evolution operator NP = 50 # Number of individuals in first initial population h = 10 # Number of head elements in each chromosome pm = .1 # Probability of mutation pc1 = .7 # Probability of cross-over 1 point pc2 = .7 # Probability of cross-over 2 point pi = .1 # Probability of inversion pis = .1 # Probability of insertion sequence pris = .1 # Probability of root insertion sequence ng = 1 # Number of gene perfect_hit = 0.01 # The RMSE will converge if it is less than perfect hit # This function return false when terminate condition is wrong def converge_con(populaion = [], perfect_hit = 0.01): for chrome in populaion: try: if RMSE(chrome) < perfect_hit: return True, chrome except Exception as error: pass return False, 1 # This function demonstrate one run def each_run(): # Initializing first random population as parent population = init_population(NP, h) # This loop is iteration of preproduction, each generation # has been referred to reproduction function generation = 1 while (not converge_con(population, perfect_hit)[0]) and (generation < NG): print('generation {} in time: {}'.format(generation, time() - start_time)) print(population) population = reproduction(population, pm, pc1, pc2, pis, pris, pi) generation += 1 # Print the next generation and its index (optional) print('This is generation {} in time: {}'.format(generation, time() - start_time)) print(population) print('The solution is ', converge_con(population)[1]) return converge_con(population)[0] """ This is main part of program to demonstrate GEP efficient in practical by success rate """ if __name__ == '__main__': suc = 0 for i in range(NR): print("THIS IS THE RUN", i+1) if each_run(): suc += 1 print('Success rate in 100 runs is', suc, '%') <file_sep>/Traditional/Training_set.py """ ||========================================================|| || This is my label for every program which coded by Hung || ||========================================================|| """ import numpy as np from random import random, seed # Some constants in this program NT = 200 # Number of test case # seed(7) # Make one set of random number to reuse def target_function(x, y): return x**4 + x**3 + x**2 + x def xy_create(): input = np.random.uniform(-10, 10, (NT, 2)) return input * 10 def training_create(): input = xy_create() x = input[:, 0].reshape((-1, 1)) y = input[:, 1].reshape((-1, 1)) reslut = target_function(x, y) return np.concatenate((input, reslut), axis=1) if __name__ == '__main__': print(training_create())<file_sep>/Traditional/Reproduction.py """ ||========================================================|| || This is my label for every program which coded by Hung || ||========================================================|| """ # Python program to build and evaluate expression tree # Function node set is {+,-,*,/,sqrt(Q),exp(E),sin(s)} # Terminal node set is {x, y, ?} from random import random, choice, choices, randint, getstate from Initialization import init_population from Selection import selection # Some constants in this program population = init_population() head_set = list('+-*/QEsx') func_set = list('+-*/QEs') ter_set = ['x'] h = 10 def mutation(population = [], pm = .1): NP = len(population) for i in range(NP): mutated = list(population[i]) # Mutated each chromosome in population for i in range(len(mutated)): r = random() if r < pm: if i < h: mutated[i] = choice(head_set) else: mutated[i] = choice(ter_set) population[i] = ''.join(mutated) return population def inversion(population = [], pi = .1): NP = len(population) for i in range (NP): if random() < pi: position = choices(range(len(population[i])), k=2) crack1, crack2 = min(position), max(position) new_gene = population[i][:crack1] + population[i][crack2:crack1:-1]\ + population[i][crack2:] population[i] = new_gene return population # Transportation step of evolution operators def is_transportation(population = [], pis = .1): NP = len(population) for i in range(NP): if random() < pis: j = choice(range(NP)) # i-th individual is the trans gene which received IS # j-th individual is the ori gene which cut its IS position = choices(range(len(population[j])), k=2) crack1, crack2 = min(position), max(position) k = crack2 - crack1 # Find pos trans in the receive gene to insert pos_trans = randint(1, len(population[i]) - k) new_gene = population[i][0:pos_trans] + population[j][crack1:crack2] + \ population[i][pos_trans + k:] population[i] = new_gene return population def ris_transportation(population = [], pris = .1): NP = len(population) for i in range(NP): if random() < pris: j = choice(range(NP)) # i-th individual is the trans gene which received IS # j-th individual is the ori gene which cut its IS crack1, k = choices(range(int(len(population[j]) / 2)), k=2) while ter_set.count(population[j][crack1]): crack1 = choice(range(int(len(population[j]) / 2))) new_gene = population[j][crack1:crack1+k] + population[i][k:] population[i] = new_gene return population # Recombination step of evolution operators def crossover_1point(population = [], pc1 = .7): NP = len(population) for i in range(int(NP/2)): cr1 = random() if cr1 < pc1: chrome1, chrome2 = choices(population, k=2) crack = randint(0, len(chrome1)) c1_new = chrome1[:crack] + chrome2[crack:] c2_new = chrome2[:crack] + chrome1[crack:] population.append(c1_new) population.append(c2_new) return population def crossover_2point(population = [], pc2 = .7): NP = len(population) for i in range(int(NP / 2)): cr2 = random() if cr2 < pc2: chrome1, chrome2 = choices(population, k=2) position = choices(range(len(chrome1)), k=2) crack1, crack2 = min(position), max(position) c1_new = chrome1[:crack1] + chrome2[crack1:crack2] + chrome1[crack2:] c2_new = chrome2[:crack1] + chrome1[crack1:crack2] + chrome2[crack2:] population.append(c1_new) population.append(c2_new) return population def reproduction(population=[], pm=.1, pc1=.7, pc2=.7, \ pis=.1, pris=.1, pi=.1): next_mutated = mutation(population, pm) next_inversed = inversion(next_mutated, pi) next_is_trans = is_transportation(next_inversed, pis) next_ris_trans = ris_transportation(next_is_trans, pris) next_cr1 = crossover_1point(next_ris_trans, pc1) next_cr2 = crossover_2point(next_cr1, pc2) next = selection(next_cr2) return next if __name__ == '__main__': population = init_population() print(population) print(inversion(population))<file_sep>/Traditional/Encode_Evaluate.py """ ||========================================================|| || This is my label for every program which coded by Hung || ||========================================================|| """ # Python program to build and evaluate expression tree # Function node set is {+,-,*,/,sqrt(Q),exp(E),sin(s)} # Terminal node set is {x, y, ?} # An expression tree node # Import some package into this program import math import numpy as np from Training_set import training_create # Some constant in this program terminal_set = ['x', 'y'] # This class refer to a node of expression tree class ET: def __init__(self, data): self.data = data self.maxchild = int(is_operator(data)) self.child = list() # Breadth-first Travelling Search return function node not full def breadth_fisrt_travel(self): queue = [self] while len(queue): node = queue.pop(0) if (len(node.child) < node.maxchild): return node for node_child in node.child: queue.append(node_child) return ET(0) # Calculate a tree with one parameter is root and other is value set def calculate(self, value_set = []): v = value_set if self.maxchild == 2: x0 = self.child[0] x1 = self.child[1] if self.data == '+': return x0.calculate(v) + x1.calculate(v) if self.data == '-': return x0.calculate(v) - x1.calculate(v) if self.data == '*': return x0.calculate(v) * x1.calculate(v) if self.data == '/': return x0.calculate(v) / x1.calculate(v) if self.maxchild == 1: x0 = self.child[0] if self.data == 'Q': return math.sqrt(x0.calculate(v)) if self.data == 's': return math.sin(x0.calculate(v)) if self.data == 'E': return math.exp(x0.calculate(v)) if terminal_set.index(self.data) + 1: t = terminal_set.index(self.data) return float(v[t]) # This function return the number of maximum child of a function node def is_operator(c): if c == '+' or c == '-' or c == '*' or c == '/': return 2 if c == 's' or c == 'E' or c == 'Q': return 1 return 0 def chromosome_to_et(chromosome = ''): # Some parameters of an expression tree l = len(chromosome) elements = list(chromosome) root = ET(elements[0]) # Produce a expression tree i = 1 while i < l: while root.breadth_fisrt_travel().data: node = root.breadth_fisrt_travel() if node.maxchild == 2: node.child.append(ET(elements[i])) node.child.append(ET(elements[i+1])) i += 2 if i >= l-1: break if node.maxchild == 1: node.child.append(ET(elements[i])) i += 1 if not root.breadth_fisrt_travel().data: break return root, i # This function return the valid element in one chromosome # In the other word, the redundant of chromosome isn't valid def valid_chromosome(chromosome = ''): valid_len = chromosome_to_et(chromosome)[1] return chromosome[:valid_len], valid_len # This function to calculate chromosome with particular data set def calculate_chromosome(chromosome = '', data_set = [1, 4]): root = chromosome_to_et(chromosome)[0] return root.calculate(data_set) # Calculate RMSE of one chromosome dataset = training_create() def RMSE(chromosome = ''): pass n_test = dataset.shape[0] result_set = dataset[:, -1].reshape((1, -1)) train_set = np.delete(dataset, -1, 1) train_result = [] # Make result test set for storage for i in range (n_test): x = calculate_chromosome(chromosome, train_set[i, :]) train_result.append(x) # Calculate of this norm of 2 matrix result_matrix = np.array(train_result) return np.linalg.norm(result_matrix - result_set) / math.sqrt(n_test) if __name__ == '__main__': print(RMSE('*x++/*x**+xxxxxx*xxxx')) <file_sep>/Traditional/Constant_Creation.py # This program to create random numerical constant in GEP
f5b58e62e2e7871a5ec55a81c8f11d7962779218
[ "Markdown", "Python" ]
9
Python
trinhhungfischer/GEP
946775a4029bd75d2555b7b85432a4c6f87397fe
4df92eaef23ccd465c99364547aed1fb7d147eb3
refs/heads/main
<repo_name>melodygr/Time_Series_project<file_sep>/user_functions.py import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import time import itertools from datetime import datetime from statsmodels.graphics.tsaplots import plot_pacf from matplotlib.pylab import rcParams from statsmodels.graphics.tsaplots import plot_acf from statsmodels.tsa.seasonal import seasonal_decompose from statsmodels.tsa.arima.model import ARIMA import statsmodels.api as sm def visualize_time_series(df, name): """Plot time series. Plot annual breakouts for years with all 12 values.""" df.plot(figsize = (12,4)) plt.title(name) plt.xlabel('Year') plt.ylabel('Median House Price') plt.savefig('Images/zip_lineplot.png'); # Use pandas grouper to group values using annual frequency year_groups = df.groupby(pd.Grouper(freq ='A')) # Create a new DataFrame and store yearly values in columns df_annual = pd.DataFrame() # print(list(year_groups)) for yr, group in year_groups: if len(group) == 12: # Can only use full years of data df_annual[yr.year] = group.values.ravel() # Plot the yearly groups as subplots df_annual.plot(figsize = (13,20), subplots=True, legend=True) plt.savefig('Images/annual_breakout.png'); # Plot overlapping yearly groups df_annual.plot(figsize = (15,10), subplots=False, legend=True) plt.savefig('Images/annual_overlap.png'); def visualize_all_series(list_of_df, names): """Plot a list of time series dataframes together with provided names for legend.""" df_group = pd.concat(list_of_df, axis=1) df_group.columns = names df_group.plot(figsize = (12,4), subplots=False, legend=True) plt.title('Median House Prices Over Time') plt.xlabel('Year') plt.ylabel('Median House Price') plt.savefig('Images/lineplotallzips.png') plt.show(); def stationarity_check(TS): """Calculate rolling statistics and plot against original time series, perform and output Dickey Fuller test.""" # Import adfuller from statsmodels.tsa.stattools import adfuller # Calculate rolling statistics roll_mean = TS.rolling(window=24, center=False).mean() roll_std = TS.rolling(window=24, center=False).std() # Perform the Dickey Fuller Test dftest = adfuller(TS) # Plot rolling statistics: fig = plt.figure(figsize=(12,6)) plt.plot(TS, color='blue',label='Original') plt.plot(roll_mean.dropna(), color='red', label='Rolling Mean') plt.plot(roll_std.dropna(), color='black', label = 'Rolling Std') plt.legend(loc='best') plt.title('Rolling Mean & Standard Deviation') plt.savefig('Images/rolling.png') plt.show(block=False) # Print Dickey-Fuller test results print('Results of Dickey-Fuller Test: \n') dfoutput = pd.Series(dftest[0:4], index=['Test Statistic', 'p-value', '#Lags Used', 'Number of Observations Used']) for key,value in dftest[4].items(): dfoutput['Critical Value (%s)'%key] = value print(dfoutput) return None def run_arima_models(name, train, test, order, metrics_df, seasonal_order = (0,0,0,0)): """Runs baseline ARIMA model and adds metrics and results to a passed dataframe""" model_metrics = [name, order, seasonal_order] tic = time.time() model = ARIMA(train, order=order, seasonal_order=seasonal_order, freq='MS') results = model.fit() traintime = time.time() - tic model_metrics.append(round(traintime, 4)) # Print out summary information on the fit # print(results.summary()) model_metrics.extend([round(results.params[0], 2), round(results.params[1], 4), round(results.params[2], 4), round(results.params[3], 2)]) model_metrics.append(round(results.aic, 2)) # Get predictions starting from first test index and calculate confidence intervals # toc = time.time() # pred = results.get_prediction(start = test.index[0], end = test.index[-1], dynamic=True, full_results=True) # pred_conf = pred.conf_int() # predtime = time.time() - toc # model_metrics.append(predtime) # Add model metrics to passed metrics df series = pd.Series(model_metrics, index = metrics_df.columns) metrics_df = metrics_df.append(series, ignore_index=True) return metrics_df def grid_search_arima(train, d = 0): '''Attempt all pdq parameters to find lowest AIC value''' # Define the p, d and q parameters to take any value between 0 and 2 p = q = range(0, 3) #=d # Generate all different combinations of p, d, and q triplets # pdq = list(itertools.product(p, d, q)) pq = list(itertools.product(p, q)) pdq = [(x[0], d, x[1]) for x in pq] # Generate all different combinations of seasonal p, d, q and q triplets ps = ds = qs = range(0, 3) psdsqs = list(itertools.product(ps, ds, qs)) pdqs = [(x[0], x[1], x[2], 12) for x in psdsqs] # Run a grid with pdq and seasonal pdq parameters calculated above and get the best AIC value ans = [] for comb in pdq: for combs in pdqs: try: grid_model = ARIMA(train, order=comb, seasonal_order=combs, freq='MS') grid_results = grid_model.fit() ans.append([comb, combs, grid_results.aic]) # print('ARIMA {} x {}12 : AIC Calculated ={}'.format(comb, combs, results.aic)) except: continue ans_df = pd.DataFrame(ans, columns=['pdq', 'pdqs', 'aic']) print(ans_df.loc[ans_df['aic'].idxmin()]) return ans_df def run_preds_and_plot(model_results, train, test, name, best_diff): '''Run predictions, forecasts, plot results, calculate RMSE''' # Calculate predictions and forecasts pred = model_results.get_prediction(start=best_diff[name][0]) pred_forecast = model_results.get_forecast(steps=pd.to_datetime(test.index[-1]), dynamic=True) pred_conf = pred.conf_int() pred_forecast_conf = pred_forecast.conf_int() # Plot observations all_data = pd.concat([train, test], axis=0) ax = all_data.plot(label='observed', figsize=(12, 6)) # Plot predictions and forecasts with confidence intervals (unlogged) np.exp(pred.predicted_mean).plot(label='Predictions', ax=ax) np.exp(pred_forecast.predicted_mean).plot(label='Forecast', ax=ax) ax.fill_between(np.exp(pred_conf).index, np.exp(pred_conf).iloc[:, 0], np.exp(pred_conf).iloc[:, 1], color='#F5B14C', alpha=.3) # Limit upper end of confidence interval so it doesn't blow up the graph bound_conf=[] for i in range(len(pred_forecast_conf)): if np.exp(pred_forecast_conf).iloc[i,1] > 1.5*np.exp(pred_forecast.predicted_mean)[-1]: bound_conf.append(1.5*np.exp(pred_forecast.predicted_mean)[-1]) else: bound_conf.append(np.exp(pred_forecast_conf).iloc[i,1]) bound_df = pd.DataFrame(bound_conf, index=pred_forecast_conf.index, columns=['upper value']) ax.fill_between(np.exp(pred_forecast_conf).index, np.exp(pred_forecast_conf).iloc[:, 0], bound_df.iloc[:, 0], color='#F5B14C', alpha=.3) # np.exp(pred_forecast_conf).iloc[:, 1], color='g', alpha=.3) ax.fill_betweenx(ax.get_ylim(), test.index[0], test.index[-1], alpha=.1, zorder=-1) ax.set_xlabel('Date') ax.set_ylabel('Median House Prices') plt.legend() imagename=str("Images/"+name+"pred.png") plt.savefig(imagename) plt.show() # Compute the train mean squared error rmse_train = np.sqrt(((np.exp(pred.predicted_mean) - train.value[best_diff[name][0]:]) ** 2).mean()) print('The Root Mean Squared Error of {} predictions is {}'.format(name, round(rmse_train, 2))) # Compute the test mean squared error rmse_test = np.sqrt(((np.exp(pred_forecast.predicted_mean) - test.value) ** 2).mean()) print('The Root Mean Squared Error of {} forecasts is {}'.format(name, round(rmse_test, 2))) # Plot 2 years ax = all_data.plot(label='observed', figsize=(12, 6)) np.exp(pred.predicted_mean).plot(label='Predictions', ax=ax) np.exp(pred_forecast.predicted_mean).plot(label='Forecast', ax=ax) ax.fill_between(np.exp(pred_conf).index, np.exp(pred_conf).iloc[:, 0], np.exp(pred_conf).iloc[:, 1], color='#F5B14C', alpha=.3) ax.fill_between(np.exp(pred_forecast_conf).index, np.exp(pred_forecast_conf).iloc[:, 0], bound_df.iloc[:, 0], color='#F5B14C', alpha=.3) ax.fill_betweenx(ax.get_ylim(), test.index[0], test.index[-1], alpha=.1, zorder=-1) ax.set_xlabel('Date') ax.set_ylabel('Median House Prices') ax.set_xlim(xmin=train.index[-12]) plt.legend() imagename=str("Images/2yr"+name+"pred.png") plt.savefig(imagename) plt.show() return pred, pred_forecast, rmse_train, rmse_test def track_final_metrics(grid_search, results, name): '''Add model parameters and results to a dictionary and return''' metrics = {'name':name, 'order':grid_search['pdq'].loc[grid_search['aic'].idxmin()], 'seasonal order':grid_search['pdqs'].loc[grid_search['aic'].idxmin()]} for i in range(len(results.params)): metrics.update({results.params.index[i]:round(results.params[i], 4)}) metrics.update({'aic':round(results.aic, 2)}) return metrics<file_sep>/README.md # Time Series Analysis of Zillow Data Flatiron Data Science Project - Phase 4 <img src= "Images/melting_clock.jpg" alt="Melting Clock Image" align="right" width="275" height="275"> <!---Photo by <NAME> on Unsplash---> <!---<span>Photo by <a href="https://unsplash.com/@pedroplus?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><NAME></a> on <a href="https://unsplash.com/s/photos/stop-sign?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>---> Prepared and Presented by: **_<NAME>_** [Presentation PDF](https://github.com/melodygr/dsc-phase-4-project/blob/main/Zillow_Presentation.pdf "Presentation PDF") ### Business Problem For this analysis I will be working as a Data Scientist for a financial investment firm that is looking for short-term real estate investment opportunities for it's smaller investors to diversify their investment profiles. I will be analyzing median monthly housing sales prices for over 14,000 United States zipcodes and choosing the best areas to further analyze for potential investment. I will then forecast future real estate prices in those zip codes. ### Data There are many datasets available on the [Zillow Research Page](https://www.zillow.com/research/data/). The data used here represents median monthly housing sales prices for 14,723 zip codes over the period of April 1996 through April 2018 as reported by Zillow. Each row represents a unique zip code. Each record contains location info and median housing sales prices for each month. There are 14,723 rows and 272 variables: RegionID, RegionName (zip code), City, State, Metro, CountyName, SizeRank, finally 1996-04 through 2018-04 which represent 265 data points of monthly data for each zip code. ### Modeling Process Starting with the initial data cleaning/scrubbing phase, it was discovered that many zip codes did not have the full date range of data. Some zip codes had data only going back to 06-2014. I chose not to eliminate any zip codes for missing values but would model on the data available. My next step was to calculate an ROI for each zip code that I could compare across all of the data, so for instance a 10 year ROI would not be possible. Since my business case was for short term investment opportunities, a 10 year ROI would not be necessary. I calculated a 4 year ROI and the most recent year (2018) ROI. Finally I calculated the average one year ROI over the past 3 years and chose to use that as my comparison metric. Per my business problem, I was looking for the best ROI for small investors so I graphed ROI against the current Median Housing Price and then subset to the lower housing prices, eventually selecting six zip codes with high average ROI and low median housing prices for further analysis. ![Scatterplot](https://github.com/melodygr/dsc-phase-4-project/blob/main/Images/scatterplot2.png "ROI vs Median House Price") ![Scatterplot](https://github.com/melodygr/dsc-phase-4-project/blob/main/Images/scatterplot3.png "ROI vs Median House Price") ![Scatterplot](https://github.com/melodygr/dsc-phase-4-project/blob/main/Images/scatterplot4.png "ROI vs Median House Price") Here is a comparison of the data on the 6 zip codes over time. As you can see, Indianapolis and Columbus have limited data. But generally they all reflect the housing market crash of 2009 and then these six zipcodes have shown significant increases over the past 4 years. ![Lineplot](https://github.com/melodygr/dsc-phase-4-project/blob/main/Images/lineplotallzips.png "ROI vs Median House Price") This graph of the Philadelphia data shows how each time series can be broken out into trend, seasonality, and noise components. ![Decomposition](https://github.com/melodygr/dsc-phase-4-project/blob/main/Images/decomposition.png "ROI vs Median House Price") Initial ARMA (Auto-regressive Moving Average) models were run on all 6 zip codes to establish a baseline for future models, and then several models were run and parameters tuned to find the model with the least error. <br /> <img src= "Images/baseline.png" alt="Baseline Models" align="center" width="700" height="200"> <br /> <br /> Final Seasonal ARIMA model parameters <br /> <br /> <img src= "Images/final_model_params.png" alt="Final Models" align="center" width="900" height="260"> <br /> ### Model Predictions <br/> <img src= "Images/six_graphs.png" alt="Model Predictions" align="center" width="1000" height="350"> <br/> <br/> ### Model ROI Comparison <br /> <br /> <img src= "Images/final_model_forecast_ROI.png" alt="Final Models" align="center" width="700" height="160"> ### Conclusions * All training data far outperformed the test data, indicating some overfitting. * The models are all very skewed because of the market crash in 2009. * Columbus and Daytona had very large confidence intervals and overly high forecasts. * Chattanooga has outperformed even the confidence intervals of the model. * Philadelphia is potentially a good 50K investment , Indianapolis at 75K and Chattanooga at 100K investment ### Caveats: * Logged and differenced the data but some still did not test as stationary according to the Dickey Fuller test. * Real estate predictions can vary due to unseen fluctuations in the market ### Next Steps / Future Work * Obtain current data after 2018 for current predictions. Found zip code data on Redfin but it is rolling avg by zip code. * Investigate why some of the models seem so far off in their forecasts. * Try Facebook Prophet with each of the chosen zip codes * Try other methods of choosing zip codes, including clustering to find trends * Look for exogenous data to add to the model
feac270d14db8fe6a36ba91f12b1c891f9d0c6f5
[ "Markdown", "Python" ]
2
Python
melodygr/Time_Series_project
19a68d8999560e1aa89c6f8b2b24b671f5eb3a4c
b49406b41352af5b5fec7db8ae2796f1ca10cd48
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class RightCommand : ICommand { public string Name => "Right"; public void ExectueCommand (Player player) { player.MoveRight (); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public interface ICommand { string Name { get; } void ExectueCommand (Player player); }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerSelectionManager : MonoBehaviour { public List<Player> PlayersInGame; public static PlayerSelectionManager Instance; public Player currentSelectedPlayer; private void Awake () { if (Instance == null) Instance = this; } public void SelectPlayer (Player player) { foreach (var p in PlayersInGame) { p.activeIndicator.SetActive (false); } player.activeIndicator.SetActive (true); currentSelectedPlayer = player; } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class LeftCommand : ICommand { public string Name => "Left"; public void ExectueCommand (Player player) { player.MoveLeft (); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ForwardCommand : ICommand { public string Name => "Forward"; public void ExectueCommand (Player player) { player.MoveForward (); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { public GameObject activeIndicator; public float moveSpeed = 0.02f; private Animator animator; private Vector3 moveDirection; private void Awake () { animator = GetComponent<Animator> (); } private void Update () { transform.position += moveDirection * moveSpeed; } private void OnMouseDown () { PlayerSelectionManager.Instance.SelectPlayer (this); } public void MoveForward () { moveDirection = Vector3.forward; transform.eulerAngles = Vector3.up * 0; animator.SetTrigger ("Walk"); } public void MoveBack () { moveDirection = -Vector3.forward; transform.eulerAngles = Vector3.up * 180; animator.SetTrigger ("Walk"); } public void MoveRight () { moveDirection = Vector3.right; transform.eulerAngles = Vector3.up * 90; animator.SetTrigger ("Walk"); } public void MoveLeft () { moveDirection = -Vector3.right; transform.eulerAngles = Vector3.up * -90; animator.SetTrigger ("Walk"); } public void Stop () { moveDirection = Vector3.zero; animator.SetTrigger ("Normal"); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CommandController : MonoBehaviour { public static CommandController Instance; private List<ICommand> MovementCommands = new List<ICommand> (); private void Awake () { if (Instance == null) Instance = this; MovementCommands.Add (new ForwardCommand ()); MovementCommands.Add (new BackwardCommand ()); MovementCommands.Add (new RightCommand ()); MovementCommands.Add (new LeftCommand ()); MovementCommands.Add (new StopCommand ()); } public void ExecuteCommand (string commandName) { ICommand targetCommand = MovementCommands.Find (c => c.Name == commandName); targetCommand.ExectueCommand (PlayerSelectionManager.Instance.currentSelectedPlayer); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class StopCommand : ICommand { public string Name => "Stop"; public void ExectueCommand (Player player) { player.Stop (); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BackwardCommand : ICommand { public string Name => "Backward"; public void ExectueCommand (Player player) { player.MoveBack (); } }
0d55ee6cd9c47674d398d3547225786f8d2463eb
[ "C#" ]
9
C#
ahmedsabry22/Command-Pattern-Tutorial-Ahmed-Sabry
1b96cd32ad7b72f830a530f9e790a86eba0e75d9
f8bcce6df5786fa1fc9aa9e2967e5e88530209ce
refs/heads/master
<repo_name>rokborf/react-widgets<file_sep>/packages/react-widgets/src/Widget.js import React from 'react' import PropTypes from 'prop-types' import cn from 'classnames' class Widget extends React.Component { static propTypes = { tabIndex: PropTypes.node, focused: PropTypes.bool, disabled: PropTypes.bool, readOnly: PropTypes.bool, open: PropTypes.bool, dropUp: PropTypes.bool, } static contextTypes = { isRtl: PropTypes.bool, } render() { let { className, tabIndex, focused, open, dropUp, disabled, readOnly, ...props } = this.props let isRtl = !!this.context.isRtl tabIndex = tabIndex != null ? tabIndex : '-1' return ( <div {...props} tabIndex={tabIndex} className={cn( className, 'rw-widget', isRtl && 'rw-rtl', disabled && 'rw-state-disabled', readOnly && 'rw-state-readonly', focused && 'rw-state-focus', open && `rw-open${dropUp ? '-up' : ''}` )} /> ) } } export default Widget <file_sep>/packages/react-widgets/src/Year.js import React from 'react'; import PropTypes from 'prop-types'; import CalendarView from './CalendarView' import dates from './util/dates'; import { date as dateLocalizer } from './util/localizers'; import { chunk } from './util/_'; import * as Props from './util/Props'; import * as CustomPropTypes from './util/PropTypes'; class YearView extends React.Component { static propTypes = { activeId: PropTypes.string, culture: PropTypes.string, today: PropTypes.instanceOf(Date), value: PropTypes.instanceOf(Date), focused: PropTypes.instanceOf(Date), min: PropTypes.instanceOf(Date), max: PropTypes.instanceOf(Date), onChange: PropTypes.func.isRequired, headerFormat: CustomPropTypes.dateFormat, monthFormat: CustomPropTypes.dateFormat, disabled: PropTypes.bool, }; render() { let { focused, activeId } = this.props , months = dates.monthsInYear(dates.year(focused)) return ( <CalendarView {...Props.omitOwn(this)} activeId={activeId} > <CalendarView.Body> {chunk(months, 4).map(this.renderRow)} </CalendarView.Body> </CalendarView> ) } renderRow = (row, rowIdx) => { let { focused , activeId , disabled , onChange , value , today , culture , headerFormat , monthFormat , min , max } = this.props headerFormat = dateLocalizer.getFormat('header', headerFormat); monthFormat = dateLocalizer.getFormat('month', monthFormat); return ( <CalendarView.Row key={rowIdx}> {row.map((date, colIdx) => { let label = dateLocalizer.format(date, headerFormat, culture); return ( <CalendarView.Cell key={colIdx} activeId={activeId} label={label} date={date} now={today} min={min} max={max} unit="month" onChange={onChange} focused={focused} selected={value} disabled={disabled} > {dateLocalizer.format(date, monthFormat, culture)} </CalendarView.Cell> ) })} </CalendarView.Row> ) } } export default YearView; <file_sep>/www/src/pages/localization.md # Localization In order to handle the complex international differences in number and date formats `react-widgets` relies on third party parsing and formatting libraries via an integration layer of "localizers". We maintain and support localizers for __Globalize.js__, __Moment.js__ and a simple number localizer, but you can easily write your own for whichever library you are using. Localization sensitive widgets have `format` props that passed directly to your chosen localizer. The type and shape of these format props is determined by the api of the backing i18n library. Moment.js, for instance, uses string based date formats like: `MMM dd YYYY` whereas the newer Globalize.js may take an object like: `{ skeleton: GyMMMd }`. Regardless of the localizer, formats **always** accept `function` values for doing on-the-fly custom formatting. ### Globalize.js (recommended) <small>date, number</small> ```sh npm install globalize react-widgets-globalize --save ``` Globalize can be a bit of a challenge to set up correctly so please consult the [globalize docs](https://github.com/jquery/globalize#getting-started) for a lot of info on setting up Globalize and integrating into lots of different app environments. The Globalize localizer handles both __number__ and __date__ localization so there is no need for any additional localizers. _Note: the examples below are for Globalize `>= v1.0.0`, however the localizer supports `v0.1.0` as well._ {{ <TabbedCodeBlock> <Tab title="webpack globalize plugin"> {` import Globalize from 'globalize'; import globalizeLocalizer from 'react-widgets-globalize'; import DateTimePicker from 'react-widgets/lib/DateTimePicker'; Globalize.locale('en') globalizeLocalizer() render(<DateTimePicker />, document.getElementById('app-root')) `} </Tab> <Tab title="browser globals"> {` <script src='node_modules/react-widgets/dist/react-widgets.js'></script> <script src='node_modules/react-widgets-globalize/dist/react-widgets-globalize.js'></script> <script> var DateTimePicker = ReactWidgets.DateTimePicker; ReactDOM.render(<DateTimePicker />, document.getElementById('app-root')) </script> `} </Tab> </TabbedCodeBlock> }} While you _can_ use option objects and raw pattern strings directly as `format`s with react-widgets. It's [recommended](https://github.com/globalizejs/globalize#compilation-and-the-runtime-modules) that you use _statically_ determinable formatter functions instead. These can be extracted as part of your application's build step and compiled, ensuring applications only include exactly the i18n data needed. ```jsx // dates let monthYearFormatter = Globalize.dateFormatter({ raw: 'mmm YY' }); let monthYearParser = Globalize.dateParser({ raw: 'mmm YY' }); // numbers let percentFormatter = Globalize.numberFormatter({ style: 'percent', maximumFractionDigits: 2 }); let percentParser = Globalize.numberParser({ style: 'percent', maximumFractionDigits: 2 }); return ( <div> <DateTimePicker format={monthYearFormatter} parse={monthYearParser} /> <NumberPicker format={percentFormatter} parse={percentParser} /> {/* this is also supported but leads to much larger bundles */} <DateTimePicker format="mmm YY" /> <NumberPicker format=#{{ currency: 'USD', style: 'accounting' }} /> </div> ) ``` ### Moment.js <small>date</small> ```sh npm install moment react-widgets-moment --save ``` Again see the official [Moment docs](http://momentjs.com/) for information on integrating Moment into your build pipeline effectively. Moment only provides __date__ localization, if you also need Number localization consider the __simple-number__ localizer below, or Globalize.js. {{<TabbedCodeBlock> <Tab title="webpack"> {` import Moment from 'moment' import momentLocalizer from 'react-widgets-moment'; import DateTimePicker from 'react-widgets/lib/DateTimePicker'; Moment.locale('en') momentLocalizer() render(<DateTimePicker />, document.getElementById('app-root')) `} </Tab> <Tab title="browser globals"> {` <script src='node_modules/react-widgets/dist/react-widgets.js'></script> <script src='node_modules/react-widgets-moment/dist/react-widgets-moment.js'></script> <script> var DateTimePicker = ReactWidgets.DateTimePicker; ReactDOM.render(<DateTimePicker />, document.getElementById('app-root')) </script> `} </Tab> </TabbedCodeBlock>}} Moment [format](http://momentjs.com/docs/#/displaying/format/) props accept `string`s ```jsx <DateTimePicker format='mmm YYY' /> ``` ### Simple Number <small>number</small> The `simple-number` localizer provides a minimal number formatting and parsing strategy. Its best when you don't need robust locale support for currencies, and numbers; ```js var numberLocalizer = require('react-widgets/lib/localizers/simple-number') numberLocalizer(); ``` Or ```html <script src='node_modules/react-widgets/dist/react-widgets.js'></script> <script src='node_modules/react-widgets/dist/react-widgets-simple-number.js'></script> ``` {{<TabbedCodeBlock> <Tab title="webpack globalize plugin"> {` import simpleNumberLocalizer from 'react-widgets-simple-number'; import NumberPicker from 'react-widgets/lib/NumberPicker'; simpleNumberLocalizer() render(<NumberPicker />, document.getElementById('app-root')) `} </Tab> <Tab title="browser globals"> {` <script src='node_modules/react-widgets/dist/react-widgets.js'></script> <script src='node_modules/react-widgets-simple-number/dist/react-widgets-simple-number.js'></script> <script> var NumberPicker = ReactWidgets.NumberPicker; ReactDOM.render(<NumberPicker />, document.getElementById('app-root')) </script> `} </Tab> </TabbedCodeBlock>}} Check out the documentation for [format-number-with-string](https://www.npmjs.com/package/format-number-with-string) for a complete guide to its format syntax. ```jsx <NumberPicker format='-$#,###.00' /> ``` ## Creating a Localizer Creating a localizer is as easy as providing `react-widgets` an localizer options object. Localizers must provide `parse()` and `format()` functions as well as provide default values for all the required formats the widgets need. Formats can be whatever type your localization strategy requires (strings, objects, etc), however functions are always valid. The default formats, for example, can be strings or functions. If you wanted to use the built-in `Intl` api's for formatting, formats might be an options object to pass to `Intl.DateTimeFormat()`. Function formats are called automatically by the localizer with the `value`, the `culture` string and the localizer instance. ```jsx var localizer = { formats: { day: 'DD', month: 'mmm', // function formats are useful for more advanced formatting, such as a // year 'range' to represent a decade e.g "2000 - 2009". // Notice the localizer instance is the third argument, which can be // used to format or parse as needed. decade: (date, cultureStr, localizer) => { return ( localizer.format(date, 'YYYY') + ' - ' + localizer.format(lastYearOfDecade(date), 'YYYY') ) } }, parse(value, format, cultureStr) { return parsedDate }, format(value, format, cultureStr) { return formattedDatestring } } ReactWidgets.setDateLocalizer(localizer) ``` ## Localizer Api ### `DateLocalizer` An Object implementing the following api. ```js type Localizer = { propType: PropType? firstOfWeek: (culture: string) => number parse: (date: string, format: string|object, culture: string?)=> Date | null format: (date: Date, format: string|object, culture: string?)=> string formats: { default: string | object | function date: string | object | function footer: string | object | function dayOfMonth: string | object | function year: string | object | function decade: string | object | function century: string | object | function } } ``` #### required formats _Localizers must provide default values for each required format._ - `default`: the default date display format, generally a "long" format showing both date and time - `date`: A date only format - `time`: A time only format - `header`: The heading of the Calendar month view, contextualizes the current month, e.g. "Jan 2014" - `footer`: The Calendar footer format, for displaying Today's date - `dayOfMonth`: The day of the month - `month`: Month name, used in the Year view of the Calendar - `year`: year format, used in the Decade view of the Calendar - `decade`: a decade format, used in the Century view of the Calendar, eg. "2010 - 2019" - `century`: A century format, used the in the Calendar heading #### `propType` (optional) A React PropType that is used to validate the Date formats #### `parse` Convert a locale formatted string to a JavaScript Date object. ```js function( value: string, format: string|object, culture: ?string ): Date | null ``` #### `format` Convert a Date object to a locale specific string ```js function( value: Date, format: string|object, culture: ?string ): string ``` #### `firstOfWeek` Return the locale specific first day of the week from 0 (Sunday) to 6 (Saturday). ```js function( culture: ?string ): number ``` ### `NumberLocalizer` An Object implementing the following api. ```js { propType: ?PropType, formats: { default: string|object; }; parse: (num: string, format: string|object, culture: ?string)=> number | null; format: (num: number, format: string|object, culture: ?string)=> string; precision: (format: ?string|object) => number; decimalChar: (format: string|object, culture: ?string) => string; } ``` #### required formats _Localizers must provide default values for each required format._ - `default` The number picker display format. #### `propType` (optional) A React PropType that is used to validate the number formats. #### `parse` Convert a locale specific string to a JavaScript Number. ``` function( value: number, culture: ?string ): number | null ``` #### `format` Convert a Number to a locale specific string. ``` function( value: number, format: string|object, culture: ?string ): string ``` #### `decimalChar` (default: `'.'`) Return the decimal separator character. ``` function( format: string|object; culture: ?string ): string ``` #### `precision` Return the decimal precision for a given format or culture. Necessary for dealing with the quirks of floating point math. ``` function( format: string|object; culture: ?string ): number | null ``` <file_sep>/packages/react-widgets/src/SlideTransitionGroup.js import cn from 'classnames'; import events from 'dom-helpers/events'; import css from 'dom-helpers/style'; import getHeight from 'dom-helpers/query/height'; import { transitionDuration, transitionEnd } from 'dom-helpers/transition/properties'; import PropTypes from 'prop-types'; import TransitionGroup from 'react-transition-group/TransitionGroup'; import Transition, { ENTERING, ENTERED, EXITING, EXITED } from 'react-transition-group/Transition'; import React from 'react'; import { findDOMNode } from 'react-dom'; import * as Props from './util/Props'; const DirectionPropType = PropTypes.oneOf(['left', 'right', 'top', 'bottom']); const transitionStyle = { [ENTERING]: { position: 'absolute' }, [EXITING]: { position: 'absolute' }, } const transitionClasses = { [ENTERED]: 'rw-calendar-transition-entered', [ENTERING]: 'rw-calendar-transition-entering', [EXITING]: 'rw-calendar-transition-exiting', [EXITED]: 'rw-calendar-transition-exited', } function parseDuration(node) { let str = css(node, transitionDuration) let mult = str.indexOf('ms') === -1 ? 1000 : 1 return parseFloat(str) * mult } class SlideTransition extends React.Component { static contextTypes = { direction: DirectionPropType, }; handleTransitionEnd = (node, done) => { let duration = parseDuration(node) || 300 const handler = () => { events.off(node, transitionEnd, handler, false) done(); } setTimeout(handler, duration * 1.5); events.on(node, transitionEnd, handler, false); } render() { const { children, ...props } = this.props; const { direction } = this.context; const child = React.Children.only(children); return ( <Transition {...props} timeout={5000} addEndListener={this.handleTransitionEnd} > {(status, innerProps) => ( React.cloneElement(child, { ...innerProps, style: transitionStyle[status], className: cn( child.props.className, 'rw-calendar-transition', `rw-calendar-transition-${direction}`, transitionClasses[status], ) }) )} </Transition> ) } } class SlideTransitionGroup extends React.Component { static propTypes = { direction: DirectionPropType, }; static defaultProps = { direction: 'left', }; static childContextTypes = { direction: DirectionPropType, } getChildContext() { return { direction: this.props.direction }; } handleEnter = (child) => { let node = findDOMNode(this) if (!child) return const height = getHeight(child) + 'px'; css(node, { height, overflow: 'hidden', }) } handleExited = () => { let node = findDOMNode(this) css(node, { overflow: '', height: '' }); } render() { let { children, direction } = this.props return ( <TransitionGroup {...Props.omitOwn(this)} component='div' className="rw-calendar-transition-group" > <SlideTransition key={children.key} direction={direction} onEnter={this.handleEnter} onExited={this.handleExited} > {children} </SlideTransition> </TransitionGroup> ) } } export default SlideTransitionGroup <file_sep>/packages/react-widgets/src/NumberInput.js import canUseDOM from 'dom-helpers/util/inDOM'; import activeElement from 'dom-helpers/activeElement'; import PropTypes from 'prop-types'; import React from 'react'; import { findDOMNode } from 'react-dom'; import Input from './Input'; import * as Props from './util/Props'; import * as CustomPropTypes from './util/PropTypes'; import { number as numberLocalizer } from './util/localizers'; let getFormat = props => numberLocalizer.getFormat('default', props.format) let isSign = val => (val || '').trim() === '-'; function isPaddedZeros(str, culture) { let localeChar = numberLocalizer.decimalChar(null, culture) let [_, decimals] = str.split(localeChar); return !!( decimals && decimals.match(/0+$/) ) } function isAtDelimiter(num, str, culture) { let localeChar = numberLocalizer.decimalChar(null, culture) , lastIndex = str.length - 1 , char; if (str.length < 1) return false char = str[lastIndex] return !!( char === localeChar && str.indexOf(char) === lastIndex ) } class NumberPickerInput extends React.Component { static propTypes = { value: PropTypes.number, editing: PropTypes.bool, placeholder: PropTypes.string, format: CustomPropTypes.numberFormat, parse: PropTypes.func, culture: PropTypes.string, min: PropTypes.number, max: PropTypes.number, disabled: CustomPropTypes.disabled, readOnly: CustomPropTypes.disabled, onChange: PropTypes.func.isRequired, }; static defaultProps = { value: null, editing: false }; constructor(...args) { super(...args); this.state = this.getDefaultState() } componentWillReceiveProps(nextProps) { if (canUseDOM) { this.tabbedSelection = this.isSelectingAllText(); } this.setState( this.getDefaultState(nextProps) ) } componentDidUpdate(prevProps) { if (this.tabbedSelection && !prevProps.editing && this.props.editing) { findDOMNode(this).select(); } } getDefaultState(props = this.props){ let { value, culture, editing } = props let decimal = numberLocalizer.decimalChar(null, culture) , format = getFormat(props); if (value == null || isNaN(value)) value = '' else value = editing ? ('' + value).replace('.', decimal) : numberLocalizer.format(value, format, culture) return { stringValue: '' + value } } isSelectingAllText() { const node = findDOMNode(this); return activeElement() === node && node.selectionStart === 0 && node.selectionEnd === node.value.length; } handleChange = (event) => { let { value, onChange } = this.props; let stringValue = event.target.value , numberValue = this.parseNumber(stringValue) let isIntermediate = this.isIntermediateValue( numberValue, stringValue ); if (stringValue == null || stringValue.trim() === '') { this.setStringValue('') onChange(null, event) return } // order here matters a lot if (isIntermediate) { this.setStringValue(stringValue) } else if (numberValue !== value) { onChange(numberValue, event) } else if (stringValue != this.state.stringValue) { this.setStringValue(stringValue) } }; handleBlur = (event) => { var str = this.state.stringValue , number = this.parseNumber(str); // if number is below the min // we need to flush low values and decimal stops, onBlur means i'm done inputing if (this.isIntermediateValue(number, str)) { if (isNaN(number)) { number = null; } this.props.onChange(number, event) } } parseNumber(strVal) { let { culture, parse: userParse } = this.props let delimChar = numberLocalizer.decimalChar(null, culture) if (userParse) return userParse(strVal, culture) strVal = strVal.replace(delimChar, '.') strVal = parseFloat(strVal); return strVal } isIntermediateValue(num, str) { let { culture, min } = this.props; return !!( num < min || isSign(str) || isAtDelimiter(num, str, culture) || isPaddedZeros(str, culture) ); } // this intermediate state is for when one runs into // the decimal or are typing the number setStringValue(stringValue) { this.setState({ stringValue }) } render() { let { disabled, readOnly, placeholder, min, max } = this.props; let value = this.state.stringValue; let props = Props.omitOwn(this); return ( <Input {...props} className="rw-widget-input" onChange={this.handleChange} onBlur={this.handleBlur} aria-valuenow={value} aria-valuemin={isFinite(min) ? min : null} aria-valuemax={isFinite(max) ? max : null} disabled={disabled} readOnly={readOnly} placeholder={placeholder} value={value} /> ) } } export default NumberPickerInput; <file_sep>/packages/react-widgets/src/util/dataHelpers.js import { isShallowEqual } from './_'; export const dataValue = (data, field) => { let value = data; if (typeof field === 'function') value = field(data) else if (data == null) value = data else if ( typeof field === 'string' && typeof data === 'object' && field in data ) value = data[field] return value } export const dataText = (item, textField) => { var value = dataValue(item, textField); return value == null ? '' : (value + '') } export function dataIndexOf(data, item, valueField) { let idx = -1 let isValueEqual = datum => valueMatcher(item, datum, valueField); while (++idx < data.length) { var datum = data[idx]; if (datum === item || isValueEqual(datum)) return idx } return -1 } /** * I don't know that the shallow equal makes sense here but am too afraid to * remove it. */ export function valueMatcher(a, b, valueField) { return isShallowEqual( dataValue(a, valueField), dataValue(b, valueField) ) } export function dataItem(data, item, valueField) { let idx = dataIndexOf(data, dataValue(item, valueField), valueField) return idx !== -1? data[idx] : item } <file_sep>/packages/react-widgets/src/TimeList.js import React from 'react'; import PropTypes from 'prop-types'; import { timeoutManager } from 'react-component-managers'; import List from './List'; import dates from './util/dates'; import listDataManager from './util/listDataManager'; import { date as dateLocalizer } from './util/localizers'; import * as CustomPropTypes from './util/PropTypes'; import * as Props from './util/Props'; var format = props => dateLocalizer.getFormat('time', props.format) class TimeList extends React.Component { static propTypes = { value: PropTypes.instanceOf(Date), step: PropTypes.number, min: PropTypes.instanceOf(Date), max: PropTypes.instanceOf(Date), currentDate: PropTypes.instanceOf(Date), itemComponent: CustomPropTypes.elementType, format: CustomPropTypes.dateFormat, onSelect: PropTypes.func, preserveDate: PropTypes.bool, culture: PropTypes.string, delay: PropTypes.number } static defaultProps = { step: 30, onSelect: () => {}, min: new Date(1900, 0, 1), max: new Date(2099, 11, 31), preserveDate: true, delay: 300, } constructor(...args) { super(...args) this.accessors = { text: item => item.label, value: item => item.date, }; this.timeouts = timeoutManager(this) this.list = listDataManager(this, { getListDataState: List.getListDataState, accessors: this.accessors }) this.state = this.getStateFromProps(this.props) } componentWillReceiveProps(nextProps) { this.setState(this.getStateFromProps(nextProps)) } componentWillUnmount() { this.unmounted = true; } getStateFromProps(props = this.props) { let { value, currentDate } = props; let data = this.getDates(props) let selectedItem = this.getClosestDate(data, value || currentDate) this.list.setData(data) return { dates: data, selectedItem: this.list.nextEnabled(selectedItem), focusedItem: this.list.nextEnabled(selectedItem || data[0]), } } handleKeyDown = (e) => { let key = e.key let focusedItem = this.state.focusedItem let list = this.list; if (key === 'End') { e.preventDefault() this.setState({ focusedItem: list.last() }) } else if (key === 'Home') { e.preventDefault() this.setState({ focusedItem: list.first() }) } else if (key === 'Enter') { this.props.onSelect(focusedItem) } else if (key === 'ArrowDown') { e.preventDefault() this.setState({ focusedItem: list.next(focusedItem) }) } else if (key === 'ArrowUp') { e.preventDefault() this.setState({ focusedItem: list.prev(focusedItem) }) } } handleKeyPress = (e) => { e.preventDefault(); this.search(String.fromCharCode(e.which), item => { !this.unmounted && this.setState({ focusedItem: item }) }) } render() { let { onSelect } = this.props; let { selectedItem, focusedItem } = this.state; let props = Props.omitOwn(this) let listProps = this.list.defaultProps(); return ( <List ref="list" {...props} {...listProps} onSelect={onSelect} textAccessor={this.accessors.text} valueAccessor={this.accessors.value} selectedItem={selectedItem} focusedItem={focusedItem} /> ) } scrollTo = () => { this.refs.list.move && this.refs.list.move() } getClosestDate(times, date) { var roundTo = 1000 * 60 * this.props.step , inst = null , label; if( !date) return null date = new Date(Math.floor(date.getTime() / roundTo) * roundTo) label = dateLocalizer.format(date, format(this.props), this.props.culture) times.some( time => { if( time.label === label ) return (inst = time) }) return inst } getDates(props = this.props) { let times = []; let values = this.getBounds(props) let start = values.min let startDay = dates.date(start); while (dates.date(start) === startDay && dates.lte(start, values.max)) { times.push({ date: start, label: dateLocalizer.format(start, format(props), props.culture) }) start = dates.add(start, props.step || 30, 'minutes') } return times } getBounds(props) { var value = props.value || props.currentDate || dates.today() , useDate = props.preserveDate , min = props.min , max = props.max , start, end; //compare just the time regradless of whether they fall on the same day if(!useDate) { start = dates.startOf(dates.merge(new Date(), min, props.currentDate), 'minutes') end = dates.startOf(dates.merge(new Date(), max, props.currentDate), 'minutes') if( dates.lte(end, start) && dates.gt(max, min, 'day')) end = dates.tomorrow() return { min: start, max: end } } start = dates.today() end = dates.tomorrow() //date parts are equal return { min: dates.eq(value, min, 'day') ? dates.merge(start, min, props.currentDate) : start, max: dates.eq(value, max, 'day') ? dates.merge(start, max, props.currentDate) : end } } search(character, cb) { var word = ((this._searchTerm || '') + character).toLowerCase(); this._searchTerm = word this.timeouts.set('search', () => { var item = this.list.next(this.state.focusedItem, word); this._searchTerm = '' if (item) cb(item) }, this.props.delay) } } export default TimeList <file_sep>/packages/react-widgets/src/util/localizers.js import invariant from 'invariant'; import { has } from './_'; import PropTypes from 'prop-types'; const localePropType = PropTypes.oneOfType([ PropTypes.string, PropTypes.func ]) const REQUIRED_NUMBER_FORMATS = ['default']; const REQUIRED_DATE_FORMATS = [ 'default', 'date', 'time', 'header', 'footer', 'dayOfMonth', 'month', 'year', 'decade', 'century' ]; let _numberLocalizer = createWrapper('NumberPicker') export const number = { propType: (...args) => _numberLocalizer.propType(...args), getFormat: (key, format) => format || _numberLocalizer.formats[key], parse: (...args) => _numberLocalizer.parse(...args), format: (...args) => _numberLocalizer.format(...args), decimalChar: (...args) => _numberLocalizer.decimalChar(...args), precision: (...args) => _numberLocalizer.precision(...args), } export function setNumber({ format, parse, formats, propType = localePropType, decimalChar = () => '.', precision = () => null, }) { checkFormats(REQUIRED_NUMBER_FORMATS, formats) _numberLocalizer = { formats, precision, decimalChar, propType, format: wrapFormat(format), parse(value, culture, format) { let result = parse.call(this, value, culture, format) invariant(result == null || typeof result === 'number' , 'number localizer `parse(..)` must return a number, null, or undefined') return result } } } let _dateLocalizer = createWrapper('DateTimePicker') export const date = { propType: (...args) => _dateLocalizer.propType(...args), getFormat: (key, format) => format || _dateLocalizer.formats[key], parse: (...args) => _dateLocalizer.parse(...args), format: (...args) => _dateLocalizer.format(...args), firstOfWeek: (...args) => _dateLocalizer.firstOfWeek(...args), } export function setDate({ formats, format, parse, firstOfWeek, propType = localePropType, }) { checkFormats(REQUIRED_DATE_FORMATS, formats) _dateLocalizer = { formats, propType, firstOfWeek, format: wrapFormat(format), parse(value, culture) { let result = parse.call(this, value, culture) invariant(result == null || (result instanceof Date && !isNaN(result.getTime())) , 'date localizer `parse(..)` must return a valid Date, null, or undefined') return result } } } const wrapFormat = (formatter) => function( value, format, culture) { let result = typeof format === 'function' ? format(value, culture, this) : formatter.call(this, value, format, culture) invariant(result == null || typeof result === 'string', '`localizer format(..)` must return a string, null, or undefined') return result } function checkFormats(required, formats) { if (process.env.NODE_ENV !== 'production') required.forEach(f => invariant(has(formats, f), 'localizer missing required format: `%s`', f)) } function createWrapper() { let dummy = {}; if (process.env.NODE_ENV !== 'production') { ['formats', 'parse', 'format', 'firstOfWeek', 'precision', 'propType'] .forEach(name => Object.defineProperty(dummy, name, { enumerable: true, get() { throw new Error( '[React Widgets] You are attempting to use a widget that requires localization ' + '(Calendar, DateTimePicker, NumberPicker). ' + 'However there is no localizer set. Please configure a localizer. \n\n' + 'see http://jquense.github.io/react-widgets/docs/#/i18n for more info.') } })) } return dummy } <file_sep>/packages/react-widgets/src/Multiselect.js // @flow import cn from 'classnames'; import closest from 'dom-helpers/query/closest'; import PropTypes from 'prop-types'; import React from 'react'; import uncontrollable from 'uncontrollable'; import Widget from './Widget'; import WidgetPicker from './WidgetPicker'; import Select from './Select'; import Popup from './Popup'; import MultiselectInput from './MultiselectInput'; import TagList from './MultiselectTagList'; import List from './List'; import AddToListOption from './AddToListOption'; import { makeArray } from './util/_'; import * as Filter from './util/Filter'; import * as Props from './util/Props'; import { getMessages } from './messages'; import * as CustomPropTypes from './util/PropTypes'; import accessorManager from './util/accessorManager'; import focusManager from './util/focusManager'; import listDataManager from './util/listDataManager'; import scrollManager from './util/scrollManager'; import withRightToLeft from './util/withRightToLeft'; import { widgetEditable, disabledManager } from './util/interaction'; import { instanceId, notify, isFirstFocusedRender } from './util/widgetHelpers'; const CREATE_OPTION = {}; const ENTER = 13; const INSERT = 'insert'; const REMOVE = 'remove'; let propTypes = { ...Filter.propTypes, data: PropTypes.array, //-- controlled props -- value: PropTypes.array, /** * @type {function ( * dataItems: ?any[], * metadata: { * dataItem: any, * action: 'insert' | 'remove', * originalEvent: SyntheticEvent, * lastValue: ?any[], * searchTerm: ?string * } * ): void} */ onChange: PropTypes.func, searchTerm: PropTypes.string, /** * @type {function ( * searchTerm: ?string, * metadata: { * action: 'clear' | 'input', * lastSearchTerm: ?string, * originalEvent: SyntheticEvent, * } * ): void} */ onSearch: PropTypes.func, open: PropTypes.bool, onToggle: PropTypes.func, //------------------------------------------- valueField: CustomPropTypes.accessor, textField: CustomPropTypes.accessor, tagComponent: CustomPropTypes.elementType, itemComponent: CustomPropTypes.elementType, listComponent: CustomPropTypes.elementType, groupComponent: CustomPropTypes.elementType, groupBy: CustomPropTypes.accessor, allowCreate: PropTypes.oneOf([true, false, 'onFilter']), /** * * @type { (dataItem: ?any, metadata: { originalEvent: SyntheticEvent }) => void } */ onSelect: PropTypes.func, /** * @type { (searchTerm: string) => void } */ onCreate: PropTypes.func, busy: PropTypes.bool, dropUp: PropTypes.bool, popupTransition: CustomPropTypes.elementType, inputProps: PropTypes.object, listProps: PropTypes.object, autoFocus: PropTypes.bool, placeholder: PropTypes.string, disabled: CustomPropTypes.disabled.acceptsArray, readOnly: CustomPropTypes.disabled, messages: PropTypes.shape({ open: CustomPropTypes.message, emptyList: CustomPropTypes.message, emptyFilter: CustomPropTypes.message, createOption: CustomPropTypes.message, tagsLabel: CustomPropTypes.message, selectedItems: CustomPropTypes.message, noneSelected: CustomPropTypes.message, removeLabel: CustomPropTypes.message, }) }; /** * --- * shortcuts: * - { key: left arrow, label: move focus to previous tag } * - { key: right arrow, label: move focus to next tag } * - { key: delete, deselect focused tag } * - { key: backspace, deselect next tag } * - { key: alt + up arrow, label: close Multiselect } * - { key: down arrow, label: open Multiselect, and move focus to next item } * - { key: up arrow, label: move focus to previous item } * - { key: home, label: move focus to first item } * - { key: end, label: move focus to last item } * - { key: enter, label: select focused item } * - { key: ctrl + enter, label: create new tag from current searchTerm } * - { key: any key, label: search list for item starting with key } * --- * * A select listbox alternative. * * @public */ @withRightToLeft class Multiselect extends React.Component { static propTypes = propTypes; static defaultProps = { data: [], allowCreate: 'onFilter', filter: 'startsWith', value: [], searchTerm: '', listComponent: List, }; constructor(...args) { super(...args); this.messages = getMessages(this.props.messages); this.inputId = instanceId(this, '_input') this.tagsId = instanceId(this, '_taglist') this.notifyId = instanceId(this, '_notify_area') this.listId = instanceId(this, '_listbox') this.createId = instanceId(this, '_createlist_option') this.activeTagId = instanceId(this, '_taglist_active_tag') this.activeOptionId = instanceId(this, '_listbox_active_option') this.list = listDataManager(this) this.tagList = listDataManager(this, { getStateGetterFromProps: null }) this.accessors = accessorManager(this) this.handleScroll = scrollManager(this) this.focusManager = focusManager(this, { didHandle: this.handleFocusDidChange, }) this.isDisabled = disabledManager(this) this.state = { focusedTag: null, ...this.getStateFromProps(this.props), }; } componentWillReceiveProps(nextProps) { this.messages = getMessages(nextProps.messages); this.setState(this.getStateFromProps(nextProps)) } getStateFromProps(props) { let { accessors, list, tagList } = this let { data, searchTerm, minLength, caseSensitive, filter } = props let values = makeArray(props.value); let dataItems = values.map(item => accessors.findOrSelf(data, item)); data = data.filter(i => !values.some(v => accessors.matches(i, v)) ); this._lengthWithoutValues = data.length; data = Filter.filter(data, { filter, searchTerm, minLength, caseSensitive, textField: accessors.text, }) list.setData(data); tagList.setData(dataItems); let { focusedItem, focusedTag } = this.state || {}; return { data, dataItems, focusedTag: list.nextEnabled( ~dataItems.indexOf(focusedTag) ? focusedTag : null), focusedItem: list.nextEnabled( ~data.indexOf(focusedItem) ? focusedItem : data[0]), } } handleFocusDidChange = (focused) => { if (focused) return this.focus(); this.close() this.clearSearch(); if (this.refs.tagList) this.setState({ focusedTag: null }) } handleDelete = (dataItem, event) => { let { disabled, readOnly} = this.props; if (disabled == true || readOnly) return; this.focus() this.change(dataItem, event, REMOVE) }; handleSearchKeyDown = (e) => { if (e.key === 'Backspace' && e.target.value && !this._deletingText) this._deletingText = true }; handleSearchKeyUp = (e) => { if (e.key === 'Backspace' && this._deletingText) this._deletingText = false }; handleInputChange = (e) => { this.search(e.target.value, e, 'input') this.open() }; @widgetEditable handleClick = ({ target }) => { this.focus() if (closest(target, '.rw-select')) this.toggle() else this.open() }; @widgetEditable handleDoubleClick = () => { if (!this.refs.input) return this.focus() this.refs.input.select(); }; @widgetEditable handleSelect = (dataItem, originalEvent) => { if (dataItem === undefined || dataItem === CREATE_OPTION) { this.handleCreate(this.props.searchTerm, originalEvent) return } notify(this.props.onSelect, [dataItem, { originalEvent }]) this.change(dataItem, originalEvent, INSERT) this.focus() }; @widgetEditable handleCreate = (searchTerm = '', event) => { notify(this.props.onCreate, searchTerm) this.clearSearch(event) this.focus() }; @widgetEditable handleKeyDown = (event) => { const { open, searchTerm, onKeyDown } = this.props; let { key, keyCode, altKey, ctrlKey } = event let { focusedTag, focusedItem } = this.state; let { list, tagList } = this; let createIsFocused = focusedItem === CREATE_OPTION; let canCreate = this.allowCreate() const focusTag = tag => this.setState({ focusedTag: tag }) const focusItem = item => this.setState({ focusedItem: item, focusedTag: null }) notify(onKeyDown, [event]) if (event.defaultPrevented) return if (key === 'ArrowDown') { event.preventDefault() if (!open) return this.open(); let next = list.next(focusedItem) let creating = createIsFocused || (canCreate && focusedItem === next); focusItem(creating ? CREATE_OPTION : next) } else if (key === 'ArrowUp' && (open || altKey)) { event.preventDefault() if (altKey) return this.close() focusItem(createIsFocused ? list.last() : list.prev(focusedItem)) } else if (key === 'End') { event.preventDefault() if (open) focusItem(list.last()) else focusTag(tagList.last()) } else if (key === 'Home') { event.preventDefault() if (open) focusItem(list.first()) else focusTag(tagList.first()) } // using keyCode to ignore enter for japanese IME else if (open && keyCode === ENTER) { event.preventDefault(); if (ctrlKey && canCreate) return this.handleCreate(searchTerm, event) this.handleSelect(focusedItem, event) } else if (key === 'Escape') { open ? this.close() : tagList && focusTag(null) } else if (!searchTerm && !this._deletingText) { if (key === 'ArrowLeft') { focusTag(tagList.prev(focusedTag) || tagList.last()) } else if (key === 'ArrowRight' && focusedTag) { let nextTag = tagList.next(focusedTag) focusTag(nextTag === focusedTag ? null : nextTag) } else if (key === 'Delete' && !tagList.isDisabled(focusedTag)) { this.handleDelete(focusedTag, event) } else if (key === 'Backspace') { this.handleDelete(tagList.last(), event) } else if (key === ' ' && !open) { event.preventDefault() this.open() } } }; renderInput(ownedIds) { let { searchTerm , maxLength , tabIndex , busy , autoFocus , inputProps , open } = this.props; let { focusedItem, focusedTag } = this.state; let disabled = this.props.disabled === true let readOnly = this.props.readOnly === true let active; if (!open) active = focusedTag ? this.activeTagId : ''; else if (focusedItem || this.allowCreate()) active = this.activeOptionId return ( <MultiselectInput ref='input' {...inputProps} autoFocus={autoFocus} tabIndex={tabIndex || 0} role='listbox' aria-expanded={!!open} aria-busy={!!busy} aria-owns={ownedIds} aria-haspopup={true} aria-activedescendant={active || null} value={searchTerm} maxLength={maxLength} disabled={disabled} readOnly={readOnly} placeholder={this.getPlaceholder()} onKeyDown={this.handleSearchKeyDown} onKeyUp={this.handleSearchKeyUp} onChange={this.handleInputChange} /> ) } renderList(messages) { let { inputId, activeOptionId, listId, accessors } = this; let { open } = this.props; let { focusedItem } = this.state; let List = this.props.listComponent let props = this.list.defaultProps(); return ( <List {...props} ref="list" id={listId} activeId={activeOptionId} valueAccessor={accessors.value} textAccessor={accessors.text} focusedItem={focusedItem} onSelect={this.handleSelect} onMove={this.handleScroll} aria-live='polite' aria-labelledby={inputId} aria-hidden={!open} messages={{ emptyList: this._lengthWithoutValues ? messages.emptyFilter : messages.emptyList }} /> ) } renderNotificationArea(messages) { let { focused, dataItems } = this.state; let itemLabels = dataItems.map(item => this.accessors.text(item)) return ( <span id={this.notifyId} role="status" className='rw-sr' aria-live='assertive' aria-atomic="true" aria-relevant="additions removals text" > {focused && ( dataItems.length ? messages.selectedItems(itemLabels) : messages.noneSelected() )} </span> ) } renderTags(messages) { let { readOnly } = this.props; let { focusedTag, dataItems } = this.state; let Component = this.props.tagComponent; return ( <TagList ref='tagList' id={this.tagsId} activeId={this.activeTagId} textAccessor={this.accessors.text} valueAccessor={this.accessors.value} label={messages.tagsLabel()} value={dataItems} readOnly={readOnly} disabled={this.isDisabled()} focusedItem={focusedTag} onDelete={this.handleDelete} valueComponent={Component} /> ) } render() { let { className , busy , dropUp , open , searchTerm , popupTransition } = this.props; let { focused, focusedItem, dataItems } = this.state; let elementProps = Props.pickElementProps(this); let shouldRenderTags = !!dataItems.length , shouldRenderPopup = isFirstFocusedRender(this) || open , allowCreate = this.allowCreate(); let inputOwns = `${this.listId} ${this.notifyId} ` + (shouldRenderTags ? this.tagsId : '') + (allowCreate ? this.createId : ''); let disabled = this.isDisabled() === true let readOnly = this.props.readOnly === true let messages = this.messages; return ( <Widget {...elementProps} open={open} dropUp={dropUp} focused={focused} disabled={disabled} readOnly={readOnly} onKeyDown={this.handleKeyDown} onBlur={this.focusManager.handleBlur} onFocus={this.focusManager.handleFocus} className={cn(className, 'rw-multiselect')} > {this.renderNotificationArea(messages)} <WidgetPicker className="rw-widget-input" onClick={this.handleClick} onDoubleClick={this.handleDoubleClick} onTouchEnd={this.handleClick} > <div> {shouldRenderTags && this.renderTags(messages) } {this.renderInput(inputOwns)} </div> <Select busy={busy} icon={focused ? 'caret-down' :''} aria-hidden="true" role="presentational" disabled={disabled || readOnly} /> </WidgetPicker> {shouldRenderPopup && <Popup dropUp={dropUp} open={open} transition={popupTransition} onEntering={()=> this.refs.list.forceUpdate()} > <div> {this.renderList(messages)} {allowCreate && ( <AddToListOption id={this.createId} searchTerm={searchTerm} onSelect={this.handleCreate} focused={!focusedItem || focusedItem === CREATE_OPTION} > {messages.createOption(this.props)} </AddToListOption> )} </div> </Popup> } </Widget> ) } change(dataItem, originalEvent, action) { let { onChange, searchTerm, value: lastValue } = this.props; let { dataItems } = this.state; switch (action) { case INSERT: dataItems = dataItems.concat(dataItem); break; case REMOVE: dataItems = dataItems.filter(d => d !== dataItem) break; } notify(onChange, [dataItems, { action, dataItem, originalEvent, lastValue, searchTerm, }]); this.clearSearch(originalEvent) } clearSearch(originalEvent) { this.search('', originalEvent, 'clear') } search(searchTerm, originalEvent, action: 'clear' | 'input' = 'input') { let { onSearch, searchTerm: lastSearchTerm } = this.props; if (searchTerm !== lastSearchTerm) notify(onSearch, [searchTerm, { action, lastSearchTerm, originalEvent, }]) } focus() { if (this.refs.input) this.refs.input.focus() } toggle() { this.props.open ? this.close() : this.open() } open() { if (!this.props.open) notify(this.props.onToggle, true) } close() { if (this.props.open) notify(this.props.onToggle, false) } allowCreate() { let { searchTerm, onCreate, allowCreate } = this.props; return !!( onCreate && (allowCreate === true || (allowCreate === 'onFilter' && searchTerm)) && !this.hasExtactMatch() ) } hasExtactMatch() { let { searchTerm, caseSensitive } = this.props; let { data, dataItems } = this.state; let { text } = this.accessors; let lower = text => caseSensitive ? text : text.toLowerCase(); let eq = v => lower(text(v)) === lower(searchTerm); // if there is an exact match on textFields: // "john" => { name: "john" }, don't show return dataItems.some(eq) || data.some(eq) } getPlaceholder() { let { value, placeholder } = this.props; return (value && value.length ? '' : placeholder) || '' } } export default uncontrollable(Multiselect, { open: 'onToggle', value: 'onChange', searchTerm: 'onSearch' }, ['focus']); <file_sep>/www/src/pages/index.md --- name: Getting Started --- # Getting Started react-widgets is a suite of high-quality input components built for React. Each component is built for ease of use, accessibility, and the practical needs of complex (or simple) forms. The work great with complex data structures and models, and in keeping with the [React approach](http://facebook.github.io/react/docs/forms.html#controlled-components) to form inputs, each component's props can easily be [_controlled_ or _uncontrolled_](/react-widgets/controllables/). A special shout-out to Kendo UI Core, and jQuery UI, whose original work inspired this suite. <div className='row'> <div className='col-sm-6'> <h4>Install: npm (recommended)</h4> <pre><code>npm install react-widgets --save</code></pre> </div> <div className='col-sm-6'> <h4>bower</h4> <pre><code>bower install react-widgets --save</code></pre> </div> </div> The npm build offers an additional advantage of allowing you to only require the individual widgets allowing code bundlers like webpack and Browserify to only package up the pieces you use, saving you bytes. ## Setup Stylesheets, images, and fonts are found in the `dist` directory. You can use webpack to `require()` the styles, or include the css normally. The included icons are provided by - [Font Awesome by <NAME>]("http://fontawesome.io">) {{ <TabbedCodeBlock> <Tab title="webpack"> {` // Add the css styles... import 'react-widgets/dist/css/react-widgets.css'; // ...Or if you prefer to use the Less or Sass files directly // import 'react-widgets/lib/less/react-widgets.less'; // import 'react-widgets/lib/scss/react-widgets.scss'; import { render } from 'react-dom'; import DropdownList from 'react-widgets/lib/DropdownList'; render(<DropdownList />, document.getElementById('app-root')) `} </Tab> <Tab title="browser globals"> {` <link href="dist/css/react-widgets.css" rel="stylesheet"/> <script src="http://fb.me/react-15.5.5.js"></script> <script src="http://fb.me/react-dom-15.5.0.js"></script> <script src='node_modules/react-widgets/dist/react-widgets.js'></script> <script> var DropdownList = ReactWidgets.DropDownlist; ReactDOM.render(<DropdownList/>, document.getElementById('app-root')) </script> `} </Tab> </TabbedCodeBlock> }} > **Hey!** Date and number components need a *Localizer* configured in order to work! > Check out the [Localization page](/react-widgets/localization/) for more information. If are using webpack to handle styles in your application you are probably already configured loaders to make it work with appropriate file extensions. If not, you will have to use the `css-loader`, `style-loader`, `url-loader` and, optionally, the `less-loader` or `scss-loader`. Here's a common configuration: ```js module: { loaders: [ // for good ol' css { test: /\\.css$/, use: ['style-loader', 'css-loader'] }, // OR if using less { test: /\\.less$/, use: ['style-loader', 'css-loader', 'less-loader'] }, // OR if using scss { test: /\\.scss$/, use: ['style-loader', 'css-loader', 'scss-loader'] }, // images and fonts { test: /\\.(gif|ttf|eot|svg|woff2?)$/, use: 'url-loader?name=[name].[ext]'}, ] } ``` When using Less or Sass, you'll need to help webpack find the font and image folders. Override corresponding variables from `variables` file. {{ <TabbedCodeBlock> <Tab title="Sass" lang="text/x-scss"> {` $font-path: '~react-widgets/lib/fonts'; $img-path: '~react-widgets/lib/img'; @import '~react-widgets/lib/scss/react-widgets'; `} </Tab> <Tab title="Less" lang="text/x-less"> {` @import '~react-widgets/lib/less/react-widgets'; @font-path: '~react-widgets/lib/fonts'; @img-path: '~react-widgets/lib/img'; `} </Tab> </TabbedCodeBlock> }} ## Accessibility and Read Direction React-widgets tries to be as inclusive and wide reaching as possible. Along with an included solution for date and number localization, there is first class support for cultures and languages that read right to left (with the `isRtl` prop). Each widget also has appropriate ARIA roles and attributes for the benefit of screen readers and visually impaired users. Keyboard-only navigation of widgets is also supported, for those who prefer to not, or cannot use a mouse. To help ensure maximum accessibility, every widget should have an `id` attribute. If you do not wish to provide an id attribute, the component will generate the necessary id's to properly label and annotate the widget ARIA. > **Note:** Because of how server-side rendering works, using auto generated `id`s may > cause checksum mismatches. Always provide `id` props to your components to avoid this possible pitfall. <file_sep>/packages/react-widgets/src/Popup.js import cn from 'classnames'; import PropTypes from 'prop-types'; import React, { cloneElement } from 'react'; import SlideDownTransition from './SlideDownTransition'; import { elementType }from './util/PropTypes'; class StaticContainer extends React.Component { shouldComponentUpdate = ({ shouldUpdate }) => !!shouldUpdate render = () => this.props.children; } class Popup extends React.Component { static propTypes = { open: PropTypes.bool, dropUp: PropTypes.bool, onEntering: PropTypes.func, onEntered: PropTypes.func, transition: elementType }; static defaultProps = { open: false, transition: SlideDownTransition, }; render() { let { className, dropUp, open, transition: Transition, ...props } = this.props let child = React.Children.only(this.props.children) return ( <Transition {...props} in={open} dropUp={dropUp} className={cn(className, 'rw-popup-container')} > <StaticContainer shouldUpdate={open}> {cloneElement(child, { className: cn(child.props.className, 'rw-popup') })} </StaticContainer> </Transition> ) } } export default Popup <file_sep>/packages/react-widgets/test/DateTimePicker-test.js import React from 'react'; import Globalize from 'globalize'; import { mount, shallow } from 'enzyme'; import DateTimePicker from '../src/DateTimePicker' import TimeList from '../src/TimeList' import Calendar from '../src/Calendar' let ControlledDateTimePicker = DateTimePicker.ControlledComponent; describe('DateTimePicker', () => { it('should set initial values', () => { var date = new Date(); expect( mount(<DateTimePicker defaultValue={date} format="MM-dd-yyyy"/>) .find('.rw-input') .getDOMNode() .value ) .to.equal(Globalize.format(date, 'MM-dd-yyyy')) }) it('should start closed', () => { let inst = shallow(<ControlledDateTimePicker />) expect(inst.prop('open')).to.not.equal(true) expect(inst.find('Popup').first().prop('open')).to.not.equal(true) inst.assertNone('.rw-open') inst.assertSingle(`DateTimePickerInput[aria-expanded=false]`) }) it('should open when clicked', () => { var onOpen = sinon.spy() let wrapper = shallow(<ControlledDateTimePicker onToggle={onOpen} />) wrapper.find('Button') .first() .simulate('click') wrapper.find('Button') .last() .simulate('click'); expect(onOpen.calledTwice).to.equal(true) }) it('should change when selecting a date', () => { let change = sinon.spy() shallow( <ControlledDateTimePicker open='date' onChange={change} onToggle={()=>{}} /> ) .assertSingle(Calendar) .simulate('change', new Date()); expect(change.calledOnce).to.equal(true) }) it('should change when selecting a time', () => { let change = sinon.spy() , select = sinon.spy() shallow( <ControlledDateTimePicker open='date' onChange={change} onSelect={select} onToggle={()=>{}} /> ) .assertSingle(TimeList) .simulate('select', { date: new Date() }); expect(select.calledOnce).to.equal(true) expect(change.calledAfter(select)).to.equal(true) expect(change.calledOnce).to.equal(true) }) it('should change when selecting a time', () => { let change = sinon.spy() , select = sinon.spy(); shallow( <ControlledDateTimePicker open='date' onChange={change} onSelect={select} onToggle={()=>{}} /> ) .assertSingle(TimeList) .simulate('select', { date: new Date() }); expect(select.calledOnce).to.equal(true) expect(change.calledAfter(select)).to.equal(true) expect(change.calledOnce).to.equal(true) }) it('should set id on list', () => { expect( mount(<DateTimePicker />) .find('ul').getDOMNode() .hasAttribute('id') ).to.equal(true); }) it('should not show time button when not selected', () => { var spy = sinon.spy() mount( <DateTimePicker time={false} date={false} onToggle={spy }/> ) .tap(_ => _.assertNone('.rw-btn-time')) .tap(_ => _.assertNone('.rw-btn-calendar')) .simulate('keyDown', { altKey: true }) .simulate('keyDown', { altKey: true }) expect(spy.callCount).to.equal(0) }) it('should simulate focus/blur events', (done) => { let blur = sinon.spy() let focus = sinon.spy() let inst = mount(<DateTimePicker onBlur={blur} onFocus={focus} />) expect(focus.calledOnce).to.equal(false) expect(blur.calledOnce).to.equal(false) inst.simulate('focus') setTimeout(() => { expect(focus.calledOnce).to.equal(true) inst.simulate('blur') setTimeout(() => { expect(blur.calledOnce).to.equal(true) done() }) }) }) it('should simulate key events', () => { let kp = sinon.spy() , kd = sinon.spy() , ku = sinon.spy() mount( <DateTimePicker onKeyPress={kp} onKeyUp={ku} onKeyDown={kd}/> ) .find('.rw-input') .simulate('keyPress') .simulate('keyDown') .simulate('keyUp') expect(kp.calledOnce).to.equal(true) expect(kd.calledOnce).to.equal(true) expect(ku.calledOnce).to.equal(true) }) it('should do nothing when disabled', (done) => { let wrapper = mount( <DateTimePicker defaultValue={new Date()} disabled /> ) let input = wrapper.find('.rw-input').getDOMNode(); expect(input.hasAttribute('disabled')).to.equal(true); wrapper.find('.rw-i-calendar').simulate('click') setTimeout(() => { expect(wrapper.instance()._values.open).to.not.equal(true) done() }, 0) }) it('should do nothing when readonly', (done) => { let wrapper = mount( <DateTimePicker defaultValue={new Date()} readOnly /> ) let input = wrapper.find('.rw-input').getDOMNode(); expect(input.hasAttribute('readonly')).to.equal(true); wrapper.find('.rw-i-calendar').simulate('click') setTimeout(() => { expect(wrapper.instance()._values.open).to.not.equal(true) done() }) }) it('should change values on key down', () => { let change = sinon.spy() let wrapper = mount( <DateTimePicker onChange={change} /> ) let options = wrapper.find('li').map(n => n.getDOMNode()) wrapper.simulate('keyDown', { key: 'ArrowDown', altKey: true }) expect(wrapper.instance()._values.open).to.equal('date') wrapper.simulate('keyDown', { key: 'ArrowDown', altKey: true }) expect(wrapper.instance()._values.open).to.equal('time') wrapper.simulate('keyDown', { key: 'Home' }) expect(options[0].className) .to.match(/\brw-state-focus\b/) wrapper.simulate('keyDown', { key: 'End' }) expect(options[options.length - 1].className) .to.match(/\brw-state-focus\b/) wrapper.simulate('keyDown', { key: 'ArrowUp' }) expect(options[options.length - 2].className) .to.match(/\brw-state-focus\b/) wrapper.simulate('keyDown', { key: 'ArrowDown' }) expect(options[options.length - 1].className) .to.match(/\brw-state-focus\b/) }) describe('TimeList', () => { it('should render max correctly', ()=>{ let date = new Date(2014, 0, 16, 9, 30) let inst = mount( <TimeList value={new Date(2014, 0, 16, 8)} max={date} preserveDate /> ) let dates = inst.state('dates'); let time = dates[dates.length - 1] expect(time.date.getHours()).to.eql(9) expect(time.date.getMinutes()).to.eql(30) expect(time.date.getSeconds()).to.eql(0) inst.setProps({ value: new Date(2014, 0, 15, 8) }) dates = inst.state('dates'); time = dates[dates.length - 1] expect(time.date.getHours()).to.eql(23) expect(time.date.getMinutes()).to.eql(30) expect(time.date.getSeconds()).to.eql(0) }) it('should render min correctly', ()=>{ let date = new Date(2014, 0, 16, 9, 30) let inst = mount( <TimeList value={new Date(2014, 0, 16, 12)} min={date} preserveDate /> ) let time = inst.state('dates')[0]; expect(time.date.getHours()).to.eql(9) expect(time.date.getMinutes()).to.eql(30) expect(time.date.getSeconds()).to.eql(0) inst = mount(<TimeList value={new Date(2014, 0, 18, 8)} min={date} preserveDate />) time = inst.state('dates')[0]; expect(time.date.getHours()).to.eql(0) expect(time.date.getMinutes()).to.eql(0) expect(time.date.getSeconds()).to.eql(0) }) it('should set the step property', ()=>{ let dates = mount(<DateTimePicker step={60} />) .find(TimeList) .instance().state.dates expect(dates[0].date.getHours()).to.equal(0) expect(dates[1].date.getHours()).to.equal(1) expect(dates[2].date.getHours()).to.equal(2) dates = mount(<DateTimePicker step={120} />) .find(TimeList) .instance().state.dates expect(dates[0].date.getHours()).to.equal(0) expect(dates[1].date.getHours()).to.equal(2) expect(dates[2].date.getHours()).to.equal(4) }) }) }) <file_sep>/packages/react-widgets/src/DateTimePickerInput.js import PropTypes from 'prop-types'; import React from 'react'; import { findDOMNode } from 'react-dom'; import Input from './Input'; import { date as dateLocalizer } from './util/localizers'; import * as CustomPropTypes from './util/PropTypes'; import * as Props from './util/Props'; class DateTimePickerInput extends React.Component { static propTypes = { format: CustomPropTypes.dateFormat.isRequired, editing: PropTypes.bool, editFormat: CustomPropTypes.dateFormat, parse: PropTypes.func.isRequired, value: PropTypes.instanceOf(Date), onChange: PropTypes.func.isRequired, onBlur: PropTypes.func, culture: PropTypes.string, disabled: CustomPropTypes.disabled, readOnly: CustomPropTypes.disabled, }; constructor(...args) { super(...args) let { value, editing, editFormat, format, culture } = this.props; this.state = { textValue: formatDate( value , editing && editFormat ? editFormat : format , culture ) } } componentWillReceiveProps(nextProps) { let { value, editing, editFormat, format, culture } = nextProps; this.setState({ textValue: formatDate( value , editing && editFormat ? editFormat : format , culture ) }) } handleChange = ({ target: { value } }) => { this._needsFlush = true this.setState({ textValue: value }); }; handleBlur = (event) => { let { format, culture, parse, onChange, onBlur } = this.props; onBlur && onBlur(event) if (this._needsFlush) { let date = parse(event.target.value); this._needsFlush = false onChange(date, formatDate(date, format, culture)) } }; render() { let { disabled, readOnly } = this.props let { textValue } = this.state let props = Props.omitOwn(this); return ( <Input {...props} type='text' className="rw-widget-input" value={textValue} disabled={disabled} readOnly={readOnly} onChange={this.handleChange} onBlur={this.handleBlur} /> ) } focus(){ findDOMNode(this).focus() } } export default DateTimePickerInput; function isValid(d) { return !isNaN(d.getTime()); } function formatDate(date, format, culture){ var val = '' if ( (date instanceof Date) && isValid(date) ) val = dateLocalizer.format(date, format, culture) return val; } <file_sep>/packages/react-widgets/src/util/PropTypes.js import PropTypes from 'prop-types'; import elementType from 'react-prop-types/lib/elementType'; import createChainableTypeChecker from 'react-prop-types/lib/utils/createChainableTypeChecker'; import { date, number } from './localizers'; export { elementType } export const numberFormat = createChainableTypeChecker( (...args) => number.propType(...args)) export const dateFormat = createChainableTypeChecker( (...args) => date.propType(...args)) export const disabled = createChainableTypeChecker( (...args) => PropTypes.bool(...args)); disabled.acceptsArray = PropTypes.oneOfType([disabled, PropTypes.array]) export const accessor = PropTypes.oneOfType([ PropTypes.string, PropTypes.func, ]) export const message = PropTypes.oneOfType([ PropTypes.node, PropTypes.string, PropTypes.func, ]) <file_sep>/packages/react-widgets/src/util/withRightToLeft.js import PropTypes from 'prop-types'; import { mixin } from 'react-component-managers'; export default mixin({ propTypes: { isRtl: PropTypes.bool }, contextTypes: { isRtl: PropTypes.bool }, childContextTypes: { isRtl: PropTypes.bool }, getChildContext() { return { isRtl: this.isRtl() } }, isRtl() { return !!( this.props.isRtl || (this.context && this.context.isRtl) ) } }) <file_sep>/packages/react-widgets/src/Century.js import React from 'react'; import PropTypes from 'prop-types'; import CalendarView from './CalendarView'; import dates from './util/dates'; import { date as dateLocalizer } from './util/localizers'; import { chunk } from './util/_'; import * as Props from './util/Props'; import * as CustomPropTypes from './util/PropTypes'; class CenturyView extends React.Component { static propTypes = { activeId: PropTypes.string, culture: PropTypes.string, today: PropTypes.instanceOf(Date), value: PropTypes.instanceOf(Date), focused: PropTypes.instanceOf(Date), min: PropTypes.instanceOf(Date), max: PropTypes.instanceOf(Date), onChange: PropTypes.func.isRequired, decadeFormat: CustomPropTypes.dateFormat, disabled: PropTypes.bool, }; render(){ let { focused, activeId } = this.props; return ( <CalendarView {...Props.omitOwn(this)} activeId={activeId} > <CalendarView.Body> {chunk(getCenturyDecades(focused), 4) .map(this.renderRow) } </CalendarView.Body> </CalendarView> ) } renderRow = (row, rowIdx) => { let { focused , activeId , disabled , onChange , value , today , culture , min , decadeFormat , max } = this.props decadeFormat = dateLocalizer.getFormat('decade', decadeFormat); return ( <CalendarView.Row key={rowIdx}> {row.map((date, colIdx) => { let label = dateLocalizer.format( dates.startOf(date, 'decade'), decadeFormat, culture ) return ( <CalendarView.Cell key={colIdx} unit="decade" activeId={activeId} label={label} date={date} now={today} min={min} max={max} onChange={onChange} focused={focused} selected={value} disabled={disabled} > {label} </CalendarView.Cell> ) })} </CalendarView.Row> ) } } function getCenturyDecades(_date){ var days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] , date = dates.add(dates.startOf(_date, 'century'), -20, 'year') return days.map(() => (date = dates.add(date, 10, 'year'))) } export default CenturyView; <file_sep>/packages/react-widgets/src/List.js import PropTypes from 'prop-types'; import React from 'react'; import { findDOMNode } from 'react-dom'; import * as CustomPropTypes from './util/PropTypes'; import * as Props from './util/Props'; import { notify } from './util/widgetHelpers'; import { defaultGetDataState } from './util/listDataManager'; import Listbox from './Listbox'; import ListOption from './ListOption'; import ListOptionGroup from './ListOptionGroup' import { getMessages } from './messages'; const EMPTY_DATA_STATE = {} const propTypes = { data: PropTypes.array, dataState: PropTypes.shape({ sortedKeys: PropTypes.array, groups: PropTypes.object, data: PropTypes.array, sequentialData: PropTypes.array, }), onSelect: PropTypes.func, onMove: PropTypes.func, activeId: PropTypes.string, optionComponent: CustomPropTypes.elementType, renderItem: PropTypes.func.isRequired, renderGroup: PropTypes.func, focusedItem: PropTypes.any, selectedItem: PropTypes.any, searchTerm: PropTypes.string, isDisabled: PropTypes.func.isRequired, groupBy: CustomPropTypes.accessor, messages: PropTypes.shape({ emptyList: PropTypes.func.isRequired, }) } const defaultProps = { onSelect: () => {}, data: [], dataState: EMPTY_DATA_STATE, optionComponent: ListOption, } class List extends React.Component { static getDataState = defaultGetDataState componentDidMount() { this.move() } componentDidUpdate() { this.move() } mapItems(fn) { const { data, dataState } = this.props let { sortedKeys, groups } = dataState; if (!groups) return data.map((item, idx) => fn(item, idx, false)) let idx = -1 return sortedKeys.reduce((items, key) => { let group = groups[key] return items.concat( fn(key, idx, true), group.map(item => fn(item, ++idx, false)) ) }, []) } render() { let { className, messages } = this.props let elementProps = Props.pickElementProps(this); let { emptyList } = getMessages(messages) return ( <Listbox {...elementProps} className={className} emptyListMessage={emptyList(this.props)} > {this.mapItems((item, idx, isHeader) => { return isHeader ? this.renderGroupHeader(item) : this.renderItem(item, idx) })} </Listbox> ) } renderGroupHeader(group) { let { renderGroup } = this.props; return ( <ListOptionGroup key={'group_' + group} group={group} > {renderGroup({ group })} </ListOptionGroup> ) } renderItem(item, index) { let { activeId , focusedItem , selectedItem , onSelect , isDisabled , renderItem , optionComponent: Option } = this.props let isFocused = focusedItem === item; return ( <Option dataItem={item} key={'item_' + index} index={index} activeId={activeId} focused={isFocused} onSelect={onSelect} disabled={isDisabled(item)} selected={selectedItem === item} > {renderItem({ item, index })} </Option> ) } move() { let { focusedItem, onMove, data, dataState } = this.props; let list = findDOMNode(this); let idx = renderedIndexOf(focusedItem, list, data, dataState) let selectedItem = list.children[idx] if (selectedItem) notify(onMove, [selectedItem, list, focusedItem]) } } function renderedIndexOf(item, list, data, dataState) { let { groups, sortedKeys } = dataState if (!groups) return data.indexOf(item) let runningIdx = -1 let idx = -1 sortedKeys.some(group => { let itemIdx = groups[group].indexOf(item) runningIdx++; if (itemIdx !== -1) { idx = runningIdx + itemIdx + 1; return true } runningIdx += groups[group].length }) return idx; } List.propTypes = propTypes; List.defaultProps = defaultProps; export default List; <file_sep>/packages/react-widgets/src/Input.js import React from 'react'; import PropTypes from 'prop-types'; import cn from 'classnames'; class Input extends React.Component { static propTypes = { disabled: PropTypes.bool, readOnly: PropTypes.bool, value: PropTypes.string, type: PropTypes.string, tabIndex: PropTypes.string, component: PropTypes.any, }; render() { let { className , disabled , readOnly , value , tabIndex , type = 'text' , component: Component = 'input' , ...props } = this.props; return ( <Component {...props} type={type} tabIndex={tabIndex || 0} autoComplete='off' disabled={disabled} readOnly={readOnly} aria-disabled={disabled} aria-readonly={readOnly} value={value == null ? '' : value} className={cn( className, 'rw-input' )} /> ) } } export default Input; <file_sep>/packages/react-widgets/src/DropdownList.js import React from 'react' import { findDOMNode } from 'react-dom' import PropTypes from 'prop-types' import activeElement from 'dom-helpers/activeElement' import cn from 'classnames' import { autoFocus, mountManager, timeoutManager, } from 'react-component-managers' import uncontrollable from 'uncontrollable' import Widget from './Widget' import WidgetPicker from './WidgetPicker' import Select from './Select' import Popup from './Popup' import List from './List' import AddToListOption from './AddToListOption'; import DropdownListInput from './DropdownListInput' import { getMessages } from './messages' import * as Props from './util/Props' import * as Filter from './util/Filter' import focusManager from './util/focusManager' import listDataManager from './util/listDataManager' import * as CustomPropTypes from './util/PropTypes' import accessorManager from './util/accessorManager' import scrollManager from './util/scrollManager' import withRightToLeft from './util/withRightToLeft' import { widgetEditable } from './util/interaction' import { instanceId, notify, isFirstFocusedRender } from './util/widgetHelpers' const CREATE_OPTION = {}; /** * --- * shortcuts: * - { key: alt + down arrow, label: open dropdown } * - { key: alt + up arrow, label: close dropdown } * - { key: down arrow, label: move focus to next item } * - { key: up arrow, label: move focus to previous item } * - { key: home, label: move focus to first item } * - { key: end, label: move focus to last item } * - { key: enter, label: select focused item } * - { key: ctrl + enter, label: create new option from current searchTerm } * - { key: any key, label: search list for item starting with key } * --- * * A `<select>` replacement for single value lists. * @public */ @withRightToLeft class DropdownList extends React.Component { static propTypes = { ...Filter.propTypes, value: PropTypes.any, /** * @type {function ( * dataItems: ?any, * metadata: { * lastValue: ?any, * searchTerm: ?string * originalEvent: SyntheticEvent, * } * ): void} */ onChange: PropTypes.func, open: PropTypes.bool, onToggle: PropTypes.func, data: PropTypes.array, valueField: CustomPropTypes.accessor, textField: CustomPropTypes.accessor, allowCreate: PropTypes.oneOf([true, false, 'onFilter']), /** * A React component for customizing the rendering of the DropdownList * value */ valueComponent: CustomPropTypes.elementType, itemComponent: CustomPropTypes.elementType, listComponent: CustomPropTypes.elementType, groupComponent: CustomPropTypes.elementType, groupBy: CustomPropTypes.accessor, /** * * @type {(dataItem: ?any, metadata: { originalEvent: SyntheticEvent }) => void} */ onSelect: PropTypes.func, onCreate: PropTypes.func, /** * @type function(searchTerm: string, metadata: { action, lastSearchTerm, originalEvent? }) */ onSearch: PropTypes.func, searchTerm: PropTypes.string, busy: PropTypes.bool, placeholder: PropTypes.string, dropUp: PropTypes.bool, popupTransition: CustomPropTypes.elementType, disabled: CustomPropTypes.disabled.acceptsArray, readOnly: CustomPropTypes.disabled, inputProps: PropTypes.object, listProps: PropTypes.object, messages: PropTypes.shape({ open: PropTypes.string, emptyList: CustomPropTypes.message, emptyFilter: CustomPropTypes.message, filterPlaceholder: PropTypes.string, createOption: CustomPropTypes.message, }), } static defaultProps = { data: [], delay: 500, searchTerm: '', allowCreate: false, listComponent: List, } constructor(...args) { super(...args) autoFocus(this) this.messages = getMessages(this.props.messages) this.inputId = instanceId(this, '_input') this.listId = instanceId(this, '_listbox') this.activeId = instanceId(this, '_listbox_active_option') this.list = listDataManager(this) this.mounted = mountManager(this) this.timeouts = timeoutManager(this) this.accessors = accessorManager(this) this.handleScroll = scrollManager(this) this.focusManager = focusManager(this, { didHandle: this.handleFocusChanged, }) this.state = this.getStateFromProps(this.props) } componentWillReceiveProps(nextProps) { this.messages = getMessages(nextProps.messages) this.setState(this.getStateFromProps(nextProps)) } getStateFromProps(props) { let { open, value, data, searchTerm, filter, minLength, caseSensitive, } = props let { accessors, list } = this let initialIdx = accessors.indexOf(data, value) if (open) data = Filter.filter(data, { filter, searchTerm, minLength, caseSensitive, textField: this.accessors.text, }) list.setData(data) let selectedItem = data[initialIdx] return { data, selectedItem: list.nextEnabled(selectedItem), focusedItem: list.nextEnabled(selectedItem || data[0]), } } handleFocusChanged = focused => { if (!focused) this.close() } @widgetEditable handleSelect = (dataItem, originalEvent) => { if (dataItem === undefined || dataItem === CREATE_OPTION) { this.handleCreate(this.props.searchTerm) return } notify(this.props.onSelect, [dataItem, { originalEvent }]) this.change(dataItem, originalEvent) this.close() this.focus(this) } @widgetEditable handleCreate = (searchTerm = '', event) => { notify(this.props.onCreate, searchTerm) this.clearSearch(event) this.close() this.focus(this) }; @widgetEditable handleClick = e => { this.focus() this.toggle() notify(this.props.onClick, e) } @widgetEditable handleKeyDown = (e) => { let { key, altKey, ctrlKey } = e let { list } = this; let { open, onKeyDown, filter, searchTerm } = this.props; let { focusedItem, selectedItem } = this.state; let createIsFocused = focusedItem === CREATE_OPTION; let canCreate = this.allowCreate() notify(onKeyDown, [e]) let closeWithFocus = () => { this.close() findDOMNode(this).focus() } const change = item => item != null && this.change(item, e) const focusItem = item => this.setState({ focusedItem: item }) if (e.defaultPrevented) return if (key === 'End') { e.preventDefault() if (open) focusItem(list.last()) else change(list.last()) } else if (key === 'Home') { e.preventDefault() if (open) focusItem(list.first()) else change(list.first()) } else if (key === 'Escape' && open) { e.preventDefault() closeWithFocus() } else if (key === 'Enter' && open && ctrlKey && canCreate) { e.preventDefault() this.handleCreate(searchTerm, e) } else if ((key === 'Enter' || (key === ' ' && !filter)) && open) { e.preventDefault() this.handleSelect(focusedItem, e) } else if (key === ' ' && !open) { e.preventDefault() this.open() } else if (key === 'ArrowDown') { e.preventDefault() if (altKey) return this.open() if (!open) change(list.next(selectedItem)) let next = list.next(focusedItem) let creating = createIsFocused || (canCreate && focusedItem === next); focusItem(creating ? CREATE_OPTION : next) } else if (key === 'ArrowUp') { e.preventDefault() if (altKey) return closeWithFocus() if (!open) return change(list.prev(selectedItem)) focusItem(createIsFocused ? list.last() : list.prev(focusedItem)) } } @widgetEditable handleKeyPress = e => { notify(this.props.onKeyPress, [e]) if (e.defaultPrevented) return if (!(this.props.filter && this.props.open)) this.findOption(String.fromCharCode(e.which), item => { this.mounted() && this.props.open ? this.setState({ focusedItem: item }) : item && this.change(item, e) }) } handleInputChange = (e) => { this.search(e.target.value, e, 'input') }; change(nextValue, originalEvent) { let { onChange, searchTerm, value: lastValue } = this.props if (!this.accessors.matches(nextValue, lastValue)) { notify(onChange, [ nextValue, { originalEvent, lastValue, searchTerm, }, ]) this.clearSearch(originalEvent) this.close() } } renderList(messages) { let { open, filter, data, searchTerm } = this.props let { selectedItem, focusedItem } = this.state let { value, text } = this.accessors let List = this.props.listComponent let props = this.list.defaultProps() return ( <div> {filter && ( <WidgetPicker ref="filterWrapper" className="rw-filter-input rw-input" > <input ref="filter" value={searchTerm} className="rw-input-reset" onChange={this.handleInputChange} placeholder={messages.filterPlaceholder(this.props)} /> <Select icon="search" role="presentation" aria-hidden="true" /> </WidgetPicker> )} <List {...props} ref="list" id={this.listId} activeId={this.activeId} valueAccessor={value} textAccessor={text} selectedItem={selectedItem} focusedItem={open ? focusedItem : null} onSelect={this.handleSelect} onMove={this.handleScroll} aria-live={open && 'polite'} aria-labelledby={this.inputId} aria-hidden={!this.props.open} messages={{ emptyList: data.length ? messages.emptyFilter : messages.emptyList, }} /> {this.allowCreate() && ( <AddToListOption id={this.createId} searchTerm={searchTerm} onSelect={this.handleCreate} focused={!focusedItem || focusedItem === CREATE_OPTION} > {messages.createOption(this.props)} </AddToListOption> )} </div> ) } render() { let { className, tabIndex, popupTransition, textField, data, busy, dropUp, placeholder, value, open, filter, inputProps, valueComponent, } = this.props let { focused } = this.state let disabled = this.props.disabled === true, readOnly = this.props.readOnly === true, valueItem = this.accessors.findOrSelf(data, value) let shouldRenderPopup = open || isFirstFocusedRender(this) let elementProps = Object.assign(Props.pickElementProps(this), { name: undefined, role: 'combobox', id: this.inputId, tabIndex: open && filter ? -1 : tabIndex || 0, 'aria-owns': this.listId, 'aria-activedescendant': open ? this.activeId : null, 'aria-expanded': !!open, 'aria-haspopup': true, 'aria-busy': !!busy, 'aria-live': !open && 'polite', 'aria-autocomplete': 'list', 'aria-disabled': disabled, 'aria-readonly': readOnly, }) let messages = this.messages return ( <Widget {...elementProps} ref="input" open={open} dropUp={dropUp} focused={focused} disabled={disabled} readOnly={readOnly} onBlur={this.focusManager.handleBlur} onFocus={this.focusManager.handleFocus} onKeyDown={this.handleKeyDown} onKeyPress={this.handleKeyPress} className={cn(className, 'rw-dropdown-list')} > <WidgetPicker onClick={this.handleClick} className="rw-widget-input"> <DropdownListInput {...inputProps} value={valueItem} textField={textField} placeholder={placeholder} valueComponent={valueComponent} /> <Select busy={busy} icon="caret-down" role="presentational" aria-hidden="true" disabled={disabled || readOnly} label={messages.openDropdown(this.props)} /> </WidgetPicker> {shouldRenderPopup && <Popup open={open} dropUp={dropUp} transition={popupTransition} onEntered={() => this.focus()} onEntering={() => this.refs.list.forceUpdate()} > {this.renderList(messages)} </Popup>} </Widget> ) } focus = target => { let { filter, open } = this.props let inst = target || (filter && open ? this.refs.filter : this.refs.input) inst = findDOMNode(inst) if (inst && activeElement() !== inst) inst.focus() } findOption(character, cb) { var word = ((this._currentWord || '') + character).toLowerCase() if (!character) return this._currentWord = word this.timeouts.set( 'search', () => { var list = this.list, key = this.props.open ? 'focusedItem' : 'selectedItem', item = list.next(this.state[key], word) if(item === this.state[key]) { item = list.next(null, word) } this._currentWord = '' if (item) cb(item) }, this.props.delay ) } clearSearch(originalEvent) { this.search('', originalEvent, 'clear') } search(searchTerm, originalEvent, action: 'clear' | 'input' = 'input') { let { onSearch, searchTerm: lastSearchTerm } = this.props; if (searchTerm !== lastSearchTerm) notify(onSearch, [searchTerm, { action, lastSearchTerm, originalEvent, }]) } open() { if (!this.props.open) notify(this.props.onToggle, true) } close() { if (this.props.open) notify(this.props.onToggle, false) } toggle() { this.props.open ? this.close() : this.open() } allowCreate() { let { searchTerm, onCreate, allowCreate } = this.props; return !!( onCreate && (allowCreate === true || (allowCreate === 'onFilter' && searchTerm)) && !this.hasExtactMatch() ) } hasExtactMatch() { let {searchTerm, caseSensitive, filter } = this.props; let { data } = this.state; let { text } = this.accessors; let lower = text => caseSensitive ? text : text.toLowerCase(); // if there is an exact match on textFields: return filter && data.some(v => lower(text(v)) === lower(searchTerm)) } } export default uncontrollable( DropdownList, { open: 'onToggle', value: 'onChange', searchTerm: 'onSearch', }, ['focus'] ) <file_sep>/packages/react-widgets/src/NumberPicker.js import cn from 'classnames' import PropTypes from 'prop-types' import React from 'react' import { findDOMNode } from 'react-dom' import uncontrollable from 'uncontrollable' import Widget from './Widget' import WidgetPicker from './WidgetPicker' import Select from './Select' import Input from './NumberInput' import Button from './Button' import { getMessages } from './messages' import * as Props from './util/Props' import focusManager from './util/focusManager' import { widgetEditable } from './util/interaction' import { notify } from './util/widgetHelpers' import * as CustomPropTypes from './util/PropTypes' import { directions } from './util/constants' import withRightToLeft from './util/withRightToLeft' import { number as numberLocalizer } from './util/localizers' var format = props => numberLocalizer.getFormat('default', props.format) // my tests in ie11/chrome/FF indicate that keyDown repeats // at about 35ms+/- 5ms after an initial 500ms delay. callback fires on the leading edge function createInterval(callback) { let fn var id, cancel = () => clearTimeout(id) id = setTimeout( (fn = () => { id = setTimeout(fn, 35) callback() //fire after everything in case the user cancels on the first call }), 500 ) return cancel } function clamp(value, min, max) { max = max == null ? Infinity : max min = min == null ? -Infinity : min if (value == null || value === '') return null return Math.max(Math.min(value, max), min) } /** * --- * localized: true, * shortcuts: * - { key: down arrow, label: decrement value } * - { key: up arrow, label: increment value } * - { key: home, label: set value to minimum value, if finite } * - { key: end, label: set value to maximum value, if finite } * --- * * @public */ @withRightToLeft class NumberPicker extends React.Component { static propTypes = { value: PropTypes.number, /** * @example ['onChangePicker', [ [1, null] ]] */ onChange: PropTypes.func, /** * The minimum number that the NumberPicker value. * @example ['prop', ['min', 0]] */ min: PropTypes.number, /** * The maximum number that the NumberPicker value. * * @example ['prop', ['max', 0]] */ max: PropTypes.number, /** * Amount to increase or decrease value when using the spinner buttons. * * @example ['prop', ['step', 5]] */ step: PropTypes.number, /** * Specify how precise the `value` should be when typing, incrementing, or decrementing the value. * When empty, precision is parsed from the current `format` and culture. */ precision: PropTypes.number, culture: PropTypes.string, /** * A format string used to display the number value. Localizer dependent, read [localization](/i18n) for more info. * * @example ['prop', { max: 1, min: -1 , defaultValue: 0.2585, format: "{ style: 'percent' }" }] */ format: CustomPropTypes.numberFormat, /** * Determines how the NumberPicker parses a number from the localized string representation. * You can also provide a parser `function` to pair with a custom `format`. */ parse: PropTypes.func, /** @ignore */ tabIndex: PropTypes.any, name: PropTypes.string, placeholder: PropTypes.string, onKeyDown: PropTypes.func, onKeyPress: PropTypes.func, onKeyUp: PropTypes.func, autoFocus: PropTypes.bool, disabled: CustomPropTypes.disabled, readOnly: CustomPropTypes.disabled, inputProps: PropTypes.object, messages: PropTypes.shape({ increment: PropTypes.string, decrement: PropTypes.string, }), } static defaultProps = { value: null, open: false, min: -Infinity, max: Infinity, step: 1, } constructor(...args) { super(...args) this.messages = getMessages(this.props.messages) this.focusManager = focusManager(this, { willHandle: focused => { if (focused) this.focus() }, }) this.state = { focused: false, } } componentWillReceiveProps({ messages }) { this.messages = getMessages(messages) } @widgetEditable handleMouseDown = (direction, event) => { let { min, max } = this.props event && event.persist() let method = direction === directions.UP ? this.increment : this.decrement let value = method.call(this, event), atTop = direction === directions.UP && value === max, atBottom = direction === directions.DOWN && value === min if (atTop || atBottom) this.handleMouseUp() else if (!this._cancelRepeater) { this._cancelRepeater = createInterval(() => { this.handleMouseDown(direction, event) }) } } @widgetEditable handleMouseUp = () => { this._cancelRepeater && this._cancelRepeater() this._cancelRepeater = null } @widgetEditable handleKeyDown = event => { let { min, max, onKeyDown } = this.props let key = event.key notify(onKeyDown, [event]) if (event.defaultPrevented) return if (key === 'End' && isFinite(max)) this.handleChange(max, event) else if (key === 'Home' && isFinite(min)) this.handleChange(min, event) else if (key === 'ArrowDown') { event.preventDefault() this.decrement(event) } else if (key === 'ArrowUp') { event.preventDefault() this.increment(event) } } handleChange = (rawValue, originalEvent = null) => { let { onChange, value: lastValue, min, max } = this.props let nextValue = clamp(rawValue, min, max) if (lastValue !== nextValue) notify(onChange, [ nextValue, { rawValue, lastValue, originalEvent, }, ]) } renderInput(value) { let { placeholder, autoFocus, tabIndex, parse, name, onKeyPress, onKeyUp, min, max, disabled, readOnly, inputProps, format, culture, } = this.props return ( <Input {...inputProps} ref="input" role="spinbutton" tabIndex={tabIndex} value={value} placeholder={placeholder} autoFocus={autoFocus} editing={this.state.focused} format={format} culture={culture} parse={parse} name={name} min={min} max={max} disabled={disabled} readOnly={readOnly} onChange={this.handleChange} onKeyPress={onKeyPress} onKeyUp={onKeyUp} /> ) } render() { let { className, disabled, readOnly, value, min, max } = this.props let { focused } = this.state let elementProps = Props.pickElementProps(this) value = clamp(value, min, max) return ( <Widget {...elementProps} focused={focused} disabled={disabled} readOnly={readOnly} onKeyDown={this.handleKeyDown} onBlur={this.focusManager.handleBlur} onFocus={this.focusManager.handleFocus} className={cn(className, 'rw-number-picker')} > <WidgetPicker> {this.renderInput(value)} <Select bordered> <Button icon="caret-up" onClick={this.handleFocus} disabled={value === max || disabled} label={this.messages.increment({ value, min, max })} onMouseUp={e => this.handleMouseUp(directions.UP, e)} onMouseDown={e => this.handleMouseDown(directions.UP, e)} onMouseLeave={e => this.handleMouseUp(directions.UP, e)} /> <Button icon="caret-down" onClick={this.handleFocus} disabled={value === min || disabled} label={this.messages.decrement({ value, min, max })} onMouseUp={e => this.handleMouseUp(directions.DOWN, e)} onMouseDown={e => this.handleMouseDown(directions.DOWN, e)} onMouseLeave={e => this.handleMouseUp(directions.DOWN, e)} /> </Select> </WidgetPicker> </Widget> ) } focus() { findDOMNode(this.refs.input).focus() } increment(event) { return this.step(this.props.step, event) } decrement(event) { return this.step(-this.props.step, event) } step(amount, event) { var value = (this.props.value || 0) + amount var decimals = this.props.precision != null ? this.props.precision : numberLocalizer.precision(format(this.props)) this.handleChange(decimals != null ? round(value, decimals) : value, event) return value } } export default uncontrollable( NumberPicker, { value: 'onChange', }, ['focus'] ) // thank you kendo ui core // https://github.com/telerik/kendo-ui-core/blob/master/src/kendo.core.js#L1036 function round(value, precision) { precision = precision || 0 value = ('' + value).split('e') value = Math.round( +(value[0] + 'e' + (value[1] ? +value[1] + precision : precision)) ) value = ('' + value).split('e') value = +(value[0] + 'e' + (value[1] ? +value[1] - precision : -precision)) return value.toFixed(precision) } <file_sep>/packages/react-widgets/src/Month.js import cn from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import CalendarView from './CalendarView'; import dates from './util/dates'; import { date as dateLocalizer } from './util/localizers'; import * as CustomPropTypes from './util/PropTypes'; import { chunk } from './util/_'; import * as Props from './util/Props'; let isEqual = (dateA, dateB) => dates.eq(dateA, dateB, 'day') class MonthView extends React.Component { static propTypes = { activeId: PropTypes.string, culture: PropTypes.string, today: PropTypes.instanceOf(Date), value: PropTypes.instanceOf(Date), focused: PropTypes.instanceOf(Date), min: PropTypes.instanceOf(Date), max: PropTypes.instanceOf(Date), onChange: PropTypes.func.isRequired, dayComponent: CustomPropTypes.elementType, dayFormat: CustomPropTypes.dateFormat, dateFormat: CustomPropTypes.dateFormat, footerFormat: CustomPropTypes.dateFormat, disabled: PropTypes.bool, }; static isEqual = isEqual; renderRow = (row, rowIdx) => { let { focused , today , activeId , disabled , onChange , value , culture, min, max , footerFormat , dateFormat , dayComponent: Day } = this.props footerFormat = dateLocalizer.getFormat('footer', footerFormat) dateFormat = dateLocalizer.getFormat('dayOfMonth', dateFormat) return ( <CalendarView.Row key={rowIdx}> {row.map((date, colIdx) => { let formattedDate = dateLocalizer.format(date, dateFormat, culture) let label = dateLocalizer.format(date, footerFormat, culture); return ( <CalendarView.Cell key={colIdx} activeId={activeId} label={label} date={date} now={today} min={min} max={max} unit="day" viewUnit="month" onChange={onChange} focused={focused} selected={value} disabled={disabled} > {Day ? <Day date={date} label={formattedDate}/> : formattedDate} </CalendarView.Cell> ) })} </CalendarView.Row> ) } renderHeaders(week, format, culture) { let firstOfWeek = dateLocalizer.firstOfWeek(culture); return week.map(date => { return ( <th key={'header_' + dates.weekday(date, undefined, firstOfWeek) }> { dateLocalizer.format(date, format, culture) } </th> ) }) } render() { let { className, focused, culture, activeId, dayFormat } = this.props let month = dates.visibleDays(focused, culture) let rows = chunk(month, 7); dayFormat = dateLocalizer.getFormat('weekday', dayFormat) return ( <CalendarView {...Props.omitOwn(this)} activeId={activeId} className={cn(className, 'rw-calendar-month')} > <thead> <tr> {this.renderHeaders(rows[0], dayFormat, culture)} </tr> </thead> <CalendarView.Body > {rows.map(this.renderRow)} </CalendarView.Body> </CalendarView> ) } } export default MonthView <file_sep>/packages/react-widgets/test/Calendar-test.js import transform from 'lodash/transform'; import React from 'react' import { mount, shallow } from 'enzyme'; import Calendar from '../src/Calendar' import Footer from '../src/Footer'; import Month from '../src/Month'; import Year from '../src/Year'; import Decade from '../src/Decade'; import Century from '../src/Century'; import { directions } from '../src/util/constants'; import dates from '../src/util/dates'; import globalize from 'globalize'; const BaseCalendar = Calendar.ControlledComponent; describe('Calendar', () => { let originalTransition; beforeEach(() => { originalTransition = BaseCalendar.Transition; BaseCalendar.Transition = (props) => props.children; }) afterEach(() => { BaseCalendar.Transition = originalTransition }) it('should set default View', () => { mount( <Calendar defaultValue={new Date()} defaultView='year' /> ) .assertSingle(Year); }) it('should click up through views', () => { let date = new Date() let calendar = mount(<Calendar defaultValue={date} />) let navBtn = calendar.find('button.rw-calendar-btn-view') calendar.assertSingle(Month); navBtn.simulate('click'); calendar.assertSingle(Year); navBtn.simulate('click'); calendar.assertSingle(Decade); navBtn.simulate('click'); calendar.assertSingle(Century); expect(navBtn.getDOMNode().hasAttribute('disabled')).to.equal(true) }) it('should key up through views', () => { let date = new Date() let keys = { ctrlKey: true, key: 'ArrowUp' }; let wrapper = mount(<Calendar defaultValue={date} />) wrapper.assertSingle(Month) wrapper.simulate('keyDown', keys) .assertSingle(Year) wrapper.simulate('keyDown', keys) .assertSingle(Decade) wrapper.simulate('keyDown', keys) .assertSingle(Century); }) it('should navigate into the past', () => { var date= new Date(2014, 5, 15, 0, 0, 0) let calendar = mount(<Calendar defaultValue={date} />) let leftBtn = calendar.find('button.rw-calendar-btn-left') let navBtn = calendar.find('button.rw-calendar-btn-view') leftBtn.simulate('click'); expect( calendar .assertSingle(Month).prop('focused') .getMonth() ).to.equal(4); navBtn.simulate('click'); leftBtn.simulate('click'); expect( calendar .assertSingle(Year).prop('focused') .getFullYear() ).to.equal(2013); navBtn.simulate('click'); leftBtn.simulate('click'); expect( calendar .assertSingle(Decade).prop('focused') .getFullYear() ).to.equal(2003); navBtn.simulate('click'); leftBtn.simulate('click'); expect( calendar .assertSingle(Century).prop('focused') .getFullYear() ).to.equal(1903); }) it('should navigate into the future', () => { let date = new Date(2014, 5, 15, 0, 0, 0) let calendar = mount( <Calendar defaultValue={date} max={new Date(2199, 11, 31)} /> ) let rightBtn = calendar.find('button.rw-calendar-btn-right') let navBtn = calendar.find('button.rw-calendar-btn-view') rightBtn.simulate('click'); expect( calendar .assertSingle(Month).prop('focused') .getMonth() ).to.equal(6); navBtn.simulate('click'); rightBtn.simulate('click'); expect( calendar .assertSingle(Year).prop('focused') .getFullYear() ).to.equal(2015); navBtn.simulate('click'); rightBtn.simulate('click'); expect( calendar .assertSingle(Decade).prop('focused') .getFullYear() ).to.equal(2025); navBtn.simulate('click'); rightBtn.simulate('click'); expect( calendar .assertSingle(Century).prop('focused') .getFullYear() ).to.equal(2125); }) it('should have a footer', () => { let wrapper = shallow(<BaseCalendar footer={false} />) wrapper.assertNone(Footer) wrapper .setProps({ footer: true }) .assertSingle(Footer); }) it('should display date in footer', () => { expect( mount(<BaseCalendar />) .assertSingle(Footer) .text() ) .to.equal(globalize.format(new Date(), 'D')); }) it('should accept footer format', () => { let formatter = sinon.spy((dt, culture) => { expect(dt).to.be.a('Date') expect(culture).to.be.a('string').and.equal('en') return 'test' }) expect( mount(<BaseCalendar footerFormat={formatter} culture='en'/>) .assertSingle(Footer) .text() ) .to.equal('test') expect(formatter.called).to.equal(true) }) it('should navigate to footer date', () => { let changeSpy = sinon.spy(); mount( <BaseCalendar value={new Date(2013, 5, 15)} onChange={changeSpy} /> ) .find(Footer) .find('button') .simulate('click') expect( changeSpy.calledOnce ) .to.equal(true) }) it('should constrain movement by min and max', () => { let changeSpy = sinon.spy(); let date = new Date(2014, 5, 15); let wrapper = mount( <Calendar defaultValue={date} max={new Date(2014, 5, 25)} min={new Date(2014, 5, 5)} onCurrentDateChange={changeSpy} /> ) wrapper .find('button.rw-calendar-btn-right') .tap(inst => inst.is('[disabled]')) .simulate('click') wrapper .find('button.rw-calendar-btn-left') .tap(inst => inst.is('[disabled]')) .simulate('click') expect(changeSpy.called).to.equal(false) }) it('should use passed in culture', () => { require('globalize/lib/cultures/globalize.culture.es') let date = new Date(2014, 5, 15) let calendar = mount( <Calendar value={date} culture='es' onChange={()=>{}} /> ) expect( calendar.find('button.rw-calendar-btn-view').contains('junio 2014') ).to.equal(true) expect( calendar.first('thead th').contains('lu') ).to.equal(true) calendar = mount( <Calendar defaultView='year' value={date} culture='es' onChange={()=>{}} /> ) expect( calendar.first('tbody td').contains('ene') ) .to.equal(true) }) it('should pass on format', () => { let date = new Date(2014, 5, 15) let formats = transform( ['dayFormat', 'dateFormat', 'monthFormat', 'yearFormat', 'decadeFormat' ], (o, v) => o[v] = v, {} ) let calendar = mount( <Calendar {...formats} value={date} onChange={()=>{}} onViewChange={()=>{}} /> ) expect( calendar.assertSingle(Month).prop('dayFormat') ) .to.equal('dayFormat'); expect( calendar.assertSingle(Month).prop('dateFormat') ) .to.equal('dateFormat'); calendar.setProps({ view: 'year' }) expect( calendar.assertSingle(Year).prop('monthFormat') ) .to.equal('monthFormat'); calendar.setProps({view: 'decade' }) expect( calendar.assertSingle(Decade).prop('yearFormat') ) .to.equal('yearFormat'); calendar.setProps({view: 'century' }) expect( calendar.assertSingle(Century).prop('decadeFormat') ) .to.equal('decadeFormat'); }) it('should accept a currentDate', () => { let focused = mount( <Calendar currentDate={new Date(2000, 1, 15)} onCurrentDateChange={()=>{}} /> ) .assertSingle(Month) .prop('focused') expect(focused.getFullYear()).to.equal(2000); expect(focused.getMonth()).to.equal(1); expect(focused.getDate()).to.equal(15); }) describe('Date Helpers', () => { it('should move to the proper day', () => { var date = new Date(2014, 0, 16, 0, 0, 0) , min, max; expect(dates.move(date, min, max, 'month', directions.LEFT).toString()) .to.equal((new Date(2014, 0, 15, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'month', directions.RIGHT).toString()) .to.equal((new Date(2014, 0, 17, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'month', directions.UP).toString()) .to.equal((new Date(2014, 0, 9, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'month', directions.DOWN).toString()) .to.equal((new Date(2014, 0, 23, 0, 0, 0)).toString()) min = new Date(2014, 0, 11, 0, 0, 0) max = new Date(2014, 0, 20, 0, 0, 0) expect(dates.move(date, min, max, 'month', directions.UP)) .to.eql(date) expect(dates.move(date, min, max, 'month', directions.DOWN)) .to.eql(date) }) it('should move to the proper month', () => { var date = new Date(2014, 6, 16, 0, 0, 0) , min, max; expect(dates.move(date, min, max, 'year', directions.LEFT).toString()) .to.equal((new Date(2014, 5, 16, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'year', directions.RIGHT).toString()) .to.equal((new Date(2014, 7, 16, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'year', directions.UP).toString()) .to.equal((new Date(2014, 2, 16, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'year', directions.DOWN).toString()) .to.equal((new Date(2014, 10, 16, 0, 0, 0)).toString()) min = new Date(2014, 3, 16, 0, 0, 0) max = new Date(2014, 8, 16, 0, 0, 0) expect(dates.move(date, min, max, 'year', directions.UP)) .to.eql(date) expect(dates.move(date, min, max, 'year', directions.DOWN)) .to.eql(date) }) it('should move to the proper year', () => { var date = new Date(2015, 6, 16, 0, 0, 0) , min, max; expect(dates.move(date, min, max, 'decade', directions.LEFT).toString()) .to.equal((new Date(2014, 6, 16, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'decade', directions.RIGHT).toString()) .to.equal((new Date(2016, 6, 16, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'decade', directions.UP).toString()) .to.equal((new Date(2011, 6, 16, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'decade', directions.DOWN).toString()) .to.equal((new Date(2019, 6, 16, 0, 0, 0)).toString()) min = new Date(2014, 6, 16, 0, 0, 0) max = new Date(2016, 6, 16, 0, 0, 0) expect(dates.move(date, min, max, 'decade', directions.UP)) .to.eql(date) expect(dates.move(date, min, max, 'decade', directions.DOWN)) .to.eql(date) }) it('should move to the proper decade', () => { var date = new Date(2055, 6, 16, 0, 0, 0) , min, max; expect(dates.move(date, min, max, 'century', directions.LEFT).toString()) .to.equal((new Date(2045, 6, 16, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'century', directions.RIGHT).toString()) .to.equal((new Date(2065, 6, 16, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'century', directions.UP).toString()) .to.equal((new Date(2015, 6, 16, 0, 0, 0)).toString()) expect(dates.move(date, min, max, 'century', directions.DOWN).toString()) .to.equal((new Date(2095, 6, 16, 0, 0, 0)).toString()) min = new Date(2045, 6, 16, 0, 0, 0) max = new Date(2065, 6, 16, 0, 0, 0) expect(dates.move(date, min, max, 'century', directions.UP)) .to.eql(date) expect(dates.move(date, min, max, 'century', directions.DOWN)) .to.eql(date) }) }) }) <file_sep>/packages/storybook/webpack.config.js const path = require('path') const { plugins, rules } = require('webpack-atoms') module.exports = (baseConfig) => Object.assign({}, baseConfig, { module: { rules: [ { parser: { amd: false } }, rules.js.inlineCss({ tagName: 'less', extension: '.less' }), rules.css(), rules.less(), rules.images(), rules.woff(), ], }, resolve: { symlinks: false, alias: { 'react-widgets$': path.resolve('../react-widgets/src/index.js'), 'react-widgets/lib': path.resolve('../react-widgets/src'), 'react-widgets-virtualized$': path.resolve('../virtualized/src/index.js'), 'react-widgets-virtualized/lib': path.resolve('../virtualized/src') } }, plugins: [ plugins.define(), plugins.extractText(), plugins.hotModuleReplacement(), ], node: { Buffer: false, fs: 'empty', net: 'empty', tls: 'empty', }, } ) <file_sep>/packages/react-widgets/src/DateTimePicker.js import invariant from 'invariant' import PropTypes from 'prop-types' import React from 'react' import { findDOMNode } from 'react-dom' import activeElement from 'dom-helpers/activeElement' import cn from 'classnames' import deprecated from 'react-prop-types/lib/deprecated' import uncontrollable from 'uncontrollable' import Widget from './Widget' import WidgetPicker from './WidgetPicker' import Popup from './Popup' import Button from './Button' import BaseCalendar from './Calendar' import DateTimePickerInput from './DateTimePickerInput' import Select from './Select' import TimeList from './TimeList' import { getMessages } from './messages' import * as Props from './util/Props' import * as CustomPropTypes from './util/PropTypes' import focusManager from './util/focusManager' import scrollManager from './util/scrollManager' import withRightToLeft from './util/withRightToLeft' import { widgetEditable } from './util/interaction' import dates from './util/dates' import { date as dateLocalizer } from './util/localizers' import { datePopups as popups } from './util/constants' import { instanceId, notify, isFirstFocusedRender } from './util/widgetHelpers' let NEXT_VIEW = { [popups.DATE]: popups.TIME, [popups.TIME]: popups.DATE, } let isBothOrNeither = (a, b) => (a && b) || (!a && !b) let propTypes = { ...BaseCalendar.ControlledComponent.propTypes, value: PropTypes.instanceOf(Date), /** * @example ['onChangePicker', [ ['new Date()', null] ]] */ onChange: PropTypes.func, /** * @type (false | 'time' | 'date') */ open: PropTypes.oneOf([false, popups.TIME, popups.DATE]), onToggle: PropTypes.func, /** * Default current date at which the calendar opens. If none is provided, opens at today's date or the `value` date (if any). */ currentDate: PropTypes.instanceOf(Date), /** * Change event Handler that is called when the currentDate is changed. The handler is called with the currentDate object. */ onCurrentDateChange: PropTypes.func, onSelect: PropTypes.func, /** * The minimum Date that can be selected. Min only limits selection, it doesn't constrain the date values that * can be typed or pasted into the widget. If you need this behavior you can constrain values via * the `onChange` handler. * * @example ['prop', ['min', 'new Date()']] */ min: PropTypes.instanceOf(Date), /** * The maximum Date that can be selected. Max only limits selection, it doesn't constrain the date values that * can be typed or pasted into the widget. If you need this behavior you can constrain values via * the `onChange` handler. * * @example ['prop', ['max', 'new Date()']] */ max: PropTypes.instanceOf(Date), /** * The amount of minutes between each entry in the time list. * * @example ['prop', { step: 90 }] */ step: PropTypes.number, culture: PropTypes.string, /** * A formatter used to display the date value. For more information about formats * visit the [Localization page](/i18n) * * @example ['dateFormat', ['format', "{ raw: 'MMM dd, yyyy' }", null, { defaultValue: 'new Date()', time: 'false' }]] */ format: CustomPropTypes.dateFormat, /** * A formatter used by the time dropdown to render times. For more information about formats visit * the [Localization page](/i18n). * * @example ['dateFormat', ['timeFormat', "{ time: 'medium' }", null, { date: 'false', open: '"time"' }]] */ timeFormat: CustomPropTypes.dateFormat, /** * A formatter to be used while the date input has focus. Useful for showing a simpler format for inputing. * For more information about formats visit the [Localization page](/i18n) * * @example ['dateFormat', ['editFormat', "{ date: 'short' }", null, { defaultValue: 'new Date()', format: "{ raw: 'MMM dd, yyyy' }", time: 'false' }]] */ editFormat: CustomPropTypes.dateFormat, /** * Enable the calendar component of the picker. */ date: PropTypes.bool, /** * Enable the time list component of the picker. */ time: PropTypes.bool, /** @ignore */ calendar: deprecated(PropTypes.bool, 'Use `date` instead'), /** * A customize the rendering of times but providing a custom component. */ timeComponent: CustomPropTypes.elementType, dropUp: PropTypes.bool, popupTransition: CustomPropTypes.elementType, placeholder: PropTypes.string, name: PropTypes.string, autoFocus: PropTypes.bool, disabled: CustomPropTypes.disabled, readOnly: CustomPropTypes.disabled, /** * Determines how the widget parses the typed date string into a Date object. You can provide an array of formats to try, * or provide a function that returns a date to handle parsing yourself. When `parse` is unspecified and * the `format` prop is a `string` parse will automatically use that format as its default. */ parse: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.string), PropTypes.string, PropTypes.func, ]), /** @ignore */ tabIndex: PropTypes.any, /** @ignore */ 'aria-labelledby': PropTypes.string, /** @ignore */ 'aria-describedby': PropTypes.string, onKeyDown: PropTypes.func, onKeyPress: PropTypes.func, onBlur: PropTypes.func, onFocus: PropTypes.func, inputProps: PropTypes.object, messages: PropTypes.shape({ dateButton: PropTypes.string, timeButton: PropTypes.string, }), } /** * --- * subtitle: DatePicker, TimePicker * localized: true * shortcuts: * - { key: alt + down arrow, label: open calendar or time } * - { key: alt + up arrow, label: close calendar or time } * - { key: down arrow, label: move focus to next item } * - { key: up arrow, label: move focus to previous item } * - { key: home, label: move focus to first item } * - { key: end, label: move focus to last item } * - { key: enter, label: select focused item } * - { key: any key, label: search list for item starting with key } * --- * * @public * @extends Calendar */ @withRightToLeft class DateTimePicker extends React.Component { static displayName = 'DateTimePicker' static propTypes = propTypes static defaultProps = { ...BaseCalendar.ControlledComponent.defaultProps, value: null, min: new Date(1900, 0, 1), max: new Date(2099, 11, 31), date: true, time: true, open: false, } constructor(...args) { super(...args) this.messages = getMessages(this.props.messages) this.inputId = instanceId(this, '_input') this.dateId = instanceId(this, '_date') this.listId = instanceId(this, '_listbox') this.activeCalendarId = instanceId(this, '_calendar_active_cell') this.activeOptionId = instanceId(this, '_listbox_active_option') this.handleScroll = scrollManager(this) this.focusManager = focusManager(this, { didHandle: focused => { if (!focused) this.close() }, }) this.state = { focused: false, } } componentWillReceiveProps({ messages }) { this.messages = getMessages(messages) } @widgetEditable handleChange = (date, str, constrain) => { let { onChange, value } = this.props if (constrain) date = this.inRangeValue(date) if (onChange) { if (date == null || value == null) { if ( date != value //eslint-disable-line eqeqeq ) onChange(date, str) } else if (!dates.eq(date, value)) { onChange(date, str) } } } @widgetEditable handleKeyDown = e => { let { open, onKeyDown } = this.props notify(onKeyDown, [e]) if (e.defaultPrevented) return if (e.key === 'Escape' && open) this.close() else if (e.altKey) { if (e.key === 'ArrowDown') { e.preventDefault() this.open() } else if (e.key === 'ArrowUp') { e.preventDefault() this.close() } } else if (open) { if (open === popups.DATE) this.refs.calPopup.refs.inner.handleKeyDown(e) if (open === popups.TIME) this.refs.timePopup.handleKeyDown(e) } } @widgetEditable handleKeyPress = e => { notify(this.props.onKeyPress, [e]) if (e.defaultPrevented) return if (this.props.open === popups.TIME) this.refs.timePopup.handleKeyPress(e) } @widgetEditable handleDateSelect = date => { var format = getFormat(this.props), dateTime = dates.merge(date, this.props.value, this.props.currentDate), dateStr = formatDate(date, format, this.props.culture) this.close() notify(this.props.onSelect, [dateTime, dateStr]) this.handleChange(dateTime, dateStr, true) this.focus() } @widgetEditable handleTimeSelect = datum => { var format = getFormat(this.props), dateTime = dates.merge( this.props.value, datum.date, this.props.currentDate ), dateStr = formatDate(datum.date, format, this.props.culture) this.close() notify(this.props.onSelect, [dateTime, dateStr]) this.handleChange(dateTime, dateStr, true) this.focus() } @widgetEditable handleCalendarClick = () => { this.focus() this.toggle(popups.DATE) } @widgetEditable handleTimeClick = () => { this.focus() this.toggle(popups.TIME) } renderInput(owns) { let { open, value, editFormat, culture, placeholder, disabled, readOnly, name, tabIndex, autoFocus, inputProps, 'aria-labelledby': ariaLabelledby, 'aria-describedby': ariaDescribedby, } = this.props let { focused } = this.state let activeId = null if (open === popups.TIME) { activeId = this.activeOptionId } else if (open === popups.DATE) { activeId = this.activeCalendarId } return ( <DateTimePickerInput {...inputProps} id={this.inputId} ref="valueInput" role="combobox" name={name} tabIndex={tabIndex} autoFocus={autoFocus} placeholder={placeholder} disabled={disabled} readOnly={readOnly} value={value} format={getFormat(this.props)} editFormat={editFormat} editing={focused} culture={culture} parse={this.parse} onChange={this.handleChange} aria-haspopup aria-activedescendant={activeId} aria-labelledby={ariaLabelledby} aria-describedby={ariaDescribedby} aria-expanded={!!open} aria-owns={owns} /> ) } renderButtons() { let { date, time, disabled, readOnly } = this.props if (!date && !time) { return null } let messages = this.messages return ( <Select bordered> {date && <Button icon="calendar" label={messages.dateButton()} disabled={disabled || readOnly} onClick={this.handleCalendarClick} />} {time && <Button icon="clock-o" label={messages.timeButton()} disabled={disabled || readOnly} onClick={this.handleTimeClick} />} </Select> ) } renderCalendar() { let { activeCalendarId, inputId, dateId } = this let { open, value, popupTransition, dropUp, onCurrentDateChange, currentDate } = this.props let calendarProps = Props.pick(this.props, BaseCalendar.ControlledComponent) return ( <Popup dropUp={dropUp} open={open === popups.DATE} className="rw-calendar-popup" transition={popupTransition} > <BaseCalendar {...calendarProps} ref="calPopup" id={dateId} activeId={activeCalendarId} tabIndex="-1" value={value} autoFocus={false} onChange={this.handleDateSelect} // #75: need to aggressively reclaim focus from the calendar otherwise // disabled header/footer buttons will drop focus completely from the widget onNavigate={() => this.focus()} currentDate={currentDate} onCurrentDateChange={onCurrentDateChange} aria-hidden={!open} aria-live="polite" aria-labelledby={inputId} /> </Popup> ) } renderTimeList() { let { activeOptionId, inputId, listId } = this let { open, value, min, max, step, currentDate, dropUp, date, culture, timeFormat, timeComponent, popupTransition, } = this.props return ( <Popup dropUp={dropUp} transition={popupTransition} open={open === popups.TIME} onEntering={() => this.refs.timePopup.forceUpdate()} > <div> <TimeList ref="timePopup" id={listId} min={min} max={max} step={step} currentDate={currentDate} activeId={activeOptionId} format={timeFormat} culture={culture} value={dateOrNull(value)} onMove={this.handleScroll} onSelect={this.handleTimeSelect} preserveDate={!!date} itemComponent={timeComponent} aria-labelledby={inputId} aria-live={open && 'polite'} aria-hidden={!open} messages={this.messages} /> </div> </Popup> ) } render() { let { className, date, time, open, disabled, readOnly, dropUp } = this.props let { focused } = this.state let elementProps = Props.pickElementProps(this, BaseCalendar.ControlledComponent) let shouldRenderList = open || isFirstFocusedRender(this) let owns = '' if (date) owns += this.dateId if (time) owns += ' ' + this.listId return ( <Widget {...elementProps} open={!!open} dropUp={dropUp} focused={focused} disabled={disabled} readOnly={readOnly} onKeyDown={this.handleKeyDown} onKeyPress={this.handleKeyPress} onBlur={this.focusManager.handleBlur} onFocus={this.focusManager.handleFocus} className={cn(className, 'rw-datetime-picker')} > <WidgetPicker> {this.renderInput(owns.trim())} {this.renderButtons()} </WidgetPicker> {!!(shouldRenderList && time) && this.renderTimeList()} {!!(shouldRenderList && date) && this.renderCalendar()} </Widget> ) } focus() { let { valueInput } = this.refs if (valueInput && activeElement() !== findDOMNode(valueInput)) valueInput.focus() } parse = string => { const { parse, culture, editFormat } = this.props const format = getFormat(this.props, true) let parsers = [] if (format != null) parsers.push(format) if (editFormat != null) parsers.push(editFormat) invariant( parsers.length, 'React Widgets: there are no specified `parse` formats provided and the `format` prop is a function. ' + 'the DateTimePicker is unable to parse `%s` into a dateTime, ' + 'please provide either a parse function or localizer compatible `format` prop', string ) parsers.sort(sortFnsFirst) if (parse) parsers = [].concat(parse, parsers) let date for (var i = 0; i < parsers.length; i++) { date = parseDate(string, parsers[i], culture) if (date) return date } return null } toggle(view) { const { open } = this.props if (!open || open !== view) this.open(view) else this.close() } open(view) { const { open, date, time, onToggle } = this.props if (!view) { if (time) view = popups.TIME if (date) view = popups.DATE if (isBothOrNeither(date, time)) view = NEXT_VIEW[open] || popups.DATE } if (open !== view) notify(onToggle, view) } close() { if (this.props.open) notify(this.props.onToggle, false) } inRangeValue(value) { if (value == null) return value return dates.max(dates.min(value, this.props.max), this.props.min) } } export default uncontrollable( DateTimePicker, { open: 'onToggle', value: 'onChange', currentDate: 'onCurrentDateChange', }, ['focus'] ) function parseDate(string, parser, culture) { return typeof parser === 'function' ? parser(string, culture) : dateLocalizer.parse(string, parser, culture) } function getFormat(props) { var isDate = props[popups.DATE] != null ? props[popups.DATE] : true, isTime = props[popups.TIME] != null ? props[popups.TIME] : true return props.format ? props.format : (isDate && isTime) || (!isDate && !isTime) ? dateLocalizer.getFormat('default') : dateLocalizer.getFormat(isDate ? 'date' : 'time') } function formatDate(date, format, culture) { var val = '' if (date instanceof Date && !isNaN(date.getTime())) val = dateLocalizer.format(date, format, culture) return val } function sortFnsFirst(a, b) { let aFn = typeof a === 'function' let bFn = typeof b === 'function' if (aFn && !bFn) return -1 if (!aFn && bFn) return 1 if ((aFn && bFn) || (!aFn && !bFn)) return 0 } function dateOrNull(dt) { if (dt && !isNaN(dt.getTime())) return dt return null } <file_sep>/packages/react-widgets/test/Multiselect-test.js import React from 'react'; import { mount, shallow } from 'enzyme'; import Multiselect from '../src/Multiselect'; import MultiselectTag from '../src/MultiselectTag'; import MultiselectTagList from '../src/MultiselectTagList'; describe('Multiselect', function() { const ControlledMultiselect = Multiselect.ControlledComponent; let dataList = [ { label: 'jimmy', id: 0 }, { label: 'sally', id: 1 }, { label: 'pat', id: 2 } ]; it('should set initial values', function() { mount(<Multiselect value={['hello']} onChange={()=>{}} />) .find(MultiselectTag) .contains('hello') }) it('should respect textField and valueFields', function(){ mount(<Multiselect defaultValue={[0]} data={dataList} textField='label' valueField='id' />) .find(MultiselectTag) .contains('jimmy') }) it('should start closed', () => { let wrapper = shallow( <ControlledMultiselect value={dataList.slice(0, 2)} data={dataList} textField='label' valueField='id' /> ) expect(wrapper.prop('open')).to.not.equal(true) expect(wrapper.find('Popup').prop('open')).to.not.equal(true) wrapper.assertNone('.rw-open') wrapper.assertSingle(`MultiselectInput[aria-expanded=false]`) }) it('should toggle add aria when open', () => { let inst = shallow(<ControlledMultiselect open />) expect(inst.prop('open')).to.equal(true) inst.assertSingle('Popup[open]') inst.assertSingle('Widget[open]') inst.assertSingle('MultiselectInput[aria-expanded]') }) it('should foward props to Popup', () => { let props = shallow(<ControlledMultiselect open dropUp />) .find('Popup') .props() expect(props.dropUp).to.equal(true) expect(props.open).to.equal(true) }) it('should open when clicked', (done) => { let openSpy = sinon.spy(); mount(<ControlledMultiselect onToggle={openSpy} />) .find('WidgetPicker') .simulate('click') setTimeout(() => { expect(openSpy.calledOnce).to.equal(true); expect(openSpy.calledWith(true)).to.equal(true); done() }) }) it('should not open when disabled', (done) => { let openSpy = sinon.spy(); mount(<ControlledMultiselect onToggle={openSpy} disabled />) .simulate('focus') setTimeout(() => { expect(openSpy.called).to.equal(false); done() }) }) it('should set id on list', () =>{ expect( shallow(<ControlledMultiselect open />) .find('List') .prop('id') ).to.be.a('string'); }) it('should remove tag when clicked', function(){ let del = sinon.spy() mount( <MultiselectTagList id="list" activeId="list_active" data={dataList} onDelete={del} value={dataList.slice(0, 2)} valueAccessor={i => i.id} textAccessor={i => i.label} /> ) .tap(inst => expect(inst.find(MultiselectTag).length).to.equal(2) ) .find('.rw-multiselect-tag-btn') .first() .simulate('click', {}); expect(del.calledOnce).to.equal(true) expect(del.calledWith(dataList[0])).to.equal(true) }) it('should change value when tag is clicked', function(){ let change = sinon.spy() mount( <Multiselect onChange={change} value={dataList.slice(0, 2)} data={dataList} textField='label' valueField='id' /> ) .find('.rw-multiselect-tag-btn') .first() .simulate('click', {}); expect(change.calledOnce).to.equal(true) expect(change.getCall(0).args[0]).to.eql(dataList.slice(1, 2)) }) it('should simulate focus/blur events', function(done){ let blur = sinon.spy() , focus = sinon.spy() mount(<Multiselect onBlur={blur} onFocus={focus}/>) .simulate('focus') .tap(inst => { setTimeout(() => { inst.simulate('blur') setTimeout(() => { expect(focus.calledOnce).to.equal(true) expect(blur.calledOnce).to.equal(true) done() }) }) }); }) it('should not simulate focus/blur events when disabled', function(done){ let blur = sinon.spy() , focus = sinon.spy() mount(<Multiselect disabled onBlur={blur} onFocus={focus}/>) .simulate('focus') .tap(inst => { setTimeout(() => { inst.simulate('blur') setTimeout(() => { expect(focus.called).to.equal(false) expect(blur.called).to.equal(false) done() }) }) }); }) it('should simulate key events', function(){ let kp = sinon.spy() , kd = sinon.spy() , ku = sinon.spy() mount( <Multiselect onKeyPress={kp} onKeyUp={ku} onKeyDown={kd} /> ) .simulate('keyPress') .simulate('keyDown') .simulate('keyUp') expect(kp.calledOnce).to.equal(true) expect(kd.calledOnce).to.equal(true) expect(ku.calledOnce).to.equal(true) }) it('should add correct markup when read-only', () => { let input = mount(<ControlledMultiselect readOnly />) .assertSingle('.rw-input-reset') .getDOMNode() expect(input.hasAttribute('readonly')).to.equal(true); expect(input.getAttribute('aria-readonly')).to.equal('true'); }) it('should add correct markup when disabled', () => { let input = mount(<ControlledMultiselect disabled />) .assertSingle('.rw-input-reset') .getDOMNode() expect(input.hasAttribute('disabled')).to.equal(true); expect(input.getAttribute('aria-disabled')).to.equal('true'); }) it('should disable only certain tags', () => { let change = sinon.spy() mount( <Multiselect onChange={change} defaultValue={[0, 1]} data={dataList} disabled={[1]} textField='label' valueField='id' /> ) .find(MultiselectTagList) .assertSingle('li.rw-state-disabled button.rw-multiselect-tag-btn') .simulate('click') expect(change.called).to.equal(false) }) it('should not remove tags when disabled', () => { let changeSpy = sinon.spy(); mount( <Multiselect disabled onChange={changeSpy} value={['jimmy']} data={dataList} /> ) .find('button.rw-multiselect-tag-btn') .simulate('click') expect(changeSpy.called).to.equal(false) }) it('should not remove disabled tags', function() { let change = sinon.spy(); mount( <Multiselect onChange={change} defaultValue={[1, 0]} data={dataList} disabled={[1]} textField='label' valueField='id' /> ) .find('button.rw-multiselect-tag-btn') .first() .simulate('click') expect(change.called).to.equal(false) }) it('should not remove tags when readOnly', () => { let changeSpy = sinon.spy(); mount( <Multiselect readOnly onChange={changeSpy} value={['jimmy']} data={dataList} /> ) .find('button.rw-multiselect-tag-btn') .simulate('click') expect(changeSpy.called).to.equal(false) }) it('should call onChange with event object from select', function(){ let change = sinon.spy() let value = dataList.slice(0, 1); shallow( <ControlledMultiselect open searchTerm="" value={value} data={dataList} onChange={change} onToggle={() =>{}} /> ) .find('List') .prop('onSelect')(dataList[1], 'foo') expect(change.getCall(0).args[1]).to.eql({ originalEvent: 'foo', lastValue: value, dataItem: dataList[1], action: 'insert', searchTerm: '' }) }) it('should call onSearch with event object from select', function(){ let search = sinon.spy() let value = dataList.slice(0, 1); let event = { target: { value: 'ba' } }; shallow( <ControlledMultiselect open searchTerm="b" value={value} data={dataList} onSearch={search} onToggle={() =>{}} /> ) .assertSingle('MultiselectInput') .simulate('change', event) expect(search.getCall(0).args[1]).to.eql({ originalEvent: event, lastSearchTerm: 'b', action: 'input', }) }) it('should call Select handler', function(){ let change = sinon.spy() let onSelect = sinon.spy(); let value = dataList.slice(1); shallow( <ControlledMultiselect open onToggle={() =>{}} value={value} data={dataList} onChange={change} onSelect={onSelect} /> ) .find('List') .simulate('select', dataList[1], 'foo') expect(onSelect.calledOnce).to.equal(true) expect(onSelect.getCall(0).args[1]).to.eql({ originalEvent: 'foo' }) expect(change.calledAfter(onSelect)).to.equal(true) }) it('should clear search on blur', done => { let onSearch = sinon.spy(); mount( <Multiselect data={dataList} onSearch={onSearch} defaultSearchTerm="foo" /> ) .find('input') .simulate('blur') setTimeout(() => { expect(onSearch.calledOnce).to.equal(true) expect(onSearch.calledWith('')).to.equal(true) done() }) }) it('should clear searchTerm when an item is selected', () => { let searchSpy = sinon.spy(); mount( <Multiselect defaultOpen data={dataList} textField='label' valueField='id' defaultSearchTerm='ji' onSearch={searchSpy} /> ) .simulate('keyDown', { keyCode: 13 }) expect(searchSpy.calledOnce).to.equal(true) expect(searchSpy.calledWith('')).to.equal(true) }) it('should not simulate form submission', function(){ let spy = sinon.spy() mount( <form action='/' onSubmit={() => {throw new Error('should not submit!')}} > <Multiselect searchTerm="jim" data={dataList} onSearch={()=>{}} onKeyDown={spy} /> </form> ) .find('input') .simulate('keyDown', { key: 'Enter' }) expect(spy.calledOnce).to.equal(true); }) it('should show create tag correctly', function(){ mount( <Multiselect defaultOpen searchTerm="custom tag" onCreate={()=>{}} data={dataList} onSearch={()=>{}} textField='label' valueField='id' /> ) .tap(s => s .assertSingle('ul.rw-list-option-create') ) .setProps({ searchTerm: undefined }) .tap(s => s .assertNone('ul.rw-list-option-create') ) .setProps( {searchTerm: 'JIMMY' }) .tap(s => s .assertNone('ul.rw-list-option-create') ) .setProps({ searchTerm: 'custom', onCreate: undefined }) .tap(s => s .assertNone('ul.rw-list-option-create') ) }) it('should show create tag correctly when caseSensitive', function(){ mount( <Multiselect defaultOpen searchTerm="Jimmy" onCreate={()=>{}} data={ dataList } onSearch={()=>{}} textField='label' valueField='id' caseSensitive={true} /> ) .tap(s => s .assertSingle('ul.rw-list-option-create') ) .setProps({ searchTerm: 'jimmy' }) .tap(s => s .assertNone('ul.rw-list-option-create') ) }) it('should call onCreate', function(){ let create = sinon.spy() let assertOnCreateCalled = () => { expect(create.calledOnce).to.equal(true) expect(create.calledWith('custom tag')).to.equal(true) create.reset() }; let wrapper = mount( <Multiselect open searchTerm="custom tag" data={dataList} onCreate={create} onSearch={()=>{}} onToggle={()=>{}} /> ) wrapper .find('.rw-list-option-create .rw-list-option') .simulate('click') .tap(assertOnCreateCalled) wrapper .simulate('keyDown', { keyCode: 13 }) .tap(assertOnCreateCalled) .simulate('keyDown', { keyCode: 13, ctrlKey: true }) .tap(assertOnCreateCalled) }) it('should navigate tags list', function(){ let change = sinon.spy(); let listHead = dataList.slice(0, 2); let inst = mount( <Multiselect value={[0, 1, 2]} data={dataList} textField='label' valueField='id' onChange={change} /> ) let tags = inst.find('MultiselectTagList li'); inst.simulate('keyDown', { key: 'ArrowLeft' }) tags.last().is('.rw-state-focus') inst.simulate('keyDown', { key: 'ArrowRight' }) tags.at(1).is('.rw-state-focus') inst.simulate('keyDown', { key: 'Home' }) tags.first().is('.rw-state-focus') inst.simulate('keyDown', { key: 'End' }) tags.last().is('.rw-state-focus') inst.simulate('keyDown', { key: 'Delete' }) expect(change.calledOnce).to.equal(true) expect(change.calledWith(listHead)).to.equal(true) change.reset() inst.simulate('keyDown', { key: 'Backspace' }) expect(change.calledOnce).to.equal(true) expect(change.calledWith(listHead)).to.equal(true) }) it('should open on ArrowDown', () => { let openSpy = sinon.spy(); mount( <Multiselect data={dataList} onToggle={openSpy} /> ) .simulate('keyDown', { key: 'ArrowDown' }) expect(openSpy.calledOnce).to.equal(true) expect(openSpy.calledWith(true)).to.equal(true) }) it('should navigate list', function(){ let change = sinon.spy(); let inst = mount( <Multiselect defaultOpen data={dataList} textField='label' valueField='id' onChange={change} /> ) let listItems = inst.find('List li'); listItems.first().is('.rw-state-focus') inst.simulate('keyDown', { key: 'ArrowDown' }) listItems.at(1).is('.rw-state-focus') inst.simulate('keyDown', { key: 'ArrowUp' }) listItems.first().is('.rw-state-focus') inst.simulate('keyDown', { key: 'End' }) listItems.last().is('.rw-state-focus') inst.simulate('keyDown', { key: 'Home' }) listItems.first().is('.rw-state-focus') }) })
848076c9455fad254ca465064204e75b94948c07
[ "JavaScript", "Markdown" ]
25
JavaScript
rokborf/react-widgets
4f7452738283e7f6e7327d81144246fc2b56f645
34a848c60ce93d90167d98bf7d1fadd3ce8e321f
refs/heads/master
<repo_name>EverMario/The-way-to-PM<file_sep>/README.md # daily-P.M.<file_sep>/Java language/Singleton/Client.java public class Client { public static void main(String[] args) { Singleton object1 = Singleton.getSingleton(); Singleton object2 = Singleton.getSingleton(); object1.showMessage(); object2.showMessage(); } } <file_sep>/Ruby.rb class WordCounter def initialize(file_name) @file = File.new(file_name).read() end def count @str = @file.force_encoding("UTF-8") @str.lstrip! @str = @str.split(/[\W|\s][\W*|\s*]*/) puts @str.length end def uniq_count puts @str.uniq.length end def frequency $i = 0 $j = 0 $num = @str.length(); wordNum = Hash.new(); while $i < $num do word = @str[$i]; if(wordNum.has_key?(word)) wordNum[word] = wordNum[word] + 1; else wordNum[word] = 1; end $i += 1 end while $j < wordNum.length do puts wordNum.keys[$j] + ": #{wordNum[wordNum.keys[$j]]}" $j += 1 end end end file1 = WordCounter.new(ARGV.first) file1.count file1.uniq_count file1.frequency <file_sep>/C++.cpp #include <iostream> #include <string> #include <regex> using namespace std; class student { private: string StudentFirstName; string StudentLastName; string StudentGNoss; public: student() { this -> StudentFirstName = "no"; this -> StudentLastName = "no"; this -> StudentGNoss = "no"; } ~student() { } void setStudentLastName(string StudentLastName) { this -> StudentLastName = StudentLastName; } string getStudentLastName() { return this -> StudentLastName; } void setStudentFirstName(string StudentFirstName) { this -> StudentFirstName = StudentFirstName; } string getStudentFirstName() { return this -> StudentFirstName; } void setStudentGNoss(string StudentGNoss) { this -> StudentGNoss = StudentGNoss; } string getStudentGNoss() { return this -> StudentGNoss; } }; student p[100]; int total = 0; void addStudent() { string firstName; string lastName; string GNoss; cout << "Please enter a student's first name :" << endl; cin >> firstName; cout << "Please enter a student's last name :" << endl; cin >> lastName; cout << "please enter a student's GWorld Number :" << endl; cin >> GNoss; p[total].setStudentFirstName(firstName); p[total].setStudentLastName(lastName); p[total].setStudentGNoss(GNoss); total++; cout << "Success!" <<endl; } void showAllStudent() { for (int i = 0; i < total; i++) { cout << "FirstName :" << p[i].getStudentFirstName() << "\t\t\tLastName :" << p[i].getStudentLastName() << "\t\t\tGNumber:" << p[i].getStudentGNoss()<< endl; } } void selectStudentByGN() { cout << "Please enter a student's GWorld number :" << endl; string key; cin >> key; for (int i = 0; i < total; i++){ if(regex_search(p[i].getStudentGNoss(),regex(key))){ cout << "FirstName :" << p[i].getStudentFirstName() << "\t\t\tLastName :" << p[i].getStudentLastName() << "\t\t\tGNumber:" << p[i].getStudentGNoss()<< endl; } } } void selectStudentByName() { cout << "Please enter a student's first name :" << endl; string key1; cin >> key1; cout << "Please enter a student's last name :" << endl; string key2; cin >> key2; for (int i = 0; i < total; i++){ if(regex_search(p[i].getStudentFirstName(),regex(key1)) && regex_search(p[i].getStudentLastName(),regex(key2))){ cout << "FirstName :" << p[i].getStudentFirstName() << "\t\t\tLastName :" << p[i].getStudentLastName() << "\t\t\tGNumber:" << p[i].getStudentGNoss()<< endl; } } } void deleteStudentByGN(){ cout << "Please enter a student's GWorld number :" << endl; string key; cin >> key; for (int i = 0; i < total; i++){ if(regex_search(p[i].getStudentGNoss(),regex(key))){ for (int j = i; j < total; j++){ p[j].setStudentFirstName(p[j+1].getStudentFirstName()); p[j].setStudentLastName(p[j+1].getStudentLastName()); p[j].setStudentGNoss(p[j+1].getStudentGNoss()); } total --; i = i-1; } } } void show() { cout << "\n" << endl; cout << "1. Add new a student" << endl; cout << "2. Show all students" << endl; cout << "3. Select students by GWorld number" << endl; cout << "4. Select students by name" << endl; cout << "5. Delete students by GWorld number" << endl; cout << "0. Log out the system" << endl; } int main() { bool quit = false; int choice = 100; while(!quit){ show(); cin >> choice; switch(choice){ case 1 : addStudent(); break; case 2 : showAllStudent(); break; case 3 : selectStudentByGN(); break; case 4 : selectStudentByName(); break; case 5 : deleteStudentByGN(); break; case 0 : quit = true; break; } } return 0; } <file_sep>/C language/StructOrNon.c //struct record #include <stdio.h> struct Student { char name[20]; int age; float gpa; char grade[20]; }; typedef struct Student Record; int main() { Record r[10] = { {"James",18,3.80,"freshman"}, {"Andy",18,3.80,"freshman"}, {"Brandon",18,3.80,"freshman"}, {"Heria",18,3.80,"freshman"}, {"Addison",18,3.80,"freshman"}, {"Keila",18,3.80,"freshman"}, {"Sunny",18,3.80,"freshman"}, {"Stark",18,3.80,"freshman"}, {"Hork",18,3.80,"freshman"}, {"Hugo",18,3.80,"freshman"} }; for(int i = 0; i < 10 ; i++) { printf("Name: %s, Age: %d, Gpa %.2f, Grade: %s \n",r[i].name, r[i].age, r[i].gpa, r[i].grade); } return 0; } //non-struct record #include <stdio.h> #include <stdlib.h> int main() { char *name[10]; int age[10]; float gpa[10]; char *grade[10]; name[0]=(char*)malloc(20); name[0]="James"; age[0]=18; gpa[0]=3.7; grade[0]=(char*)malloc(20); grade[0]="First year"; name[1]=(char*)malloc(20); name[1]="Andy"; age[1]=18; gpa[1]=3.3; grade[1]=(char*)malloc(20); grade[1]="First year"; name[2]=(char*)malloc(20); name[2]="Brandon"; age[2]=18; gpa[2]=3.4; grade[2]=(char*)malloc(20); grade[2]="First year"; name[3]=(char*)malloc(20); name[3]="Heria"; age[3]=18; gpa[3]=3.2; grade[3]=(char*)malloc(20); grade[3]="First year"; name[4]=(char*)malloc(20); name[4]="Addison"; age[4]=18; gpa[4]=3.7; grade[4]=(char*)malloc(20); grade[4]="First year"; name[5]=(char*)malloc(20); name[5]="Keila"; age[5]=18; gpa[5]=3.8; grade[5]=(char*)malloc(20); grade[5]="First year"; name[6]=(char*)malloc(20); name[6]="Sunny"; age[6]=18; gpa[6]=3.9; grade[6]=(char*)malloc(20); grade[6]="First year"; name[7]=(char*)malloc(20); name[7]="Stark"; age[7]=18; gpa[7]=3.4; grade[7]=(char*)malloc(20); grade[7]="First year"; name[8]=(char*)malloc(20); name[8]="Hork"; age[8]=18; gpa[8]=3.6; grade[8]=(char*)malloc(20); grade[8]="First year"; name[9]=(char*)malloc(20); name[9]="Hugo"; age[9]=18; gpa[9]=3.3; grade[9]=(char*)malloc(20); grade[9]="First year"; int i = 0; for(i = 0; i < 10 ; i++) { printf("Name: %s, Age: %d, Gpa %.2f, Grade: %s \n", name[i], age[i], gpa[i], grade[i]); } return 0; } <file_sep>/C language/QuickSort.c #include <stdio.h> #include <stdlib.h> #include <time.h> #define N 1000 void F1(int arr[], int n); // The recursion sort void F2(int arr[], int n); // The bubble sort void PrintArray(int arr[], int n); // Print 1,000 integer numbers void GenerateArray(int arr[], int n); // Generate 1,000 integer numbers randomly int main(int argc, char *argv[]) { int arr[N]; GenerateArray(arr, N); printf("Before the recursion sort ----------\n"); PrintArray(arr, N); printf("Start the recursion sort ----------\n"); clock_t start_time1 = clock(); F1(arr, N); clock_t end_time1 = clock(); printf("Running time is: %lf ms\n", (double)(end_time1 - start_time1) / CLOCKS_PER_SEC * 1000); printf("After the recursion sort ----------\n"); PrintArray(arr, N); printf("**********\n"); GenerateArray(arr, N); printf("Before the bubble sort ----------\n"); PrintArray(arr, N); printf("Start Bubble sort ----------\n"); clock_t start_time2 = clock(); F2(arr, N); clock_t end_time2 = clock(); printf("Running time is: %lf ms\n", (double)(end_time2 - start_time2) / CLOCKS_PER_SEC * 1000); printf("After the bubble sort ----------\n"); PrintArray(arr, N); return 0; } // Generate 1,000 integer numbers randomly void GenerateArray(int arr[], int n) { int i; srand((unsigned)time(0)); for(i = 0; i <N; i++) { arr[i] = rand(); } } // Print 1,000 integer numbers void PrintArray(int arr[], int n) { int i = 0; for(i = 0; i < n; i++) printf("%6d\t", arr[i]); printf("\n"); } // recursion sort void F1(int arr[], int n) { if(n <= 1) return; int i =0 , j = n - 1; int key = arr[0]; int index = 0; while(i < j) { while(j > i && arr[j] >= key) j--; if(j == i) break; else { arr[j] = arr[j] ^arr[i]; arr[i] = arr[j] ^arr[i]; arr[j] = arr[j] ^arr[i]; index = j; } while(i < j && arr[i] <= key) i++; if(i == j) break; else { arr[j] = arr[j] ^arr[i]; arr[i] = arr[j] ^arr[i]; arr[j] = arr[j] ^arr[i]; index = i; } } F1(arr, index); F1(arr + index + 1, n - 1 - index); } // bubble sort void F2(int arr[], int n) { int i = 0, j =0; for(i = 0; i < n; i++) for(j = 0; j < n - 1 - i; j++) { if(arr[j] > arr[j + 1]) { arr[j] = arr[j] ^ arr[j+1]; arr[j+1] = arr[j] ^ arr[j+1]; arr[j] = arr[j] ^ arr[j+1]; } } } <file_sep>/Java language/OODP/MaritalStatus.java public class MaritalStatus { String status; MaritalStatus(){ status = ""; } MaritalStatus(String status){ this.status = status; } public void changeStatus(String newSt){ if(validStatus(newSt)){ this.status = newSt; System.out.println("Status changed successfully!"); } else System.out.println("Fail! Invalid status."); } public boolean validStatus(String newSt){ if( (status.equalsIgnoreCase("single") && newSt.equalsIgnoreCase("married")) || (status.equalsIgnoreCase("married") && ( newSt.equalsIgnoreCase("divorced") || newSt.equalsIgnoreCase("widow") )) || (status.equalsIgnoreCase("divorced") && newSt.equalsIgnoreCase("married")) || (status.equalsIgnoreCase("widow") && newSt.equalsIgnoreCase("married")) ){ return true; } return false; } public String getStatus() { return status; } } <file_sep>/C language/StackHeap.c #include <stdio.h> #include <stdlib.h> #include <time.h> // declares a large array on the stack void allocateOnStack() { char space[1024]; } // declares a same large array from the heap void allocateOnHeap() { void *space = malloc(1024); free(space); } // calls each of the funtions 1m times and outputs the time required by each int main() { int counter = 1000000; clock_t timeBegin; clock_t timeEnd; timeBegin = clock(); for (int i = 0; i < counter; i++) { allocateOnStack(); } timeEnd = clock(); printf("[%d times] Allocate 1 KiB on stack: %lu tick\n", counter, timeEnd - timeBegin); timeBegin = clock(); for (int i = 0; i < counter; i++) { allocateOnHeap(); } timeEnd = clock(); printf("[%d times] Allocate 1 KiB on heap: %lu tick\n", counter, timeEnd - timeBegin); return 0; }
17060c29c1ba1d062f44b3848617d8836133b9d7
[ "Ruby", "Markdown", "Java", "C", "C++" ]
8
Markdown
EverMario/The-way-to-PM
f85c68e9c6630dfdc6491a8d94b2d9d7d1b66a7a
052ae7c760337678f0e94d55abc2597e2e9deb5c
refs/heads/master
<repo_name>dineschandgr/UnitTest_Junit_Mockito<file_sep>/src/test/java/io/springboot/starter/hello/HelloControllerTest.java package io.springboot.starter.hello; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @RunWith(SpringJUnit4ClassRunner.class) class HelloControllerTest { private MockMvc mockMvc; @InjectMocks private HelloController helloController; @BeforeEach public void setUp() throws Exception{ HelloController helloController = new HelloController(); mockMvc = MockMvcBuilders.standaloneSetup(helloController).build(); } @Test void testHelloWorld() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/hello")) .andExpect(status().isOk()) .andExpect(content().string("Hello World")); } @Test void testHelloWorldJson() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/json") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.title",Matchers.is("Hello Title"))) .andExpect(jsonPath("$.value",Matchers.is("Hello Message"))); } } <file_sep>/src/main/java/io/springboot/starter/course/CourseService.java package io.springboot.starter.course; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CourseService { @Autowired private CourseRepository courseRepository; public Course getCourse(String id) { Course course = courseRepository.findById(id).orElse(null); System.out.println("inside getCourse id "+course); return course; } public List<Course> getAllCourses(String topicId) { List<Course> courseList = new ArrayList<>(); courseRepository.findByTopicTopicId(topicId) .forEach(courseList :: add); return courseList; } public List<Course> getAllCoursesbyCourseName(String courseName) { List<Course> courseList = new ArrayList<>(); courseRepository.findByCourseName(courseName) .forEach(courseList :: add); System.out.println("inside getAllCoursesbyCourseName id "+courseName); return courseList; } public List<Course> getAllCoursesbyTopicName(String topicName) { List<Course> courseList = new ArrayList<>(); courseRepository.findByTopicTopicName(topicName) .forEach(courseList :: add); return courseList; } public Course addCourse(Course course) { return courseRepository.save(course); } public Course updateCourse(String id, Course course) { return courseRepository.save(course); } public void deleteCourse(String id) { courseRepository.deleteById(id); } public Course getCoursesbyId(String courseId) { return courseRepository.findById(courseId).orElse(new Course("Test","Test","Test","1")); } } <file_sep>/README.md # UnitTest_Junit_Mockito Unit Test using Junit5 and Mockito <file_sep>/src/main/java/io/springboot/starter/hello/HelloController.java package io.springboot.starter.hello; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping(value = "/hello") public String sayHi() { return "Hello World"; } @GetMapping(value = "/json",produces = MediaType.APPLICATION_JSON_VALUE) public Hello json() { return new Hello("Hello Title","Hello Value"); } private class Hello{ private String title; private String value; public Hello(String title, String value) { super(); this.title = title; this.value = value; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
c91ce6f67580a68008a658a7d09aa9c54136af02
[ "Markdown", "Java" ]
4
Java
dineschandgr/UnitTest_Junit_Mockito
984effec02ff5a6301d432aa9754ac23825b8375
c203cfb17ce6809ab46574ded3586818b42b8865
refs/heads/master
<repo_name>bozus94/php_shopping<file_sep>/includes/views/categorias/ver.view.php <div class="d-flex flex-row"> <?php require('includes/templates/aside.php'); ?> <main class="ml-5"> <h2><?= isset($category) ? 'Categoria: ' . $category->nombre : ' La categoria no existe' ?></h2> <div class="contenedor-main d-flex flex-column flex-center bg-blanco"> <?php if ($products->num_rows > 0) : ?> <div class="section-productos"> <div class="productos d-flex flex-row flex-wrap"> <?php while ($pro = $products->fetch_object()) : ?> <div class="producto"> <a href="<?= RUTA; ?>producto/productoView&prod=<?= $pro->id; ?>" class="link-producto"> <div class="thumb-producto"> <?php if ($pro->imagen == null) : ?> <img src="<?= RUTA; ?>assets/img/new-product2.jpg" alt="producto"> <?php else : ?> <img src="<?= RUTA; ?>uploads/images/<?= $pro->imagen; ?>" alt="producto"> <?php endif; ?> </div><!-- ./thumb-producto --> <div class="info-producto"> <p class="precio-producto">$<?= $pro->precio; ?></p> <p class="titulo-producto"><?= $pro->nombre; ?></p> </div><!-- ./info-producto --> </a> </div> <!--./producto --> <?php endwhile; ?> </div> <!--./productos --> </div><!-- ./section-producto --> <?php else : ?> <p class="p-5">No hay productos para mostrar</p> <?php endif; ?> </div><!-- ./contenedor-main --> </main> </div><file_sep>/includes/views/pedido/crear.view.php <main class="main-100 vh77-center d-flex flex-column"> <h2> Realizar pedido</h2> <div class="contenedor-main d-flex flex-row flex-y-center h-100"> <div class="contenedor-main-header d-flex w-100 flex-y-center"> <div class="bg-blanco mr-auto"> <a href="<?= RUTA ?>categoria/index" class="btn-contenedor-main-header"><i class="fas fa-arrow-left"></i></a> </div> <?php if (isset($_SESSION[$this->session])) : ?> <?php if ($_SESSION[$this->session]['state'] === true) : ?> <h3 class="alert alert-success alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php else : ?> <h3 class="alert alert-error alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php endif; ?> <?php endif; Utils::deleteSession($this->session); ?> </div><!-- ./contenedor-main-header --> <div class="formulario bg-blanco"> <form action="<?= RUTA ?>pedido/add" method="post" enctype="multipart/form-data"> <select id="busqueda_provincia" class="form-control" name="provincia"> <option value='alava'>Álava</option> <option value='albacete'>Albacete</option> <option value='alicante'>Alicante/Alacant</option> <option value='almeria'>Almería</option> <option value='asturias'>Asturias</option> <option value='avila'>Ávila</option> <option value='badajoz'>Badajoz</option> <option value='barcelona'>Barcelona</option> <option value='burgos'>Burgos</option> <option value='caceres'>Cáceres</option> <option value='cadiz'>Cádiz</option> <option value='cantabria'>Cantabria</option> <option value='castellon'>Castellón/Castelló</option> <option value='ceuta'>Ceuta</option> <option value='ciudadreal'>Ciudad Real</option> <option value='cordoba'>Córdoba</option> <option value='cuenca'>Cuenca</option> <option value='girona'>Girona</option> <option value='laspalmas'>Las Palmas</option> <option value='granada'>Granada</option> <option value='guadalajara'>Guadalajara</option> <option value='guipuzcoa'>Guipúzcoa</option> <option value='huelva'>Huelva</option> <option value='huesca'>Huesca</option> <option value='illesbalears'>Illes Balears</option> <option value='jaen'>Jaén</option> <option value='acoruña'>A Coruña</option> <option value='larioja'>La Rioja</option> <option value='leon'>León</option> <option value='lleida'>Lleida</option> <option value='lugo'>Lugo</option> <option value='madrid'>Madrid</option> <option value='malaga'>Málaga</option> <option value='melilla'>Melilla</option> <option value='murcia'>Murcia</option> <option value='navarra'>Navarra</option> <option value='ourense'>Ourense</option> <option value='palencia'>Palencia</option> <option value='pontevedra'>Pontevedra</option> <option value='salamanca'>Salamanca</option> <option value='segovia'>Segovia</option> <option value='sevilla'>Sevilla</option> <option value='soria'>Soria</option> <option value='tarragona'>Tarragona</option> <option value='santacruztenerife'>Santa Cruz de Tenerife</option> <option value='teruel'>Teruel</option> <option value='toledo'>Toledo</option> <option value='valencia'>Valencia/Valéncia</option> <option value='valladolid'>Valladolid</option> <option value='vizcaya'>Vizcaya</option> <option value='zamora'>Zamora</option> <option value='zaragoza'>Zaragoza</option> </select> <input type="text" name="localidad" id="localidad" class="form-control" placeholder="localidad"> <input type="text" name="direccion" id="direccion" class="form-control" placeholder="direccion"> <div class="footer-form"> <div class="btn-group d-flex flex-column "> <input type="hidden" name="usuarioId" value="<?= $_SESSION['login']['usuario']->id ?>"> <input type="hidden" name="coste" value="<?= Utils::statsCarrito()['total'] ?>"> <input type="hidden" name="estado" value="pendiente"> <input type="submit" value="Realizar pedido" class="btn btn-submit btn-hover w-50-center" name="submit"> </div> </div><!-- ./footer-form --> </form><!-- ./form --> </div><!-- ./formulario --> </div><!-- ./contenedor_main --> </main><file_sep>/includes/controllers/UsuarioController.php <?php require_once 'includes/models/UsuarioModel.php'; class UsuarioController { public $session; public function __construct() { $this->session = Utils::getController(); } public function index() { echo 'controlador usuario,Accion index'; } public function registro() { require_once 'includes/views/usuario/registro.view.php'; } public function guardar() { if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['registro']) && $_POST['registro'] === 'Registrarse') { $nombre = isset($_POST['nombre']) ? Utils::sanitizeData($_POST['nombre']) : false; $apellidos = isset($_POST['apellidos']) ? Utils::sanitizeData($_POST['apellidos']) : false; $password = isset($_POST['password']) ? Utils::sanitizeData($_POST['password']) : false; $password_hash = Utils::passwordHash($password, 12); $rol = isset($_POST['rol']) ? Utils::sanitizeData($_POST['rol']) : false; $imagen = isset($_POST['imagen']) ? Utils::sanitizeData($_POST['imagen']) : false; $email = isset($_POST['email']) ? Utils::sanitizeEmail($_POST['email']) : false; if ($nombre && $apellidos && $password && $rol && $email) { $usuario = new UsuarioModel(); $usuario->setNombre($nombre); $usuario->setApellidos($apellidos); $usuario->setPassword($<PASSWORD>); $usuario->setEmail($email); $usuario->setRol($rol); $save = $usuario->save(); if ($save['state'] === true) { $_SESSION[$this->session]['state'] = $save['state']; $_SESSION[$this->session]['newReg'] = 'Inicia Sesion con tu usuario y contraseña'; header('Location:' . RUTA . 'usuario/iniciarSesion'); } else { $_SESSION[$this->session]['state'] = $save['state']; $_SESSION[$this->session]['message'] = $save['message']; header('Location:' . RUTA . 'usuario/registro'); } } else { $_SESSION[$this->session]['state'] = false; $_SESSION[$this->session]['message'] = 'Todos los campos son obligatorios'; header('Location:' . RUTA . 'usuario/registro'); } } else { $_SESSION[$this->session]['state'] = false; $_SESSION[$this->session]['message'] = 'No se pudo registrar al usuario'; header('Location:' . RUTA . 'usuario/registro'); } } else { $_SESSION[$this->session]['state'] = false; $_SESSION[$this->session]['message'] = 'No se pudo registrar al usuario'; header('Location:' . RUTA . 'usuario/registro'); } } public function iniciarSesion() { if (isset($_SESSION[$this->session]['status']) && $_SESSION[$this->session]['status'] === true) { header('Location:' . RUTA); } else { require_once 'includes/views/usuario/login.view.php'; } } public function login() { if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) { $email = isset($_POST['usuario']) ? Utils::sanitizeEmail($_POST['usuario']) : false; $password = isset($_POST['password']) ? Utils::sanitizeData($_POST['password']) : false; if ($email && $password) { $usuario = new UsuarioModel(); $usuario->setEmail($email); $usuario->setPassword($password); $login = $usuario->login(); if ($login && is_object($login['usuario'])) { $_SESSION[$this->session]['usuario'] = $login['usuario']; if ($login['usuario']->rol === 'admin') { $_SESSION[$this->session]['admin'] = true; } header('Location:' . RUTA); } else { $_SESSION[$this->session]['state'] = $login['state']; $_SESSION[$this->session]['message'] = $login['message']; header('Location:' . RUTA . 'usuario/iniciarSesion'); } } else { $_SESSION['login']['state'] = false; $_SESSION['login']['message'] = 'No se pudo iniciar sesesion'; header('Location:' . RUTA . 'usuario/iniciarSesion'); } } else { $_SESSION['login']['state'] = false; $_SESSION['login']['message'] = 'No se pudo iniciar sesion'; header('Location:' . RUTA . 'usuario/iniciarSesion'); } } public function logOut() { Utils::deleteSession('usuario'); if (isset($_SESSION['usuario']['admin'])) { Utils::deleteSession('admin'); } header('Location:' . RUTA); } } <file_sep>/includes/models/CategoriaModel.php <?php class CategoriaModel { private $id; private $nombre; private $db; public function __construct() { $this->db = DataBase::conexionDB(); } public function getId() { return $this->id; } public function setId($id) { $this->id = $id; return $this; } public function getNombre() { return $this->nombre; } public function setNombre($nombre) { $this->nombre = $this->db->real_escape_string($nombre);; return $this; } public function getAll() { $categorias = $this->db->query(" SELECT * FROM categorias ORDER BY id DESC "); return $categorias; } public function getOne() { $categoria = $this->db->query(" SELECT * FROM categorias WHERE id = '{$this->getId()}' "); return $categoria->fetch_object(); } public function save() { $result['state'] = false; $cat_existe = Utils::compararCampo($this->db, 'categorias', 'nombre', $this->getNombre()); /* comprobamos que la categoria no exista */ if ($cat_existe->num_rows > 0) { $result['state'] = false; $result['message'] = 'Esta categoria ya existe!'; } else { $sql = " INSERT INTO categorias (nombre) VALUES ('{$this->getNombre()}')"; $save = $this->db->query($sql); if ($save) { $result['state'] = true; $result['message'] = 'Categoria creada existosamente'; } else { $result['state'] = false; $result['message'] = 'No se pudo crear la categoria'; } } return $result; } public function delete() { $result['state'] = false; $sql = " DELETE FROM categorias WHERE id = ('{$this->getId()}') "; $delete = $this->db->query($sql); if ($delete) { $result['state'] = true; $result['message'] = 'Categoria eliminada existosamente!'; } else { $result['state'] = false; $result['message'] = 'No se pudo eliminar la categoria!'; } return $result; } public function update() { $result['state'] = false; $cat_existe = Utils::compararCampo($this->db, 'categorias', 'nombre', $this->getNombre()); /* comprobamos que la categoria no exista */ if ($cat_existe->num_rows > 0) { $result['state'] = false; $result['message'] = 'Esta categoria ya existe!'; } else { $sql = " UPDATE categorias SET nombre='{$this->getNombre()}' WHERE id='{$this->getId()}' "; $update = $this->db->query($sql); if ($update) { $result['state'] = true; $result['message'] = 'Categoria modificada existosamente!'; } else { $result['state'] = false; $result['message'] = 'No se pudo modificar la categoria!'; } } return $result; } }<file_sep>/includes/templates/paginacion_buscar.php <div class="paginacion"> <ul> <!-- boton de pagina anterior --> <?php if (paginaActual() == 1) : ?> <li class="disable">&laquo;</li> <?php else : ?> <li><a href="<?php echo $nombre_pagina; ?>?pagina=<?php echo paginaActual() - 1; ?>&buscar=<?php echo $consultaBD['busqueda'] ?> ">&laquo;</a></li> <?php endif; ?> <!-- paginas del blog --> <?php for ($i = 1; $i <= $numero_paginas; $i++) : ?> <?php if (paginaActual() === $i) : ?> <li class="activo"><?php echo $i; ?></li> <?php else : ?> <li><a href="<?php echo $nombre_pagina; ?>?pagina=<?php echo $i; ?>&buscar=<?php echo $consultaBD['busqueda'] ?>"> <?php echo $i; ?></a></li> <?php endif; ?> <?php endfor; ?> <!-- boton de siguiente pagina --> <?php if (paginaActual() == $numero_paginas) : ?> <li class="disable">&raquo;</li> <?php else : ?> <li><a href="<?php echo $nombre_pagina; ?>?pagina=<?php echo paginaActual() + 1; ?>&buscar=<?php echo $consultaBD['busqueda'] ?> ">&raquo;</a></li> <?php endif; ?> </ul> </div><file_sep>/includes/views/producto/producto.view.php <main class="main-100 vh77-center d-flex"> <?php if ($producto) : ?> <div class="contenedor-main d-flex flex-column h-100 bg-blanco"> <div class="contenedor-main-header d-flex w-100 flex-y-center"> <div class="bg-blanco mr-auto mr-5"> <a href="<?= RUTA ?>" class="btn-contenedor-main-header"><i class="fas fa-arrow-left"></i></a> </div> <?php if (isset($_SESSION[$this->session])) : ?> <?php if ($_SESSION[$this->session]['state'] === true) : ?> <h3 class="alert alert-success alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php else : ?> <h3 class="alert alert-error alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php endif; ?> <?php endif; Utils::deleteSession($this->session); ?> </div><!-- ./contenedor-main-header --> <div class="producto-detalles d-flex flex-column"> <div class="d-flex flex-row flex-y-center"> <div class="thumb-detalle-producto"> <?php if ($producto->imagen == null) : ?> <img src="<?= RUTA; ?>/assets/img/new-product2.jpg" alt=""> <?php else : ?> <img src="<?= RUTA; ?>uploads/images/<?= $producto->imagen ?>" alt=""> <?php endif; ?> </div><!-- .thumb-detalle-producto--> <div class="detalles-producto d-flex flex-column"> <div class="detalle precio d-flex"> <p class="detalle-precio-producto">$<?= $producto->precio ?></p> <?php if ($producto->oferta != 0) : ?> <div class="descuento d-flex flex-column"> <p class="precio-n">$35</p> <span>ahorras $10</span> </div> <?php endif; ?> </div> <div class="detalle descripcion"> <h2><?= $producto->nombre; ?></h2> </div> <div class="detalle descripcion"> <h3> <?= $producto->descripcion ?></h3> </div> <div class="detalle detalle-2 d-flex"> <p class="Marca">Marca</p> <span> Producto </span> </div> <div class="detalle detalle-2 d-flex"> <p class="disponibildiad">Disponibilidad</p> <span>En estock! recibelo mañana </span> </div> <div class="detalle detalle-2 d-flex"> <p class="envio">Envio</p> <span>Gratis! </span> </div> <div class="detalle caracteristicas"> <ul> <li class="caracteristica">Lorem ipsum dolor sit amet.</li> <li class="caracteristica">Lorem ipsum dolor sit amet.</li> <li class="caracteristica">Lorem ipsum dolor sit amet.</li> <li class="caracteristica">Lorem ipsum dolor sit amet.</li> <li class="caracteristica">Lorem ipsum dolor sit amet.</li> </ul> </div> </div><!-- .detalles-producto --> </div> <div class="detalle-compra w-50-center d-flex"> <p class="envio-1-dia">¿Quieres recibirlo <span>mañana</span> ? Cómpralo antes de <span>6 hrs y 11 mins</span> y elige <span>Envío 1 día</span> al completar tu pedido.</p> <form action="<?= RUTA ?>carrito/add" method="post"> <div class="cantidad d-flex"> <label for="cantidad">Cantidad (<small>maximo 15 productos)</small></label> <div class="mas-menos d-flex"> <!-- <button class="menos">-</button> --> <input type="number" name="cantidad" id="cantidad" min="1" value="1" max="15"> <!-- <button class="mas">+</button> --> </div> </div> <div class="botones-compras"> <!-- <input type="button" value="Comprar Ya!" class="btn btn-compra comprarYa" name="accion-compra"> --> <input type="hidden" name="producto_id" value="<?= $producto->id ?>"> <input type="submit" value="Añadir al carrito" class="btn btn-compra comprarYa" name="añadirCarrito"> </div> </form> </div><!-- .detalle-compra --> </div><!-- ./producto-detalles --> </div><!-- ./contenedor-main --> <?php else : ?> <p>Lo sentimos este producto no esta disponible.</p> <?php endif ?> </main><file_sep>/includes/views/categorias/index.view.php <main class="main-100 vh77-center d-flex flex-column flex-y-center"> <h2>Gestionar categorias</h2> <div class="contenedor-main w-50-center d-flex flex-column h-100 bg-blanco"> <div class="contenedor-main-header d-flex w-100 flex-y-center"> <div class="bg-blanco mr-auto w-25"> <a href="<?= RUTA ?>" class="btn-contenedor-main-header"><i class="fas fa-arrow-left"></i></a> <a href="<?= RUTA ?>categoria/crear" class="btn-contenedor-main-header"><i class="fas fa-plus"></i></a> </div> <?php if (isset($_SESSION[$this->session])) : ?> <?php if ($_SESSION[$this->session]['state'] === true) : ?> <h3 class="alert alert-success alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php else : ?> <h3 class="alert alert-error alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php endif; ?> <?php endif; Utils::deleteSession($this->session); ?> </div><!-- ./contenedor-main-header --> <div class="contenido d-flex flex-column flex-y-center"> <table class="table table-v2"> <thead> <tr> <td>Id</td> <td>Nombre</td> <td>Acciones</td> </tr> </thead> <tbody> <?php while ($cat = $categorias->fetch_object()) : ?> <tr> <!-- --> <td><?= $cat->id; ?></td> <td><?= $cat->nombre; ?></td> <td> <a href="<?= RUTA ?>categoria/editar&cat=<?= $cat->id ?>" class="btn btn-table-editar">Editar</a> <a href="<?= RUTA ?>categoria/eliminar&cat=<?= $cat->id ?>" class="btn btn-table-eliminar">Eliminar</a> </td> </tr> <?php endwhile; ?> </tbody> <tfoot> <tr> <td>Id</td> <td>Nombre</td> <td>Acciones</td> </tr> </tfoot> </table> </div> </div><!-- ./contenedor-main --> </main><file_sep>/includes/views/usuario/login.view.php <main class="main-100 vh77-center d-flex flex-column"> <h2>Inicio Sesion</h2> <div class="contenedor-main d-flex flex-column flex-y-center h-100 formulario bg-blanco"> <div class="contenedor-main-header d-flex w-100 flex-y-center"> <div class="bg-blanco mr-auto mr-5"> <a href="<?= RUTA ?>" class="btn-contenedor-main-header"><i class="fas fa-arrow-left"></i></a> </div> <?php if (isset($_SESSION[$this->session])) : ?> <?php if ($_SESSION[$this->session]['state'] === true && isset($_SESSION[$this->session]['newReg'])) : ?> <h3 class="alert alert-success"><?= $_SESSION[$this->session]['newReg'] ?></h3> <?php else : ?> <h3 class="alert alert-error "><?= $_SESSION[$this->session]['message'] ?></h3> <?php endif; ?> <?php Utils::deleteSession($this->session); ?> <?php endif; ?> </div><!-- ./contenedor-main-header --> <div class="box-shadow formulario-2 w-100"> <!-- notificacion del login --> <form action="<?php echo RUTA; ?>usuario/login" method="post"> <?php if (isset($respuesta)) : ?> <input type="email" name="usuario" id="usuario" class="form-control" value="<?php echo $respuesta['usuario'] ?>"> <input type="<PASSWORD>" name="password" id="password" class="form-control" value="<?php echo $respuesta['password'] ?>"> <?php else : ?> <input type="email" name="usuario" id="usuario" class="form-control" placeholder="<EMAIL>"> <input type="<PASSWORD>" name="password" id="password" class="form-control" placeholder="<PASSWORD>"> <?php endif ?> <div class="footer-form"> <div class="btn-group d-flex flex-column "> <input type="submit" value="Iniciar Sesion" class="btn btn-submit btn-hover w-50-center" name="login"> <a href="<?= RUTA; ?>usuario/registro" class="btn btn-secundario">no tienes cuenta, registrate!</a> </div> </div> </form> </div> </div> </main><file_sep>/includes/views/producto/index.view.php <div class="d-flex flex-row"> <?php require('includes/templates/aside.php'); ?> <main> <div class="contenedor-main d-flex flex-column ml-5 bg-blanco"> <div class="section-productos"> <h2 class="titulo-section-producto">Ofertas de la semana</h2> <div class="productos d-flex flex-row flex-wrap"> <?php ?> <?php while ($pro = $productos->fetch_object()) : ?> <div class="producto"> <a href="<?= RUTA; ?>producto/productoView&prod=<?= $pro->id; ?>" class="link-producto"> <div class="thumb-producto"> <?php if ($pro->imagen == null) : ?> <img src="<?= RUTA; ?>assets/img/new-product2.jpg" alt="producto"> <?php else : ?> <img src="<?= RUTA; ?>uploads/images/<?= $pro->imagen; ?>" alt="producto"> <?php endif; ?> </div><!-- ./thumb-producto --> <div class="info-producto"> <p class="precio-producto">$<?= $pro->precio; ?></p> <p class="titulo-producto"><?= $pro->nombre; ?></p> </div><!-- ./info-producto --> </a> </div> <!--./producto --> <?php endwhile; ?> </div> <!--./productos --> </div><!-- ./section-producto --> <div class="section-productos"> <h2 class="titulo-section-producto">Destacados</h2> <div class="productos d-flex flex-row flex-wrap"> <?php ?> <?php while ($pro = $productos2->fetch_object()) : ?> <div class="producto"> <a href="<?= RUTA; ?>producto/productoView&prod=<?= $pro->id; ?>" class="link-producto"> <div class="thumb-producto"> <?php if ($pro->imagen == null) : ?> <img src="<?= RUTA; ?>assets/img/new-product2.jpg" alt="producto"> <?php else : ?> <img src="<?= RUTA; ?>uploads/images/<?= $pro->imagen; ?>" alt="producto"> <?php endif; ?> </div><!-- ./thumb-producto --> <div class="info-producto"> <p class="precio-producto">$<?= $pro->precio; ?></p> <p class="titulo-producto"><?= $pro->nombre; ?></p> </div><!-- ./info-producto --> </a> </div> <!--./producto --> <?php endwhile; ?> </div> <!--./productos --> </div><!-- ./section-producto --> </div><!-- ./contenedor-main --> </main> </div><file_sep>/includes/controllers/ProductoController.php <?php include_once 'includes/models/ProductoModel.php'; class ProductoController { public $session; public function __construct() { $this->session = Utils::getController(); } public function index() { $producto = new ProductoModel(); $productos = $producto->getRamdom(PRODUCTOS_X_SECTION); $productos2 = $producto->getRamdom(PRODUCTOS_X_SECTION); require_once 'includes/views/producto/index.view.php'; } public function productoView() { $producto = false; if (isset($_GET['prod'])) { $idProd = $_GET['prod']; $prod = new ProductoModel(); $prod->setId($idProd); $producto = $prod->getOne(); require_once 'includes/views/producto/producto.view.php'; } else { header('Location:' . RUTA); } } public function gestion() { Utils::isAdmin('header'); $producto = new ProductoModel(); $productos = $producto->getAll(); require_once 'includes/views/producto/gestion.view.php'; } public function crear() { Utils::isAdmin('header'); require_once 'includes/views/producto/form_gestion.view.php'; } public function guardar() { Utils::isAdmin('header'); if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) { $nombre = Utils::sanitizeData($_POST['nombre']); $categoriaId = Utils::sanitizeData($_POST['categoriaId']); $descripcion = Utils::sanitizeData($_POST['descripcion']); $precio = Utils::sanitizeData($_POST['precio']); $stock = Utils::sanitizeData($_POST['stock']); $file = ($_FILES['image']); $name_file = Utils::sanitizeData($file['name']); if ($nombre && $categoriaId && $descripcion && $precio && $stock) { $producto = new ProductoModel(); $producto->setCategoriaId($categoriaId); $producto->setNombre($nombre); $producto->setDescripcion($descripcion); $producto->setPrecio($precio); $producto->setStock($stock); /* comprobamos que nos llegue la imagen para procesarla */ if (isset($name_file) && $name_file !== '') { $mimetype = $file['type']; $file_tmp_name = $file['tmp_name']; $file_destination = 'uploads/images'; if ($mimetype == 'image/jpg' || $mimetype == 'image/jpeg') { if (!is_dir($file_destination)) { mkdir($file_destination, 0777, true); } $producto->setImagen($name_file); } } /* comprobamos que nos llegue por le metodo get el parametro id */ /* si nos llega el parametro actulizamos el producto */ /* de lo contrario se trata de un nuevo porducto */ if (isset($_GET['id'])) { $id = $_GET['id']; $producto->setId($id); $save = $producto->update(); } else { $save = $producto->save(); } /* verificamos que la sentencia sql se haya relizado correctamente */ if ($save) { move_uploaded_file($file_tmp_name, $file_destination . '/' . $name_file); $_SESSION['producto']['state'] = true; $accion_mensaje = $_POST['submit'] == 'Crear' ? 'Agrego' : ' Modifico'; $_SESSION['producto']['message'] = "<span class='alert_span'> {$nombre} </span> se " . $accion_mensaje . " correctamente"; header('Location:' . RUTA . 'producto/gestion'); } else { $_SESSION['producto']['state'] = 'error'; $_SESSION['producto']['message'] = 'No se pudo agregar el producto'; header('Location:' . RUTA . 'producto/gestion'); } } else { $_SESSION['producto']['state'] = 'error'; $_SESSION['producto']['message'] = 'Todos los datos son obligatorios'; header('Location:' . RUTA . 'producto/crear'); } } } public function eliminar() { Utils::isAdmin('header'); if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['id'])) { $id = Utils::sanitizeData($_GET['id']); if ($id) { $producto = new ProductoModel(); $producto->setId($id); $delete = $producto->delete(); if ($delete) { $_SESSION['producto']['state'] = true; $_SESSION['producto']['message'] = 'Se elimino el producto correctamente'; header('Location:' . RUTA . 'producto/gestion'); } else { $_SESSION['producto']['state'] = 'error'; $_SESSION['producto']['message'] = 'No se pudo borrar el producto'; header('Location:' . RUTA . 'producto/gestion'); } } else { $_SESSION['producto']['state'] = 'error'; $_SESSION['producto']['message'] = 'Se intento eliminar un producto no valido'; header('Location:' . RUTA . 'producto/gestion'); } } else { $_SESSION['producto']['state'] = 'error'; $_SESSION['producto']['message'] = 'Error al borrar el producto'; header('Location:' . RUTA . 'producto/gestion'); } } public function editar() { Utils::isAdmin('header'); if (isset($_GET['id']) && $_SERVER['REQUEST_METHOD'] === 'GET') { $editar = true; $producto = new ProductoModel(); $producto->setId($_GET['id']); $pro = $producto->getOne(); require_once 'includes/views/producto/form_gestion.view.php'; } } } <file_sep>/includes/models/UsuarioModel.php <?php class UsuarioModel { private $nombre; private $apellidos; private $email; private $password; private $rol; private $imagen; private $db; public function __construct() { $this->db = DataBase::conexionDB(); } public function getNombre() { return $this->nombre; } public function setNombre($nombre) { $this->nombre = $this->db->real_escape_string($nombre); return $this; } public function getApellidos() { return $this->apellidos; } public function setApellidos($apellidos) { $this->apellidos = $this->db->real_escape_string($apellidos); return $this; } public function getEmail() { return $this->email; } public function setEmail($email) { $this->email = $this->db->real_escape_string($email); return $this; } public function getPassword() { return $this->password; } public function setPassword($password) { $this->password = $this->db->real_escape_string($password); return $this; } public function getRol() { return $this->rol; } public function setRol($rol) { $this->rol = $this->db->real_escape_string($rol); return $this; } public function getImagen() { return $this->imagen; } public function setImagen($imagen) { $this->imagen = $this->db->real_escape_string($imagen); return $this; } public function save() { $result = false; $user_exist = Utils::compararCampo($this->db, 'usuarios', 'email', $this->getEmail()); if ($user_exist->num_rows !== 1) { $sql = " INSERT INTO usuarios(nombre, apellidos, email, password, rol) VALUES ('{$this->getNombre()}', '{$this->getApellidos()}', '{$this->getEmail()}', '{$this->getPassword()}', '{$this->getRol()}')"; $save = $this->db->query($sql); Utils::preDump($save); if ($save) { $result['state'] = true; } else { $result['state'] = false; $result['message'] = 'No se pudo registrar al usuario'; } } else { $result['state'] = false; $result['message'] = 'Este usuario ya existe'; } return $result; } public function login() { $result = false; //comprobar si existe el usuario $sql = " SELECT * FROM usuarios WHERE email = '{$this->getEmail()}' "; $login = $this->db->query($sql); if ($login && $login->num_rows == 1) { $usuario = $login->fetch_object(); //verificar la password $verify = password_verify($this->getPassword(), $usuario->password); if ($verify) { $result['usuario'] = $usuario; $result['state'] = true; } else { $result['state'] = false; $result['message'] = 'El usuario o la contraseña es incorrecta'; } } return $result; } } <file_sep>/index.php <?php session_start(); require_once('autoload.php'); require_once('config/configApp.php'); require_once('config/DataBase.php'); require_once('includes/funciones/funciones.php'); require_once('includes/templates/header.php'); require_once('includes/templates/barra.php'); require_once('includes/templates/footer_barra.php'); /* Utils::preDump($_SESSION); */ $controller = null; $action = null; function error() { $error = new ErrorController(); $error->index(); } if (isset($_GET['controller'])) { $controller = ucfirst($_GET['controller']) . 'Controller'; } elseif (!isset($_GET['controller']) && !isset($_GET['action'])) { $controller = CONTROLLER_DEFAULT; } else { error(); exit(); } if (class_exists($controller)) { $controlador = new $controller(); if (isset($_GET['action']) && method_exists($controlador, $_GET['action'])) { $accion = $_GET['action']; } elseif (!isset($_GET['controller']) && !isset($_GET['action'])) { $accion = ACTION_DEFAULT; } else { error(); } $controlador->$accion(); } else { error(); } require_once('includes/templates/footer.php'); <file_sep>/includes/views/pedido/index.view.php <main class="main-100 vh77-center d-flex flex-column flex-y-center"> <h2>Gestionar Pedidos</h2> <div class="contenedor-main w-50-center d-flex flex-column h-100 bg-blanco"> <div class="contenedor-main-header d-flex w-100 flex-y-center"> <div class="bg-blanco mr-auto w-25"> <a href="<?= RUTA ?>" class="btn-contenedor-main-header"><i class="fas fa-arrow-left"></i></a> </div> <?php if (isset($_SESSION[$this->session])) : ?> <?php if ($_SESSION[$this->session]['state'] === true) : ?> <h3 class="alert alert-success alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php else : ?> <h3 class="alert alert-error alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php endif; ?> <?php endif; Utils::deleteSession($this->session); ?> </div><!-- ./contenedor-main-header --> <div class="contenido d-flex flex-column flex-y-center"> <table class="table table-v2 table-td_min_w_150"> <thead> <tr> <td>Id</td> <td>Coste</td> <td>Estado</td> <td>Fecha</td> <td>Acciones</td> </tr> </thead> <tbody> <?php if (isset($pedidos) && $pedidos->num_rows !== 0) : ?> <?php while ($pedido = $pedidos->fetch_object()) : ?> <tr> <td><?= $pedido->id; ?></td> <td class="f-numero">$<?= $pedido->coste; ?></td> <td><?= $pedido->estado; ?></td> <td><?= $pedido->fecha; ?></td> <td> <a href="<?= RUTA ?>pedido/pedidoView&p=<?= $pedido->id ?>" class="btn btn-table-eliminar">Ver</a> <a href="<?= RUTA ?>pedido/eliminar&p=<?= $pedido->id ?>" class="btn btn-table-eliminar">Eliminar</a> </td> </tr> <?php endwhile; ?> <?php else : ?> <tr> <td class="td-notifiacion">Oh no! todavia no tienes pedidos</td> </tr> <?php endif; ?> </tbody> <tfoot> <tr> <td>Id</td> <td>Coste</td> <td>Estado</td> <td>Fecha</td> <td>Acciones</td> </tr> </tfoot> </table> </div> </div><!-- ./contenedor-main --> </main><file_sep>/includes/controllers/ErrorController.php <?php class ErrorController { public function index() { echo '<h1>La Pagina que buscas <strong>no existe</strong><h1>'; } } <file_sep>/includes/templates/barra.php <header> <div class="contenedor contenedor-header d-flex d-row"> <div class="logo"> <a href="<?php echo RUTA; ?>"> <h1>ShoppinG!</h1> </a> </div> <div class="contenedor-utilidades d-flex"> <div class="buscador"> <form action="<?php echo RUTA; ?>buscar.php" method="get" name="busqueda" class="buscar"> <input type="text" name="buscar" id="buscar" placeholder="Buscar"> <button type="submit" class="icono fas fa-search"></button> </form> </div> <nav class="contenedor-i d-flex"> <li> <?php if (isset($_SESSION['usuario']) /* && $_SESSION['usuario']['state'] === true */) : ?> <a href="<?= RUTA; ?>usuario/logOut"><i class="fas fa-sign-out-alt"></i></a> <?php else : ?> <a href="<?= RUTA; ?>usuario/iniciarSesion"><i class="fas fa-user"></i></i></a> <?php endif ?> </li> <li> <a href="<?= RUTA; ?>carrito/index"><i class="fas fa-shopping-cart"></i></i></a> </li> </nav> </div> <!--<div class="burguer"> <div class="line1"></div> <div class="line2"></div> <div class="line3"></div> </div> --> </div> </header><file_sep>/config/configApp.php <?php define('RUTA', 'http://php_shopping.test/'); define('CONTROLLER_DEFAULT', 'ProductoController'); define('ACTION_DEFAULT', 'index'); define('PRODUCTOS_X_SECTION', 5); $bd_config = array( 'db_nombre' => 'tienda_master', 'usuario' => 'root', 'password' => '', 'puerto' => 3306 ); $nombre_pagina = htmlspecialchars($_SERVER['PHP_SELF']); <file_sep>/includes/views/usuario/registro.view.php <main class="main-100 vh77-center d-flex flex-column"> <h2>Registrate!</h2> <div class="contenedor-main d-flex flex-column flex-y-center h-100 formulario bg-blanco"> <div class="contenedor-main-header d-flex w-100 flex-y-center"> <div class="bg-blanco mr-auto mr-5"> <a href="<?= RUTA ?>" class="btn-contenedor-main-header"><i class="fas fa-arrow-left"></i></a> </div> <?php if (isset($_SESSION[$this->session])) : ?> <h3 class="alert alert-error"><?= $_SESSION[$this->session]['message'] ?></h3> <?php Utils::deleteSession($this->session); ?> <?php endif; ?> </div><!-- ./contenedor-main-header --> <div class="box-shadow formulario-2 w-100"> <!-- notificacion del registro --> <form action="<?= RUTA; ?>usuario/guardar" method="post" enctype="multipart/form-data"> <?php if (isset($respuesta)) : ?> <input type="text" name="usuario" id="usuario" class="form-control" value="<?php echo $respuesta['usuario'] ?>"> <input type="password" name="password" id="password" class="form-control" value="<?php echo $respuesta['password'] ?>"> <?php else : ?> <input type="text" name="nombre" id="usuario" class="form-control" placeholder="Nombre"> <input type="text" name="apellidos" id="password" class="form-control" placeholder="<PASSWORD>"> <input type="email" name="email" id="usuario" class="form-control" placeholder="Email"> <input type="<PASSWORD>" name="password" id="usuario" class="form-control" placeholder="<PASSWORD>"> <input type="text" name="rol" id="usuario" class="form-control" placeholder="Rol"> <input type="file" name="imagen" id="usuario" class="imagen-form form-control"> <?php endif ?> <div class="footer-form"> <div class="btn-group d-flex flex-column "> <input type="submit" value="Registrarse" class="btn btn-submit btn-hover w-50-center" name="registro"> <a href="<?= RUTA; ?>usuario/iniciarSesion" class="btn btn-secundario">ya tienes cuenta, inicia sesion!</a> </div> <?php if (!empty($respuesta['errores'])) : ?> <div class="error"> <ul> <?php echo $respuesta['errores']; ?> </ul> </div> <?php endif; ?> </div> </form> </div> </div> </main><file_sep>/includes/views/pedido/confirmacion.view.php <main class="main-100 vh77-center d-flex flex-column"> <h2>Confirmacion</h2> <div class="contenedor-main d-flex flex-column flex-y-center h-100 bg-blanco"> <?php if (isset($_SESSION['pedido'])) : ?> <?php if ($_SESSION['pedido']['estate'] == 'completed') : ?> <p class="alert alert-success alert-pedido alert-animado">Tu pedido se ha creado correctamente.</p> <?php if (isset($pedido) && is_object($pedido)) : ?> <div class="info-pedido d-flex flex-row flex-y-center "> <p>Numero de pedido: <span class="f-numero"><?= $pedido->id ?></span> </p> <p>Coste: <strong><span class="f-numero">$<?= $pedido->coste ?></span></strong></p> <p>Estado: <strong><?= $pedido->estado ?></strong></p> </div> <table class="table table-v3 table-td_min_w_150"> <tbody> <?php if (isset($productos)) : ?> <?php while ($pro = $productos->fetch_object()) : ?> <tr> <td> <?php if ($pro->imagen == null) : ?> <a href="<?= RUTA ?>producto/productoView&prod=<?= $pro->id ?>"><img src="<?= RUTA; ?>assets/img/new-product2.jpg" alt="producto"></a> <?php else : ?> <a href="<?= RUTA ?>producto/productoView&prod=<?= $pro->id ?>"><img src="<?= RUTA; ?>uploads/images/<?= $pro->imagen; ?>" alt="producto"></a> <?php endif; ?> </td> <td><?= $pro->nombre; ?></td> <td><?= $pro->stock; ?></td> <td><?= $pro->precio; ?></td> <td><?= $pro->unidades; ?></td> </tr> <?php endwhile; ?> <?php endif; ?> </tbody> </table> <p class="alert alert-info">El estado de tu pedido esta en pendiente, debes ingresar el importe total al numero de cuenta <strong>#045D985VQ4</strong>, para poder porcesarlo, en el concepto debes poner el numero de tu pedido. </p> <?php endif; ?> <!-- comporbacion de $pedido --> <?php else : ?> <p class="alert alert-error">Oh no! ocurrio un error al crear tu pedido, intentalo denuevo.</p> <?php endif; ?> <?php endif; ?> </div><!-- ./contenedor_main --> </main><file_sep>/includes/views/categorias/form_gestion.view.php <?php if (isset($editar) && isset($cat) && is_object($cat)) { $accion = 'editar'; $titulo = 'Editar <strong>' . $cat->nombre . '</strong>'; $url = RUTA . 'categoria/guardar&cat=' . $cat->id; } else { $accion = 'crear'; $titulo = 'Crear categoria'; $url = RUTA . 'categoria/guardar'; } ?> <main class="main-100 vh77-center d-flex flex-column"> <h2><?= $titulo ?> </h2> <div class="contenedor-main d-flex flex-column flex-y-center h-100 formulario bg-blanco"> <div class="contenedor-main-header d-flex w-100 flex-y-center"> <div class="bg-blanco mr-auto"> <a href="<?= RUTA ?>categoria/index" class="btn-contenedor-main-header"><i class="fas fa-arrow-left"></i></a> </div> <?php if (isset($_SESSION[$this->session])) : ?> <?php if ($_SESSION[$this->session]['state'] === true) : ?> <h3 class="alert alert-success alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php else : ?> <h3 class="alert alert-error alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php endif; ?> <?php endif; Utils::deleteSession($this->session); ?> </div><!-- ./contenedor-main-header --> <div class="formulario-2 w-100 box-shadow"> <form action="<?= $url ?>" method="post" enctype="multipart/form-data"> <input type="text" name="nombre" id="nombre" class="form-control" placeholder="Nombre" value="<?= isset($cat) ? $cat->nombre : '' ?>"> <div class="footer-form"> <div class="btn-group d-flex flex-column "> <input type="submit" value="<?= ucfirst($accion); ?>" class="btn btn-submit btn-hover w-50-center" name="categoria"> </div> </div> </form> </div> </div> </main><file_sep>/includes/funciones/funciones.php <?php class Utils { public static function preDump($objeto) { echo '<pre>'; var_dump($objeto); echo '</pre>'; } public static function deleteSession($session) { if (isset($_SESSION[$session])) { unset($_SESSION[$session]); } } public static function sanitizeData($data) { $result = false; if (!empty($data)) { if (is_integer($data)) { $sanitize = filter_var($data, FILTER_SANITIZE_NUMBER_INT); } else { $sanitize = filter_var($data, FILTER_SANITIZE_STRING); } $result = $sanitize; } return $result; } public static function sanitizeEmail($email) { $result = false; if (!empty($email)) { $sanitize = filter_var($email, FILTER_SANITIZE_STRING); $result = $sanitize; } return $result; } public static function passwordHash($password, $cost) { $result = false; if (!empty($password)) { $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => $cost]); $result = $hash; } return $result; } public static function isAdmin($accion = null) { $isAdmin = false; if (isset($_SESSION['usuario']['admin'])) { $isAdmin = true; } elseif (isset($_SESSION['usuario']['admin'])) { if ($accion === 'header') { header('Location:' . RUTA); } elseif ($accion == 'login') { header('Location:' . RUTA . 'usuario/iniciarSesion'); } } return $isAdmin; } public static function isLogin($accion = null) { $isLogin = false; if (isset($_SESSION['usuario']['usuario'])) { $isLogin = true; } else { if ($accion === 'header') { header('Location:' . RUTA); } elseif ($accion == 'login') { header('Location:' . RUTA . 'usuario/iniciarSesion'); } } return $isLogin; } public static function compararCampo($db, $tabla, $campo, $datoComparar) { $sql = $db->query(" SELECT * FROM $tabla WHERE $campo = '{$datoComparar}' "); return $sql; } public static function showCategorias() { include_once 'includes/models/CategoriaModel.php'; $categoria = new CategoriaModel(); $categorias = $categoria->getAll(); return $categorias; } public static function statsCarrito() { $stats = array( 'count' => 0, 'total' => 0 ); if (isset($_SESSION['carrito'])) { foreach ($_SESSION['carrito'] as $indice => $producto) { $stats['count'] += $producto['cantidad']; $stats['total'] += $producto['precio'] * $producto['cantidad']; } } return $stats; } public static function getController() { $result = false; if (isset($_GET['controller'])) { $result = $_GET['controller']; } return $result; } public static function comprobarSwl($database) { if (isset($database->error)) { echo $database->error; echo '<br>'; echo $database->errno; echo '<br>'; foreach ($database->error_list as $error) { echo $error; } die(); } } }<file_sep>/autoload.php <?php function controllers_autoload($controller) { require 'includes/controllers/' . $controller . '.php'; } spl_autoload_register('controllers_autoload'); <file_sep>/includes/views/producto/gestion.view.php <main class="main-100 vh77-center d-flex flex-column flex-y-center justify-center"> <h2>Gestionar Productos</h2> <div class="contenedor-main w-50-center d-flex flex-column h-100 bg-blanco"> <div class="contenedor-main-header d-flex w-100 flex-y-center"> <div class="bg-blanco mr-auto mr-5"> <a href="<?= RUTA ?>" class="btn-contenedor-main-header"><i class="fas fa-arrow-left"></i></a> <a href="<?= RUTA ?>/producto/crear" class="btn-contenedor-main-header"><i class="fas fa-plus"></i></a> </div> <?php if (isset($_SESSION[$this->session])) : ?> <?php if ($_SESSION[$this->session]['state'] === true) : ?> <h3 class="alert alert-success alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php else : ?> <h3 class="alert alert-error alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php endif; ?> <?php endif; Utils::deleteSession($this->session); ?> </div><!-- ./contenedor-main-header --> <div class="contenido d-flex flex-column flex-y-center"> <table class="table table-v2"> <thead> <tr> <td>Id</td> <td>Nombre</td> <td>descripcion</td> <td>stock</td> <td>precio</td> <td>oferta</td> <td>Acciones</td> </tr> </thead> <tbody> <?php while ($pro = $productos->fetch_object()) : ?> <tr> <!-- --> <td><?= $pro->id; ?></td> <td><?= $pro->nombre; ?></td> <td><?= $pro->descripcion; ?></td> <td><?= $pro->stock; ?></td> <td><?= $pro->precio; ?></td> <td><?= $pro->oferta; ?></td> <td> <a href="<?= RUTA ?>producto/editar&id=<?= $pro->id; ?>" class="btn btn-table-editar">Editar</a> <a href="<?= RUTA ?>producto/eliminar&id=<?= $pro->id; ?>" class="btn btn-table-eliminar">Eliminar</a> </td> </tr> <?php endwhile; ?> </tbody> <tfoot> <tr> <td>Id</td> <td>Nombre</td> <td>descripcion</td> <td>stock</td> <td>precio</td> <td>oferta</td> <td>Acciones</td> </tr> </tfoot> </table> </div> </div> </main><file_sep>/includes/templates/footer.php </div><!-- ./contenedor --> <footer> <p class="copyright"><span>JDesign</span> todos los derechos reservados&copy;</p> </footer> <script src="<?php echo RUTA; ?>/assets/js/main.js"></script> </body> </html><file_sep>/includes/views/pedido/ver.view.php <main class="main-100 vh77-center d-flex flex-column"> <h2>Tu pedido</h2> <!-- <?php Utils::preDump($_SESSION); ?> --> <div class="contenedor-main d-flex flex-column flex-y-center h-100 bg-blanco"> <div class="contenedor-main-header d-flex w-100 flex-y-center"> <div class="bg-blanco mr-auto mr-5"> <a href="<?= RUTA ?>pedido/pedidos" class="btn-contenedor-main-header"><i class="fas fa-arrow-left"></i></a> </div> <?php if (isset($_SESSION[$this->session])) : ?> <?php if ($_SESSION[$this->session]['state'] === true) : ?> <h3 class="alert alert-success alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php else : ?> <h3 class="alert alert-error alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php endif; ?> <?php endif; Utils::deleteSession($this->session); ?> </div><!-- ./contenedor-main-header --> <!-- isset$_SESSION'pedido' --> <div class="contenido"> <?php if (Utils::isAdmin()) : ?> <div class="formulario formulario-min "> <form action="<?= RUTA ?>pedido/editar" method="post" enctype="multipart/form-data"> <select name="estado" id="estado" class="form-control"> <option value="pendiente" <?= $pedido->estado == 'pendiente' ? 'selected' : '' ?>>Pendiente</option> <option value="preparando" <?= $pedido->estado == 'preparando' ? 'selected' : '' ?>>Preparando</option> <option value="prepaenviar" <?= $pedido->estado == 'prepaenviar' ? 'selected' : '' ?>>Preparado para enviar</option> <option value="enviado" <?= $pedido->estado == 'enviado' ? 'selected' : '' ?>>Enviado</option> <option value="entregado" <?= $pedido->estado == 'entregado' ? 'selected' : '' ?>>Entregado</option> </select> <input type="hidden" name="id" value="<?= $pedido->id ?>"> <input type="submit" value="Modificar" class="btn btn-submit btn-hover w-50-center" name="submit"> </form><!-- ./form --> </div><!-- ./formulario --> <?php endif; ?> <div class="d-flex flex-row justify-around w-100 p-5 flex-y-center p-relative"> <div class="info-pedido d-flex flex-column flex-y-center "> <h3 class="d-block">Datos de facturacion</h3> <p>Provincia: <?= $pedido->provincia ?></p> <p>Localidad: <?= $pedido->localidad ?></p> <p>Direccion: <?= $pedido->direccion ?></p> </div> <div class="separador-y p-absolute"></div> <div class="info-pedido d-flex flex-column flex-y-center "> <h3 class="d-block">Datos del envio</h3> <p>Numero de pedido: <span class="f-numero"><?= $pedido->id ?></span> </p> <p>Coste: <strong><span class="f-numero">$<?= $pedido->coste ?></span></strong></p> <p>Estado: <strong><?= ucfirst($pedido->estado) ?></strong></p> </div> </div> <table class="table table-v3 table-td_min_w_150"> <thead> <td>Imagen</td> <td>Nombre</td> <td>Stock</td> <td>Precio</td> <td>Unidades</td> </thead> <tbody> <?php if (isset($prods_pedido)) : ?> <?php while ($pro = $prods_pedido->fetch_object()) : ?> <tr> <td> <?php if ($pro->imagen == null) : ?> <a href="<?= RUTA ?>producto/productoView&prod=<?= $pro->id ?>"><img src="<?= RUTA; ?>assets/img/new-product2.jpg" alt="producto"></a> <?php else : ?> <a href="<?= RUTA ?>producto/productoView&prod=<?= $pro->id ?>"><img src="<?= RUTA; ?>uploads/images/<?= $pro->imagen; ?>" alt="producto"></a> <?php endif; ?> </td> <td><?= $pro->nombre; ?></td> <td class="f-numero"><?= $pro->stock; ?></td> <td class="f-numero"><?= $pro->precio; ?></td> <td class="f-numero"><?= $pro->unidades; ?></td> </tr> <?php endwhile; ?> <?php endif; ?> </tbody> </table> <p class="alert alert-info alert-w-100">El estado de tu pedido esta en pendiente, debes ingresar el importe total al numero de cuenta <strong>#045D985VQ4</strong>, para poder porcesarlo, en el concepto debes poner el numero de tu pedido. </p> </div> </div><!-- ./contenedor_main --> </main><file_sep>/includes/views/producto/form_gestion.view.php <?php $categorias = Utils::showCategorias(); if (isset($editar) && isset($pro) && is_object($pro)) { $url_action = RUTA . 'producto/guardar&id=' . $pro->id; $titulo = 'Editar producto <strong>' . $pro->nombre . '</strong>'; $submit_value = 'Editar'; } else { $url_action = RUTA . 'producto/guardar'; $titulo = 'Crear producto '; $submit_value = 'Crear'; } ?> <main class="main-100 vh77-center d-flex flex-column"> <h2> <?= $titulo ?></h2> <div class="contenedor-main d-flex flex-column flex-y-center h-100 bg-blanco formulario"> <div class="contenedor-main-header d-flex w-100 flex-y-center"> <div class="bg-blanco mr-auto mr-5"> <a href="<?= RUTA ?>producto/gestion" class="btn-contenedor-main-header"><i class="fas fa-arrow-left"></i></a> </div> <?php if (isset($_SESSION[$this->session])) : ?> <?php if ($_SESSION[$this->session]['state'] === true) : ?> <h3 class="alert alert-success alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php else : ?> <h3 class="alert alert-error alert-animate"><?= $_SESSION[$this->session]['message'] ?></h3> <?php endif; ?> <?php endif; Utils::deleteSession($this->session); ?> </div><!-- ./contenedor-main-header --> <div class="formulario-2 w-100 box-shadow"> <form action="<?= $url_action ?>" method="post" enctype="multipart/form-data"> <input type="text" name="nombre" id="nombre" class="form-control" placeholder="Nombre" <?= (isset($pro) && is_object($pro)) ? "value='{$pro->nombre}'" : '' ?>> <textarea name="descripcion" class="form-control textarea" placeholder="Descripcion"><?= (isset($pro) && is_object($pro)) ? $pro->descripcion : '' ?></textarea> <input type="text" name="precio" id="precio" class="form-control" placeholder="Precio" <?= (isset($pro) && is_object($pro)) ? "value='{$pro->precio}'" : '' ?>> <input type="number" name="stock" id="stock" class="form-control" placeholder="Stock" <?= (isset($pro) && is_object($pro)) ? "value='{$pro->stock}'" : '' ?>> <select name="categoriaId" id="categoriaId" class="form-control"> <option value="null">Seleccione una categoria </option> <?php while ($cat = $categorias->fetch_object()) : ?> <option value="<?= $cat->id; ?>" <?= (isset($pro) && is_object($pro) && $cat->id == $pro->categoria_id) ? "selected" : '' ?>><?= $cat->nombre; ?> </option> <?php endwhile; ?> </select> <input type="file" name="image" id="image" class="form-control"> <?php if (isset($pro) && is_object($pro) && !empty($pro->imagen)) : ?> <div class="thumbs_container w-100 d-flex"> <img src="<?= RUTA ?>uploads/images/<?= $pro->imagen ?>" alt="<?= $pro->imagen ?>" class="thumb_form"> </div> <?php endif; ?> <div class="footer-form"> <div class="btn-group d-flex flex-column "> <input type="submit" value="<?= $submit_value ?>" class="btn btn-submit btn-hover w-50-center" name="submit"> </div> </div><!-- ./footer-form --> </form><!-- ./form --> </div><!-- ./formulario --> </div><!-- ./contenedor_main --> </main><file_sep>/includes/controllers/CarritoController.php <?php include_once 'includes/models/ProductoModel.php'; class CarritoController { public function index() {/* Utils::preDump($_SESSION['carrito'][0]); */ $stats = Utils::statsCarrito(); require_once 'includes/views/carrito/carrito.view.php'; } public function add() { if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['añadirCarrito'])) { if (isset($_POST['producto_id'])) { $producto_id = $_POST['producto_id']; } else { header('Location:' . $_SERVER['HTTP_REFERER']); } /* si existe el carrito y counter no es igual 0 y el id es igual se aumentan las unidades */ if (isset($_SESSION['carrito'])) { $counter = 0; foreach ($_SESSION['carrito'] as $indice => $elemento) { /* Utils::preDump($indice); die(); */ if ($elemento['id_producto'] == $producto_id) { for ($i = 0; $i < $_POST['cantidad']; $i++) { $_SESSION['carrito'][$indice]['cantidad']++; } $counter++; } } } /* si counter no existe o esta en 0 se añade el producto al carrito*/ if (!isset($counter) || $counter == 0) { /* conseguir producto */ $product = new ProductoModel(); $product->setId($producto_id); $producto = $product->getOne(); /* añadir la carrito */ if (is_object($producto)) { $_SESSION['carrito'][] = array( 'id_producto' => $producto->id, 'precio' => $producto->precio, 'cantidad' => isset($_POST['cantidad']) ? $_POST['cantidad'] : 1, 'producto' => $producto ); } /* Utils::preDump($_SESSION['carrito']); */ } header('Location:' . RUTA . 'carrito/index'); } else { header('Location:' . $_SERVER['HTTP_REFERER']); } } public function delete() { unset($_SESSION['carrito']); header('location:' . RUTA); } public function remove() { if (isset($_GET['prod'])) { $indice = $_GET['prod']; if (isset($_SESSION['carrito'][$indice])) { $indice = $_SESSION['carrito'][$indice]; foreach (array_keys($_SESSION['carrito'], $indice) as $key) { unset($_SESSION['carrito'][$key]); header('Location:' . RUTA . 'carrito/index'); } } } } } <file_sep>/includes/controllers/PedidoController.php <?php include_once 'includes/models/PedidoModel.php'; class PedidoController { public $session; public function __construct() { $this->session = Utils::getController(); } public function index() { Utils::isAdmin('header'); $pedido = new PedidoModel(); $pedidos = $pedido->getAll(); include_once 'includes/views/pedido/index.view.php'; } public function crear() { include_once 'includes/views/pedido/crear.view.php'; } public function add() { if (isset($_SESSION['login'])) { $provincia = Utils::sanitizeData($_POST['provincia']); $localidad = Utils::sanitizeData($_POST['localidad']); $direccion = Utils::sanitizeData($_POST['direccion']); $usuarioId = Utils::sanitizeData($_POST['usuarioId']); $coste = Utils::sanitizeData($_POST['coste']); $estado = Utils::sanitizeData($_POST['estado']); if ($provincia && $localidad && $direccion && $usuarioId && $coste && $estado) { $pedido = new PedidoModel(); $pedido->setUsuarioId($usuarioId); $pedido->setProvincia($provincia); $pedido->setLocalidad($localidad); $pedido->setDireccion($direccion); $pedido->setCoste($coste); $pedido->setEstado($estado); $save = $pedido->save(); if ($save) { /* si se guardo el pedido se guardarn los datos pivotes del pivote */ $save_linea = $pedido->saveLinea(); if ($save_linea) { $_SESSION[$this->session]['estate'] = $save['state']; $_SESSION[$this->session]['message'] = $save['message']; header('Location:' . RUTA . 'pedido/confirmacion'); } } else { $_SESSION[$this->session]['estate'] = $save['state']; $_SESSION[$this->session]['message'] = $save['message']; header('Location:' . RUTA . 'carrito/index'); } } else { $_SESSION[$this->session]['estate'] = 'failed'; $_SESSION[$this->session]['estate'] = 'Los datos introducidos no son correctos'; header('Location:' . RUTA . 'carrito/crear'); } } else { header('Location:' . RUTA); } } public function confirmacion() { if (isset($_SESSION['login']['usuario'])) { /* conseguir datos del pedido */ $usuario = $_SESSION['login']['usuario']; $pedido = new PedidoModel(); $pedido->setUsuarioId($usuario->id); $pedido = $pedido->getOneByUser(); /* conseguir los productos del pedido */ $prods_pedido = new PedidoModel(); $prods_pedido->setId($pedido->id); $productos = $prods_pedido->getProductosByPedido(); include_once 'includes/views/pedido/confirmacion.view.php'; } } public function pedidos() { if (Utils::isLogin()) { $usuario = $_SESSION['usuario']['usuario']; $pedidos = new PedidoModel(); $pedidos->setUsuarioId($usuario->id); $pedidos = $pedidos->getAllByUser(); include_once 'includes/views/pedido/pedidos.view.php'; } } public function pedidoView() { if (Utils::isLogin()) { /* conseguir datos del pedido */ if (isset($_GET['p'])) { $pedido = new PedidoModel(); $pedido->setId($_GET['p']); $pedido = $pedido->getOne(); if (!$pedido) { header('Location:' . RUTA . 'pedido/pedidos'); } /* conseguir los productos del pedido */ $prods_pedido = new PedidoModel(); $prods_pedido->setId($_GET['p']); $prods_pedido = $prods_pedido->getProductosByPedido(); include_once 'includes/views/pedido/ver.view.php'; } else { header('Location:' . RUTA . 'pedido/pedidos'); } } } public function editar() { if (Utils::isLogin()) { if (isset($_POST['estado']) && $_SERVER['REQUEST_METHOD'] === 'POST') { $estado = Utils::sanitizeData($_POST['estado']); $id = Utils::sanitizeData($_POST['id']); $editar = true; $pedido = new PedidoModel(); $pedido->setId($id); $pedido->setEstado($estado); $update = $pedido->update(); if ($update) { $_SESSION[$this->session]['state'] = $update['state'];; $_SESSION[$this->session]['message'] = $update['message']; header('Location:' . RUTA . 'pedido/pedidoView&p=' . $id); } } } } public function eliminar() { if ($_GET['p']) { $pedidoID = Utils::sanitizeData($_GET['p']); $pedido = new PedidoModel(); $pedido->setId($pedidoID); $delete = $pedido->delete(); if ($delete) { $deleteLinea = $pedido->deleteLinea(); if ($deleteLinea) { $_SESSION['pedido']['state'] = $delete['state']; $_SESSION['pedido']['message'] = $delete['message']; header('Location:' . RUTA . 'pedido/index'); } else { $_SESSION['pedido']['state'] = $delete['state']; $_SESSION['pedido']['message'] = $delete['message']; header('Location:' . RUTA . 'pedido/index'); } } else { $_SESSION['pedido']['state'] = $delete['state']; $_SESSION['pedido']['message'] = $delete['message']; header('Location:' . RUTA . 'pedido/index'); } } } } <file_sep>/config/DataBase.php <?php class DataBase { public static function conexionDB() { try { $conn = new mysqli('localhost', 'root', '', 'tienda_master'); $conn->query(" SET NAMES 'utf8' "); return $conn; } catch (mysqli_sql_exception $e) { echo 'Falló la conexión: ' . $e->getMessage(); } } } <file_sep>/includes/controllers/CategoriaController.php <?php include_once 'includes/models/CategoriaModel.php'; include_once 'includes/models/ProductoModel.php'; class CategoriaController { public $session; public function __construct() { $this->session = Utils::getController();/* Utils::preDump($_GET); */ } public function index() { Utils::isAdmin('header'); $categoria = new CategoriaModel(); $categorias = $categoria->getAll(); require_once 'includes/views/categorias/index.view.php'; } public function categoria() { if (isset($_GET['cat'])) { $catId = Utils::sanitizeData($_GET['cat']); /* conseguir la categoria */ $category = new CategoriaModel(); $category->setId($catId); $category = $category->getOne(); /* conseguir los productos */ $product = new ProductoModel(); $product->setCategoriaId($catId); $products = $product->getAllCategoria(); } require_once 'includes/views/categorias/ver.view.php'; } public function crear() { if (Utils::isAdmin('header')) { require_once 'includes/views/categorias/form_gestion.view.php'; } } public function editar() { if (Utils::isAdmin('header')) { if (isset($_GET['cat'])) { $editar = true; $catId = Utils::sanitizeData($_GET['cat']); $cat = new CategoriaModel(); $cat->setId($catId); $cat = $cat->getOne(); require_once 'includes/views/categorias/form_gestion.view.php'; } else { header('Location:' . RUTA . 'categoria/index'); } } } public function guardar() { Utils::isAdmin('header'); if (isset($_POST) && isset($_POST['nombre'])) { $nombre = ($_POST['nombre'] != '') ? Utils::sanitizeData(ucfirst($_POST['nombre'])) : null; if ($nombre) { $categoria = new CategoriaModel(); $categoria->setNombre($nombre); if (isset($_GET['cat'])) { $catId = Utils::sanitizeData($_GET['cat']); $url = 'editar&cat=' . $catId; $categoria->setId($catId); $categoria = $categoria->update(); } else { $url = 'crear'; $categoria = $categoria->save(); } if ($categoria) { $_SESSION[$this->session]['state'] = $categoria['state']; $_SESSION[$this->session]['message'] = $categoria['message']; if ($_SESSION[$this->session]['state'] !== true) { header('Location:' . RUTA . 'categoria/' . $url); } else { header('Location:' . RUTA . 'categoria/index'); } } } } } public function eliminar() { Utils::isAdmin('header'); if (isset($_GET['cat'])) { $catId = Utils::sanitizeData($_GET['cat']); /* conseguir la categoria */ $category = new CategoriaModel(); $category->setId($catId); $delete = $category->delete(); if ($delete) { $_SESSION[$this->session]['state'] = $delete['state']; $_SESSION[$this->session]['message'] = $delete['message']; header('Location:' . RUTA . 'categoria/index'); } } else { $_SESSION[$this->session]['state'] = $delete['state']; $_SESSION[$this->session]['message'] = $delete['message']; header('Location:' . RUTA . 'categoria/index'); } } } <file_sep>/includes/templates/aside.php <?php $usuario_session = isset($_SESSION['usuario']['usuario']) ? $_SESSION['usuario']['usuario'] : null ?> <aside class="panel"> <?php if (Utils::isLogin()) : ?> <div class="section_panel "> <h3 class="titulo_section_panel"><?= $usuario_session->nombre ?></h3> <div class="contenedor_section_panel"> <a href="<?= RUTA ?>pedido/pedidos" class="btn-aside">Mis pedidos</a> </div> </div> <?php endif ?> <?php if (Utils::isAdmin()) : ?> <div class="section_panel "> <h3 class="titulo_section_panel">@Admin</h3> <div class="contenedor_section_panel"> <a href="<?= RUTA; ?>categoria/index" class="btn-aside ">Gestionar categorias</a> <a href="<?= RUTA; ?>producto/gestion" class="btn-aside ">Gestionar Productos</a> <a href="<?= RUTA; ?>pedido/index" class="btn-aside ">Gestionar Pedidos</a> </div> </div> <?php endif ?> <div class="section_panel "> <h3 class="titulo_section_panel">Categorias</h3> <div class="contenedor_section_panel"> <?php $categorias = Utils::showCategorias(); ?> <ul class="d-flex flex-column"> <?php while ($categoria = $categorias->fetch_object()) : ?> <a href="<?= RUTA ?>categoria/categoria&cat=<?= $categoria->id ?>" class="link_btn_aside"> <li class="btn-aside"><?= $categoria->nombre; ?></li> </a> <?php endwhile; ?> </ul> </div> </div> </aside><file_sep>/includes/views/carrito/carrito.view.php <main class="main-100 vh77-center d-flex flex-column flex-y-center justify-center"> <div class="contenedor-main w-50-center d-flex flex-column h-100 bg-blanco"> <div class="contenido d-flex flex-column flex-y-center"> <?php if ($stats['count'] == 0) : ?> <h3>El carrito esta vacio</h3> <?php else : ?> <h3>(<?= $stats['count'] ?>) productos del carrito</h3> <?php endif; ?> <?php if (isset($_SESSION['carrito'])) : ?> <table class="table table-v3"> <tbody> <?php foreach ($_SESSION['carrito'] as $indice => $elemento) : ?> <tr> <td> <?php if ($elemento['producto']->imagen == null) : ?> <a href="<?= RUTA ?>producto/productoView&prod=<?= $elemento['id_producto'] ?>"><img src="<?= RUTA; ?>assets/img/new-product2.jpg" alt="producto"></a> <?php else : ?> <a href="<?= RUTA ?>producto/productoView&prod=<?= $elemento['id_producto'] ?>"><img src="<?= RUTA; ?>uploads/images/<?= $elemento['producto']->imagen; ?>" alt="producto"></a> <?php endif; ?> </td> <td><?= $elemento['producto']->nombre; ?></td> <td><?= $elemento['cantidad'] ?></td> <td>$<?= $elemento['producto']->precio * $elemento['cantidad'] ?></td> <td> <a href="<?= RUTA ?>carrito/delete&prod=<?= $indice ?>" class="table-i"><i class="far fa-trash-alt"></i></a> </td> </tr> <?php endforeach; ?> </tbody> </table> <div class="tbl-total d-flex w-100"> <p>Total</p> <p>$<?= $stats['total'] ?></p> </div> <div class="btn-group d-flex w-100"> <a href="<?= RUTA ?>" class="btn btn-hover btn-Scomprando">Seguir comprando</a> <?php if (isset($_SESSION['login'])) : ?> <a href="<?= RUTA ?>pedido/crear" class="btn btn-hover btn-Ppedido">Realizar pedido</a> <?php else : ?> <a href="<?= RUTA ?>usuario/iniciarSesion" class="btn btn-Ppedido-b">Realizar pedido</a> <?php endif; ?> </div> <?php endif; ?> </div> </div> </main>
9bdea3a18a59cd5f8e62e829514bae01bfb80bf4
[ "PHP" ]
31
PHP
bozus94/php_shopping
25dfcf6661e6c71111aa3e5ece3b44adba3f6f85
0c8fac728a061c7c256996e05d5826d910ab8655
refs/heads/master
<file_sep>function startTimer(){ window[0].exportRoot.scr_timer.grc_start.dispatchEvent("mousedown") } function setTimer(hour,minute){ let interval = setInterval(()=>{ let sound = new Audio('https://www.jothamhernandez.com/beep.mp3') sound.src = "https://cdn.videvo.net/videvo_files/audio/premium/audio0083/watermarked/ElectronicBeep%20PS01_62_1_preview.mp3"; if((new Date()).getHours() == hour && (new Date()).getMinutes() == minute - 1 && (new Date()).getSeconds() >= 50){ sound.play(); } if((new Date()).getHours() == hour && (new Date()).getMinutes() == minute){ startTimer(); clearInterval(interval); } },1000) } <file_sep>(function() { // Load the script var script = document.createElement("SCRIPT"); var link = document.createElement("LINK"); link.href="https://cdn.rawgit.com/jothamhernandez/snippetFiles/master/bday.css"; link.type="text/css"; link.rel="stylesheet"; script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'; script.type = 'text/javascript'; script.onload = function() { var $ = window.jQuery; // Use $ here... $(document).ready(function(){ $.ajax({ url: "https://cdn.rawgit.com/jothamhernandez/snippetFiles/master/message.json", method: "GET", dataType: "JSON", success: function(data){ var content = $(".my_greeting > p").html(data.message); } }) }); }; document.getElementsByTagName("head")[0].appendChild(script); document.getElementsByTagName("head")[0].appendChild(link); })();
09df5ca870bcbcd9f17598c2bc8d3063146da1fd
[ "JavaScript" ]
2
JavaScript
jothamhernandez/snippetFiles
1d6a08d1c87982f01af5f3fa19be0f4d42d39450
af26350aa5aa71a3e059b6cc7c8bc2ac4076bbdf
refs/heads/main
<repo_name>zukhriddinakhmedov/User-generator<file_sep>/script.js const btn = document.getElementById("mainBtn") const displayUsers = function (users) { const row = document.querySelector("table") row.innerHTML = "" users.forEach((user, index) => { row.innerHTML += ` <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">Numeration</th> <th scope="col">Gender</th> <th scope="col">Full name</th> <th scope="col">Location</th> <th scope="col">Email</th> <th scope="col">Age</th> </tr> <tr> <th scope="row">${index}</th> <td>${user.gender}</td> <td>${user.name.first + " " + user.name.last}</td> <td>${user.location.city}</td> <td>${user.email}</td> <td>${user.dob.age}</td> </tr> </table> ` }) } function filteredAge(usersArr) { const filterAge = usersArr.filter(user => user.dob.age > 18) displayUsers(filterAge) console.log(filterAge) } const getUsers = () => { fetch("https://randomuser.me/api/?results=10") .then(response => response.json()) .then(users => { console.log(users) displayUsers(users.results) btn.addEventListener("click", (e) => { e.preventDefault() filteredAge(users.results) }) }) } window.onload = () => { getUsers() }
3f4cbc63b642227858303072b2223d5e96a1caa5
[ "JavaScript" ]
1
JavaScript
zukhriddinakhmedov/User-generator
e9d2d2882e070224ca822f0181a6242529144506
9dc0eac96ccce3c22a1f000fa0dfae6c6487b034
refs/heads/main
<repo_name>ravikiran-ds/assistant-and-hate-speech-recog<file_sep>/hate_speech.py # -*- coding: utf-8 -*- """ Created on Sun Oct 25 12:10:30 2020 @author: HP """ import pandas as pd import numpy as np import matplotlib.pyplot as plt df=pd.read_csv('hate_speech.csv') #lookin at the shape of the dataset rows,cols=df.shape #columns df.columns #sample rows df.head() #lookin at first tweet df.tweet[0] #preprocessing df2=df[["offensive_language","tweet"]] df2.tweet=df.tweet.apply(lambda x:x.split(":",1)) #lookina t tweets df2.tweet[0] #removing the user name for i in range(0,rows): if len(df2.tweet[i])>1: df2.tweet[i]=df2.tweet[i][1] else: df2.tweet[i]=df2.tweet[i][0] #convertng offensive language to binary df2["offensive_language"]= df2.offensive_language.apply(lambda x:1 if x>0 else 0 ) #text processing #converting text to lower df2.tweet=df2.tweet.apply(lambda x:x.lower()) #keeping only the text import re df2.tweet=df2.tweet.apply(lambda x:re.sub(pattern='[^a-zA-Z]',repl=" ",string=x)) #removing stopwords import nltk #nltk.download('stopwords') from nltk.corpus import stopwords df2.tweet=df2.tweet.apply(lambda x:x.split()) from nltk.stem.porter import PorterStemmer stem=PorterStemmer() df2.tweet=df2.tweet.apply(lambda x:[stem.stem(word) for word in x if word not in set(stopwords.words('english'))]) #creating the sparse matrix df2.tweet=df2.tweet.apply(lambda x:" ".join(x)) corpus=[x for x in df2.tweet] from sklearn.feature_extraction.text import CountVectorizer cv=CountVectorizer(max_features=1500) sparse_matrix=cv.fit_transform(corpus).toarray() #cv.get_feature_names() #dataframe of the sparse matrix with dependent variable df0=pd.DataFrame(sparse_matrix,columns=cv.get_feature_names()) df0["hate"]=df2['offensive_language'] #classification x=df0.drop("hate",axis=1) y=df0['hate'].values #splitting train test data from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=101) #model building import tensorflow import keras from keras.models import load_model from keras.models import Sequential from keras.layers import Dense #initializing the ANN ann_cls=Sequential() #adding input and first layer ann_cls.add(Dense(output_dim=750,input_dim=1499,activation='relu',init='uniform')) #adding 2nd hidden layer ann_cls.add(Dense(output_dim=750,activation='relu')) #adding output layer ann_cls.add(Dense(output_dim=1,activation='sigmoid')) #compiling ANN ann_cls.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy']) #fitting the data ann_cls.fit(x_train,y_train,batch_size=100,epochs=10) #saving the model ann_cls.save('hate_speech.model') #loading model ann_cls=load_model('hate_speech.model') #predicting ypred=ann_cls.predict(x_test) ypred=(ypred >0.5) from sklearn.metrics import confusion_matrix cm=confusion_matrix(y_test, ypred) cm data={} for i in x_train.columns.unique(): data[i]=0 temp=pd.DataFrame(data,columns=x_train.columns.unique(),index=[0]) temp.to_csv("hate_headers.csv",index=False) def user_speech(text): #text=input("Enter a sentence:") temp_list=text.split() for i in temp_list: if i in temp.columns: temp[i]=1 temp_pred=ann_cls.predict(temp) if temp_pred>0.5: #print("hate") return "hate" else: return "fine" <file_sep>/assistant.py # -*- coding: utf-8 -*- """ Created on Sun Oct 25 01:48:18 2020 @author: HP """ import speech_recog as sr from speak import SpeakText import tensorflow import keras from keras import models import pandas as pd from search import search_term from search import search_youtube from search import search_website #loading the model model=models.load_model("hate_speech.model") #taking input from users speak=SpeakText() #getting voice input from user #text=sr.get_text_from_speech() def take_inp(): text=input("Enter text :") temp=text.split() #predicitng x=pd.read_csv("hate_headers.csv") for i in temp: if i in x.columns.unique(): x[i]=1 pred=model.predict(x) return pred,text print("{} is the list of values {} is the text {} is the prediction for hate.".format(temp,text,pred[0][0])) #take_inp() def response(text,speed=200,sound=5): speak.Speak(text,speed,sound) #quores set quotes=pd.read_csv('quots.csv', sep=" ", header=None,dtype={0:str}) quotes.drop([0],inplace=True) for i in range(1,len(quotes)+1): quotes[0][i]=quotes[0][i].replace("\x9d","") quotes[0][i]=quotes[0][i].replace("\t","") #facts set facts=pd.read_csv('facts.csv') for i in range(0,len(facts)): facts["facts"][i]=facts["facts"][i].replace('\x9d',"") facts["facts"][i]=facts["facts"][i].replace('â€',"'") from random import randint def hate_response(): #print('hate') qu=randint(0,len(quotes)) response(quotes.iloc[qu,0],speed=150,sound=10) response("do not hate",speed=100,sound=10) def normal_response(): #print('normal') fa=randint(0,len(facts)) response(facts.iloc[fa,0],speed=150,sound=10) #response("Good for you",speed=100,sound=5) #responding to input def out(): pred=take_inp() if pred[0][0]>0.7: hate_response() out() else: normal_response() out() def hate_speech(): i=1 while i==1: try: out() except KeyboardInterrupt: print("good bye") response("Good Bye",speed=120,sound=7) i=2 def search(): _,text=take_inp() search_term(text) def youtube(): _,text=take_inp() search_youtube(text) def website(): print(" at the end add '.com'") _,text=take_inp() search_website(text) #hate speech assistant hate_speech() #search assistant search() #search youtube youtube() #website website() <file_sep>/README.md # hate-speech-assistant assistant.py is the main file This project was created to avoid personal usage collection byb websites since you are not logged into the browser by opening in this method The main ojective is identifying hate speech but it can also open google and search the terms open youtube and play the first video search for website the libraries used keras tensorflow nltk pandas speechregonition #for hate speech I have creates a ANN to identify the hae speech in the text #for searching just enter the text #in future speech recog can be added <file_sep>/search.py # -*- coding: utf-8 -*- """ Created on Mon Oct 26 09:10:35 2020 @author: HP """ from selenium.common.exceptions import NoSuchElementException, ElementClickInterceptedException from selenium import webdriver from selenium.webdriver.common.keys import Keys import time def search_term(text): options = webdriver.ChromeOptions() driver = webdriver.Chrome(executable_path="C:\\bin\\chromedriver.exe", options=options) driver.set_window_size(1120, 1000) url= 'https://www.google.com/' driver.get(url) somthing=driver.find_elements_by_class_name("gsfi") somthing[1].send_keys(text) somthing[1].send_keys(Keys.ENTER) time.sleep(20) driver.quit() def search_youtube(text): options = webdriver.ChromeOptions() driver = webdriver.Chrome(executable_path="C:\\bin\\chromedriver.exe", options=options) driver.set_window_size(1120, 1000) url= 'https://www.youtube.com/results?search_query=' driver.get(url+text) link=driver.find_element_by_tag_name("img") link.click() def search_website(text): options = webdriver.ChromeOptions() driver = webdriver.Chrome(executable_path="C:\\bin\\chromedriver.exe", options=options) driver.set_window_size(1120, 1000) url= 'https://www.google.com/' driver.get(url) somthing=driver.find_elements_by_class_name("gsfi") somthing[1].send_keys(text) somthing[1].send_keys(Keys.ENTER) link=driver.find_element_by_tag_name("cite") link.click()
d02ccadd3ae64f678c2c35041f29c2bb1dcf1429
[ "Markdown", "Python" ]
4
Python
ravikiran-ds/assistant-and-hate-speech-recog
70d929105da7c12bcbeb0aeb57dfa62ffcf342c5
aebf2e7b93af6abab3595acf55ad03454b89d9aa
refs/heads/master
<file_sep>DynNPC:RegisterNPC("Junkie", { Model = "Thug", Animation = "Scared", Dynamic = true, ShouldRelocate = function(self) for _, Plr in pairs(player.GetAll()) do if Plr:isCP() and Plr:EyePos():Distance(self:EyePos()) <= 160 then return CurTime() - self.LastRelocate > 10, 60 end end return CurTime() - self.LastRelocate > 240 end, Options = { { Name = "Sell me stuff", Select = function(Plr) end, Requirement = function(Plr) return true end } } }) <file_sep>DynNPC:RegisterNPC("Realtor", { Model = "SuitsClosedTie", Animation = "Standing", CustomNetFunc = "PropertiesMenuNet" }) hook.Add("SetupPlayerVisibility", "PropertiesRenderCameras", function() for i, v in pairs(GlobalProperties) do if v.Cameras[1] then AddOriginToPVS(v.Cameras[1][1]) end end end) local function OwnDoor(Plr, Ent) Ent:keysOwn(Plr) hook.Call("playerBoughtDoor", GAMEMODE, Plr, Ent, 0) end local function DisownDoor(Plr, Ent) Ent:keysUnOwn(Plr) Ent:setKeysTitle() hook.Call("playerKeysSold", GAMEMODE, Plr, Ent, 0) end util.AddNetworkString("PropertiesMenuNet") net.Receive("PropertiesMenuNet", function(Len, Plr) local Type = net.ReadString() local PropertyName = net.ReadString() if not GlobalProperties[PropertyName] then return end if Type == "Buy" then for _, v in pairs(GlobalProperties[PropertyName].Doors) do OwnDoor(Plr, v) end elseif Type == "Sell" then for _, v in pairs(GlobalProperties[PropertyName].Doors) do DisownDoor(Plr, v) end end end) local function DoorToPropertyName(Door) for i, v in pairs(GlobalProperties) do for _, x in pairs(v.Doors) do if Door == x then return i end end end end hook.Add("getDoorCost", "PropertiesGetDoorCost", function(Plr, Ent) if DoorToPropertyName(Ent) then return 0 end end) hook.Add("playerBuyDoor", "PropertiesBuyDoor", function(Plr, Ent, Custom) if DoorToPropertyName(Ent) then return Custom or false, "You must buy this door from a realtor!" end end) hook.Add("playerSellDoor", "PropertiesSellDoor", function(Plr, Ent, Custom) if DoorToPropertyName(Ent) then return Custom or false, "You must sell this door from a realtor!" end end) hook.Add("hideSellDoorMessage", "PropertiesHideSellMessage", function(Plr, Ent) if DoorIDtoPropertyName(Ent) then return true end end) <file_sep>include("shared.lua") function ENT:Initialize() self.AutomaticFrameAdvance = true self.Rotation = 90 self.UpRot = 90 end function ENT:Draw() self:DrawModel() end function ENT:Think() if LocalPlayer():EyePos():Distance(self:EyePos()) <= 1000 then local OrigAngles = self:GetNWAngle("OrigAngles") local FoundPlayer = false for _, Plr in pairs(player.GetAll()) do local Dist = Plr:EyePos():Distance(self:EyePos()) if Dist <= 160 and WorldToLocal(self:EyePos(), OrigAngles, Plr:EyePos(), OrigAngles).x < -20 then self.Rotation = math.Approach(self.Rotation, (Plr:EyePos() - self:EyePos()):Angle().y, 1) self.UpRot = math.Approach(self.UpRot, 360 - (Plr:EyePos() - self:EyePos()):Angle().x - 42 + Dist / 10, 1) FoundPlayer = true break end end if not FoundPlayer then self.Rotation = math.Approach(self.Rotation, OrigAngles.y, 1) self.UpRot = math.Approach(self.UpRot, OrigAngles.z, 1) end self:SetAngles(Angle(0, (self.Rotation - OrigAngles.y) * 0.4 + OrigAngles.y, 0)) self:ManipulateBoneAngles(self:LookupBone("ValveBiped.Bip01_Spine"), Angle(0, 0, (self.Rotation - OrigAngles.y) * 0.3)) self:ManipulateBoneAngles(self:LookupBone("ValveBiped.Bip01_Head1"), Angle(0, self.UpRot, (self.Rotation - OrigAngles.y) * 0.3)) end end <file_sep>TOOL.Category = "GreyRP" TOOL.Name = "#tool.propertydev.name" TOOL.Information = { {name = "left"}, {name = "right"}, {name = "reload"} } local PropertyDataFormat = { Name = "Unnamed", Price = 100, Rent = 0, Business = false, Warehouse = false, Start = Vector(), End = Vector(), Doors = {}, Cameras = {}, Nodes = {} } local PropertyDataFormatView = { "Name", "DETAILS", "Price", "Rent", "Business", "Warehouse", "BUSINESS", "Job", "ADVANCED", "Start", "End" } if SERVER then util.AddNetworkString("PropertiesDev") GlobalProperties = {} local function Load() GlobalProperties = GreyRP.GetData("property") for i, v in pairs(PropertyDataFormat) do for x, y in pairs(GlobalProperties) do if y[i] == nil or type(y[i]) ~= type(v) then if type(v) == "table" then y[i] = table.Copy(v) else y[i] = v end end end end for i, v in pairs(GlobalProperties) do for x, y in pairs(v) do if x ~= "Container" and PropertyDataFormat[x] == nil then v[x] = nil end end end end ENTITIES_LOADED = ENTITIES_LOADED or false if ENTITIES_LOADED then Load() else hook.Add("InitPostEntity", "GreyRPPostEntity", function() ENTITIES_LOADED = true timer.Simple(2, Load) end) end local function UpdateData() GreyRP.SetData("property", GlobalProperties) end net.Receive("PropertiesDev", function(_, Plr) local Type = net.ReadString() if Type == "Get" then local Tbl = table.Copy(GlobalProperties) for i, v in pairs(Tbl) do local NewDoors = {} for _, x in pairs(v.Doors) do NewDoors[#NewDoors + 1] = x:EntIndex() end v.Doors = NewDoors end net.Start("PropertiesDev") net.WriteInt(0, 10) net.WriteTable(Tbl) net.Send(Plr) return end local Property = net.ReadInt(10) if Type == "Set" then local New = net.ReadTable() GlobalProperties[Property] = New for _, v in pairs(player.GetAll()) do if v ~= Plr then net.Start("PropertiesDev") net.WriteInt(Property + 800 , 10) net.WriteTable(New) net.Send(v) end end UpdateData() return elseif Type == "Remove" then GlobalProperties[Property] = nil for _, v in pairs(player.GetAll()) do if v ~= Plr then net.Start("PropertiesDev") net.WriteInt(Property, 10) net.Send(v) end end UpdateData() return end local Var = net.ReadString() if Var == "Position" then local New = net.ReadTable() GlobalProperties[Property].Start, GlobalProperties[Property].End = New[1], New[2] for _, v in pairs(player.GetAll()) do if v ~= Plr then net.Start("PropertiesDev") net.WriteInt(Property, 10) net.WriteString("Position") net.WriteType(New) net.Send(v) end end else local New = net.ReadType() GlobalProperties[Property][Var] = New for _, v in pairs(player.GetAll()) do if v ~= Plr then net.Start("PropertiesDev") net.WriteInt(Property, 10) net.WriteString(Var) net.WriteType(New) net.Send(v) end end end UpdateData() end) end if CLIENT then local function CheckNumericCustom(self, Val) return not (string.find("1234567890", Val, 1, true) or string.find("-", Val, 1, true)) end local function GetSimilarEnt(Ent, Pos, Distance) for _, v in pairs(ents.FindInSphere(Pos, Distance)) do if v:GetClass() == Ent:GetClass() then return v end end end function EfficientText(Text, x, y, Center) if Center then local w, h = surface.GetTextSize(Text) x = x - w / 2 y = y - h / 2 end surface.SetTextPos(math.ceil(x), math.ceil(y)) surface.DrawText(Text) end local function MirrorPosition(Position, MirrorPos, MirrorOffset) local New = Vector(Position) if MirrorPos.x ~= 0 then New.x = MirrorPos.x - (New.x - MirrorPos.x) end if MirrorPos.y ~= 0 then New.y = MirrorPos.y - (New.y - MirrorPos.y) end if MirrorOffset then New = New + MirrorOffset end return New end local function GetPlanesIntersection(Planes) local x, y, z for _, v in pairs(Planes) do local Normal = Vector(math.Round(math.abs(v[2].x)), math.Round(math.abs(v[2].y)), math.Round(math.abs(v[2].z))) if Normal == Vector(1, 0, 0) then x = v[1].x elseif Normal == Vector(0, 1, 0) then y = v[1].y elseif Normal == Vector(0, 0, 1) then z = v[1].z end end return x, y, z end local Normals = { Front = Vector(0, -1, 0), Back = Vector(0, 1, 0), Left = Vector(-1, 0, 0), Right = Vector(1, 0, 0), Top = Vector(0, 0, 1), Bottom = Vector(0, 0, -1) } local function GetFaceNormals(Face) return Normals[Face] end local function GetFaceFromNormal(Normal) for i, v in pairs(Normals) do if v == Normal then return i end end end local function GetFaceSize(Face, Size) if Face == "Front" or Face == "Back" then return {Size.x, Size.z} elseif Face == "Left" or Face == "Right" then return {Size.y, Size.z} elseif Face == "Top" or Face == "Bottom" then return {Size.y, Size.x} end end local function Notify(Text, IsError) notification.AddLegacy(Text, IsError and NOTIFY_ERROR or NOTIFY_HINT, IsError and 4 or 2) surface.PlaySound("buttons/button15.wav") end hook.Add("CanTool", "FPP_CL_CanTool", function(ply, trace, tool) local PropertyToolGun = LocalPlayer().GetActiveWeapon and LocalPlayer():GetActiveWeapon().PrintName == "Tool Gun" and LocalPlayer():GetActiveWeapon():GetMode() == "propertydev" if not PropertyToolGun and IsValid(trace.Entity) and not FPP.canTouchEnt(trace.Entity, "Toolgun") then return false end end) GlobalProperties = {} GlobalPropertiesCheckSum = {} local Plr = LocalPlayer() net.Receive("PropertiesDev", function() local Property = net.ReadInt(10) if Property == 0 then GlobalProperties = net.ReadTable() for i, _ in pairs(GlobalProperties) do GlobalPropertiesCheckSum[i] = 0 end elseif Property > 800 then GlobalProperties[Property - 800] = net.ReadTable() GlobalPropertiesCheckSum[Property - 800] = 0 else GlobalProperties[Property][net.ReadString()] = net.ReadType() GlobalPropertiesCheckSum[Property] = GlobalPropertiesCheckSum [Property] + 1 end end) timer.Simple(1, function() Plr = LocalPlayer() net.Start("PropertiesDev") net.WriteString("Get") net.SendToServer() end) Properties = {} function Properties.GetAll() return GlobalProperties end function Properties.Get(Property) return GlobalProperties[Property] end function Properties.GetByName(Name) for _, v in pairs(GlobalProperties) do if v.Name == Name then return v end end end function Properties.Exists(Property) return GlobalProperties[Property] ~= nil end function Properties.Add(Data) local Key = table.insert(GlobalProperties, Data) GlobalPropertiesCheckSum[Key] = 0 net.Start("PropertiesDev") net.WriteString("Set") net.WriteInt(Key, 10) net.WriteTable(Data) net.SendToServer() return Key end function Properties.Remove(Property) if Plr.GetActiveWeapon and Plr:GetActiveWeapon().PrintName == "Tool Gun" and Plr:GetActiveWeapon():GetMode() == "propertydev" then local Tool = Plr:GetTool("propertydev") if Tool.SelectedProperty == Property then Tool.SelectedProperty = nil end end for i, v in pairs(Properties.GetAll()) do if v.Container == Property then Properties.UpdateVariable(v, "Container") end end net.Start("PropertiesDev") net.WriteString("Remove") net.WriteInt(Property, 10) net.SendToServer() GlobalProperties[Property] = nil GlobalPropertiesCheckSum[Property] = nil end function Properties.CheckContainer(Property) if not Properties.Exists(Property) then return end local LProp = GlobalProperties[Property] for i, v in pairs(Properties.GetAll()) do local Start, End = v.Start - Vector(5, 5, 5), v.End + Vector(5, 5, 5) OrderVectors(Start, End) if i ~= Property and not v.Business and not v.Warehouse and LProp.Start:WithinAABox(Start, End) and LProp.End:WithinAABox(Start, End) then Properties.UpdateVariable(Property, "Container", i) return end end Properties.UpdateVariable(Property, "Container") end function Properties.IsContainer(Property) for _, v in pairs(Properties.GetAll()) do if v.Container == Property then return true end end return false end function Properties.GetContained(Property) for i, v in pairs(Properties.GetAll()) do if v.Container == Property then return i end end end function Properties.ValidateDoors(Property) if not Properties.Exists(Property) then return true end local LProp = GlobalProperties[Property] for i, v in pairs(LProp.Doors) do if type(v) == "number" and IsValid(ents.GetByIndex(v)) then LProp.Doors[i] = ents.GetByIndex(v) end end for i, v in pairs(LProp.Doors) do if type(v) == "number" then return true end end end function Properties.UpdateVariable(Property, Var, New) if not Properties.Exists(Property) or Properties.GetVariable(Property, Var) == New then return end if Var == "Position" then GlobalProperties[Property].Start = New[1] GlobalProperties[Property].End = New[2] for i, _ in pairs(GlobalProperties) do Properties.CheckContainer(i) end net.Start("PropertiesDev") net.WriteString("Update") net.WriteInt(Property, 10) net.WriteString("Position") net.WriteTable(New) net.SendToServer() else GlobalProperties[Property][Var] = New net.Start("PropertiesDev") net.WriteString("Update") net.WriteInt(Property, 10) net.WriteString(Var) net.WriteType(New) net.SendToServer() if Var == "Start" or Var == "End" or Var == "Business" or Var == "Warehouse" then for i, _ in pairs(GlobalProperties) do Properties.CheckContainer(i) end end end GlobalPropertiesCheckSum[Property] = GlobalPropertiesCheckSum[Property] + 1 end function Properties.GetVariable(Property, Var, Backup) if not GlobalProperties[Property] or GlobalProperties[Property][Var] == nil then return Backup end return GlobalProperties[Property][Var] end function Properties.UpdateTableVariable(Property, Var, Ind, New) if not GlobalProperties[Property] or GlobalProperties[Property][Var] == nil then return end local Tbl = table.Copy(GlobalProperties[Property][Var]) Tbl[Ind] = New Properties.UpdateVariable(Property, Var, Tbl) end function Properties.InsertTableVariable(Property, Var, New) if not GlobalProperties[Property] or GlobalProperties[Property][Var] == nil then return end local Tbl = table.Copy(GlobalProperties[Property][Var]) table.insert(Tbl, New) Properties.UpdateVariable(Property, Var, Tbl) end function Properties.RemoveTableVariable(Property, Var, Key) if not GlobalProperties[Property] or GlobalProperties[Property][Var] == nil then return end local Tbl = table.Copy(GlobalProperties[Property][Var]) for i, _ in pairs(Tbl) do if i == Key then table.remove(Tbl, i) break end end Properties.UpdateVariable(Property, Var, Tbl) end local Planes = {} local Face function TOOL:LeftClick(Trace) Plr = LocalPlayer() if not IsFirstTimePredicted() then return end if self.EditMode == "Select" then local TargetSelf = false local Closest, ClosestDist, ClosestPos, ClosestNormal for i, v in pairs(Properties.GetAll()) do local Pos = (v.Start + v.End) / 2 local MinS = Vector(math.min(Pos.x - v.Start.x, Pos.x - v.End.x), math.min(Pos.y - v.Start.y, Pos.y - v.End.y), math.min(Pos.z - v.Start.z, Pos.z - v.End.z)) local MaxS = Vector(math.max(Pos.x - v.Start.x, Pos.x - v.End.x), math.max(Pos.y - v.Start.y, Pos.y - v.End.y), math.max(Pos.z - v.Start.z, Pos.z - v.End.z)) local HitPos, HitNormal = util.IntersectRayWithOBB(Trace.StartPos, Trace.Normal * 10000, Pos, Angle(), MinS - Vector(2, 2, 2), MaxS + Vector(2, 2, 2)) if HitPos and (not Closest or (Trace.StartPos - HitPos):Length() < ClosestDist) then if self.SelectedProperty == i then TargetSelf = true else Closest, ClosestDist, ClosestPos, ClosestNormal = i, (Trace.StartPos - HitPos):Length(), HitPos, HitNormal end end end if Closest and not util.TraceLine({start = Trace.StartPos, endpos = ClosestPos, filter = Plr}).Hit then self.SelectedProperty = Closest Plr:GetActiveWeapon():DoShootEffect(ClosestPos, ClosestNormal, nil, 1, IsFirstTimePredicted()) elseif self.SelectedProperty and not TargetSelf then self.SelectedProperty = nil return true end elseif self.EditMode == "Add" then if Trace.Hit and not Trace.HitSky then Planes[#Planes + 1] = {Trace.HitPos, Trace.HitNormal} if #Planes ~= 6 then return true end local SX, SY, SZ = GetPlanesIntersection({Planes[1], Planes[2], Planes[3]}) local EX, EY, EZ = GetPlanesIntersection({Planes[4], Planes[5], Planes[6]}) if not SX or not SY or not SZ or not EX or not EY or not EZ then Notify("Box invalid", true) Planes = {} self.EditMode = "Select" return false end local Start, End = Vector(SX, SY, SZ), Vector(EX, EY, EZ) OrderVectors(Start, End) if Start:Distance(End) < 10 then Notify("Box too small", true) Planes = {} self.EditMode = "Select" return false end for _, v in pairs(Properties.GetAll()) do local NewStart, NewEnd = Vector(v.Start), Vector(v.End) OrderVectors(NewStart, NewEnd) if NewStart:Distance(Start) < 10 and NewEnd:Distance(End) < 10 then Notify("Box already exists", true) Planes = {} self.EditMode = "Select" return false end end local Property = Properties.Add(table.Copy(PropertyDataFormat)) Properties.UpdateVariable(Property, "Position", {Start, End}) self.SelectedProperty = Property Notify("Property created", false) Planes = {} self.EditMode = "Select" return true end elseif self.EditMode == "Door" then if Properties.ValidateDoors(self.SelectedProperty) then return end if Trace.Entity and Trace.Entity:isDoor() and not table.HasValue(Properties.GetVariable(self.SelectedProperty, "Doors", {}), Trace.Entity) then Properties.InsertTableVariable(self.SelectedProperty, "Doors", Trace.Entity) return true end elseif self.EditMode == "Camera" then Properties.InsertTableVariable(self.SelectedProperty, "Cameras", {Trace.StartPos, Trace.Normal:Angle()}) Plr:GetActiveWeapon():DoShootEffect(Trace.StartPos, Trace.Normal, nil, 1, IsFirstTimePredicted()) elseif self.EditMode == "Expand" then if Properties.Exists(self.SelectedProperty) then local v = Properties.Get(self.SelectedProperty) local Pos = (v.Start + v.End) / 2 local MinS = Vector(math.min(Pos.x - v.Start.x, Pos.x - v.End.x), math.min(Pos.y - v.Start.y, Pos.y - v.End.y), math.min(Pos.z - v.Start.z, Pos.z - v.End.z)) local MaxS = Vector(math.max(Pos.x - v.Start.x, Pos.x - v.End.x), math.max(Pos.y - v.Start.y, Pos.y - v.End.y), math.max(Pos.z - v.Start.z, Pos.z - v.End.z)) local HitPos, HitNormal = util.IntersectRayWithOBB(Trace.StartPos, Trace.Normal * 10000, Pos, Angle(), MinS, MaxS) local InBox = Trace.StartPos:WithinAABox(Pos + MinS - Vector(20, 20, 20), Pos + MaxS + Vector(20, 20, 20)) if HitPos and not InBox then Face = GetFaceFromNormal(HitNormal) Plr:GetActiveWeapon():DoShootEffect(HitPos, HitNormal, nil, 1, IsFirstTimePredicted()) return false end local Menu = DermaMenu() for i, _ in pairs(Normals) do Menu:AddOption(i, function() Face = i end) end Menu:AddOption("Close", function() end) Menu:Open() Menu:SetPos(gui.MousePos()) end elseif self.EditMode == "Node" then if Properties.Exists(self.SelectedProperty) then local v = Properties.Get(self.SelectedProperty) local NewStart, NewEnd = Vector(v.Start), Vector(v.End) OrderVectors(NewStart, NewEnd) local InBox = Trace.HitPos:WithinAABox(NewStart, NewEnd) if InBox then Properties.InsertTableVariable(self.SelectedProperty, "Nodes", {Trace.HitPos, Trace.HitNormal}) return true end end end return false end function TOOL:RightClick(Trace) if not IsFirstTimePredicted() then return end if self.EditMode == "Select" then local Menu = DermaMenu() for i, v in pairs(Properties.GetAll()) do Menu:AddOption(v.Name, function() self.SelectedProperty = i end) end Menu:AddOption("Close", function() end) Menu:Open() Menu:SetPos(gui.MousePos()) elseif self.EditMode == "Add" then self.EditMode = "Select" Planes = {} return true elseif self.EditMode == "Door" then if Properties.ValidateDoors(self.SelectedProperty) then return end if Trace.Entity and Trace.Entity:isDoor() and table.HasValue(Properties.GetVariable(self.SelectedProperty, "Doors", {}), Trace.Entity) then for i, v in pairs(Properties.GetVariable(self.SelectedProperty, "Doors")) do if v == Trace.Entity then Properties.UpdateTableVariable(self.SelectedProperty, "Doors", i, nil) end end return true end elseif self.EditMode == "Camera" then local Closest, ClosestDist, ClosestPos, ClosestNormal for _, v in pairs(Properties.GetAll()) do for i, x in pairs(v.Cameras) do local HitPos, HitNormal = util.IntersectRayWithOBB(Trace.StartPos, Trace.Normal * 10000, x[1], x[2], -Vector(15, 15, 15), Vector(15, 15, 15)) if HitPos and (not Closest or (Trace.StartPos - HitPos):Length() < ClosestDist) then Closest, ClosestDist, ClosestPos, ClosestNormal = i, (Trace.StartPos - HitPos):Length(), HitPos, HitNormal end end end if Closest and not util.TraceLine({start = Trace.StartPos, endpos = ClosestPos, filter = Plr}).Hit then Properties.RemoveTableVariable(self.SelectedProperty, "Cameras", Closest) Plr:GetActiveWeapon():DoShootEffect(ClosestPos, ClosestNormal, nil, 1, IsFirstTimePredicted()) end elseif self.EditMode == "Expand" then if Face and Properties.Exists(self.SelectedProperty) then local v = Properties.Get(self.SelectedProperty) local Pos = (v.Start + v.End) / 2 local NewStart, NewEnd = Vector(v.Start), Vector(v.End) local MaxS = Vector(math.max(Pos.x - v.Start.x, Pos.x - v.End.x), math.max(Pos.y - v.Start.y, Pos.y - v.End.y), math.max(Pos.z - v.Start.z, Pos.z - v.End.z)) local Normal = GetFaceNormals(Face) local Position = Pos + MaxS * Normal local Difference = Position * Normal - Trace.HitPos * Normal if Normal.x ~= 0 then if math.Round(NewStart.x) == math.Round(Position.x) then NewStart = NewStart - Difference * Normal.x else NewEnd = NewEnd - Difference * Normal.x end elseif Normal.y ~= 0 then if math.Round(NewStart.y) == math.Round(Position.y) then NewStart = NewStart - Difference * Normal.y else NewEnd = NewEnd - Difference * Normal.y end else if math.Round(NewStart.z) == math.Round(Position.z) then NewStart = NewStart - Difference * Normal.z else NewEnd = NewEnd - Difference * Normal.z end end Properties.UpdateVariable(self.SelectedProperty, "Position", {NewStart, NewEnd}) return true end elseif self.EditMode == "Node" then local Closest, ClosestDist, ClosestPos, ClosestNormal for _, v in pairs(Properties.GetAll()) do for i, x in pairs(v.Nodes) do local HitPos, HitNormal = util.IntersectRayWithOBB(Trace.StartPos, Trace.Normal * 10000, x[1], x[2]:Angle(), -Vector(15, 15, 15), Vector(15, 15, 15)) if HitPos and (not Closest or (Trace.StartPos - HitPos):Length() < ClosestDist) then Closest, ClosestDist, ClosestPos, ClosestNormal = i, (Trace.StartPos - HitPos):Length(), HitPos, HitNormal end end end if Closest and not util.TraceLine({start = Trace.StartPos, endpos = ClosestPos, filter = Plr}).Hit then for i, _ in pairs(Properties.GetVariable(self.SelectedProperty, "Nodes")) do if i == Closest then Properties.UpdateTableVariable(self.SelectedProperty, "Nodes", i, nil) end end Plr:GetActiveWeapon():DoShootEffect(ClosestPos, ClosestNormal, nil, 1, IsFirstTimePredicted()) end end return false end function TOOL:Reload() if not IsFirstTimePredicted() or not Properties.Exists(self.SelectedProperty) then return end local StartSelection = self.SelectedProperty local Frame = vgui.Create("DFrame") Frame:SetSize(500, 700) Frame:Center() Frame:SetTitle("Editing property " .. Properties.GetVariable(StartSelection, "Name")) Frame:SetDraggable(true) Frame:MakePopup() local function DoCheck() if not Properties.Exists(StartSelection) or StartSelection ~= self.SelectedProperty then Frame:Remove() end end local PropertyPanel = vgui.Create("DProperties", Frame) PropertyPanel:Dock(FILL) local Container = Properties.GetVariable(StartSelection, "Container") local Stage = "Data" for _, v in pairs(PropertyDataFormatView) do if Container and (v == "Price" or v == "Rent" or v == "Business" or v == "Warehouse") then continue end if v:upper() == v then Stage = v:lower():gsub("^%l", string.upper) continue end local Type = type(PropertyDataFormat[v]) local New = PropertyPanel:CreateRow(Stage, v) New:Setup(Type == "boolean" and "Boolean" or "Generic", {waitforenter = true}) if Type == "string" then local Text1 = New:GetChildren()[2]:GetChildren()[1]:GetChildren()[1] function Text1:OnLoseFocus() self:OnValueChange(self:GetText()) end elseif Type == "number" then local Text1 = New:GetChildren()[2]:GetChildren()[1]:GetChildren()[1] Text1:SetNumeric(true) Text1.CheckNumeric = CheckNumericCustom function Text1:OnValueChange(Val) if self:GetText() == "" then self:SetText(0) end self:GetParent():ValueChanged(Val) end function Text1:OnLoseFocus() self:OnValueChange(self:GetText()) end elseif Type == "Vector" then local Panel = New:GetChildren()[2]:GetChildren()[1] local Text1 = Panel:GetChildren()[1] Text1:SetNumeric(true) Text1:SetWide(255 / 3) Text1:Dock(LEFT) Text1.CheckNumeric = CheckNumericCustom local Text2 = Panel:Add("DTextEntry") Text2:SetNumeric(true) Text2:Dock(FILL) Text2:SetPaintBackground(false) Text2.CheckNumeric = CheckNumericCustom local Text3 = Panel:Add("DTextEntry") Text3:SetNumeric(true) Text3:SetWide(255 / 3) Text3:Dock(RIGHT) Text3:SetPaintBackground(false) Text3.CheckNumeric = CheckNumericCustom function New:SetValue(Val) Text1:SetValue(math.Round(Val.x)) Text2:SetValue(math.Round(Val.y)) Text3:SetValue(math.Round(Val.z)) end end New:SetValue(Properties.GetVariable(StartSelection, v)) if Type == "Vector" then local Panel = New:GetChildren()[2]:GetChildren()[1] local Text1 = Panel:GetChildren()[1] local Text2 = Panel:GetChildren()[2] local Text3 = Panel:GetChildren()[3] function Panel.IsEditing() return Text1:IsEditing() or Text2:IsEditing() or Text3:IsEditing() end function Panel:ValueChanged(x, y, z) if Text1:GetText() == "" then Text1:SetText(0) end if Text2:GetText() == "" then Text2:SetText(0) end if Text3:GetText() == "" then Text3:SetText(0) end self.m_pRow:DataChanged(Vector(x, y, z)) end function Text1.OnValueChange() Panel:ValueChanged(Text1:GetValue(), Text2:GetValue(), Text3:GetValue()) end function Text2.OnValueChange() Panel:ValueChanged(Text1:GetValue(), Text2:GetValue(), Text3:GetValue()) end function Text3.OnValueChange() Panel:ValueChanged(Text1:GetValue(), Text2:GetValue(), Text3:GetValue()) end function Text1:OnLoseFocus() self:OnValueChange(self:GetText()) end function Text2:OnLoseFocus() self:OnValueChange(self:GetText()) end function Text3:OnLoseFocus() self:OnValueChange(self:GetText()) end end New.DataChanged = function(_, Val) DoCheck() if Type == "number" then Val = tonumber(Val) elseif Type == "boolean" then Val = tobool(Val) end Properties.UpdateVariable(StartSelection, v, Val) if v == "Name" then Frame:SetTitle("Editing property " .. Val) end end end local RemoveButton = vgui.Create("DButton", Frame) RemoveButton:Dock(BOTTOM) RemoveButton:SetText("Remove") function RemoveButton:DoClick() DoCheck() Properties.Remove(StartSelection) Frame:Remove() end if Container then local MirrorOnParent = vgui.Create("DButton", Frame) MirrorOnParent:Dock(BOTTOM) MirrorOnParent:SetText("Mirror On Parent") function MirrorOnParent.DoClick() local ContainerProperty = Properties.Get(Container) if not ContainerProperty then return end local OldProperty = Properties.Get(StartSelection) if Properties.ValidateDoors(StartSelection) then return end local ContainerPos = (ContainerProperty.Start + ContainerProperty.End) / 2 local OldPos = (OldProperty.Start + OldProperty.End) / 2 local MirrorPos local Offset = ContainerPos - OldPos if math.abs(math.abs(Offset.x) - math.abs(Offset.y)) < math.abs(Offset.x + Offset.y) * 0.2 then MirrorPos = Vector(ContainerPos.x, ContainerPos.y, 0) elseif math.abs(Offset.x) >= math.abs(Offset.y) then MirrorPos = Vector(ContainerPos.x, 0, 0) else MirrorPos = Vector(0, ContainerPos.y, 0) end local MirrorOffset for i, v in pairs(OldProperty.Doors) do local NewPos = MirrorPosition(v:GetPos(), MirrorPos) local Ent = GetSimilarEnt(v, NewPos, 30) if Ent then MirrorOffset = MirrorOffset and ((MirrorOffset + Ent:GetPos() - NewPos) / 2) or Ent:GetPos() - NewPos end end local NewStart = MirrorPosition(OldProperty.Start, MirrorPos, MirrorOffset) local NewEnd = MirrorPosition(OldProperty.End, MirrorPos, MirrorOffset) for _, v in pairs(Properties.GetAll()) do if NewEnd == NewStart and v.End == NewEnd then return end end local Property = Properties.Add(table.Copy(PropertyDataFormat)) local NewName = {} for i, v in pairs(string.Explode(" ", OldProperty.Name)) do if tonumber(v) then NewName[i] = tonumber(v) + 1 else NewName[i] = v end end Properties.UpdateVariable(Property, "Name", table.concat(NewName, " ")) Properties.UpdateVariable(Property, "Position", {NewStart, NewEnd}) Properties.UpdateVariable(Property, "Price", OldProperty.Price) Properties.UpdateVariable(Property, "Business", OldProperty.Business) Properties.UpdateVariable(Property, "Warehouse", OldProperty.Warehouse) local NewCameras = {} for i, v in pairs(OldProperty.Cameras) do local NewPos = MirrorPosition(v[1], MirrorPos, MirrorOffset) local NewAng = Angle(v[2]) if MirrorPos.x ~= 0 and MirrorPos.y ~= 0 then NewAng:RotateAroundAxis(Vector(0, 0, 1), 180) elseif MirrorPos.x ~= 0 then NewAng:RotateAroundAxis(Vector(0, 0, 1), 180) NewAng.y = -NewAng.y else NewAng.y = -NewAng.y end NewCameras[i] = {NewPos, NewAng} end Properties.UpdateVariable(Property, "Cameras", NewCameras) local NewDoors = {} for i, v in pairs(OldProperty.Doors) do NewDoors[i] = GetSimilarEnt(v, MirrorPosition(v:GetPos(), MirrorPos, MirrorOffset), 10) end Properties.UpdateVariable(Property, "Doors", NewDoors) if self.SelectNewProperty then self.SelectedProperty = Property Planes = {} self.EditMode = "Select" Frame:Remove() end end local DuplicateUp = vgui.Create("DButton", Frame) DuplicateUp:Dock(BOTTOM) DuplicateUp:SetText("Duplicate 1 floor up") function DuplicateUp.DoClick() local OldProperty = Properties.Get(StartSelection) if Properties.ValidateDoors(StartSelection) then return end local UpHeight for i, v in pairs(OldProperty.Doors) do local NewPos = v:GetPos() + Vector(0, 0, 140) local Ent = GetSimilarEnt(v, NewPos, 30) if Ent then UpHeight = UpHeight and ((UpHeight + Ent:GetPos() - v:GetPos()) / 2) or Ent:GetPos() - v:GetPos() end end if not UpHeight then return end for _, v in pairs(Properties.GetAll()) do if v.Start == OldProperty.Start + UpHeight and v.End == OldProperty.End + UpHeight then return end end local Property = Properties.Add(table.Copy(PropertyDataFormat)) local NewName = {} for i, v in pairs(string.Explode(" ", OldProperty.Name)) do if tonumber(v) then NewName[i] = tonumber(v) + 2 else NewName[i] = v end end Properties.UpdateVariable(Property, "Name", table.concat(NewName, " ")) Properties.UpdateVariable(Property, "Position", {OldProperty.Start + UpHeight, OldProperty.End + UpHeight}) Properties.UpdateVariable(Property, "Price", OldProperty.Price) Properties.UpdateVariable(Property, "Business", OldProperty.Business) Properties.UpdateVariable(Property, "Warehouse", OldProperty.Warehouse) local NewCameras = {} for i, v in pairs(OldProperty.Cameras) do NewCameras[i] = {v[1] + UpHeight, v[2]} end Properties.UpdateVariable(Property, "Cameras", NewCameras) local NewDoors = {} for i, v in pairs(OldProperty.Doors) do NewDoors[i] = GetSimilarEnt(v, v:GetPos() + UpHeight, 10) end Properties.UpdateVariable(Property, "Doors", NewDoors) if self.SelectNewProperty then self.SelectedProperty = Property Planes = {} self.EditMode = "Select" Frame:Remove() end end self.SelectNewProperty = self.SelectNewProperty ~= nil and self.SelectNewProperty or true local CheckBox = vgui.Create("DCheckBoxLabel", Frame) CheckBox:Dock(BOTTOM) CheckBox:SetText("Select new") CheckBox:SetValue(self.SelectNewProperty) function CheckBox.OnChange(_, Val) self.SelectNewProperty = Val end end end TOOL.Initialized = false function TOOL:Think() if not self.Initialized then self.Initialized = true self.EditMode = self.EditMode or "Select" concommand.Add("propertydevsetmode", function(Ply, Cmd, Args) if #Args == 1 then if self.EditMode == "Add" then Planes = {} elseif self.EditMode == "Expand" then Face = nil end if Args[1]:lower() == "select" then self.EditMode = "Select" elseif Args[1]:lower() == "add" then self.EditMode = "Add" elseif Args[1]:lower() == "door" then self.EditMode = "Door" elseif Args[1]:lower() == "camera" then self.EditMode = "Camera" elseif Args[1]:lower() == "expand" then self.EditMode = "Expand" elseif Args[1]:lower() == "node" then self.EditMode = "Node" end end end) end end function TOOL:DrawHUD() if self.EditMode == "Add" then draw.SimpleTextOutlined("Press left mouse to set position " .. (#Planes < 3 and 1 or 2) .. " plane " .. (#Planes % 3 + 1), "DermaLarge", ScrW() / 2, ScrH() * 0.7, Color(90, 200, 90, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, Color(0, 0, 0, 255)) draw.SimpleTextOutlined("Right click to cancel", "DermaLarge", ScrW() / 2, ScrH() * 0.7 + 50, Color(90, 200, 90, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, Color(0, 0, 0, 255)) end end function TOOL:DrawToolScreen(w, h) surface.SetDrawColor(Color(20, 20, 20, 255)) surface.DrawRect(0, 0, w, h) draw.SimpleText("Property Dev", "DermaLarge", w / 2, h * 0.3, Color(200, 200, 200, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) draw.SimpleText("Mode: " .. self.EditMode, "DermaLarge", w / 2, h * 0.45, Color(200, 200, 200, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) draw.SimpleText("Selection:", "DermaLarge", w / 2, h * 0.6, Color(200, 200, 200, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) draw.SimpleText(self.SelectedProperty and Properties.GetVariable(self.SelectedProperty, "Name") or "None", "DermaLarge", w / 2, h * 0.7, Color(200, 200, 200, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) end local CameraModels = {} local CameraKey = 1 local function GetCameraModel(i) if not CameraModels[i] then CameraModels[i] = ClientsideModel("models/dav0r/camera.mdl", RENDERGROUP_OPAQUE) CameraModels[i]:SetModelScale(2) end return CameraModels[i] end --local function LerpN(a, b, t) -- return a * (1 - t) + b * t --end local function BoundTrace(Start, Direction) local tr = {} tr.start = Start - Direction tr.endpos = Start + Direction * 1000 tr.mask = 1 + 2 local Trace = util.TraceLine(tr) if Trace.Hit and Trace.MatType ~= MAT_WOOD then return math.Round(Trace.HitPos.x), math.Round(Trace.HitPos.y) end end local function RemoveNearNodes(Nodes, N) for i, v in pairs(Nodes) do if math.abs(v[1] - N[1]) < 20 and math.abs(v[2] - N[2]) < 20 then table.remove(Nodes, i) end end end local function GetBoundsArea(Nodes) local Area = 0 local j = #Nodes for i, v in pairs(Nodes) do Area = Area + (Nodes[j][1] + v[1]) * (Nodes[j][2] - v[2]) j = i end return Area / 2 end local BoundsCache = {} local function GetBounds(Index) if BoundsCache[Index] then return BoundsCache[Index][1], BoundsCache[Index][2] end local Quality = 3 local Prop = Properties.Get(Index) local Start, End = Vector(Prop.Start), Vector(Prop.End) OrderVectors(Start, End) local Height = End.z - 2 local NodesA, NodesB, NodesC, NodesD = {}, {}, {}, {} local lx, ly for i = Start.y, End.y, Quality do local x, y = BoundTrace(Vector(Start.x, i, Height), Vector(1, 0, 0)) --print(x and lx ~= x, not ly or y - ly > 15, ly and y - ly) --if x and lx ~= x and (not ly or y - ly > 15) then -- if lx and y - ly > 20 then if x and lx ~= x then if lx then NodesA[#NodesA + 1] = {lx, y} end if ly and y - ly > 500 then break end NodesA[#NodesA + 1] = {x, y} lx, ly = x, y end end local l = lx lx, ly = nil, nil for i = l, End.x, Quality do local x, y = BoundTrace(Vector(i, End.y, Height), Vector(0, -1, 0)) if y and ly ~= y then if ly then RemoveNearNodes(NodesA, {x, ly}) NodesB[#NodesB + 1] = {x, ly} end NodesB[#NodesB + 1] = {x, y} lx, ly = x, y end end l = ly lx, ly = nil, nil if l then for i = l, Start.y, -Quality do local x, y = BoundTrace(Vector(End.x, i, Height), Vector(-1, 0, 0)) if x and lx ~= x then if lx then RemoveNearNodes(NodesB, {lx, y}) NodesC[#NodesC + 1] = {lx, y} end NodesC[#NodesC + 1] = {x, y} lx, ly = x, y end end end l = lx lx, ly = nil, nil if l then for i = l, Start.x, -Quality do local x, y = BoundTrace(Vector(i, Start.y, Height), Vector(0, 1, 0)) if y and ly ~= y then if ly then RemoveNearNodes(NodesA, {x, ly}) RemoveNearNodes(NodesC, {x, ly}) NodesD[#NodesD + 1] = {x, ly} end RemoveNearNodes(NodesA, {x, y}) NodesD[#NodesD + 1] = {x, y} lx, ly = x, y end end end local Nodes = NodesA for _, v in pairs(NodesB) do Nodes[#Nodes + 1] = v end for _, v in pairs(NodesC) do Nodes[#Nodes + 1] = v end for _, v in pairs(NodesD) do Nodes[#Nodes + 1] = v end local NewNodes = Nodes NewNodes[#NewNodes + 1] = NewNodes[1] BoundsCache[Index] = {Nodes, Height} return BoundsCache[Index][1], BoundsCache[Index][2] end function Properties.GetSquareFootage(Index) if not Properties.Exists(Index) then return end local Prop = Properties.Get(Index) return ((Prop.Business or Prop.Container) and math.Round(math.abs(Prop.Start.x - Prop.End.x)) * math.Round(math.abs(Prop.Start.y - Prop.End.y)) or GetBoundsArea(GetBounds(Index))) / 256 * 0.8 end local WhiteMaterial = CreateMaterial("WhiteMaterial", "UnlitGeneric", { ["$basetexture"] = "models/debug/debugwhite", ["$ignorez"] = 1 }) hook.Add("PostDrawTranslucentRenderables", "PropertyDevDrawWorld", function() if not Plr.GetActiveWeapon or not Plr:GetActiveWeapon() or Plr:GetActiveWeapon().PrintName ~= "Tool Gun" or Plr:GetActiveWeapon():GetMode() ~= "propertydev" then return end local Tool = Plr:GetTool("propertydev") if Tool.EditMode == "Add" then local tr = util.GetPlayerTrace(Plr) tr.mask = bit.bor(CONTENTS_SOLID, CONTENTS_MOVEABLE, CONTENTS_MONSTER, CONTENTS_WINDOW, CONTENTS_DEBRIS, CONTENTS_GRATE, CONTENTS_AUX) local Trace = util.TraceLine(tr) local EPlanes = table.Copy(Planes) EPlanes[#EPlanes + 1] = {Trace.HitPos, Trace.HitNormal} for _, v in pairs(EPlanes) do local Text local Normal = Vector(math.Round(math.abs(v[2].x)), math.Round(math.abs(v[2].y)), math.Round(math.abs(v[2].z))) if Normal == Vector(1, 0, 0) then Text = "X" elseif Normal == Vector(0, 1, 0) then Text = "Y" elseif Normal == Vector(0, 0, 1) then Text = "Z" end if Text then local Col = Text == "X" and Color(255, 0, 0, 255) or Text == "Y" and Color(0, 255, 0, 255) or Color(0, 0, 255, 255) render.SetColorMaterial() render.DrawQuadEasy(v[1] + v[2] * 0.2, v[2], 30, 30, Color(Col.r * 0.8, Col.g * 0.8, Col.b * 0.8, 150), 0) local Ang = v[2]:Angle() Ang:RotateAroundAxis(Ang:Forward(), 90) Ang:RotateAroundAxis(Ang:Right(), -90) cam.Start3D2D(v[1] + v[2] * 0.2, Ang, 1) draw.SimpleTextOutlined(Text, "DermaLarge", 0, 0, Col, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, Color(0, 0, 0, 150)) cam.End3D2D() end end for i = 1, 2 do local NewPlanes = (i == 2 and #EPlanes > 3 and {EPlanes[4], EPlanes[5], EPlanes[6]}) or (i == 1 and {EPlanes[1], EPlanes[2], EPlanes[3]}) if not NewPlanes then continue end local AX, AY, AZ for _, v in pairs(NewPlanes) do if not AX then AX, AY, AZ = v[1].x, v[1].y, v[1].z else AX, AY, AZ = (AX + v[1].x) / 2, (AY + v[1].y) / 2, (AZ + v[1].z) / 2 end end local LineLength = 1000 local X, Y, Z = GetPlanesIntersection(NewPlanes) render.SetColorMaterial() cam.IgnoreZ(true) if Y and Z then render.DrawBeam(Vector(AX - LineLength, Y, Z), Vector(AX + LineLength, Y, Z), 2, 0, 0, Color(255, 0, 0, 255)) end if X and Z then render.DrawBeam(Vector(X, AY - LineLength, Z), Vector(X, AY + LineLength, Z), 2, 0, 0, Color(0, 255, 0, 255)) end if X and Y then render.DrawBeam(Vector(X, Y, AZ - LineLength), Vector(X, Y, AZ + LineLength), 2, 0, 0, Color(0, 0, 255, 255)) end cam.IgnoreZ(false) end end for i, v in pairs(Properties.GetAll()) do local SelfSelected = Tool.SelectedProperty == i local Pos = (v.Start + v.End) / 2 if LocalPlayer():EyePos():Distance(Pos) > 6000 then continue end local MinS = Vector(math.min(Pos.x - v.Start.x, Pos.x - v.End.x), math.min(Pos.y - v.Start.y, Pos.y - v.End.y), math.min(Pos.z - v.Start.z, Pos.z - v.End.z)) local MaxS = Vector(math.max(Pos.x - v.Start.x, Pos.x - v.End.x), math.max(Pos.y - v.Start.y, Pos.y - v.End.y), math.max(Pos.z - v.Start.z, Pos.z - v.End.z)) render.SetColorMaterial() render.DrawWireframeBox(Pos, Angle(), MinS, MaxS, SelfSelected and Color(0, 150, 0, 150) or Color(255, 0, 0, 150), not SelfSelected) render.DrawBox(Pos, Angle(), MinS - Vector(0.5, 0.5, 0.5), MaxS + Vector(0.5, 0.5, 0.5), SelfSelected and Color(0, 150, 0, 100) or Color(255, 0, 0, 40), false) render.DrawBox(Pos, Angle(), MaxS - Vector(0.5, 0.5, 0.5), MinS + Vector(0.5, 0.5, 0.5), SelfSelected and Color(0, 150, 0, 60) or Color(255, 0, 0, 20), false) if not SelfSelected then continue end if not v.Business and not v.Container then local Bounds, Height = GetBounds(i) local LastBound cam.IgnoreZ(true) for f, g in pairs(Bounds) do local e = (f / #Bounds) * 255 if LastBound then render.SetColorMaterial() render.DrawBeam(Vector(LastBound[1], LastBound[2], Height), Vector(g[1], g[2], Height), 2, 0, 0, Color(e, e, e, 255), false) end render.DrawSphere(Vector(g[1], g[2], Height), 1, 20, 20, Color(e, e, e, 255)) render.DrawSphere(Vector(g[1], g[2], Height), 5, 20, 20, Color(e, e, e, 150)) LastBound = g end render.DrawBeam(Vector(Bounds[1][1], Bounds[1][2], Height), Vector(Bounds[#Bounds][1], Bounds[#Bounds][2], Height), 2, 0, 0, Color(0, 0, 0, 255), false) cam.IgnoreZ(false) end if Face then local Normal = GetFaceNormals(Face) local Position = Pos + MaxS * Normal local Size = GetFaceSize(Face, MaxS * 2) render.DrawQuadEasy(Position, Normal, Size[1], Size[2], Color(0, 0, 255, 150), 0) render.DrawQuadEasy(Position, -Normal, Size[1], Size[2], Color(0, 0, 255, 100), 0) end if #v.Nodes > 0 then render.SetColorMaterial() for _, x in pairs(v.Nodes) do render.DrawQuadEasy(x[1], x[2], 30, 30, Color(255, 255, 255, 255), 0) render.DrawQuadEasy(x[1], -x[2], 30, 30, Color(80, 80, 80, 255), 0) end end if #v.Doors > 0 then render.MaterialOverride(WhiteMaterial) render.SetBlend(0.3) Properties.ValidateDoors(i) for _, x in pairs(v.Doors) do if type(x) == "number" or not IsValid(x) then continue end local NewStart, NewEnd = Vector(v.Start), Vector(v.End) OrderVectors(NewStart, NewEnd) local InBox = x:GetPos():WithinAABox(NewStart - Vector(100, 100, 100), NewEnd + Vector(100, 100, 100)) render.SetColorModulation(InBox and 0 or 1, 1, 0) cam.Start3D() x:DrawModel() cam.End3D() if not InBox then render.DrawBeam(Pos + (Pos - x:GetPos()):GetNormal() * -math.min(v.Start:Distance(v.End), v.Start:Distance(x:GetPos())) * 0.3, x:GetPos(), 10, 0, 0, Color(255, 255, 0, 255)) end end render.SetColorModulation(1, 1, 1) render.SetBlend(1) render.MaterialOverride() end if #v.Cameras > 0 then CameraKey = 1 render.SetBlend(0.3) render.MaterialOverride(WhiteMaterial) for _, x in pairs(v.Cameras) do local NewStart, NewEnd = Vector(v.Start), Vector(v.End) OrderVectors(NewStart, NewEnd) local InBox = x[1]:WithinAABox(NewStart - Vector(20, 20, 20), NewEnd + Vector(20, 20, 20)) render.SetColorModulation(InBox and 0 or 1 or 1, 1, 0) render.Model({model = "models/dav0r/camera.mdl", pos = x[1], angle = x[2]}, GetCameraModel(CameraKey)) if not InBox then render.DrawBeam(Pos + (Pos - x[1]):GetNormal() * -math.min(v.Start:Distance(v.End), v.Start:Distance(x[1])) * 0.3, x[1], 10, 0, 0, Color(255, 255, 0, 255)) end CameraKey = CameraKey + 1 end render.SetColorModulation(1, 1, 1) render.SetBlend(1) render.MaterialOverride() end end cam.IgnoreZ(true) for i, v in pairs(Properties.GetAll()) do local SelfSelected = Tool.SelectedProperty == i local Pos = (v.Start + v.End) / 2 if LocalPlayer():EyePos():Distance(Pos) > 2000 then continue end local Ang = (LocalPlayer():EyePos() - Pos):Angle() Ang:RotateAroundAxis(Ang:Forward(), 90) Ang:RotateAroundAxis(Ang:Right(), 90) if (LocalPlayer():EyePos() - Pos):Dot(Ang:Up()) < 0 then Ang:RotateAroundAxis(Ang:Right(), 180) end surface.SetFont("DermaLarge") cam.Start3D2D(Pos, Ang, v.Container and 0.4 or 0.7) local _, Height = surface.GetTextSize("Text") local Text = { v.Name, v.Container and Properties.GetVariable(v.Container, "Name", "nil") or (v.Price > 0 or v.Rent > 0) and (v.Price > 0 and "Price: " .. DarkRP.formatMoney(v.Price) .. (v.Rent > 0 and " " or "") or "") .. (v.Rent > 0 and "Rent: " .. DarkRP.formatMoney(v.Rent) or "") or "Unownable", Properties.IsContainer(i) and "Apartment Building" or v.Container and "Apartment" or (v.Price > 0 or v.Rent > 0) and (v.Warehouse and "Warehouse" or v.Business and "Business" or "House") or nil } local Col = SelfSelected and Color(0, 255, 0, 255) or Color(255, 0, 0, 255) surface.SetTextColor(Color(0, 0, 0, 255)) for x, y in pairs(Text) do EfficientText(y, -1, -1 + (x - 1) * Height - ((#Text - 1) * Height) / 2, true) EfficientText(y, 1, 1 + (x - 1) * Height - ((#Text - 1) * Height) / 2, true) EfficientText(y, -1, 1 + (x - 1) * Height - ((#Text - 1) * Height) / 2, true) EfficientText(y, 1, -1 + (x - 1) * Height - ((#Text - 1) * Height) / 2, true) end surface.SetTextColor(Col) for x, y in pairs(Text) do EfficientText(y, 0, (x - 1) * Height - ((#Text - 1) * Height) / 2, true) end cam.End3D2D() end cam.IgnoreZ(false) end) language.Add("tool.propertydev.name", "Property Dev") language.Add("tool.propertydev.desc", "Add, edit and remove properties") language.Add("tool.propertydev.left", "Run mode") language.Add("tool.propertydev.right", "Run mode secondary") language.Add("tool.propertydev.reload", "Edit properties of selection") end function TOOL.BuildCPanel(Panel) Panel:AddControl("Button", { Label = "Mode: Selection", Command = "propertydevsetmode select" }) Panel:AddControl("Button", { Label = "Mode: Add", Command = "propertydevsetmode add" }) Panel:AddControl("Button", { Label = "Mode: Door", Command = "propertydevsetmode door" }) Panel:AddControl("Button", { Label = "Mode: Camera", Command = "propertydevsetmode camera" }) Panel:AddControl("Button", { Label = "Mode: Expand", Command = "propertydevsetmode expand" }) Panel:AddControl("Button", { Label = "Mode: Node", Command = "propertydevsetmode node" }) end <file_sep>DynNPC:RegisterNPC("Police Commissioner", { Model = "Police", Animation = "ArmsSide", Jobs = {{"Enlist in the police", TEAM_POLICE}, {"Become a SWAT", TEAM_SWAT}} }) DynNPC:RegisterNPC("Hospital Director", { Model = "Paramedic", Animation = "ArmsCrossed", Options = { { Name = "Get healed $100", Select = function(Plr) if Plr:canAfford(100) then Plr:addMoney(-100) Plr:SetHealth(Plr:GetMaxHealth()) end end, Requirement = function(Plr) for _, v in pairs(player.GetAll()) do if v:Team() == TEAM_PARAMEDIC then return false end end return Plr:canAfford(100) and Plr:Health() <= Plr:GetMaxHealth() * 0.9 end } }, Jobs = {{"Become a paramedic", TEAM_PARAMEDIC}} }) <file_sep>ENT.Type = "anim" ENT.Base = "base_anim" ENT.PrintName = "DynNPC" ENT.Author = "CodeNil" ENT.Spawnable = false ENT.AdminSpawnable = false<file_sep>local MinZoom, MaxZoom = 500, 4000 local RenderingMap = false GreyRP = GreyRP or {} --GreyRP.PanelData = GreyRP.PanelData or {} GreyRP.MapWaypoints = {} timer.Create("MapWaypointUpdate", 1, 0, function() GreyRP.MapWaypoints = {} hook.Run("GetMapWaypoints") end) MapIconMaterials = MapIconMaterials or {} MapFonts = {} local function GetFont(Size, Weight) Size = math.Round(Size) if not MapFonts[Size] then MapFonts[Size] = true surface.CreateFont("MapFont" .. Size, { font = "Trebuchet", size = Size, weight = Weight }) end return "MapFont" .. Size end function GreyRP:SetupMapPanel(sx, sy, sz, Id) self:SetMouseInputEnabled(true) self:SetKeyboardInputEnabled(true) self.LastUpdate = 0 --[[if Id then if GreyRP.PanelData[Id] then Id = GreyRP.PanelData[Id] self.TransX, self.TransY = Id.x, Id.y self.Zoom = Id.z else GreyRP.PanelData[Id] = {} Id = GreyRP.PanelData[Id] self.TransX, self.TransY = sx, sy self.Zoom = sz end else self.TransX, self.TransY = sx, sy self.Zoom = sz end]] self.TransX, self.TransY = sx, sy self.Zoom = sz function self:GetVector() return Vector(self.TransY, self.TransX, 2700) end function self:SetTrans(x, y) self.TransX = x self.TransY = y --if Id then -- Id.x, Id.y = self.TransX, self.TransY --end end function self:ChangeTrans(x, y) if x then self.TransX = self.TransX + x --if Id then -- Id.x = self.TransX --end end if y then self.TransY = self.TransY + y --if Id then -- Id.y = self.TransY --end end end function self:Paint(w, h) if RealTime() - self.LastUpdate > 0.5 and self.LastUpdateVec ~= self:GetVector() then net.Start("MapPositionData") net.WriteVector(self:GetVector()) net.SendToServer() self.LastUpdate = RealTime() self.LastUpdateVec = self:GetVector() end if not self.Dragging then if input.IsKeyDown(KEY_W) or input.IsKeyDown(KEY_UP) then self:ChangeTrans(nil, 20) end if input.IsKeyDown(KEY_S) or input.IsKeyDown(KEY_DOWN) then self:ChangeTrans(nil, -20) end if input.IsKeyDown(KEY_A) or input.IsKeyDown(KEY_LEFT) then self:ChangeTrans(20) end if input.IsKeyDown(KEY_D) or input.IsKeyDown(KEY_RIGHT) then self:ChangeTrans(-20) end end local x, y = self:LocalToScreen() local OldW, OldH = ScrW(), ScrH() render.SetViewPort(x, y, w, h) render.Clear(0, 0, 0, 0) cam.Start2D() RenderingMap = true local PlrDraws = {} for _, v in pairs(player.GetAll()) do if not v:GetNoDraw() then PlrDraws[#PlrDraws + 1] = v v:SetNoDraw(true) end end local OrthoAmount = self.Zoom render.RenderView({ origin = self:GetVector(), angles = Angle(90, 0, 0), x = x, y = y, w = w, h = h, ortho = true, ortholeft = -OrthoAmount / 1000 * w, orthoright = OrthoAmount / 1000 * w, orthotop = -OrthoAmount / 1000 * h, orthobottom = OrthoAmount / 1000 * h, drawviewmodel = false }) for _, v in pairs(PlrDraws) do v:SetNoDraw(false) end RenderingMap = false cam.End2D() render.SetViewPort(0, 0, OldW, OldH) for _, v in pairs(GreyRP.MapWaypoints) do local tx, ty = w / 2 + (self.TransX - v[2].y) / self.Zoom * 500, h / 2 + (self.TransY - v[2].x) / self.Zoom * 500 local yx, yy = w / 2 + (self.TransX - v[3].y) / self.Zoom * 500, h / 2 + (self.TransY - v[3].x) / self.Zoom * 500 if not MapIconMaterials[v[4]] then MapIconMaterials[v[4]] = Material("icon16/" .. v[4] .. ".png") end if gui.MouseX() < x + tx and gui.MouseX() > x + yx and gui.MouseY() < y + ty and gui.MouseY() > y + yy then surface.SetDrawColor(v[5].r, v[5].g, v[5].b, 200) surface.DrawRect(yx, yy, tx - yx, ty - yy) local Gap = 150 / self.Zoom * 500 for e, g in pairs(v[6]) do draw.SimpleText(g[1], GetFont(g[2] / self.Zoom * 500, 1000), tx - (tx - yx) / 2, ty - (ty - yy) / 2 + Gap * (e - (#v[6] + 1) / 2), Color(0, 0, 0, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) end else surface.SetDrawColor(v[5].r, v[5].g, v[5].b, 100) surface.DrawRect(yx, yy, tx - yx, ty - yy) surface.SetDrawColor(Color(255, 255, 255, 255)) surface.SetMaterial(MapIconMaterials[v[4]]) surface.DrawTexturedRectRotated((tx + yx) / 2, (ty + yy) / 2, 300 / self.Zoom * 500, 300 / self.Zoom * 500, 0) end end if not MapIconMaterials["arrow_up"] then MapIconMaterials["arrow_up"] = Material("icon16/arrow_up.png") end local PlrPos = LocalPlayer():EyePos() local tx, ty = w / 2 + (self.TransX - PlrPos.y) / self.Zoom * 500, h / 2 + (self.TransY - PlrPos.x) / self.Zoom * 500 surface.SetDrawColor(255, 0, 0, 255) surface.SetMaterial(MapIconMaterials["arrow_up"]) surface.DrawTexturedRectRotated(tx, ty, 50, 50, LocalPlayer():EyeAngles().y) draw.DrawText("TransX: " .. self.TransX .. " TransY: " .. self.TransY .. " Zoom: " .. self.Zoom, "DermaDefault", 50, 50, Color(255, 255, 255, 255), TEXT_ALIGN_LEFT) end function self:OnMouseWheeled(Delta) self.Zoom = math.Clamp(self.Zoom - Delta * 50, MinZoom, MaxZoom) --if Id then -- Id.z = self.Zoom --end end function self:OnCursorMoved(x, y) if self.Dragging then if self.LastMX and self.LastMY then local Amount = self.Zoom / 500 self:SetTrans(self.TransX + (x - self.LastMX) * Amount, self.TransY + (y - self.LastMY) * Amount) end self.LastMX = x self.LastMY = y end end function self:OnMousePressed(Code) if Code == MOUSE_LEFT or Code == MOUSE_MIDDLE then self.Dragging = true self:SetCursor("hand") end end function self:OnMouseReleased(Code) if Code == MOUSE_LEFT or Code == MOUSE_MIDDLE then self.Dragging = false self:SetCursor("none") self.LastMX = nil self.LastMY = nil end end function self:OnCursorExited() if self.Dragging then self.Dragging = false self:SetCursor("none") self.LastMX = nil self.LastMY = nil end end end hook.Add("PreDrawSkyBox", "MapRender", function() if RenderingMap then return true end end) hook.Add("ShouldDrawLocalPlayer", "MapRender", function() if RenderingMap then return true end end) local Menu local function OpenMenu(x, y, z) if Menu and IsValid(Menu) then Menu:Remove() end Menu = vgui.Create("DFrame") Menu:SetSize(1000, 1000) Menu:Center() Menu:SetTitle("Map") Menu:ShowCloseButton(true) Menu:SetDraggable(true) Menu:SetSizable(true) Menu:MakePopup() Menu.lblTitle:SetFont("DYNNPC_FONT_LARGE") Menu.btnMaxim:SetVisible(false) Menu.btnMinim:SetVisible(false) Menu.btnClose:SetZPos(100) function Menu.btnClose:Paint(w, h) draw.RoundedBoxEx(8, 0, 2, w, 16, Color(220, 80, 80), false, true, true, false) end function Menu:Paint(w, h) draw.RoundedBoxEx(8, 0, 0, w, 24, Color(32, 178, 170, 255), false, true, false, false) draw.RoundedBoxEx(8, 0, 24, w, h - 24, Color(245, 245, 245, 255), false, false, true, false) end local Panel = vgui.Create("Panel", Menu) Panel:Dock(FILL) GreyRP.SetupMapPanel(Panel, y or EyePos().y, x or EyePos().x, z or (MinZoom + MaxZoom) / 2, "map_menu") end concommand.Add("greymap_open", function(Plr, Cmd, Args) OpenMenu(unpack(Args)) end) --[[ local PANEL = {} PANEL.Items = {} AccessorFunc(PANEL, "m_Zoom", "Zoom") AccessorFunc(PANEL, "m_TransX", "TransX") AccessorFunc(PANEL, "m_TransY", "TransY") function PANEL:Init() self:SetMouseInputEnabled(true) self:SetKeyboardInputEnabled(true) self.m_Zoom = 1 self.m_TransX = 0 self.m_TransY = 0 self:NoClipping(false) end function PANEL:UpdateItems() for i, v in pairs(self.Items) do if IsValid(v) then v:SetPos(v.TruePos[1] - v.TrueSize[1] * (self:GetZoom() - 1)/2 + self:GetTransX(), v.TruePos[2] - v.TrueSize[2] * (self:GetZoom() - 1)/2 + self:GetTransY()) v:SetSize(v.TrueSize[1] * self:GetZoom(), v.TrueSize[2] * self:GetZoom()) if v.TrueBorderWeight and v.TrueBorderWeight > 0 and not v:GetPage() then v.m_BorderWeight = v.TrueBorderWeight * self:GetZoom() end else self.Items[i] = nil end end end function PANEL:SetZoom(Zoom) self.m_Zoom = Zoom self:UpdateItems() end function PANEL:SetTransX(New) self.m_TransX = New self:UpdateItems() end function PANEL:SetTransY(New) self.m_TransY = New self:UpdateItems() end function PANEL:SetTrans(x, y) self.m_TransX = x self.m_TransY = y self:UpdateItems() end function PANEL:OnMouseWheeled(Delta) if input.IsControlDown() then self:SetZoom(math.Clamp(self:GetZoom() + Delta/4, MinZoom, MaxZoom)) else self:SetTransY(self:GetTransY() + Delta * 20) end end function PANEL:OnCursorMoved(x, y) if self.MiddleDown then if self.LastMX and self.LastMY then self:SetTrans(self:GetTransX() + x - self.LastMX, self:GetTransY() + y - self.LastMY) end self.LastMX = x self.LastMY = y end end function PANEL:OnMousePressed(Code) if Code == MOUSE_MIDDLE then self.MiddleDown = true self:SetCursor("hand") end end function PANEL:OnMouseReleased(Code) if Code == MOUSE_MIDDLE then self.MiddleDown = false self:SetCursor("none") self.LastMX = nil self.LastMY = nil end end function PANEL:OnCursorExited() if self.MiddleDown then self.MiddleDown = false self:SetCursor("none") self.LastMX = nil self.LastMY = nil end end function PANEL:AddItem(Item) self.Items[Item:GetZPos()] = Item Item.TruePos = {Item:GetPos()} Item.TrueSize = {Item:GetSize()} Item.TrueBorderWeight = Item.TrueBorderWeight or Item.m_BorderWeight or 0 function Item.Update() self:UpdateItems() end self:UpdateItems() end function PANEL:Paint(w, h) for i, v in SortedPairs(self.Items) do if IsValid(v) then local x, y = v:GetPos() local w, h = v:GetSize() v:Paint(x, y, w, h) if v:GetZPos() ~= i then self.Items[v:GetZPos()] = v self.Items[i] = nil end else self.Items[i] = nil end end end]] <file_sep>surface.CreateFont("DYNNPC_FONT_LARGE", { font = "Roboto", size = 18, weight = 200, antialias = true }) surface.CreateFont("DYNNPC_FONT_MEDIUM", { font = "Roboto", size = 16, weight = 200, antialias = true }) local Scale = 1.5 local Menu net.Receive("DynNPCMenu", function() if Menu and IsValid(Menu) then Menu:Remove() end local Name, Ent, Tbl = net.ReadString(), net.ReadEntity(), net.ReadTable() Tbl[#Tbl + 1] = "Cancel" local Height = 36 * #Tbl * Scale + 40 Menu = vgui.Create("DFrame") Menu:SetSize(400 * Scale, Height) Menu:SetTitle(Name) Menu:SetPos(0, ScrH() * 0.6 - Height / 2) Menu:CenterHorizontal() Menu:ShowCloseButton(false) Menu:SetDraggable(false) Menu:MakePopup() Menu.lblTitle:SetFont("DYNNPC_FONT_LARGE") function Menu:Paint(w, h) draw.RoundedBoxEx(8, 0, 0, w, 24, Color(32, 178, 170, 255), false, true, false, false) draw.RoundedBoxEx(8, 0, 24, w, h - 24, Color(245, 245, 245, 255), false, false, true, false) end for i, v in pairs(Tbl) do local New = vgui.Create("DButton", Menu) New:Dock(TOP) New:DockMargin(6 * Scale, 6 * Scale, 6 * Scale, i == #Tbl and 6 * Scale or 0) New:SetTall(30 * Scale) New:SetFont("DYNNPC_FONT_MEDIUM") New:SetTextColor(Color(80, 80, 80, 255)) New:SetText(v) function New:Paint(w, h) draw.RoundedBoxEx(8, 0, 0, w, h, Color(120, 120, 120, 255), false, i == 1, i == #Tbl, false) draw.RoundedBoxEx(8, 1, 1, w - 2, h - 2, Color(225, 225, 225, 255), false, i == 1, i == #Tbl, false) end function New:DoClick() net.Start("DynNPCMenu") net.WriteString(Name) net.WriteEntity(Ent) net.WriteString(v) net.SendToServer() Menu:Close() end end end) <file_sep>if not file.IsDir("greyrp", "DATA") then file.CreateDir("greyrp", "DATA") end if not file.IsDir("greyrp/" .. game.GetMap():lower(), "DATA") then file.CreateDir("greyrp/" .. game.GetMap():lower(), "DATA") end if not file.IsDir("greyrp/" .. game.GetMap():lower() .. "/backups", "DATA") then file.CreateDir("greyrp/" .. game.GetMap():lower() .. "/backups", "DATA") end GreyRP = {} function GreyRP.ConvertFromOld(Name) if file.Exists("codenil/dynnpc/" .. game.GetMap():lower() .. "/" .. Name .. ".txt", "DATA") then local Text = file.Read("codenil/dynnpc/" .. game.GetMap():lower() .. "/" .. Name .. ".txt", "DATA") file.Write("greyrp/" .. game.GetMap():lower() .. "/" .. Name .. ".txt", von.serialize(util.JSONToTable(Text)), "DATA") file.Delete("codenil/dynnpc/" .. game.GetMap():lower() .. "/" .. Name .. ".txt") end end function GreyRP.GetData(Name) --GreyRP.ConvertFromOld(Name) if file.Exists("greyrp/" .. game.GetMap():lower() .. "/" .. Name .. ".txt", "DATA") then local Text = file.Read("greyrp/" .. game.GetMap():lower() .. "/" .. Name .. ".txt", "DATA") local Tbl = von.deserialize(Text) if Name == "property" then for i, v in pairs(Tbl) do local NewDoors = {} for _, x in pairs(v.Doors) do NewDoors[#NewDoors + 1] = ents.GetMapCreatedEntity(x) end v.Doors = NewDoors end end return Tbl end return {} end local function RoundVector(Vec) return Vector(math.Round(Vec.x), math.Round(Vec.y), math.Round(Vec.z)) end local function RoundAngle(Ang) return Angle(math.Round(Ang.p), math.Round(Ang.y), math.Round(Ang.r)) end local function LoopRound(v) for i, x in pairs(v) do if type(x) == "Vector" then v[i] = RoundVector(x) elseif type(x) == "Angle" then v[i] = RoundAngle(x) elseif type(x) == "table" then LoopRound(x) end end end function GreyRP.SetData(Name, Data) local Tbl = table.Copy(Data) if Name == "property" then for _, v in pairs(Tbl) do LoopRound(v) local NewDoors = {} for _, x in pairs(v.Doors) do if IsValid(x) then NewDoors[#NewDoors + 1] = x:MapCreationID() end end v.Doors = NewDoors end end local SData = von.serialize(Tbl) file.Write("greyrp/" .. game.GetMap():lower() .. "/" .. Name .. ".txt", SData, "DATA") file.Write("greyrp/" .. game.GetMap():lower() .. "/backups/" .. Name .. os.date(",%d,%m,%Y,%H", os.time()) .. ".txt", SData, "DATA") end local function Load() for _, v in pairs(file.Find("greyrp_modules/*.lua", "LUA")) do include("greyrp_modules/" .. v) end end local Loaded = false hook.Add("InitPostEntity", "GreyRPPostEntity", function() if not Loaded then Loaded = true Load() end end) timer.Simple(2, function() if not Loaded then Loaded = true Load() end end) <file_sep>AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:SetSolid(SOLID_BBOX) self:PhysicsInit(SOLID_BBOX) self:SetMoveType(MOVETYPE_NONE) self:DrawShadow(true) self:SetUseType(SIMPLE_USE) self.LastRelocate = CurTime() self.Hiding = false self.TotalSounds = 0 end function ENT:PhysgunPickup(Plr) return false end function ENT:CanTool(Plr) return false end function ENT:IsSpeaking() return self.TotalSounds > 0 end function ENT:VoiceVolume() return 0.1 + (1 + math.sin(CurTime() * 20)/2) * 0.3 end function ENT:Speak(Time, SoundName) self:EmitSound(SoundName) self.TotalSounds = self.TotalSounds + 1 timer.Simple(Time, function() if IsValid(self) then self.TotalSounds = self.TotalSounds - 1 end end) end<file_sep>local Data = GreyRP.GetData("npcpos") local function UpdateData() GreyRP.SetData("npcpos", Data) end DynNPC = {} DynNPC.NPCs = {} local function GenerateModelList(Path, Num) local New = {} for i = 1, Num do local ni = i < 10 and "0" .. tostring(i) or tostring(i) table.insert(New, string.Replace(Path, "*", ni)) end return New end local PlayerModels = { Citizen = table.Merge(GenerateModelList("models/player/group01/male_*.mdl", 9), GenerateModelList("models/player/group01/female_*.mdl", 6)), Thug = table.Merge(GenerateModelList("models/player/group03/male_*.mdl", 9), GenerateModelList("models/player/group03/female_*.mdl", 6)), Scientist = "models/player/scientist.mdl", Security = GenerateModelList("models/player/guard_pack/guard_*.mdl", 9), Police = GenerateModelList("models/taggart/police01/male_*.mdl", 9), Paramedic = GenerateModelList("models/taggart/police02/male_*.mdl", 9), Swat = "models/payday2/units/blue_swat_player.mdl", HeavySwat = "models/payday2/units/heavy_swat_player.mdl", President = "models/Player/Donald_Trump.mdl", SuitsClosedCoatTie = GenerateModelList("models/player/Suits/male_*_closed_coat_tie.mdl", 9), SuitsClosedTie = GenerateModelList("models/player/Suits/male_*_closed_tie.mdl", 9), SuitsOpen = GenerateModelList("models/player/Suits/male_*_open.mdl", 9), SuitsOpenTie = GenerateModelList("models/player/Suits/male_*_open_tie.mdl", 9), SuitsOpenWaistcoat = GenerateModelList("models/player/Suits/male_*_open_waistcoat.mdl", 9), SuitsShirt = GenerateModelList("models/player/Suits/male_*_shirt.mdl", 9), SuitsShirtTie = GenerateModelList("models/player/Suits/male_*_shirt_tie.mdl", 9), } function DynNPC:RegisterNPC(Name, Tbl) DynNPC.NPCs[Name] = Tbl DynNPC.NPCs[Name].Options = DynNPC.NPCs[Name].Options or {} DynNPC.NPCs[Name].Dynamic = DynNPC.NPCs[Name].Dynamic or false DynNPC.NPCs[Name].Sounds = DynNPC.NPCs[Name].Sounds or {Hi = "vo/npc/male01/hi01.wav", Ok = "vo/npc/male01/ok01.wav", Cancel = "vo/npc/male01/busy02.wav", Run = "vo/npc/male01/strider_run.wav"} DynNPC.NPCs[Name].Model = PlayerModels[DynNPC.NPCs[Name].Model] or DynNPC.NPCs[Name].Model if type(DynNPC.NPCs[Name].Model) == "table" then DynNPC.NPCs[Name].Model = table.Random(DynNPC.NPCs[Name].Model) end if Tbl.Jobs then for _, v in pairs(Tbl.Jobs) do DynNPC.NPCs[Name].Options[#DynNPC.NPCs[Name].Options + 1] = { Name = v[1], Select = function(Plr) Plr:changeTeam(v[2], true, true) end, Requirement = function(Plr) return Plr:Team() ~= v[2] end } end DynNPC.NPCs[Name].Options[#DynNPC.NPCs[Name].Options + 1] = { Name = "Quit job", Select = function(Plr) Plr:changeTeam(TEAM_CITIZEN, true, true) end, Requirement = function(Plr) for _, v in pairs(Tbl.Jobs) do if Plr:Team() == v[2] then return true end end return false end } end end for _, v in pairs(file.Find("greyrp_modules/dynnpcs/*.lua", "LUA")) do include("greyrp_modules/dynnpcs/" .. v) end local Animations = { Standing = "idle_all_01", Angry = "idle_all_angry", Scared = "idle_all_scared", Cower = "idle_all_cower", ArmsCrossed = "pose_standing_01", ArmsSide = "pose_standing_02", ThumbsUp = "pose_standing_04", Fist = "idle_fist" } local DynNPCs = {} for _, v in pairs(ents.FindByClass("dyn_npc")) do v:Remove() end for i, v in pairs(DynNPC.NPCs) do if not Data[i] then Data[i] = {default = {Vector(0, 0, 0), Angle(0, 0, 0)}} end end local EntityDebounces = {} local function AddNPC(i, PosKey, Key) local New = ents.Create("dyn_npc") New:SetModel(DynNPC.NPCs[i].Model) New.Dynamic = DynNPC.NPCs[i].Dynamic New.ShouldRelocate = DynNPC.NPCs[i].ShouldRelocate New:SetPos(PosKey[1]) New:SetAngles(PosKey[2]) New:SetNWAngle("OrigAngles", PosKey[2]) New:SetCollisionGroup(COLLISION_GROUP_DEBRIS) New:DropToFloor() New:SetCollisionGroup(COLLISION_GROUP_NONE) New:Spawn() New:PhysWake() New:Activate() New:ResetSequence(New:LookupSequence(Animations[DynNPC.NPCs[i].Animation]) or 1) function New:Relocate(NewPos) if IsValid(self) then self.Hiding = false self:SetPos(NewPos[1]) self:SetAngles(NewPos[2]) self:SetNWAngle("OrigAngles", NewPos[2]) self:SetCollisionGroup(COLLISION_GROUP_DEBRIS) self:DropToFloor() self:SetCollisionGroup(COLLISION_GROUP_NONE) self.LastRelocate = CurTime() end end function New:Think() GAMEMODE:MouthMoveAnimation(self) if not self.Hiding and self.Dynamic then local Should, HideTime = self:ShouldRelocate() local NPosKey = table.Random(Data[i]) if NPosKey[1] == self:GetPos(PosKey[1]) then local n = 0 repeat NPosKey = table.Random(Data[i]) n = n + 1 until NPosKey[1] == self:GetPos(PosKey[1]) or n == 10 end if Should and NPosKey then if HideTime then self.Hiding = true self:Speak(0.7, DynNPC.NPCs[i].Sounds.Run) self:SetPos(Vector(0, 0, -99999)) timer.Simple(HideTime, function() self:Relocate(NPosKey) end) else self:Relocate(NPosKey) end end end end function New:AcceptInput(InputName, Plr) if IsValid(Plr) and Plr:IsPlayer() and not EntityDebounces[Plr] then EntityDebounces[Plr] = true timer.Simple(1, function() EntityDebounces[Plr] = nil end) self:Speak(0.5, DynNPC.NPCs[i].Sounds.Hi) if DynNPC.NPCs[i].CustomNetFunc then net.Start(DynNPC.NPCs[i].CustomNetFunc) net.Send(Plr) else local Tbl = {} for _, v in pairs(DynNPC.NPCs[i].Options) do if v.Requirement(Plr) then Tbl[#Tbl + 1] = v.Name end end net.Start("DynNPCMenu") net.WriteString(i) net.WriteEntity(New) net.WriteTable(Tbl) net.Send(Plr) end end end if DynNPC.NPCs[i].Dynamic then DynNPCs[i] = New else DynNPCs[i] = DynNPCs[i] or {} DynNPCs[i][Key] = New end return New end local function RemoveInvalidNPCS() for i, v in pairs(DynNPCs) do if type(v) == "table" then for e, x in pairs(v) do if not IsValid(x) then DynNPCs[i][x] = nil elseif not Data[i][e] and IsValid(x) then x:Remove() DynNPCs[i][x] = nil end end else if not IsValid(v) then DynNPCs[i] = nil elseif not Data[i] and IsValid(v) then v:Remove() DynNPCs[i] = nil end end end end local function SetNPCPos(Ent, Pos, Ang) Ent:SetPos(Pos) Ent:SetAngles(Ang) Ent:SetNWAngle("OrigAngles", Ang) Ent:SetCollisionGroup(COLLISION_GROUP_DEBRIS) Ent:DropToFloor() Ent:SetCollisionGroup(COLLISION_GROUP_NONE) Ent.LastRelocate = CurTime() end local function RefreshNPC(Key) RemoveInvalidNPCS() if type(DynNPCs[Key]) == "table" then for i, v in pairs(Data[Key]) do local Ent = DynNPCs[Key][i] local PosKey = Data[Key][i] if not IsValid(Ent) then Ent = AddNPC(Key, v, PosKey) end if PosKey then SetNPCPos(Ent, PosKey[1], PosKey[2]) end end else local PosKey = table.Random(Data[Key]) if PosKey then SetNPCPos(DynNPCs[Key], PosKey[1], PosKey[2]) end end end for i, v in pairs(Data) do if not DynNPC.NPCs[i] then Data[i] = nil return end if DynNPC.NPCs[i].Dynamic then local Key = table.GetKeys(v)[1] AddNPC(i, v[Key], Key) else for e, PosKey in pairs(v) do AddNPC(i, PosKey, e) end end end util.AddNetworkString("DynNPCMenu") net.Receive("DynNPCMenu", function(Len, Plr) local EntName = net.ReadString() local Ent = net.ReadEntity() local String = net.ReadString() if IsValid(Ent) then if String == "Cancel" then Ent:Speak(1.7, DynNPC.NPCs[EntName].Sounds.Cancel) else Ent:Speak(0.5, DynNPC.NPCs[EntName].Sounds.Ok) end end for _, v in pairs(DynNPC.NPCs[EntName].Options) do if String == v.Name then v.Select(Plr) end end end) local function LookupString(String) for i, v in pairs(DynNPC.NPCs) do if i:lower():gsub(" ", "") == String:lower():gsub(" ", "") then return i end end end concommand.Add("setnpcpos", function(Plr, Cmd, Args) if IsValid(Plr) and Plr:IsAdmin() and #Args >= 1 and #Args <= 2 and LookupString(Args[1]) then local Key = Args[2] if not Key or #Key > 0 then local EntName = LookupString(Args[1]) Data[EntName][Key or "default"] = {Plr:GetPos(), Plr:GetAngles()} UpdateData() RefreshNPC(EntName) end elseif IsValid(Plr) and Plr:IsAdmin() then Plr:PrintMessage(HUD_PRINTCONSOLE, "Invalid args") end end) concommand.Add("removenpcpos", function(Plr, Cmd, Args) -- dont allow 0 positions, recreate a default one, dont allow no default either if IsValid(Plr) and Plr:IsAdmin() and #Args == 2 and LookupString(Args[1]) then local EntName = LookupString(Args[1]) local Key = Args[2] if Key == "default" then Plr:PrintMessage(HUD_PRINTCONSOLE, "Cannot remove the default position, change its position instead") elseif Key and Data[EntName][Key] then Data[EntName][Key] = nil UpdateData() RefreshNPC(EntName) end elseif IsValid(Plr) and Plr:IsAdmin() then Plr:PrintMessage(HUD_PRINTCONSOLE, "Invalid args") end end) concommand.Add("getnpcpos", function(Plr, Cmd, Args) if IsValid(Plr) and Plr:IsAdmin() and #Args == 1 and LookupString(Args[1]) then local EntName = LookupString(Args[1]) for i, v in pairs(Data[EntName]) do Plr:PrintMessage(HUD_PRINTCONSOLE, EntName .. " Key: " .. i .. " Pos: " .. tostring(v[1]) .. " Ang: " .. tostring(v[2])) end elseif IsValid(Plr) and Plr:IsAdmin() then Plr:PrintMessage(HUD_PRINTCONSOLE, "Invalid args") end end) concommand.Add("refreshnpcpos", function(Plr, Cmd, Args) if IsValid(Plr) and Plr:IsAdmin() and #Args >= 1 and #Args <= 2 and LookupString(Args[1]) then local EntName = LookupString(Args[1]) RefreshNPC(EntName) elseif IsValid(Plr) and Plr:IsAdmin() then Plr:PrintMessage(HUD_PRINTCONSOLE, "Invalid args") end end) <file_sep>hook.Add("GetMapWaypoints", "PropertiesMapWaypoints", function() for i, v in pairs(Properties.GetAll()) do if v.Container then continue end local IsContainer = Properties.IsContainer(i) local Text = IsContainer and "Apartments" or v.Warehouse and "Warehouse" or v.Business and "Business" or "House" if Text then local Icon = IsContainer and "house_link" or v.Warehouse and "lorry_flatbed" or v.Business and "building" or "house" local Col = IsContainer and Color(255, 140, 70) or v.Business and Color(140, 70, 30) or v.Business and Color(50, 140, 255) or Color(50, 220, 50) local NewStart, NewEnd = Vector(v.Start), Vector(v.End) OrderVectors(NewStart, NewEnd) GreyRP.MapWaypoints[#GreyRP.MapWaypoints + 1] = {i, NewStart, NewEnd, Icon, Col, {{v.Name, 120}, {Text, 110}}} end end end) PropertyRTMaterials = PropertyRTMaterials or {} PropertyRTTextures = PropertyRTTextures or {} local PropertyRTRendered = {} local inhook = false local function GetRTTexture(Key, Origin, Angles, w, h) if not PropertyRTTextures[Key] then PropertyRTTextures[Key] = GetRenderTargetEx("propertyrt_" .. Key .. SysTime(), 2048, 2048, RT_SIZE_DEFAULT, MATERIAL_RT_DEPTH_SEPARATE, bit.bor(4, 8), CREATERENDERTARGETFLAGS_UNFILTERABLE_OK, IMAGE_FORMAT_RGB888) PropertyRTMaterials[Key] = CreateMaterial("propertyrt_" .. Key .. SysTime(), "UnlitGeneric", { ["$ignorez"] = 1, ["$vertexcolor"] = 1, ["$vertexalpha"] = 1, ["$nolod"] = 0, ["$basetexture"] = PropertyRTTextures[Key]:GetName() }) end if not PropertyRTRendered[Key] and not inhook then local OldRT = render.GetRenderTarget() render.SetRenderTarget(PropertyRTTextures[Key]) inhook = true render.ClearDepth() render.Clear(0, 0, 0, 255) local PlrDraws = {} for _, v in pairs(player.GetAll()) do if not v:GetNoDraw() then PlrDraws[#PlrDraws + 1] = v v:SetNoDraw(true) end end render.RenderView({ origin = Origin, angles = Angles, x = 0, y = 0, w = ScrW(), h = ScrH(), aspectratio = 2 }) for _, v in pairs(PlrDraws) do v:SetNoDraw(false) end inhook = false render.SetRenderTarget(OldRT) PropertyRTRendered[Key] = true end return PropertyRTMaterials[Key] end local function ValidRealtorProperty(Props, Index) if not Props[Index] then return false end if not Props[Index].Cameras[1] then return false end if Props[Index].Container then return false end if Props[Index].Price == 0 and Props[Index].Rent == 0 then return false end return true end local Descriptions = { Houses = { "This FLOORS floored property is AREA square feet. It has ROOMS rooms. It's in a REGIONPRICE and REGIONOCCUPANCY neighbourhood. It has GARAGES." }, Apartments = { "Text" }, Businesses = { "Text" } } local PropertyDataTypes = {"FLOORS", "AREA"} local function GetPropertyData(Index, Key) local Prop = Properties.Get(Index) if Key == "FLOORS" then return math.Round(math.abs(Prop.Start.z - Prop.End.z) / 160) elseif Key == "AREA" then return string.Comma(math.Round(Properties.GetSquareFootage(Index), -2)) end end PropertyDescriptionCache = {} --PropertyDescriptionCache or {} local function GetPropertyDescription(Index, w) local Key = Index .. "," .. w local Cache = PropertyDescriptionCache[Key] local CheckSum = GlobalPropertiesCheckSum[Key] if Cache and Cache[2] == CheckSum then return Cache[1] end local Text = Descriptions.Houses[1] for _, v in pairs(PropertyDataTypes) do if string.find(Text, v) then Text = string.gsub(Text, v, GetPropertyData(Index, v)) end end local TextSplit = string.Explode(" ", Text) local TextSegments = {{}} local CurLen = 0 local SpaceSize = surface.GetTextSize(" ") for _, g in pairs(TextSplit) do local Size = surface.GetTextSize(g) + SpaceSize if CurLen + Size <= w then CurLen = CurLen + Size else CurLen = Size TextSegments[#TextSegments + 1] = {} end table.insert(TextSegments[#TextSegments], g) end PropertyDescriptionCache[Index] = {TextSegments, CheckSum} return TextSegments end surface.CreateFont("RealtorPosterFont", { font = "Trebuchet", size = 28, weight = 500, antialias = true }) surface.CreateFont("RealtorPosterFontSmall", { font = "Trebuchet", size = 16, weight = 1000, antialias = true }) surface.CreateFont("RealtorFont", { font = "Trebuchet", size = 34, weight = 500, antialias = true }) surface.CreateFont("RealtorFontSmall", { font = "Trebuchet", size = 26, weight = 500, antialias = true }) local function DrawPropertySheet(Index, RTKey, TextRender, x, y, w, h, Light) local Prop = Properties.Get(Index) if Light then surface.SetDrawColor(245, 245, 245, 255) else surface.SetDrawColor(140, 140, 140, 255) end surface.DrawRect(x, y, w, h) local m = w * 0.06 local m2 = w * 0.02 local t = 24 local cy = y x = x + m w = w - m * 2 cy = cy + m surface.SetDrawColor(50, 100, 50, 255) surface.DrawRect(x, cy, w, h * 0.08) if TextRender then surface.SetFont("RealtorPosterFont") surface.SetTextColor(255, 255, 255, 255) EfficientText(Prop.Name, x + w / 2, cy + h * 0.04, true) end cy = cy + h * 0.08 + m2 surface.SetDrawColor(140, 140, 140, 255) surface.SetMaterial(PropertyRTMaterials[RTKey]) surface.DrawTexturedRect(x, cy, w, h * 0.4) cy = cy + h * 0.4 + m2 surface.SetDrawColor(50, 100, 50, 255) surface.DrawRect(x, cy, w, h * 0.08) if TextRender then EfficientText(Properties.IsContainer(Index) and "Apartments" or Prop.Warehouse and "Warehouse" or Prop.Business and "Business" or "House", x + w / 2, cy + h * 0.04, true) end cy = cy + h * 0.08 + m2 if TextRender then surface.SetFont("RealtorPosterFontSmall") surface.SetTextColor(0, 0, 0, 255) for _, g in pairs(GetPropertyDescription(Index, w)) do EfficientText(table.concat(g, " "), x, cy) cy = cy + t end end cy = y + h * 0.92 - m surface.SetDrawColor(50, 100, 50, 255) surface.DrawRect(x, cy, w, h * 0.08) if TextRender then surface.SetFont("RealtorPosterFont") surface.SetTextColor(255, 255, 255, 255) EfficientText((Prop.Price > 0 and "Price: " .. DarkRP.formatMoney(Prop.Price) .. (Prop.Rent > 0 and " " or "") or "") .. (Prop.Rent > 0 and "Rent: " .. DarkRP.formatMoney(Prop.Rent) or ""), x + w / 2, cy + h * 0.04, true) end end hook.Add("PostDrawTranslucentRenderables", "RealtorDrawWorld", function() local Property = Properties.GetByName("Realtor") if not Property then return end local Props = Properties.GetAll() render.SetColorMaterial() local TravelDistance = 0 local Index = 1 for _, v in pairs(Property.Nodes or {}) do local Render = v[1]:ToScreen().visible and EyePos():Distance(v[1]) < 2000 local TextRender = EyePos():Distance(v[1]) < 500 local Ang = v[2]:Angle() Ang:RotateAroundAxis(Ang:Forward(), 90) Ang:RotateAroundAxis(Ang:Right(), 90) for a = 1, 5 do for b = 1, 4 do if not ValidRealtorProperty(Props, Index) then TravelDistance = 0 repeat TravelDistance = TravelDistance + 1 Index = Index + 1 until ValidRealtorProperty(Props, Index) or TravelDistance == 20 if not ValidRealtorProperty(Props, Index) then continue end end if not Render then Index = Index + 1 return end local Prop = Props[Index] local Pos = v[1] + v[2]:Angle():Right() * (a - 3) * 15 + -v[2]:Angle():Up() * (b - 2.5) * 21 local RTKey = tostring(Index) .. "," .. 1 GetRTTexture(RTKey, Prop.Cameras[1][1], Prop.Cameras[1][2]) local Scale = 0.05 * 0.9 cam.Start3D2D(Pos, Ang, Scale * 0.8) local x, y, w, h = -17.5 / Scale / 2, -25 / Scale / 2, 17.5 / Scale, 25 / Scale if WorldToLocal(LocalPlayer():EyePos(), Ang, Pos, Ang).z > 0 then DrawPropertySheet(Index, RTKey, TextRender, x, y, w, h) else surface.SetDrawColor(140, 140, 140, 255) surface.DrawRect(x, y, w, h) end cam.End3D2D() Index = Index + 1 end end end end) local MatBlurScreen = Material("pp/blurscreen") local function DrawBackgroundBlur(Panel, StartTime) local Fraction = math.Clamp((SysTime() - StartTime) / 1, 0, 1) local x, y = Panel:LocalToScreen(0, 0) DisableClipping( true ) surface.SetMaterial(MatBlurScreen) surface.SetDrawColor(255, 255, 255, 255) for i = 0.33, 1, 0.33 do MatBlurScreen:SetFloat("$blur", Fraction * 5 * i) MatBlurScreen:Recompute() if render then render.UpdateScreenEffectTexture() end surface.DrawTexturedRect(x * -1, y * -1, ScrW(), ScrH()) end surface.SetDrawColor(80, 80, 80, 60 * Fraction) surface.DrawRect(x * -1, y * -1, ScrW(), ScrH()) DisableClipping(false) end function ReplacementOpenMenu(self, pControlOpener) if pControlOpener and pControlOpener == self.TextEntry then return end if #self.Choices == 0 then return end if IsValid(self.Menu) then self.Menu:Remove() self.Menu = nil end self.Menu = DermaMenu(false, self) for k, v in pairs(self.Choices) do self.Menu:AddOption(v, function() self:ChooseOption(v, k) end) end local x, y = self:LocalToScreen(0, self:GetTall()) self.Menu:SetMinimumWidth(self:GetWide()) self.Menu:SetMaxHeight(300) self.Menu:Open(x, y, false, self) end local CurMenuProperty net.Receive("PropertiesMenuNet", function(Len, Plr) local Frame = vgui.Create("DFrame") Frame:SetSize(ScrW() * 0.7, ScrH() * 0.8) Frame:SetTitle("") Frame:Center() Frame:SetDraggable(false) Frame:DockPadding(0, 35, 0, 0) Frame:MakePopup() Frame.btnMaxim:SetVisible(false) Frame.btnMinim:SetVisible(false) Frame.btnClose:SetZPos(100) function Frame.btnClose:Paint(w, h) draw.RoundedBoxEx(8, 0, 2, w, 16, Color(220, 80, 80), false, true, true, false) end function Frame:Paint(w, h) DrawBackgroundBlur(self, self.m_fCreateTime) draw.RoundedBoxEx(8, 0, 0, w, 20, Color(32, 178, 170, 255), false, true, false, false) draw.RoundedBox(0, 5, 20, w - 10, h - 20, Color(50, 50, 50, 200)) end local Header = vgui.Create("Panel", Frame) Header:SetHeight(80) Header:Dock(TOP) Header:DockPadding(4, 4, 4, 4) function Header:Paint(w, h) draw.RoundedBoxEx(0, 0, 0, w, h, Color(230, 120, 50, 255)) end local HeaderImage = vgui.Create("DImage", Header) HeaderImage:SetWide(220) HeaderImage:Dock(LEFT) HeaderImage:SetImage("ocrp/quarantine1") local CurrentHeader = "Rent" local function ReSearch() end local ForRent = vgui.Create("DButton", Header) ForRent:SetWide(150) ForRent:Dock(LEFT) ForRent:SetTextColor(Color(255, 255, 255, 255)) ForRent:SetText("For Rent") ForRent:SetFont("RealtorPosterFont") ForRent:NoClipping(true) function ForRent:Paint(w, h) if CurrentHeader == "Rent" then surface.SetDrawColor(245, 245, 245, 255) surface.DrawRect(10, 0, w - 20, h + 4) self:SetTextColor(Color(80, 80, 80, 255)) else self:SetTextColor(Color(255, 255, 255, 255)) end end function ForRent:DoClick() CurrentHeader = "Rent" ReSearch() end local ForSale = vgui.Create("DButton", Header) ForSale:SetWide(150) ForSale:Dock(LEFT) ForSale:SetTextColor(Color(255, 255, 255, 255)) ForSale:SetText("For Sale") ForSale:SetFont("RealtorPosterFont") ForSale:NoClipping(true) function ForSale:Paint(w, h) if CurrentHeader == "Sale" then surface.SetDrawColor(245, 245, 245, 255) surface.DrawRect(10, 0, w - 20, h + 4) self:SetTextColor(Color(80, 80, 80, 255)) else self:SetTextColor(Color(255, 255, 255, 255)) end end function ForSale:DoClick() CurrentHeader = "Sale" ReSearch() end local Business = vgui.Create("DButton", Header) Business:SetWide(150) Business:Dock(LEFT) Business:SetTextColor(Color(255, 255, 255, 255)) Business:SetText("Businesses") Business:SetFont("RealtorPosterFont") Business:NoClipping(true) function Business:Paint(w, h) if CurrentHeader == "Business" then surface.SetDrawColor(245, 245, 245, 255) surface.DrawRect(10, 0, w - 20, h + 4) self:SetTextColor(Color(80, 80, 80, 255)) else self:SetTextColor(Color(255, 255, 255, 255)) end end function Business:DoClick() CurrentHeader = "Business" ReSearch() end local Warehouse = vgui.Create("DButton", Header) Warehouse:SetWide(150) Warehouse:Dock(LEFT) Warehouse:SetTextColor(Color(255, 255, 255, 255)) Warehouse:SetText("Warehouses") Warehouse:SetFont("RealtorPosterFont") Warehouse:NoClipping(true) function Warehouse:Paint(w, h) if CurrentHeader == "Warehouse" then surface.SetDrawColor(245, 245, 245, 255) surface.DrawRect(10, 0, w - 20, h + 4) self:SetTextColor(Color(80, 80, 80, 255)) else self:SetTextColor(Color(255, 255, 255, 255)) end end function Warehouse:DoClick() CurrentHeader = "Warehouse" ReSearch() end local Owned = vgui.Create("DButton", Header) Owned:SetWide(150) Owned:Dock(LEFT) Owned:SetTextColor(Color(255, 255, 255, 255)) Owned:SetText("Owned") Owned:SetFont("RealtorPosterFont") Owned:NoClipping(true) function Owned:Paint(w, h) if CurrentHeader == "Owned" then surface.SetDrawColor(245, 245, 245, 255) surface.DrawRect(10, 0, w - 20, h + 4) self:SetTextColor(Color(80, 80, 80, 255)) else self:SetTextColor(Color(255, 255, 255, 255)) end end function Owned:DoClick() CurrentHeader = "Owned" ReSearch() end local SearchTerms = {} local SearchOptions = vgui.Create("Panel", Frame) SearchOptions:SetHeight(80) SearchOptions:Dock(TOP) SearchOptions:DockPadding(4, 4, 4, 4) function SearchOptions:Paint(w, h) draw.RoundedBox(0, 0, 0, w, h, Color(245, 245, 245, 255)) end SearchOptions:InvalidateLayout(true) local function AddSearchOption(Key, Icon, Values) local Panel = vgui.Create("Panel", SearchOptions) Panel:SetWide((ScrW() * 0.7 - 8) / 8) Panel:Dock(LEFT) Panel:DockPadding(10, 10, 10, 10) local Text = vgui.Create("DLabel", Panel) Text:SetFont("RealtorPosterFontSmall") Text:SetTextColor(Color(80, 80, 80, 255)) Text:SetText(Key) Text:SetTall(20) Text:Dock(TOP) Text:SetContentAlignment(5) local Image = vgui.Create("DImage", Panel) Image:SetImage("icon16/" .. Icon .. ".png") Image:SetWide(42) Image:Dock(LEFT) Image:SetImageColor(Color(0, 0, 0, 120)) function Image:Paint(w, h) draw.RoundedBoxEx(6, 0, 0, w, h, Color(190, 190, 190, 255), true, false, true, false) draw.RoundedBoxEx(4, 1, 1, w - 2, h - 2, Color(235, 235, 235, 255), true, false, true, false) self:PaintAt(12, 8, w - 24, h - 16) end local Combo = vgui.Create("DComboBox", Panel) Combo:Dock(FILL) Combo:SetValue(Values[1]) Combo:SetSortItems(false) Combo.OpenMenu = ReplacementOpenMenu for i, v in pairs(Values) do Combo:AddChoice(v) end function Combo:Paint(w, h) draw.RoundedBoxEx(6, 0, 0, w, h, Color(190, 190, 190, 255), false, true, false, true) draw.RoundedBoxEx(4, 1, 1, w - 2, h - 2, Color(245, 245, 245, 255), false, true, false, true) end SearchTerms[Key] = Values[1] function Combo:OnSelect(Index, Value) SearchTerms[Key] = Value ReSearch() end end local Prices = {} local Cur, Rise = 0, 10000 for i = 1, 90 do Cur = Cur + Rise Prices[#Prices + 1] = DarkRP.formatMoney(Cur) if Cur == 250000 then Rise = Rise * 2.5 elseif Cur == 500000 then Rise = Rise * 2 elseif Cur == 1000000 then Rise = Rise * 2 elseif Cur == 2500000 then Rise = Rise * 2.5 elseif Cur == 5000000 then Rise = Rise * 2 end end AddSearchOption("Min price", "money_dollar", {"No min", unpack(Prices)}) AddSearchOption("Max price", "money_dollar", {"No max", unpack(Prices)}) AddSearchOption("Property type", "building", {"Any", "Houses", "Apartments"}) AddSearchOption("Size", "shape_group", {"Any", "Small", "Medium", "Large"}) local List = vgui.Create("DScrollPanel", Frame) List:Dock(FILL) List:DockMargin(0, 15, 0, 0) List:DockPadding(4, 4, 4, 4) function List:Paint(w, h) draw.RoundedBoxEx(8, 4, 0, w - 8, h, Color(200, 200, 200, 255), false, false, true, false) end local SBar = List:GetVBar() function SBar:Paint(w, h) draw.RoundedBox(0, w * 0.2, 0, w * 0.6, h, Color(50, 50, 50, 200)) end function SBar.btnUp:Paint(w, h) draw.RoundedBox(0, 0, 0, w, h, Color(150, 150, 150, 255)) end function SBar.btnDown:Paint(w, h) draw.RoundedBox(0, 0, 0, w, h, Color(150, 150, 150, 255)) end function SBar.btnGrip:Paint(w, h) draw.RoundedBox(0, w * 0.1, 0, w * 0.8, h, Color(150, 150, 150, 255)) end local function GetSearchTerm(Key, Default) if Key == "MinPrice" then return tonumber(string.gsub(SearchTerms["Min price"], "%D", ""), 10) or Default elseif Key == "MaxPrice" then return tonumber(string.gsub(SearchTerms["Max price"], "%D", ""), 10) or Default elseif Key == "Size" then return SearchTerms["Size"] or Default elseif Key == "PropertyType" then return SearchTerms["Property type"] or Default end end local OTbl = table.ClearKeys(Properties.GetAll(), true) table.SortByMember(OTbl, "Price", true) local Tbl = {} for i, v in pairs(OTbl) do if ValidRealtorProperty(Properties.GetAll(), v.__key) then Tbl[#Tbl + 1] = v end if not CurMenuProperty and not v.IsBusiness and Properties.IsContainer(i) and not v.Container then CurMenuProperty = v.__key break end end function ReSearch() List:Clear() if CurrentHeader == "Rent" or CurrentHeader == "Warehouse" then table.SortByMember(Tbl, "Rent", true) end for i, v in pairs(Tbl) do if CurrentHeader == "Rent" then if v.Business or v.Warehouse or v.Rent == 0 or v.Rent < GetSearchTerm("MinPrice", 0) or v.Rent > GetSearchTerm("MaxPrice", math.huge) then continue end elseif CurrentHeader == "Sale" then if v.Business or v.Warehouse or v.Price == 0 or v.Price < GetSearchTerm("MinPrice", 0) or v.Price > GetSearchTerm("MaxPrice", math.huge) then continue end elseif CurrentHeader == "Business" then if not v.Business then continue end elseif CurrentHeader == "Warehouse" then if not v.Warehouse then continue end elseif CurrentHeader == "Owned" then continue end local Contained = Properties.GetContained(v.__key) local Size = GetSearchTerm("Size", "Any") local SqrFeet = Properties.GetSquareFootage(Contained or v.__key) if Size == "Small" and SqrFeet > 2000 or Size == "Medium" and SqrFeet > 3500 or Size == "Large" and SqrFeet > 4500 then continue end local Type = GetSearchTerm("PropertyType", "Any") if Type == "Houses" and Contained or Type == "Apartments" and not Contained then continue end local RTKey = tostring(v.__key) .. "," .. 1 GetRTTexture(RTKey, v.Cameras[1][1], v.Cameras[1][2]) local New = vgui.Create("Panel", List) New:SetTall(300) New:DockMargin(0, 0, 0, 15) New:Dock(TOP) New:SetMouseInputEnabled(true) New.OldTextureKey = 0 New.TextureKey = 1 New.FadeStart = 0 New.Current = 0 function New:DrawButton(x, y, sx, sy, Text, MX, MY) surface.DrawTexturedRect(x, y, sx, sy) EfficientText(Text, x + sx / 2, y + sy / 2, true) if MX > x and MX < x + sx and MY > y and MY < y + sy then self.Button = Text self:SetCursor("hand") return true end return false end local Price = (CurrentHeader == "Sale" or CurrentHeader == "Business") and DarkRP.formatMoney(v.Price) or DarkRP.formatMoney(v.Rent) .. " per month, down payment of " .. DarkRP.formatMoney(v.Rent / 2) function New:Paint(w, h) surface.SetDrawColor(245, 245, 245, 255) surface.DrawRect(0, 0, w, h) surface.SetDrawColor(230, 120, 50, 255) surface.DrawRect(0, h * 0.7 - 2, h * 1.1, h * 0.3 + 2) surface.SetDrawColor(255, 255, 255, 255) if SysTime() - self.FadeStart < 0.3 then local Fraction = math.Clamp((SysTime() - self.FadeStart) / 0.3, 0, 1) surface.SetMaterial(GetRTTexture(tostring(v.__key) .. "," .. self.OldTextureKey, unpack(v.Cameras[self.OldTextureKey]))) surface.DrawTexturedRect(2, 2, h * 1.1 - 4, h * 0.7 - 6) surface.SetDrawColor(255, 255, 255, 255 * Fraction) surface.SetMaterial(GetRTTexture(tostring(v.__key) .. "," .. self.TextureKey, unpack(v.Cameras[self.TextureKey]))) surface.DrawTexturedRect(2, 2, h * 1.1 - 4, h * 0.7 - 6) else surface.SetMaterial(GetRTTexture(tostring(v.__key) .. "," .. self.TextureKey, unpack(v.Cameras[self.TextureKey]))) surface.DrawTexturedRect(2, 2, h * 1.1 - 4, h * 0.7 - 6) end surface.SetDrawColor(255, 255, 255, 255) local MX, MY = self:LocalCursorPos() local sx, sy = self:LocalToScreen() render.SetScissorRect(sx + 2, sy, sx + h * 1.1 - 2, sy + h, true) local MouseX = MX / (h * 1.1) if not self.Camera then self.Camera = math.min(-#v.Cameras * h * 0.2 + h * 0.55, 0) end if MouseX >= 0 and MouseX <= 1 and MY > h * 0.7 and MY < h then self.Camera = math.Clamp(self.Camera + (MouseX - 0.5) * 15, math.min(-#v.Cameras * h * 0.2 + h * 0.55, 0), math.max(#v.Cameras * h * 0.2 - h * 0.55 + 2, 0)) end self.Button = nil self.Current = 0 for x, y in pairs(v.Cameras) do local px, py = h * 0.15 + (x - #v.Cameras / 2) * h * 0.4 - self.Camera, h * 0.7 surface.SetMaterial(GetRTTexture(tostring(v.__key) .. "," .. x, y[1], y[2])) surface.DrawTexturedRect(px + 2, py, h * 0.4 - 2, h * 0.3 - 2) if MX < h * 1.1 and MX > px and MX < px + h * 0.4 and MY > py and MY < py + h * 0.3 then self.Current = x self.Button = "Camera" self:SetCursor("hand") end end render.SetScissorRect(0, 0, 0, 0, false) surface.SetFont("RealtorFont") surface.SetTextColor(245, 245, 245, 255) surface.SetDrawColor(230, 120, 50, 255) draw.NoTexture() self:DrawButton(h * 1.15, h * 0.7 - 2, w * 0.2, h * 0.3 + 2, "Buy", MX, MY) local Success = self:DrawButton(h * 1.2 + w * 0.2, h * 0.7 - 2, w * 0.2, h * 0.3 + 2, "Show on map", MX, MY) if Success then self.Current = x end if not self.Button then self:SetCursor("none") end surface.SetTextColor(150, 0, 0, 255) EfficientText(Price, h * 1.15, 15) surface.SetFont("RealtorFontSmall") surface.SetTextColor(80, 80, 80, 255) local wi = w - h * 1.2 for f, g in pairs(GetPropertyDescription(v.__key, wi)) do EfficientText(table.concat(g, " "), h * 1.15, 40 + f * 26) end end function New:OnMouseReleased(Code) if Code == MOUSE_LEFT then if self.Button == "Camera" and self.Current ~= 0 then self.OldTextureKey = self.TextureKey self.TextureKey = self.Current self.FadeStart = SysTime() elseif self.Button == "Show on map" then LocalPlayer():ConCommand("greymap_open " .. (v.Start.x + v.End.x) / 2 .. " " .. (v.Start.y + v.End.y) / 2) elseif self.Button == "Buy" then Derma_Query("Really buy this property for " .. Price:gsub("month, down ", "month with an immediate ") .. "?", "Purchase confirmation", "Yes", function() end, "No") end end end end end ReSearch() end) --[[ local BottomFrame = vgui.Create("Panel", Frame) BottomFrame:SetHeight(ScrH() * 0.2) BottomFrame:Dock(BOTTOM) BottomFrame:DockMargin(0, 20, 0, 0) BottomFrame:DockPadding(15, 35, 15, 15) function BottomFrame:Paint(w, h) draw.RoundedBoxEx(8, 0, 0, w, 20, Color(32, 178, 170, 255), false, true, false, false) draw.RoundedBoxEx(8, 0, 20, w, h - 20, Color(245, 245, 245, 255), false, false, true, false) end local BuyButton = vgui.Create("Button", BottomFrame) BuyButton:SetWide(ScrW() * 0.1) BuyButton:Dock(LEFT) BuyButton:SetFont("DYNNPC_FONT_LARGE") BuyButton:SetText("BUY") function BuyButton:DoClick() net.Start("PropertiesMenuNet") net.WriteString("Buy") net.WriteString(CurMenuProperty) net.SendToServer() end function BuyButton:Paint(w, h) self:SetTextColor(self.Hovered and Color(80, 80, 80, 255) or Color(255, 255, 255, 255)) surface.SetDrawColor(self.Hovered and Color(155, 242, 236, 255) or Color(74, 211, 202, 255)) surface.DrawRect(0, 0, w, h) end local SellButton = vgui.Create("Button", BottomFrame) SellButton:SetWide(ScrW() * 0.1) SellButton:Dock(LEFT) SellButton:DockMargin(15, 0, 0, 0) SellButton:SetFont("DYNNPC_FONT_LARGE") SellButton:SetText("SELL") function SellButton:DoClick() net.Start("PropertiesMenuNet") net.WriteString("Sell") net.WriteString(CurMenuProperty) net.SendToServer() end function SellButton:Paint(w, h) self:SetTextColor(self.Hovered and Color(80, 80, 80, 255) or Color(255, 255, 255, 255)) surface.SetDrawColor(self.Hovered and Color(155, 242, 236, 255) or Color(74, 211, 202, 255)) surface.DrawRect(0, 0, w, h) end local PictureFrame = vgui.Create("Panel", Frame) PictureFrame:SetWidth(ScrW() * 0.5 - 20) PictureFrame:Dock(RIGHT) PictureFrame:DockMargin(20, 0, 0, 0) PictureFrame:DockPadding(15, 35, 15, 15) function PictureFrame:Paint(w, h) draw.RoundedBoxEx(8, 0, 0, w, 20, Color(32, 178, 170, 255), false, true, false, false) draw.RoundedBoxEx(8, 0, 20, w, h - 20, Color(245, 245, 245, 255), false, false, true, false) end local PictureBox = vgui.Create("DHorizontalScroller", PictureFrame) PictureBox:SetTall(ScrH() * 0.42) PictureBox:Dock(TOP) local PictureBoxI = 1 function PictureBox:Paint(w, h) if #GlobalProperties[CurMenuProperty].Cameras == 0 then return end if CurMenuProperty and GlobalProperties[CurMenuProperty] then -- TODO Check if not owned or self owned local x, y = self:LocalToScreen() h = (#GlobalProperties[CurMenuProperty].Cameras <= 1) and h * 1.429 - 70 or h - 15 render.DrawTextureToScreenRect(GetRTTexture(CurMenuProperty .. PictureBoxI), x, y, w, h) end end local PictureScroll = vgui.Create("DHorizontalScroller", PictureFrame) PictureScroll:Dock(FILL) PictureScroll:SetOverlap(-15) function PictureScroll.btnLeft:Paint(w, h) draw.RoundedBox(0, 0, 0, w, h, Color(200, 200, 200, 255)) end function PictureScroll.btnLeft:AlignBottom() self:SetWide(15) self:DockMargin(10, 10, 10, 10) self:Dock(LEFT) end function PictureScroll.btnRight:Paint(w, h) draw.RoundedBox(0, 0, 0, w, h, Color(200, 200, 200, 255)) end function PictureScroll.btnRight:AlignBottom() self:SetWide(15) self:DockMargin(10, 10, 10, 10) self:Dock(RIGHT) end function PictureScroll:RefreshList() for _, v in pairs(self.Panels) do v:Remove() end self.Panels = {} if not CurMenuProperty or not GlobalProperties[CurMenuProperty] then return end RenderCameras = {} for i, v in pairs(GlobalProperties[CurMenuProperty].Cameras) do RenderCameras[#RenderCameras + 1] = v[1] local New = vgui.Create("DButton") New.LastRender = 0 New:SetText("") New:NoClipping(true) function New:Paint(w, h) local x, y = self:LocalToScreen() local RTTex = GetRTTexture(CurMenuProperty .. i) if SysTime() - New.LastRender > 1 then local OldRT = render.GetRenderTarget() local OldW, OldH = ScrW(), ScrH() render.SetRenderTarget(RTTex) render.SetViewPort(x, y, w, h) IN_CAM = true WAS_IN_CAM = false render.RenderView({ x = 0, y = 0, w = OldW, h = OldH, aspectratio = OldW / OldH, origin = v[1], angles = v[2], drawhud = false, drawviewmodel = false }) WAS_IN_CAM = true IN_CAM = false render.SetViewPort(0, 0, OldW, OldH) render.SetRenderTarget(OldRT) New.LastRender = SysTime() end if #GlobalProperties[CurMenuProperty].Cameras > 1 then local px, py = PictureScroll:LocalToScreen() local pw, ph = PictureScroll:GetSize() x, y = self:GetPos() w, h = self:GetSize() render.SetScissorRect(px, py, px + pw, py + ph, true) render.DrawTextureToScreenRect(RTTex, px + x - PictureScroll.OffsetX, py + y, w, h) render.SetScissorRect(0, 0, 0, 0, false) end end function New:ApplySchemeSettings() self:SetWide(self:GetTall() * 1.777) end function New:DoClick() PictureBoxI = i end PictureScroll:AddPanel(New) end end PictureScroll:RefreshList() local PropertySheet = vgui.Create("DPropertySheet", Frame) PropertySheet:SetWidth(ScrW() * 0.2) PropertySheet:Dock(LEFT) function PropertySheet:Paint(w, h) draw.RoundedBoxEx(8, 0, 0, w, 20, Color(32, 178, 170, 255), false, true, false, false) draw.RoundedBoxEx(8, 0, 20, w, h - 20, Color(245, 245, 245, 255), false, false, true, false) end local HousesPanel = vgui.Create("Panel", PropertySheet) function HousesPanel:Paint(w, h) end local HousesScroll = vgui.Create("DScrollPanel", HousesPanel) HousesScroll:Dock(FILL) local Sheet = PropertySheet:AddSheet("Houses", HousesPanel) function Sheet.Tab:Paint(w, h) self.m_colText = self:IsActive() and Color(74, 211, 202, 255) or Color(255, 255, 255, 255) surface.SetDrawColor(self:IsActive() and Color(245, 245, 245, 255) or (self.Hovered and Color(108, 216, 209, 255) or Color(74, 211, 202, 255))) surface.DrawRect(0, 0, w, h) end local BusinessesPanel = vgui.Create("Panel", PropertySheet) function BusinessesPanel:Paint(w, h) end local BusinessesScroll = vgui.Create("DScrollPanel", BusinessesPanel) BusinessesScroll:Dock(FILL) Sheet = PropertySheet:AddSheet("Businesses", BusinessesPanel) function Sheet.Tab:Paint(w, h) self.m_colText = self:IsActive() and Color(74, 211, 202, 255) or Color(255, 255, 255, 255) surface.SetDrawColor(self:IsActive() and Color(245, 245, 245, 255) or (self.Hovered and Color(108, 216, 209, 255) or Color(74, 211, 202, 255))) surface.DrawRect(0, 0, w, h) end for _, v in pairs(Tbl) do local Start = string.find(v.Name, "_", #v.Name - 3) if not string.EndsWith(v.Name, "_0") and Start then continue end local New = vgui.Create("DButton", v.IsBusiness and BusinessesScroll or HousesScroll) New:Dock(TOP) New:DockMargin(0, 9, 0, 0) New:SetTall(45) New:SetFont("DYNNPC_FONT_MEDIUM") New:SetTextColor(Color(255, 255, 255, 255)) local NewTitle = (Start and v.Name:sub(1, Start - 1) or v.Name):gsub(" ", "") NewTitle = NewTitle:gsub("[A-Z]", " %1"):Trim() surface.SetFont("DYNNPC_FONT_MEDIUM") local sws = surface.GetTextSize(" ") New:SetText(NewTitle .. ":" .. string.rep(" ", (50 * sws - surface.GetTextSize(NewTitle)) / sws) .. "Price: $" .. v.Price) function New:Paint(w, h) self:SetTextColor(CurMenuProperty == v.Name and Color(80, 80, 80, 255) or Color(255, 255, 255, 255)) surface.SetDrawColor(CurMenuProperty == v.Name and Color(155, 242, 236, 255) or Color(74, 211, 202, 255)) surface.DrawRect(0, 0, w, h) end function New:DoClick() CurMenuProperty = v.__key PictureScroll:RefreshList() PictureBoxI = 1 end end]] <file_sep>local Data = {} hook.Add("SetupPlayerVisibility", "MapRender", function(Plr) if Data[Plr] then AddOriginToPVS(Data[Plr]) end end) util.AddNetworkString("MapPositionData") net.Receive("MapPositionData", function(Len, Plr) Data[Plr] = net.ReadVector() end)
02a033d0ee3946acb089a160671494ec7c8eff47
[ "Lua" ]
13
Lua
CodedNil/dynnpc
e23b79a8b3a14d87de0a175c3b2f5c3cd3702ed9
0d911ab0cefe4165cedcfb6c91cd8dce4998e722
refs/heads/master
<file_sep><li [ngClass]="{'list-group-item': true, 'list-group-item-success': postLoveits > 0, 'list-group-item-danger': postLoveits < 0}"> <div [ngStyle]="{color: getColor()} "> <div class="row"> <div class="col-md-8"> <h2> {{ postTitle }} </h2> </div> <div class="col-md-4"> <div class="float-right"> <p class="text-secondary" style="color: #9a9494;">{{ postCreated | date: 'short' | uppercase}}</p> </div> </div> </div> <p> {{ postContent }} </p> </div> <button class="btn btn-success" (click)="love(postLoveits)">love it!</button> <button class="btn btn-danger" (click)="dlove([postLoveits])">Don't love it!</button> </li><file_sep>import { Component, Input, OnInit } from "@angular/core"; import { Post } from "../post.model"; @Component({ selector: "app-post-list-component", templateUrl: "./post-list-component.component.html", styleUrls: ["./post-list-component.component.scss"] }) export class PostListComponentComponent implements OnInit { /*posts: Post[] = [ new Post("Mon premier post", "test description", 1, new Date()), new Post("Mon deuxiéme post", "test description", -1, new Date()), new Post("Mon autre post", "test description", 0, new Date()) ];*/ posts = [ { title: "Mon premier post", content: "test description", loveIts: -1, created_at: new Date() }, { title: "Mon deuxiéme post", content: "test description", loveIts: 1, created_at: new Date() }, { title: "Encore", content: "test description", loveIts: 0, created_at: new Date() } ]; constructor() {} ngOnInit() {} }
5262c8580ab5ee7c118e6eea8583e5ece32806b6
[ "TypeScript", "HTML" ]
2
HTML
Hassenne/OCblogAngular
27f29fc436a1f9c6ba073226ea13c7ec07da750f
218313f44b2c9b0ffb5e83dc3e3a78f803475565
refs/heads/master
<repo_name>cireli9/cnn<file_sep>/README.md # cnn LeNet CNN coded in Python from scratch (NumPy) <file_sep>/pool_layer.py from __future__ import division from conv_layer import BaseConvLayer from collections import OrderedDict import numpy as np dtype = np.float32 class PoolLayer(BaseConvLayer): def __init__(self, act_type, kernel_size, stride, pad): self.act_type = act_type self.kernel_size = kernel_size self.stride = stride self.pad = pad self.outputs = [] self.params = OrderedDict() super(PoolLayer, self).__init__() def init(self, height, width, in_channels): """No need to implement this func""" pass def forward(self, inputs): """The forward pass Arguments: inputs (OrderedDict): A dictionary containing height: the height of the current input width: the width of the current input channels: number of channels in the current inputs data: a flattened data array of the form batch_size * height * width * channel, unrolled in the same way Returns: outputs (OrderedDict): A dictionary containing height: The height of the output width: The width of the output out_channels: The output number of feature maps Same as the input channels for this layer data: a flattened output data array of the form height * width * channel, unrolled in the same way You may want to take a look at the im2col_conv and col2im_conv functions present in the base class ``BaseConvLayer`` You may also find it useful to cache the height, width and channel of the input image for the backward pass. The output heights, widths and channels can be computed on the fly using the ``get_output_dim`` function. """ h_in = inputs["height"] w_in = inputs["width"] c = inputs["channels"] data = inputs["data"] batch_size = data.shape[0] k = self.kernel_size h_out, w_out, c = self.get_output_dim( h_in, w_in, self.pad, self.stride, self.kernel_size, c ) # cache for backward pass self.h_in, self.w_in, self.c = h_in, w_in, c self.data = data outputs = OrderedDict() outputs["height"] = h_out outputs["width"] = w_out outputs["channels"] = c outputs["data"] = np.zeros((batch_size, h_out * w_out * c), dtype=dtype) ################## ## Using im2col ## ################## stack = [] for ix in range(batch_size): col = self.im2col_conv(data[ix], h_in, w_in, c, h_out, w_out).reshape((k*k, c, h_out*w_out)) self.outputs.append(col) out = np.max(col, axis = 0).transpose(1, 0).flatten() stack.append(out) stack = np.stack(stack) outputs["data"] = stack # outputs["data"] = np.zeros( # (batch_size, h_out * w_out * c), dtype=dtype).reshape((batch_size, h_out, w_out, c)) # outputs["data"] = data.reshape(batch_size, c, h_out, k, w_out, k).max(axis=(3,5)) #outputs["data"] = outputs["data"].flatten().reshape((batch_size, h_out*w_out*c)) return outputs def backward(self, output_grads): """The backward pass Arguments: output_grads (OrderedDict): Containing grad: gradient wrt output Returns: input_grads (OrderedDict): Containing grad: gradient wrt input Note that we compute the output heights, widths, and channels on the fly in the backward pass as well. You may want to take a look at the im2col_conv and col2im_conv functions present in the base class ``BaseConvLayer`` """ input_grads = OrderedDict() input_grads["grad"] = np.zeros_like(self.data, dtype=dtype) h_in, w_in, c = self.h_in, self.w_in, self.c batch_size = self.data.shape[0] output_diff = output_grads["grad"] k = self.kernel_size stride = self.stride p = self.pad h_out, w_out, c = self.get_output_dim( h_in, w_in, self.pad, self.stride, self.kernel_size, c ) data = self.data outputs = self.outputs ################## ## Using col2im ## ################## for ix in range(batch_size): col = outputs[ix].reshape(c, k*k, h_out*w_out) out = np.max(col, axis = 0, keepdims = True) max_i = np.equal(out, col).transpose(1, 0, 2) # col = self.im2col_conv(data[ix], h_in, w_in, c, h_out, w_out).flatten().reshape((k,k, c, h_out*w_out)) # col = col.flatten().reshape((k*k, c, h_out*w_out)) # max_i = np.argmax(col, axis = 0) # mask = np.zeros((k*k, c, h_out*w_out)) # mask[max_i] = 1 grads = output_diff[ix].reshape(h_out*w_out, c).transpose(1, 0) new_col = grads[np.newaxis, :, :] * max_i # grads = np.repeat(grads[np.newaxis, :, :], k*k, axis=0) # col = np.multiply(grads, mask).flatten().reshape(k*k*c, h_out*w_out) im = self.col2im_conv(new_col, h_in, w_in, c, h_out, w_out) input_grads["grad"][ix] = im.flatten() ################################## ## Using repeat and np.multiply ## ################################## # col = np.zeros_like(k*k*c, h_out*w_out) # grads_flat = output_diff.reshape((batch_size, h_in, w_in, c)transpose(2, 3, 0, 1).ravel() # col[max_i, range(max_i.size)] = grads_flat # grads = self.col2im_conv(col, h_in, w_in, c, h_out, w_out) # input_grads["grad"] = grads.reshape(self.data.shape) # print(np.sum(input_grads["grad"])) # # create array filled with grad values and mask # maxvals = np.repeat(self.outputs["data"], k**2, axis = 1) # mask = np.equal(data,maxvals) # #print(mask) # grads = np.repeat(output_diff, k**2, axis = 1) # # grads = np.repeat(np.repeat(grads, k, axis=2), k, axis=3) # for ix in range(batch_size): # input_grads["grad"][ix] = np.multiply(mask[ix],grads[ix]) ################# ## Using loops ## ################# # input_grads["grad"] = input_grads["grad"].reshape((batch_size, h_in, w_in, c)) # for ix in range(batch_size): # im = data[ix].flatten().reshape((h_in, w_in, c)) # tmp_diff = output_diff[ix].flatten().reshape((h_out*w_out, c)) # for depth in range(c): # for h in range(h_out): # for w in range(w_out): # left_r = h * stride # right_r = h * stride + k # left_c = w * stride # right_c = w * stride + k # pool = im[left_r:right_r, left_c:right_c, depth] # mask = (pool == np.max(pool)) # input_grads["grad"][ix][left_r:right_r, left_c:right_c, depth] = \ # mask*tmp_diff[h*w_out+w,depth] # input_grads["grad"] = input_grads["grad"].flatten().reshape((batch_size, h_in*w_in*c)) return input_grads
9be519be550ef53a2d376e9fa74fac41920e0b10
[ "Markdown", "Python" ]
2
Markdown
cireli9/cnn
cc2cda392e857e100a264af121722e73ebbadd10
e282ddc10d045375bd9cf6721b56c5f18ca250cf
refs/heads/master
<file_sep>import * as ReactGA from '../../src'; jest.mock('../../src/utils/loadGA'); describe('event()', () => { const spies = {}; beforeEach(() => { spies.warn = jest .spyOn(global.console, 'warn') .mockImplementation(() => {}); spies.info = jest .spyOn(global.console, 'info') .mockImplementation(() => {}); spies.ga = jest.fn(); global.window.ga = spies.ga; }); afterEach(() => { jest.restoreAllMocks(); }); it('should record an event', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test' }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'Send Test', eventCategory: 'Test', hitType: 'event' }); }); it('should record an event with multiple trackers', () => { ReactGA.initialize([ { trackingId: 'foo' }, { trackingId: 'bar', gaOptions: { name: 'baz' } } ]); ReactGA.event({ category: 'Test', action: 'Send Test' }, ['baz']); expect(spies.ga).toHaveBeenCalledTimes(4); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'create', 'bar', { name: 'baz' }); expect(spies.ga).toHaveBeenNthCalledWith(3, 'send', { eventAction: 'Send Test', eventCategory: 'Test', hitType: 'event' }); expect(spies.ga).toHaveBeenNthCalledWith(4, 'baz.send', { eventAction: 'Send Test', eventCategory: 'Test', hitType: 'event' }); }); it('should record an event with strings converted to titleCase', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'test', action: 'send test' }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'Send Test', eventCategory: 'Test', hitType: 'event' }); }); it('should not convert strings to titleCase if the flag is false', () => { ReactGA.initialize('foo', { titleCase: false }); ReactGA.event({ category: 'test', action: 'send test' }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'send test', eventCategory: 'test', hitType: 'event' }); }); it('should warn if args object is missing', () => { ReactGA.initialize('foo'); ReactGA.event(); expect(spies.warn).toHaveBeenCalledTimes(1); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'args.category AND args.action are required in event()' ); }); it('should warn if category is missing', () => { ReactGA.initialize('foo'); ReactGA.event({ action: 'Send Test' }); expect(spies.warn).toHaveBeenCalledTimes(1); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'args.category AND args.action are required in event()' ); }); it('should warn if category is empty string', () => { ReactGA.initialize('foo'); ReactGA.event({ category: '', action: 'Send Test' }); expect(spies.warn).toHaveBeenCalledTimes(1); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'args.category AND args.action are required in event()' ); }); it('should warn if action is missing', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test' }); expect(spies.warn).toHaveBeenCalledTimes(1); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'args.category AND args.action are required in event()' ); }); it('should warn if action is empty string', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: '' }); expect(spies.warn).toHaveBeenCalledTimes(1); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'args.category AND args.action are required in event()' ); }); it('should record a label value', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test', label: 'Test Label Value' }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'Send Test', eventCategory: 'Test', eventLabel: 'Test Label Value', hitType: 'event' }); }); it('should record a value', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test', value: 10 }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'Send Test', eventCategory: 'Test', eventValue: 10, hitType: 'event' }); }); it('should record a value of zero', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test', value: 0 }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'Send Test', eventCategory: 'Test', eventValue: 0, hitType: 'event' }); }); it('should reject a non-numeric value value', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test', value: 'millions' }); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'Expected `args.value` arg to be a Number.' ); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'Send Test', eventCategory: 'Test', hitType: 'event' }); }); it('should record a nonInteraction value', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test', nonInteraction: true }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'Send Test', eventCategory: 'Test', nonInteraction: true, hitType: 'event' }); }); it('should reject a non-boolean nonInteraction value', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test', nonInteraction: 'yeahsure' }); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', '`args.nonInteraction` must be a boolean.' ); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'Send Test', eventCategory: 'Test', hitType: 'event' }); }); it('should record a valid transport value', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test', transport: 'beacon' }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'Send Test', eventCategory: 'Test', transport: 'beacon', hitType: 'event' }); }); it('should reject a non-string transport value', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test', transport: true }); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', '`args.transport` must be a string.' ); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'Send Test', eventCategory: 'Test', hitType: 'event' }); }); it('should warn but allow an invalid transport value string', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test', transport: 'lolwut' }); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', '`args.transport` must be either one of these values: ' + '`beacon`, `xhr` or `image`' ); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { eventAction: 'Send Test', eventCategory: 'Test', transport: 'lolwut', hitType: 'event' }); }); it('should send custom dimensions with the event payload', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test', dimension1: 'foo', dimension20: 'bar' }); expect(spies.ga).toHaveBeenCalledWith('send', { eventAction: 'Send Test', eventCategory: 'Test', hitType: 'event', dimension1: 'foo', dimension20: 'bar' }); }); it('should send custom metrics with the event payload', () => { ReactGA.initialize('foo'); ReactGA.event({ category: 'Test', action: 'Send Test', metric1: 1, metric20: 2.6 }); expect(spies.ga).toHaveBeenCalledWith('send', { eventAction: 'Send Test', eventCategory: 'Test', hitType: 'event', metric1: 1, metric20: 2.6 }); }); }); <file_sep>import * as ga from './index'; declare function describe(desc: string, f: () => void): void; declare function it(desc: string, f: () => void): void; describe('Testing react-ga initialize object', () => { it('Able to initialize react-ga object', () => { ga.initialize('UA-65432-1'); }); it('Able to initailize react-ga object', () => { const options: ga.InitializeOptions = { debug: true }; ga.initialize('UA-65432-1', options); }); it('Able to initialize multiple trackers', () => { ga.initialize([ { trackingId: 'abc', debug: true }, { trackingId: 'efg', debug: true, gaOptions: { name: 'blah' } } ]); }); }); describe('Testing react-ga pageview calls', () => { it('Able to make pageview calls', () => { ga.initialize('UA-65432-1'); ga.pageview('http://telshin.com'); }); it('Able to make pageview calls with multiple trackers', () => { ga.initialize([ { trackingId: 'abc', debug: true }, { trackingId: 'efg', debug: true, gaOptions: { name: 'blah' } } ]); ga.pageview('http://telshin.com', ['blah']); }); it('Able to make pageview calls with custom title', () => { ga.initialize('UA-65432-1'); ga.pageview('http://telshin.com', undefined, 'custom title'); }); }); describe('Testing react-ga modal calls', () => { it('Able to make modal calls', () => { ga.initialize('UA-65432-1'); ga.modalview('Test modal'); }); it('Able to make modal calls with multiple trackers', () => { ga.initialize([ { trackingId: 'abc', debug: true }, { trackingId: 'efg', debug: true, gaOptions: { name: 'blah' } } ]); ga.modalview('Test modal', ['blah']); }); }); describe('Testing react-ga event calls', () => { const options: ga.EventArgs = { category: 'Test', action: 'CI', label: 'Running Jasmine tests for react-ga typscript library', value: 4, nonInteraction: true }; it('Able to make event calls', () => { ga.initialize('UA-65432-1'); ga.event(options); }); it('Able to make event calls with multiple trackers', () => { ga.initialize([ { trackingId: 'abc', debug: true }, { trackingId: 'efg', debug: true, gaOptions: { name: 'blah' } } ]); ga.event(options, ['blah']); }); it('Able to pass custom dimensions with events', () => { const payloadWithDimensions: ga.EventArgs = { dimension1: 'foo', dimension20: 'bar', ...options }; ga.initialize('UA-65432-1'); ga.event(payloadWithDimensions); }); it('Able to pass custom metrics with events', () => { const payloadWithmetrics: ga.EventArgs = { metric1: 1, metric20: 2.99, ...options }; ga.initialize('UA-65432-1'); ga.event(payloadWithmetrics); }); }); describe('Testing react-ga set calls', () => { const fieldObject: ga.FieldsObject = { page: '/users' }; it('Able to make set calls', () => { ga.initialize('UA-65432-1'); ga.set(fieldObject); }); it('Able to make set calls with multiple trackers', () => { ga.initialize([ { trackingId: 'abc', debug: true }, { trackingId: 'efg', debug: true, gaOptions: { name: 'blah' } } ]); ga.set(fieldObject, ['blah']); }); }); describe('Testing react-ga v2.1.2', () => { it('Able to make ga calls', () => { ga.ga(); }); it('Able to make send calls', () => { let fieldObject: ga.FieldsObject = { page: '/users' }; ga.send(fieldObject, []); }); it('Able to make timing calls', () => { ga.timing( { category: 'string', variable: 'string', value: 1, label: 'string' }, [] ); }); it('Able to make exception calls', () => { let fieldObject: ga.FieldsObject = { page: '/users' }; ga.exception(fieldObject, []); }); it('Able to make plugin object calls', () => { const execute = ga.plugin.execute; const require = ga.plugin.require; const payload = {}; execute('name', 'action', payload); execute('name', 'action', 'type', payload); require('name', {}); require('name', {}, 'trackerName'); }); it('Able to make outboundLink calls', () => { ga.outboundLink({ label: 'string' }, () => {}, []); }); }); <file_sep>import * as ReactGA from '../../src/index'; describe('test mode', () => { it('should send the correct arguments to window.ga when arguments are passed', () => { ReactGA.initialize('foo', { testMode: true }); ReactGA.ga('send', 'pageview', '/mypage'); expect(ReactGA.testModeAPI.calls).toStrictEqual([ ['create', 'foo', 'auto'], ['send', 'pageview', '/mypage'] ]); }); }); <file_sep>import React from 'react'; import { shallow } from 'enzyme'; import OutboundLink from '../../src/components/OutboundLink'; jest.mock('../../src/utils/loadGA'); /** * <OutboundLink> React components */ describe('<OutboundLink> React component', () => { let renderedOutboundLink; let warnSpy; beforeEach(() => { warnSpy = jest.spyOn(global.console, 'warn').mockImplementation(() => {}); renderedOutboundLink = shallow(<OutboundLink eventLabel="" />); }); afterEach(() => { renderedOutboundLink = null; jest.restoreAllMocks(); }); it('should create an <a> DOM node', () => { expect(renderedOutboundLink.type()).toEqual('a'); }); it('should have `href` set in the underlying <a> DOM node', () => { const destinationUrl = 'http://example.com/'; renderedOutboundLink = shallow( <OutboundLink to={destinationUrl} eventLabel="" /> ); expect(renderedOutboundLink.prop('href')).toEqual(destinationUrl); }); it('should raise warning if ga module is not available', () => { const OutboundLinkComponent = React.createElement(OutboundLink, { eventLabel: '' }); expect(warnSpy).toHaveBeenCalledTimes(0); if (OutboundLink.origTrackLink) { // OutboundLink.trackLink has already been replaced in react-ga OutboundLinkComponent.type.trackLink = OutboundLink.origTrackLink; } OutboundLinkComponent.type.trackLink({}, () => {}); expect(warnSpy).toHaveBeenCalledTimes(1); expect(warnSpy).toHaveBeenCalledWith( '[react-ga]', 'ga tracking not enabled' ); }); it('should call ga.outboundLink in its onClick event handler', () => { const fakeOutboundLinkFunc = jest.fn(); const fakeGA = { outboundLink: fakeOutboundLinkFunc }; const OutboundLinkComponent = React.createElement(OutboundLink, { eventLabel: '' }); OutboundLinkComponent.type.trackLink = fakeGA.outboundLink; renderedOutboundLink = shallow(OutboundLinkComponent); expect(fakeOutboundLinkFunc).toHaveBeenCalledTimes(0); renderedOutboundLink.simulate('click', { preventDefault: () => {} }); expect(fakeOutboundLinkFunc).toHaveBeenCalledTimes(1); }); it('should pass eventLabel prop to ga.outboundLink', () => { const fakeOutboundLinkFunc = jest.fn(); const OutboundLinkComponent = React.createElement(OutboundLink, { eventLabel: 'helloworld' }); OutboundLinkComponent.type.trackLink = fakeOutboundLinkFunc; renderedOutboundLink = shallow(OutboundLinkComponent); renderedOutboundLink.simulate('click', { preventDefault: () => {} }); expect(fakeOutboundLinkFunc).toHaveBeenCalledWith( { label: 'helloworld' }, expect.anything(), null ); }); it('should pass trackerNames prop to ga.outboundLink', () => { const fakeOutboundLinkFunc = jest.fn(); const props = { eventLabel: 'helloworld', trackerNames: ['tracker2'] }; const OutboundLinkComponent = React.createElement(OutboundLink, props); OutboundLinkComponent.type.trackLink = fakeOutboundLinkFunc; renderedOutboundLink = shallow(OutboundLinkComponent); renderedOutboundLink.simulate('click', { preventDefault: () => {} }); expect(fakeOutboundLinkFunc).toHaveBeenCalledWith( { label: 'helloworld' }, expect.anything(), ['tracker2'] ); }); it('should call preserve onClick prop in onClick event handler', () => { const onComponentClick = jest.fn(); renderedOutboundLink = shallow( <OutboundLink eventLabel="" onClick={onComponentClick} /> ); expect(onComponentClick).toHaveBeenCalledTimes(0); renderedOutboundLink.simulate('click', { preventDefault: () => {} }); expect(onComponentClick).toHaveBeenCalledTimes(1); }); it('should add rel=`noopener noreferrer` to a link if the target is _blank', () => { const destinationUrl = 'http://example.com/'; renderedOutboundLink = shallow( <OutboundLink to={destinationUrl} eventLabel="" target="_blank" /> ); expect(renderedOutboundLink.prop('rel')).toEqual('noopener noreferrer'); }); it('should add custom rel tags if the target is _blank', () => { const destinationUrl = 'http://example.com/'; renderedOutboundLink = shallow( <OutboundLink to={destinationUrl} eventLabel="" target="_blank" rel="nofollow" /> ); expect(renderedOutboundLink.prop('rel')).toEqual( 'nofollow noopener noreferrer' ); }); }); <file_sep>import * as ReactGA from '../../src'; jest.mock('../../src/utils/loadGA'); describe('ga()', () => { const spies = {}; beforeEach(() => { spies.warn = jest .spyOn(global.console, 'warn') .mockImplementation(() => {}); spies.info = jest .spyOn(global.console, 'info') .mockImplementation(() => {}); spies.ga = jest.fn(); global.window.ga = spies.ga; }); afterEach(() => { jest.restoreAllMocks(); }); it('should return the same object as window.ga when no arguments are passed', () => { ReactGA.initialize('foo'); expect(ReactGA.ga()).toEqual(window.ga); }); it('should send the correct arguments to window.ga when arguments are passed', () => { ReactGA.initialize('foo'); ReactGA.ga('send', 'pageview', '/mypage'); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', 'pageview', '/mypage'); }); it('should output debug info, if debug is on', () => { ReactGA.initialize('foo', { debug: true }); ReactGA.ga('send', 'pageview', '/mypage'); expect(spies.info).toHaveBeenCalledTimes(2); expect(spies.info).toHaveBeenNthCalledWith( 1, '[react-ga]', "called ga('arguments');" ); expect(spies.info).toHaveBeenNthCalledWith( 2, '[react-ga]', 'with arguments: ["send","pageview","/mypage"]' ); }); }); <file_sep>import * as ReactGA from '../../src'; jest.mock('../../src/utils/loadGA'); describe('exception()', () => { const spies = {}; beforeEach(() => { spies.warn = jest .spyOn(global.console, 'warn') .mockImplementation(() => {}); spies.info = jest .spyOn(global.console, 'info') .mockImplementation(() => {}); spies.ga = jest.fn(); global.window.ga = spies.ga; }); afterEach(() => { jest.restoreAllMocks(); }); it('should record an exception', () => { ReactGA.initialize('foo'); ReactGA.exception({}); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { hitType: 'exception' }); }); it('should record a description value', () => { ReactGA.initialize('foo'); ReactGA.exception({ description: 'This is an exception!' }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { exDescription: 'This Is an Exception!', hitType: 'exception' }); }); it('should record a fatal value', () => { ReactGA.initialize('foo'); ReactGA.exception({ fatal: true }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { exFatal: true, hitType: 'exception' }); }); it('should reject a non-boolean fatal value', () => { ReactGA.initialize('foo'); ReactGA.exception({ fatal: 'this-is-fatal' }); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', '`args.fatal` must be a boolean.' ); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { hitType: 'exception' }); }); }); <file_sep>import * as ReactGA from '../../src'; jest.mock('../../src/utils/loadGA'); describe('initialize()', () => { const spies = {}; beforeEach(() => { spies.warn = jest .spyOn(global.console, 'warn') .mockImplementation(() => {}); spies.info = jest .spyOn(global.console, 'info') .mockImplementation(() => {}); spies.ga = jest.fn(); global.window.ga = spies.ga; }); afterEach(() => { jest.restoreAllMocks(); }); it('should define window.ga', () => { ReactGA.initialize('foo'); expect(typeof window.ga).toBe('function'); }); it('should call window.ga() if no options given', () => { ReactGA.initialize('foo'); expect(spies.ga).toHaveBeenCalledTimes(1); expect(spies.ga).toHaveBeenCalledWith('create', 'foo', 'auto'); }); it('should call window.ga() with ga options if they are given', () => { ReactGA.initialize('foo', { gaOptions: { userId: 123 } }); expect(spies.ga).toHaveBeenCalledTimes(1); expect(spies.ga).toHaveBeenCalledWith('create', 'foo', { userId: 123 }); }); it('should not call window.ga() if options.useExistingGa is set', () => { ReactGA.initialize('foo', { useExistingGa: true }); expect(spies.ga).toHaveBeenCalledTimes(0); }); it('should initialize multiple trackers if they are given', () => { ReactGA.initialize([ { trackingId: 'foo', gaOptions: { userId: 123 } }, { trackingId: 'bar', gaOptions: { name: 'baz' } } ]); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', { userId: 123 }); expect(spies.ga).toHaveBeenNthCalledWith(2, 'create', 'bar', { name: 'baz' }); }); it('should error if initialize multiple trackers are missing trackingId', () => { ReactGA.initialize([{ gaOptions: { userId: 123 } }]); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'gaTrackingID is required in initialize()' ); expect(spies.ga).toHaveBeenCalledTimes(0); }); it('should abort, log warning if tracking ID is not given', () => { ReactGA.initialize(); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'gaTrackingID is required in initialize()' ); expect(spies.ga).toHaveBeenCalledTimes(0); }); }); <file_sep>import format from '../../src/utils/format'; describe('format()', () => { it('should not format when redactingEmail is false', () => { const titleCase = false; const redactingEmail = false; expect(format('<EMAIL>', titleCase, redactingEmail)).toEqual( '<EMAIL>' ); expect(format('<EMAIL>', titleCase, redactingEmail)).toEqual( '<EMAIL>' ); expect(format('<EMAIL>', titleCase, redactingEmail)).toEqual( '<EMAIL>' ); }); it('should not format email addresses', () => { const warnSpy = jest .spyOn(global.console, 'warn') .mockImplementation(() => {}); expect(warnSpy).toHaveBeenCalledTimes(0); expect(format('<EMAIL>')).toEqual( 'REDACTED (Potential Email Address)' ); expect(warnSpy).toHaveBeenCalledTimes(1); expect(format('<EMAIL>')).toEqual( 'REDACTED (Potential Email Address)' ); expect(warnSpy).toHaveBeenCalledTimes(2); expect(format('<EMAIL>')).toEqual( 'REDACTED (Potential Email Address)' ); expect(warnSpy).toHaveBeenCalledTimes(3); jest.restoreAllMocks(); }); it('should format non-email addresses', () => { expect(format('mystring')).toEqual('mystring'); expect(format('mystring', true)).toEqual('Mystring'); expect(format('foo bar')).toEqual('foo bar'); expect(format('foo bar', true)).toEqual('Foo Bar'); expect(format('foo_bar')).toEqual('foo_bar'); expect(format('foo_bar', true)).toEqual('Foo_bar'); expect(format('foo.bar')).toEqual('foo.bar'); expect(format('foo.bar', true)).toEqual('foo.bar'); expect(format('FOO_BAR')).toEqual('FOO_BAR'); expect(format('FOO_BAR', true)).toEqual('FOO_BAR'); expect(format('123456789')).toEqual('123456789'); expect(format('123456789', true)).toEqual('123456789'); expect(format('the quick brown fox')).toEqual('the quick brown fox'); expect(format('the quick brown fox', true)).toEqual('The Quick Brown Fox'); }); }); <file_sep>import * as ReactGA from '../../src'; jest.mock('../../src/utils/loadGA'); describe('set()', () => { const spies = {}; beforeEach(() => { spies.warn = jest .spyOn(global.console, 'warn') .mockImplementation(() => {}); spies.info = jest .spyOn(global.console, 'info') .mockImplementation(() => {}); spies.ga = jest.fn(); global.window.ga = spies.ga; }); afterEach(() => { jest.restoreAllMocks(); }); it('should output debug info, if debug is on', () => { ReactGA.initialize('foo', { debug: true }); ReactGA.set({ userId: 123 }); expect(spies.info).toHaveBeenCalledTimes(2); expect(spies.info).toHaveBeenNthCalledWith( 1, '[react-ga]', "called ga('set', fieldsObject);" ); expect(spies.info).toHaveBeenNthCalledWith( 2, '[react-ga]', 'with fieldsObject: {"userId":123}' ); }); it('should warn if fieldsObject object is missing', () => { ReactGA.initialize('foo'); ReactGA.set(); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', '`fieldsObject` is required in .set()' ); }); it('should warn if fieldsObject is not an Object', () => { ReactGA.initialize('foo'); ReactGA.set(123); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'Expected `fieldsObject` arg to be an Object' ); }); it('should warn if fieldsObject object is an empty object', () => { ReactGA.initialize('foo'); ReactGA.set({}); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'empty `fieldsObject` given to .set()' ); }); it('should set the field values', () => { ReactGA.initialize('foo'); ReactGA.set({ userId: 123 }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'set', { userId: 123 }); }); }); <file_sep>/** * React Google Analytics Module * * @package react-ga * @author <NAME> <<EMAIL>> * <NAME> <<EMAIL>> */ /** * Utilities */ import format from './utils/format'; import removeLeadingSlash from './utils/removeLeadingSlash'; import trim from './utils/trim'; import loadGA from './utils/loadGA'; import warn from './utils/console/warn'; import log from './utils/console/log'; import TestModeAPI from './utils/testModeAPI'; const _isNotBrowser = typeof window === 'undefined' || typeof document === 'undefined'; let _debug = false; let _titleCase = true; let _testMode = false; let _alwaysSendToDefaultTracker = true; let _redactEmail = true; const internalGa = (...args) => { if (_testMode) return TestModeAPI.ga(...args); if (_isNotBrowser) return false; if (!window.ga) return warn( 'ReactGA.initialize must be called first or GoogleAnalytics should be loaded manually' ); return window.ga(...args); }; function _format(s) { return format(s, _titleCase, _redactEmail); } function _gaCommand(trackerNames, ...args) { const command = args[0]; if (typeof internalGa === 'function') { if (typeof command !== 'string') { warn('ga command must be a string'); return; } if (_alwaysSendToDefaultTracker || !Array.isArray(trackerNames)) internalGa(...args); if (Array.isArray(trackerNames)) { trackerNames.forEach((name) => { internalGa(...[`${name}.${command}`].concat(args.slice(1))); }); } } } function _initialize(gaTrackingID, options) { if (!gaTrackingID) { warn('gaTrackingID is required in initialize()'); return; } if (options) { if (options.debug && options.debug === true) { _debug = true; } if (options.titleCase === false) { _titleCase = false; } if (options.redactEmail === false) { _redactEmail = false; } if (options.useExistingGa) { return; } } if (options && options.gaOptions) { internalGa('create', gaTrackingID, options.gaOptions); } else { internalGa('create', gaTrackingID, 'auto'); } } export function addTrackers(configsOrTrackingId, options) { if (Array.isArray(configsOrTrackingId)) { configsOrTrackingId.forEach((config) => { if (typeof config !== 'object') { warn('All configs must be an object'); return; } _initialize(config.trackingId, config); }); } else { _initialize(configsOrTrackingId, options); } return true; } export function initialize(configsOrTrackingId, options) { if (options && options.testMode === true) { _testMode = true; } else { if (_isNotBrowser) { return; } if (!options || options.standardImplementation !== true) loadGA(options); } _alwaysSendToDefaultTracker = options && typeof options.alwaysSendToDefaultTracker === 'boolean' ? options.alwaysSendToDefaultTracker : true; addTrackers(configsOrTrackingId, options); } /** * ga: * Returns the original GA object. */ export function ga(...args) { if (args.length > 0) { internalGa(...args); if (_debug) { log("called ga('arguments');"); log(`with arguments: ${JSON.stringify(args)}`); } } return window.ga; } /** * set: * GA tracker set method * @param {Object} fieldsObject - a field/value pair or a group of field/value pairs on the tracker * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on */ export function set(fieldsObject, trackerNames) { if (!fieldsObject) { warn('`fieldsObject` is required in .set()'); return; } if (typeof fieldsObject !== 'object') { warn('Expected `fieldsObject` arg to be an Object'); return; } if (Object.keys(fieldsObject).length === 0) { warn('empty `fieldsObject` given to .set()'); } _gaCommand(trackerNames, 'set', fieldsObject); if (_debug) { log("called ga('set', fieldsObject);"); log(`with fieldsObject: ${JSON.stringify(fieldsObject)}`); } } /** * send: * Clone of the low level `ga.send` method * WARNING: No validations will be applied to this * @param {Object} fieldObject - field object for tracking different analytics * @param {Array} trackerNames - trackers to send the command to * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on */ export function send(fieldObject, trackerNames) { _gaCommand(trackerNames, 'send', fieldObject); if (_debug) { log("called ga('send', fieldObject);"); log(`with fieldObject: ${JSON.stringify(fieldObject)}`); log(`with trackers: ${JSON.stringify(trackerNames)}`); } } /** * pageview: * Basic GA pageview tracking * @param {String} path - the current page page e.g. '/about' * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on * @param {String} title - (optional) the page title e. g. 'My Website' */ export function pageview(rawPath, trackerNames, title) { if (!rawPath) { warn('path is required in .pageview()'); return; } const path = trim(rawPath); if (path === '') { warn('path cannot be an empty string in .pageview()'); return; } const extraFields = {}; if (title) { extraFields.title = title; } if (typeof ga === 'function') { _gaCommand(trackerNames, 'send', { hitType: 'pageview', page: path, ...extraFields }); if (_debug) { log("called ga('send', 'pageview', path);"); let extraLog = ''; if (title) { extraLog = ` and title: ${title}`; } log(`with path: ${path}${extraLog}`); } } } /** * modalview: * a proxy to basic GA pageview tracking to consistently track * modal views that are an equivalent UX to a traditional pageview * @param {String} modalName e.g. 'add-or-edit-club' * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on */ export function modalview(rawModalName, trackerNames) { if (!rawModalName) { warn('modalName is required in .modalview(modalName)'); return; } const modalName = removeLeadingSlash(trim(rawModalName)); if (modalName === '') { warn('modalName cannot be an empty string or a single / in .modalview()'); return; } if (typeof ga === 'function') { const path = `/modal/${modalName}`; _gaCommand(trackerNames, 'send', 'pageview', path); if (_debug) { log("called ga('send', 'pageview', path);"); log(`with path: ${path}`); } } } /** * timing: * GA timing * @param args.category {String} required * @param args.variable {String} required * @param args.value {Int} required * @param args.label {String} required * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on */ export function timing( { category, variable, value, label } = {}, trackerNames = undefined ) { if (typeof ga === 'function') { if (!category || !variable || typeof value !== 'number') { warn( 'args.category, args.variable ' + 'AND args.value are required in timing() ' + 'AND args.value has to be a number' ); return; } // Required Fields const fieldObject = { hitType: 'timing', timingCategory: _format(category), timingVar: _format(variable), timingValue: value }; if (label) { fieldObject.timingLabel = _format(label); } send(fieldObject, trackerNames); } } /** * event: * GA event tracking * @param args.category {String} required * @param args.action {String} required * @param args.label {String} optional * @param args.value {Int} optional * @param args.nonInteraction {boolean} optional * @param args.transport {string} optional * @param {{action: string, category: string}} trackerNames - (optional) a list of extra trackers to run the command on */ export function event( { category, action, label, value, nonInteraction, transport, ...args } = {}, trackerNames = undefined ) { if (typeof ga === 'function') { // Simple Validation if (!category || !action) { warn('args.category AND args.action are required in event()'); return; } // Required Fields const fieldObject = { hitType: 'event', eventCategory: _format(category), eventAction: _format(action) }; // Optional Fields if (label) { fieldObject.eventLabel = _format(label); } if (typeof value !== 'undefined') { if (typeof value !== 'number') { warn('Expected `args.value` arg to be a Number.'); } else { fieldObject.eventValue = value; } } if (typeof nonInteraction !== 'undefined') { if (typeof nonInteraction !== 'boolean') { warn('`args.nonInteraction` must be a boolean.'); } else { fieldObject.nonInteraction = nonInteraction; } } if (typeof transport !== 'undefined') { if (typeof transport !== 'string') { warn('`args.transport` must be a string.'); } else { if (['beacon', 'xhr', 'image'].indexOf(transport) === -1) { warn( '`args.transport` must be either one of these values: `beacon`, `xhr` or `image`' ); } fieldObject.transport = transport; } } Object.keys(args) .filter((key) => key.substr(0, 'dimension'.length) === 'dimension') .forEach((key) => { fieldObject[key] = args[key]; }); Object.keys(args) .filter((key) => key.substr(0, 'metric'.length) === 'metric') .forEach((key) => { fieldObject[key] = args[key]; }); // Send to GA send(fieldObject, trackerNames); } } /** * exception: * GA exception tracking * @param args.description {String} optional * @param args.fatal {boolean} optional * @param {Array} trackerNames - (optional) a list of extra trackers to run the command on */ export function exception({ description, fatal }, trackerNames) { if (typeof ga === 'function') { // Required Fields const fieldObject = { hitType: 'exception' }; // Optional Fields if (description) { fieldObject.exDescription = _format(description); } if (typeof fatal !== 'undefined') { if (typeof fatal !== 'boolean') { warn('`args.fatal` must be a boolean.'); } else { fieldObject.exFatal = fatal; } } // Send to GA send(fieldObject, trackerNames); } } export const plugin = { /** * require: * GA requires a plugin * @param name {String} e.g. 'ecommerce' or 'myplugin' * @param options {Object} optional e.g {path: '/log', debug: true} * @param trackerName {String} optional e.g 'trackerName' */ require: (rawName, options, trackerName) => { if (typeof ga === 'function') { // Required Fields if (!rawName) { warn('`name` is required in .require()'); return; } const name = trim(rawName); if (name === '') { warn('`name` cannot be an empty string in .require()'); return; } const requireString = trackerName ? `${trackerName}.require` : 'require'; // Optional Fields if (options) { if (typeof options !== 'object') { warn('Expected `options` arg to be an Object'); return; } if (Object.keys(options).length === 0) { warn('Empty `options` given to .require()'); } ga(requireString, name, options); if (_debug) { log(`called ga('require', '${name}', ${JSON.stringify(options)}`); } } else { ga(requireString, name); if (_debug) { log(`called ga('require', '${name}');`); } } } }, /** * execute: * GA execute action for plugin * Takes variable number of arguments * @param pluginName {String} e.g. 'ecommerce' or 'myplugin' * @param action {String} e.g. 'addItem' or 'myCustomAction' * @param actionType {String} optional e.g. 'detail' * @param payload {Object} optional e.g { id: '1x5e', name : 'My product to track' } */ execute: (pluginName, action, ...args) => { let payload; let actionType; if (args.length === 1) { [payload] = args; } else { [actionType, payload] = args; } if (typeof ga === 'function') { if (typeof pluginName !== 'string') { warn('Expected `pluginName` arg to be a String.'); } else if (typeof action !== 'string') { warn('Expected `action` arg to be a String.'); } else { const command = `${pluginName}:${action}`; payload = payload || null; if (actionType && payload) { ga(command, actionType, payload); if (_debug) { log(`called ga('${command}');`); log( `actionType: "${actionType}" with payload: ${JSON.stringify( payload )}` ); } } else if (payload) { ga(command, payload); if (_debug) { log(`called ga('${command}');`); log(`with payload: ${JSON.stringify(payload)}`); } } else { ga(command); if (_debug) { log(`called ga('${command}');`); } } } } } }; /** * outboundLink: * GA outboundLink tracking * @param args.label {String} e.g. url, or 'Create an Account' * @param {function} hitCallback - Called after processing a hit. */ export function outboundLink(args, hitCallback, trackerNames) { if (typeof hitCallback !== 'function') { warn('hitCallback function is required'); return; } if (typeof ga === 'function') { // Simple Validation if (!args || !args.label) { warn('args.label is required in outboundLink()'); return; } // Required Fields const fieldObject = { hitType: 'event', eventCategory: 'Outbound', eventAction: 'Click', eventLabel: _format(args.label) }; let safetyCallbackCalled = false; const safetyCallback = () => { // This prevents a delayed response from GA // causing hitCallback from being fired twice safetyCallbackCalled = true; hitCallback(); }; // Using a timeout to ensure the execution of critical application code // in the case when the GA server might be down // or an ad blocker prevents sending the data // register safety net timeout: const t = setTimeout(safetyCallback, 250); const clearableCallbackForGA = () => { clearTimeout(t); if (!safetyCallbackCalled) { hitCallback(); } }; fieldObject.hitCallback = clearableCallbackForGA; // Send to GA send(fieldObject, trackerNames); } else { // if ga is not defined, return the callback so the application // continues to work as expected setTimeout(hitCallback, 0); } } export const testModeAPI = TestModeAPI; export default { initialize, ga, set, send, pageview, modalview, timing, event, exception, plugin, outboundLink, testModeAPI: TestModeAPI }; <file_sep>import mightBeEmail from '../../src/utils/mightBeEmail'; describe('mightBeEmail()', () => { it('should return `true` for possible emails', () => { expect(mightBeEmail('<EMAIL>')).toEqual(true); expect(mightBeEmail('<EMAIL>')).toEqual(true); expect(mightBeEmail('<EMAIL>')).toEqual(true); }); it('should return `false` for non-emails', () => { expect(mightBeEmail('<NAME>')).toEqual(false); expect(mightBeEmail('123456789')).toEqual(false); expect(mightBeEmail('foo')).toEqual(false); expect( mightBeEmail('The quick brown fox jumps over the lazy dog.') ).toEqual(false); }); }); <file_sep>import * as ReactGA from '../../src'; jest.mock('../../src/utils/loadGA'); describe('send()', () => { const spies = {}; beforeEach(() => { spies.warn = jest .spyOn(global.console, 'warn') .mockImplementation(() => {}); spies.info = jest .spyOn(global.console, 'info') .mockImplementation(() => {}); spies.ga = jest.fn(); global.window.ga = spies.ga; }); afterEach(() => { jest.restoreAllMocks(); }); it('should record a pageview using send', () => { ReactGA.initialize('foo'); ReactGA.send({ hitType: 'pageview', page: '/valid' }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { hitType: 'pageview', page: '/valid' }); }); it('should record an event using send', () => { ReactGA.initialize('foo'); ReactGA.send({ hitType: 'event', eventCategory: 'category', eventAction: 'action' }); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { hitType: 'event', eventCategory: 'category', eventAction: 'action' }); }); it('should send to multiple trackers', () => { ReactGA.initialize([ { trackingId: 'foo', gaOptions: { userId: 123 } }, { trackingId: 'bar', gaOptions: { name: 'baz' } } ]); ReactGA.send( { hitType: 'event', eventCategory: 'category', eventAction: 'action' }, ['baz'] ); expect(spies.ga).toHaveBeenCalledTimes(4); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', { userId: 123 }); expect(spies.ga).toHaveBeenNthCalledWith(2, 'create', 'bar', { name: 'baz' }); expect(spies.ga).toHaveBeenNthCalledWith(3, 'send', { hitType: 'event', eventCategory: 'category', eventAction: 'action' }); expect(spies.ga).toHaveBeenNthCalledWith(4, 'baz.send', { hitType: 'event', eventCategory: 'category', eventAction: 'action' }); }); it('should send to default', () => { ReactGA.initialize( [ { trackingId: 'foo', gaOptions: { userId: 123 } }, { trackingId: 'bar', gaOptions: { name: 'baz' } } ], { alwaysSendToDefaultTracker: false } ); ReactGA.send( { hitType: 'event', eventCategory: 'category', eventAction: 'action' }, ['baz'] ); expect(spies.ga).toHaveBeenCalledTimes(3); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', { userId: 123 }); expect(spies.ga).toHaveBeenNthCalledWith(2, 'create', 'bar', { name: 'baz' }); expect(spies.ga).toHaveBeenNthCalledWith(3, 'baz.send', { hitType: 'event', eventCategory: 'category', eventAction: 'action' }); }); it('should ignore the alwaysSendToDefaultTracker flag when no trackerNames are specified', () => { ReactGA.initialize( [ { trackingId: 'foo', gaOptions: { userId: 123 } }, { trackingId: 'bar', gaOptions: { name: 'baz' } } ], { alwaysSendToDefaultTracker: false } ); ReactGA.send({ hitType: 'event', eventCategory: 'category', eventAction: 'action' }); expect(spies.ga).toHaveBeenCalledTimes(3); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', { userId: 123 }); expect(spies.ga).toHaveBeenNthCalledWith(2, 'create', 'bar', { name: 'baz' }); expect(spies.ga).toHaveBeenNthCalledWith(3, 'send', { hitType: 'event', eventCategory: 'category', eventAction: 'action' }); }); }); <file_sep>module.exports = { parser: '@babel/eslint-parser', extends: ['airbnb', 'prettier', 'plugin:jest/recommended'], plugins: ['prettier', 'jest'], env: { browser: true }, rules: { 'prettier/prettier': 'error', 'react/no-find-dom-node': 'off', 'arrow-body-style': 'off', 'no-mixed-operators': 'off', 'no-shadow': ['error', { allow: ['err', 'error'] }], 'react/prefer-stateless-function': [ 'error', { ignorePureComponents: true } ], 'no-console': ['error', { allow: ['warn', 'error', 'info'] }], 'no-underscore-dangle': 'off', 'guard-for-in': 'off', 'no-param-reassign': ['error', { props: false }], 'jsx-a11y/label-has-associated-control': 'off', 'jsx-a11y/control-has-associated-control': 'off', 'react/jsx-curly-brace-presence': 'off', 'react/jsx-one-expression-per-line': 'off', 'react/jsx-props-no-spreading': 'off' }, overrides: [ { files: ['demo/**/*', 'src/components/*.js'], rules: { 'import/no-extraneous-dependencies': [ 'error', { devDependencies: true } ], 'import/no-named-as-default-member': 'off', 'react/no-array-index-key': 'off', 'react/jsx-no-bind': 'off', 'react/prop-types': 'off' } }, { files: ['test/**/*'], env: { browser: true, node: true, 'jest/globals': true }, rules: { 'import/no-extraneous-dependencies': [ 'error', { devDependencies: true } ] } } ] }; <file_sep>import toTitleCase from '../../src/utils/toTitleCase'; describe('toTitleCase()', () => { // Tests taken from https://github.com/gouch/to-title-case/blob/master/test/tests.json it('should convert correctly to title case', () => { expect(toTitleCase('follow step-by-step instructions')).toEqual( 'Follow Step-by-Step Instructions' ); expect(toTitleCase('this sub-phrase is nice')).toEqual( 'This Sub-Phrase Is Nice' ); expect(toTitleCase('catchy title: a subtitle')).toEqual( 'Catchy Title: A Subtitle' ); expect(toTitleCase("catchy title: 'a quoted subtitle'")).toEqual( "Catchy Title: 'A Quoted Subtitle'" ); expect(toTitleCase('catchy title: "\'a twice quoted subtitle\'"')).toEqual( 'Catchy Title: "\'A Twice Quoted Subtitle\'"' ); expect(toTitleCase("'a title inside double quotes'")).toEqual( "'A Title Inside Double Quotes'" ); expect(toTitleCase('all words capitalized')).toEqual( 'All Words Capitalized' ); expect(toTitleCase('small words are for by and of lowercase')).toEqual( 'Small Words Are for by and of Lowercase' ); expect(toTitleCase('a small word starts')).toEqual('A Small Word Starts'); expect(toTitleCase('a small word it ends on')).toEqual( 'A Small Word It Ends On' ); expect(toTitleCase('do questions work?')).toEqual('Do Questions Work?'); expect(toTitleCase('multiple sentences. more than one.')).toEqual( 'Multiple Sentences. More Than One.' ); expect(toTitleCase('Ends with small word of')).toEqual( 'Ends With Small Word Of' ); expect(toTitleCase("double quoted 'inner' word")).toEqual( "Double Quoted 'Inner' Word" ); expect(toTitleCase("single quoted 'inner' word")).toEqual( "Single Quoted 'Inner' Word" ); expect(toTitleCase('fancy double quoted "inner" word')).toEqual( 'Fancy Double Quoted "Inner" Word' ); expect(toTitleCase("fancy single quoted 'inner' word")).toEqual( "Fancy Single Quoted 'Inner' Word" ); expect(toTitleCase('this vs. that')).toEqual('This vs. That'); expect(toTitleCase('this vs that')).toEqual('This vs That'); expect(toTitleCase('this v. that')).toEqual('This v. That'); expect(toTitleCase('this v that')).toEqual('This v That'); expect(toTitleCase('address <EMAIL> titles')).toEqual( 'Address <EMAIL> Titles' ); expect(toTitleCase('pass camelCase through')).toEqual( 'Pass camelCase Through' ); expect(toTitleCase("don't break")).toEqual("Don't Break"); expect(toTitleCase('catchy title: substance subtitle')).toEqual( 'Catchy Title: Substance Subtitle' ); expect(toTitleCase('we keep NASA capitalized')).toEqual( 'We Keep NASA Capitalized' ); expect(toTitleCase('leave Q&A unscathed')).toEqual('Leave Q&A Unscathed'); expect( toTitleCase('<NAME> and TheStreet.com’s million iPhone la-la land') ).toEqual('<NAME> and TheStreet.com’s Million iPhone La-La Land'); expect(toTitleCase('you have a http://example.com/foo/ title')).toEqual( 'You Have a http://example.com/foo/ Title' ); expect(toTitleCase('your hair[cut] looks (nice)')).toEqual( 'Your Hair[cut] Looks (Nice)' ); expect(toTitleCase('keep that colo(u)r')).toEqual('Keep That Colo(u)r'); expect(toTitleCase('have you read "The Lottery"?')).toEqual( 'Have You Read "The Lottery"?' ); expect( toTitleCase( 'Read markdown_rules.txt to find out how _underscores around words_ will be interpreted' ) ).toEqual( 'Read markdown_rules.txt to Find Out How _Underscores Around Words_ Will Be Interpreted' ); expect( toTitleCase( 'Read markdown_rules.txt to find out how *asterisks around words* will be interpreted' ) ).toEqual( 'Read markdown_rules.txt to Find Out How *Asterisks Around Words* Will Be Interpreted' ); expect( toTitleCase( 'Notes and observations regarding Apple’s announcements from ‘The Beat Goes On’ special event' ) ).toEqual( 'Notes and Observations Regarding Apple’s Announcements From ‘The Beat Goes On’ Special Event' ); expect( toTitleCase('Drink this piña colada while you listen to ænima') ).toEqual('Drink This Piña Colada While You Listen to Ænima'); expect(toTitleCase('capitalize hyphenated words on-demand')).toEqual( 'Capitalize Hyphenated Words On-Demand' ); expect(toTitleCase('take them on: special lower cases')).toEqual( 'Take Them On: Special Lower Cases' ); }); }); <file_sep>const path = require('path'); const TerserPlugin = require('terser-webpack-plugin'); const pkg = require('./package.json'); module.exports = { entry: { 'react-ga': './src/index.js', 'react-ga.min': './src/index.js', 'react-ga-core': './src/core.js', 'react-ga-core.min': './src/core.js' }, output: { path: path.resolve('./dist'), filename: '[name].js', libraryTarget: 'umd', globalObject: "typeof self !== 'undefined' ? self : this" // temporary fix for https://github.com/webpack/webpack/issues/6525 }, externals: [] .concat(Object.keys(pkg.peerDependencies || {})) .concat(Object.keys(pkg.dependencies || {})) .concat(Object.keys(pkg.devDependencies || {})), module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ } ] }, optimization: { minimizer: [ new TerserPlugin({ include: /\.min\.js$/ }) ] } }; <file_sep># react-ga ### React Google Analytics Module [![Build Status](https://img.shields.io/travis/react-ga/react-ga/master.svg?style=flat-square)](https://travis-ci.org/react-ga/react-ga) [![npm version](https://img.shields.io/npm/v/react-ga.svg?style=flat-square)](https://www.npmjs.com/package/react-ga) [![npm downloads](https://img.shields.io/npm/dm/react-ga.svg?style=flat-square)](https://www.npmjs.com/package/react-ga) This is a JavaScript module that can be used to include Google Analytics tracking code in a website or app that uses [React](https://facebook.github.io/react/) for its front-end codebase. It does not currently use any React code internally, but has been written for use with a number of Mozilla Foundation websites that are using React, as a way to standardize our GA Instrumentation across projects. It is designed to work with [Universal Analytics](https://support.google.com/analytics/answer/2790010) and will not support the older `ga.js` implementation. This module is mildly opinionated in how we instrument tracking within our front-end code. Our API is slightly more verbose than the core Google Analytics library, in the hope that the code is easier to read and understand for our engineers. See examples below. If you use `react-ga` too, we'd love your feedback. Feel free to file [issues, ideas and pull requests against this repo](https://github.com/react-ga/react-ga/issues). ## Installation With [npm](https://www.npmjs.com/): ```bash npm install react-ga --save ``` With [bower](http://bower.io/): ```bash bower install react-ga --save ``` Note that [React](https://github.com/facebook/react) >= 0.14.0 is needed in order to use the `<OutboundLink>` component. ## Usage ### With npm Initializing GA and Tracking Pageviews: ```js import ReactGA from 'react-ga'; ReactGA.initialize('UA-000000-01'); ReactGA.pageview(window.location.pathname + window.location.search); ``` ### With bower When included as a script tag, a variable `ReactGA` is exposed in the global scope. ```js <!-- The core React library --> <script src="https://unpkg.com/react@15.5.0/dist/react.min.js"></script> <!-- The ReactDOM Library --> <script src="https://unpkg.com/react-dom@15.5.0/dist/react-dom.min.js"></script> <!-- ReactGA library --> <script src="/path/to/bower_components/react-ga/dist/react-ga.min.js"></script> <script> ReactGA.initialize('UA-000000-01', { debug: true }); </script> ``` ### Demo Code For a working demo have a look at the [demo files](/demo) or clone this repo and run `npm install` `npm start` then open http://localhost:8080 and follow the instructions. Demo requires you to have your own TrackingID. ## Upgrading from `1.x` to `2.x` You can safely upgrade to `2.x` as there are no breaking changes. The main new feature is that the underlying `ga` function is now exposed via the property `ReactGA.ga`. This can be helpful when you need a function that `ReactGA` doesn't support at the moment. Also, for that reason, it is recommended that you rename your imported value as `ReactGA` rather than `ga` so as to distinguish between the React GA wrapper and the original `ga` function. ## Community Components While some convenience components are included inside the package, some are specific to each application. A community curated list of these is available in the wiki: https://github.com/react-ga/react-ga/wiki/Community-Components. Feel free to add any you have found useful. ## API #### ReactGA.initialize(gaTrackingID, options) GA must be initialized using this function before any of the other tracking functions will record any data. The values are checked and sent through to the `ga('create', ...` call. If you aren't getting any data back from Page Timings, you may have to add `siteSpeedSampleRate: 100` to the `gaOptions` object. This will send 100% of hits to Google Analytics. By default only 1% are sent. ###### Example ```js ReactGA.initialize('UA-000000-01', { debug: true, titleCase: false, gaOptions: { userId: 123 } }); ``` Or with multiple trackers ```js ReactGA.initialize( [ { trackingId: 'UA-000000-01', gaOptions: { name: 'tracker1', userId: 123 } }, { trackingId: 'UA-000000-02', gaOptions: { name: 'tracker2' } } ], { debug: true, alwaysSendToDefaultTracker: false } ); ``` | Value | Notes | | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | gaTrackingID | `String`. Required. GA Tracking ID like `UA-000000-01`. | | options.debug | `Boolean`. Optional. If set to `true`, will output additional feedback to the console. | | options.titleCase | `Boolean`. Optional. Defaults to `true`. If set to `false`, strings will not be converted to title case before sending to GA. | | options.gaOptions | `Object`. Optional. [GA configurable create only fields.](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference) | | options.gaAddress | `String`. Optional. If you are self-hosting your `analytics.js`, you can specify the URL for it here. | | options.alwaysSendToDefaultTracker | `Boolean`. Optional. Defaults to `true`. If set to `false` _and_ using multiple trackers, the event will not be send to the default tracker. | | options.testMode | `Boolean`. Optional. Defaults to `false`. Enables test mode. See [here](https://github.com/react-ga/react-ga#test-mode) for more information. | | options.standardImplementation | `Boolean`. Optional. Defaults to `false`. Enables loading GA as google expects it. See [here](https://github.com/react-ga/react-ga#standard-implementation) for more information. | | options.useExistingGa | `Boolean`. Optional. Skips call to `window.ga()`, assuming you have manually run it. | | options.redactEmail | `Boolean`. Optional. Defaults to `true`. Enables redacting a email as the string that in "Event Category" and "Event Action". | If you are having additional troubles and setting `debug = true` shows as working please try using the [Chrome GA Debugger Extension](https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna). This will help you figure out if your implementation is off or your GA Settings are not correct. #### ReactGA.set(fieldsObject) This will set the values of [custom dimensions](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#dimension) in Google Analytics. ###### Example ```js ReactGA.set({ dimension14: 'Sports' }); ``` Or with multiple trackers ```js ReactGA.set({ userId: 123 }, ['tracker2']); ``` | Value | Notes | | ------------ | ----------------------------------------------------------------- | | fieldsObject | `Object`. e.g. `{ userId: 123 }` | | trackerNames | `Array`. Optional. A list of extra trackers to run the command on | #### ReactGA.pageview(path) ###### Example ```js ReactGA.pageview('/about/contact-us'); ``` Or with multiple trackers ```js ReactGA.pageview('/about/contact-us', ['tracker2']); ``` This will send all the named trackers listed in the array parameter. The default tracker will or will not send according to the `initialize()` setting `alwaysSendToDefaultTracker` (defaults to `true` if not provided). | Value | Notes | | ------------ | ----------------------------------------------------------------- | | path | `String`. e.g. '/get-involved/other-ways-to-help' | | trackerNames | `Array`. Optional. A list of extra trackers to run the command on | | title | `String`. Optional. e.g. 'Other Ways to Help' | See example above for use with `react-router`. #### ReactGA.modalview(modalName) A modal view is often an equivalent to a pageview in our UX, but without a change in URL that would record a standard GA pageview. For example, a 'contact us' modal may be accessible from any page in a site, even if we don't have a standalone 'contact us' page on its own URL. In this scenario, the modalview should be recorded using this function. ###### Example ```js ReactGA.modalview('/about/contact-us'); ``` | Value | Notes | | --------- | --------------------------------------------------- | | modalName | `String`. E.g. 'login', 'read-terms-and-conditions' | #### ReactGA.event(args) Tracking in-page `event` interactions is key to understanding the use of any interactive web property. This is how we record user interactions that don't trigger a change in URL. ###### Examples ```js ReactGA.event({ category: 'User', action: 'Created an Account' }); ReactGA.event({ category: 'Social', action: 'Rated an App', value: 3 }); ReactGA.event({ category: 'Editing', action: 'Deleted Component', label: 'Game Widget' }); ReactGA.event({ category: 'Promotion', action: 'Displayed Promotional Widget', label: 'Homepage Thing', nonInteraction: true }); ``` | Value | Notes | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | args.category | `String`. Required. A top level category for these events. E.g. 'User', 'Navigation', 'App Editing', etc. | | args.action | `String`. Required. A description of the behaviour. E.g. 'Clicked Delete', 'Added a component', 'Deleted account', etc. | | args.label | `String`. Optional. More precise labelling of the related action. E.g. alongside the 'Added a component' action, we could add the name of a component as the label. E.g. 'Survey', 'Heading', 'Button', etc. | | args.value | `Int`. Optional. A means of recording a numerical value against an event. E.g. a rating, a score, etc. | | args.nonInteraction | `Boolean`. Optional. If an event is not triggered by a user interaction, but instead by our code (e.g. on page load), it should be flagged as a `nonInteraction` event to avoid skewing bounce rate data. | | args.transport | `String`. Optional. This specifies the transport mechanism with which hits will be sent. Valid values include 'beacon', 'xhr', or 'image'. | #### ReactGA.timing(args) Allow to measure periods of time such as AJAX requests and resources loading by sending hits using the analytics.js library. For more detailed description, please refer to https://developers.google.com/analytics/devguides/collection/analyticsjs/user-timings. ###### Example Usage: ```js ReactGA.timing({ category: 'JS Libraries', variable: 'load', value: 20, // in milliseconds label: 'CDN libs' }); ``` This is equivalent to the following Google Analytics command: ```js ga('send', 'timing', 'JS Libraries', 'load', 20, 'CDN libs'); ``` | Value | Notes | | ------------- | ------------------------------------------------------------------------------------------------- | | args.category | `String`. Required. A string for categorizing all user timing variables into logical groups. | | args.variable | `String`. Required. Name of the variable being recorded. | | args.value | `Int`. Required. Number of milliseconds elapsed time to report. | | args.label | `String`. Optional. It can be used to add flexibility in visualizing user timings in the reports. | #### ReactGA.ga() The original `ga` function can be accessed via this method. This gives developers the flexibility of directly using `ga.js` features that have not yet been implemented in `ReactGA`. No validations will be done by `ReactGA` as it is being bypassed if this approach is used. If no arguments are passed to `ReactGA.ga()`, the `ga` object is returned instead. ###### Example Usage with arguments: ```js ReactGA.ga('send', 'pageview', '/mypage'); ``` Usage without arguments: ```js var ga = ReactGA.ga(); ga('send', 'pageview', '/mypage'); ``` #### ReactGA.outboundLink(args, hitCallback) Tracking links out to external URLs (including id.webmaker.org for OAuth 2.0 login flow). A declarative approach is found in the next section, by using an `<OutboundLink>` component. ###### Example ```js ReactGA.outboundLink( { label: 'Clicked Create an Account' }, function () { console.log('redirect here'); }, ['tracker2'] ); ``` | Value | Notes | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | args.label | `String`. Required. Description of where the outbound link points to. Either as a URL, or a string. | | hitCallback | `function`. The react-ga implementation accounts for the possibility that GA servers are down, or GA is blocked, by using a fallback 250ms timeout. See [notes in GA Dev Guide](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#hitCallback) | | trackerNames | `Array<String>` Optional. A list of extra trackers to run the command on. | ### `<OutboundLink>` Component Outbound links can directly be used as a component in your React code and the event label will be sent directly to ReactGA. ###### Example ```js var ReactGA = require('react-ga'); render() { return ( <div> <ReactGA.OutboundLink eventLabel="myLabel" to="http://www.example.com" target="_blank" trackerNames={['tracker2']} > My Link </ReactGA.OutboundLink> </div> ); } ``` | Value | Notes | | ------------ | --------------------------------------------------------------------------------------------------- | | eventLabel | `String`. Required. Description of where the outbound link points to. Either as a URL, or a string. | | to | `String`. Required. URL the link leads to. | | target | `String`. Optional. To open the link in a new tab, use a value of `_blank`. | | trackerNames | `Array<String>` Optional. A list of extra trackers to run the command on. | For bower, use the `<ReactGA.OutboundLink>` component. #### ReactGA.exception(args) [GA exception tracking](https://developers.google.com/analytics/devguides/collection/analyticsjs/exceptions) ###### Example ```js ReactGA.exception({ description: 'An error occurred', fatal: true }); ``` | Value | Notes | | ---------------- | -------------------------------------------------------------- | | args.description | `String`. Optional. Description of what happened. | | args.fatal | `boolean`. Optional. Set to `true` if it was a fatal exception. | #### ReactGA.plugin.require(name, [options]) Require GA plugins. ###### Example ```js ReactGA.plugin.require('localHitSender', { path: '/log', debug: true }); ``` | Value | Notes | | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | name | `String`. Required. The name of the plugin to be required. Note: if the plugin is not an official analytics.js plugin, it must be provided elsewhere on the page. | | options | `Object`. Optional. An initialization object that will be passed to the plugin constructor upon instantiation. | #### ReactGA.plugin.execute(pluginName, action, [actionType], [payload]) Execute the `action` for the `pluginName` with the payload. ###### Example ```js ReactGA.plugin.execute('ecommerce', 'addTransaction', { id: 'jd38je31j', revenue: '3.50' }); ``` You can use this function with four arguments to pass `actionType` and `payload` along with executed action ###### Example ```js ReactGA.plugin.execute('ec', 'setAction', 'purchase', { id: 'jd38je31j', revenue: '3.50' }); ``` ### Test Mode To enable test mode, initialize ReactGA with the `testMode: true` option. Here's an example from `tests/utils/testMode.test.js` ```js // This should be part of your setup ReactGA.initialize('foo', { testMode: true }); // This would be in the component/js you are testing ReactGA.ga('send', 'pageview', '/mypage'); // This would be how you check that the calls are made correctly expect(ReactGA.testModeAPI.calls).toEqual([ ['create', 'foo', 'auto'], ['send', 'pageview', '/mypage'] ]); ``` ### Standard Implementation To enable standard implemention of google analytics. Add this script to your html ```html <!-- Google Analytics --> <script> (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; (i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments); }), (i[r].l = 1 * new Date()); (a = s.createElement(o)), (m = s.getElementsByTagName(o)[0]); a.async = 1; a.src = g; m.parentNode.insertBefore(a, m); })( window, document, 'script', '<%=htmlWebpackPlugin.options.analyticsURL%>', 'ga' ); ga('create', 'UA-XXX-X', 'auto'); ga('send', 'pageview'); </script> <!-- End Google Analytics --> ``` Initialize ReactGA with `standardImplementation: true` option. ```js // This should be part of your setup ReactGA.initialize('UA-XXX-X', { standardImplementation: true }); ``` --- ## Development ### Prerequisites - node.js - npm - `npm install` - `npm install react@^15.6.1 prop-types@^15.5.10` - This is for the optional dependencies. ### To Test ```bash npm test ``` ### Submitting changes/fixes Follow instructions inside [CONTRIBUTING.md](https://github.com/react-ga/react-ga/blob/master/CONTRIBUTING.md) --- #### Acknowledgements - Quite a lot of the code in this repo, came from [webmaker-analytics](https://github.com/mozilla/webmaker-analytics). <file_sep>// eslint-disable-next-line const index = require('./dist/react-ga-core.js'); module.exports = index.default; <file_sep>import removeLeadingSlash from '../../src/utils/removeLeadingSlash'; describe('removeLeadingSlash()', () => { it('should remove leading slashes', () => { expect(removeLeadingSlash('/mymodal')).toEqual('mymodal'); expect(removeLeadingSlash('/mymodal/is/awesome')).toEqual( 'mymodal/is/awesome' ); }); it('should not modify the string if there is no leading slash', () => { expect(removeLeadingSlash('mymodal')).toEqual('mymodal'); expect(removeLeadingSlash('mymodal/is/awesome')).toEqual( 'mymodal/is/awesome' ); }); }); <file_sep>import * as ReactGA from '../../src'; jest.mock('../../src/utils/loadGA'); describe('pageview()', () => { const spies = {}; beforeEach(() => { spies.warn = jest .spyOn(global.console, 'warn') .mockImplementation(() => {}); spies.info = jest .spyOn(global.console, 'info') .mockImplementation(() => {}); spies.ga = jest.fn(); global.window.ga = spies.ga; }); afterEach(() => { jest.restoreAllMocks(); }); it('should output debug info, if debug is on', () => { const options = { debug: true }; ReactGA.initialize('foo', options); ReactGA.pageview('/valid'); expect(spies.info).toHaveBeenCalledTimes(2); expect(spies.info).toHaveBeenNthCalledWith( 1, '[react-ga]', "called ga('send', 'pageview', path);" ); expect(spies.info).toHaveBeenNthCalledWith( 2, '[react-ga]', 'with path: /valid' ); }); it('should record a pageview', () => { ReactGA.initialize('foo'); ReactGA.pageview('/valid'); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { hitType: 'pageview', page: '/valid' }); }); it('should pass an optional title', () => { ReactGA.initialize('foo'); ReactGA.pageview('/valid', null, 'Title'); expect(spies.ga).toHaveBeenCalledTimes(2); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'send', { hitType: 'pageview', page: '/valid', title: 'Title' }); }); it('should record a pageview with multiple trackers', () => { ReactGA.initialize([ { trackingId: 'foo' }, { trackingId: 'bar', gaOptions: { name: 'baz' } } ]); ReactGA.pageview('/valid', ['baz']); expect(spies.ga).toHaveBeenCalledTimes(4); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'create', 'bar', { name: 'baz' }); expect(spies.ga).toHaveBeenNthCalledWith(3, 'send', { hitType: 'pageview', page: '/valid' }); expect(spies.ga).toHaveBeenNthCalledWith(4, 'baz.send', { hitType: 'pageview', page: '/valid' }); }); it('should record a pageview with multiple trackers, except default', () => { ReactGA.initialize( [ { trackingId: 'foo' }, { trackingId: 'bar', gaOptions: { name: 'baz' } } ], { alwaysSendToDefaultTracker: false } ); ReactGA.pageview('/valid', ['baz']); expect(spies.ga).toHaveBeenCalledTimes(3); expect(spies.ga).toHaveBeenNthCalledWith(1, 'create', 'foo', 'auto'); expect(spies.ga).toHaveBeenNthCalledWith(2, 'create', 'bar', { name: 'baz' }); expect(spies.ga).toHaveBeenNthCalledWith(3, 'baz.send', { hitType: 'pageview', page: '/valid' }); }); it('should abort, log warning if path is not provided', () => { ReactGA.initialize('foo'); ReactGA.pageview(); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'path is required in .pageview()' ); }); it('should abort, log warning if path is empty string', () => { ReactGA.initialize('foo'); ReactGA.pageview(''); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'path is required in .pageview()' ); }); it('should abort, log warning if path is empty string of spaces', () => { ReactGA.initialize('foo'); ReactGA.pageview(' '); expect(spies.warn).toHaveBeenCalledWith( '[react-ga]', 'path cannot be an empty string in .pageview()' ); }); }); <file_sep>// eslint-disable-next-line import/no-duplicates import DefaultReactGA from '../src/index'; // eslint-disable-next-line import/no-duplicates import * as ReactGA from '../src/index'; describe('react-ga', () => { it('should import as both default and * syntax', () => { expect(Object.keys(DefaultReactGA).sort()).toStrictEqual( Object.keys(ReactGA).sort() ); }); }); <file_sep>/** * To Title Case 2.1 - http://individed.com/code/to-title-case/ * Copyright 2008-2013 <NAME>. Licensed under the MIT License. * https://github.com/gouch/to-title-case */ import trim from './trim'; const smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i; // test export default function toTitleCase(string) { return trim(string).replace( /[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, (match, index, title) => { if ( index > 0 && index + match.length !== title.length && match.search(smallWords) > -1 && title.charAt(index - 2) !== ':' && (title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') && title.charAt(index - 1).search(/[^\s-]/) < 0 ) { return match.toLowerCase(); } if (match.substr(1).search(/[A-Z]|\../) > -1) { return match; } return match.charAt(0).toUpperCase() + match.substr(1); } ); }
4f30c283f67c5b050ffbac6427ce0c59bf7c5d91
[ "JavaScript", "TypeScript", "Markdown" ]
21
JavaScript
react-ga/react-ga
087837dc03d482549ded7669ac559df0c7cc5498
b96c36f54aecaec7d840a34bcbad0c865c2798fb
refs/heads/master
<repo_name>icorvoh/Java-To-Learn<file_sep>/src/Test_10/Test_1011.java package Test_10; public class Test_1011 { public static void main(String args[]) { Circle2D c1 = new Circle2D(2, 2, 5.5); double area = c1.getArea(); double radius = c1.getRadius(); double perimeter = c1.getPerimeter(); System.out.println("c1`s center: (" + c1.getX() + ", " + c1.getY() + ")"); System.out.println("c1`s radius: " + String.format("%.2f", radius)); System.out.println("c1`s perimeter: " + String.format("%.2f", perimeter)); System.out.println("c1`s area: " + String.format("%.2f", area)); if(c1.contains(3, 3)) { System.out.println("(3, 3) is inside c1"); } else { System.out.println("(3, 3) is not inside c1"); } if(c1.contains(new Circle2D(4, 5, 10.5))) { System.out.println("Circle2D(4, 5, 10.5) is inside c1"); } else { System.out.println("Circle2D(4, 5, 10.5) is not inside c1"); } if(c1.overlaps(new Circle2D(3, 5, 2.3))) { System.out.println("Circle2D(3, 5, 2.3) is overlaps c1"); } else { System.out.println("Circle2D(3, 5, 2.3) is not overlaps c1"); } } } class Circle2D { private double x; private double y; private double radius; Circle2D(double x, double y, double radius) { this.x = x; this.y = y; this.radius = radius; } public double getX() { return this.x; } public double getY() { return this.y; } public double getRadius(){ return this.radius; } public double getArea() { return radius *radius * Math.PI; } public double getPerimeter() { return 2 *radius * Math.PI; } public boolean contains(double x, double y) { double distance = Math.pow(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2), 0.5); return distance <= this.radius ? true : false; } public boolean contains(Circle2D circle) { double radius = circle.getRadius(); double distance = Math.pow(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2), 0.5); return (distance <= this.radius - radius) ? true : false; } public boolean overlaps(Circle2D circle) { double radius = circle.getRadius(); double distance = Math.pow(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2), 0.5); return (distance >= this.radius - radius && distance <= this.radius + radius) ? true : false; } }<file_sep>/src/Test_06/Test_0619.java package Test_06; import java.util.Scanner; public class Test_0619 { public static void main(String args[]) { int n; String name; double score; Scanner input = new Scanner(System.in); System.out.print("Students` number: "); n = input.nextInt(); Student[] students = new Student[n]; System.out.println("-------- Input Info --------"); for(int i = 0; i < n; i++) { students[i] = new Student(); System.out.print("The No." + i+1 + " Student`s name: "); name = input.next(); students[i].setName(name); System.out.print("The No." + i+1 + " Student`s score: "); score = input.nextDouble(); students[i].setScore(score); } System.out.println("-------- After Sort --------"); Student.sortScore(students); Student.printInfo(students); input.close(); } } class Student { private String name; private double score; public void setName(String name) { this.name = name; } public void setScore(double score) { this.score = score; } public String getName() { return this.name; } public double getScore() { return this.score; } public static void sortScore(Student[] students) { for(int i = 0; i< students.length - 1; i++) { Student currentMax = students[i]; int currentMaxIndex = i; for(int j = i + 1;j < students.length; j++) { if(currentMax.getScore() < students[j].getScore()) { currentMax = students[j]; currentMaxIndex = j; } } if(currentMaxIndex != i) { students[currentMaxIndex] = students[i]; students[i] = currentMax; } } } public static void printInfo(Student[] students) { for(int i = 0; i < students.length; i++) { System.out.println("The No." + i+1 + " student`s name: " + students[i].getName()); System.out.println("The No." + i+1 + " student`s score: " +students[i].getScore()); } } }<file_sep>/src/Test_08/Test_0802.java package Test_08; public class Test_0802 { public static void main(String args[]) { Stock Stock1 = new Stock("JAVA", "Sun Microsystems Inc", 4.5, 4.35); double getedChangePercent = Stock1.getChangePercent(); System.out.println("Symbol: " + Stock1.symbol); System.out.println("Name: " + Stock1.name); System.out.println("ChangePercent: " + String.format("%.2f",getedChangePercent) + "%"); } } class Stock { String symbol; String name; private double previousClosingPrice; private double currentPrice; public Stock(String symbol, String name, double pCP, double cP) { this.symbol = symbol; this.name = name; this.previousClosingPrice = pCP; this.currentPrice= cP; } public double getChangePercent() { return (currentPrice - previousClosingPrice) / previousClosingPrice; } }<file_sep>/src/Test_02/Test_0211_02.java package Test_02; import javax.swing.JOptionPane; public class Test_0211_02 { public static void main(String args[]) { String name = JOptionPane.showInputDialog(null, "Enter employee's full name:", "Test_0211_02 Input", JOptionPane.QUESTION_MESSAGE); String hoursString = JOptionPane.showInputDialog(null, "Enter number of hours worked in a week:", "Test_0211_02 Input", JOptionPane.QUESTION_MESSAGE); float numberOfHours = Float.parseFloat(hoursString); String rateString = JOptionPane.showInputDialog(null, "Enter hourly pay rate:", "Test_0211_02 Input", JOptionPane.QUESTION_MESSAGE); float hourlyPayRate = Float.parseFloat(rateString); String fedTaxWithholdingRateString = JOptionPane.showInputDialog(null, "Enter federal tax withholding rate:", "Test_0211_02 Input", JOptionPane.QUESTION_MESSAGE); float fedraltaxWithholdingRate = Float.parseFloat(fedTaxWithholdingRateString); String stateTaxWithholdingRateString = JOptionPane.showInputDialog(null, "Enter state tax withholding rate:", "Test_0211_02 Input", JOptionPane.QUESTION_MESSAGE); float stateTaxWithholdingRate = Float.parseFloat(stateTaxWithholdingRateString); // Calculate float grossPay = numberOfHours * hourlyPayRate; float fideraltaxDeduction = grossPay * fedraltaxWithholdingRate; float statetaxDeduction = grossPay * stateTaxWithholdingRate; float totalDeduction = fideraltaxDeduction + statetaxDeduction; float netPay = grossPay - totalDeduction; // Print result String out = "Employee Name: " + name + "\n\n"; out += "Hours Worked:" + " " + hoursString + '\n'; out += "Pay Rate:" + " $" + rateString + '\n'; out += "Gross Pay:" + " $" + grossPay + '\n'; out += "Deductions:\n"; out += " Federal Withholding (" + fedraltaxWithholdingRate * 100 + "%):" + " $" + (int)(fedraltaxWithholdingRate * 100) / 100.0 + '\n'; out += " State Withholding (" + stateTaxWithholdingRate * 100 + "%):" + " $" + (int)(stateTaxWithholdingRate * 100) / 100.0 + '\n'; out += " Total Deduction:" + " $" + (int)(totalDeduction * 100) / 100.0 + '\n'; out += "Net Pay:" + " $" + (int)(netPay * 100) / 100.0; System.out.print(out); JOptionPane.showMessageDialog(null, out, "Test_0211_02 Output", JOptionPane.INFORMATION_MESSAGE); } }<file_sep>/src/Test_08/Test_0804.java package Test_08; public class Test_0804 { public static void main(String[] args) { int three=3; char one='1'; int four=(one + three); System.out.println(four); } }<file_sep>/src/Test_10/Test_1009.java package Test_10; public class Test_1009 { public static void main(String args[]) { Course course = new Course("JAVA"); String[] students; int numberOfStudents; course.addStudent("icorvoh"); course.addStudent("Phodal"); course.addStudent("justjavac"); students = course.getStudents(); numberOfStudents = course.getNumberOfStudents(); for(int i = 0; i < numberOfStudents; i++) { System.out.println(students[i]); } course.dropStudent("justjavac"); numberOfStudents = course.getNumberOfStudents(); for(int i = 0; i < numberOfStudents; i++) { System.out.println(students[i]); } course.clear(); } } class Course { private String courseName; private String[] students = new String[100]; private int numberOfStudents; public Course(String courseName) { this.courseName = courseName; } public void addStudent(String student) { students[numberOfStudents] = student; numberOfStudents++; } public String[] getStudents() { return students; } public int getNumberOfStudents() { return numberOfStudents; } public String getCourseName() { return courseName; } public void dropStudent(String student) { String[] students = getStudents(); int dropIndex; for(dropIndex = 0; dropIndex < numberOfStudents; dropIndex++) { if(students[dropIndex] == student) { break; } } for(int i = dropIndex; i < numberOfStudents; i++) { students[i] = students[i+1]; numberOfStudents--; } } public void clear() { numberOfStudents = 0; } }<file_sep>/src/Test_06/Test_0627.java package Test_06; import java.util.Arrays; import java.util.Scanner; public class Test_0627 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] list1 = {5, 5, 5, 6, 6, 1}; int[] list2 = {5, 2, 5, 6, 1, 6}; System.out.print("Enter list1: "); for(int i: list1) { System.out.print(i + " "); } System.out.print("\nEnter list2: "); for(int j: list2) { System.out.print(j + " "); } if(equal(list1, list2)) { System.out.println("\nTwo lists are identical"); } else { System.out.println("\nTwo lists are not identical"); } input.close(); } public static boolean equal(int[] list1, int[] list2) { if(list1.length != list2.length) { return false; } Arrays.sort(list1); Arrays.sort(list2); for(int i = 0; i < list1.length; i++) { if(list1[i] != list2[i]) { return false; } } return true; } }<file_sep>/README.md # The Book`s Contents * Chapter 2: Elementary Programming * Chapter 3: Selections * Chapter 6: Single-Dimensional Arrays * Chapter 8: Objects and Classes * Chapter 10: Thinking in Objects # What I`ve learn A Scanner object should be closed by "close()" method at the end ``` System.out.print() will not create a newline after printing System.out.println() will create a newline after printing ``` |Methods for Scanner Objects|Method Description| |---------------------------|------------------| |nextByte() |reads an integer of byte type| |nextShort() |reads an integer of short type| |nextInt() |reads an integer of int type| |nextLong() |reads an integer of long type| |nextFloat() |reads a number of the float type| |nextDouble() |reads a number of the double type| |next() |reads a string that ends before a whitespace character| |nextline() |reads a line of text (a string ending with the enter key pressed)| * To control the number`s output format,we can import java.text.NumberFormat * create an object from the NumberFormat class * set the maximum fraction digits of that object * format number,return a digital string<file_sep>/src/Test_03/Test_0301.java package Test_03; import java.util.Scanner; import java.text.NumberFormat; public class Test_0301 { public static void main(String[] args) { // Initialize a Scanner object and NumberFormat object Scanner input = new Scanner(System.in); NumberFormat nf= NumberFormat.getInstance(); nf.setMaximumFractionDigits(6); // Enter data System.out.print("Enter a,b,c:"); double a = input.nextDouble(); double b = input.nextDouble(); double c = input.nextDouble(); // Calculate double d = b * b - 4 * a * c; if(d < 0) { System.out.println("The equation has no roots"); } else if (d == 0) { double r1 = -b / (2*a); System.out.println("The root is " + r1); } else { double r1 = (-b + Math.pow(d, 0.5)) / (2 * a); double r2 = (-b - Math.pow(d, 0.5)) / (2 * a); String r1String = nf.format(r1); String r2String = nf.format(r2); System.out.println("The roots are " + r1String + " and " + r2String); } // close Scanner object input.close(); } }
71c1875b8cdb9e49a1a0da67c258656d0e818cdd
[ "Markdown", "Java" ]
9
Java
icorvoh/Java-To-Learn
61aff29b55a616ca5c7b89e616614118fa586e2e
355d9100d5835c1022fac576363dc5bc8a6d1c9e
refs/heads/master
<repo_name>speed57/dentacoin-hub-app<file_sep>/src/app/forgotten-password/forgotten-password.component.ts import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {Router} from '@angular/router'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {RedirectsService} from '../_services/redirects.service'; import {HttpClient, HttpParams} from '../../../node_modules/@angular/common/http'; import {RequestsService} from '../_services/requests.service'; import {AdditionalService} from '../_services/additional.service'; import {TranslateService} from '@ngx-translate/core'; import {LanguageService} from '../_services/language.service'; @Component({ selector: 'app-forgotten-password', templateUrl: './forgotten-password.component.html' }) export class ForgottenPasswordComponent implements OnInit { forgottenPasswordForm: FormGroup; forgottenPasswordFormSubmitted = false; sendFormSucceed = false; sendFormFailed = false; constructor(public router: Router, public formBuilder: FormBuilder, public authenticationServiceService: AuthenticationServiceService, public redirectsService: RedirectsService, public http: HttpClient, public requestsService: RequestsService, public additionalService: AdditionalService, public translate: TranslateService, public languageService: LanguageService) { } ngOnInit() { if (this.authenticationServiceService.hasPatientStorageSession()) { // redirect to home if logged in this.redirectsService.redirectToLoggedHome(); } else { this.forgottenPasswordForm = this.formBuilder.group({ email: new FormControl('', Validators.compose([ Validators.required, Validators.email ])) }); } } // convenience getter for easy access to form fields get forgotten_password_form_data() { return this.forgottenPasswordForm.controls; } // on request form account submit onForgottenPasswordFormSubmit() { this.additionalService.showLoader(); this.forgottenPasswordFormSubmitted = true; // stop here if form is invalid if (this.forgottenPasswordForm.invalid) { this.additionalService.hideLoader(); return; } let paramsMap = new Map<any, any>(); paramsMap.set('email', this.forgotten_password_form_data.email.value); paramsMap.set('type_language', this.translate.currentLang); let params = new HttpParams(); paramsMap.forEach((value: any, key: any) => { params = params.set(key, value); }); this.requestsService.requestForgottenPasswordToken(params.toString()).subscribe((response: any) => { if (response.success) { this.forgottenPasswordForm.reset(); Object.keys(this.forgottenPasswordForm.controls).forEach(key => { this.forgottenPasswordForm.get(key).setErrors(null); }); this.sendFormSucceed = true; this.sendFormFailed = false; this.additionalService.hideLoader(); } else { this.sendFormFailed = true; this.sendFormSucceed = false; this.additionalService.hideLoader(); } }); } } <file_sep>/src/app/landing-page/landing-page.component.ts import {Component, OnInit} from '@angular/core'; import {TranslateService} from '@ngx-translate/core'; import {LanguageService} from '../_services/language.service'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {DentistDataObject} from '../admin/advanced-admin-panel/advanced-admin-panel.component'; import {AdditionalService} from '../_services/additional.service'; import {RequestsService} from '../_services/requests.service'; import {HttpClient} from '../../../node_modules/@angular/common/http'; import {RedirectsService} from '../_services/redirects.service'; @Component({ selector: 'app-landing-page', templateUrl: './landing-page.component.html' }) export class LandingPageComponent implements OnInit { public year = new Date().getFullYear(); public isNotAPartnerDentistLoggedIn: boolean; public myAccountLink: string; public dcnAmount: number = 0; public usdAmount: number = 0; public updateDentistDcnAndUsdBalanceTimer: any; public dentistData: DentistDataObject = { name: '', email: '', avatar_url: '' }; constructor(public authenticationServiceService: AuthenticationServiceService, public translate: TranslateService, public languageService: LanguageService, public additionalService: AdditionalService, public requestsService: RequestsService, private redirectsService: RedirectsService) { this.isNotAPartnerDentistLoggedIn = authenticationServiceService.hasNotAPartnerDentistStorageSession(); } ngOnInit() { if (window.localStorage.getItem('currentDentist') != null) { this.redirectsService.redirectToAdmin(); } else if (window.localStorage.getItem('currentNotAPartnerDentist') != null) { this.myAccountLink = this.additionalService.generateNotAPartnerDentistAccountLink(); this.requestsService.getUserData(JSON.parse(window.localStorage.getItem('currentNotAPartnerDentist')).token).subscribe({ next: (response: any) => { this.dentistData.name = response.data.name; this.dentistData.email = response.data.email; this.dentistData.avatar_url = response.data.avatar_url; if (response.data.is_partner === true || response.data.is_hub_app_dentist === true) { this.redirectsService.redirectToAdmin(); } }, error: error => this.authenticationServiceService.logout('dentist') }); this.updateDentistDcnAndUsdBalance(); if (typeof(this.updateDentistDcnAndUsdBalanceTimer) !== 'undefined') { clearInterval(this.updateDentistDcnAndUsdBalanceTimer); this.updateDentistDcnAndUsdBalanceTimer = undefined; } this.updateDentistDcnAndUsdBalanceTimer = setInterval(() => { if (!this.authenticationServiceService.hasPatientStorageSession()) { clearInterval(this.updateDentistDcnAndUsdBalanceTimer); this.updateDentistDcnAndUsdBalanceTimer = undefined; } else { this.updateDentistDcnAndUsdBalance(); } }, 5000); } } updateDentistDcnAndUsdBalance() { this.requestsService.getDCNBalance(JSON.parse(window.localStorage.getItem('currentNotAPartnerDentist')).token).subscribe({ next: (response: any) => { if (response.success) { this.dcnAmount = response.data; this.requestsService.getDentacoinDataByExternalProvider('USD').subscribe((coingeckoResponse: any) => { this.usdAmount = Number(((1 / Number(Number(coingeckoResponse) / 100)) * this.dcnAmount).toFixed(2)); }); } }, error: error => this.authenticationServiceService.logout('dentist') }); } } <file_sep>/src/environments/environment.prod.ts export const environment = { production: true, hybrid: false, default_language: 'en', /*dentacoinDomain: 'https://dev.dentacoin.com', coreDbApiDomain: 'https://dev-api.dentacoin.com', accountDomain: 'https://dev-account.dentacoin.com',*/ dentacoinDomain: 'https://dentacoin.com', coreDbApiDomain: 'https://api.dentacoin.com', accountDomain: 'https://account.dentacoin.com' }; <file_sep>/src/app/edit-account/edit-account.component.ts import {Component, OnInit} from '@angular/core'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {RedirectsService} from '../_services/redirects.service'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {HttpParams} from '../../../node_modules/@angular/common/http'; import {RequestsService} from '../_services/requests.service'; import {AdditionalService} from '../_services/additional.service'; @Component({ selector: 'app-edit-account', templateUrl: './edit-account.component.html' }) export class EditAccountComponent implements OnInit { patientsEditAccountForm: FormGroup; patientsEditAccountFormSubmitted = false; public showCountries: boolean = false; countriesList = {}; public showTitles: boolean = false; titlesList = {}; patientData = {}; patientName: string; patientEncryptedPassword: string; public editAccountSuccess: boolean = false; public editAccountFailed: boolean = false; public editPasswordFailed: boolean = false; public passwordsNotMatching: boolean = false; public updateCoreDBData: boolean = false; constructor(public authenticationServiceService: AuthenticationServiceService, public redirectsService: RedirectsService, public formBuilder: FormBuilder, public requestsService: RequestsService, public additionalService: AdditionalService) { } ngOnInit() { if (!this.authenticationServiceService.hasPatientStorageSession()) { this.redirectsService.redirectToPatientLogin('login'); } else { this.additionalService.showLoader(); this.patientsEditAccountForm = this.formBuilder.group({ title: new FormControl('', Validators.compose([ Validators.required ])), firstName: new FormControl('', Validators.compose([ Validators.required, Validators.maxLength(100) ])), lastName: new FormControl('', Validators.compose([ Validators.required, Validators.maxLength(100) ])), phone: new FormControl('', Validators.compose([ Validators.required, Validators.maxLength(20) ])), country: new FormControl('', Validators.compose([ Validators.required ])), password: new FormControl('', Validators.compose([ Validators.minLength(6), Validators.maxLength(20) ])), repeatPassword: new FormControl('', Validators.compose([ Validators.minLength(6), Validators.maxLength(20) ])) }); this.requestsService.getCountries().subscribe((response: any) => { if (response.success && response.data) { this.countriesList = response.data; this.showCountries = true; } }); this.requestsService.getTitles().subscribe({ next: (response:any) => { if (response.success && response.data) { this.titlesList = response.data.titles; this.showTitles = true; } }, error: error => this.authenticationServiceService.logout('patient') }); this.requestsService.getUserData(JSON.parse(window.localStorage.getItem('currentPatient')).token).subscribe({ next: (response:any) => { this.additionalService.hideLoader(); if (response.success && response.data) { this.patientData = response.data; this.patientName = response.data.name; this.patientEncryptedPassword = <PASSWORD>; if (response.data.title !== '' && response.data.title !== null) { this.patientsEditAccountForm.controls['title'].setValue(response.data.title); } if (response.data.name !== '' && response.data.name !== null) { this.patientsEditAccountForm.controls['firstName'].setValue(response.data.name); } if (response.data.phone !== '' && response.data.phone !== null) { this.patientsEditAccountForm.controls['phone'].setValue(response.data.phone); } if (response.data.country !== '' && response.data.country !== null) { this.patientsEditAccountForm.controls['country'].setValue(response.data.country); } } }, error: error => this.authenticationServiceService.logout('patient') }); } } // convenience getter for easy access to form fields get patients_edit_account_form_data() { return this.patientsEditAccountForm.controls; } // patient trying to log in onPatientsEditAccountFormSubmit() { this.additionalService.showLoader(); this.patientsEditAccountFormSubmitted = true; let paramsMap = new Map<any,any>(); paramsMap.set('title', this.patients_edit_account_form_data.title.value); paramsMap.set('name', this.patients_edit_account_form_data.firstName.value); paramsMap.set('phone', this.patients_edit_account_form_data.phone.value); paramsMap.set('country', this.patients_edit_account_form_data.country.value); let coreDBparamsMap = new Map<any,any>(); if (this.patients_edit_account_form_data.password.value.trim() !== '' || this.patients_edit_account_form_data.repeatPassword.value.trim() !== '') { if (this.patients_edit_account_form_data.password.value.trim() !== this.patients_edit_account_form_data.repeatPassword.value.trim()) { this.passwordsNotMatching = true; } else { this.passwordsNotMatching = false; this.updateCoreDBData = true; paramsMap.set('password', this.patients_edit_account_form_data.password.value.trim()); coreDBparamsMap.set('password', this.<PASSWORD>_edit_account_form_data.password.value.trim()); coreDBparamsMap.set('repeat-password', this.patients_edit_account_form_data.repeatPassword.value.trim()); } } if (this.patients_edit_account_form_data.firstName.value.trim() !== '' || this.patients_edit_account_form_data.lastName.value.trim() !== '') { this.updateCoreDBData = true; coreDBparamsMap.set('name', this.patients_edit_account_form_data.firstName.value.trim() + ' ' + this.patients_edit_account_form_data.lastName.value.trim()); } // stop here if form is invalid if (this.patientsEditAccountForm.invalid || this.passwordsNotMatching) { window.scrollTo(0, 0); this.additionalService.hideLoader(); return; } let params = new HttpParams(); paramsMap.forEach((value: any, key: any) => { params = params.set(key, value); }); let coreDBparams = new HttpParams(); coreDBparamsMap.forEach((value: any, key: any) => { coreDBparams = coreDBparams.set(key, value); }); this.requestsService.editProfile(coreDBparams.toString(), JSON.parse(window.localStorage.getItem('currentPatient')).token).subscribe({ next: (response: any) => { if (response.success) { this.additionalService.hideLoader(); this.patientsEditAccountForm.controls['password'].setValue(''); this.patientsEditAccountForm.controls['repeatPassword'].setValue(''); this.editAccountSuccess = true; window.scrollTo(0, 0); } else { this.additionalService.hideLoader(); this.patientsEditAccountForm.controls['password'].setValue(''); this.patientsEditAccountForm.controls['repeatPassword'].setValue(''); this.editPasswordFailed = true; window.scrollTo(0, 0); } }, error: error => this.authenticationServiceService.logout('patient') }); } } <file_sep>/src/app/_services/authentication-service.service.ts import {Injectable} from '@angular/core'; import {HttpClient, HttpParams, HttpHeaders} from '@angular/common/http'; import {Router} from '@angular/router'; import {BehaviorSubject, Observable} from 'rxjs'; import {RedirectsService} from './redirects.service'; import {RequestsService} from './requests.service'; @Injectable({ providedIn: 'root' }) export class AuthenticationServiceService { isDentistLoggedSubject = new BehaviorSubject<boolean>(this.hasDentistStorageSession()); isNotAPartnerDentistLoggedSubject = new BehaviorSubject<boolean>(this.hasNotAPartnerDentistStorageSession()); isPatientLoggedSubject = new BehaviorSubject<boolean>(this.hasPatientStorageSession()); generalError: boolean = false; dentistAuthFailed: boolean = false; notAPartner: boolean = false; constructor(private router: Router, private http: HttpClient, private redirectsService: RedirectsService, public requestsService: RequestsService) { } dentistLogin(email: string, password: string) { this.notAPartner = false; this.dentistAuthFailed = false; this.generalError = false; const ParseHeaders = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }; const body = new HttpParams().set('email', email).set('password', <PASSWORD>).set('platform', 'dentacoin').set('type', 'dentist'); this.requestsService.dentistLogin(body.toString()).subscribe((response: any) => { if (response.success) { if (response.data.is_partner == true || response.data.is_hub_app_dentist == true) { console.log('partner'); window.scrollTo(0, 0); window.localStorage.setItem('currentDentist', JSON.stringify({ id: response.data.id, token: response.token, encrypted_id: response.encrypted_data.encrypted_id, encrypted_token: response.encrypted_data.encrypted_token, encrypted_type: response.encrypted_data.encrypted_type })); this.requestsService.getDentistData(response.data.id).subscribe((innerResponse: any) => { if (innerResponse.data.logo != null) { this.isDentistLoggedSubject.next(true); this.redirectsService.redirectToMyPatients(); } else { this.isDentistLoggedSubject.next(true); this.redirectsService.redirectToAdmin(); } }); } else { console.log('not a partner'); window.scrollTo(0, 0); window.localStorage.setItem('currentNotAPartnerDentist', JSON.stringify({ id: response.data.id, token: response.token, encrypted_id: response.encrypted_data.encrypted_id, encrypted_token: response.encrypted_data.encrypted_token, encrypted_type: response.encrypted_data.encrypted_type })); this.isNotAPartnerDentistLoggedSubject.next(true); this.redirectsService.redirectToLandingPage(); } } else { this.dentistAuthFailed = true; } }); /*this.http.post(environment.coreDbApiDomain + '/api/login', body.toString(), ParseHeaders).subscribe({ next: (response: any) => { console.log(response, 'dentistLogin'); if (response.success) { if (response.data.is_partner == true) { console.log('partner'); window.scrollTo(0, 0); window.localStorage.setItem('currentDentist', JSON.stringify({ id: response.data.id, token: response.token /!*encrypted_id: coredbResponse.encrypted_id, encrypted_token: coredbResponse.encrypted_token, encrypted_type: coredbResponse.encrypted_type*!/ })); this.isDentistLoggedSubject.next(true); this.redirectsService.redirectToAdmin(); } else { console.log('not partner'); this.notAPartner = true; } } else { this.dentistAuthFailed = true; } }, error: error => { this.generalError = true; } });*/ } logout(redirect: string) { window.localStorage.clear(); window.localStorage.setItem('greetNewUser', 'true'); this.isPatientLoggedSubject.next(false); this.isDentistLoggedSubject.next(false); this.isNotAPartnerDentistLoggedSubject.next(false); if (redirect === 'dentist') { this.redirectsService.redirectToAdminLogin(); } else if (redirect === 'patient') { this.redirectsService.redirectToPatientLogin('login'); } } hasDentistStorageSession(): boolean { return !!window.localStorage.getItem('currentDentist'); } hasNotAPartnerDentistStorageSession(): boolean { return !!window.localStorage.getItem('currentNotAPartnerDentist'); } hasPatientStorageSession(): boolean { return !!window.localStorage.getItem('currentPatient'); } isDentistLoggedIn() : Observable<boolean> { return this.isDentistLoggedSubject.asObservable(); } isNotAPartnerDentistLoggedIn() : Observable<boolean> { return this.isNotAPartnerDentistLoggedSubject.asObservable(); } isPatientLoggedIn() : Observable<boolean> { return this.isPatientLoggedSubject.asObservable(); } redirectToLoginIfNotLoggedIn() { if (!this.hasDentistStorageSession()) { this.redirectsService.redirectToAdminLogin(); } } } <file_sep>/src/app/verify-account/verify-account.component.ts import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {HttpClient, HttpHeaders, HttpParams} from '../../../node_modules/@angular/common/http'; import {ActivatedRoute, Params} from '@angular/router'; import {RedirectsService} from '../_services/redirects.service'; import {AdditionalService} from '../_services/additional.service'; import {TranslateService} from '@ngx-translate/core'; import {LanguageService} from '../_services/language.service'; @Component({ selector: 'app-verify-account', templateUrl: './verify-account.component.html' }) export class VerifyAccountComponent implements OnInit { verifyAccountForm: FormGroup; verifyAccountFormSubmitted = false; differentPasswords = false; failedVerifiedAccount = false; constructor(public formBuilder: FormBuilder, public authenticationServiceService: AuthenticationServiceService, public http: HttpClient, public activatedRoute: ActivatedRoute, public redirectsService: RedirectsService, public additionalService: AdditionalService, public translate: TranslateService, public languageService: LanguageService) { } ngOnInit() { if (this.authenticationServiceService.hasPatientStorageSession()) { // redirect to home if logged in this.redirectsService.redirectToLoggedHome(); } else { this.verifyAccountForm = this.formBuilder.group({ password: new FormControl('', Validators.compose([ Validators.required, Validators.minLength(6), Validators.maxLength(20) ])), repeat_password: new FormControl('', Validators.compose([ Validators.required, Validators.minLength(6), Validators.maxLength(20) ])) }); } } // convenience getter for easy access to form fields get verify_account_form_data() { return this.verifyAccountForm.controls; } // dentist trying to log in onVerifyAccountFormSubmit() { this.differentPasswords = false; this.verifyAccountFormSubmitted = true; // stop here if form is invalid if (this.verifyAccountForm.invalid) { return; } if (this.verify_account_form_data.password.value.trim() !== this.verify_account_form_data.repeat_password.value.trim()) { this.differentPasswords = true; return; } const ParseHeaders = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }; this.activatedRoute.params.subscribe( (params: Params) => { this.additionalService.showLoader(); const body = new HttpParams().set('password', this.verify_account_form_data.password.value.trim()).set('type_language', this.translate.currentLang); this.http.post('https://dcn-hub-app-api.dentacoin.com/external-api/validate-token/' + params['token'], body.toString(), ParseHeaders).subscribe((response: any) => { this.additionalService.hideLoader(); if (response.success) { this.redirectsService.redirectToPatientLogin('account-verification'); } else if (response.errors) { this.failedVerifiedAccount = true; } }); }); } } <file_sep>/src/app/admin/advanced-admin-panel/advanced-admin-panel.component.ts import {Component, OnInit} from '@angular/core'; import {Observable} from 'rxjs'; import {AuthenticationServiceService} from '../../_services/authentication-service.service'; import {RedirectsService} from '../../_services/redirects.service'; import {RequestsService} from '../../_services/requests.service'; import {LanguageService} from '../../_services/language.service'; import {TranslateService} from '@ngx-translate/core'; import {AdditionalService} from '../../_services/additional.service'; @Component({ selector: 'app-advanced-admin-panel', templateUrl: './advanced-admin-panel.component.html' }) export class AdvancedAdminPanelComponent implements OnInit { public isDentistLoggedIn: Observable<boolean>; public myAccountLink: string; public dcnAmount: number = 0; public usdAmount: number = 0; public updateDentistDcnAndUsdBalanceTimer: any; public dentistData: DentistDataObject = { name: '', email: '', avatar_url: '' }; constructor(public authenticationServiceService: AuthenticationServiceService, public redirectsService: RedirectsService, public requestsService: RequestsService, public languageService: LanguageService, public translate: TranslateService, public additionalService: AdditionalService) { this.isDentistLoggedIn = authenticationServiceService.isDentistLoggedSubject; } ngOnInit() { this.myAccountLink = this.additionalService.generateAccountLink(); this.requestsService.getUserData(JSON.parse(window.localStorage.getItem('currentDentist')).token).subscribe({ next: (response: any) => { console.log(response.data, 'response.data'); this.dentistData.name = response.data.name; this.dentistData.email = response.data.email; this.dentistData.avatar_url = response.data.avatar_url; console.log(this.dentistData, 'this.dentistData'); }, error: error => this.authenticationServiceService.logout('dentist') }); this.updateDentistDcnAndUsdBalance(); if (typeof(this.updateDentistDcnAndUsdBalanceTimer) !== 'undefined') { clearInterval(this.updateDentistDcnAndUsdBalanceTimer); this.updateDentistDcnAndUsdBalanceTimer = undefined; } this.updateDentistDcnAndUsdBalanceTimer = setInterval(() => { if (!this.authenticationServiceService.hasPatientStorageSession()) { clearInterval(this.updateDentistDcnAndUsdBalanceTimer); this.updateDentistDcnAndUsdBalanceTimer = undefined; } else { this.updateDentistDcnAndUsdBalance(); } }, 5000); } updateDentistDcnAndUsdBalance() { this.requestsService.getDCNBalance(JSON.parse(window.localStorage.getItem('currentDentist')).token).subscribe({ next: (response: any) => { if (response.success) { this.dcnAmount = response.data; this.requestsService.getDentacoinDataByExternalProvider('USD').subscribe((coingeckoResponse: any) => { this.usdAmount = Number(((1 / Number(Number(coingeckoResponse) / 100)) * this.dcnAmount).toFixed(2)); }); } }, error: error => this.authenticationServiceService.logout('dentist') }); } } export interface DentistDataObject { name: string; email: string; avatar_url: string; }<file_sep>/src/app/admin/basic-admin-panel/basic-admin-panel.component.ts import {Component, OnInit} from '@angular/core'; import {TranslateService} from '@ngx-translate/core'; import {RedirectsService} from '../../_services/redirects.service'; import {LanguageService} from '../../_services/language.service'; import {AdditionalService} from '../../_services/additional.service'; // import * as $ from 'jquery'; @Component({ selector: 'app-basic-admin-panel', templateUrl: './basic-admin-panel.component.html' }) export class BasicAdminPanelComponent implements OnInit { public myAccountLink: string; constructor(public translate: TranslateService, public redirectsService: RedirectsService, public languageService: LanguageService, public additionalService: AdditionalService) { } ngOnInit() { this.myAccountLink = this.additionalService.generateAccountLink(); } }<file_sep>/src/app/partials/account-sidebar/account-sidebar.component.ts import {Component, Input, OnInit} from '@angular/core'; import {RedirectsService} from '../../_services/redirects.service'; import {AuthenticationServiceService} from '../../_services/authentication-service.service'; import {RequestsService} from '../../_services/requests.service'; import {Router} from '@angular/router'; @Component({ selector: 'app-account-sidebar', templateUrl: './account-sidebar.component.html' }) export class AccountSidebarComponent implements OnInit { public patientData: PatientDataObject = { name: '' }; constructor(public redirectsService: RedirectsService, public authenticationServiceService: AuthenticationServiceService, public router: Router, public requestsService: RequestsService) { } ngOnInit() { if (!this.authenticationServiceService.hasPatientStorageSession()) { this.redirectsService.redirectToPatientLogin('login'); } else { this.requestsService.getUserData(JSON.parse(window.localStorage.getItem('currentPatient')).token).subscribe({ next: (response:any) => { this.patientData.name = response.data.name; }, error: error => this.authenticationServiceService.logout('patient') }); } } } export interface PatientDataObject { name: string; }<file_sep>/src/app/admin/advanced-admin-panel/push-notifications/push-notifications.component.ts import {Component, OnInit} from '@angular/core'; import {RedirectsService} from '../../../_services/redirects.service'; import {AuthenticationServiceService} from '../../../_services/authentication-service.service'; import {HttpParams} from '../../../../../node_modules/@angular/common/http'; import {RequestsService} from '../../../_services/requests.service'; import {AdditionalService} from '../../../_services/additional.service'; import {TranslateService} from '@ngx-translate/core'; @Component({ selector: 'app-push-notifications', templateUrl: './push-notifications.component.html' }) export class PushNotificationsComponent implements OnInit { public showPushNotificationsHistory: boolean = false; public push_notifications = []; public showCurrentDentistPatients: boolean = false; public currentDentistPatients: string = ''; constructor(public redirectsService: RedirectsService, public requestsService: RequestsService, public authenticationServiceService: AuthenticationServiceService, public additionalService: AdditionalService, public translate: TranslateService) { } ngOnInit() { if (!this.authenticationServiceService.hasDentistStorageSession()) { // redirect to home if logged in this.redirectsService.redirectToLoggedHome(); } else { this.requestsService.getPushNotificationsHistory(new HttpParams().set('id', JSON.parse(window.localStorage.getItem('currentDentist')).id).set('token', JSON.parse(window.localStorage.getItem('currentDentist')).token).toString()).subscribe((response: any) => { if (response.success) { this.showPushNotificationsHistory = true; this.push_notifications = response.data; if (this.push_notifications.length) { for (let i = 0; i < this.push_notifications.length; i += 1) { if (this.push_notifications[i].scheduled != null) { this.push_notifications[i].date = this.additionalService.dateObjToFormattedDate(new Date(this.push_notifications[i].scheduled)); } else { this.push_notifications[i].date = this.additionalService.dateObjToFormattedDate(new Date(this.push_notifications[i].created_at)); } } } } }); this.requestsService.getPatientsWhichCanReceivePushNotifications(new HttpParams().set('id', JSON.parse(window.localStorage.getItem('currentDentist')).id).set('token', JSON.parse(window.localStorage.getItem('currentDentist')).token).toString()).subscribe((response: any) => { if (response.success && response.data.length) { this.currentDentistPatients = JSON.stringify(response.data); this.showCurrentDentistPatients = true; } }); } } }<file_sep>/src/app/_services/requests.service.ts import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Observable} from 'rxjs'; import {environment} from '../../environments/environment'; @Injectable({ providedIn: 'root' }) export class RequestsService { constructor(private http: HttpClient) { } public getDentacoinDataByExternalProvider(currency: string): Observable<{}> { return this.http.get('https://indacoin.com/api/GetCoinConvertAmount/' + currency + '/DCN/100/dentacoin'); } // ===================================== HubApp api methods ===================================== public getDentistData(id: any): Observable<{}> { return this.http.get('https://dcn-hub-app-api.dentacoin.com/dentist/get-dentist-data/' + id); } public sendRequestAccountMail(body: string): Observable<{}> { return this.http.post('https://dcn-hub-app-api.dentacoin.com/patient/send-request-account-mail', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }); } public dentistSendRequestAccountMail(body: string): Observable<{}> { return this.http.post('https://dcn-hub-app-api.dentacoin.com/dentist/dentist-send-request-account-mail', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }); } public withdraw(body: string): Observable<{}> { return this.http.post('https://dcn-hub-app-api.dentacoin.com/patient/withdraw', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }) }); } public dentistLogin(body: string): Observable<{}> { return this.http.post('https://dcn-hub-app-api.dentacoin.com/dentist/coredb-login', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }) }); } public getDentistSlug(body: string): Observable<{}> { return this.http.post('https://dcn-hub-app-api.dentacoin.com/patient/get-dentist-slug', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }) }); } public getInviteHistory(body: string): Observable<{}> { return this.http.post('https://dcn-hub-app-api.dentacoin.com/dentist/get-invite-history', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }) }); } public getPushNotificationsHistory(body: string): Observable<{}> { return this.http.post('https://dcn-hub-app-api.dentacoin.com/dentist/get-push-notifications', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }) }); } public getPatientsWhichCanReceivePushNotifications(body: string): Observable<{}> { return this.http.post('https://dcn-hub-app-api.dentacoin.com/dentist/get-patients-which-can-receive-push-notifications', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }) }); } public coreDbLogin(body: string): Observable<{}> { return this.http.post('https://dcn-hub-app-api.dentacoin.com/patient/coredb-login', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }) }); } public getWithdrawHistory(body: string): Observable<{}> { return this.http.post('https://dcn-hub-app-api.dentacoin.com/patient/get-dcn-withdraw-history', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }); } public requestForgottenPasswordToken(body: string): Observable<{}> { return this.http.post('https://dcn-hub-app-api.dentacoin.com/patient/request-forgotten-password', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }); } // ===================================== CoreDB api methods ===================================== public getTitles(): Observable<{}> { return this.http.get(environment.coreDbApiDomain + '/api/enums'); } public getCountries(): Observable<{}> { return this.http.get(environment.coreDbApiDomain + '/api/countries'); } public validatePhone(body: string): Observable<{}> { console.log(body, 'body'); return this.http.post(environment.coreDbApiDomain + '/api/phone/', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }) }); } public downloadGDPRData(token: string): Observable<{}> { return this.http.post(environment.coreDbApiDomain + '/api/gdpr/', null, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Authorization': 'Bearer ' + token }) }); } public deleteProfile(body: string, token: string): Observable<{}> { return this.http.post(environment.coreDbApiDomain + '/api/user/', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Authorization': 'Bearer ' + token }) }); } public editProfile(body: string, token: string): Observable<{}> { return this.http.post(environment.coreDbApiDomain + '/api/user/', body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Authorization': 'Bearer ' + token }) }); } public getUserData(token: string): Observable<{}> { return this.http.get(environment.coreDbApiDomain + '/api/user/', { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer ' + token }) }); } public getDCNBalance(token: string): Observable<{}> { return this.http.post(environment.coreDbApiDomain + '/api/balance', null, { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer ' + token }) }); } public getAddresses(id: any): Observable<{}> { return this.http.get(environment.coreDbApiDomain + '/api/wallet-addresses/' + id); } } <file_sep>/src/app/change-password/change-password.component.ts import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms"; import {ActivatedRoute, Params, Router} from "@angular/router"; import {AuthenticationServiceService} from "../_services/authentication-service.service"; import {RedirectsService} from "../_services/redirects.service"; import {HttpClient, HttpHeaders, HttpParams} from "../../../node_modules/@angular/common/http"; import {AdditionalService} from "../_services/additional.service"; import {TranslateService} from "@ngx-translate/core"; import {LanguageService} from "../_services/language.service"; @Component({ selector: 'app-change-password', templateUrl: './change-password.component.html' }) export class ChangePasswordComponent implements OnInit { changePasswordForm: FormGroup; changePasswordFormSubmitted = false; differentPasswords = false; failedChangePassword = false; constructor(public formBuilder: FormBuilder, public authenticationServiceService: AuthenticationServiceService, public http: HttpClient, public activatedRoute: ActivatedRoute, public redirectsService: RedirectsService, public additionalService: AdditionalService, public translate: TranslateService, public languageService: LanguageService) { } ngOnInit() { if (this.authenticationServiceService.hasPatientStorageSession()) { // redirect to home if logged in this.redirectsService.redirectToLoggedHome(); } else { this.changePasswordForm = this.formBuilder.group({ password: new FormControl('', Validators.compose([ Validators.required, Validators.minLength(6), Validators.maxLength(20) ])), repeat_password: new FormControl('', Validators.compose([ Validators.required, Validators.minLength(6), Validators.maxLength(20) ])) }); } } // convenience getter for easy access to form fields get change_password_form_data() { return this.changePasswordForm.controls; } // dentist trying to log in onchangePasswordFormSubmit() { this.differentPasswords = false; this.changePasswordFormSubmitted = true; // stop here if form is invalid if (this.changePasswordForm.invalid) { return; } if (this.change_password_form_data.password.value.trim() !== this.change_password_form_data.repeat_password.value.trim()) { this.differentPasswords = true; return; } const ParseHeaders = { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }; this.activatedRoute.params.subscribe( (params: Params) => { this.additionalService.showLoader(); const body = new HttpParams().set('recoverToken', '123').set('password', this.change_password_form_data.password.value.trim()); this.http.post('https://dcn-hub-app-api.dentacoin.com/patient/change-password', body.toString(), ParseHeaders).subscribe({ next: (response: any) => { this.additionalService.hideLoader(); if (response.success) { this.redirectsService.redirectToPatientLogin('change-password'); } else if (response.errors) { this.failedChangePassword = true; } }, error: error => this.authenticationServiceService.logout('patient') }); }); } } <file_sep>/src/app/my-wallet/my-wallet.component.ts import { Component, OnInit } from '@angular/core'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {RedirectsService} from '../_services/redirects.service'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {HttpParams} from '../../../node_modules/@angular/common/http'; import {RequestsService} from '../_services/requests.service'; import {AdditionalService} from '../_services/additional.service'; import * as $ from 'jquery'; @Component({ selector: 'app-my-wallet', templateUrl: './my-wallet.component.html' }) export class MyWalletComponent implements OnInit { withdrawForm: FormGroup; withdrawFormSubmitted = false; dcnAmount: number; usdAmount: number; currenciesList: {}; showCurrenciesList: boolean = false; showWithdrawHistory: boolean = false; withdrawHistory = []; withdrawFailed: boolean = false; withdrawSucceed: boolean = false; errorMessage: string; successMessage: string; usdVal: number = 0; eurVal: number = 0; gbpVal: number = 0; rubVal: number = 0; public addresses = []; public currencies = ['USD', 'EUR', 'GBP', 'RUB']; constructor(public authenticationServiceService: AuthenticationServiceService, public redirectsService: RedirectsService, public formBuilder: FormBuilder, public requestsService: RequestsService, public additionalService: AdditionalService) { } ngOnInit() { if (!this.authenticationServiceService.hasPatientStorageSession()) { this.redirectsService.redirectToPatientLogin('login'); } else { this.withdrawForm = this.formBuilder.group({ address: new FormControl('', Validators.compose([ Validators.required, Validators.minLength(42), Validators.maxLength(42) ])), amount: new FormControl('', Validators.compose([ Validators.required, Validators.min(10000) ])) }); $('form#withdraw .disabled-amount').on('click', (e) => { $(e.currentTarget).hide(); $('form#withdraw .amount').show().focus(); }); $(document).on('click', '.search-result .search-body ul li a', (e) => { this.withdrawForm.controls['address'].setValue($(e.currentTarget).attr('data-value')); $('.search-result').hide(); }); this.requestsService.getAddresses(JSON.parse(window.localStorage.getItem('currentPatient')).id).subscribe((response: any) => { if (response.success) { if (response.data.length) { this.addresses = Object.keys(response.data).map(i => response.data[i]); if (this.addresses.length) { this.withdrawForm.controls['address'].setValue(this.addresses[0].dcn_address); } } } }); this.updateDCNBalance(); this.updateDCNWithdrawHistory(); } } updateDCNBalance() { this.requestsService.getDCNBalance(JSON.parse(window.localStorage.getItem('currentPatient')).token).subscribe({ next: async (response:any) => { if (response.success) { this.withdrawForm.controls['amount'].setValue(response.data); this.dcnAmount = response.data; for (let i = 0, len = this.currencies.length; i < len; i++) { this.requestsService.getDentacoinDataByExternalProvider(this.currencies[i]).subscribe((coingeckoResponse: any) => { if (this.currencies[i] === 'USD') { this.usdVal = 1 / Number(Number(coingeckoResponse) / 100); this.usdAmount = Number((this.usdVal * this.dcnAmount).toFixed(4)); } else if (this.currencies[i] === 'EUR') { this.eurVal = 1 / Number(Number(coingeckoResponse) / 100); } else if (this.currencies[i] === 'GBP') { this.gbpVal = 1 / Number(Number(coingeckoResponse) / 100); } else if (this.currencies[i] === 'RUB') { this.rubVal = 1 / Number(Number(coingeckoResponse) / 100); } }); } let checkingIfRequestsFinished = setInterval(() => { console.log('checkingIfRequestsFinished'); if (this.usdVal !== 0 && this.eurVal !== 0 && this.gbpVal !== 0 && this.rubVal !== 0) { clearInterval(checkingIfRequestsFinished); $(document).ready(function() { $('.my-wallet-container .dropdown-hidden-menu button').on('click', (e) => { var this_btn = $(e.currentTarget); $('.my-wallet-container .current-converted-price .amount').html((parseFloat($('.current-dcn-amount').html()) * parseFloat(this_btn.attr('data-multiple-with'))).toFixed(2)); $('.my-wallet-container .current-converted-price .symbol span').html(this_btn.html()); }); }); } }, 500); } }, error: error => this.authenticationServiceService.logout('patient') }); } updateDCNWithdrawHistory() { const withdrawHistoryBody = new HttpParams().set('id', JSON.parse(window.localStorage.getItem('currentPatient')).id).set('token', JSON.parse(window.localStorage.getItem('currentPatient')).token); this.requestsService.getWithdrawHistory(withdrawHistoryBody.toString()).subscribe({ next: (withdrawHistoryResponse:any) => { if (withdrawHistoryResponse.success) { this.withdrawHistory = Object.keys(withdrawHistoryResponse.data).map(i => withdrawHistoryResponse.data[i]); this.showWithdrawHistory = true; } }, error: error => this.authenticationServiceService.logout('patient') }); } // convenience getter for easy access to form fields get withdraw_form_data() { return this.withdrawForm.controls; } withdraw(body) { this.requestsService.withdraw(body).subscribe((withdrawResponse: any) => { this.additionalService.hideLoader(); if (withdrawResponse.success) { this.updateDCNBalance(); this.updateDCNWithdrawHistory(); this.successMessage = withdrawResponse.message; this.withdrawSucceed = true; } else { this.errorMessage = withdrawResponse.error; this.withdrawFailed = true; } }); } // patient saving his DCN addess in CoreDB onWithdrawSubmit() { this.additionalService.showLoader(); this.withdrawFormSubmitted = true; // stop here if form is invalid if (this.withdrawForm.invalid) { this.additionalService.hideLoader(); return; } // if the withdraw to address is the same as the last time withdrawing const withdrawBody = new HttpParams().set('amount', this.withdraw_form_data.amount.value).set('address', this.withdraw_form_data.address.value.trim()).set('id', JSON.parse(window.localStorage.getItem('currentPatient')).id).set('token', JSON.parse(window.localStorage.getItem('currentPatient')).token); this.withdraw(withdrawBody.toString()); return; } } <file_sep>/src/app/patient-login-page/patient-login-page.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { PatientLoginPageComponent } from './patient-login-page.component'; describe('PatientLoginPageComponent', () => { let component: PatientLoginPageComponent; let fixture: ComponentFixture<PatientLoginPageComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ PatientLoginPageComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(PatientLoginPageComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/src/app/patient-register-by-invite/patient-register-by-invite.component.ts import {Component, OnInit} from '@angular/core'; import {FormControl, Validators} from '@angular/forms'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {ActivatedRoute, Params} from '@angular/router'; import {RedirectsService} from '../_services/redirects.service'; import {HttpClient, HttpParams} from '../../../node_modules/@angular/common/http'; import {TranslateService} from '@ngx-translate/core'; import {environment} from '../../environments/environment'; import {RequestsService} from '../_services/requests.service'; import {AdditionalService} from '../_services/additional.service'; import * as $ from 'jquery'; @Component({ selector: 'app-patient-register-by-invite', templateUrl: './patient-register-by-invite.component.html' }) export class PatientRegisterByInviteComponent implements OnInit { public coreDbApiDomain = environment.coreDbApiDomain; public inviter = ''; public inviteId = ''; public is_dentist_patient_relation_creation = ''; patientRegisterEventsAdded = false; constructor(public authenticationServiceService: AuthenticationServiceService, public redirectsService: RedirectsService, public activatedRoute: ActivatedRoute, public translate: TranslateService, public additionalService: AdditionalService, public requestsService: RequestsService) { } ngOnInit() { if (this.authenticationServiceService.hasPatientStorageSession()) { // redirect to home if logged in this.redirectsService.redirectToLoggedHome(); } else { if (this.activatedRoute.snapshot.queryParamMap.get('invite') == null) { this.redirectsService.redirectToPatientLogin('login'); } else { this.inviter = this.activatedRoute.snapshot.queryParamMap.get('invite'); if (this.activatedRoute.snapshot.queryParamMap.get('inviteid') != null) { this.inviteId = this.activatedRoute.snapshot.queryParamMap.get('inviteid'); } if (this.activatedRoute.snapshot.queryParamMap.get('is-dentist-patient-relation-creation') != null) { this.is_dentist_patient_relation_creation = 'true'; } if (!this.patientRegisterEventsAdded) { document.addEventListener('patientAuthSuccessResponse', (e: any) => { console.log(e, 'patientAuthSuccessResponse'); this.onPatientsRegister(e.detail.response_data.token, e.detail.response_data.data.id, e.detail.response_data.data.patient_of); }); document.addEventListener('receiveCoredbTokenFromCivicAuth', (e: any) => { this.requestsService.getUserData(e.detail.response_data).subscribe({ next: (response: any) => { if (response.success) { this.onPatientsRegister(e.detail.response_data, response.data.id, response.data.patient_of); } else { this.authenticationServiceService.logout('patient'); } }, error: error => this.authenticationServiceService.logout('patient') }); }); document.addEventListener('receivedFacebookToken', (e: any) => { this.additionalService.showLoader(); }); document.addEventListener('civicRead', (e: any) => { this.additionalService.showLoader(); }); document.addEventListener('hideGatewayLoader', (e: any) => { this.additionalService.hideLoader(); }); document.addEventListener('registeredAccountMissingEmail', (e: any) => { // COVER THIS !!!!!!!!!!!!! document.getElementById('patient-login-failed-missing-email').classList.remove('hide'); }); document.addEventListener('patientAuthErrorResponse', (e: any) => { console.log(e, 'e'); let errorsHtml = ''; if (e.detail.response_data.not_registered) { errorsHtml = this.translate.instant('account-not-found'); } else { if (e.detail.response_data.errors) { for (let key in e.detail.response_data.errors) { errorsHtml += e.detail.response_data.errors[key] + '<br>'; } } } document.getElementById('custom-error').classList.remove('hide'); document.getElementById('custom-error').innerHTML = errorsHtml; if ($('.log-link.open-dentacoin-gateway').length) { $('.log-link.open-dentacoin-gateway').on('click', () => { if (this.activatedRoute.snapshot.queryParamMap.get('inviteid') != null) { this.redirectsService.redirectToPatientLogin('login?invite=' + this.inviter + '&inviteid=' + this.inviteId); } else { this.redirectsService.redirectToPatientLogin('login?invite=' + this.inviter); } }); } this.additionalService.hideLoader(); }); document.addEventListener('noCoreDBApiConnection', (e: any) => { document.getElementById('patient-login-failed').classList.remove('hide'); this.additionalService.hideLoader(); }); document.addEventListener('noExternalLoginProviderConnection', (e: any) => { document.getElementById('patient-login-failed').classList.remove('hide'); this.additionalService.hideLoader(); }); window.addEventListener('message', (event: any) => { if (event.data.event_id === 'noUserIdReceived') { document.getElementById('patient-login-failed').classList.remove('hide'); document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'registeredAccountMissingEmail') { // COVER THIS THE PROPER WAY !!!!!!!!!!!!! document.getElementById('patient-login-failed-missing-email').classList.remove('hide'); document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'patientProceedWithCreatingSession') { this.onPatientsRegister(event.data.data.token, event.data.data.data.id, event.data.data.data.patient_of); document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'patientAuthErrorResponse') { let errorsHtml = ''; if (event.data.not_registered) { errorsHtml = this.translate.instant('account-not-found'); } else { if (event.data.errors) { for (let key in event.data.errors) { errorsHtml += event.data.errors[key] + '<br>'; } } } document.getElementById('custom-error').classList.remove('hide'); document.getElementById('custom-error').innerHTML = errorsHtml; if ($('.log-link.open-dentacoin-gateway').length) { $('.log-link.open-dentacoin-gateway').on('click', () => { if (this.activatedRoute.snapshot.queryParamMap.get('inviteid') != null) { this.redirectsService.redirectToPatientLogin('login?invite=' + this.inviter + '&inviteid=' + this.inviteId); } else { this.redirectsService.redirectToPatientLogin('login?invite=' + this.inviter); } }); } document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'noCoreDBApiConnection') { document.getElementById('patient-login-failed').classList.remove('hide'); document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'noExternalLoginProviderConnection') { document.getElementById('patient-login-failed').classList.remove('hide'); document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'removeCivicIframeAndRedirectToAccountPage') { document.getElementById('iframe-civic-popup').remove(); window.open(event.data.data.redirect, '_system'); } }); } } } } // we already have the token, but we are passing the data to dcn hub app backend in order to encrypt it and save it user localstorage onPatientsRegister(_token: any, _id: any, _patient_of: any) { if (_patient_of !== null && _patient_of !== undefined) { this.requestsService.coreDbLogin(new HttpParams().set('token', _token).set('id', _id).set('patient_of', _patient_of).toString()).subscribe({ next: (coredbResponse: any) => { window.scrollTo(0, 0); if (coredbResponse.success) { window.localStorage.setItem('currentPatient', JSON.stringify({ token: _token, id: _id, patient_of: _patient_of, encrypted_id: coredbResponse.encrypted_id, encrypted_token: coredbResponse.encrypted_token, encrypted_type: coredbResponse.encrypted_type })); window.localStorage.setItem('dentist', String(_patient_of)); this.authenticationServiceService.isPatientLoggedSubject.next(true); this.redirectsService.redirectToLoggedHome(); this.additionalService.hideLoader(); } else if (coredbResponse.error) { document.getElementById('custom-error').classList.remove('hide'); document.getElementById('custom-error').innerHTML = coredbResponse.message; this.additionalService.hideLoader(); } }, error: error => { document.getElementById('patient-login-failed').classList.remove('hide'); this.additionalService.hideLoader(); } }); } else { document.getElementById('patient-login-failed-not-a-patient-of-any-dentist').classList.remove('hide'); this.additionalService.hideLoader(); } } }<file_sep>/src/app/home/home.component.ts import { Component, OnInit } from '@angular/core'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {RedirectsService} from '../_services/redirects.service'; import {RequestsService} from '../_services/requests.service'; import {TranslateService} from '@ngx-translate/core'; import {HttpHeaders, HttpParams} from '../../../node_modules/@angular/common/http'; @Component({ selector: 'app-home', templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { public applications = []; public pageColumnClass: string = 'col-xs-12 col-md-8 col-md-offset-2 col-lg-6 col-lg-offset-3'; public applicationsColumnClass: string = 'col-xs-4'; public hubTitleEn: string; public hubTitleDe: string; constructor(public authenticationServiceService: AuthenticationServiceService, public redirectsService: RedirectsService, public requestsService: RequestsService, public translate: TranslateService) { } ngOnInit() { if (!this.authenticationServiceService.hasPatientStorageSession()) { this.redirectsService.redirectToPatientLogin('login'); } else { this.requestsService.getDentistData(JSON.parse(window.localStorage.getItem('currentPatient')).patient_of).subscribe((response: any) => { this.requestsService.getDentistSlug(new HttpParams().set('id', JSON.parse(window.localStorage.getItem('currentPatient')).patient_of).toString()).subscribe((dentistSlugResponse: any) => { console.log(dentistSlugResponse, 'dentistSlugResponse'); this.hubTitleEn = response.data.hub_title_en; this.hubTitleDe = response.data.hub_title_de; this.applications = Object.keys(response.data.applications).map(i => response.data.applications[i]); if (this.applications.length) { for (let i = 0; i < this.applications.length; i += 1) { // setting dynamic dentist trp profile link if (this.applications[i].url.includes('reviews.dentacoin.com') && dentistSlugResponse.success) { // setting up trp link to head to dentist profile and cross login this.applications[i].url = this.applications[i].url + '/custom-cookie?slug=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_id) + '&type=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_type) + '&token=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_token) + '&dentist_slug=' + dentistSlugResponse.data; } else if (this.applications[i].url.includes('dentavox.dentacoin.com') || this.applications[i].url.includes('assurance.dentacoin.com')) { // setting up dentavox and assurance cross login this.applications[i].url = this.applications[i].url + '/custom-cookie?slug=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_id) + '&type=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_type) + '&token=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_token); } if (this.applications[i].resource_type === 'svg') { this.applications[i].media = encodeURIComponent(this.applications[i].media); } } } if (this.applications.length >= 7) { this.pageColumnClass = 'col-xs-12 col-md-8 col-md-offset-2'; this.applicationsColumnClass = 'col-xs-4 col-sm-3'; } }); }); } } } export interface DentistDataObject { hubTitleEn: string; hubTitleDe: string; }<file_sep>/src/app/admin-login/admin-login.component.ts import {Component, OnInit} from '@angular/core'; import {Observable} from 'rxjs'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {Router} from '@angular/router'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {RedirectsService} from '../_services/redirects.service'; import {TranslateService} from '@ngx-translate/core'; import {HttpClient} from '../../../node_modules/@angular/common/http'; @Component({ selector: 'app-admin-login', templateUrl: './admin-login.component.html' }) export class AdminLoginComponent implements OnInit { public isDentistLoggedIn: Observable<boolean>; constructor(public router: Router, public formBuilder: FormBuilder, public authenticationServiceService: AuthenticationServiceService, public redirectsService: RedirectsService, public translate: TranslateService) { this.isDentistLoggedIn = authenticationServiceService.isDentistLoggedSubject; } dentistsLoginForm: FormGroup; dentistsFormSubmitted = false; ngOnInit() { if (this.authenticationServiceService.hasDentistStorageSession()) { // logged-in logic this.redirectsService.redirectToAdmin(); } else { // not logged-in logic this.dentistsLoginForm = this.formBuilder.group({ email: new FormControl('', Validators.compose([ Validators.required, Validators.email ])), password: ['', Validators.required] }); } } // convenience getter for easy access to form fields get dentists_form_data() { return this.dentistsLoginForm.controls; } // dentist trying to log in onDentistsFormSubmit() { this.dentistsFormSubmitted = true; // stop here if form is invalid if (this.dentistsLoginForm.invalid) { return; } this.authenticationServiceService.dentistLogin(this.dentists_form_data.email.value.trim(), this.dentists_form_data.password.value.trim()); } } <file_sep>/src/app/_services/additional.service.spec.ts import { TestBed } from '@angular/core/testing'; import { AdditionalService } from './additional.service'; describe('AdditionalService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: AdditionalService = TestBed.get(AdditionalService); expect(service).toBeTruthy(); }); }); <file_sep>/src/app/app.module.ts import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {ReactiveFormsModule} from '@angular/forms'; import {HttpClientModule, HttpClient} from '@angular/common/http'; import {AppRoutingModule, routingComponents} from './app-routing.module'; import {AppComponent} from './app.component'; import {TranslateLoader, TranslateModule} from '@ngx-translate/core'; import {TranslateHttpLoader} from '@ngx-translate/http-loader'; import { AccountSidebarComponent } from './partials/account-sidebar/account-sidebar.component'; import { LandingPageComponent } from './landing-page/landing-page.component'; @NgModule({ declarations: [ AppComponent, routingComponents, AccountSidebarComponent, LandingPageComponent ], imports: [ BrowserModule.withServerTransition({ appId: 'serverApp' }), AppRoutingModule, ReactiveFormsModule, HttpClientModule, // ngx-translate and the loader module TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } // required for AOT compilation export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http, 'assets/languages/'); }<file_sep>/src/app/_services/additional.service.ts import {Injectable} from '@angular/core'; import * as $ from 'jquery'; import {environment} from '../../environments/environment'; @Injectable({ providedIn: 'root' }) export class AdditionalService { constructor() { } // showing front end loader showLoader() { if (!$('.camping-loader').hasClass('loaded')) { $('.camping-loader').html('<div class="response-layer"><div class="wrapper"><picture itemscope="" itemtype="http://schema.org/ImageObject"><source media="(max-width: 768px)" srcset="assets/images/dcn-flipping-coin-logo-loader-v3-mobile.gif"><img itemprop="contentUrl" src="assets/images/dcn-flipping-coin-logo-loader-v3_desktop.gif" class="max-width-250 max-width-xs-200" alt="Loader"></picture></div></div>').addClass('loaded'); $('.camping-loader .response-layer').show(); } else { $('.camping-loader .response-layer').show(); } } // hiding front end loader hideLoader() { $('.camping-loader .response-layer').hide(); } dateObjToFormattedDate(object) { let date; let month; if (object.getDate() < 10) { date = '0' + object.getDate(); } else { date = object.getDate(); } if (object.getMonth() + 1 < 10) { month = '0' + (object.getMonth() + 1); } else { month = object.getMonth() + 1; } return date + '/' + month + '/' + object.getFullYear(); } generateAccountLink() { if (environment.hybrid === true) { return environment.accountDomain + '/custom-cookie?mobile-app=hubapp&slug=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentDentist')).encrypted_id) + '&type=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentDentist')).encrypted_type) + '&token=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentDentist')).encrypted_token); } else { return environment.accountDomain + '/custom-cookie?slug=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentDentist')).encrypted_id) + '&type=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentDentist')).encrypted_type) + '&token=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentDentist')).encrypted_token); } } generateNotAPartnerDentistAccountLink() { if (environment.hybrid === true) { return environment.accountDomain + '/custom-cookie?mobile-app=hubapp&slug=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentNotAPartnerDentist')).encrypted_id) + '&type=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentNotAPartnerDentist')).encrypted_type) + '&token=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentNotAPartnerDentist')).encrypted_token); } else { return environment.accountDomain + '/custom-cookie?slug=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentNotAPartnerDentist')).encrypted_id) + '&type=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentNotAPartnerDentist')).encrypted_type) + '&token=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentNotAPartnerDentist')).encrypted_token); } } } <file_sep>/src/app/patient-login-page/patient-login-page.component.ts import {Component, OnInit} from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {RedirectsService} from '../_services/redirects.service'; import {HttpClient, HttpParams} from '../../../node_modules/@angular/common/http'; import {TranslateService} from '@ngx-translate/core'; import {LanguageService} from '../_services/language.service'; import { environment } from '../../environments/environment'; import {RequestsService} from '../_services/requests.service'; import {AdditionalService} from '../_services/additional.service'; import * as $ from 'jquery'; @Component({ selector: 'app-patient-login-page', templateUrl: './patient-login-page.component.html' }) export class PatientLoginPageComponent implements OnInit { coreDbApiDomain = environment.coreDbApiDomain; missingPatientAccount = true; patientLoginEventsAdded = false; public inviter = ''; public inviteId = ''; public is_dentist_patient_relation_creation = ''; constructor(public router: Router, public authenticationServiceService: AuthenticationServiceService, public redirectsService: RedirectsService, public http: HttpClient, public translate: TranslateService, public languageService: LanguageService, public requestsService: RequestsService, public additionalService: AdditionalService, public activatedRoute: ActivatedRoute) { } ngOnInit() { if (this.authenticationServiceService.hasPatientStorageSession()) { // redirect to home if logged in this.redirectsService.redirectToLoggedHome(); } else { this.inviter = this.activatedRoute.snapshot.queryParamMap.get('invite'); if (this.activatedRoute.snapshot.queryParamMap.get('inviteid') != null) { this.inviteId = this.activatedRoute.snapshot.queryParamMap.get('inviteid'); } if (this.activatedRoute.snapshot.queryParamMap.get('is-dentist-patient-relation-creation') != null) { this.is_dentist_patient_relation_creation = 'true'; } if (!this.patientLoginEventsAdded) { this.patientLoginEventsAdded = true; document.addEventListener('patientAuthSuccessResponse', (e: any) => { console.log(e, 'patientAuthSuccessResponse'); this.onPatientsLogin(e.detail.response_data.token, e.detail.response_data.data.id, e.detail.response_data.data.patient_of); }); document.addEventListener('receiveCoredbTokenFromCivicAuth', (e: any) => { console.log(e, 'receiveCoredbTokenFromCivicAuth'); this.requestsService.getUserData(e.detail.response_data).subscribe({ next: (response: any) => { if (response.success) { this.onPatientsLogin(e.detail.response_data, response.data.id, response.data.patient_of); } else { this.authenticationServiceService.logout('patient'); } }, error: error => this.authenticationServiceService.logout('patient') }); }); document.addEventListener('receivedFacebookToken', (e: any) => { this.additionalService.showLoader(); }); document.addEventListener('civicRead', (e: any) => { this.additionalService.showLoader(); }); document.addEventListener('hideGatewayLoader', (e: any) => { this.additionalService.hideLoader(); }); document.addEventListener('registeredAccountMissingEmail', (e: any) => { document.getElementById('patient-login-failed-missing-email').classList.remove('hide'); }); document.addEventListener('patientAuthErrorResponse', (e: any) => { console.log(e, 'e'); let errorsHtml = ''; if (e.detail.response_data.not_registered) { this.missingPatientAccount = true; document.getElementById('missing-patient-account-error').classList.remove('hide'); } else { if (e.detail.response_data.errors) { for (let key in e.detail.response_data.errors) { errorsHtml += e.detail.response_data.errors[key] + '<br>'; } } document.getElementById('custom-error').classList.remove('hide'); document.getElementById('custom-error').innerHTML = errorsHtml; } if ($('.log-link.open-dentacoin-gateway').length) { $('.log-link.open-dentacoin-gateway').on('click', () => { this.redirectsService.redirectToPatientLogin('login'); }); } this.additionalService.hideLoader(); }); document.addEventListener('noCoreDBApiConnection', (e: any) => { document.getElementById('patient-login-failed').classList.remove('hide'); this.additionalService.hideLoader(); }); document.addEventListener('noExternalLoginProviderConnection', (e: any) => { document.getElementById('patient-login-failed').classList.remove('hide'); this.additionalService.hideLoader(); }); window.addEventListener('message', (event: any) => { if (event.data.event_id === 'noUserIdReceived') { document.getElementById('patient-login-failed').classList.remove('hide'); document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'registeredAccountMissingEmail') { document.getElementById('patient-login-failed-missing-email').classList.remove('hide'); document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'patientProceedWithCreatingSession') { this.onPatientsLogin(event.data.data.token, event.data.data.data.id, event.data.data.data.patient_of); document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'patientAuthErrorResponse') { let errorsHtml = ''; if (event.data.data.not_registered) { this.missingPatientAccount = true; document.getElementById('missing-patient-account-error').classList.remove('hide'); } else { if (event.data.data.errors) { for (let key in event.data.data.errors) { errorsHtml += event.data.data.errors[key] + '<br>'; } } document.getElementById('custom-error').classList.remove('hide'); document.getElementById('custom-error').innerHTML = errorsHtml; } if ($('.log-link.open-dentacoin-gateway').length) { $('.log-link.open-dentacoin-gateway').on('click', () => { this.redirectsService.redirectToPatientLogin('login'); }); } document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'noCoreDBApiConnection') { document.getElementById('patient-login-failed').classList.remove('hide'); document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'noExternalLoginProviderConnection') { document.getElementById('patient-login-failed').classList.remove('hide'); document.getElementById('iframe-civic-popup').remove(); } else if (event.data.event_id === 'removeCivicIframeAndRedirectToAccountPage') { document.getElementById('iframe-civic-popup').remove(); window.open(event.data.data.redirect, '_system'); } }); } } } // we already have the token, but we are passing the data to dcn hub app backend in order to encrypt it and save it user localstorage onPatientsLogin(_token: any, _id: any, _patient_of: any) { if (_patient_of !== null && _patient_of !== undefined) { this.requestsService.coreDbLogin(new HttpParams().set('token', _token).set('id', _id).set('patient_of', _patient_of).toString()).subscribe({ next: (coredbResponse: any) => { window.scrollTo(0, 0); if (coredbResponse.success) { window.localStorage.setItem('currentPatient', JSON.stringify({ token: _token, id: _id, patient_of: _patient_of, encrypted_id: coredbResponse.encrypted_id, encrypted_token: coredbResponse.encrypted_token, encrypted_type: coredbResponse.encrypted_type })); window.localStorage.setItem('dentist', String(_patient_of)); this.authenticationServiceService.isPatientLoggedSubject.next(true); this.redirectsService.redirectToLoggedHome(); this.additionalService.hideLoader(); } else if (coredbResponse.error) { document.getElementById('custom-error').classList.remove('hide'); document.getElementById('custom-error').innerHTML = coredbResponse.message; this.additionalService.hideLoader(); } }, error: error => { document.getElementById('patient-login-failed').classList.remove('hide'); this.additionalService.hideLoader(); } }); } else { document.getElementById('patient-login-failed-not-a-patient-of-any-dentist').classList.remove('hide'); this.additionalService.hideLoader(); } } }<file_sep>/src/app/app.component.ts import {Component, OnInit} from '@angular/core'; import {TranslateService} from '@ngx-translate/core'; import {environment} from '../environments/environment'; import {AdditionalService} from './_services/additional.service'; import {RedirectsService} from './_services/redirects.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent implements OnInit { hybrid = environment.hybrid; dentacoinDomain = environment.dentacoinDomain; production = environment.production; constructor(public translate: TranslateService, public additionalService: AdditionalService, public redirectsService: RedirectsService) { } ngOnInit() { document.addEventListener('hideLoader', (e: any) => { this.additionalService.hideLoader(); }); document.addEventListener('showLoader', (e: any) => { this.additionalService.showLoader(); }); document.addEventListener('redirectToPatientsRegisterByInvite', (e: any) => { this.redirectsService.redirectToPatientInvite(e.detail.response_data.invite, e.detail.response_data.inviteId); }); } }<file_sep>/src/app/_services/redirects.service.ts import {Injectable, NgZone} from '@angular/core'; import {Router} from '@angular/router'; import {TranslateService} from '@ngx-translate/core'; @Injectable({ providedIn: 'root' }) export class RedirectsService { constructor(private router: Router, private translate: TranslateService, private ngZone: NgZone) { } redirectToAdminLogin() { this.ngZone.run(() => this.router.navigateByUrl(this.translate.currentLang + '/admin-login')).then(); } redirectToAdmin() { this.ngZone.run(() => this.router.navigateByUrl(this.translate.currentLang + '/admin')).then(); } redirectToAdvancedAdmin() { this.ngZone.run(() => this.router.navigateByUrl(this.translate.currentLang + '/admin/advanced')).then(); } redirectToMyPatients() { this.ngZone.run(() => this.router.navigateByUrl(this.translate.currentLang + '/admin/advanced/my-patients')).then(); } redirectToLoggedHome() { this.ngZone.run(() => this.router.navigateByUrl(this.translate.currentLang + '/patients')).then(); } redirectToLandingPage() { this.ngZone.run(() => this.router.navigateByUrl(this.translate.currentLang)).then(); } redirectToDentistRequestAccount() { this.ngZone.run(() => this.router.navigateByUrl(this.translate.currentLang + '/dentist-request-account')).then(); } redirectToPatientRequestAccount() { this.ngZone.run(() => this.router.navigateByUrl(this.translate.currentLang + '/request-account')).then(); } redirectToPatientLogin(type: string) { if (type === 'account-verification') { this.ngZone.run(() => this.router.navigate([this.translate.currentLang + '/login'], {state: {successfullyVerifiedAccount: true}})).then(); } else if (type === 'change-password') { this.ngZone.run(() => this.router.navigate([this.translate.currentLang + '/login'], {state: {successfullyChangePassword: true}})).then(); } else if (type === 'login') { this.ngZone.run(() => this.router.navigateByUrl(this.translate.currentLang + '/login')).then(); } else { this.ngZone.run(() => this.router.navigateByUrl(this.translate.currentLang + '/' + type)).then(); } } redirectToMyWallet() { this.router.navigateByUrl(this.translate.currentLang + '/my-wallet'); } redirectToEditAccount() { this.router.navigateByUrl(this.translate.currentLang + '/edit-account'); } redirectToManagePrivacy() { this.router.navigateByUrl(this.translate.currentLang + '/manage-privacy'); } redirectToPatientInvite(invite: string, inviteId: string) { this.ngZone.run(() => this.router.navigateByUrl(this.translate.currentLang + '/patient-register-by-invite?invite=' + invite + '&inviteid=' + inviteId)).then(); } } <file_sep>/src/app/logged-in-wrapper/logged-in-wrapper.component.ts import {Component, OnInit} from '@angular/core'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {RedirectsService} from '../_services/redirects.service'; import {RequestsService} from '../_services/requests.service'; import {LanguageService} from '../_services/language.service'; import {TranslateService} from '@ngx-translate/core'; import {Router} from '@angular/router'; import { environment } from '../../environments/environment'; @Component({ selector: 'app-logged-in-wrapper', templateUrl: './logged-in-wrapper.component.html' }) export class LoggedInWrapperComponent implements OnInit { public dentistData: DentistDataObject = { logo: '' }; public patientData: PatientDataObject = { name: '' }; /*public applications = []; public showApplications: boolean = false;*/ public dcnAmount: number = 0; public usdAmount: number = 0; public updatePatientDcnAndUsdBalanceTimer: any; public myAccountLink: string; constructor(public authenticationServiceService: AuthenticationServiceService, public redirectsService: RedirectsService, public requestsService: RequestsService, public languageService: LanguageService, public translate: TranslateService, public router: Router) {} ngOnInit() { if (!this.authenticationServiceService.hasPatientStorageSession()) { this.redirectsService.redirectToPatientLogin('login'); } else { if (environment.hybrid === true) { document.addEventListener('shouldLogoutPatient', () => { this.authenticationServiceService.logout('patient'); }); this.myAccountLink = environment.accountDomain + '/custom-cookie?mobile-app=hubapp&slug=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_id) + '&type=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_type) + '&token=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_token); } else { this.myAccountLink = environment.accountDomain + '/custom-cookie?slug=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_id) + '&type=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_type) + '&token=' + encodeURIComponent(JSON.parse(window.localStorage.getItem('currentPatient')).encrypted_token); } this.requestsService.getDentistData(JSON.parse(window.localStorage.getItem('currentPatient')).patient_of).subscribe((response: any) => { this.dentistData.logo = response.data.logo; }); this.requestsService.getUserData(JSON.parse(window.localStorage.getItem('currentPatient')).token).subscribe({ next: (response:any) => { this.patientData.name = response.data.name; }, error: error => this.authenticationServiceService.logout('patient') }); this.updatePatientDcnAndUsdBalance(); if (typeof(this.updatePatientDcnAndUsdBalanceTimer) !== 'undefined') { clearInterval(this.updatePatientDcnAndUsdBalanceTimer); this.updatePatientDcnAndUsdBalanceTimer = undefined; } this.updatePatientDcnAndUsdBalanceTimer = setInterval(() => { if (!this.authenticationServiceService.hasPatientStorageSession()) { clearInterval(this.updatePatientDcnAndUsdBalanceTimer); this.updatePatientDcnAndUsdBalanceTimer = undefined; } else { this.updatePatientDcnAndUsdBalance(); } }, 5000); } } updatePatientDcnAndUsdBalance() { this.requestsService.getDCNBalance(JSON.parse(window.localStorage.getItem('currentPatient')).token).subscribe({ next: (response:any) => { if (response.success) { this.dcnAmount = response.data; this.requestsService.getDentacoinDataByExternalProvider('USD').subscribe((coingeckoResponse: any) => { this.usdAmount = Number(((1 / Number(Number(coingeckoResponse) / 100)) * this.dcnAmount).toFixed(2)); }); } }, error: error => this.authenticationServiceService.logout('patient') }); } isAccountPage() { if (this.router.url.indexOf('my-wallet') !== -1 || this.router.url.indexOf('edit-account') !== -1 || this.router.url.indexOf('manage-privacy') !== -1) { return true; } else { return false; } } } export interface DentistDataObject { logo: string; } export interface PatientDataObject { name: string; }<file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import {environment} from './../environments/environment'; import { PatientLoginPageComponent } from './patient-login-page/patient-login-page.component'; import { AdminComponent } from './admin/admin.component'; import { BasicAdminPanelComponent } from './admin/basic-admin-panel/basic-admin-panel.component'; import { AdvancedAdminPanelComponent } from './admin/advanced-admin-panel/advanced-admin-panel.component'; import { PushNotificationsComponent } from './admin/advanced-admin-panel/push-notifications/push-notifications.component'; import { AdminLoginComponent } from './admin-login/admin-login.component'; import { FrontEndLanguageComponent } from './front-end-language/front-end-language.component'; import { VerifyAccountComponent } from './verify-account/verify-account.component'; import { HomeComponent } from './home/home.component'; import { LandingPageComponent } from './landing-page/landing-page.component'; import { MyWalletComponent } from './my-wallet/my-wallet.component'; import { EditAccountComponent } from './edit-account/edit-account.component'; import { ManagePrivacyComponent } from './manage-privacy/manage-privacy.component'; import { LoggedInWrapperComponent } from './logged-in-wrapper/logged-in-wrapper.component'; import { RequestAccountComponent } from './request-account/request-account.component'; import { ForgottenPasswordComponent } from './forgotten-password/forgotten-password.component'; import { ChangePasswordComponent } from './change-password/change-password.component'; import { NotLoggedInWrapperComponent } from './not-logged-in-wrapper/not-logged-in-wrapper.component'; import { PatientRegisterByInviteComponent } from './patient-register-by-invite/patient-register-by-invite.component'; import { DentistRequestAccountComponent } from './dentist-request-account/dentist-request-account.component'; import { MyPatientsComponent } from './admin/advanced-admin-panel/my-patients/my-patients.component'; /*const routes: Routes = [ {path: '', pathMatch: 'full', redirectTo: '/' + environment.default_language}, {path: ':lang', component: FrontEndLanguageComponent, children: [ {path: '', component: LoggedInWrapperComponent, children: [ {path: '', component: HomeComponent}, /!*{path: 'my-wallet', component: MyWalletComponent}, {path: 'edit-account', component: EditAccountComponent}, {path: 'manage-privacy', component: ManagePrivacyComponent},*!/ ]}, {path: '', component: NotLoggedInWrapperComponent, children: [ {path: 'dentist-request-account', component: DentistRequestAccountComponent}, {path: 'request-account', component: RequestAccountComponent}, {path: 'login', component: PatientLoginPageComponent}, {path: 'patient-register-by-invite', component: PatientRegisterByInviteComponent}, /!*{path: 'forgotten-password', component: ForgottenPasswordComponent}, {path: 'change-password/:token', component: ChangePasswordComponent}, {path: 'verify-account', children: [ {path: ':token', component: VerifyAccountComponent} ]},*!/ ]}, {path: 'admin-login', component: AdminLoginComponent}, {path: 'admin', component: AdminComponent, children: [ { path: '', component: BasicAdminPanelComponent }, { path: 'advanced', component: AdvancedAdminPanelComponent, children: [ { path: 'my-patients', component: MyPatientsComponent }, { path: 'push-notifications', component: PushNotificationsComponent } ] } ] } ]}, {path: '**', redirectTo: '/' + environment.default_language} ];*/ const routes: Routes = environment.hybrid ? [ {path: '', pathMatch: 'full', redirectTo: '/' + environment.default_language}, {path: ':lang', component: FrontEndLanguageComponent, children: [ {path: '', component: LoggedInWrapperComponent, children: [ {path: '', component: HomeComponent} ]}, {path: '', component: NotLoggedInWrapperComponent, children: [ {path: 'dentist-request-account', component: DentistRequestAccountComponent}, {path: 'request-account', component: RequestAccountComponent}, {path: 'login', component: PatientLoginPageComponent}, {path: 'patient-register-by-invite', component: PatientRegisterByInviteComponent} ]} ]}, {path: '**', redirectTo: '/' + environment.default_language} ] : [ {path: '', pathMatch: 'full', redirectTo: '/' + environment.default_language}, {path: ':lang', component: FrontEndLanguageComponent, children: [ {path: '', component: LandingPageComponent}, {path: '', component: LoggedInWrapperComponent, children: [ {path: 'patients', component: HomeComponent} ]}, {path: '', component: NotLoggedInWrapperComponent, children: [ {path: 'dentist-request-account', component: DentistRequestAccountComponent}, {path: 'request-account', component: RequestAccountComponent}, {path: 'login', component: PatientLoginPageComponent}, {path: 'patient-register-by-invite', component: PatientRegisterByInviteComponent} ]}, {path: 'admin-login', component: AdminLoginComponent}, {path: 'admin', component: AdminComponent, children: [ { path: '', component: BasicAdminPanelComponent }, { path: 'advanced', component: AdvancedAdminPanelComponent, children: [ { path: 'my-patients', component: MyPatientsComponent }, { path: 'push-notifications', component: PushNotificationsComponent } ] } ] } ]}, {path: '**', redirectTo: '/' + environment.default_language} ]; @NgModule({ imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})], exports: [RouterModule] }) export class AppRoutingModule {} export const routingComponents = [FrontEndLanguageComponent, PatientLoginPageComponent, BasicAdminPanelComponent, AdminComponent, AdvancedAdminPanelComponent, PushNotificationsComponent, AdminLoginComponent, VerifyAccountComponent, HomeComponent, LandingPageComponent, MyWalletComponent, EditAccountComponent, ManagePrivacyComponent, LoggedInWrapperComponent, RequestAccountComponent, ForgottenPasswordComponent, ChangePasswordComponent, NotLoggedInWrapperComponent, PatientRegisterByInviteComponent, DentistRequestAccountComponent, MyPatientsComponent]; <file_sep>/src/app/request-account/request-account.component.ts import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {Router} from '@angular/router'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {RedirectsService} from '../_services/redirects.service'; import {HttpClient, HttpParams} from '../../../node_modules/@angular/common/http'; import {RequestsService} from '../_services/requests.service'; import {AdditionalService} from '../_services/additional.service'; import {TranslateService} from '@ngx-translate/core'; import {LanguageService} from '../_services/language.service'; @Component({ selector: 'app-request-account', templateUrl: './request-account.component.html' }) export class RequestAccountComponent implements OnInit { requestAccountForm: FormGroup; requestAccountFormSubmitted: boolean = false; sendRequestSucceed: boolean = false; sendRequestFailed: boolean = false; public notValidPhone: boolean = false; public showCountries: boolean = false; countriesList = {}; constructor(public router: Router, public formBuilder: FormBuilder, public authenticationServiceService: AuthenticationServiceService, public redirectsService: RedirectsService, public http: HttpClient, public requestsService: RequestsService, public additionalService: AdditionalService, public translate: TranslateService, public languageService: LanguageService) { } ngOnInit() { if (this.authenticationServiceService.hasPatientStorageSession()) { // redirect to home if logged in this.redirectsService.redirectToLoggedHome(); } else { this.requestsService.getCountries().subscribe((response: any) => { if (response.success && response.data) { this.countriesList = response.data; this.showCountries = true; } }); this.requestAccountForm = this.formBuilder.group({ firstName: new FormControl('', Validators.compose([ Validators.required, Validators.maxLength(100) ])), lastName: new FormControl('', Validators.compose([ Validators.required, Validators.maxLength(100) ])), email: new FormControl('', Validators.compose([ Validators.required, Validators.email ])), country: new FormControl('', Validators.compose([ Validators.required ])), phone: new FormControl('', Validators.compose([ Validators.required, Validators.maxLength(20) ])), dentistName: new FormControl('', Validators.compose([ Validators.required, Validators.maxLength(200) ])), privacyPolicy: new FormControl('', Validators.requiredTrue) }); } } get isPatientPrivacyAccepted() { return this.requestAccountForm.get('privacyPolicy'); } // convenience getter for easy access to form fields get request_form_data() { return this.requestAccountForm.controls; } // on request form account submit onAccountRequestFormSubmit() { this.additionalService.showLoader(); this.requestAccountFormSubmitted = true; this.notValidPhone = false; // stop here if form is invalid if (this.requestAccountForm.invalid) { this.additionalService.hideLoader(); return; } let paramsMap = new Map<any,any>(); paramsMap.set('firstName', this.request_form_data.firstName.value); paramsMap.set('lastName', this.request_form_data.lastName.value); paramsMap.set('email', this.request_form_data.email.value); paramsMap.set('country', this.request_form_data.country.value); paramsMap.set('phone', this.request_form_data.phone.value); paramsMap.set('dentistName', this.request_form_data.dentistName.value); /*paramsMap.set('captcha', this.request_form_data.captcha.value);*/ let params = new HttpParams(); paramsMap.forEach((value: any, key: any) => { params = params.set(key, value); }); this.requestsService.validatePhone(new HttpParams().set('phone', this.request_form_data.phone.value).set('country_code', this.request_form_data.country.value).toString()).subscribe((validatePhoneResponse: any) => { if (validatePhoneResponse.success) { this.requestsService.sendRequestAccountMail(params.toString()).subscribe((response: any) => { if (response.success) { this.requestAccountForm.reset(); Object.keys(this.requestAccountForm.controls).forEach(key => { this.requestAccountForm.get(key).setErrors(null) ; }); this.sendRequestSucceed = true; this.sendRequestFailed = false; this.additionalService.hideLoader(); } else { this.sendRequestFailed = true; this.sendRequestSucceed = false; this.additionalService.hideLoader(); } }); } else { this.notValidPhone = true; this.additionalService.hideLoader(); } }); } } <file_sep>/src/environments/environment.ts // This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. export const environment = { production: true, hybrid: false, default_language: 'en', /*dentacoinDomain: 'https://dev.dentacoin.com', coreDbApiDomain: 'https://dev-api.dentacoin.com', accountDomain: 'https://dev-account.dentacoin.com',*/ dentacoinDomain: 'https://dentacoin.com', coreDbApiDomain: 'https://api.dentacoin.com', accountDomain: 'https://account.dentacoin.com' }; /* * For easier debugging in development mode, you can import the following file * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. * * This import should be commented out in production mode because it will have a negative impact * on performance if an error is thrown. */ // import 'zone.js/dist/zone-error'; // Included with Angular CLI. <file_sep>/src/app/manage-privacy/manage-privacy.component.ts import { Component, OnInit } from '@angular/core'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {RedirectsService} from '../_services/redirects.service'; import {RequestsService} from '../_services/requests.service'; import { environment } from '../../environments/environment'; import {HttpParams} from '../../../node_modules/@angular/common/http'; @Component({ selector: 'app-manage-privacy', templateUrl: './manage-privacy.component.html' }) export class ManagePrivacyComponent implements OnInit { accountDataDownloadingFailed: boolean = false; accountDeletionFailed: boolean = false; downloadingGDPRDataFailed: boolean = false; constructor(public authenticationServiceService: AuthenticationServiceService, public redirectsService: RedirectsService, public requestsService: RequestsService) { } ngOnInit() { if (!this.authenticationServiceService.hasPatientStorageSession()) { this.redirectsService.redirectToPatientLogin('login'); } } deleteAccountMethod() { const deleteAccount = confirm('Warning! Are you sure you want to delete your account? Deleting your account is permanent action.'); if (deleteAccount === true) { this.requestsService.deleteProfile(new HttpParams().set('self_deleted', 'true').toString(), JSON.parse(window.localStorage.getItem('currentPatient')).token).subscribe({ next: (response:any) => { if (response.success && response.data) { this.authenticationServiceService.logout('patient'); } else { this.accountDeletionFailed = true; } }, error: error => this.authenticationServiceService.logout('patient') }); } } downloadGDPRDataMethod() { console.log('downloadGDPRDataMethod'); this.requestsService.downloadGDPRData(JSON.parse(window.localStorage.getItem('currentPatient')).token).subscribe({ next: (response:any) => { if (response.success && response.data) { window.open(response.data, '_system'); return false; } else { this.downloadingGDPRDataFailed = true; } }, error: error => this.authenticationServiceService.logout('patient') }); } } <file_sep>/src/app/not-logged-in-wrapper/not-logged-in-wrapper.component.ts import {Component, OnInit} from '@angular/core'; import {AuthenticationServiceService} from '../_services/authentication-service.service'; import {RequestsService} from '../_services/requests.service'; import {TranslateService} from '@ngx-translate/core'; import {LanguageService} from '../_services/language.service'; @Component({ selector: 'app-not-logged-in-wrapper', templateUrl: './not-logged-in-wrapper.component.html' }) export class NotLoggedInWrapperComponent implements OnInit { dentistLogo = ''; dentistLogoClass = ''; constructor(public authenticationServiceService: AuthenticationServiceService, public requestsService: RequestsService, public translate: TranslateService, public languageService: LanguageService) {} ngOnInit() { if (!this.authenticationServiceService.hasPatientStorageSession()) { if (window.localStorage.getItem('currentPatient') != null) { this.requestsService.getDentistData(JSON.parse(window.localStorage.getItem('currentPatient')).patient_of).subscribe((response: any) => { if (response.success) { this.dentistLogo = response.data.logo; } }); } else { this.dentistLogo = 'assets/images/one-line-logo-black.svg'; this.dentistLogoClass = 'max-width-140'; } } } } <file_sep>/src/app/admin/advanced-admin-panel/my-patients/my-patients.component.ts import {Component, OnInit} from '@angular/core'; import {HttpParams} from '../../../../../node_modules/@angular/common/http'; import {RedirectsService} from '../../../_services/redirects.service'; import {RequestsService} from '../../../_services/requests.service'; import {AuthenticationServiceService} from '../../../_services/authentication-service.service'; import {AdditionalService} from '../../../_services/additional.service'; @Component({ selector: 'app-my-patients', templateUrl: './my-patients.component.html' }) export class MyPatientsComponent implements OnInit { showInvitationHistory: boolean = false; public invites = []; constructor(public redirectsService: RedirectsService, public requestsService: RequestsService, public authenticationServiceService: AuthenticationServiceService, public additionalService: AdditionalService) { } ngOnInit() { if (!this.authenticationServiceService.hasDentistStorageSession()) { this.redirectsService.redirectToPatientLogin('login'); } else { this.requestsService.getInviteHistory(new HttpParams().set('token', JSON.parse(window.localStorage.getItem('currentDentist')).token).toString()).subscribe((response: any) => { if (response.success) { this.showInvitationHistory = true; this.invites = response.data; if (this.invites.length) { for (let i = 0; i < this.invites.length; i += 1) { this.invites[i].created_at = this.additionalService.dateObjToFormattedDate(new Date(this.invites[i].created_at)); } } } }); } } }
4adfdd2b825d56c998875368081fa2d596564458
[ "TypeScript" ]
30
TypeScript
speed57/dentacoin-hub-app
cdd72bf3cc07d5673760cb0a87186a44d97eb2b4
ead5e3fffc97f8c14d0c07519ab5fdef4857fa83
refs/heads/master
<repo_name>shenxiaolinZERO/MyProject02_MunicipalManagement<file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/readme.txt 0325.readme modify 0326£ºadd a setDateTime function at assessor.html 0327£ºresearch modal !dismiss<file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/article/updatearticle.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; using System.IO; public partial class ysmzadmin_article_updatearticle : System.Web.UI.Page { protected string pagetitle; oledata o = new oledata(); protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack== false) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet dw = new DataSet(); da.Fill(dw, "baseinfo"); DataRowView view = dw.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); OleDbConnection ole = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ole.Open(); OleDbDataAdapter db = new OleDbDataAdapter("select * from newscolumn order by columnid desc", ole); DataSet ds = new DataSet(); db.Fill(ds); DropDownList1.DataSource = ds; DropDownList1.DataTextField = "columntitle"; DropDownList1.DataValueField = "columnid"; DropDownList1.DataBind(); ole.Close(); OleDbConnection ol = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ol.Open(); OleDbDataAdapter oledb = new OleDbDataAdapter("select * from newsarticle where articleid=" + Request["articleid"], ol); DataSet dst = new DataSet(); oledb.Fill(dst,"newsarticle"); DataRowView row = dst.Tables["newsarticle"].DefaultView[0]; TextBox1.Text = Convert.ToString(row["articletitle"]); TextBox2.Text = Convert.ToString(row["articleauthor"]); TextBox3.Text = Convert.ToString(row["articlefrom"]); TextBox4.Text = Convert.ToString(row["articlecontent"]); Label7.Text = Convert.ToString(row["articletime"]); Label9.Text = Convert.ToString(row["articlepic"]); ol.Close(); } } protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("articlemanager.aspx"); } protected void Button2_Click(object sender, EventArgs e) { if(CheckBox1.Checked==true) //判断删除原来图片是否选定 { if(Label9.Text=="") //判断删除原来图片是否显示 { Response.Write("<script language=javascript> alert('不能给删除原来图片复选框打勾!');location='javascript:history.go(-1)'</script>"); } else if(File2.PostedFile.FileName=="") { FileInfo info = new FileInfo(Server.MapPath(Label9.Text.ToString())); info.Delete(); //删除原来图片 string st = "update newsarticle set articlecolumn='" + DropDownList1.Text + "',articletitle='" + TextBox1.Text + "',articleauthor='" + TextBox2.Text + "',articlefrom='" + TextBox3.Text + "',articletime='" + DateTime.Now + "',articlecontent='" + TextBox4.Text + "',articlepic='" + null + "' where articleid=" + Request["articleid"]; o.excutesql(st); //更新数据库 Response.Write("<script language=javascript> alert('更新文章成功!');location='articlemanager.aspx'</script>"); } else { Response.Write("<script language=javascript> alert('删除原来图片复选框打勾后,不能插入图片!');location='javascript:history.go(-1)'</script>"); } } else { if(File2.PostedFile.FileName=="") //判断插入图片是否有路径 { string st = "update newsarticle set articlecolumn='" + DropDownList1.Text + "',articletitle='" + TextBox1.Text + "',articleauthor='" + TextBox2.Text + "',articlefrom='" + TextBox3.Text + "',articletime='" + DateTime.Now + "',articlecontent='" + TextBox4.Text + "' where articleid=" + Request["articleid"]; o.excutesql(st); //更新数据库 Response.Write("<script language=javascript> alert('更新文章成功!');location='articlemanager.aspx'</script>"); } else { if(Label9.Text=="") //判断删除原来图片是否显示 { string p_filename = "", p_fileexename = "", m_filename, m_filepath; p_filename = this.File2.PostedFile.FileName; p_fileexename = p_filename.Substring(p_filename.LastIndexOf(".") + 1); try { m_filepath = Server.MapPath("../updateimage/"); m_filename = p_filename.Substring(p_filename.LastIndexOf("\\") + 1); File2.PostedFile.SaveAs(m_filepath + m_filename); //插入图片 Label9.Text = "../updateimage/" + m_filename; } catch (Exception err) { Response.Write(err.ToString()); } string st = "update newsarticle set articlecolumn='" + DropDownList1.Text + "',articletitle='" + TextBox1.Text + "',articleauthor='" + TextBox2.Text + "',articlefrom='" + TextBox3.Text + "',articletime='" + DateTime.Now + "',articlecontent='" + TextBox4.Text + "',articlepic='" + Label9.Text + "' where articleid=" + Request["articleid"]; o.excutesql(st); //更新数据库 Response.Write("<script language=javascript> alert('更新文章成功!');location='articlemanager.aspx'</script>"); } else { FileInfo info = new FileInfo(Server.MapPath(Label9.Text.ToString())); info.Delete(); //删除原来图片 string p_filename = "", p_fileexename = "", m_filename, m_filepath; p_filename = this.File2.PostedFile.FileName; p_fileexename = p_filename.Substring(p_filename.LastIndexOf(".") + 1); try { m_filepath = Server.MapPath("../updateimage/"); m_filename = p_filename.Substring(p_filename.LastIndexOf("\\") + 1); File2.PostedFile.SaveAs(m_filepath + m_filename); //插入图片 Label9.Text = "../updateimage/" + m_filename; } catch (Exception err) { Response.Write(err.ToString()); } string st = "update newsarticle set articlecolumn='" + DropDownList1.Text + "',articletitle='" + TextBox1.Text + "',articleauthor='" + TextBox2.Text + "',articlefrom='" + TextBox3.Text + "',articletime='" + DateTime.Now + "',articlecontent='" + TextBox4.Text + "',articlepic='" + Label9.Text + "' where articleid=" + Request["articleid"]; o.excutesql(st); //更新数据库 Response.Write("<script language=javascript> alert('更新文章成功!');location='articlemanager.aspx'</script>"); } } } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; using System.IO; public partial class ysmzadmin_login : System.Web.UI.Page { protected string pagetitle; protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); da.Fill(ds, "baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); if(!IsPostBack) { Random ra = new Random(); b4.Text = ra.Next(10000, 99999).ToString(); } } protected void Button2_Click(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if (this.t3.Text != this.b4.Text) { Response.Write("<script lanuage=javescript>alert('验证码错误!');location='javascript:history.go(-1)'</script>"); } else { OleDbConnection con = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); con.Open(); OleDbCommand com = new OleDbCommand("select * from newsuser where username='" + this.TextBox1.Text + "' and userpwd='" + this.TextBox2.Text + "'", con); int count = Convert.ToInt32(com.ExecuteScalar()); if (count > 0) { Page.Response.Redirect("~/ysmzadmin/baseinfo/baseinfo.aspx"); } else { Response.Write("<script lanuage=javescript>alert('用户名或密码错误!');location='javascript:history.go(-1)'</script>"); return; } con.Close(); } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/baseinfo/baseinfo.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; using System.IO; public partial class ysmzadmin_baseinfo_baseinfo : System.Web.UI.Page { protected string pagetitle; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter dw = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); dw.Fill(ds, "baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); oledata da = new oledata(); OleDbDataReader drd = da.executeread("select * from baseinfo"); drd.Read(); if (drd.HasRows) { this.sitenamebox.Text = drd["sitename"].ToString(); this.siteadressbox.Text = drd["siteadress"].ToString(); this.sitepostbox.Text = drd["sitepost"].ToString(); this.programerbox.Text = drd["programer"].ToString(); this.logotxt.Text = drd["logopic"].ToString(); this.banbenbox.Text = drd["banben"].ToString(); this.save.Enabled = false; } else { this.save.Enabled = true; this.reset.Enabled = false; } drd.Close(); } } protected void Button2_Click(object sender, EventArgs e) { string filepath = ""; string fileexename = ""; string mfilename, mpath; if (logotxt.Text == "") //判断原有LOGO是否存在 { if (this.File1.PostedFile.FileName == "") //判断原有现在LOGO是否有地址 { string m_updatestr = "update baseinfo set sitename='" + sitenamebox.Text + "',siteadress='" + siteadressbox.Text + "',sitepost='" + sitepostbox.Text + "',programer='" + programerbox.Text + "',banben='" + banbenbox.Text + "'"; oledata oda = new oledata(); oda.excutesql(m_updatestr); Response.Write("<script language=javascript>alert('修改成功!');location='baseinfo.aspx'</script>"); Page_Load(sender, e); } else { filepath = File1.PostedFile.FileName; fileexename = filepath.Substring(filepath.LastIndexOf(".") + 1); try { mpath = Server.MapPath("../image/"); mfilename = filepath.Substring(filepath.LastIndexOf("\\") + 1); File1.PostedFile.SaveAs(mpath + mfilename); //保存图片 this.TextBox1.Text = "../image/" + mfilename; this.TextBox1.Visible = true; } catch (Exception err) { Response.Write(err.ToString()); } string m_updatestr = "update baseinfo set sitename='" + sitenamebox.Text + "',siteadress='" + siteadressbox.Text + "',sitepost='" + sitepostbox.Text + "',programer='" + programerbox.Text + "',logopic='" + TextBox1.Text + "',banben='" + banbenbox.Text + "'"; oledata oda = new oledata(); oda.excutesql(m_updatestr); Response.Write("<script language=javascript>alert('修改成功!');location='baseinfo.aspx'</script>"); Page_Load(sender, e); } } else { if (this.File1.PostedFile.FileName == "") { string m_updatestr = "update baseinfo set sitename='" + sitenamebox.Text + "',siteadress='" + siteadressbox.Text + "',sitepost='" + sitepostbox.Text + "',programer='" + programerbox.Text + "',banben='" + banbenbox.Text + "'"; oledata oda = new oledata(); oda.excutesql(m_updatestr); Response.Write("<script language=javascript>alert('修改成功!');location='baseinfo.aspx'</script>"); Page_Load(sender, e); } else { FileInfo fi = new FileInfo(Server.MapPath(logotxt.Text.ToString())); fi.Delete(); filepath = File1.PostedFile.FileName; fileexename = filepath.Substring(filepath.LastIndexOf(".") + 1); try { mpath = Server.MapPath("../image/"); mfilename = filepath.Substring(filepath.LastIndexOf("\\") + 1); File1.PostedFile.SaveAs(mpath + mfilename); this.TextBox1.Text = "../image/" + mfilename; this.TextBox1.Visible = true; } catch (Exception err) { Response.Write(err.ToString()); } string m_updatestr = "update baseinfo set sitename='" + sitenamebox.Text + "',siteadress='" + siteadressbox.Text + "',sitepost='" + sitepostbox.Text + "',programer='" + programerbox.Text + "',logopic='" + TextBox1.Text + "',banben='" + banbenbox.Text + "'"; oledata oda = new oledata(); oda.excutesql(m_updatestr); Response.Write("<script language=javascript>alert('修改成功!');location='baseinfo.aspx'</script>"); Page_Load(sender, e); } } } protected void save_Click(object sender, EventArgs e) { string m_str = " insert into baseinfo(sitename,siteadress,sitepost,programer,logopic,banben) values ('" + sitenamebox.Text + "','" + siteadressbox.Text + "','" + sitepostbox.Text + "','" + programerbox.Text + "','" + TextBox1.Text + "','" + banbenbox.Text + "')"; oledata oda = new oledata(); bool bl = oda.excutesql(m_str); if (bl==true) { Response.Write("<script language=javascript>alert('保存成功!');location='baseinfo.aspx'</script>"); Page_Load(sender, e); } else { Response.Write("<script language=javascript>alert('保存失败!');loaction='javascript:history.go(-1)'</script>"); } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/App_Code/oledata.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; /// <summary> /// Class1 的摘要说明 /// </summary> public class oledata { #region 全局变量 /// <summary> /// 创建时间:2008.1.15 /// 创建人:史纯武 /// 用来定义全局变量 /// </summary> private OleDbConnection con; private OleDbCommand com; #endregion #region 构造函数 /// <summary> /// 创建时间:2008.1.15 /// 创建人:史纯武 /// 初始化时用来连接数据库 /// </summary> public oledata() { con = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); con.Open(); } #endregion #region 返回oleDataReader类型的数据 /// <summary> /// 创建人:史纯武 /// 创建时间:2008.1.15 /// 此方法用于返回SqlDataReader类型的数据 /// </summary> /// <param name="olecom"></param> /// <returns></returns> public OleDbDataReader executeread(string olecom) { OleDbCommand com = new OleDbCommand(olecom,con); OleDbDataReader dr = com.ExecuteReader(); return dr; } #endregion #region 执行sql语句 /// <summary> /// 创建时间:2008.1.15 /// 创建人:史纯武 /// 此方法用来执行sql语句 /// </summary> /// <param name="strsql"></param> /// <returns></returns> public bool excutesql(string strsql) { com = new OleDbCommand(strsql,con); try { com.ExecuteNonQuery(); return true; } catch { return false; } finally { con.Close(); } } #endregion #region 执行gridview的数据邦定 /// <summary> /// 创建时间:2008.1.15 /// 创建人:史纯武 /// 此方法用来邦定数据 /// </summary> /// <returns></returns> public bool executegridview(GridView gridviewn, string str,string sdk) { OleDbDataAdapter myad = new OleDbDataAdapter(str, con); DataSet ds = new DataSet(); myad.Fill(ds); gridviewn.DataSource = ds; gridviewn.DataKeyNames = new string[] { sdk }; try { gridviewn.DataBind(); return true; } catch { return false; } finally { con.Close(); } } #endregion #region 执行gridviewbind数据绑定 public void executedatabind(GridView GridviewN, string str) { OleDbDataAdapter ole = new OleDbDataAdapter(str, con); DataSet ds = new DataSet(); ole.Fill(ds); GridviewN.DataSource = ds; try { GridviewN.DataBind(); } finally { con.Close(); } } #endregion #region 用来填充数据集 public DataSet getdataset(string str, string picname) { OleDbDataAdapter odb = new OleDbDataAdapter(str, con); DataSet myds = new DataSet(); odb.Fill(myds,picname); return myds; } #endregion } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/Front-End/Municipal_02/js/waiting_assess.js /** * Created by lenovo on 2016/1/21. */ /*---------删除按钮-----------*/ $(function(){ $(".delete_btn").click(function () { //触发显示对话框事件 alert("您确定要删除该条投诉单记录吗?"); }) }); /*--------审核按钮-----------*/ $(function(){ })<file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/boarder/boardmanage.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; public partial class ysmzadmin_boarder_boardmanage : System.Web.UI.Page { protected string pagetitle; protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); da.Fill(ds, "baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); } protected void gonggaoreset_Click(object sender, EventArgs e) { this.titletext.Text = ""; this.titletext.Focus(); this.nametext.Text = ""; this.gonggaocentent.Text = ""; } protected void gonggaook_Click(object sender, EventArgs e) { if (titletext.Text != "" && nametext.Text != "" && gonggaocentent.Text != "") { string str = "insert into gonggao(title,author,centents) values('" + titletext.Text + "','" + nametext.Text + "','" + gonggaocentent.Text + "')"; oledata od = new oledata(); bool gonggao = od.excutesql(str); if (gonggao == true) { Response.Write("<script language=javascript>alert('保存成功!');location='boardmanage.aspx'</script>"); Page_Load(sender, e); } else { Response.Write("<script language=javascript>alert('保存失败!');loaction='javascript:history.go(-1)'</script>"); } } else { Response.Write("<script language=javascript>alert('不允许为空!');location='boardmanage.aspx'</script>"); } } protected void goback_Click(object sender, EventArgs e) { Page.Response.Redirect("boarderinfo.aspx"); } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/guanggao/guanggaomanager.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; public partial class ysmzadmin_guanggao_guanggaomanager : System.Web.UI.Page { protected string pagetitle; oledata ta = new oledata(); protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); da.Fill(ds, "baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); string str = "select * from guanggao order by id desc"; ta.executegridview(pic_GridView, str, "id"); } protected void pic_GridView_PageIndexChanging(object sender, GridViewPageEventArgs e) { pic_GridView.PageIndex = e.NewPageIndex; pic_GridView.DataBind(); } protected void pic_GridView_RowDeleting(object sender, GridViewDeleteEventArgs e) { string sr = pic_GridView.DataKeys[e.RowIndex].Value.ToString(); OleDbConnection le = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); le.Open(); OleDbCommand com = new OleDbCommand("delete from guanggao where id=" + sr, le); try { com.ExecuteNonQuery(); } finally { le.Close(); } OleDbConnection oe = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); oe.Open(); OleDbDataAdapter db = new OleDbDataAdapter("select * from guanggao order by id desc", oe); DataSet ds = new DataSet(); db.Fill(ds); pic_GridView.DataSource = ds; pic_GridView.DataBind(); oe.Close(); } protected void pic_GridView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { ((LinkButton)(e.Row.Cells[3].Controls[0])).Attributes.Add("onclick", "return confirm('确定要删除吗?')"); } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/Front-End/readme.txt Municipal_01:为原始审核员、接单员。 02版本去掉了接单员,超级管理员需要管理施工人员 03版本借鉴一个模板,将整体框架搭在一起。<file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/article/articleadd.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; using System.IO; public partial class ysmzadmin_article_articleadd : System.Web.UI.Page { protected string pagetitle; protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack == false) { //显示标题 string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter de = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); de.Fill(ds, "baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); //初始化数据 OleDbConnection oledb = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); oledb.Open(); OleDbDataAdapter dbd = new OleDbDataAdapter("select * from newscolumn order by columnid desc", oledb); DataSet da = new DataSet(); dbd.Fill(da); DropDownList1.DataSource = da; DropDownList1.DataTextField = "columntitle"; DropDownList1.DataValueField = "columnid"; DropDownList1.DataBind(); oledb.Close(); } } protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("articlemanager.aspx"); } protected void add_save_Click(object sender, EventArgs e) { if (DropDownList1.Text != "" && add_title.Text != "" && add_content.Text != "" && add_from.Text != "" && add_author.Text != "") { //保存图片 string myfilepath = "", myexefile = "", m_myfilepath, m_myexefile; if ("" != this.File1.PostedFile.FileName) { myfilepath = File1.PostedFile.FileName; myexefile = myfilepath.Substring(myfilepath.LastIndexOf(".") + 1); try { m_myfilepath = Server.MapPath("../updateimage/"); m_myexefile = myfilepath.Substring(myfilepath.LastIndexOf("\\") + 1); File1.PostedFile.SaveAs(m_myfilepath + m_myexefile); TextBox1.Text ="../updateimage/"+ m_myexefile; TextBox1.Visible = true; } catch (Exception err) { Response.Write(err.ToString()); } } //保存数据 string stre = "insert into newsarticle(articlecolumn,articletitle,articlecontent,articlefrom,articleauthor,articletime,articlepic) values('" + DropDownList1.Text + "','" + add_title.Text + "','" + add_content.Text + "','" + add_from.Text + "','" + add_author.Text + "','" + DateTime.Now + "','" + TextBox1.Text + "')"; OleDbConnection ole = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ole.Open(); OleDbCommand com = new OleDbCommand(stre, ole); com.ExecuteNonQuery(); ole.Close(); Response.Write("<script language=javascript>alert('恭喜恭喜!你添加成功!');location='articlemanager.aspx'</script>"); } else { Response.Write("<script language=javascript>alert('对不起!请将数据输入完整!');location='javascript:history.go(-1)'</script>"); } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/boarder/updateboardmanage.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; using System.IO; public partial class ysmzadmin_boarder_updateboardmanage : System.Web.UI.Page { protected string pagetitle; protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet dse = new DataSet(); da.Fill(dse, "baseinfo"); DataRowView view = dse.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); if (Page.IsPostBack == false) { OleDbConnection conn = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); conn.Open(); OleDbDataAdapter odt = new OleDbDataAdapter("select * from gonggao where gonggaoid=" + Request["gonggaoid"], conn); DataSet ds = new DataSet(); odt.Fill(ds, "gonggao"); DataRowView row = ds.Tables["gonggao"].DefaultView[0]; titletext_up.Text = Convert.ToString(row["title"]); nametext_up.Text = Convert.ToString(row["author"]); gonggaocentent_up.Text = Convert.ToString(row["centents"]); conn.Close(); } } protected void gonggaoreset_Click(object sender, EventArgs e) { this.titletext_up.Text = ""; this.titletext_up.Focus(); this.nametext_up.Text = ""; this.gonggaocentent_up.Text = ""; } protected void goback_Click(object sender, EventArgs e) { Page.Response.Redirect("boarderinfo.aspx"); } protected void gonggao_up_Click(object sender, EventArgs e) { string strg = "update gonggao set title='" + titletext_up.Text + "',author='" + nametext_up.Text + "',centents='" + gonggaocentent_up.Text + "' where gonggaoid="+Request.QueryString["gonggaoid"]; oledata odt = new oledata(); bool bl = odt.excutesql(strg); if (bl == true) { Response.Write("<script language=javascript>alert('恭喜你,修改成功!');loaction='boarderinfo.aspx'</script>"); Page_Load(sender, e); } else { Response.Write("<script language=javascript>alert('对不起,修改失败!');loaction='javascript:history.go.(-1)'</script>"); } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/classmanager/addclass.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; public partial class ysmzadmin_article_addclass : System.Web.UI.Page { protected string pagetitle; oledata ole = new oledata(); protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); da.Fill(ds, "baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); this.class_edit.Enabled = false; ole.executegridview(GridView1, "select * from newscolumn", "columnid"); this.GridView1.Enabled = false; } protected void class_back_Click(object sender, EventArgs e) { Response.Redirect("classmanager.aspx"); } protected void class_add_Click(object sender, EventArgs e) { if (""!=this.class_text.Text) { string strin = "insert into newscolumn(columntitle,columntime)values('" + class_text.Text + "','" + DateTime.Now + "')"; OleDbConnection ode = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ode.Open(); OleDbCommand cmd = new OleDbCommand(strin, ode); try { cmd.ExecuteNonQuery(); } finally { ode.Close(); } Response.Write("<script language=javascript>alert('添加类别成功!');location='addclass.aspx'</script>"); } else { Response.Write("<script language=javascript>alert('添加类别文本框不能空!');location='javascript:history.go(-1)'</script>"); } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/boarder/boarderinfo.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; public partial class ysmzadmin_boarder_boarderinfo : System.Web.UI.Page { protected string pagetitle; protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); da.Fill(ds, "baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); string str = "select * from gonggao order by gonggaoid desc"; oledata od = new oledata(); od.executegridview(GridView1, str, "gonggaoid"); } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; GridView1.DataBind(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { oledata ole = new oledata(); string str = this.GridView1.DataKeys[e.RowIndex].Value.ToString(); ole.excutesql("delete from gonggao where gonggaoid="+str); ole.executedatabind(GridView1,"select * from gonggao order by gonggaoid desc"); } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { ((LinkButton)(e.Row.Cells[4].Controls[0])).Attributes.Add("onclick", "return confirm('确定要删除吗?')"); } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/pictures/updatepicture.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; using System.IO; public partial class ysmzadmin_pictures_updatepicture : System.Web.UI.Page { protected string pagetitle; oledata dt = new oledata(); protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); da.Fill(ds, "baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); this.p_add.Enabled = false; DataSet dset = null; dset = dt.getdataset("select * from picture where picid=" + Request["picid"], "picture"); DataRowView row = dset.Tables["picture"].DefaultView[0]; p_txt.Text = row["picurl"].ToString(); try { this.Image1.ImageUrl = p_txt.Text; } catch { Response.Write("<script language=javascript> alert('图片显示失败!');location='updatepicture.aspx'</script>"); } } protected void p_back_Click(object sender, EventArgs e) { Response.Redirect("picturemanager.aspx"); } protected void p_edit_Click(object sender, EventArgs e) { if (this.p_File1.PostedFile.FileName == "") { Response.Write("<script language=javascript>alert('请添加图片地址!');location='javascript:history.go(-1)'</script>"); } else { FileInfo info = new FileInfo(Server.MapPath(p_txt.Text.ToString())); info.Delete(); string p_filename = "", p_fileexename = "", m_filename, m_filepath; if ("" != this.p_File1.PostedFile.FileName) { p_filename = this.p_File1.PostedFile.FileName; p_fileexename = p_filename.Substring(p_filename.LastIndexOf(".") + 1); try { m_filepath = Server.MapPath("../updateimage/"); m_filename = p_filename.Substring(p_filename.LastIndexOf("\\") + 1); p_File1.PostedFile.SaveAs(m_filepath + m_filename); p_txt.Text = "../updateimage/" + m_filename; this.p_txt.Visible = true; } catch (Exception err) { Response.Write(err.ToString()); } } } bool ol=dt.excutesql("update picture set picurl='" + p_txt.Text + "' where picid=" + Request["picid"]); if (ol == true) { Response.Write("<script language=javascript> alert('更新图片成功!');location='picturemanager.aspx'</script>"); } else { Response.Write("<script language=javascript> alert('更新图片失败!');location='javascript:history.go(-1)'</script>"); } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/classmanager/updateclass.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; public partial class ysmzadmin_article_updateclass : System.Web.UI.Page { protected string pagetitle; oledata ole = new oledata(); protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet dse = new DataSet(); da.Fill(dse, "baseinfo"); DataRowView view = dse.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); if (!IsPostBack) { this.e_add.Enabled = false; ole.executegridview(GridView1, "select * from newscolumn", "columnid"); this.GridView1.Enabled = false; OleDbConnection connection = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); connection.Open(); OleDbDataAdapter db = new OleDbDataAdapter("select * from newscolumn where columnid=" + Request["columnid"], connection); DataSet ds = new DataSet(); db.Fill(ds, "newscolumn"); DataRowView row = ds.Tables["newscolumn"].DefaultView[0]; this.TextBox1.Text = Convert.ToString(row["columntitle"]); connection.Close(); } } protected void e_back_Click(object sender, EventArgs e) { Response.Redirect("classmanager.aspx"); } protected void e_edit_Click(object sender, EventArgs e) { if (TextBox1.Text == "") { Response.Write("<script language=javascript>alert('对不起,修改文本框不能为空!');location='javascript:history.go(-1)'</script>"); } else { this.TextBox2.Text = Convert.ToString(DateTime.Now); string str = "update newscolumn set columntitle='" + TextBox1.Text + "',columntime='" + TextBox2.Text + "' where columnid=" + Request.QueryString["columnid"]; bool oo = ole.excutesql(str); if (oo == true) { Response.Write("<script language=javascript>alert('恭喜恭喜,修改成功!');location='classmanager.aspx'</script>"); } else { Response.Write("<script language=javascript>alert('对不起,修改失败!');location='javascript:history.go(-1)'</script>"); } } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/guanggao/updateguanggao.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; using System.IO; public partial class ysmzadmin_guanggao_updateguanggao : System.Web.UI.Page { protected string pagetitle; oledata dt = new oledata(); protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); da.Fill(ds, "baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); this.p_add.Enabled = false; DataSet dset = null; dset = dt.getdataset("select * from guanggao where id=" + Request["id"], "guanggao"); DataRowView row = dset.Tables["guanggao"].DefaultView[0]; p_txt.Text = row["guanggaourl"].ToString(); try { this.Image1.ImageUrl = p_txt.Text; } catch { Response.Write("<script language=javascript> alert('图片显示失败!');location='updateguanggao.aspx'</script>"); } } protected void p_back_Click(object sender, EventArgs e) { Response.Redirect("guanggaomanager.aspx"); } protected void p_edit_Click(object sender, EventArgs e) { if(this.p_File1.PostedFile.FileName=="") { Response.Write("<script language=javascript> alert('请选择要上传的文件!');location='javascript:history.go(-1)'</script>"); } else { FileInfo info = new FileInfo(Server.MapPath(p_txt.Text.ToString())); info.Delete(); string p_filename = "", p_fileexename = "", m_filename, m_filepath; if ("" != this.p_File1.PostedFile.FileName) { p_filename = this.p_File1.PostedFile.FileName; p_fileexename = p_filename.Substring(p_filename.LastIndexOf(".") + 1); try { m_filepath = Server.MapPath("../updateimage/"); m_filename = p_filename.Substring(p_filename.LastIndexOf("\\") + 1); p_File1.PostedFile.SaveAs(m_filepath + m_filename); p_txt.Text = "../updateimage/" + m_filename; this.p_txt.Visible = true; } catch (Exception err) { Response.Write(err.ToString()); } } } bool ol = dt.excutesql("update guanggao set guanggaourl='" + p_txt.Text + "' where id=" + Request["id"]); if (ol == true) { Response.Write("<script language=javascript> alert('更新广告成功!');location='guanggaomanager.aspx'</script>"); } else { Response.Write("<script language=javascript> alert('更新广告失败!');location='javascript:history.go(-1)'</script>"); } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/article/articlemanager.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; public partial class ysmzadmin_article_articlemanager : System.Web.UI.Page { protected string pagetitle; oledata olet = new oledata(); protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); da.Fill(ds,"baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); olet.executegridview(GridView1, "select * from newsarticle order by articleid desc", "articleid"); } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; GridView1.DataBind(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { string strt = this.GridView1.DataKeys[e.RowIndex].Value.ToString(); OleDbConnection ol = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ol.Open(); OleDbCommand com = new OleDbCommand("delete from newsarticle where articleid=" + strt, ol); com.ExecuteNonQuery(); ol.Close(); OleDbConnection olb = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); olb.Open(); OleDbDataAdapter db = new OleDbDataAdapter("select * from newsarticle order by articleid desc", olb); DataSet ds = new DataSet(); db.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); olb.Close(); } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { ((LinkButton)(e.Row.Cells[5].Controls[0])).Attributes.Add("onclick", "return confirm('确定要删除吗?')"); } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/classmanager/classmanager.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; public partial class ysmzadmin_article_classmanager : System.Web.UI.Page { protected string pagetitle; protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); da.Fill(ds, "baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); oledata ol = new oledata(); ol.executegridview(GridView1, "select * from newscolumn", "columnid"); } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; GridView1.DataBind(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { OleDbConnection con = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); con.Open(); string str = this.GridView1.DataKeys[e.RowIndex].Value.ToString(); OleDbCommand com = new OleDbCommand("delete from newscolumn where columnid=" + str, con); try { com.ExecuteNonQuery(); } finally { con.Close(); } OleDbConnection contion = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); contion.Open(); try { OleDbDataAdapter db = new OleDbDataAdapter("select * from newscolumn", contion); DataSet ds = new DataSet(); db.Fill(ds, "newscolumn"); GridView1.DataSource = ds; GridView1.DataBind(); } finally { contion.Close(); } } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { ((LinkButton)(e.Row.Cells[4].Controls[0])).Attributes.Add("onclick", "return confirm('确定要删除吗?')"); } } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/guanggao/addguanggao.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; public partial class ysmzadmin_guanggao_addguanggao : System.Web.UI.Page { protected string pagetitle; oledata tai = new oledata(); protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet dse = new DataSet(); da.Fill(dse, "baseinfo"); DataRowView view = dse.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); this.btnupdate.Enabled = false; string str = "select * from guanggao order by id desc"; OleDbConnection ole = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ole.Open(); OleDbDataAdapter db = new OleDbDataAdapter(str, ole); DataSet ds = new DataSet(); db.Fill(ds); this.guang_GridView.DataSource = ds; this.guang_GridView.DataBind(); guang_GridView.Enabled = false; ole.Close(); } protected void btnadd_Click(object sender, EventArgs e) { string filepath = ""; string fileexename = ""; string mfilename, mpath; if ("" != this.upimage.PostedFile.FileName) { filepath = upimage.PostedFile.FileName; fileexename = filepath.Substring(filepath.LastIndexOf(".") + 1); try { mpath = Server.MapPath("../updateimage/"); mfilename = filepath.Substring(filepath.LastIndexOf("\\") + 1); upimage.PostedFile.SaveAs(mpath + mfilename); this.pictxt.Text = "../updateimage/" + mfilename; this.pictxt.Visible = true; } catch (Exception err) { Response.Write(err.ToString()); } string xx = "insert into guanggao(guanggaourl)values('" + pictxt.Text + "')"; OleDbConnection cx = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); cx.Open(); OleDbCommand com = new OleDbCommand(xx, cx); try { com.ExecuteNonQuery(); } finally { cx.Close(); } Response.Write("<script language=javascript> alert('提交广告成功!');location='guanggaomanager.aspx'</script>"); } else { Response.Write("<script language=javascript> alert('请选择上传的广告!');location='javascript:history.go(-1)'</script>"); } } protected void backet_Click(object sender, EventArgs e) { Response.Redirect("guanggaomanager.aspx"); } } <file_sep>/MyProject02_MunicipalManagement/MyProject02_MunicipalManagement/网站后台管理模板(4个)/教育网站后台管理系统源代码/ysmzadmin/pictures/picturemanager.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; using System.IO; public partial class ysmzadmin_pictures_picturemanager : System.Web.UI.Page { protected string pagetitle; oledata ta = new oledata(); protected void Page_Load(object sender, EventArgs e) { string strsql = "select * from baseinfo"; OleDbConnection ll = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ll.Open(); OleDbDataAdapter da = new OleDbDataAdapter(strsql, ll); DataSet ds = new DataSet(); da.Fill(ds, "baseinfo"); DataRowView view = ds.Tables["baseinfo"].DefaultView[0]; pagetitle = Convert.ToString(view["sitename"]) + Convert.ToString(view["programer"]); ll.Close(); string str = "select * from picture order by picid desc"; ta.executegridview(pic_GridView, str, "picid"); } protected void pic_GridView_PageIndexChanging(object sender, GridViewPageEventArgs e) { pic_GridView.PageIndex = e.NewPageIndex; pic_GridView.DataBind(); } protected void pic_GridView_RowDeleting(object sender, GridViewDeleteEventArgs e) { OleDbConnection ole = new OleDbConnection(ConfigurationManager.AppSettings["constr"]); ole.Open(); string ting = this.pic_GridView.DataKeys[e.RowIndex].Value.ToString(); OleDbDataAdapter db = new OleDbDataAdapter("select * from picture where picid="+ting, ole); DataSet ds = new DataSet(); db.Fill(ds, "picture"); DataRow[] row = ds.Tables[0].Select(); foreach (DataRow r in row) { if (r["picurl"].ToString() != "") { FileInfo fi=new FileInfo(Server.MapPath("../updateimage/"+r["picurl"].ToString())); fi.Delete(); } } ole.Close(); OleDbConnection oledb=new OleDbConnection(ConfigurationManager.AppSettings["constr"]); oledb.Open(); OleDbCommand cmd=new OleDbCommand("delete from picture where picid="+ting,oledb); cmd.ExecuteNonQuery(); OleDbDataAdapter dba=new OleDbDataAdapter("select * from picture order by picid desc",oledb); DataSet dst=new DataSet(); dba.Fill(dst); this.pic_GridView.DataSource=dst; this.pic_GridView.DataBind(); oledb.Close(); } protected void pic_GridView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { ((LinkButton)(e.Row.Cells[3].Controls[0])).Attributes.Add("onclick", "return confirm('您确定删除吗?')"); } } }
bce639167a81a5148bc5eca8cbab05d79155170e
[ "JavaScript", "C#", "Text" ]
20
Text
shenxiaolinZERO/MyProject02_MunicipalManagement
315b02e566d4df520eccae517ee4d54a62c69257
33b90aae6c62bc381a02ff36a93706a17d32f0e4
refs/heads/master
<repo_name>JudeBake/svnserve_svndmin<file_sep>/README.md # centos_svn_ssh_svadmin CentOS SVN Server setup for ssh and SVNAdmin Web UI <file_sep>/Dockerfile # From CentOS FROM linuxserver/openssh-server # Install Depedencies RUN apk update RUN apk add --no-cache subversion # Setup sebversion RUN addgroup -S svn-tunnel && adduser -S svn-tunnel -G svn-tunnel USER appuser # Create repos directory RUN mkdir ~/svn RUN mkdir ~./ssh # Expose the svn directory VOLUME [ "/home/svn-tunnel/.ssh" ] VOLUME [ "/home/svn-tunnel/svn" ] <file_sep>/deploy.sh ssh jbacon@192.168.5.235 'test -d ~/svnserve_svnadmin || mkdir ~/svnserve_svnadmin' rsync -avz . jbacon@192.168.5.235:svnserve_svnadmin
d818721f9cc27d9a5a00372b2e702ffbe1d8a07c
[ "Markdown", "Dockerfile", "Shell" ]
3
Markdown
JudeBake/svnserve_svndmin
d6cf447e31c62b2d64183bff2b231a879ab90631
6d728c582ed145a3bf0fee68577f921b7711ea4e
refs/heads/main
<file_sep> #include "minitalk.h" static t_msg g_msg; void get_len(int bit) { g_msg.c += ((bit & 1) << g_msg.size); g_msg.size++; if (g_msg.size == 7) { g_msg.len *= 10; g_msg.len += g_msg.c - '0'; g_msg.c = 0; g_msg.size = 0; } } void get_bit_by_bit(int bit) { g_msg.c += ((bit & 1) << g_msg.size); g_msg.size++; if (g_msg.size == 7) { *g_msg.msg = g_msg.c; (*g_msg.msg)++; if (!g_msg.c) { *g_msg.msg = 0; (*g_msg.msg) -= g_msg.len; ft_putstr(g_msg.msg); } g_msg.c = 0; g_msg.size = 0; } } void usr1(int s) { } int main(void) { struct sigaction sa; sa.sa_handler = &usr1; sigaction(SIGUSR1, &sa, NULL); g_msg.c = 0; g_msg.size = 0; g_msg.len = 0; ft_putstr("server pid : "); ft_putnbr(getpid()); ft_putchar('\n'); signal(SIGUSR2, get_len); signal(SIGUSR1, get_len); g_msg.msg = malloc(g_msg.len); while (1) { signal(SIGUSR2, get_bit_by_bit); signal(SIGUSR1, get_bit_by_bit); pause(); } } <file_sep>#include "minitalk.h" void send_bit_by_bit(int pid, char *msg, size_t len) { int shift; size_t i; i = 0; while (i <= len) { shift = 0; while (shift < 7) { if ((msg[i] >> shift) & 1) kill(pid, SIGUSR2); else kill(pid, SIGUSR1); shift++; usleep(100); } i++; } } int main(int ac, char **av) { int pid; if (ac == 3) { pid = atoi(av[1]); send_bit_by_bit(pid, av[2], ft_strlen(av[2])); } else ft_putstr("usage:\n./client [server_pid] \"[msg_to_send]\"\n"); return (0); } <file_sep>#include "minitalk.h" static t_msg g_msg; void get_bit_by_bit(int bit) { g_msg.c += ((bit & 1) << g_msg.size); g_msg.size++; if (g_msg.size == 7) { ft_putchar(g_msg.c); if (!g_msg.c) ft_putchar('\n'); g_msg.c = 0; g_msg.size = 0; } } int main(void) { g_msg.c = 0; g_msg.size = 0; ft_putstr("server pid : "); ft_putnbr(getpid()); ft_putchar('\n'); while (1) { signal(SIGUSR2, get_bit_by_bit); signal(SIGUSR1, get_bit_by_bit); pause(); } } <file_sep>NAME1 = server NAME2 = client all : make -C libft gcc -Wall -Wextra -Werror server.c libft/libft.a -o $(NAME1) gcc -Wall -Wextra -Werror client.c libft/libft.a -o $(NAME2) clean : make clean -C libft rm -rf client.o server.o fclean : clean make fclean -C libft rm -rf $(NAME1) $(NAME2) re : fclean all
f44dbc638a703c7205fd8880ea5f224a5dab0d80
[ "C", "Makefile" ]
4
C
zensushi/minitalk
2e284face95dc09f730614a07c7400351d7d9998
d649d441422aa6eadb8df59125c3c958c87a8877
refs/heads/master
<file_sep>package com.uw.hw6b; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; public class Dijkstra { private String filePath; private SimpleGraph simpleGraph; private Hashtable<String, Vertex> hashTable; private ArrayList<DijkstraHeapNode> calculatedPath; public static Dijkstra loadGraphForDijkstra(String fileName) { return new Dijkstra(fileName); } @SuppressWarnings("unchecked") private Dijkstra(String filePath) { this.filePath = filePath; this.simpleGraph = new SimpleGraph(); if (!filePath.equals("")) { hashTable = GraphInput.LoadSimpleGraph(simpleGraph, filePath); Iterator<Vertex> iter = simpleGraph.vertices(); // iterating each vertex of the graph while (iter.hasNext()) { Vertex v = iter.next(); DijkstraHeapNode heapNode = new DijkstraHeapNode(v); v.setData(heapNode); // associating the DijkstraHeapNode // object with Vertex object } System.out.println(hashTable.toString()); } } public String getCurrentFilePath() { return this.filePath; } public SimpleGraph getGraph() { return this.simpleGraph; } public Hashtable<String, Vertex> getVertexTable() { return this.hashTable; } public ArrayList<DijkstraHeapNode> getCalculatedPath() { return this.calculatedPath; } public void calculatePath(String start, String end) { this.calculatedPath = calculateAndReturnPath(start, end); } private ArrayList<DijkstraHeapNode> calculateAndReturnPath(String start, String end) { start = start.trim(); end = end.trim(); if (hashTable.containsKey(start) && hashTable.containsKey(end)) { Vertex startV = hashTable.get(start); Vertex endV = hashTable.get(end); // Dijsktra algorithm implementation begins DijkstraMinHeap heap = new DijkstraMinHeap(); @SuppressWarnings("unchecked") Iterator<Vertex> iter = simpleGraph.vertices(); // iterating each vertex of the graph while (iter.hasNext()) { Vertex v = iter.next(); DijkstraHeapNode dhn = (DijkstraHeapNode) v.getData(); dhn.init(); heap.insert(dhn); // inserting every // DijkstraHeapNode object into // heap } DijkstraHeapNode startDhn = (DijkstraHeapNode) startV .getData(); startDhn.updateDistanceIfLess(0, null); // updating the // distance of the // starting // node/vertex for (int i = 0; i < simpleGraph.vertexList.size(); i++) // running // this // loop // |V| // times { try { DijkstraHeapNode uDhn = heap.deleteMin(); // Capturing the node deleted // from heap Vertex u = uDhn.getMyNode(); // finding the associated vertex // of the deleted DijkstraHeapNode @SuppressWarnings("unchecked") Iterator<Edge> iterEdge = u.incidentEdgeList .iterator(); while (iterEdge.hasNext()) // iterating each neighboring vertex of // the vertex in the known set { // and updating the distance accordingly Edge edge = iterEdge.next(); Vertex v = simpleGraph.opposite(u, edge); DijkstraHeapNode vDhn = (DijkstraHeapNode) v .getData(); if (vDhn.getHeapIndex() > 0) { double distance = uDhn.getDistance() + (Double) edge.getData(); vDhn.updateDistanceIfLess(distance, u); } } } catch (EmptyHeapException exception) { exception.printStackTrace(); } } DijkstraHeapNode dhn = (DijkstraHeapNode) endV.getData(); ArrayList<DijkstraHeapNode> nodeList = new ArrayList<DijkstraHeapNode>(); nodeList.add(0, dhn); while (dhn.getPreviousNode() != null) { dhn = (DijkstraHeapNode) dhn.getPreviousNode() .getData(); nodeList.add(0, dhn); } return nodeList; // // StringBuilder sb = new StringBuilder(); // sb.append("PATH: \n"); // for (DijkstraHeapNode dh : nodeList) { // sb.append("City: "); // sb.append(dh.getMyNode().getName()); // sb.append(" -- Total Distance: "); // sb.append(dh.getDistance()); // sb.append("\n"); // } // //PATH = sb.toString(); //System.out.println(PATH); } else { return null; } } } <file_sep>package com.uw.hw6b; import com.uw.hw6b.DijkstraHeapNode.DistanceUpdateListener; //Modified by Group 6 /** * A binary minheap of DijkstraHeapNode objects. * * @author <NAME> * @version September 19, 2003 */ public class DijkstraMinHeap implements DistanceUpdateListener{ /* the heap is organized using the implicit array implementation. * Array index 0 is not used */ private DijkstraHeapNode[] elements; private int size; // index of last element in the heap // Constructor public DijkstraMinHeap() { int initialCapacity = 10; this.elements = new DijkstraHeapNode[initialCapacity + 1]; this.elements[0] = null; this.size = 0; } /** * Constructor * @param capacity number of active elements the heap can contain */ public DijkstraMinHeap(int capacity) { this.elements = new DijkstraHeapNode[capacity + 1]; this.elements[0] = null; this.size = 0; } /** * Given an array of Comparables, return a binary heap of those * elements. * @param data an array of data (no particular order) * @return a binary heap of the given data */ public static DijkstraMinHeap buildHeap(DijkstraHeapNode[] data) { DijkstraMinHeap newHeap = new DijkstraMinHeap(data.length); for (int i = 0; i < data.length; i++) { newHeap.elements[i+1] = data[i]; newHeap.elements[i+1].setHeapIndex(i + 1); newHeap.elements[i+1].registerDistanceUpdateListener(newHeap); } newHeap.size = data.length; for (int i = newHeap.size / 2; i > 0; i--) { newHeap.percolateDown(i); } return newHeap; } /** * Determine whether the heap is empty. * @return true if the heap is empty; false otherwise */ public boolean isEmpty() { return (size < 1); } /** * Insert an object into the heap. * @param key a key */ public void insert(DijkstraHeapNode key) { if (size >= elements.length - 1) { // not enough room -- create a new array and copy // the elements of the old array to the new DijkstraHeapNode[] newElements = new DijkstraHeapNode[2*size]; for (int i = 0; i < elements.length; i++) { newElements[i] = elements[i]; } elements = newElements; } size++; elements[size] = key; elements[size].setHeapIndex(size); elements[size].registerDistanceUpdateListener(this); percolateUp(size); } /** * Remove the object with minimum key from the heap. * @return the object with minimum key of the heap */ public DijkstraHeapNode deleteMin() throws EmptyHeapException { if (!isEmpty()) { DijkstraHeapNode returnValue = elements[1]; elements[1] = elements[size]; elements[1].setHeapIndex(1); size--; percolateDown(1); returnValue.setHeapIndex(0); returnValue.unregisterDistanceUpdateListener(); return returnValue; } else { throw new EmptyHeapException(); } } /** * Given an index in the heap array, percolate that key up the heap. * @param index an index into the heap array */ private void percolateUp(int index) { DijkstraHeapNode temp = elements[index]; // keep track of the item to be moved while (index > 1) { if (temp.compareTo(elements[index/2]) < 0) { elements[index] = elements[index/2]; elements[index].setHeapIndex(index); index = index / 2; } else { break; } } elements[index] = temp; elements[index].setHeapIndex(index); } /** * Given an index in the heap array, percolate that key down the heap. * @param index an index into the heap array */ private void percolateDown(int index) { int child; DijkstraHeapNode temp = elements[index]; while (2*index <= size) { child = 2 * index; if ((child != size) && (elements[child + 1].compareTo(elements[child]) < 0)) { child++; } // ASSERT: at this point, elements[child] is the smaller of // the two children if (elements[child].compareTo(temp) < 0) { elements[index] = elements[child]; elements[index].setHeapIndex(index); index = child; } else { break; } } elements[index] = temp; elements[index].setHeapIndex(index); } @Override public void onDistanceUpdate(int index) { this.percolateUp(index); } }
2bc0aa53e71eb6b0a4fded7ba43a7a5d490d6d51
[ "Java" ]
2
Java
sharmasamiksha/dijkstra
4248cbdb8b663b5d2f54c95a9f8b8f5d6ac84d3e
8977924cc50c2ee0b93020573e25126104972f33
refs/heads/master
<repo_name>roman-zm/multMatrs<file_sep>/fraction.cpp #include "fraction.h" #include <iostream> fraction::fraction() { numerator = 1; denominator = 1; } int gcd(int first, int second){ int q; if( first%second == 0) q = second; else { while( first%second !=0 ){ q = first%second; first=second; second=q; } } return q; } int fraction::getDenominator(){ return denominator; } int fraction::getNumenator(){ return numerator; } void fraction::setNumerator(int input){ numerator = input; } void fraction::setDenominator(int input){ denominator = input; } void fraction::print(){ std::cout<<numerator<<"/"<<denominator; } void fraction::reduce(){ int divisor = gcd(numerator, denominator); numerator /= divisor; denominator /= divisor; } double fraction::toDouble(){ return numerator/denominator; } //-------------------------reloaded operators std::ostream& operator <<(std::ostream& os, const fraction& frac){ os << frac.numerator <<"/"<< frac.denominator; return os; } std::istream& operator >>(std::istream& is, fraction& frac){ int a,b; is >> a >> b; frac.setNumerator(a); frac.setDenominator(b); return is; } fraction fraction::operator *(fraction inFraction){ fraction response = *this; response.numerator *= inFraction.numerator; response.denominator *= inFraction.denominator; //response.reduce(); return response; } fraction fraction::operator /(fraction inFraction){ fraction response = *this; response.numerator *= inFraction.denominator; response.denominator *= inFraction.numerator; //response.reduce(); return response; } fraction fraction::operator +(fraction inFraction){ fraction response = *this; response.numerator *= inFraction.denominator; response.denominator *= inFraction.denominator; inFraction.numerator *= this->denominator; response.numerator += inFraction.numerator; response.reduce(); return response; } fraction fraction::operator -(fraction inFraction){ fraction response = *this; response.numerator *= inFraction.denominator; response.denominator *= inFraction.denominator; inFraction.numerator *= this->denominator; response.numerator -= inFraction.numerator; response.reduce(); return response; } fraction fraction::operator *(int inInt){ fraction response = *this; response.numerator *= inInt; response.reduce(); return response; } fraction fraction::operator /(int inInt){ fraction response = *this; response.denominator *= inInt; response.reduce(); return response; } <file_sep>/main.cpp #include <iostream> #include <matrix.h> #include <fraction.h> using namespace std; int main(int argc, char *argv[]) { matrix matr; matr.enterMatrix(); fraction deter = det(matr); matr.print(); cout<<endl<<deter; return 0; } <file_sep>/matrix.cpp #include "matrix.h" #include "fraction.h" #include <algorithm> #include <iomanip> #include <iostream> #include <vector> #include <cmath> matrix::matrix() { // enterMatrix(); } matrix::~matrix(){ clear(); } fraction det(matrix inMatrix){ return inMatrix.det(); } fraction matrix::det(matrix inMatrix){ fraction response; if(inMatrix.size(0)==inMatrix.size(1)){ if(inMatrix.size(0)==2){ response = inMatrix[0][0]*inMatrix[1][1] - inMatrix[0][1]*inMatrix[1][0]; } else if(inMatrix.size(0)==1) { response = inMatrix[0][0]; } else { response.setNumerator(0); for(size_t i = 0; i<inMatrix.size(0); i++){ matrix Minor = getMinor(inMatrix, 0, i); response = response + inMatrix[0][i]*pow(-1.0,i)*det(Minor); } } } return response; } fraction matrix::det(){ return det(*this); } void matrix::clear(){ matr.clear(); } void matrix::enterMatrix(){ clear(); size_t a, b; std::cout << "Enter number of rows and columns" << std::endl; std::cin >> a >> b; for (size_t i = 0; i < a; i++) { std::vector<fraction> temp; for (size_t j = 0; j < b; j++) { fraction n; std::cout << "A(" << i + 1 << "," << j + 1 << ") = "; std::cin >> n; temp.push_back(n); } matr.push_back(temp); } } std::vector< std::vector<fraction> > matrix::toVector(){ return matr; } std::vector<fraction> matrix::operator [](std::size_t idx){ return matr[idx]; } size_t matrix::size(unsigned depth){ if(depth==0) return matr.size(); else if(depth == 1) return matr[0].size(); else return 0; } matrix matrix::operator /(fraction number){ for(size_t i=0; i<this->size(0);i++){ for(size_t j=0; j<this->size(1); j++){ fraction dTemp = matr[i][j]; matr[i][j] = dTemp/number; } } return *this; } matrix matrix::operator *(fraction number){ for(size_t i=0; i<this->size(0);i++){ for(size_t j=0; j<this->size(1); j++){ fraction dTemp = matr[i][j]; matr[i][j] = dTemp*number; } } return *this; } void matrix::push_back(std::vector<fraction> temp){ matr.push_back(temp); } matrix getMinor(matrix inMatrix, size_t exclRow, size_t exclCol){ return inMatrix.getMinor(exclRow, exclCol); } matrix matrix::getMinor(matrix inMatrix, size_t exclRow, size_t exclCol){ unsigned ri=0, ci=0; matrix response; for(size_t i=0; i<inMatrix.size(0)-1; i++){ std::vector<fraction> temp; if(i>=exclRow) ri=1; for(size_t j=0; j<inMatrix.size(0)-1; j++){ if(j>=exclCol)ci=1; temp.push_back(inMatrix[i+ri][j+ci]); ci=0; } response.push_back(temp); } return response; } matrix matrix::getMinor(size_t exclRow, size_t exclCol){ return getMinor(*this, exclRow, exclCol); } matrix matrix::operator -(matrix inMatrix){ fraction negOne; negOne.setNumerator(-1); inMatrix = inMatrix * negOne ; return *this+inMatrix; } matrix matrix::operator +(matrix inMatrix){ for(size_t i=0; i<this->size(0); i++){ for(size_t j=0; j<this->size(1); j++){ matr[i][j] = matr[i][j] + inMatrix[i][j]; } } return *this; } matrix matrix::operator *(matrix inMatrix){ std::vector< std::vector<fraction> > result; if(inMatrix.size(0) != this->size(1)){ this->clear(); return *this; } for (size_t i = 0; i < this->size(0); i++) { std::vector<fraction> temp; for (size_t j = 0; j < inMatrix.size(1); j++) { fraction sum; sum.setNumerator(0); for (size_t ri = 0; ri < inMatrix.size(0); ri++) { sum = sum + matr[i][ri] * inMatrix[ri][j]; } temp.push_back(sum); } result.push_back(temp); } matr.clear(); matr = result; return *this; } void matrix::print(){ for (size_t i = 0; i < matr.size(); i++) { for (size_t j = 0; j < matr[i].size(); j++) { //std::cout << std::left << std::setw(5) << matr[i][j]; std::cout << std::left << matr[i][j].getNumenator()<<"/"<< std::setw(5)<<matr[i][j].getDenominator(); } std::cout << std::endl; } } matrix getInversiveMatrix(matrix inMatrix){ return inMatrix.getInversiveMatrix(); } matrix matrix::getInversiveMatrix(matrix inMatrix){ matrix response; for(size_t i=0; i<inMatrix.size(0); i++){ std::vector<fraction> temp; for(size_t j=0; j<inMatrix.size(1); j++){ matrix Minor = getMinor(inMatrix, i, j); fraction dTemp = det(Minor)*pow(-1.0,i+j); temp.push_back( dTemp ); } response.push_back(temp); } fraction number = det(inMatrix); response = transposeMatrix(response); response = response*number; return response; } matrix matrix::getInversiveMatrix(){ return getInversiveMatrix(*this); } matrix transposeMatrix(matrix inMatrix){ return inMatrix.transposeMatrix(); } matrix matrix::transposeMatrix(matrix inMatrix){ matrix response; for(size_t i =0; i<inMatrix.size(1); i++){ std::vector<fraction> temp; for(size_t j=0; j<inMatrix.size(0); j++){ temp.push_back(inMatrix[j][i]); } response.push_back(temp); } return response; } matrix matrix::transposeMatrix(){ return transposeMatrix(*this); } <file_sep>/fraction.h #ifndef FRACTION_H #define FRACTION_H #include <iostream> class fraction { public: fraction(); void setNumerator(int input); void setDenominator(int input); int getNumenator(); int getDenominator(); void print(); void reduce(); double toDouble(); friend std::ostream& operator <<(std::ostream& os, const fraction& frac); friend std::istream& operator >>(std::istream& is, fraction& frac); fraction operator +(fraction inFraction); fraction operator -(fraction inFraction); fraction operator *(fraction inFraction); fraction operator /(fraction inFraction); fraction operator +(int inInt); fraction operator -(int inInt); fraction operator *(int inInt); fraction operator /(int inInt); // fraction operator =(int inInt); private: int numerator; int denominator; }; int gcd(int first, int second); #endif // FRACTION_H <file_sep>/matrix.h #ifndef MATRIX_H #define MATRIX_H #include "fraction.h" #include <vector> #include <sys/types.h> class matrix { public: matrix(); ~matrix(); void enterMatrix(); void print(); void clear(); void push_back(std::vector<fraction> temp); std::size_t size(unsigned depth); std::vector< std::vector<fraction> > toVector(); std::vector<fraction> operator [](std::size_t idx); friend fraction det(matrix inMatrix); friend matrix getInversiveMatrix(matrix inMatrix); friend matrix getMinor(matrix inMatrix, size_t exclRow, size_t exclCol); friend matrix transposeMatrix(matrix inMatrix); fraction det(); matrix getInversiveMatrix(); matrix getMinor(size_t exclRow, size_t exclCol); matrix transposeMatrix(); matrix operator +(matrix inMatrix); matrix operator -(matrix inMatrix); matrix operator +(fraction number); matrix operator -(fraction number); matrix operator *(matrix inMatrix); matrix operator *(fraction number); matrix operator /(fraction number); private: std::vector< std::vector<fraction> > matr; fraction det(matrix inMatrix); matrix getInversiveMatrix(matrix inMatrix); matrix getMinor(matrix inMatrix, size_t exclRow, size_t exclCol); matrix transposeMatrix(matrix inMatrix); }; #endif // MATRIX_H
1be3ccd407f91a35159ed7b47cdd433a88e38c63
[ "C++" ]
5
C++
roman-zm/multMatrs
e0690455582d595a03deb06dfbe3298349086c4b
8530e6f95973250e92d04e5e4108335dbb05e924
refs/heads/master
<file_sep>import { UserDb } from './user-types'; export interface FlightApplyDb { id?: number; uid?: string; passenger_name?: string; passenger_mobile?: string; departure_flight_number?: string; departure_time?: string; back_flight_number?: string; back_time?: string; ID_number?: string; flight_apply_submission_time?: string; is_flight_book_succeed?: number; flight_apply_update_time?: string; remark?: string; is_flight_apply_cancel?: number; } export interface FlightApplyUserViewDb extends FlightApplyDb, UserDb { } export interface FlightApplyGetRes { id?: number; uid?: string; enName?: string; jobNumber?: string; mobile?: string; passengerName?: string; passengerMobile?: string; departureFlightNumber?: string; departureTime?: string; backFlightNumber?: string; backTime?: string; IDNumber?: string; flightApplySubmissionTime?: string; isFlightBookSucceed?: number; flight_apply_update_time?: string; remark?: string; isFlightApplyCancel?: number; } export interface FlightApplyUpdateRes { isUpdateSuccess: boolean; } export interface FlightApplyDeleteRes { isDeleteSuccess: boolean; }<file_sep>import { ResponseUtils, date_utils } from '@service-fw'; import { vehicle_arrange_dao, VehicleArrangeGetRes, VehicleArrangeDeleteRes, VehicleArrangeUpdateRes } from '../dao'; /** * 添加用车安排 */ export async function postVehicleArrange(ctx) { const body = ctx.request.body; const param = { uid: body.uid, passenger_mobile: body.passenger_mobile, driver_name: body.driver_name, driver_mobile: body.driver_mobile, voiture_number: body.voiture_number, voiture_type: body.voiture_type, voiture_color: body.voiture_color, voiture_seats: body.voiture_seats, remaining_seats: body.remaining_seats, vehicle_arrange_departure_time: body.vehicle_arrange_departure_time, vehicle_arrange_departure_place: body.vehicle_arrange_departure_place, vehicle_arrange_reach_place: body.vehicle_arrange_reach_place, vehicle_arrange_is_round: body.vehicle_arrange_is_round, is_vehicle_arrange: body.is_vehicle_arrange, remark: body.remark, vehicle_arrange_add_time: body.vehicle_arrange_add_time, vehicle_arrange_update_time: body.vehicle_arrange_update_time, is_vehicle_arrange_cancel: body.is_vehicle_arrange_cancel }; const vehicleArrangeModel = { uid: null, passenger_mobile: null, driver_name: null, driver_mobile: null, voiture_number: null, voiture_type: null, voiture_color: null, voiture_seats: null, remaining_seats: null, vehicle_arrange_departure_time: null, vehicle_arrange_departure_place: null, vehicle_arrange_reach_place: null, vehicle_arrange_is_round: null, is_vehicle_arrange: null, remark: null, vehicle_arrange_add_time: null, vehicle_arrange_update_time: null, is_vehicle_arrange_cancel: null }; Object.keys(vehicleArrangeModel).forEach(item => { vehicleArrangeModel[item] = param[item]; }); vehicleArrangeModel.vehicle_arrange_add_time = date_utils.getNowDateString(); const insertResult = await vehicle_arrange_dao.insertVehicleArrange(vehicleArrangeModel); if (insertResult[0] <= 0) { return ctx.body = ResponseUtils.error({ error_no: 100102 }); } const getResult1 = await vehicle_arrange_dao.getVehicleArrange({ id: insertResult[0] }); const resData = vehicle_arrange_dao.formatVehicleApplyVehicleArrangeUserViewDb(getResult1[0]); return ctx.body = ResponseUtils.normal<VehicleArrangeGetRes>({ data: resData }); } /** * 删除用车安排 */ export async function deleteVehicleArrange(ctx) { const param = { id: ctx.params.id }; const vehicleArrangeModel = { is_vehicle_arrange_cancel: null }; Object.keys(vehicleArrangeModel).forEach(item => { vehicleArrangeModel[item] = param[item]; }); const getResult = await vehicle_arrange_dao.getVehicleArrange({ id: param.id, is_vehicle_arrange_cancel: 0 }); if (getResult.length === 0) { return ctx.body = ResponseUtils.error({ error_no: 100103, error_message: '删除失败,不存在该用车安排!' }); } // 删除用车安排 vehicleArrangeModel.is_vehicle_arrange_cancel = 1; const updateResult = await vehicle_arrange_dao.updateVehicleArrange(param.id, vehicleArrangeModel); if (updateResult !== 1) { // 删除失败(更新失败) return ctx.body = ResponseUtils.error({ error_no: 100103 }); } // 返回删除结果 ctx.body = ResponseUtils.normal<VehicleArrangeDeleteRes>({ data: { isDeleteSuccess: true } }); } /** * 更新用车安排 */ export async function putVehicleArrange(ctx) { const param = { id: ctx.params.id }; const vehicleArrangeModel = { passenger_mobile: null, driver_name: null, driver_mobile: null, voiture_number: null, voiture_type: null, voiture_color: null, voiture_seats: null, remaining_seats: null, vehicle_arrange_departure_time: null, vehicle_arrange_departure_place: null, vehicle_arrange_reach_place: null, vehicle_arrange_is_round: null, is_vehicle_arrange: null, remark: null, vehicle_arrange_update_time: null, is_vehicle_arrange_cancel: null }; Object.keys(vehicleArrangeModel).forEach(item => { vehicleArrangeModel[item] = ctx.request.body[item]; }); const getResult = await vehicle_arrange_dao.getVehicleArrange({ id: param.id, is_vehicle_arrange_cancel: 0 }); if (getResult.length <= 0) { return ctx.body = ResponseUtils.error({ error_no: 100101, error_message: '更新失败,不存在该用车安排!' }); } vehicleArrangeModel.vehicle_arrange_update_time = date_utils.getNowDateString(); const updateResult = await vehicle_arrange_dao.updateVehicleArrange(param.id, vehicleArrangeModel); if (updateResult !== 1) { // 更新失败 return ctx.body = ResponseUtils.error({ error_no: 100101 }); } return ctx.body = ResponseUtils.normal<VehicleArrangeUpdateRes>({ data: { isUpdateSuccess: true } }); } /** * 查询用车安排 */ export async function getVehicleArrange(ctx) { const query = ctx.request.query; const param = { id: query.id, uid: query.uid, passenger_mobile: query.passenger_mobile, driver_name: query.driver_name, driver_mobile: query.driver_mobile, voiture_number: query.voiture_number, voiture_type: query.voiture_type, voiture_color: query.voiture_color, voiture_seats: query.voiture_seats, remaining_seats: query.remaining_seats, vehicle_arrange_departure_time: query.vehicle_arrange_departure_time, vehicle_arrange_departure_place: query.vehicle_arrange_departure_place, vehicle_arrange_reach_place: query.vehicle_arrange_reach_place, vehicle_arrange_is_round: query.vehicle_arrange_is_round, is_vehicle_arrange: query.is_vehicle_arrange, remark: query.remark, vehicle_arrange_add_time: query.vehicle_arrange_add_time, vehicle_arrange_update_time: query.vehicle_arrange_update_time, is_vehicle_arrange_cancel: query.is_vehicle_arrange_cancel, search: query.search, page_no: query.page_no, page_size: query.page_size }; const vehicleArrangeModel = { id: null, uid: null, passenger_mobile: null, driver_name: null, driver_mobile: null, voiture_number: null, voiture_type: null, voiture_color: null, voiture_seats: null, remaining_seats: null, vehicle_arrange_departure_time: null, vehicle_arrange_departure_place: null, vehicle_arrange_reach_place: null, vehicle_arrange_is_round: null, is_vehicle_arrange: null, remark: null, vehicle_arrange_add_time: null, vehicle_arrange_update_time: null, is_vehicle_arrange_cancel: null }; Object.keys(vehicleArrangeModel).forEach(item => { vehicleArrangeModel[item] = param[item]; }); const getResult = await vehicle_arrange_dao.getVehicleArrange(vehicleArrangeModel, param.search, param.page_no, param.page_size); const resData = vehicle_arrange_dao.formatVehicleApplyVehicleArrangeUserViewDbList(getResult); const totalCount = await vehicle_arrange_dao.getVehicleArrangeCount(vehicleArrangeModel, param.search); // 响应数据 return ctx.body = ResponseUtils.normal<Array<VehicleArrangeGetRes>>({ data: resData, pageNo: param.page_no, pageSize: param.page_size, totalCount }); }<file_sep>import ldap from 'ldapjs'; interface User { cn?: string; givenName?: string; displayName?: string; department?: string; name?: string; uid?: string; mail?: string; mobile?: string; thumbnailPhoto?: string; } export async function v01User(uid: string): Promise<any> { const client = ldap.createClient({ url: 'ldap://v01.net:389' }); const user: User = { cn: null, givenName: null, displayName: null, department: null, name: null, uid: null, mail: null, mobile: null, thumbnailPhoto: null }; // 创建 LDAP 查询选项 // filter 的作用就是相当于 SQL 的条件 const opts = { filter: '(sAMAccountName=' + uid + ')', // 查询条件过滤器,查找 uid=kxh 的用户数据 scope: 'sub', // 查询范围 timeLimit: 500 // 查询超时 }; return new Promise((resolve, reject) => { client.bind('<EMAIL>', 'Aa123456', function () { client.search('OU=lda,DC=v01,DC=net', opts, function (err, res) { res.on('searchEntry', function (entry) { let base64ThumbnailPhoto; entry.attributes.forEach(attr => { if (attr.type === 'thumbnailPhoto') { base64ThumbnailPhoto = attr._vals[0].toString('base64'); } }); // 获取查询的对象 const userInfo = entry.object; user.cn = userInfo.cn; user.givenName = userInfo.givenName; user.displayName = userInfo.displayName; user.department = userInfo.department; user.name = userInfo.name; user.uid = userInfo.sAMAccountName; user.mail = userInfo.mail; user.mobile = userInfo.mobile; user.thumbnailPhoto = base64ThumbnailPhoto; }); res.on('searchReference', function () { // console.log('referral: ' + referral.uris.join()); }); // 查询错误事件 res.on('error', function (err) { console.error('error: ' + err.message); // unbind操作,必须要做 client.unbind(); reject('ERROR'); }); //查询结束 res.on('end', function () { // unbind操作,必须要做 client.unbind(); if (!user.uid) { resolve(''); } resolve(user); }); }); }); }); } <file_sep>export { errorMessages } from './errors'; export { v01User } from './v01-user';<file_sep># trip-assistant-tst-ing-server Micro Service: Trip assistant tst ing server<file_sep>import Router from 'koa-router'; import * as flight_apply_controller from './flight-apply-controller'; const router = new Router(); router.prefix('/'); /** * @api {POST} /flight_apply 添加机票预订 * @apiDescription 添加机票预订 * @apiVersion 1.0.0 * @apiName postFlightApply * @apiGroup flight_apply * * @apiParam (query) {string} [uid] 提交“机票预订”用户的uid号 * @apiParam (query) {string} [passenger_name] 登机人/客人姓名 * @apiParam (query) {string} [passenger_mobile] 登机人手机号码 * @apiParam (query) {string} [departure_flight_number] 航班号(去程) * @apiParam (query) {string} [departure_time] 出发时间 * @apiParam (query) {string} [back_flight_number] 航班号(返程) * @apiParam (query) {string} [back_time] 返回时间 * @apiParam (query) {string} [ID_number] 身份证号 * @apiParam (query) {string} [flight_apply_submission_time] 机票预订提交时间 * @apiParam (query) {number} [is_flight_book_succeed] 是否预定成功(0预订失败,1预订成功,2待预订) * @apiParam (query) {number} [flight_apply_update_time] 机票预订更新时间 * @apiParam (query) {string} [remark] 备注 * @apiParam (query) {number} [is_flight_apply_cancel] 是否已删除(0未删除,1已删除) */ router.post('/flight_apply', flight_apply_controller.postFlightApply); /** * @api {DELETE} /flight_apply/:id 删除机票预订 * @apiDescription 删除机票预订 * @apiVersion 1.0.0 * @apiName deleteFlightApply * @apiGroup flight_apply * * @apiParam (path) {flight_apply} [id] id */ router.delete('/flight_apply/:id', flight_apply_controller.deleteFlightApply); /** * @api {PUT} /flight_apply/:id 更新机票预订 * @apiDescription 更新机票预订 * @apiVersion 1.0.0 * @apiName putFlightApply * @apiGroup flight_apply * * @apiParam (query) {string} [passenger_name] 登机人/客人姓名 * @apiParam (query) {string} [passenger_mobile] 登机人手机号码 * @apiParam (query) {string} [departure_flight_number] 航班号(去程) * @apiParam (query) {string} [departure_time] 出发时间 * @apiParam (query) {string} [back_flight_number] 航班号(返程) * @apiParam (query) {string} [back_time] 返回时间 * @apiParam (query) {number} [is_flight_book_succeed] 是否预定成功(0预订失败,1预订成功,2待预订) * @apiParam (query) {number} [flight_apply_update_time] 机票预订更新时间 * @apiParam (query) {string} [remark] 备注 */ router.put('/flight_apply/:id', flight_apply_controller.putFlightApply); /** * @api {GET} /flight_apply 查询机票预订 * @apiDescription 查询机票预订 * @apiVersion 1.0.0 * @apiName getFlightApply * @apiGroup flight_apply * * @apiParam (query) {number} [id] id * @apiParam (query) {string} [uid] 提交“机票预订”用户的uid号 * @apiParam (query) {string} [en_name] 英文名 * @apiParam (query) {string} [job_number] 工号 * @apiParam (query) {string} [mobile] 手机号 * @apiParam (query) {string} [passenger_name] 登机人/客人姓名 * @apiParam (query) {string} [passenger_mobile] 登机人手机号码 * @apiParam (query) {string} [departure_flight_number] 航班号(去程) * @apiParam (query) {string} [departure_time] 出发时间 * @apiParam (query) {string} [back_flight_number] 航班号(返程) * @apiParam (query) {string} [back_time] 返回时间 * @apiParam (query) {string} [ID_number] 身份证号 * @apiParam (query) {string} [flight_apply_submission_time] 机票预订提交时间 * @apiParam (query) {string} [is_flight_book_succeed] 是否预定成功(0预订失败,1预订成功,2待预订) * @apiParam (query) {string} [flight_apply_update_time] 机票预订更新时间 * @apiParam (query) {string} [remark] 备注 * @apiParam (query) {string} [is_flight_apply_cancel] 是否已删除(0未删除,1已删除) * @apiParam (query) {string} [search] 关键词搜索 * @apiParam (query) {string} [page_no] 页码 * @apiParam (query) {string} [page_size] 页大小 */ router.get('/flight_apply', flight_apply_controller.getFlightApply); export default router;<file_sep>import { UserDb } from './user-types'; export interface VehicleArrangeDb { id?: number; uid?: string; passenger_mobile?: string; driver_name?: string; driver_mobile?: string; voiture_number?: string; voiture?: string; voiture_color?: string; seats?: number; departure_time?: string; is_arrange?: number; remark?: string; add_time?: string; update_time?: string; is_vehicle_arrange_cancel?: number; } export interface VehicleApplyVehicleArrangeUserViewDb extends VehicleArrangeDb, UserDb { } export interface VehicleArrangeGetRes { id?: number; uid?: string; enName?: string; jobNumber?: string; mobile?: string; passengerName?: string; passengerMobile?: string; vehicleApplyDeparturePlace?: string; vehicleApplyReachPlace?: string; vehicleApplyIsRound?: number; vehicleApplyDetailPlace?: string; flightNumber?: string; flightDepartureTime?: string; flightReachTime?: string; costCenter?: string; projectBudgetNo?: string; vehicleApplySubmissionTime?: string; driverName?: string; driverMobile?: string; voitureNumber?: string; voitureType?: string; voitureColor?: string; voitureSeats?: number; remainingSeats?: number; vehicleArrangeDepartureTime?: string; vehicleArrangeDeparturePlace?: string; vehicleArrangeReachPlace?: string; vehicleArrangeIsRound?: number; isVehicleArrange?: number; remark?: string; vehicleArrangeAddTime?: string; vehicleArrangeUpdateTime?: string; isVehicleArrangeCancel?: number; } export interface VehicleArrangeUpdateRes { isUpdateSuccess: boolean; } export interface VehicleArrangeDeleteRes { isDeleteSuccess: boolean; }<file_sep># 启动测试版 # 在 centos 下,可以使用 dos2unix 工具,解决 windows 和 linux sh \r 的问题 # ------------------ 更新项目文档 ------------------ echo '---- 更新项目文档 ----' # 项目文档路径 APIDOC_PATH='../doc' # 文档静态资源服务器路径 APIDOC_SERVER_PATH='/qjq/www/html/apidoc/trip-assistant-tst-ing' # 删除静态资源文档 rm -rf $APIDOC_SERVER_PATH/** echo "删除 apidoc: ${APIDOC_SERVER_PATH}" # 编译静态资源文档 npx apidoc -i ../src -o $APIDOC_PATH/dist -c $APIDOC_PATH echo "编译生成 apidoc: ${APIDOC_PATH}/dist" # 将本地项目的静态资源文档拷贝到服务器 cp -rf $APIDOC_PATH/dist/* $APIDOC_SERVER_PATH echo "拷贝 apidoc to ${APIDOC_SERVER_PATH}" # ------------------------------------------------------ # ------------------ 启动项目 ------------------ echo '---- 启动项目 ----' export NODE_CONFIG='{"tripdb":{"db":{"password":"<PASSWORD>"}}}' npm run start:test # ------------------------------------------------------ <file_sep>import { trip_db } from './trip-db'; import { FlightApplyDb, FlightApplyUserViewDb } from './flight-apply-types'; // 添加机票预订 async function insertFlightApply(flightApply: FlightApplyDb) { return (await trip_db.table('flight_apply') .insert(flightApply)) as Array<number>; } // 删除机票预订 async function deleteFlightApply(id: number) { return await trip_db.table('flight_apply') .del() .where('id', id); } // 更新机票预订 async function updateFlightApply(id: number, flightApply: FlightApplyDb) { return (await trip_db.table('flight_apply') .update(flightApply) .where('id', id)) as number; } // 获取机票预订 async function getFlightApply(flightApply?: FlightApplyDb, search?: string, pageNo?: number, pageSize?: number) { let sql = trip_db.table('flight_apply_user_view').select('*'); for (const key in flightApply) { if (flightApply[key] === undefined) { delete flightApply[key]; } } if (flightApply) { sql = sql .where(flightApply); } if (search) { const searchSql = '%' + search + '%'; sql = sql .orWhere('uid', 'like', searchSql) .orWhere('en_name', 'like', searchSql) .orWhere('job_number', 'like', searchSql) .orWhere('mobile', 'like', searchSql) .orWhere('passenger_name', 'like', searchSql) .orWhere('passenger_mobile', 'like', searchSql) .orWhere('departure_flight_number', 'like', searchSql) .orWhere('departure_time', 'like', searchSql) .orWhere('back_flight_number', 'like', searchSql) .orWhere('back_time', 'like', searchSql) .orWhere('ID_number', 'like', searchSql) .orWhere('flight_apply_submission_time', 'like', searchSql) .orWhere('flight_apply_update_time', 'like', searchSql) .orWhere('remark', 'like', searchSql); } if (pageNo && pageSize) { sql = sql.limit(pageSize).offset(pageSize * (pageNo - 1)); } return (await sql) as Array<FlightApplyUserViewDb>; } // 获取机票预订总数 async function getFlightCount(flightApply?: FlightApplyDb, search?: string) { let sql = trip_db.table('flight_apply_user_view').count('*', { as: 'count' }); if (flightApply) { sql = sql .where(flightApply); } if (search) { const searchSql = '%' + search + '%'; sql = sql .orWhere('uid', 'like', searchSql) .orWhere('en_name', 'like', searchSql) .orWhere('job_number', 'like', searchSql) .orWhere('mobile', 'like', searchSql) .orWhere('passenger_name', 'like', searchSql) .orWhere('passenger_mobile', 'like', searchSql) .orWhere('departure_flight_number', 'like', searchSql) .orWhere('departure_time', 'like', searchSql) .orWhere('back_flight_number', 'like', searchSql) .orWhere('back_time', 'like', searchSql) .orWhere('ID_number', 'like', searchSql) .orWhere('flight_apply_submission_time', 'like', searchSql) .orWhere('flight_apply_update_time', 'like', searchSql) .orWhere('remark', 'like', searchSql); } const result = await sql; return result[0]['count'] as number; } function formatFlightApplyUserViewDbList(dbList: string | Array<FlightApplyUserViewDb>) { if (dbList === '') { return []; } const flightList = []; for (let i = 0; i < dbList.length; i++) { const flightApply = formatFlightApplyUserViewDb(dbList[i]); flightList.push(flightApply); } return flightList; } function formatFlightApplyUserViewDb(flightDb: string | FlightApplyUserViewDb) { const flightApply = { id: flightDb['id'], uid: flightDb['uid'], enName: flightDb['en_name'], jobNumber: flightDb['job_number'], mobile: flightDb['mobile'], passengerName: flightDb['passenger_name'], passengerMobile: flightDb['passenger_mobile'], departureFlightNumber: flightDb['departure_flight_number'], departureTime: flightDb['departure_time'], backFlightNumber: flightDb['back_flight_number'], backTime: flightDb['back_time'], IDNumber: flightDb['ID_number'], flightApplySubmissionTime: flightDb['flight_apply_submission_time'], isFlightBookSucceed: flightDb['is_flight_book_succeed'], flightApplyUpdateTime: flightDb['flight_apply_update_time'], remark: flightDb['remark'], isFlightApplyCancel: flightDb['is_flight_apply_cancel'] }; return flightApply; } export const flight_apply_dao = { insertFlightApply, updateFlightApply, deleteFlightApply, getFlightApply, getFlightCount, formatFlightApplyUserViewDbList, formatFlightApplyUserViewDb }; <file_sep># trip-assistant-tst-ing <file_sep>import { ResponseUtils, date_utils } from '@service-fw'; import { flight_apply_dao, FlightApplyGetRes, FlightApplyUpdateRes, FlightApplyDeleteRes, user_dao } from '../dao'; import { v01User } from '../common'; /** * 添加机票预订 */ export async function postFlightApply(ctx) { const body = ctx.request.body; const param = { uid: body.uid, passenger_name: body.passenger_name, passenger_mobile: body.passenger_mobile, departure_flight_number: body.departure_flight_number, departure_time: body.departure_time, back_flight_number: body.back_flight_number, back_time: body.back_time, ID_number: body.ID_number, flight_apply_submission_time: body.flight_apply_submission_time, is_flight_book_succeed: body.is_flight_book_succeed, flight_apply_update_time: body.flight_apply_update_time, remark: body.remark, is_flight_apply_cancel: body.is_flight_apply_cancel }; const flightApplyModel = { uid: null, passenger_name: null, passenger_mobile: null, departure_flight_number: null, departure_time: null, back_flight_number: null, back_time: null, ID_number: null, flight_apply_submission_time: null, is_flight_book_succeed: null, flight_apply_update_time: null, remark: null, is_flight_apply_cancel: null }; Object.keys(flightApplyModel).forEach(item => { flightApplyModel[item] = param[item]; }); const getResult = await user_dao.getUser({ uid: flightApplyModel.uid, is_user_cancel: 0 }); if (getResult.length === 0) { const userModel = { uid: null, job_number: null, cn_name: null, en_name: null, mobile: null, landline: null, mail: null, avatar: null, is_user_cancel: null }; const uidGetResult = await v01User(flightApplyModel.uid); if (uidGetResult === 'ERROR') { return ctx.body = ResponseUtils.error<any>({ error_no: 101 }); } if (!uidGetResult) { return ctx.body = ResponseUtils.error<any>({ error_no: 103, error_message: 'v01Ldap:uid号无效!' }); } userModel.uid = flightApplyModel.uid; userModel.en_name = uidGetResult.displayName; userModel.mobile = uidGetResult.mobile.substring(4); userModel.mail = uidGetResult.mail; userModel.avatar = uidGetResult.thumbnailPhoto; userModel.is_user_cancel = 0; const insertResult = await user_dao.insertUser(userModel); if (insertResult[0] != 0) { return ctx.body = ResponseUtils.error({ error_no: 100102 }); } } flightApplyModel.flight_apply_submission_time = date_utils.getNowDateString(); const insertResult = await flight_apply_dao.insertFlightApply(flightApplyModel); if (insertResult[0] <= 0) { return ctx.body = ResponseUtils.error({ error_no: 100102 }); } const getResult1 = await flight_apply_dao.getFlightApply({ id: insertResult[0] }); const resData = flight_apply_dao.formatFlightApplyUserViewDb(getResult1[0]); return ctx.body = ResponseUtils.normal<FlightApplyGetRes>({ data: resData }); } /** * 删除机票预订 */ export async function deleteFlightApply(ctx) { const param = { id: ctx.params.id }; const flightApplyModel = { is_flight_apply_cancel: null }; Object.keys(flightApplyModel).forEach(item => { flightApplyModel[item] = param[item]; }); const getResult = await flight_apply_dao.getFlightApply({ id: param.id, is_flight_apply_cancel: 0 }); if (getResult.length <= 0) { return ctx.body = ResponseUtils.error({ error_no: 100103, error_message: '删除失败,不存在该机票预订!' }); } // 删除机票预订 flightApplyModel.is_flight_apply_cancel = 1; const updateResult = await flight_apply_dao.updateFlightApply(param.id, flightApplyModel); if (updateResult !== 1) { // 删除失败(更新失败) return ctx.body = ResponseUtils.error({ error_no: 100103 }); } // 返回删除结果 ctx.body = ResponseUtils.normal<FlightApplyDeleteRes>({ data: { isDeleteSuccess: true } }); } /** * 更新机票预订 */ export async function putFlightApply(ctx) { const param = { id: ctx.params.id }; const flightApplyModel = { passenger_name: null, passenger_mobile: null, departure_flight_number: null, departure_time: null, back_flight_number: null, back_time: null, is_flight_book_succeed: null, flight_apply_update_time: null, remark: null }; Object.keys(flightApplyModel).forEach(item => { flightApplyModel[item] = ctx.request.body[item]; }); const getResult = await flight_apply_dao.getFlightApply({ id: param.id, is_flight_apply_cancel: 0 }); if (getResult.length <= 0) { return ctx.body = ResponseUtils.error({ error_no: 100101, error_message: '更新失败,不存在该机票预订!' }); } flightApplyModel.flight_apply_update_time = date_utils.getNowDateString(); const updateResult = await flight_apply_dao.updateFlightApply(param.id, flightApplyModel); if (updateResult !== 1) { // 更新失败 return ctx.body = ResponseUtils.error({ error_no: 100101 }); } return ctx.body = ResponseUtils.normal<FlightApplyUpdateRes>({ data: { isUpdateSuccess: true } }); } /** * 查询机票预订 */ export async function getFlightApply(ctx) { const query = ctx.request.query; const param = { id: query.id, uid: query.uid, en_name: query.en_name, job_number: query.job_number, mobile: query.mobile, passenger_name: query.passenger_name, passenger_mobile: query.passenger_mobile, departure_flight_number: query.departure_flight_number, departure_time: query.departure_time, back_flight_number: query.back_flight_number, back_time: query.back_time, ID_number: query.ID_number, flight_apply_submission_time: query.flight_apply_submission_time, is_flight_book_succeed: query.is_flight_book_succeed, flight_apply_update_time: query.flight_apply_update_time, remark: query.remark, is_flight_apply_cancel: query.is_flight_apply_cancel, search: query.search, page_no: query.page_no, page_size: query.page_size }; const flightApplyModel = { id: null, uid: null, en_name: null, job_number: null, mobile: null, passenger_name: null, passenger_mobile: null, departure_flight_number: null, departure_time: null, back_flight_number: null, back_time: null, ID_number: null, flight_apply_submission_time: null, is_flight_book_succeed: null, flight_apply_update_time: null, remark: null, is_flight_apply_cancel: null }; Object.keys(flightApplyModel).forEach(item => { flightApplyModel[item] = param[item]; }); const getResult = await flight_apply_dao.getFlightApply(flightApplyModel, param.search, param.page_no, param.page_size); const resData = flight_apply_dao.formatFlightApplyUserViewDbList(getResult); const totalCount = await flight_apply_dao.getFlightCount(flightApplyModel, param.search); // 响应数据 return ctx.body = ResponseUtils.normal<Array<FlightApplyGetRes>>({ data: resData, pageNo: param.page_no, pageSize: param.page_size, totalCount }); } <file_sep># 正式版 export NODE_CONFIG='{"tripdb":{"db":{"password":"???"}}}' npm run prod <file_sep>import { trip_assistant_logger } from '../logger/trip-assistant-logger'; import Knex from 'knex'; import config from 'config'; export const trip_db = Knex({ debug: true, client: 'mysql', connection: config.get('trip.db'), pool: { min: 0, max: 10 }, acquireConnectionTimeout: 10000, log: { debug: (msg: any) => trip_assistant_logger.debug(msg), warn: (msg: any) => trip_assistant_logger.warn(msg), error: (msg: any) => trip_assistant_logger.error(msg) } }); <file_sep>import { Service, logger } from '@service-fw'; import { router } from './trip-assistant'; import config from 'config'; const _svc_conf = config.get<{ name: string; port: number }>('service'); const _logger = logger(_svc_conf.name); Service({ name: _svc_conf.name, router: router, hooks: { init: () => { _logger.info(config); }, ready: () => { _logger.info('ready ...'); }, destroy: () => { _logger.info('destroy ...'); } } }, _svc_conf.port); <file_sep>export * from './flight-apply-types'; export { flight_apply_dao } from './flight-apply-dao'; export * from './vehicle-arrange-types'; export { vehicle_arrange_dao } from './vehicle-arrange-dao'; export * from './user-types'; export { user_dao } from './user-dao'; <file_sep>import { trip_db } from './trip-db'; import { VehicleArrangeDb, VehicleApplyVehicleArrangeUserViewDb } from './vehicle-arrange-types'; // 添加用车安排 async function insertVehicleArrange(vehicleArrange: VehicleArrangeDb) { return (await trip_db.table('vehicle_arrange') .insert(vehicleArrange)) as Array<number>; } // 更新用车安排 async function updateVehicleArrange(id: number, vehicleArrange: VehicleArrangeDb) { return (await trip_db.table('vehicle_arrange') .update(vehicleArrange) .where('id', id)) as number; } // 获取用车安排 async function getVehicleArrange(vehicleArrange?: VehicleArrangeDb, search?: string, pageNo?: number, pageSize?: number) { let sql = trip_db.table('vehicle_apply_vehicle_arrange_user_view').select('*'); for (const key in vehicleArrange) { if (vehicleArrange[key] === undefined) { delete vehicleArrange[key]; } } if (vehicleArrange) { sql = sql .where(vehicleArrange); } if (search) { const searchSql = '%' + search + '%'; sql = sql .orWhere('uid', 'like', searchSql) .orWhere('en_name', 'like', searchSql) .orWhere('job_number', 'like', searchSql) .orWhere('mobile', 'like', searchSql) .orWhere('driver_name', 'like', searchSql) .orWhere('driver_mobile', 'like', searchSql) .orWhere('voiture_number', 'like', searchSql) .orWhere('voiture_type', 'like', searchSql) .orWhere('voiture_color', 'like', searchSql) .orWhere('voiture_seats', 'like', searchSql) .orWhere('remaining_seats', 'like', searchSql) .orWhere('vehicle_arrange_departure_time', 'like', searchSql) .orWhere('vehicle_arrange_departure_place', 'like', searchSql) .orWhere('vehicle_arrange_reach_place', 'like', searchSql) .orWhere('vehicle_arrange_is_round', 'like', searchSql) .orWhere('remark', 'like', searchSql) .orWhere('vehicle_arrange_add_time', 'like', searchSql) .orWhere('vehicle_arrange_update_time', 'like', searchSql) .orWhere('passenger_name', 'like', searchSql) .orWhere('passenger_mobile', 'like', searchSql) .orWhere('vehicle_apply_departure_place', 'like', searchSql) .orWhere('vehicle_apply_reach_place', 'like', searchSql) .orWhere('vehicle_apply_detail_place', 'like', searchSql) .orWhere('flight_number', 'like', searchSql) .orWhere('flight_departure_time', 'like', searchSql) .orWhere('flight_reach_time', 'like', searchSql) .orWhere('cost_center', 'like', searchSql) .orWhere('project_budget_no', 'like', searchSql) .orWhere('vehicle_apply_submission_time', 'like', searchSql); } if (pageNo && pageSize) { sql = sql.limit(pageSize).offset(pageSize * (pageNo - 1)); } return (await sql) as Array<VehicleApplyVehicleArrangeUserViewDb>; } // 获取用车安排总数 async function getVehicleArrangeCount(vehicleArrange?: VehicleArrangeDb, search?: string) { let sql = trip_db.table('vehicle_apply_vehicle_arrange_user_view').count('*', { as: 'count' }); if (vehicleArrange) { sql = sql .where(vehicleArrange); } if (search) { const searchSql = '%' + search + '%'; sql = sql .orWhere('uid', 'like', searchSql) .orWhere('en_name', 'like', searchSql) .orWhere('job_number', 'like', searchSql) .orWhere('mobile', 'like', searchSql) .orWhere('driver_name', 'like', searchSql) .orWhere('driver_mobile', 'like', searchSql) .orWhere('voiture_number', 'like', searchSql) .orWhere('voiture_type', 'like', searchSql) .orWhere('voiture_color', 'like', searchSql) .orWhere('voiture_seats', 'like', searchSql) .orWhere('remaining_seats', 'like', searchSql) .orWhere('vehicle_arrange_departure_time', 'like', searchSql) .orWhere('vehicle_arrange_departure_place', 'like', searchSql) .orWhere('vehicle_arrange_reach_place', 'like', searchSql) .orWhere('vehicle_arrange_is_round', 'like', searchSql) .orWhere('remark', 'like', searchSql) .orWhere('vehicle_arrange_add_time', 'like', searchSql) .orWhere('vehicle_arrange_update_time', 'like', searchSql) .orWhere('passenger_name', 'like', searchSql) .orWhere('passenger_mobile', 'like', searchSql) .orWhere('vehicle_apply_departure_place', 'like', searchSql) .orWhere('vehicle_apply_reach_place', 'like', searchSql) .orWhere('vehicle_apply_detail_place', 'like', searchSql) .orWhere('flight_number', 'like', searchSql) .orWhere('flight_departure_time', 'like', searchSql) .orWhere('flight_reach_time', 'like', searchSql) .orWhere('cost_center', 'like', searchSql) .orWhere('project_budget_no', 'like', searchSql) .orWhere('vehicle_apply_submission_time', 'like', searchSql); } const result = await sql; return result[0]['count'] as number; } function formatVehicleApplyVehicleArrangeUserViewDbList(dbList: string | Array<VehicleApplyVehicleArrangeUserViewDb>) { if (dbList === '') { return []; } const vehicleArrangeList = []; for (let i = 0; i < dbList.length; i++) { const vehicleArrange = formatVehicleApplyVehicleArrangeUserViewDb(dbList[i]); vehicleArrangeList.push(vehicleArrange); } return vehicleArrangeList; } function formatVehicleApplyVehicleArrangeUserViewDb(db: string | VehicleApplyVehicleArrangeUserViewDb) { const vehicleArrange = { id: db['id'], uid: db['uid'], enName: db['en_name'], jobNumber: db['job_number'], mobile: db['mobile'], passengerName: db['passenger_name'], passengerMobile: db['passenger_mobile'], vehicleApplyDeparturePlace: db['vehicle_apply_departure_place'], vehicleApplyReachPlace: db['vehicle_apply_reach_place'], vehicleApplyIsRound: db['vehicle_apply_is_round'], vehicleApplyDetailPlace: db['vehicle_apply_detail_place'], flightNumber: db['flight_number'], flightDepartureTime: db['flight_departure_time'], flightReachTime: db['flight_reach_time'], costCenter: db['cost_center'], projectBudgetNo: db['project_budget_no'], vehicleApplySubmissionTime: db['vehicle_apply_submission_time'], driverName: db['driver_name'], driverMobile: db['driver_mobile'], voitureNumber: db['voiture_number'], voitureType: db['voiture_type'], voitureColor: db['voiture_color'], voitureSeats: db['voiture_seats'], remainingSeats: db['remaining_seats'], vehicleArrangeDepartureTime: db['vehicle_arrange_departure_time'], vehicleArrangeDeparturePlace: db['vehicle_arrange_departure_place'], vehicleArrangeReachPlace: db['vehicle_arrange_reach_place'], vehicleArrangeIsRound: db['vehicle_arrange_is_round'], isVehicleArrange: db['is_vehicle_arrange'], remark: db['remark'], vehicleArrangeAddTime: db['vehicle_arrange_add_time'], vehicleArrangeUpdateTime: db['vehicle_arrange_update_time'], isVehicleArrangeCancel: db['is_vehicle_arrange_cancel'] }; return vehicleArrange; } export const vehicle_arrange_dao = { insertVehicleArrange, getVehicleArrange, formatVehicleApplyVehicleArrangeUserViewDbList, formatVehicleApplyVehicleArrangeUserViewDb, updateVehicleArrange, getVehicleArrangeCount };<file_sep>import { trip_db } from './trip-db'; import { UserDb } from './user-types'; // 添加用户 async function insertUser(user: UserDb) { return (await trip_db.table('user') .insert(user)) as Array<number>; } // 获取用户 async function getUser(user?: UserDb, pageNo?: number, pageSize?: number) { let sql = trip_db.table('user').select('*'); for (const key in user) { if (user[key] === undefined) { delete user[key]; } } if (user) { sql = sql.where(user); } if (pageNo && pageSize) { sql = sql.limit(pageSize).offset(pageSize * (pageNo - 1)); } return (await sql) as Array<UserDb>; } export const user_dao = { insertUser, getUser };<file_sep>import Router from 'koa-router'; import flight_apply_router from './api/flight-apply-router'; import vehicle_arrange_router from './api/vehicle-arrange-router'; const router = new Router(); router.use(flight_apply_router.routes(), flight_apply_router.allowedMethods()); router.use(vehicle_arrange_router.routes(), vehicle_arrange_router.allowedMethods()); router.get('/', async (ctx) => { ctx.body = 'Welcome to trip-assistant-server!'; }); export { router }; <file_sep>export interface UserDb { uid?: string; job_number?: string; cn_name?: string; en_name?: string; mobile?: string; landline?: string; mail?: string; avatar?: string; position?: string; is_user_cancel?: number; }<file_sep>FROM 172.16.17.32:8888/node:12 MAINTAINER "<NAME>" "<EMAIL>" ADD . /trip-assistant-tst-ing-server/ WORKDIR /trip-assistant-tst-ing-server RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime RUN npm config set registry http://172.16.17.32:8081/repository/itti-npm-registry/ RUN npm install EXPOSE 8080 CMD ["npm","run","prod"] <file_sep>import Router from 'koa-router'; import * as vehicle_arrange_controller from './vehicle-arrange-controller'; const router = new Router(); router.prefix('/'); /** * @api {POST} /vehicle_arrange 添加用车安排 * @apiDescription 添加用车安排 * @apiVersion 1.0.0 * @apiName postVehicleArrange * @apiGroup vehicle_arrange * * @apiParam (query) {string} [uid] 提交“用车申请”用户的uid号 * @apiParam (query) {string} [passenger_mobile] 乘车人手机号码 * @apiParam (query) {string} [driver_name] 司机中文名 * @apiParam (query) {string} [driver_mobile] 司机手机号码 * @apiParam (query) {string} [voiture_number] 车牌号 * @apiParam (query) {string} [voiture_type] 车型:奔驰车、上海通用别克GL8商务车、马自达8商务车... * @apiParam (query) {string} [voiture_color] 车辆颜色 * @apiParam (query) {string} [voiture_seats] 车辆座位数 * @apiParam (query) {string} [remaining_seats] 剩余座位数 * @apiParam (query) {number} [vehicle_arrange_departure_time] 车辆安排出发时间 * @apiParam (query) {number} [vehicle_arrange_departure_place] 车辆安排出发地点 * @apiParam (query) {number} [vehicle_arrange_reach_place] 车辆安排到达地点 * @apiParam (query) {number} [vehicle_arrange_is_round] 车辆安排是否往返(0单程, 1往返) * @apiParam (query) {number} [is_vehicle_arrange] 是否已安排车辆(0未安排,1已安排,2不安排) * @apiParam (query) {string} [remark] 备注 * @apiParam (query) {string} [vehicle_arrange_add_time] 车辆安排添加时间 * @apiParam (query) {string} [vehicle_arrange_update_time] 车辆安排更新时间 * @apiParam (query) {number} [is_vehicle_arrange_cancel] 是否已删除(0未删除,1已删除) */ router.post('/vehicle_arrange', vehicle_arrange_controller.postVehicleArrange); /** * @api {DELETE} /vehicle_arrange/:id 删除用车安排 * @apiDescription 删除用车安排 * @apiVersion 1.0.0 * @apiName deleteVehicleArrange * @apiGroup vehicle_arrange * * @apiParam (path) {vehicle_arrange} [id] id */ router.delete('/vehicle_arrange/:id', vehicle_arrange_controller.deleteVehicleArrange); /** * @api {PUT} /vehicle_arrange/:id 更新用车安排 * @apiDescription 更新用车安排 * @apiVersion 1.0.0 * @apiName putVehicleArrange * @apiGroup vehicle_arrange * * @apiParam (query) {string} [passenger_mobile] 乘车人手机号码 * @apiParam (query) {string} [driver_name] 司机中文名 * @apiParam (query) {string} [driver_mobile] 司机手机号码 * @apiParam (query) {string} [voiture_number] 车牌号 * @apiParam (query) {string} [voiture_type] 车型:奔驰车、上海通用别克GL8商务车、马自达8商务车... * @apiParam (query) {string} [voiture_color] 车辆颜色 * @apiParam (query) {string} [voiture_seats] 车辆座位数 * @apiParam (query) {string} [remaining_seats] 剩余座位数 * @apiParam (query) {number} [vehicle_arrange_departure_time] 车辆安排出发时间 * @apiParam (query) {number} [vehicle_arrange_departure_place] 车辆安排出发地点 * @apiParam (query) {number} [vehicle_arrange_reach_place] 车辆安排到达地点 * @apiParam (query) {number} [vehicle_arrange_is_round] 车辆安排是否往返(0单程, 1往返) * @apiParam (query) {number} [is_vehicle_arrange] 是否已安排车辆(0未安排,1已安排,2不安排) * @apiParam (query) {string} [remark] 备注 * @apiParam (query) {string} [vehicle_arrange_update_time] 车辆安排更新时间 * @apiParam (query) {number} [is_vehicle_arrange_cancel] 是否已删除(0未删除,1已删除) */ router.put('/vehicle_arrange/:id', vehicle_arrange_controller.putVehicleArrange); /** * @api {GET} /vehicle_arrange 查询用车安排 * @apiDescription 查询用车安排 * @apiVersion 1.0.0 * @apiName getVehicleArrange * @apiGroup vehicle_arrange * * @apiParam (query) {number} [id] id * @apiParam (query) {string} [uid] 提交“用车申请”用户的uid号 * @apiParam (query) {string} [passenger_mobile] 乘车人手机号码 * @apiParam (query) {string} [driver_name] 司机中文名 * @apiParam (query) {string} [driver_mobile] 司机手机号码 * @apiParam (query) {string} [voiture_number] 车牌号 * @apiParam (query) {string} [voiture_type] 车型:奔驰车、上海通用别克GL8商务车、马自达8商务车... * @apiParam (query) {string} [voiture_color] 车辆颜色 * @apiParam (query) {string} [voiture_seats] 车辆座位数 * @apiParam (query) {string} [remaining_seats] 剩余座位数 * @apiParam (query) {string} [vehicle_arrange_departure_time] 车辆安排出发时间 * @apiParam (query) {string} [vehicle_arrange_departure_place] 车辆安排出发地点 * @apiParam (query) {string} [vehicle_arrange_reach_place] 车辆安排到达地点 * @apiParam (query) {string} [vehicle_arrange_is_round] 车辆安排是否往返(0单程, 1往返) * @apiParam (query) {string} [is_vehicle_arrange] 是否已安排车辆(0未安排,1已安排,2不安排) * @apiParam (query) {string} [remark] 备注 * @apiParam (query) {string} [vehicle_arrange_add_time] 车辆安排添加时间 * @apiParam (query) {string} [vehicle_arrange_update_time] 车辆安排更新时间 * @apiParam (query) {string} [is_vehicle_arrange_cancel] 是否已删除(0未删除,1已删除) * @apiParam (query) {string} [search] 关键词搜索 * @apiParam (query) {string} [page_no] 页码 * @apiParam (query) {string} [page_size] 页大小 */ router.get('/vehicle_arrange', vehicle_arrange_controller.getVehicleArrange); export default router;
687f41c7edc39574a82759b9a9710590b09d7880
[ "Markdown", "TypeScript", "Dockerfile", "Shell" ]
21
TypeScript
QinJianqing/trip-assistant-TST-ING
cca04f6809f4c02ac31919b967ebf6f7c7f9a4a8
9ed1a747b56c53b97821bb0f24eb2eb1869a0128
refs/heads/main
<repo_name>jcarnes1/assignment7<file_sep>/Mod9.R weightLoss <- read.csv('WeightLoss.csv', stringsAsFactors = FALSE) barplot(wl1 ~ X, data = weightLoss, col = "red") barplot(wl2 ~ X, data = weightLoss, col = "green") barplot(wl3 ~ X, data = weightLoss, col = "blue") data <- structure(list(w1 = c(weightLoss$wl1), w2 = c(weightLoss$wl2), w3 = c(weightLoss$wl3)), .Names = c("Month 1", "Month 2", "Month 3"), class = "data.frame", row.names = weightLoss$X) barplot(as.matrix(data), main = "Weight Loss", ylab = "Weight Lost (lbs)", cex.lab = 1.5, cex.main = 1.4, beside = TRUE)
fe46ac3b2066715973c27cf2b05958435ffd4311
[ "R" ]
1
R
jcarnes1/assignment7
1beda44707f20c3d8109961ce2308a64500e1284
5f9adf8a621d2796b1587fcff7559e26540f19d7
refs/heads/master
<file_sep>/* Created by Ivan in 18/12/2020 Description: Interpretation of the date differential calculus. */ public class DiesEntreDates_Iván_Bosch extends CalcularDiesEntreDates{ //Builder public DiesEntreDates_Iván_Bosch() { } int diesMesInicial; int diesMesDesti; int diesMes; int diesResteAnyInicial; int diesResteAnyDesti; int diesNumAnysComplets; boolean anyDeTraspas; //Setting up each month's days @Override protected int diesMes(int mes) { switch (mes) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: this.diesMes = 31; break; case 2: this.diesMes=28; break; case 4: case 6: case 9: case 11: this.diesMes = 30; break; } return this.diesMes; } //Discounts the passed days form the actual month. @Override protected int diesMesInicial(DataXS dataXS) { this.diesMesInicial = diesMes(dataXS.mes) - dataXS.dia; return this.diesMesInicial; } //Sets up the days from the final month @Override protected int diesMesDesti(DataXS dataXS) { this.diesMesDesti = dataXS.dia; return this.diesMesDesti; } //Calculates the remaining days of the year from the initial month @Override protected int diesResteAnyInicial(DataXS datainicial) { datainicial.mes++; while (datainicial.mes <= 12){ this.diesResteAnyInicial += diesMes(datainicial.mes); datainicial.mes++; } return this.diesResteAnyInicial; } //Calculates the remaining days until the final month @Override protected int diesResteAnyDesti(DataXS datadesti) { datadesti.mes--; while (datadesti.mes >= 1){ this.diesResteAnyDesti += diesMes(datadesti.mes); datadesti.mes--; } return this.diesResteAnyDesti; } //Calculates the days of the whole years @Override protected int diesNumAnysComplets(DataXS datainicial, DataXS datadesti) { this.diesNumAnysComplets = ((datadesti.any - datainicial.any) -1) * 365; return this.diesNumAnysComplets; } //Adds up the additional day in case of a leap year @Override protected int numDiesPerAnysdeTraspas(DataXS datainicial, DataXS datadesti) { int diaTraspas = 0; for (int i = 0; i <= ((datadesti.any - datainicial.any) -1); i++) { if (anyDeTraspas(datainicial.any + i)){ diaTraspas++; } } if (anyDeTraspas(datadesti.any)){ diaTraspas++; } return diaTraspas; } //Checks for leap years @Override protected boolean anyDeTraspas(int any) { if (any % 400 == 0 || ((any % 4 == 0) && !(any % 100 == 0))){ this.anyDeTraspas = true; } else this.anyDeTraspas = false; return this.anyDeTraspas; } }
4e89b19ad2fa30b6517d43e67d70ac7e4d433bd9
[ "Java" ]
1
Java
Mike-Elitas/Dates
53091923ccc375885e06379af023feede1bf38db
ba9979a2409c4ca1d05191ef4928c56723d7c4cf
refs/heads/master
<repo_name>saqibalich1/saqib<file_sep>/assets/chat/index.js function doIt(){ $.get(base_url('chat/ans'), function(data, status){ generate_message(data,'user'); }); } var INDEX = 0; function generate_message(msg, type) { if(msg == ''){return false;} INDEX++; var str=""; str += "<div id='cm-msg-"+INDEX+"' class=\"chat-msg "+type+"\">"; str += " <span class=\"msg-avatar\">"; if(type == 'user'){ str += " <img src=" +base_url('images/bot.png') +">"; }else{ str += " <img src="+ base_url('chat/profile') +">"; } str += " <\/span>"; str += " <div class=\"cm-msg-text\">"; str += msg; str += " <\/div>"; str += " <\/div>"; $(".chat-logs").append(str); $("#cm-msg-"+INDEX).hide().fadeIn(300); if(type == 'self'){ $("#chat-input").val(''); } $(".chat-logs").stop().animate({ scrollTop: $(".chat-logs")[0].scrollHeight}, 1000); } $(function() { var INDEX = 0; $("#chat-submit").click(function(e) { e.preventDefault(); var msg = $("#chat-input").val(); if(msg.trim() == ''){ return false; } generate_message(msg, 'self'); var buttons = [ { name: 'Existing User', value: 'existing' }, { name: 'New User', value: 'new' } ]; $.post(base_url('chat/rec'), { msg: msg }, function(result){ generate_message(result, 'user'); }); }) function generate_button_message(msg, buttons){ /* Buttons should be object array [ { name: 'Existing User', value: 'existing' }, { name: 'New User', value: 'new' } ] */ INDEX++; var btn_obj = buttons.map(function(button) { return " <li class=\"button\"><a href=\"javascript:;\" class=\"btn btn-primary chat-btn\" chat-value=\""+button.value+"\">"+button.name+"<\/a><\/li>"; }).join(''); var str=""; str += "<div id='cm-msg-"+INDEX+"' class=\"chat-msg user\">"; str += " <span class=\"msg-avatar\">"; str += " <img src=\"https:\/\/image.crisp.im\/avatar\/operator\/196af8cc-f6ad-4ef7-afd1-c45d5231387c\/240\/?1483361727745\">"; str += " <\/span>"; str += " <div class=\"cm-msg-text\">"; str += msg; str += " <\/div>"; str += " <div class=\"cm-msg-button\">"; str += " <ul>"; str += btn_obj; str += " <\/ul>"; str += " <\/div>"; str += " <\/div>"; $(".chat-logs").append(str); $("#cm-msg-"+INDEX).hide().fadeIn(300); $(".chat-logs").stop().animate({ scrollTop: $(".chat-logs")[0].scrollHeight}, 1000); $("#chat-input").attr("disabled", true); } $(document).delegate(".chat-btn", "click", function() { var value = $(this).attr("chat-value"); var name = $(this).html(); $("#chat-input").attr("disabled", false); generate_message(name, 'self'); }) $("#chat-circle").click(function() { $("#chat-circle").toggle('scale'); $(".chat-box").toggle('scale'); $('#chat-input').focus(); $.get(base_url('chat/hist'), function(data, status){ data = JSON.parse(data); data.forEach(function(element) { q = element.q; ans = element.ans; generate_message(q,'self'); generate_message(ans,'user'); }); });    timer = setInterval(doIt,1500); }) $(".chat-box-toggle").click(function() { $("#chat-circle").toggle('scale'); $(".chat-box").toggle('scale'); $(".chat-logs").html('');    clearInterval(timer); }); });<file_sep>/assets/js/upload.js $(function(){ $.fn.filepond.registerPlugin(FilePondPluginImagePreview); $.fn.filepond.registerPlugin(FilePondPluginFileValidateType); FilePond.create(document.querySelector('input'), { acceptedFileTypes: ['image/png'], fileValidateTypeDetectType: (source, type) => new Promise((resolve, reject) => { // Do custom type detection here and return with promise resolve(type); }) }) // Turn input element into a pond $('.my-pond').filepond(); // Turn input element into a pond with configuration options $('.my-pond').filepond({ allowMultiple: true, }); // Set allowMultiple property to true $('.my-pond').filepond('allowMultiple', true); $('.my-pond').filepond('acceptedFileTypes', ['image/*' , 'application/msword' , 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'text/plain', 'application/pdf' ]); // Manually add a file using the addfile method FilePond.setOptions({ server: $('#uploadon').val(), allowImagePreview: true, maxFiles: 10, dropOnPage: true, }); r = 'file '; $('.my-pond').on('FilePond:addfile', function(error, file) { if (error) { // console.log('File Add Error: ' , error); c = $('#wait').val(); $('#wait').val(r); return; } // console.log('File Added', file.filename); }); $('.my-pond').on('FilePond:processfile', function() { v = $('#wait').val(); var v = v.replace(r, ""); $('#wait').val(v); }); $('.my-pond').on('FilePond:processfileabort', function() { v = $('#wait').val(); var v = v.replace(r, ""); $('#wait').val(v); }); $('.my-pond').on('FilePond:processfileprogress', function(e) { // console.log('P ', e); }); }); <file_sep>/assets/login/js/index.js //VARIABLES var FIREBASE_AUTH = 'https://authorize-demo.firebaseio.com'; var fb = new Firebase(FIREBASE_AUTH); //Logout $('.doLogout').click(function () { fb.unauth(); }) //Reset Password $('.doResetPassword').click(function () { var email = $('.login input[type="email"]').val(); fb.resetPassword({ email: email }, function(err){ if (err) { alert(err.toString()); } else { alert('Check your email!'); } }); }); //Login verification $('.login form').submit(function () { var email = $('.login input[type="email"]').val(); var password = $('.login input[type="password"]').val(); doLogin(email, password) event.preventDefault(); }); function doLogin (email, password, cb) { fb.authWithPassword({ email: email, password: <PASSWORD> }, function (err, authData) { if (err) { alert(err.toString()); } else { saveAuthData(authData); typeof cb === 'function' && cb(authData); //read about this } }); } //auth data function saveAuthData (authData) { $.ajax({ method: 'PUT', url: FIREBASE_AUTH + '/users/' + authData.uid + '/profile.json', data: JSON.stringify(authData) }); } //REGISTRATION PROCESS $('.doRegister').click(function () { var email = $('.login input[type="email"]').val(); var password = $('.login input[type="password"]').val(); fb.createUser({ email: email, password: <PASSWORD> }, function (err, userData) { if (err) { console.log(err.toString()); } else { doLogin(email, password) } }); event.preventDefault(); }); //Clearing form function clearLoginForm () { $('.login input[type="email"]').val(''); $('.login input[type="password"]').val(''); } //Change password $('.onTempPassword form').submit(function () { var email = fb.getAuth().password.email; var oldPw = $('.onTempPassword input:nth-child(1)').val(); var newPw = $('.onTempPassword input:nth-child(2)').val(); fb.changePassword({ email : email, oldPassword : <PASSWORD>, newPassword : <PASSWORD> }, function(err) { if (err) { alert(err.toString()); } else { fb.unauth(); } }); event.preventDefault(); }) //Toggle login and logout forms fb.onAuth(function (authData) { var onLoggedOut = $('.onLoggedOut'); var onLoggedIn = $('.onLoggedIn'); var onTempPassword = $('.onTempPassword'); if (authData && authData.password.isTemporaryPassword) { onTempPassword.removeClass('hidden'); onLoggedIn.addClass('hidden'); onLoggedOut.addClass('hidden'); } else if (authData) { onLoggedOut.addClass('hidden'); onLoggedIn.removeClass('hidden'); onTempPassword.addClass('hidden'); $('.onLoggedIn h1').text('Hello ' + authData.password.email); } else { onLoggedOut.removeClass('hidden'); onLoggedIn.addClass('hidden'); onTempPassword.addClass('hidden'); } clearLoginForm(); })<file_sep>/assets/js/custom.js function redirect(data){ window.location = data; } function base_url(data=''){ base= $('#base_url').val(); return base + data; } $(document).ready(function() { $("input[type=number]").on("keydown", function(event) { if (event.keyCode === 38 || event.keyCode === 40) { event.preventDefault(); } }); }); <file_sep>/assets/js/query.js function make(){ missing = [ { name: 'post', type: 'text', title: 'Form No.' }, { name: 'cnic', type: 'text', title: 'ID Card No.' }, { name: 'post', type: 'text', title: 'Post Name' }, // { name: 'mobile', type: 'text', title: 'Contact No.' }, { name: 'email', type: 'text', title: 'Email Address to send slip or other data' }, { name: 'paid', type: 'text', title: 'How you paid your fee' }, ]; rejected = [ { name: 'post', type: 'text', title: 'Form No.' }, { name: 'cnic', type: 'text', title: 'ID Card No.' }, { name: 'post', type: 'text', title: 'Post Name' }, { name: 'mobile', type: 'text', title: 'Contact No.' }, { name: 'email', type: 'text', title: 'Email Address to send slip or other data' }, { name: 'complement', type: 'text', title: 'Write your complement to solve your issue' }, ]; resultcard = [ { name: 'post', type: 'text', title: 'Form No.' }, { name: 'cnic', type: 'text', title: 'ID Card No.' }, { name: 'roll', type: 'text', title: 'Roll No' }, { name: 'addr', type: 'text', title: 'Address' }, { name: 'mobile', type: 'text', title: 'Contact No.' }, { name: 'email', type: 'text', title: 'Email Address to send slip or other data' }, ]; spell = [ { name: 'post', type: 'text', title: 'Form No.' }, { name: 'cnic', type: 'text', title: 'ID Card No.' }, { name: 'obj', type: 'text', title: 'aaWhich thing is not valid name CNIC or Father Name' }, { name: 'correct', type: 'text', title: 'Type your actual record to be correct' }, { name: 'mobile', type: 'text', title: 'Contact No.' }, { name: 'email', type: 'text', title: 'Email Address to send slip or other data' }, ]; field = [ { name: 'post', type: 'text', title: 'Form No.' }, { name: 'cnic', type: 'text', title: 'ID Card No.' }, { name: 'post', type: 'text', title: 'Correct Post Name' }, { name: 'Application No.', type: 'text', title: 'app' }, { name: 'correct', type: 'text', title: 'Type your actual record to be correct' }, { name: 'mobile', type: 'text', title: 'Contact No.' }, { name: 'email', type: 'text', title: 'Email Address to send slip or other data' }, ]; recheck = [ { name: 'post', type: 'text', title: 'Form No.' }, { name: 'cnic', type: 'text', title: 'ID Card No.' }, { name: 'wish', type: 'text', title: 'What you feel? much marks you should?' }, { name: 'app', type: 'text', title: 'Application No.' }, { name: 'correct', type: 'text', title: 'Type your actual record to be correct' }, { name: 'mobile', type: 'text', title: 'Contact No.' }, { name: 'email', type: 'text', title: 'Email Address to send slip or other data' }, ]; other = [ { name: 'cnic', type: 'text', title: 'ID Card No.' }, { name: 'mobile', type: 'text', title: 'Mobile No.' }, { name: 'details', type: 'textarea', title: 'Write detailed issue.' }, ]; passwo = [ { name: 'cnic', type: 'text', title: 'ID Card No.' }, { name: 'mobile', type: 'text', title: 'Mobile No.' }, { name: 'email', type: 'text', title: 'Email Address' }, { name: 'details',type: 'textarea', title: 'Type your details to reset password.' }, ]; m = $('#cat').val(); switch (m) { case 'pass': data = passwo; break; case 'missing': data = missing; break; case 'rejected': data = rejected; break; case 'resultcard': data = resultcard; break; case 'spell': data = spell; break; case 'field': data = field; break; case 'recheck': data = recheck; break; case 'other': data = other; break; } $('#makearea').hide(); $('#makearea').html(''); for(var i = 0; i < data.length; i++) { info = data[i]; id = info.name; if(info.type =='text'){ a = '<div class="form-group" data-toggle="tooltip" title="'+info.title+'" data-placement="left"> <label class="control-label " for="'+id+'"> '+info.title + '</label> <input class="form-control form-control-lg" required="" id="'+id+'" name="'+info.name+'" placeholder="'+info.title+'" type="'+info.type+'"> </div>' } else if(info.type =='textarea'){ a = '<div class="form-group" data-toggle="tooltip" title="'+info.title+'" data-placement="left"> <label class="control-label " for="'+id+'"> '+info.title + '</label> <textarea class="form-control" required="" id="'+id+'" name="'+info.name+'" placeholder="'+info.title+'" rows="8"></textarea></div>' } $("#makearea").append(a); $('[data-toggle="tooltip"]').tooltip() } $('#makearea').fadeIn(); $("#"+data[0].name).focus(); $('#email').val($('#emailuser').html()); $('#mobile').val($('#mobileuser').html()); $('#cnic').val($('#cnicuser').html()); } $(document).ready(function(){ $("#cat").change(function(){ make(); }); $("#queryform").submit(function(){ wait = $('#wait').val(); if(wait != ''){ $('.alert').slideDown(); return false;} }); $.get(base_url('qms/hist'), function(data, status){ $('#hist').html(data); $(".id").click(function(){ a = $(this).find('.inid').html(); $('#find').val(a); $('#find').focus(); $("#find").animate({ width: "10%"}); setTimeout(function(){ $("#find").stop( true, true).animate({ width: "100%"}); }, 450); }); }); }); $(function(){ // $.fn.filepond.registerPlugin(FilePondPluginImagePreview); $.fn.filepond.registerPlugin(FilePondPluginFileValidateType); FilePond.create(document.querySelector('input'), { acceptedFileTypes: ['image/png'], fileValidateTypeDetectType: (source, type) => new Promise((resolve, reject) => { // Do custom type detection here and return with promise resolve(type); }) }) // Turn input element into a pond $('.my-pond').filepond(); // Turn input element into a pond with configuration options $('.my-pond').filepond({ allowMultiple: true, }); // Set allowMultiple property to true $('.my-pond').filepond('allowMultiple', true); $('.my-pond').filepond('acceptedFileTypes', ['image/*' , 'application/msword' , 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'text/plain', 'application/pdf' ]); // Manually add a file using the addfile method FilePond.setOptions({ server: base_url('qms/upload'), allowImagePreview: true, maxFiles: 10, dropOnPage: true, }); r = 'file '; $('.my-pond').on('FilePond:addfile', function(error, file) { if (error) { // console.log('File Add Error: ' , error); c = $('#wait').val(); $('#wait').val(r); return; } // console.log('File Added', file.filename); }); $('.my-pond').on('FilePond:processfile', function() { v = $('#wait').val(); var v = v.replace(r, ""); $('#wait').val(v); }); $('.my-pond').on('FilePond:processfileabort', function() { v = $('#wait').val(); var v = v.replace(r, ""); $('#wait').val(v); }); $('.my-pond').on('FilePond:processfileprogress', function(e) { // console.log('P ', e); }); });
407c3fee48f4f020f8f44fc85501c30d05c40b7c
[ "JavaScript" ]
5
JavaScript
saqibalich1/saqib
0bca411ac8352411f534400a5dedc3e282181ae1
70015f819715204e4e147a52a40b31dcb1631a64
refs/heads/master
<repo_name>SeokSeth/pairbnb2<file_sep>/app/controllers/listings_controller.rb class ListingsController < ApplicationController before_action :require_login, only: [:new, :edit, :show] def index end def new @listing = Listing.new end def edit end def show end end
e14088a9c30d7f222d7e1d40380f2c7727319fe4
[ "Ruby" ]
1
Ruby
SeokSeth/pairbnb2
a7b88d860cd274411d139e1284ce5e7b5ee3656b
926e37ccd34ade6a61bb933d6f9a5b2c045b53a1
refs/heads/master
<repo_name>dzemianenka/REST-Blog<file_sep>/src/main/java/com/demosocket/blog/exception/UserAlreadyExist.java package com.demosocket.blog.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.BAD_REQUEST) public class UserAlreadyExist extends RuntimeException { private static final long serialVersionUID = -285433284280156277L; } <file_sep>/psql/create-database.sql DROP SCHEMA IF EXISTS blog; CREATE SCHEMA blog; DROP TABLE IF EXISTS blog.users; CREATE TABLE blog.users ( id serial NOT NULL CONSTRAINT users_pk PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(255) NOT NULL, hash_password VARCHAR(255) NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL, user_role VARCHAR(30) NOT NULL, enabled boolean NOT NULL ); DROP TABLE IF EXISTS blog.articles; CREATE TABLE blog.articles ( id serial NOT NULL CONSTRAINT articles_pk PRIMARY KEY, title VARCHAR(255) NOT NULL, article text NOT NULL, status VARCHAR(30) NOT NULL, user_id INTEGER NOT NULL CONSTRAINT articles_users_id_fk REFERENCES blog.users, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL, updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL ); DROP TABLE IF EXISTS blog.comments; CREATE TABLE blog.comments ( id serial NOT NULL CONSTRAINT comments_pk PRIMARY KEY, text_message text NOT NULL, article_id INTEGER NOT NULL CONSTRAINT comments_articles_id_fk REFERENCES blog.articles, user_id INTEGER NOT NULL CONSTRAINT comments_users_id_fk REFERENCES blog.users, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL ); DROP TABLE IF EXISTS blog.tags; CREATE TABLE blog.tags ( id serial NOT NULL CONSTRAINT tags_pk PRIMARY KEY, tag_name VARCHAR(255) NOT NULL ); DROP TABLE IF EXISTS blog.article_tag; CREATE TABLE blog.article_tag ( article_id INTEGER NOT NULL CONSTRAINT article_tag_articles_id_fk REFERENCES blog.articles, tag_id INTEGER NOT NULL CONSTRAINT article_tag_tags_id_fk REFERENCES blog.tags );<file_sep>/src/main/java/com/demosocket/blog/service/EmailService.java package com.demosocket.blog.service; public interface EmailService { void sendEmail(String email, String url, String token); } <file_sep>/src/main/java/com/demosocket/blog/repository/impl/CustomizeArticlesImpl.java package com.demosocket.blog.repository.impl; import com.demosocket.blog.dto.SearchParametersDto; import com.demosocket.blog.exception.UserNotFoundException; import com.demosocket.blog.model.*; import com.demosocket.blog.repository.CustomizeArticles; import com.demosocket.blog.repository.UserRepository; import lombok.AllArgsConstructor; import org.springframework.data.domain.*; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.criteria.*; import java.util.ArrayList; import java.util.List; @Repository @AllArgsConstructor public class CustomizeArticlesImpl implements CustomizeArticles { private final EntityManager entityManager; private final UserRepository userRepository; @Override public Page<Article> findCriteriaArticles(SearchParametersDto params) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Article> criteriaQuery = cb.createQuery(Article.class); Root<Article> articleRoot = criteriaQuery.from(Article.class); Predicate criteria = cb.conjunction(); // article status Predicate predicateStatus = cb.equal(articleRoot.get(Article_.status), Status.PUBLIC); criteria = cb.and(criteria, predicateStatus); // find by tags if (params.getTags() != null) { Join<Article, Tag> tagJoin = articleRoot.join(Article_.tags); Expression<String> tagExpression = tagJoin.get(Tag_.name.getName()); Predicate predicateTag = tagExpression.in(params.getTags()); criteria = cb.and(criteria, predicateTag); } // find by title if (params.getTitle() != null) { Predicate predicateTitle = cb.equal(articleRoot.get(Article_.title), params.getTitle()); criteria = cb.and(criteria, predicateTitle); } // find by user if (params.getUserId() != null) { Predicate predicateUser = cb.equal(articleRoot.get(Article_.user), userRepository.findById(params.getUserId()).orElseThrow(UserNotFoundException::new)); criteria = cb.and(criteria, predicateUser); } // sort if (Sort.Direction.fromString(params.getOrder()).isAscending()) { criteriaQuery.orderBy(cb.asc(articleRoot.get(params.getSortField()))); } else { criteriaQuery.orderBy(cb.desc(articleRoot.get(params.getSortField()))); } criteriaQuery.select(articleRoot).where(criteria); List<Article> articleList = entityManager.createQuery(criteriaQuery).getResultList(); // pagination int start = params.getPage() * params.getSize(); int end = Math.min((start + params.getSize()), articleList.size()); // copy the articleList into resultList by page List<Article> resultList = new ArrayList<>(); if (start <= end) { resultList = articleList.subList(start, end); } // 'PageImpl' work with 'Pageable' Pageable pageable = PageRequest.of(params.getPage(), params.getSize(), Sort.Direction.fromString(params.getOrder()), params.getSortField()); return new PageImpl<>(resultList, pageable, articleList.size()); } } <file_sep>/src/main/java/com/demosocket/blog/service/impl/EmailServiceImpl.java package com.demosocket.blog.service.impl; import com.demosocket.blog.service.EmailService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = @Autowired) public class EmailServiceImpl implements EmailService { @Value("${spring.mail.username}") private String EMAIL; private final JavaMailSender javaMailSender; @Override public void sendEmail(String email, String url, String code) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(EMAIL); message.setTo(email); message.setText(url + code); try { javaMailSender.send(message); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/src/main/java/com/demosocket/blog/dto/ArticleEditDto.java package com.demosocket.blog.dto; import com.demosocket.blog.model.Status; import lombok.Data; import javax.validation.constraints.NotBlank; import java.util.Set; @Data public class ArticleEditDto { @NotBlank private String title; @NotBlank private String text; private Status status; private Set<String> tags; } <file_sep>/src/main/java/com/demosocket/blog/controller/TagController.java package com.demosocket.blog.controller; import com.demosocket.blog.dto.TagsCountDto; import com.demosocket.blog.service.TagService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping @RequiredArgsConstructor(onConstructor_ = @Autowired) public class TagController { private final TagService tagService; @GetMapping("/tags-cloud") public ResponseEntity<List<TagsCountDto>> cloudOfTags() { return new ResponseEntity<>(tagService.countArticlesWithTag(), HttpStatus.OK); } } <file_sep>/src/main/java/com/demosocket/blog/model/User.java package com.demosocket.blog.model; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.*; import org.springframework.data.annotation.CreatedDate; import javax.persistence.*; import java.util.Date; import java.util.List; @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(exclude = {"articles", "comments"}) @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "email") private String email; @Column(name = "hash_password") private String hashPassword; @CreatedDate @JsonFormat(pattern = "dd.MM.yyyy HH:mm:ss", timezone = "GMT+3") @Column(name = "created_at", insertable = false, updatable = false) private Date createdAt; @Column(name = "user_role") @Enumerated(value = EnumType.STRING) private UserRole userRole; @Column(name = "enabled") private boolean enabled; @OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Article> articles; @OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Comment> comments; } <file_sep>/Dockerfile FROM openjdk:8-jdk-alpine ADD build/libs/blog-0.0.1.jar blog.jar VOLUME /tmp EXPOSE 8080 ENTRYPOINT ["java","-jar","/blog.jar"] <file_sep>/src/main/java/com/demosocket/blog/service/impl/ArticleServiceImpl.java package com.demosocket.blog.service.impl; import com.demosocket.blog.dto.ArticleEditDto; import com.demosocket.blog.dto.ArticleNewDto; import com.demosocket.blog.dto.SearchParametersDto; import com.demosocket.blog.exception.ArticleNotFoundException; import com.demosocket.blog.exception.PermissionDeniedArticleAccessException; import com.demosocket.blog.exception.UserNotFoundException; import com.demosocket.blog.model.*; import com.demosocket.blog.repository.ArticleRepository; import com.demosocket.blog.repository.CustomizeArticles; import com.demosocket.blog.repository.TagRepository; import com.demosocket.blog.repository.UserRepository; import com.demosocket.blog.service.ArticleService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.stereotype.Service; import java.util.*; @Service @RequiredArgsConstructor(onConstructor_ = @Autowired) public class ArticleServiceImpl implements ArticleService { private final TagRepository tagRepository; private final UserRepository userRepository; private final ArticleRepository articleRepository; private final CustomizeArticles customizeArticles; @Override public Page<Article> findAllPublic(SearchParametersDto params) { return customizeArticles.findCriteriaArticles(params); } @Override public Page<Article> findAllByUser(User user, Pageable pageable) { return articleRepository.findAllByUser(user, pageable); } @Override public void saveArticle(ArticleNewDto articleNewDto, String email) { Article article = articleNewDto.toEntity(); article.setUser(userRepository.findByEmail(email).orElseThrow(UserNotFoundException::new)); // check tags in db and save articleRepository.save(checkTagsInDb(article, articleNewDto.getTags())); } @Override public void checkAndDeleteArticle(Integer id, String email) { Article article = articleRepository.findById(id).orElseThrow(ArticleNotFoundException::new); User user = userRepository.findByEmail(email).orElseThrow(UserNotFoundException::new); // check if user wrote this article if (article.getUser().equals(user)) { articleRepository.delete(article); } else { throw new PermissionDeniedArticleAccessException(); } } @Override public void checkAndEditArticle(Integer id, String email, ArticleEditDto articleEditDto) { Article article = articleRepository.findById(id).orElseThrow(ArticleNotFoundException::new); User user = userRepository.findByEmail(email).orElseThrow(UserNotFoundException::new); // check if user wrote this article if (article.getUser().equals(user)) { article.setTitle(articleEditDto.getTitle()); article.setText(articleEditDto.getText()); article.setStatus(articleEditDto.getStatus()); article.setUpdatedAt(new Date()); // check tags in db and save articleRepository.save(checkTagsInDb(article, articleEditDto.getTags())); } else { throw new PermissionDeniedArticleAccessException(); } } private Article checkTagsInDb(Article article, Set<String> tags) { // result tags for article Set<Tag> tagsForArticle = new HashSet<>(); // check if tag already exist for (String tag : tags) { Optional<Tag> tagFromDb = tagRepository.findByName(tag); if (!tagFromDb.isPresent()) { Tag tagToDb = new Tag(); tagToDb.setName(tag); tagRepository.save(tagToDb); tagsForArticle.add(tagToDb); } else { tagsForArticle.add(tagFromDb.get()); } } article.setTags(tagsForArticle); return article; } } <file_sep>/src/main/java/com/demosocket/blog/dto/CommentNewDto.java package com.demosocket.blog.dto; import com.demosocket.blog.model.Comment; import lombok.Data; import javax.validation.constraints.NotBlank; @Data public class CommentNewDto { @NotBlank private String message; public Comment toEntity() { return Comment.builder() .message(message) .build(); } } <file_sep>/src/main/java/com/demosocket/blog/model/Article_.java package com.demosocket.blog.model; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.StaticMetamodel; import javax.persistence.metamodel.SingularAttribute; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(Article.class) public abstract class Article_ { public static volatile SingularAttribute<Article, Date> createdAt; public static volatile ListAttribute<Article, Comment> comments; public static volatile SingularAttribute<Article, Integer> id; public static volatile SingularAttribute<Article, String> text; public static volatile SingularAttribute<Article, String> title; public static volatile SingularAttribute<Article, User> user; public static volatile SingularAttribute<Article, Status> status; public static volatile SingularAttribute<Article, Date> updatedAt; public static volatile SetAttribute<Article, Tag> tags; public static final String CREATED_AT = "createdAt"; public static final String COMMENTS = "comments"; public static final String ID = "id"; public static final String TEXT = "text"; public static final String TITLE = "title"; public static final String USER = "user"; public static final String STATUS = "status"; public static final String UPDATED_AT = "updatedAt"; public static final String TAGS = "tags"; } <file_sep>/src/main/java/com/demosocket/blog/dto/JwtResponseDto.java package com.demosocket.blog.dto; import lombok.AllArgsConstructor; import lombok.Getter; @Getter @AllArgsConstructor public class JwtResponseDto { private final String jwtToken; } <file_sep>/src/main/java/com/demosocket/blog/model/UserRole.java package com.demosocket.blog.model; public enum UserRole { USER, ADMIN } <file_sep>/src/main/java/com/demosocket/blog/service/TagService.java package com.demosocket.blog.service; import com.demosocket.blog.dto.TagsCountDto; import java.util.List; public interface TagService { List<TagsCountDto> countArticlesWithTag(); } <file_sep>/src/main/java/com/demosocket/blog/service/impl/CommentServiceImpl.java package com.demosocket.blog.service.impl; import com.demosocket.blog.dto.CommentNewDto; import com.demosocket.blog.exception.*; import com.demosocket.blog.model.Article; import com.demosocket.blog.model.Comment; import com.demosocket.blog.model.Status; import com.demosocket.blog.model.User; import com.demosocket.blog.repository.ArticleRepository; import com.demosocket.blog.repository.CommentRepository; import com.demosocket.blog.repository.UserRepository; import com.demosocket.blog.service.CommentService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor(onConstructor_ = @Autowired) public class CommentServiceImpl implements CommentService { private final UserRepository userRepository; private final ArticleRepository articleRepository; private final CommentRepository commentRepository; @Override public Comment findComment(String email, Integer articleId, Integer commentId) { User userFinder = userRepository.findByEmail(email).orElseThrow(UserNotFoundException::new); Article article = articleRepository.findById(articleId).orElseThrow(ArticleNotFoundException::new); // check if article hasn't PRIVATE Status if (checkPermissions(article, userFinder)) { return commentRepository.findByArticleAndId(article, commentId).orElseThrow(CommentNotFoundException::new); } else { throw new PermissionDeniedArticleAccessException(); } } @Override public void deleteComment(String email, Integer articleId, Integer commentId) { User userDeleter = userRepository.findByEmail(email).orElseThrow(UserNotFoundException::new); Article article = articleRepository.findById(articleId).orElseThrow(ArticleNotFoundException::new); Comment comment = commentRepository.findById(commentId).orElseThrow(CommentNotFoundException::new); // check if deleter is articleOwner or commentOwner if (userDeleter.equals(article.getUser()) || userDeleter.equals(comment.getUser())) { commentRepository.deleteById(commentId); } else { throw new PermissionDeniedCommentAccessException(); } } public void saveNewComment(CommentNewDto commentNewDto, String email, Integer articleId) { Comment comment = commentNewDto.toEntity(); User userWriter = userRepository.findByEmail(email).orElseThrow(UserNotFoundException::new); comment.setUser(userWriter); Article article = articleRepository.findById(articleId).orElseThrow(ArticleNotFoundException::new); // check if article hasn't PRIVATE Status if (checkPermissions(article, userWriter)) { comment.setArticle(articleRepository.findById(articleId).orElseThrow(ArticleNotFoundException::new)); commentRepository.save(comment); } else { throw new PermissionDeniedArticleAccessException(); } } @Override public Page<Comment> findAllCommentsFromArticle(String email, Integer articleId, Integer userId, Pageable pageable) { User userFinder = userRepository.findByEmail(email).orElseThrow(UserNotFoundException::new); Article article = articleRepository.findById(articleId).orElseThrow(ArticleNotFoundException::new); Page<Comment> commentPage; // if @RequestParam("userId") == 'null' then we should find all articles if (userId == null) { if (checkPermissions(article, userFinder)) { commentPage = commentRepository.findAllByArticle(article, pageable); } else { throw new PermissionDeniedArticleAccessException(); } } else { if (checkPermissions(article, userFinder)) { User user = userRepository.findById(userId).orElseThrow(UserNotFoundException::new); commentPage = commentRepository.findAllByUserAndArticle(user, article, pageable); } else { throw new PermissionDeniedArticleAccessException(); } } return commentPage; } private boolean checkPermissions(Article article, User user) { // user can comment public or own article return article.getStatus().equals(Status.PUBLIC) || (article.getStatus().equals(Status.PRIVATE) && article.getUser().equals(user)); } } <file_sep>/src/test/java/com/demosocket/blog/service/impl/TagServiceImplTest.java package com.demosocket.blog.service.impl; import com.demosocket.blog.model.Article; import com.demosocket.blog.model.Tag; import com.demosocket.blog.repository.ArticleRepository; import com.demosocket.blog.repository.TagRepository; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import java.util.*; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest(classes = TagServiceImpl.class) class TagServiceImplTest { @MockBean private TagRepository tagRepository; @MockBean private ArticleRepository articleRepository; @Test void shouldCountArticlesWithTag() { Tag tag1 = Tag.builder().name("A").build(); Tag tag2 = Tag.builder().name("B").build(); Tag tag3 = Tag.builder().name("C").build(); Article article1 = Article.builder().text("1").tags(new HashSet<>(Arrays.asList(tag1, tag2))).build(); Article article2 = Article.builder().text("2").tags(new HashSet<>(Collections.singletonList(tag1))).build(); Mockito.when(articleRepository.findAllByTags(tag1)).thenReturn(Arrays.asList(article1, article2)); Mockito.when(articleRepository.findAllByTags(tag2)).thenReturn(Collections.singletonList(article2)); Mockito.when(articleRepository.findAllByTags(tag3)).thenReturn(Collections.emptyList()); assertEquals(2, articleRepository.findAllByTags(tag1).size()); assertEquals(1, articleRepository.findAllByTags(tag2).size()); assertEquals(0, articleRepository.findAllByTags(tag3).size()); } } <file_sep>/src/main/java/com/demosocket/blog/config/RedisConfig.java package com.demosocket.blog.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; @Configuration @EnableRedisRepositories public class RedisConfig { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Bean public JedisConnectionFactory redisConnectionFactory() { final RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName(host); redisStandaloneConfiguration.setPort(port); return new JedisConnectionFactory(redisStandaloneConfiguration); } @Bean public RedisTemplate<String, String> redisTemplate() { final RedisTemplate<String, String> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory()); return template; } } <file_sep>/src/main/java/com/demosocket/blog/dto/UserNewDto.java package com.demosocket.blog.dto; import com.demosocket.blog.model.User; import com.demosocket.blog.model.UserRole; import lombok.Builder; import lombok.Data; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; @Data @Builder public class UserNewDto { @NotBlank private String firstName; @NotBlank private String lastName; @Email @NotBlank private String email; @NotBlank private String password; public User toEntity() { return User.builder() .firstName(firstName) .lastName(lastName) .email(email) .hashPassword(password) .userRole(UserRole.USER) .enabled(false) .build(); } } <file_sep>/estimate.md ### Stage 1 (total: 12): - ~~Spring configuration (8+)~~ - ~~DB configuration (4)~~ ### Stage 2 (total: 40): - ~~JWT configuration (8+)~~ - ~~Registration(4+)~~ - ~~Confirm email (4+)~~ - ~~Authorization (8+)~~ - ~~Recovery password (8+)~~ - Testing (8) ### Stage 3 (total: 16): - ~~CRUD operations Articles (8)~~ - Security (4) - Testing (4) ### Stage 4 (total: 12): - ~~CRUD operations Comments (8)~~ - Testing (4) ### Stage 5 (total: 12): - ~~Tags (8)~~ - Testing (4) *** # Process ### ~~Stage 1 (total: 2):~~ - ~~Spring configuration (1)~~ - ~~DB configuration (1)~~ ### ~~Stage 2 (total: 33):~~ - ~~Simple Registration (2)~~ - ~~Send Email (1)~~ - ~~Redis configuration (2)~~ - ~~JWT configuration, Authorization, Confirm Email (12)~~ - ~~Registration with hash_code (7)~~ - ~~Recovery the password (5)~~ - ~~Exception Handler (4)~~ ### ~~Stage 3 (total: 14):~~ - ~~CRUD operations Articles with permits (10)~~ - ~~Pagination (4)~~ ### ~~Stage 4 (total: 6):~~ - ~~CRUD operations Comments with permits (4)~~ - ~~Comments pagination (2)~~ ### ~~Stage 5 (total: 10):~~ - ~~Counting Tags (2)~~ - ~~Add tags to new article (2)~~ - ~~Add tags edited article (2)~~ - ~~Sort articles by tags (4)~~ ### Stage 6 (total: 16): - ~~Docker (15)~~ - ~~Pagination(comments) find by user (1)~~ ### Stage 7 (total: 19) - ~~Docker-compose and Criteria (12)~~ - ~~Change date to timestampz (2)~~ - ~~Validation (2)~~ - ~~Readme file and docker-blog (1)~~ - ~~CommentService bugFix (2)~~ <file_sep>/src/main/java/com/demosocket/blog/controller/RegistrationController.java package com.demosocket.blog.controller; import com.demosocket.blog.dto.UserEmailDto; import com.demosocket.blog.dto.UserNewDto; import com.demosocket.blog.dto.UserResetPasswordDto; import com.demosocket.blog.service.UserService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping("/auth") @RequiredArgsConstructor(onConstructor_ = @Autowired) public class RegistrationController { private final UserService userService; @PostMapping("/sign_up") public ResponseEntity<?> signUp(@Valid @RequestBody UserNewDto userNewDto) { userService.registerNewUser(userNewDto); return new ResponseEntity<>(HttpStatus.OK); } @PostMapping("/send_again") public ResponseEntity<?> sendAgain(@Valid @RequestBody UserEmailDto userEmailDto) { userService.sendAgain(userEmailDto); return new ResponseEntity<>(HttpStatus.OK); } @GetMapping(value = "/confirm/{hash_code}") public ResponseEntity<?> confirmEmail(@PathVariable(name = "hash_code") String registrationHashCode) { userService.confirmEmail(registrationHashCode); return new ResponseEntity<>(HttpStatus.OK); } @PostMapping("/forgot_password") public ResponseEntity<?> forgotPassword(@Valid @RequestBody UserEmailDto userEmailDto) { userService.sendRestoreEmail(userEmailDto.getEmail()); return new ResponseEntity<>(HttpStatus.OK); } @PostMapping("/reset") public ResponseEntity<?> resetPassword(@Valid @RequestBody UserResetPasswordDto userResetPasswordDto) { userService.resetPassword(userResetPasswordDto); return new ResponseEntity<>(HttpStatus.OK); } } <file_sep>/src/main/java/com/demosocket/blog/service/impl/UserDetailsServiceImpl.java package com.demosocket.blog.service.impl; import com.demosocket.blog.exception.UserNotFoundException; import com.demosocket.blog.repository.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Collections; @Service @RequiredArgsConstructor(onConstructor_ = @Autowired) public class UserDetailsServiceImpl implements UserDetailsService { private final UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { com.demosocket.blog.model.User user = userRepository .findByEmail(username).orElseThrow(UserNotFoundException::new); return new User( user.getEmail(), user.getHashPassword(), user.isEnabled(), true, true, true, Collections.singletonList(new SimpleGrantedAuthority(user.getUserRole().toString()))); } } <file_sep>/README.md # REST-blog The application is REST-server ### Stack - Java 8 - Spring Boot - Gradle - PostgreSQL - Redis - Docker ### Docker-Compose Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration. Check the version: ```sh docker-compose --version ``` Start the application: ```sh docker-compose up ``` <file_sep>/src/main/java/com/demosocket/blog/dto/SearchParametersDto.java package com.demosocket.blog.dto; import lombok.Builder; import lombok.Data; import java.util.List; @Data @Builder public class SearchParametersDto { private List<String> tags; private Integer page; private Integer size; private String title; private Integer userId; private String sortField; private String order; } <file_sep>/src/main/java/com/demosocket/blog/service/UserService.java package com.demosocket.blog.service; import com.demosocket.blog.dto.UserEmailDto; import com.demosocket.blog.dto.UserNewDto; import com.demosocket.blog.dto.UserResetPasswordDto; import com.demosocket.blog.model.User; public interface UserService { User findByEmail(String email); void activateUser(String email); void confirmEmail(String token); void sendRestoreEmail(String email); void sendAgain(UserEmailDto userEmailDto); void registerNewUser(UserNewDto userNewDto); void resetPassword(UserResetPasswordDto userResetPasswordDto); } <file_sep>/src/main/java/com/demosocket/blog/security/jwt/JwtRequestFilter.java package com.demosocket.blog.security.jwt; import io.jsonwebtoken.ExpiredJwtException; import lombok.AllArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static com.demosocket.blog.security.SecurityConstants.*; @Component @AllArgsConstructor public class JwtRequestFilter extends OncePerRequestFilter { private final UserDetailsService userDetailsService; private final JwtTokenUtil jwtTokenUtil; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { final String requestTokenHeader = request.getHeader(HEADER_STRING); String email = null; String jwtToken = null; if (requestTokenHeader != null && requestTokenHeader.startsWith(TOKEN_PREFIX)) { jwtToken = requestTokenHeader.substring(7); try { email = jwtTokenUtil.getEmailFromToken(jwtToken); } catch (IllegalArgumentException e) { System.out.println(MESSAGE_CANT_GET_TOKEN); } catch (ExpiredJwtException e) { System.out.println(MESSAGE_TOKEN_HAS_EXPIRED); } } if (email != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.userDetailsService.loadUserByUsername(email); if (jwtTokenUtil.validateToken(jwtToken, userDetails)) { UsernamePasswordAuthenticationToken emailPasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); emailPasswordAuthenticationToken.setDetails( new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(emailPasswordAuthenticationToken); } } filterChain.doFilter(request, response); } } <file_sep>/src/main/java/com/demosocket/blog/repository/ArticleRepository.java package com.demosocket.blog.repository; import com.demosocket.blog.model.Article; import com.demosocket.blog.model.Tag; import com.demosocket.blog.model.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface ArticleRepository extends JpaRepository<Article, Integer> { Page<Article> findAllByUser(User user, Pageable pageable); List<Article> findAllByTags(Tag tag); }
500e83b776cac3b7eb254dfdf6825f785d8f855a
[ "Markdown", "Java", "Dockerfile", "SQL" ]
27
Java
dzemianenka/REST-Blog
de2e5481d40faf7666a795c1e64dff7eb796cdad
f4f862884dddbe5fb56f4e70d67801d8f9e24c98
refs/heads/master
<file_sep>// 1. // * Create a Human constructor function that takes in a name and age. // * Add a prototype function ageOneYear that ages the humans age. // * Add a prototype function eating, that logs "mmm, mmm, mmm, I'm love'n it". // * Create an instance of the Human class. // * console log your humans age // * call ageOneYear on your human // * console log their age again. // * call eating on your human. // function Human (name, age) { // this.name = name; // this.age = age; // }; // // Human.prototype.ageOneYear = function() { // this.age++; // }; // // Human.prototype.eating = function() { // console.log( `mmm, mmm, mmm, I'm loving it`) // }; // // let trey = new Human ("Trey", 31) // // console.log(trey); // trey.ageOneYear(); // console.log(trey.age); // trey.eating(); // // Write a constructor Vector that represents a vector in two-dimensional space. It takes two number arguments: x and y parameters, which it should be saved to properties of the same name. // // Give the Vector prototype two methods, plus and minus, that take another vector as an argument and returns a new vector that has the sum or difference of the two vectors’ (the one in this and the parameter) x and y values. // // Add a method getLength to the prototype that computes the length of the vector ; that is, the distance of the point (x, y) from the origin (0, 0).(a^2 + b^2 = c^2) class Vector { constructor(x, y) { this.x = x; this.y = y; this.plus = function(vector) { return new Vector(this.x + vector.x, this.y + vector.y); }; this.minus = function(vector) { return new Vector(this.x - vector.x, this.y + vector.y); }; this.getLength = function() { return Math.sqrt(this.x * this.x + this.y * this.y); }; } } var v1 = new Vector(1, 2) var v2 = new Vector(2, 3) var v3 = new Vector(3, 4) console.log(v3.getLength());
c36aa069bea5915438201e83feb861e0e62286d2
[ "JavaScript" ]
1
JavaScript
treaganbirbal/constructor_assignment
cbe2adf7569af63d93f7fbe00e46783f82e0ec0c
921a873323b7ef165acd5f03d258a823c432b1b9
refs/heads/master
<repo_name>emipa606/CallofCthulhuCults<file_sep>/Source/CultOfCthulhu/CultsDefOf.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here using RimWorld; using Verse; using Verse.AI; using AbilityDef = AbilityUser.AbilityDef; // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { [DefOf] public class CultsDefOf { // ============= UNSORTED ============ public static ThingDef Cults_ElixerOfPower; public static ThingDef Cults_BlackIchorMeal; public static ThingDef Cults_SignOfDagon; public static DamageDef Cults_Psionic; public static AbilityDef Cults_PsionicBlast; public static AbilityDef Cults_PsionicShock; public static AbilityDef Cults_PsionicBurn; public static RoomRoleDef Cults_Temple; public static ThingDef Cults_ForbiddenKnowledgeCenter; public static LetterDef Cults_StandardMessage; public static ThoughtDef Cults_PrayedInImpressiveTemple; public static ThingDef Cults_TransmogAura; // ============ GAME CONDITIONS ======= public static GameConditionDef CultgameCondition_StarsAreWrong; public static GameConditionDef CultgameCondition_StarsAreRight; // ============ DUTY DEFS ============= public static DutyDef Cults_LoadAndEnterTransportersPawn; // =============== JOBS =============== // Flying Pawn public static JobDef Cults_EnterTransporterPawn; // Offering Related Defs public static JobDef Cults_GiveOffering; public static JobDef Cults_ReflectOnOffering; // Sacrifice Related Defs public static JobDef Cults_HoldSacrifice; public static JobDef Cults_AttendSacrifice; public static JobDef Cults_ReflectOnResult; public static JobDef Cults_WaitTiedDown; // Worship Related Jobs public static JobDef Cults_HoldWorship; public static JobDef Cults_AttendWorship; public static JobDef Cults_ReflectOnWorship; public static JobDef Cults_Investigate; public static JobDef Cults_WriteTheBook; // Misc Jobs public static JobDef Cults_MidnightInquisition; public static JobDef Cults_PruneAndRepair; // ============== FACTIONS ============= public static FactionDef Cults_Sailors; // =============== PAWNS =============== public static PawnKindDef Cults_BlackGoat; public static PawnKindDef Cults_Byakhee; public static PawnKindDef Cults_FormlessSpawn; public static PawnKindDef Cults_Sailor; // ========== MENTAL STATE DEF ========== public static MentalStateDef Cults_DeepSleepCarcosa; // =============== HEDIFFS =============== public static HediffDef Cults_PsionicBrain; public static HediffDef Cults_MonstrousBody; public static HediffDef Cults_TentacleArm; public static HediffDef Cults_CthulhidTentacle; public static HediffDef Cults_CthulhidEyestalk; public static HediffDef Cults_SleepHediff; // =============== THOUGHTS =============== // 1.2.2 public static ThoughtDef Cults_OtherPrisonerWasSacrificed; public static ThoughtDef Cults_MadeInvestigation; public static ThoughtDef Cults_BlackoutBook; public static ThoughtDef Cults_HeldSermon; public static ThoughtDef Cults_FoundedCult; public static ThoughtDef Cults_MidnightInquisitionThought; //Sacrifice public static ThoughtDef Cults_AttendedSuccessfulSacrifice; public static ThoughtDef Cults_AttendedFailedSacrifice; public static ThoughtDef Cults_InnocentAttendedSuccessfulSacrifice; public static ThoughtDef Cults_InnocentAttendedFailedSacrifice; //Relationship Sacrifice Thoughts public static ThoughtDef Cults_ExecutedFamily; public static ThoughtDef Cults_ExecutedPet; public static ThoughtDef Cults_SacrificedFamily; public static ThoughtDef Cults_SacrificedPet; public static ThoughtDef Cults_SacrificedFriend; public static ThoughtDef Cults_SacrificedRival; // Worship public static ThoughtDef Cults_AttendedIncredibleSermonAsCultist; public static ThoughtDef Cults_AttendedIncredibleSermonAsInnocent; public static ThoughtDef Cults_AttendedGreatSermonAsCultist; public static ThoughtDef Cults_AttendedGreatSermonAsInnocent; public static ThoughtDef Cults_AttendedGoodSermonAsCultist; public static ThoughtDef Cults_AttendedGoodSermonAsInnocent; public static ThoughtDef Cults_AttendedDecentSermonAsCultist; public static ThoughtDef Cults_AttendedDecentSermonAsInnocent; public static ThoughtDef Cults_AttendedAwfulSermonAsCultist; public static ThoughtDef Cults_AttendedAwfulSermonAsInnocent; // Misc public static ThoughtDef Cults_SawAurora; // =============== SOUNDS =============== public static SoundDef RitualChanting; // =============== BUILDINGS =============== public static ThingDef Cults_SleepTotem; public static ThingDef Cults_FertilityTotem; public static ThingDef Cults_TreasureChest; public static ThingDef Cults_TreasureChest_Relic; public static ThingDef Cults_SunkenShipChunk; public static ThingDef Cults_MonolithNightmare; public static ThingDef Cults_LandedShip; // ============== THINGS ============== public static ThingDef Cults_WombBetweenWorlds; public static ThingDef Cults_PlantTreeNightmare; public static ThingDef Cults_Grimoire; public static ThingDef Cults_TheKingInYellow; // ============== MAP CONDITIONS ============== public static GameConditionDef Cults_Aurora; // ============= CORE REFERENCES ============== public static ThingDef Penoxycyline; public static ThingDef BlocksSlate; public static ThingDef BlocksLimestone; public static ThingDef BlocksMarble; public static ThingDef Neutroamine; public static PawnKindDef Rat; public static MentalStateDef FireStartingSpree; public static ResearchProjectDef Forbidden_Reports; } }<file_sep>/Source/CultOfCthulhu/UI/ITab_AltarCardUtility.cs using System.Collections.Generic; using System.Text; using CallOfCthulhu; using Cthulhu; using HarmonyLib; using RimWorld; using UnityEngine; using Verse; namespace CultOfCthulhu { internal class ITab_AltarCardUtility { /// <summary> /// This will make things easier for processing multiple possibile "actors" at the altar. /// </summary> public enum ActorType { executioner = 0, preacher = 1, offerer = 2, attendee = 3, prisoner = 4, animalSacrifice = 5 } public enum DeityType { WorshipDeity = 0, OfferingDeity = 1, SacrificeDeity = 2 } public static void DrawRename(Building_SacrificialAltar altar) { var rectRename = new Rect(ITab_AltarWorshipCardUtility.TempleCardSize.x - 85f, 0f, 30f, 30f); TooltipHandler.TipRegion(rectRename, "RenameTemple".Translate()); if (Widgets.ButtonImage(rectRename, Buttons.RenameTex)) { Find.WindowStack.Add(new Dialog_RenameTemple(altar)); } } public static void DrawDeity(CosmicEntity entity, Rect rect3, string spellDescription = null, float offset = 0f) { var entityLabel = ""; var entityDescrip = ""; if (entity != null) { entityLabel = entity.LabelCap; entityDescrip = entity.def.description; } var secondBox = rect3; secondBox.x += rect3.x + 10f + 30f + offset; secondBox.xMax += 125f; secondBox.height = ITab_AltarSacrificesCardUtility.ButtonSize; Text.Font = GameFont.Medium; Widgets.Label(secondBox, entityLabel); Text.Font = GameFont.Small; var secondBoxUnder = secondBox; secondBoxUnder.y += ITab_AltarSacrificesCardUtility.ButtonSize + ITab_AltarSacrificesCardUtility.SpacingOffset; secondBoxUnder.width -= 15f; secondBoxUnder.height = ITab_AltarSacrificesCardUtility.ButtonSize; Widgets.Label(secondBoxUnder, entityDescrip); DrawTier(entity, new Vector2(secondBoxUnder.x, secondBoxUnder.y + 70f)); var secondBoxUnder2 = secondBoxUnder; secondBoxUnder2.y += (ITab_AltarSacrificesCardUtility.ButtonSize * 2) + (ITab_AltarSacrificesCardUtility.SpacingOffset * 2); secondBoxUnder2.height = 250f; if (spellDescription != null) { Widgets.Label(secondBoxUnder2, spellDescription); } } // RimWorld.SkillUI// public static void DrawTier(CosmicEntity entity, Vector2 topLeft) { if (entity == null) { return; } _ = entity.PlayerTier.ToString(); string standingLabel = "Standing".Translate() + ":"; var tierLabelWidth = Text.CalcSize(standingLabel).x; var tierCurrentVal = entity.PlayerFavor; var tierCurrentMax = entity.currentTierMax; var tierPrevMax = entity.prevTierMax; var rect = new Rect(topLeft.x, topLeft.y, 150f, 24f); if (Mouse.IsOver(rect)) { GUI.DrawTexture(rect, TexUI.HighlightTex); } GUI.BeginGroup(rect); Text.Anchor = TextAnchor.MiddleLeft; var rect2 = new Rect(0f, 0f, tierLabelWidth + 5f, rect.height); Widgets.Label(rect2, standingLabel); var position = new Rect(rect2.xMax, 0f, 10f, 24f); var rect3 = new Rect(position.xMax, 0f, rect.width - position.xMax, rect.height); Widgets.FillableBar(rect3, (tierCurrentVal - tierPrevMax) / (tierCurrentMax - tierPrevMax), Buttons.TierBarFillTex, null, false); var rect4 = new Rect(position.xMax + 4f, 0f, 999f, rect.height); //rect4.yMin += 10f; rect4.yMax += 18f; var label = entity.TierString; GenUI.SetLabelAlign(TextAnchor.MiddleLeft); Widgets.Label(rect4, label); GenUI.ResetLabelAlign(); GUI.color = Color.white; GUI.EndGroup(); TooltipHandler.TipRegion(rect, new TipSignal(GetFavorDescription(entity), entity.def.GetHashCode() * 397945)); } // RimWorld.SkillUI private static string GetFavorDescription(CosmicEntity entity) { var stringBuilder = new StringBuilder(); if (entity == null) { stringBuilder.Append("DisabledLower".Translate().CapitalizeFirst()); } else { stringBuilder.AppendLine(string.Concat("Tier".Translate(), " ", entity.PlayerTier, ": ", entity.TierString)); if (Current.ProgramState == ProgramState.Playing) { string text = entity.PlayerTier != CosmicEntity.Tier.Final ? "ProgressToNextLevel".Translate() : "Favor".Translate(); stringBuilder.AppendLine(string.Concat(new object[] { text, ": ", entity.PlayerFavor.ToString("F"), " / ", entity.currentTierMax.ToString("F") })); } } stringBuilder.AppendLine(); stringBuilder.AppendLine(); stringBuilder.Append("FavorDescription".Translate()); return stringBuilder.ToString(); } ////////General Stuff public static string SacrificeLabel(Building_SacrificialAltar altar) { return altar.tempSacrifice == null ? "None" : altar.tempSacrifice.Name.ToStringShort; } public static string ExecutionerLabel(Building_SacrificialAltar altar) { return altar.tempExecutioner == null ? "None" : altar.tempExecutioner.Name.ToStringShort; } public static string DeityLabel(Building_SacrificialAltar altar, DeityType deityType) { switch (deityType) { case DeityType.OfferingDeity: if (altar.tempCurrentOfferingDeity == null) { return "None"; } return altar.tempCurrentOfferingDeity.LabelCap; case DeityType.WorshipDeity: if (altar.tempCurrentWorshipDeity == null) { return "None"; } return altar.tempCurrentWorshipDeity.LabelCap; case DeityType.SacrificeDeity: if (altar.tempCurrentSacrificeDeity == null) { return "None"; } return altar.tempCurrentSacrificeDeity.LabelCap; } return "None"; } public static string SpellLabel(Building_SacrificialAltar altar) { return altar.tempCurrentSacrificeDeity == null || altar.tempCurrentSpell == null ? "None" : (string) altar.tempCurrentSpell.LabelCap; } public static string SpellDescription(Building_SacrificialAltar altar) { return altar.tempCurrentSacrificeDeity == null || altar.tempCurrentSpell == null ? "None" : altar.tempCurrentSpell.description; } public static string DeityDescription(Building_SacrificialAltar altar) { if (altar.tempCurrentSacrificeDeity == null) { return "None"; } var stringBuilder = new StringBuilder(); stringBuilder.AppendLine(); stringBuilder.Append(altar.tempCurrentSacrificeDeity.def.description); return stringBuilder.ToString(); } public static void OpenSacrificeSelectMenu(Building_SacrificialAltar altar) { var list = new List<FloatMenuOption> { new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate { altar.tempSacrifice = null; }) }; foreach (var current in altar.Map.mapPawns.AllPawnsSpawned) { if (!current.RaceProps.Animal || current.Faction != Faction.OfPlayer) { continue; } var localCol = current; void Action() { altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastSacrificeType = CultUtility.SacrificeType.animal; altar.tempSacrifice = localCol; } list.Add(new FloatMenuOption(localCol.LabelShort, Action)); } Find.WindowStack.Add(new FloatMenu(list)); } public static void OpenActorSelectMenu(Building_SacrificialAltar altar, ActorType actorType) { if (altar == null) { Utility.ErrorReport("Altar Null Exception"); return; } if (altar.Map == null) { Utility.ErrorReport("Map Null Exception"); } if (altar.Map?.mapPawns == null) { Utility.ErrorReport("mapPawns Null Exception"); return; } if (altar.Map.mapPawns.FreeColonistsSpawned == null) { Utility.ErrorReport("FreeColonistsSpawned Null Exception"); return; } //if (altar.Map.mapPawns.FreeColonistsSpawnedCount <= 0) //{ // Cthulhu.Utility.ErrorReport("Colonist Count Less Than or Equal To 0 Exception"); // return; //} var actorList = new List<Pawn>(); var s = new StringBuilder(); switch (actorType) { case ActorType.executioner: case ActorType.offerer: // Cycle through candidates foreach (var candidate in altar.Map.mapPawns.FreeColonistsSpawned) { if (!CultUtility.IsCultistAvailable(candidate)) { continue; } // Executioners must be able to use tool and move. if (!candidate.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation) || !candidate.health.capacities.CapableOf(PawnCapacityDefOf.Moving)) { continue; } // Add the actors. actorList.Add(candidate); Utility.DebugReport("Actor List :: Added " + candidate.Name); } Utility.DebugReport(s.ToString()); break; case ActorType.preacher: // Cycle through candidates foreach (var candidate in altar.Map.mapPawns.FreeColonistsSpawned) { if (!CultUtility.IsCultistAvailable(candidate)) { continue; } // Preachers must be able to move and talk. if (!candidate.health.capacities.CapableOf(PawnCapacityDefOf.Moving) || !candidate.health.capacities.CapableOf(PawnCapacityDefOf.Talking)) { continue; } // Add the actors. actorList.Add(candidate); Utility.DebugReport("Actor List :: Added " + candidate.Name); } Utility.DebugReport(s.ToString()); break; case ActorType.prisoner: if (altar.Map.mapPawns.PrisonersOfColonySpawned == null) { Messages.Message("No prisoners available.", MessageTypeDefOf.RejectInput); return; } if (altar.Map.mapPawns.PrisonersOfColonySpawnedCount <= 0) { Messages.Message("No prisoners available.", MessageTypeDefOf.RejectInput); return; } // Cycle through possible candidates in the map's prisoner list foreach (var candidate in altar.Map.mapPawns.PrisonersOfColonySpawned) { if (!Utility.IsActorAvailable(candidate, true)) { continue; } actorList.Add(candidate); } break; case ActorType.animalSacrifice: if (altar.Map.mapPawns.AllPawnsSpawned == null) { Messages.Message("No " + actorType + "s available.", MessageTypeDefOf.RejectInput); return; } if (altar.Map.mapPawns.AllPawnsSpawnedCount <= 0) { Messages.Message("No " + actorType + "s available.", MessageTypeDefOf.RejectInput); return; } // Cycle through possible candidates in the player's owned animals list. foreach (var candidate in altar.Map.mapPawns.AllPawnsSpawned) { if (!Utility.IsActorAvailable(candidate, true)) { continue; } if (candidate.Faction != Faction.OfPlayer) { continue; } if (candidate.RaceProps == null) { continue; } if (!candidate.RaceProps.Animal) { continue; } actorList.Add(candidate); } break; } // Let the player know there are no prisoners available. if (actorList.Count <= 0) { Messages.Message("No " + actorType + "s available.", MessageTypeDefOf.RejectInput); return; } //There must always be a none. var list = new List<FloatMenuOption> { new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate { altar.tempExecutioner = null; }) }; foreach (var actor in actorList) { var localCol = actor; void Action() { switch (actorType) { case ActorType.executioner: MapComponent_SacrificeTracker.Get(altar.Map).lastUsedAltar = altar; altar.tempExecutioner = localCol; break; case ActorType.preacher: altar.tempPreacher = localCol; break; case ActorType.offerer: MapComponent_SacrificeTracker.Get(altar.Map).lastUsedAltar = altar; altar.tempOfferer = localCol; break; case ActorType.prisoner: MapComponent_SacrificeTracker.Get(altar.Map).lastUsedAltar = altar; MapComponent_SacrificeTracker.Get(altar.Map).lastSacrificeType = CultUtility.SacrificeType.human; altar.tempSacrifice = localCol; break; case ActorType.animalSacrifice: MapComponent_SacrificeTracker.Get(altar.Map).lastUsedAltar = altar; MapComponent_SacrificeTracker.Get(altar.Map).lastSacrificeType = CultUtility.SacrificeType.animal; altar.tempSacrifice = localCol; break; } } list.Add(new FloatMenuOption(localCol.LabelShort, Action)); } Find.WindowStack.Add(new FloatMenu(list)); } public static bool DeityInfoCardButton(float x, float y, CosmicEntity entity) { bool result; if ((bool) AccessTools.Method(typeof(Widgets), "InfoCardButtonWorker").Invoke(null, new object[] {x, y})) { Find.WindowStack.Add(new Dialog_CosmicEntityInfoBox(entity)); result = true; } else { result = false; } return result; } public static void OpenDeitySelectMenu(Building_SacrificialAltar altar, DeityType deityType) { var list = new List<FloatMenuOption> { new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate { altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; altar.tempCurrentSacrificeDeity = null; }) }; foreach (var current in DeityTracker.Get.DeityCache.Keys) { if (current.discovered == false) { continue; } var localDeity = current; void Action() { MapComponent_SacrificeTracker.Get(altar.Map).lastUsedAltar = altar; switch (deityType) { case DeityType.WorshipDeity: altar.tempCurrentWorshipDeity = localDeity; break; case DeityType.OfferingDeity: altar.tempCurrentOfferingDeity = localDeity; break; case DeityType.SacrificeDeity: altar.tempCurrentSacrificeDeity = localDeity; altar.tempCurrentSpell = null; break; } } bool extraPartOnGUI(Rect rect) { return DeityInfoCardButton(rect.x + 5f, rect.y + ((rect.height - 24f) / 2f), current); } list.Add(new FloatMenuOption(localDeity.LabelCap, Action, MenuOptionPriority.Default, null, null, 29f, extraPartOnGUI)); } Find.WindowStack.Add(new FloatMenu(list)); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/CosmicEntities/FavoredThing.cs using System.Xml; using Verse; namespace CultOfCthulhu { public class FavoredThing { public float favor; public string thingDef; public FavoredThing() { } public FavoredThing(string thingDef, float favor) { this.thingDef = thingDef; this.favor = favor; } public string Summary => favor.ToStringPercent() + " favor " + (thingDef ?? "null"); public void LoadDataFromXmlCustom(XmlNode xmlRoot) { //DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "thingDef", xmlRoot.Name); thingDef = (string) ParseHelper.FromString(xmlRoot.Name, typeof(string)); favor = (float) ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(float)); } public override string ToString() { return string.Concat(new object[] { "(", thingDef ?? "null", " (", favor.ToStringPercent(), "% Favor)", ")" }); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/Command_LoadToTransporter.cs using System.Collections.Generic; using RimWorld; using UnityEngine; using Verse; using Verse.AI; namespace CultOfCthulhu { [StaticConstructorOnStartup] public class Command_LoadToTransporterPawn : Command { public CompTransporterPawn transComp; private List<CompTransporterPawn> transporters; public override void ProcessInput(Event ev) { base.ProcessInput(ev); if (transporters == null) { transporters = new List<CompTransporterPawn>(); } if (!transporters.Contains(transComp)) { transporters.Add(transComp); } _ = transComp.Launchable; foreach (var compTransporterPawn in transporters) { if (compTransporterPawn == transComp) { continue; } if (transComp.Map.reachability.CanReach(transComp.parent.Position, compTransporterPawn.parent, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors))) { continue; } Messages.Message("MessageTransporterUnreachable".Translate(), compTransporterPawn.parent, MessageTypeDefOf.RejectInput); return; } Find.WindowStack.Add(new Dialog_LoadTransportersPawn(transComp.Map, transporters)); } public override bool InheritInteractionsFrom(Gizmo other) { var command_LoadToTransporter = (Command_LoadToTransporterPawn) other; if (command_LoadToTransporter.transComp.parent.def != transComp.parent.def) { return false; } if (transporters == null) { transporters = new List<CompTransporterPawn>(); } transporters.Add(command_LoadToTransporter.transComp); return false; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Hastur/SpellWorker_UnspeakableOath.cs using System.Collections.Generic; using System.Text; using Cthulhu; using RimWorld; using Verse; namespace CultOfCthulhu { internal class SpellWorker_UnspeakableOath : SpellWorker { public override bool CanSummonNow(Map map) { if (TempExecutioner(map) != null) { var sacrificeTracker = map.GetComponent<MapComponent_SacrificeTracker>(); if (sacrificeTracker != null) { if (sacrificeTracker.unspeakableOathPawns == null) { sacrificeTracker.unspeakableOathPawns = new List<Pawn>(); } if (!sacrificeTracker.unspeakableOathPawns.Contains(TempExecutioner(map))) { return true; } Messages.Message("Executioner has already taken an unspeakable oath.", MessageTypeDefOf.RejectInput); return false; } Messages.Message("Missing map component.", MessageTypeDefOf.RejectInput); return false; } Messages.Message("Executioner is unavailable.", MessageTypeDefOf.RejectInput); return false; } protected override bool TryExecuteWorker(IncidentParms parms) { var map = (Map) parms.target; var sacrificeTracker = map.GetComponent<MapComponent_SacrificeTracker>(); if (sacrificeTracker == null) { return Utility.ResultFalseWithReport(new StringBuilder("Missing map component.")); } if (sacrificeTracker.unspeakableOathPawns == null) { sacrificeTracker.unspeakableOathPawns = new List<Pawn>(); } if (!Utility.IsActorAvailable(executioner(map))) { Messages.Message("Executioner is unavailable.", MessageTypeDefOf.RejectInput); return false; } executioner(map).story.traits.GainTrait(new Trait(TraitDef.Named("Cults_OathtakerHastur"))); sacrificeTracker.unspeakableOathPawns.Add(executioner(map)); return true; } } }<file_sep>/Source/CultOfCthulhu/Thing_Transmogrified.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here using Verse; // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class Thing_Transmogrified : Thing { public ThingDef originalDef; public Thing_Transmogrified(ThingDef newDef) { if (newDef is ThingDef_Transmogrified) { originalDef = newDef; } } public override void SpawnSetup(Map map, bool bla) { base.SpawnSetup(map, bla); } public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref originalDef, "originalDef"); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Seed/IncidentWorker_CultSeed_NightmareMonolith.cs using Cthulhu; using RimWorld; using Verse; namespace CultOfCthulhu { internal class IncidentWorker_CultSeed_NightmareMonolith : IncidentWorker_CultSeed { protected override bool TryExecuteWorker(IncidentParms parms) { //Create a spawn point for our nightmare Tree if (!(parms.target is Map map)) { return false; } if (!Utility.TryFindSpawnCell(CultsDefOf.Cults_MonolithNightmare, map.Center, map, 60, out var intVec)) { return false; } //Spawn in the nightmare tree. var thing = (Building) ThingMaker.MakeThing(CultsDefOf.Cults_MonolithNightmare); //thing.Growth = 1f; GenPlace.TryPlaceThing(thing, intVec.RandomAdjacentCell8Way(), map, ThingPlaceMode.Near); ////Find the best researcher //Pawn researcher = CultUtility.DetermineBestResearcher(map); ////Clear all jobs for the researcher. ////Give them a new job to investigate the nightmare tree. //if (ModSettings_Data.cultsForcedInvestigation) //ModSettings.cultsForcedInvestigation()) //If forced investigation is allowed. //{ // Job J = new Job(CultsDefOf.Cults_Investigate, researcher, thing); // researcher.jobs.TryTakeOrderedJob(J); // //researcher.jobs.EndCurrentJob(JobCondition.InterruptForced); //} Find.World.GetComponent<WorldComponent_GlobalCultTracker>().currentSeedState = CultSeedState.NeedSeeing; //map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedPawn = researcher; //map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedTarget = thing; return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Interactions/InteractionWorker_SafePreach.cs using System.Collections.Generic; using RimWorld; using Verse; namespace CultOfCthulhu { /// <summary> /// Cultist shares ideas with a non-cultist successfully. /// </summary> public class InteractionWorker_SafePreach : InteractionWorker { //How great the effect is on the cultminded values. public const float CULTMINDED_EFFECT_MIN = 0.025f; public const float CULTMINDED_EFFECT_MAX = 0.05f; //Very common interaction private const float BaseSelectionWeight = 1f; public override void Interacted(Pawn initiator, Pawn recipient, List<RulePackDef> extraSentencePacks, out string letterText, out string letterLabel, out LetterDef letterDef, out LookTargets lookTargets) { base.Interacted(initiator, recipient, extraSentencePacks, out letterText, out letterLabel, out letterDef, out lookTargets); CultUtility.AffectCultMindedness(recipient, Rand.Range(CULTMINDED_EFFECT_MIN, CULTMINDED_EFFECT_MAX)); CultUtility.AffectCultMindedness(initiator, Rand.Range(CULTMINDED_EFFECT_MIN, CULTMINDED_EFFECT_MAX)); } public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) { //We need two individuals that are part of the colony if (!initiator.IsColonist || !initiator.IsPrisoner) { return 0f; } if (!recipient.IsColonist || !recipient.IsPrisoner) { return 0f; } //If they are sleeping, don't do this. if (initiator.jobs.curDriver.asleep) { return 0f; } if (recipient.jobs.curDriver.asleep) { return 0f; } //The recipient must not be cult-minded. if (CultUtility.IsCultMinded(recipient)) { return 0f; } //The initiator must be cult-minded. if (!CultUtility.IsCultMinded(initiator)) { return 0f; } //If they have a good relationship, increase the chances of the interaction. return initiator.relations.OpinionOf(recipient) > 0 ? Rand.Range(0.8f, 1f) : 0f; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Tsathoggua/Building_TotemSleep.cs using System.Collections.Generic; using System.Text; using RimWorld; using Verse; namespace CultOfCthulhu { public class Building_TotemSleep : Building { public enum State { Asleep = 0, Drowsy = 1, Awake = 2 } private bool cellsDirty = true; private Graphic curGraphic; private List<IntVec3> tempCells; private int ticksToReset = -1; public State CurState { get { var curState = State.Asleep; switch (ActiveVictims.Count) { case 0: curState = State.Awake; break; case 1: curState = State.Drowsy; break; case 2: curState = State.Asleep; break; } curGraphic = null; return curState; } } public List<IntVec3> SleepableCells { get { if (!tempCells.NullOrEmpty() && !cellsDirty) { return tempCells; } cellsDirty = false; tempCells = new List<IntVec3>(GenRadial.RadialCellsAround(Position, def.specialDisplayRadius, true)); return tempCells; } } public List<Pawn> ActiveVictims { get; set; } = new List<Pawn>(); public override Graphic Graphic { get { if (curGraphic != null) { return curGraphic; } switch (CurState) { case State.Asleep: curGraphic = GraphicConstructor( "Building/Exotic/SleepTotem/SleepTotemAsleep"); break; case State.Drowsy: curGraphic = DefaultGraphic; break; case State.Awake: curGraphic = GraphicConstructor( "Building/Exotic/SleepTotem/SleepTotemAwake"); break; } return curGraphic; } } public int TicksToReset { get => ticksToReset; set => ticksToReset = value; } public override void SpawnSetup(Map map, bool respawningAfterLoad) { base.SpawnSetup(map, respawningAfterLoad); cellsDirty = true; } public void TryToSendToSleep(Pawn victim) { TicksToReset = Find.TickManager.TicksGame + (GenDate.TicksPerHour * 8); ActiveVictims.Add(victim); //victim.needs.rest.CurLevelPercentage = 0.0f; GenExplosion.DoExplosion(victim.PositionHeld, victim.MapHeld, 1f, DamageDefOf.Smoke, this); HealthUtility.AdjustSeverity(victim, CultsDefOf.Cults_SleepHediff, 1.0f); } public override void TickRare() { base.TickRare(); if (CurState != State.Asleep) { var potentialVictim = PotentialVictims()?.RandomElement(); if (potentialVictim != null) { TryToSendToSleep(potentialVictim); } } if (!ActiveVictims.NullOrEmpty() && ticksToReset < Find.TickManager.TicksGame) { ActiveVictims = new List<Pawn>(); } } public override string GetInspectString() { var s = new StringBuilder(); var sBase = base.GetInspectString(); if (sBase != "") { s.Append(s); } switch (CurState) { case State.Asleep: s.AppendLine("Cults_SleepTotem_StateAsleep".Translate()); break; case State.Drowsy: s.AppendLine("Cults_SleepTotem_StateDrowsy".Translate()); break; case State.Awake: s.AppendLine("Cults_SleepTotem_StateAwake".Translate()); break; } if (TicksToReset == -1 || TicksToReset <= Find.TickManager.TicksGame) { return s.ToString().TrimEndNewlines(); } var ticksUntilRecovery = TicksToReset - Find.TickManager.TicksGame; s.AppendLine("Cults_SleepTotem_FullyAwakensIn".Translate(ticksUntilRecovery.ToStringTicksToPeriod())); return s.ToString().TrimEndNewlines(); } public IEnumerable<Pawn> PotentialVictims() { if (SleepableCells.NullOrEmpty()) { yield break; } foreach (var cell in SleepableCells) { var victim = cell.GetFirstPawn(MapHeld); if (victim != null && CanSendToSleep(victim)) { yield return victim; } } } public bool CanSendToSleep(Pawn victim) { return CurState != State.Asleep && !ActiveVictims.Contains(victim) && !victim.Dead && victim.Spawned && victim.Faction != null && victim.Faction.HostileTo(Faction) && !victim.RaceProps.IsMechanoid && victim.needs?.rest != null && !victim.health.hediffSet.HasHediff(CultsDefOf.Cults_SleepHediff); } public Graphic GraphicConstructor(string newTexPath) { var tempData = new GraphicData(); tempData.CopyFrom(def.graphicData); tempData.texPath = newTexPath; var result = tempData.GraphicColoredFor(this); return result; } public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref ticksToReset, "ticksToReset", -1); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Reanimation/ReanimatedPawn.cs using RimWorld; using UnityEngine; using Verse; using Verse.AI; namespace CultOfCthulhu { /// <summary> /// Originally ZombePawn from JustinC /// </summary> public class ReanimatedPawn : Pawn { public bool isRaiding = true; public float notRaidingAttackRange = 15f; public bool setZombie; public bool wasColonist; public ReanimatedPawn() { Init(); } private void Init() { pather = new Pawn_PathFollower(this); stances = new Pawn_StanceTracker(this); health = new Pawn_HealthTracker(this); jobs = new Pawn_JobTracker(this); filth = new Pawn_FilthTracker(this); } public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref wasColonist, "wasColonist"); //if (Scribe.mode == LoadSaveMode.LoadingVars) //{ // Cthulhu.Utility.GiveZombieSkinEffect(this); //} } public override void PreApplyDamage(ref DamageInfo dinfo, out bool absorbed) { health.PreApplyDamage(dinfo, out absorbed); if (Destroyed || dinfo.Def != DamageDefOf.Cut && dinfo.Def != DamageDefOf.Stab) { return; } var num = 0f; var num2 = 0f; if (dinfo.Instigator is not Pawn) { return; } var pawn = dinfo.Instigator as Pawn; if (pawn?.skills != null) { var expr_9B = pawn.skills.GetSkill(SkillDefOf.Melee); num = expr_9B.Level * 2; num2 = expr_9B.Level / 20f * 3f; } if (Random.Range(0f, 100f) < 20f + num) { dinfo.SetAmount(999); dinfo.SetHitPart(health.hediffSet.GetBrain()); dinfo.Def.Worker.Apply(dinfo, this); return; } dinfo.SetAmount((int) (dinfo.Amount * (1f + num2))); } public override void Tick() { try { if (DebugSettings.noAnimals && RaceProps.Animal) { Destroy(); } else if (!Downed) { if (Find.TickManager.TicksGame % 250 == 0) { TickRare(); } if (Spawned) { pather.PatherTick(); } Drawer.DrawTrackerTick(); health.HealthTick(); records.RecordsTick(); if (Spawned) { stances.StanceTrackerTick(); } if (Spawned) { verbTracker.VerbsTick(); } if (Spawned) { natives.NativeVerbsTick(); } equipment?.EquipmentTrackerTick(); apparel?.ApparelTrackerTick(); if (Spawned) { jobs.JobTrackerTick(); } if (!Dead) { carryTracker.CarryHandsTick(); } skills?.SkillsTick(); inventory?.InventoryTrackerTick(); } if (needs?.food != null && needs.food.CurLevel <= 0.95f) { needs.food.CurLevel = 1f; } if (needs?.joy != null && needs.joy.CurLevel <= 0.95f) { needs.joy.CurLevel = 1f; } if (needs?.beauty != null && needs.beauty.CurLevel <= 0.95f) { needs.beauty.CurLevel = 1f; } if (needs?.comfort != null && needs.comfort.CurLevel <= 0.95f) { needs.comfort.CurLevel = 1f; } if (needs?.rest != null && needs.rest.CurLevel <= 0.95f) { needs.rest.CurLevel = 1f; } if (needs?.mood != null && needs.mood.CurLevel <= 0.45f) { needs.mood.CurLevel = 0.5f; } if (!setZombie) { mindState.mentalStateHandler.neverFleeIndividual = true; setZombie = ReanimatedPawnUtility.Zombify(this); //ZombieMod_Utility.SetZombieName(this); } if (!Downed && !health.Downed && !health.InPainShock) { return; } var damageInfo = new DamageInfo(DamageDefOf.Blunt, 9999, 1f, -1f, this); damageInfo.SetHitPart(health.hediffSet.GetBrain()); //damageInfo.SetPart(new BodyPartDamageInfo(this.health.hediffSet.GetBrain(), false, HediffDefOf.Cut)); TakeDamage(damageInfo); } catch { // ignored } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Sacrifice/Building_SacrificialAltar.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Cthulhu; using RimWorld; using RimWorld.Planet; using UnityEngine; using Verse; using Verse.AI; //using System.Diagnostics; //using System.Linq; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI //using Verse.AI.Group; //using Verse.Sound; // Needed when you do something with Sound //using Verse.Noise; // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') //using RimWorld.Planet; // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public partial class Building_SacrificialAltar : Building, IBillGiver { public enum Function { Level1 = 0, Level2 = 1, Level3 = 2, Nightmare = 3 } //Offering Related Variables public enum OfferingState { off = 0, started, offering, finished } //Sacrifice Related Variables public enum SacrificeState { off = 0, started, gathering, sacrificing, finishing, finished } //Universal Variables public enum State { notinuse = 0, sacrificing, worshipping, offering } //Worship Related Variables public enum WorshipState { off = 0, started, gathering, worshipping, finishing, finished } public static int morningStart = 0; public static int eveningStart = 12; private HashSet<Pawn> availableWorshippers; private RecipeDef billRecipe; public Function currentFunction = Function.Level1; public CosmicEntity currentOfferingDeity; public OfferingState currentOfferingState = OfferingState.off; public SacrificeState currentSacrificeState = SacrificeState.off; private State currentState = State.notinuse; public CosmicEntity currentWorshipDeity; public WorshipState currentWorshipState = WorshipState.off; public bool debugAlwaysSucceed; private bool destroyedFlag; // For safety public List<ThingCount> determinedOfferings = new List<ThingCount>(); private bool didEveningRitual; private bool didMorningRitual; public int eveningHour = 18; //Misc Event Variables private Function lastFunction = Function.Level1; private string lastReport = ""; public int morningHour = 9; private Pawn offerer; public bool OptionEvening; public bool OptionMorning; public Pawn preacher; public string RoomName = "Unnamed Temple"; private Bill_Sacrifice sacrificeData; public List<int> seasonSchedule = new List<int>(new int[15]); public CosmicEntity tempCurrentOfferingDeity; public CosmicEntity tempCurrentSacrificeDeity; public IncidentDef tempCurrentSpell; public CosmicEntity tempCurrentWorshipDeity; private List<ThingCount> tempDeterminedOfferings = new List<ThingCount>(); public Pawn tempExecutioner; public Pawn tempOfferer; public CultUtility.OfferingSize tempOfferingSize = CultUtility.OfferingSize.none; public CultUtility.SacrificeType tempOfferingType = CultUtility.SacrificeType.none; public Pawn tempPreacher; public Pawn tempSacrifice; public bool toBePrunedAndRepaired; public Building_SacrificialAltar() { BillStack = new BillStack(this); } public IEnumerable<IntVec3> CellsAround => GenRadial.RadialCellsAround(Position, 5, true); public Bill_Sacrifice SacrificeData => sacrificeData; public string LastReport { get => lastReport; set => lastReport = value; } private bool DoMorningSermon => OptionMorning && Utility.IsMorning(Map) && didMorningRitual == false; private bool DoEveningSermon => OptionEvening && Utility.IsEvening(Map) && didEveningRitual == false; private bool DoSermonNow { get { var typeOfSermons = seasonSchedule[GenLocalDate.DayOfQuadrum(Map)]; if (typeOfSermons == 0) { return false; } var currentHour = GenLocalDate.HourInteger(Map); if (didMorningRitual && currentHour >= eveningStart) { didMorningRitual = false; } if (didEveningRitual && currentHour < eveningStart) { didEveningRitual = false; } if (!didMorningRitual && (typeOfSermons == 1 || typeOfSermons == 3) && currentHour == morningHour) { didMorningRitual = true; return true; } if (didEveningRitual || typeOfSermons != 2 && typeOfSermons != 3 || currentHour != eveningHour) { return false; } didEveningRitual = true; return true; } } // RimWorld.Building_Bed public static int LyingSlotsCount { get; } = 1; // RimWorld.Building_Bed public bool AnyUnoccupiedLyingSlot { get { for (var i = 0; i < LyingSlotsCount; i++) { if (GetCurOccupant() == null) { return true; } } return false; } } public HashSet<Pawn> AvailableWorshippers { get { if (availableWorshippers == null || availableWorshippers.Count == 0) { availableWorshippers = new HashSet<Pawn>(Map.mapPawns.AllPawnsSpawned.FindAll(y => y is Pawn x && x.RaceProps.Humanlike && !x.IsPrisoner && x.Faction == Faction && x.RaceProps.intelligence == Intelligence.Humanlike && !x.Downed && !x.Dead && !x.InMentalState && !x.InAggroMentalState && x.CurJob.def != CultsDefOf.Cults_MidnightInquisition && x.CurJob.def != CultsDefOf.Cults_AttendSacrifice && x.CurJob.def != CultsDefOf.Cults_ReflectOnWorship && x.CurJob.def != CultsDefOf.Cults_AttendWorship && x.CurJob.def != JobDefOf.Capture && x.CurJob.def != JobDefOf.ExtinguishSelf && //Oh god help x.CurJob.def != JobDefOf.Rescue && //Saving lives is more important x.CurJob.def != JobDefOf.TendPatient && //Saving lives is more important x.CurJob.def != JobDefOf.BeatFire && //Fire?! This is more important x.CurJob.def != JobDefOf.Lovin && //Not ready~~ x.CurJob.def != JobDefOf.LayDown && //They're resting x.CurJob.def != JobDefOf.FleeAndCower //They're not cowering ).ChangeType<List<Pawn>>()); } return availableWorshippers; } } public bool CurrentlyUsableForBills() { return true; } public BillStack BillStack { get; } public IEnumerable<IntVec3> IngredientStackCells => GenAdj.CellsOccupiedBy(this); public override string GetInspectString() { var stringBuilder = new StringBuilder(); // Add the inspections string from the base stringBuilder.Append(base.GetInspectString()); // return the complete string return stringBuilder.ToString(); } private bool IsCongregating() { return IsOffering() || IsSacrificing() || IsWorshipping(); } private bool IsOffering() { return currentState == State.offering || currentOfferingState != OfferingState.finished && currentOfferingState != OfferingState.off; } private bool IsSacrificing() { return currentState == State.sacrificing || currentSacrificeState != SacrificeState.finished && currentSacrificeState != SacrificeState.off; } private bool IsWorshipping() { return currentState == State.worshipping || currentWorshipState != WorshipState.finished && currentWorshipState != WorshipState.off; } private bool CanUpgrade() { switch (currentFunction) { case Function.Level1: if (ResearchProjectDef.Named("Forbidden_Sacrifice").IsFinished) { return true; } return false; case Function.Level2: if (ResearchProjectDef.Named("Forbidden_Human").IsFinished) { return true; } return false; case Function.Level3: return false; case Function.Nightmare: break; default: throw new ArgumentOutOfRangeException(); } return false; } private static bool RejectMessage(string s, Pawn pawn = null) { Messages.Message(s, TargetInfo.Invalid, MessageTypeDefOf.RejectInput); pawn = null; return false; } public void ChangeState(State type) { if (type == State.notinuse) { currentState = type; currentWorshipState = WorshipState.off; currentSacrificeState = SacrificeState.off; currentOfferingState = OfferingState.off; availableWorshippers = null; } else { Log.Error("Changed default state of Sacrificial Altar this should never happen."); } ReportState(); } public void ChangeState(State type, WorshipState worshipState) { currentState = type; currentWorshipState = worshipState; ReportState(); } public void ChangeState(State type, SacrificeState sacrificeState) { currentState = type; currentSacrificeState = sacrificeState; ReportState(); } public void ChangeState(State type, OfferingState offeringState) { currentState = type; currentOfferingState = offeringState; ReportState(); } private void ReportState() { var s = new StringBuilder(); s.Append("==================="); s.AppendLine("Sacrifical Altar States Changed"); s.AppendLine("==================="); s.AppendLine("State: " + currentState); s.AppendLine("Worship: " + currentWorshipState); s.AppendLine("Offering: " + currentOfferingState); s.AppendLine("Sacrifice: " + currentSacrificeState); s.AppendLine("==================="); Utility.DebugReport(s.ToString()); } private Pawn GetCurOccupant() { var sleepingSlotPos = GetLyingSlotPos(); var list = Map.thingGrid.ThingsListAt(sleepingSlotPos); if (list.NullOrEmpty()) { return null; } foreach (var t in list) { if (!(t is Pawn pawn)) { continue; } if (pawn.CurJob == null) { continue; } if (pawn.jobs.posture != PawnPosture.Standing) { return pawn; } } return null; } // RimWorld.Building_Bed public IntVec3 GetLyingSlotPos() { var index = 1; var cellRect = this.OccupiedRect(); if (Rotation == Rot4.North) { return new IntVec3(cellRect.minX + index, Position.y, cellRect.minZ); } return Rotation == Rot4.East ? new IntVec3(cellRect.minX, Position.y, cellRect.maxZ - index) : Rotation == Rot4.South ? new IntVec3(cellRect.minX + index, Position.y, cellRect.maxZ) : new IntVec3(cellRect.maxX, Position.y, cellRect.maxZ - index); } public override void SpawnSetup(Map map, bool bla) { base.SpawnSetup(map, bla); CultTracker.Get.ExposedToCults = true; if (RoomName == null) { RoomName = "Unnamed Temple"; } if (seasonSchedule == null) { var settingToMigrate = 0; if (OptionMorning && OptionEvening) { settingToMigrate = 3; } else { if (OptionMorning) { settingToMigrate = 1; } if (OptionEvening) { settingToMigrate = 2; } } seasonSchedule = new List<int>(new[] { settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate, settingToMigrate }); morningHour = 9; eveningHour = 18; } if (eveningHour == 0) { eveningHour = 18; } DeityTracker.Get.orGenerate(); switch (def.defName) { case "Cult_AnimalSacrificeAltar": currentFunction = Function.Level2; break; case "Cult_HumanSacrificeAltar": currentFunction = Function.Level3; break; case "Cult_NightmareSacrificeAltar": currentFunction = Function.Nightmare; break; } //UpdateGraphics(); } public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref RoomName, "RoomName"); Scribe_Deep.Look(ref sacrificeData, "sacrificeData"); Scribe_References.Look(ref tempCurrentSacrificeDeity, "tempCurrentSacrificeDeity"); Scribe_References.Look(ref tempSacrifice, "tempSacrifice"); Scribe_References.Look(ref tempExecutioner, "tempExecutioner"); Scribe_Defs.Look(ref tempCurrentSpell, "tempCurrentSpell"); Scribe_Values.Look(ref currentState, "currentState"); Scribe_Values.Look(ref currentSacrificeState, "currentSacrificeState"); Scribe_Values.Look(ref lastFunction, "lastFunction"); Scribe_Values.Look(ref currentFunction, "currentFunction"); // Worship values Scribe_References.Look(ref currentWorshipDeity, "currentWorshipDeity"); Scribe_References.Look(ref tempCurrentWorshipDeity, "tempCurrentWorshipDeity"); Scribe_References.Look(ref preacher, "preacher"); Scribe_References.Look(ref tempPreacher, "tempPreacher"); Scribe_Values.Look(ref currentWorshipState, "currentWorshipState"); Scribe_Values.Look(ref OptionMorning, "OptionMorning"); Scribe_Values.Look(ref OptionEvening, "OptionEvening"); Scribe_Values.Look(ref didMorningRitual, "didMorningRitual"); Scribe_Values.Look(ref didEveningRitual, "didEveningRitual"); Scribe_Values.Look(ref morningHour, "morningHour", 9); Scribe_Values.Look(ref eveningHour, "eveningHour", 18); Scribe_Collections.Look(ref seasonSchedule, "seasonSchedule", LookMode.Value, false); //Misc Scribe_Values.Look(ref toBePrunedAndRepaired, "tobePrunedAndRepaired"); Scribe_Values.Look(ref lastReport, "lastReport"); } public override void Destroy(DestroyMode mode = DestroyMode.Vanish) { // block further ticker work destroyedFlag = true; ITab_AltarSacrificesCardUtility.Tab = ITab_AltarSacrificesCardUtility.SacrificeCardTab.Offering; base.Destroy(mode); } public override void TickRare() { if (destroyedFlag) // Do nothing further, when destroyed (just a safety) { return; } if (!Spawned) { return; } // Don't forget the base work base.TickRare(); AutoWorshipRareTick(); WorshipRareTick(); OfferingRareTick(); if (currentFunction > Function.Level1) { SacrificeRareTick(); } } public override void Tick() { if (destroyedFlag) // Do nothing further, when destroyed (just a safety) { return; } if (!Spawned) { return; } // Don't forget the base work base.Tick(); WorshipTick(); if (currentFunction > Function.Level1) { SacrificeTick(); } } public void AutoWorshipRareTick() { if (DoSermonNow) { TryTimedWorship(); } // Old code, for only morning/evening options ////In the morning, let's gather to worship //if (DoMorningSermon && !IsWorshipping() && !IsSacrificing()) //{ // didMorningRitual = true; // TryTimedWorship(); //} ////In the evening, let's gather to worship //if (DoEveningSermon && !IsWorshipping() && !IsSacrificing()) //{ // didEveningRitual = true; // TryTimedWorship(); //} //Reset values //if (Cthulhu.Utility.IsEvening(Map) || Cthulhu.Utility.IsMorning(Map)) //{ // return; //} //didEveningRitual = false; //didMorningRitual = false; } public void SacrificeRareTick() { if (!Spawned) { return; } if (SacrificeData?.Executioner == null) { return; } if (currentState != State.sacrificing) { return; } switch (currentSacrificeState) { case SacrificeState.started: case SacrificeState.gathering: case SacrificeState.sacrificing: if (!Utility.IsActorAvailable(SacrificeData.Executioner)) { CultUtility.AbortCongregation(this, "Executioner".Translate() + "IsUnavailable".Translate()); return; } else if (!Utility.IsActorAvailable(SacrificeData.Sacrifice, true)) { CultUtility.AbortCongregation(this, "Sacrifice".Translate() + "IsUnavailable".Translate()); return; } else { if (SacrificeData.Executioner?.CurJob != null && SacrificeData.Executioner.CurJob.def != CultsDefOf.Cults_HoldSacrifice) { CultUtility.AbortCongregation(this, "Executioner".Translate() + "IsUnavailable".Translate()); return; } } if (availableWorshippers == null) { GetSacrificeGroup(); } return; case SacrificeState.finishing: if (!Utility.IsActorAvailable(SacrificeData.Executioner)) { CultUtility.AbortCongregation(this, "Executioner".Translate() + "IsUnavailable".Translate()); return; } if (SacrificeData.Executioner?.CurJob != null && SacrificeData.Executioner.CurJob.def != CultsDefOf.Cults_ReflectOnResult) { return; } GetSacrificeGroup(); return; case SacrificeState.finished: case SacrificeState.off: ChangeState(State.notinuse); return; } } public void OfferingRareTick() { if (currentState != State.offering) { return; } switch (currentOfferingState) { case OfferingState.started: if (!Utility.IsActorAvailable(offerer)) { CultUtility.AbortCongregation(this, "Offerer".Translate() + "IsUnavailable".Translate()); return; } else if (offerer.CurJob.def != CultsDefOf.Cults_GiveOffering) { Utility.DebugReport(offerer.CurJob.def.defName); CultUtility.AbortCongregation(this, "Offerer is not performing the task at hand."); return; } return; case OfferingState.offering: if (!Utility.IsActorAvailable(offerer)) { CultUtility.AbortCongregation(this, "Offerer".Translate() + "IsUnavailable".Translate()); return; } else if (offerer.CurJob.def != CultsDefOf.Cults_GiveOffering) { Utility.DebugReport(offerer.CurJob.def.defName); CultUtility.AbortCongregation(this, "Offerer is not performing the task at hand."); return; } return; case OfferingState.finished: case OfferingState.off: ChangeState(State.notinuse); return; } } public void WorshipRareTick() { if (currentState != State.worshipping) { return; } switch (currentWorshipState) { case WorshipState.started: case WorshipState.gathering: case WorshipState.worshipping: if (!Utility.IsActorAvailable(preacher)) { CultUtility.AbortCongregation(this, "Preacher".Translate() + "IsUnavailable".Translate()); return; } if (preacher.CurJob.def != CultsDefOf.Cults_HoldWorship) { CultUtility.AbortCongregation(this, "Preacher".Translate() + "IsUnavailable".Translate()); return; } if (availableWorshippers != null) { return; } GetWorshipGroup(this, GenRadial.RadialCellsAround(Position, GenRadial.MaxRadialPatternRadius - 1, true)); Utility.DebugReport("Gathering yay"); return; case WorshipState.finishing: if (!Utility.IsActorAvailable(preacher)) { CultUtility.AbortCongregation(this, "Preacher".Translate() + "IsUnavailable".Translate()); return; } if (preacher.CurJob.def != CultsDefOf.Cults_ReflectOnWorship) { return; } GetWorshipGroup(this, GenRadial.RadialCellsAround(Position, GenRadial.MaxRadialPatternRadius - 1, true)); Utility.DebugReport("Finishing yay"); return; case WorshipState.finished: case WorshipState.off: ChangeState(State.notinuse); return; } } public void SacrificeTick() { if (currentState != State.sacrificing) { return; } switch (currentSacrificeState) { case SacrificeState.started: case SacrificeState.gathering: case SacrificeState.sacrificing: if (Utility.IsActorAvailable(SacrificeData.Executioner)) { if (Utility.IsActorAvailable(SacrificeData.Sacrifice, true)) { if (SacrificeData.Executioner.CurJob.def != CultsDefOf.Cults_HoldSacrifice) { CultUtility.AbortCongregation(this, "Executioner".Translate() + "IsUnavailable".Translate()); } return; } CultUtility.AbortCongregation(this, "Sacrifice".Translate() + "IsUnavailable".Translate()); return; } CultUtility.AbortCongregation(this, "Executioner".Translate() + "IsUnavailable".Translate()); return; case SacrificeState.finishing: if (!Utility.IsActorAvailable(SacrificeData.Executioner)) { CultUtility.AbortCongregation(this, "Executioner".Translate() + "IsUnavailable".Translate()); } if (MapComponent_SacrificeTracker.Get(Map).lastSacrificeType == CultUtility.SacrificeType.animal) { ChangeState(State.sacrificing, SacrificeState.finished); } return; case SacrificeState.finished: case SacrificeState.off: ChangeState(State.notinuse); return; } } public void WorshipTick() { if (currentState != State.worshipping) { return; } switch (currentWorshipState) { case WorshipState.started: case WorshipState.gathering: if (Utility.IsActorAvailable(preacher)) { if (preacher.CurJob.def != CultsDefOf.Cults_HoldWorship) { CultUtility.AbortCongregation(this, "Preacher".Translate() + "IsUnavailable".Translate()); return; } } Utility.DebugReport("Gathering yay"); return; case WorshipState.finishing: if (!Utility.IsActorAvailable(preacher)) { CultUtility.AbortCongregation(this, "Preacher".Translate() + "IsUnavailable".Translate()); } Utility.DebugReport("Finishing yay"); return; case WorshipState.finished: case WorshipState.off: currentState = State.notinuse; return; } } public override IEnumerable<Gizmo> GetGizmos() { foreach (var g in base.GetGizmos()) { yield return g; } if (currentFunction < Function.Level3) { var command_Upgrade = new Command_Action { action = TryUpgrade, defaultLabel = "CommandUpgrade".Translate(), defaultDesc = "CommandUpgrade".Translate(), disabled = !CanUpgrade() || currentFunction == Function.Nightmare, disabledReason = "CommandCultDisabled".Translate(), hotKey = KeyBindingDefOf.Misc1, icon = ContentFinder<Texture2D>.Get("UI/Commands/Worship") }; if (CanUpgrade()) { if (currentFunction == Function.Level1) { command_Upgrade.icon = ContentFinder<Texture2D>.Get("UI/Commands/Upgrade2"); } else if (currentFunction == Function.Level2) { command_Upgrade.icon = ContentFinder<Texture2D>.Get("UI/Commands/Upgrade3"); } } else { if (currentFunction == Function.Level1) { command_Upgrade.icon = ContentFinder<Texture2D>.Get("UI/Commands/Upgrade2Disabled"); } else if (currentFunction == Function.Level2) { command_Upgrade.icon = ContentFinder<Texture2D>.Get("UI/Commands/Upgrade3Disabled"); } } yield return command_Upgrade; } if (!IsSacrificing()) { var command_Action = new Command_Action { action = TrySacrifice, defaultLabel = "CommandCultSacrifice".Translate(), defaultDesc = "CommandCultSacrificeDesc".Translate(), disabled = currentFunction < Function.Level2 || currentFunction == Function.Nightmare, disabledReason = "CommandCultDisabled".Translate(), hotKey = KeyBindingDefOf.Misc1, icon = ContentFinder<Texture2D>.Get("UI/Commands/Sacrifice") }; if (currentFunction < Function.Level2) { command_Action.icon = ContentFinder<Texture2D>.Get("UI/Commands/SacrificeDisabled"); } yield return command_Action; } else { var command_Cancel = new Command_Action { action = CancelSacrifice, defaultLabel = "CommandCancelConstructionLabel".Translate(), defaultDesc = "CommandCancelSacrifice".Translate(), disabled = currentFunction < Function.Level2, hotKey = KeyBindingDefOf.Designator_Cancel, icon = ContentFinder<Texture2D>.Get("UI/Designators/Cancel") }; yield return command_Cancel; } if (!IsWorshipping()) { var command_Action = new Command_Action { action = TryWorshipForced, defaultLabel = "CommandForceWorship".Translate(), defaultDesc = "CommandForceWorshipDesc".Translate(), disabled = currentFunction == Function.Nightmare, hotKey = KeyBindingDefOf.Misc2, icon = ContentFinder<Texture2D>.Get("UI/Commands/Worship") }; yield return command_Action; } else { var command_Cancel = new Command_Action { action = CancelWorship, defaultLabel = "CommandCancelConstructionLabel".Translate(), defaultDesc = "CommandCancelWorship".Translate(), hotKey = KeyBindingDefOf.Designator_Cancel, icon = ContentFinder<Texture2D>.Get("UI/Designators/Cancel") }; yield return command_Cancel; } if (!IsOffering()) { var command_Action = new Command_Action { action = TryOffering, defaultLabel = "CommandOffering".Translate(), defaultDesc = "CommandOfferingDesc".Translate(), disabled = currentFunction == Function.Nightmare, hotKey = KeyBindingDefOf.Misc3, icon = ContentFinder<Texture2D>.Get("UI/Commands/MakeOffering") }; yield return command_Action; } else { var command_Cancel = new Command_Action { action = CancelOffering, defaultLabel = "CommandCancelConstructionLabel".Translate(), defaultDesc = "CommandCancelOffering".Translate(), hotKey = KeyBindingDefOf.Designator_Cancel, icon = ContentFinder<Texture2D>.Get("UI/Designators/Cancel") }; yield return command_Cancel; } if (CultsDefOf.Forbidden_Reports.IsFinished) { yield return new Command_Action { action = GiveReport, defaultLabel = "CommandCultReport".Translate(), defaultDesc = "CommandCultReportDesc".Translate(), disabled = LastReport == "", disabledReason = "CommandCultReportDisabled".Translate(), hotKey = KeyBindingDefOf.Misc4, icon = ContentFinder<Texture2D>.Get("UI/Commands/CultReport") }; } if (currentFunction == Function.Nightmare) { yield return new Command_Toggle { hotKey = KeyBindingDefOf.Command_TogglePower, icon = ContentFinder<Texture2D>.Get("UI/Icons/Commands/PruneAndRepair"), defaultLabel = "PruneAndRepair".Translate(), defaultDesc = "PruneAndRepairDesc".Translate(), isActive = () => toBePrunedAndRepaired, toggleAction = PruneAndRepairToggle }; } if (!DebugSettings.godMode) { yield break; } yield return new Command_Action { defaultLabel = "Debug: Discover All Deities", action = delegate { foreach (var entity in DeityTracker.Get.DeityCache.Keys) { entity.discovered = true; } } }; yield return new Command_Action { defaultLabel = "Debug: All Favor to 0", action = delegate { foreach (var entity in DeityTracker.Get.DeityCache.Keys) { entity.ResetFavor(); } } }; yield return new Command_Action { defaultLabel = "Debug: Make All Colonists Cult-Minded", action = delegate { foreach (var p in Map.mapPawns.FreeColonistsSpawned) { CultUtility.AffectCultMindedness(p, 0.99f); } } }; yield return new Command_Action { defaultLabel = "Debug: Upgrade Max Level Altar", action = delegate { currentFunction = Function.Level3; } }; yield return new Command_Action { defaultLabel = "Debug: Unlock All Spells", action = delegate { foreach (var entity in DeityTracker.Get.DeityCache.Keys) { entity.AffectFavor(9999999); } } }; yield return new Command_Toggle { defaultLabel = "Debug: Always Succeed", isActive = () => debugAlwaysSucceed, toggleAction = delegate { debugAlwaysSucceed = !debugAlwaysSucceed; } }; yield return new Command_Action { defaultLabel = "Debug: Force Side Effect", action = delegate { var table = new CultTableOfFun(); var list = (from spell in table.TableOfFun let currentDef = IncidentDef.Named(spell.defName) select new FloatMenuOption(currentDef.LabelCap, delegate { var temp = DefDatabase<IncidentDef>.GetNamed(spell.defName); if (temp != null) { CultUtility.CastSpell(temp, Map); } })).ToList(); Find.WindowStack.Add(new FloatMenu(list)); } }; if (currentFunction != Function.Nightmare) { yield return new Command_Action { defaultLabel = "Debug: Force Nightmare Tree", action = NightmareEvent }; } } private void GiveReport() { Find.WindowStack.Add(new Dialog_MessageBox(LastReport)); } public void PruneAndRepairToggle() { toBePrunedAndRepaired = !toBePrunedAndRepaired; } private void TryUpgrade() { if (IsCongregating()) { Messages.Message("UpgradeCongregationWarning".Translate(), MessageTypeDefOf.RejectInput); return; } Upgrade(); } public void Upgrade() { var newDefName = ""; switch (currentFunction) { case Function.Level1: newDefName = "Cult_AnimalSacrificeAltar"; break; case Function.Level2: newDefName = "Cult_HumanSacrificeAltar"; break; case Function.Level3: Log.Error("Tried to upgrade fully functional altar. This should never happen."); return; } if (newDefName == "") { return; } ReplaceAltarWith(newDefName); } public void NightmareEvent() { lastFunction = currentFunction; currentFunction = Function.Nightmare; ReplaceAltarWith("Cult_NightmareSacrificeAltar"); } public void NightmarePruned(Pawn pruner) { var oldDefName = ""; switch (lastFunction) { case Function.Level1: oldDefName = "Cult_SacrificialAltar"; break; case Function.Level2: oldDefName = "Cult_AnimalSacrificeAltar"; break; case Function.Level3: oldDefName = "Cult_HumanSacrificeAltar"; break; } if (oldDefName == "") { return; } var newAltar = ReplaceAltarWith(oldDefName); Messages.Message("PruningSuccessful".Translate( pruner.LabelShort ), MessageTypeDefOf.PositiveEvent); newAltar.Map.reservationManager.ReleaseAllForTarget(newAltar); } private Building_SacrificialAltar ReplaceAltarWith(string newDefName) { if (newDefName == "") { Utility.ErrorReport("ReplaceAltarWith :: Null exception."); return null; } //Copy the important values. var currentLocation = Position; var currentRotation = Rotation; var currentStuff = Stuff; var compQuality = this.TryGetComp<CompQuality>(); var currentLastFunction = lastFunction; var currentMap = Map; var qualityCat = QualityCategory.Normal; if (compQuality != null) { qualityCat = compQuality.Quality; } //Worship values var s1 = RoomName; var p1 = tempPreacher; var c1 = tempCurrentWorshipDeity; var b1 = OptionMorning; var b2 = OptionEvening; Destroy(); //Spawn the new altar over the other var thing = (Building_SacrificialAltar) ThingMaker.MakeThing(ThingDef.Named(newDefName), currentStuff); var result = thing; thing.SetFaction(Faction.OfPlayer); thing.Rotation = currentRotation; GenPlace.TryPlaceThing(thing, currentLocation, currentMap, ThingPlaceMode.Direct); thing.Rotation = currentRotation; thing.TryGetComp<CompQuality>().SetQuality(qualityCat, ArtGenerationContext.Colony); thing.lastFunction = currentLastFunction; if (currentFunction != Function.Nightmare) { Messages.Message("UpgradeSuccessful".Translate(), new TargetInfo(currentLocation, Map), MessageTypeDefOf.PositiveEvent); } else { Messages.Message("CorruptedAltarWarning".Translate(), MessageTypeDefOf.NegativeEvent); } //Pass worship values thing.RoomName = s1; thing.tempPreacher = p1; thing.tempCurrentWorshipDeity = c1; thing.OptionMorning = b1; thing.OptionEvening = b2; return result; } private void CancelOffering() { var listeners = Map.mapPawns.AllPawnsSpawned.FindAll(x => x.RaceProps.intelligence == Intelligence.Humanlike); var unused = new bool[listeners.Count]; foreach (var pawn in listeners) { if (pawn.Faction != Faction.OfPlayer) { continue; } //Hold Offering if (pawn.CurJob.def == CultsDefOf.Cults_GiveOffering) { pawn.jobs.StopAll(); } } ChangeState(State.notinuse); //this.currentState = State.off; Messages.Message("Cancelling offering.", MessageTypeDefOf.NegativeEvent); } private void TryOffering() { if (IsCongregating()) { Messages.Message("A congregation is already gathering.", MessageTypeDefOf.RejectInput); return; } if (!CanGatherOfferingNow()) { return; } if (!TryDetermineOffering(tempOfferingType, tempOfferingSize, tempOfferer, this, out tempDeterminedOfferings, out billRecipe)) { Utility.DebugReport("Failed to determine offering"); return; } switch (currentOfferingState) { case OfferingState.finished: case OfferingState.off: if (IsWorshipping()) { CancelWorship(); } if (IsSacrificing()) { CancelSacrifice(); } StartOffering(); return; case OfferingState.started: case OfferingState.offering: Messages.Message("An offering is already happening.", TargetInfo.Invalid, MessageTypeDefOf.RejectInput); return; } } private bool CanGatherOfferingNow() { if (tempOfferingType == CultUtility.SacrificeType.none) { return RejectMessage("No offering type selected"); } if (tempOfferingSize == CultUtility.OfferingSize.none) { return RejectMessage("No offering amount selected"); } if (tempOfferer == null) { return RejectMessage("No offerer selected"); } if (tempOfferer.Drafted) { return RejectMessage("Offerer is drafted."); } if (tempOfferer.Dead || tempOfferer.Downed) { return RejectMessage("Select an able-bodied offerer.", tempOfferer); } if (tempCurrentOfferingDeity == null) { return RejectMessage( "No cosmic entity selected. Entities can be discovered at the forbidden knowledge center."); } return !tempOfferer.CanReserve(this) ? RejectMessage("The altar is reserved by something else.") : !Position.GetThingList(Map).OfType<Corpse>().Any() || RejectMessage("The altar needs to be cleared first."); } public void StartOffering() { determinedOfferings = tempDeterminedOfferings; offerer = tempOfferer; currentOfferingDeity = tempCurrentOfferingDeity; if (Destroyed || !Spawned) { CultUtility.AbortCongregation(null, "Altar".Translate() + "IsUnavailable".Translate()); return; } if (!Utility.IsActorAvailable(offerer)) { CultUtility.AbortCongregation(this, "Offerer".Translate() + " " + offerer.LabelShort + "IsUnavailable".Translate()); offerer = null; return; } Messages.Message("An offering is being gathered.", TargetInfo.Invalid, MessageTypeDefOf.NeutralEvent); ChangeState(State.offering, OfferingState.started); Utility.DebugReport("Make offering called."); var job2 = new Job(CultsDefOf.Cults_GiveOffering) { playerForced = true, targetA = this, targetQueueB = new List<LocalTargetInfo>(determinedOfferings.Count), targetC = PositionHeld, countQueue = new List<int>(determinedOfferings.Count) }; foreach (var thingCount in determinedOfferings) { job2.targetQueueB.Add(thingCount.Thing); job2.countQueue.Add(thingCount.Count); } job2.haulMode = HaulMode.ToCellNonStorage; job2.locomotionUrgency = LocomotionUrgency.Sprint; job2.bill = new Bill_Production(billRecipe); offerer.jobs.TryTakeOrderedJob(job2); } private void CancelSacrifice() { var listeners = Map.mapPawns.AllPawnsSpawned.FindAll(x => x.RaceProps.intelligence == Intelligence.Humanlike); if (!listeners.NullOrEmpty()) { foreach (var t in listeners) { var pawn = t; if (pawn.Faction != Faction.OfPlayer) { continue; } if (pawn.CurJob.def == CultsDefOf.Cults_HoldSacrifice || pawn.CurJob.def == CultsDefOf.Cults_AttendSacrifice || pawn.CurJob.def == CultsDefOf.Cults_ReflectOnResult || pawn.CurJob.def == CultsDefOf.Cults_GiveOffering) { pawn.jobs.StopAll(); } } } ChangeState(State.notinuse); Messages.Message("Cancelling sacrifice.", MessageTypeDefOf.NegativeEvent); } private void TrySacrifice() { if (IsSacrificing()) { Messages.Message("A sacrifice is already gathering.", MessageTypeDefOf.RejectInput); return; } if (!CanGatherSacrificeNow()) { return; } switch (currentSacrificeState) { case SacrificeState.finished: case SacrificeState.off: if (IsWorshipping()) { CancelWorship(); } StartSacrifice(); return; case SacrificeState.started: case SacrificeState.gathering: case SacrificeState.sacrificing: case SacrificeState.finishing: Messages.Message("A sacrifice is already gathering.", TargetInfo.Invalid, MessageTypeDefOf.RejectInput); return; } } private bool CanGatherSacrificeNow() { if (tempSacrifice == null) { return RejectMessage("No prisoner to sacrifice selected."); } if (tempExecutioner == null) { return RejectMessage("No executioner selected"); } if (tempExecutioner.Drafted) { return RejectMessage("The executioner is drafted."); } if (tempCurrentSacrificeDeity == null) { return RejectMessage("No cosmic entity selected"); } if (MapComponent_SacrificeTracker.Get(Map).lastSacrificeType != CultUtility.SacrificeType.animal && tempCurrentSpell == null) { return RejectMessage("No spell selected. Tip: Earn favor to unlock spells."); } if (tempSacrifice.Dead) { return RejectMessage("The sacrifice is already dead", tempSacrifice); } if (tempExecutioner.Dead || tempExecutioner.Downed) { return RejectMessage("Select an able-bodied executioner"); } if (!tempExecutioner.CanReserve(tempSacrifice)) { return RejectMessage("The executioner can't reserve the sacrifice."); } if (!tempExecutioner.CanReserve(this)) { return RejectMessage("The altar is reserved by something else"); } if (Position.GetThingList(Map).OfType<Corpse>().Any()) { return RejectMessage("The altar needs to be cleared first."); } return MapComponent_SacrificeTracker.Get(Map).lastSacrificeType != CultUtility.SacrificeType.human || tempCurrentSpell.Worker is SpellWorker worker && worker.CanSummonNow(Map); } private void StartSacrifice() { //Check for missing actors if (!PreStartSacrificeReady()) { return; } //Reset results MapComponent_SacrificeTracker.Get(Map).lastResult = CultUtility.SacrificeResult.none; //Send a message about the gathering if (Map?.info?.parent is Settlement factionBase) { Messages.Message("SacrificeGathering".Translate(factionBase.Label), TargetInfo.Invalid, MessageTypeDefOf.NeutralEvent); } //Change the state ChangeState(State.sacrificing, SacrificeState.started); //Create a new "bill" with all the variables from the sacrifice form sacrificeData = new Bill_Sacrifice(tempSacrifice, tempExecutioner, tempCurrentSacrificeDeity, tempCurrentSpell); Utility.DebugReport("Force Sacrifice called"); //Give the sacrifice job var job = new Job(CultsDefOf.Cults_HoldSacrifice, tempSacrifice, this) {count = 1}; tempExecutioner.jobs.TryTakeOrderedJob(job); //Set the congregation sacrificeData.Congregation = GetSacrificeGroup(); Utility.DebugReport("Sacrifice state set to gathering"); } private bool PreStartSacrificeReady() { if (Destroyed || !Spawned) { CultUtility.AbortCongregation(null, "The altar is unavailable."); return false; } if (!Utility.IsActorAvailable(tempExecutioner)) { CultUtility.AbortCongregation(this, "The executioner, " + tempExecutioner.LabelShort + " is unavaialable."); tempExecutioner = null; return false; } if (Utility.IsActorAvailable(tempSacrifice, true)) { return true; } CultUtility.AbortCongregation(this, "The sacrifice, " + tempSacrifice.LabelShort + " is unavaialable."); tempSacrifice = null; return false; } public static List<Pawn> GetSacrificeGroup(Building_SacrificialAltar altar) { return altar.GetSacrificeGroup(); } public List<Pawn> GetSacrificeGroup() { var room = this.GetRoom(); var pawns = new List<Pawn>(); if (room.Role == RoomRoleDefOf.PrisonBarracks || room.Role == RoomRoleDefOf.PrisonCell) { return pawns; } if (AvailableWorshippers == null || AvailableWorshippers.Count <= 0) { return pawns; } foreach (var p in AvailableWorshippers) { CultUtility.GiveAttendSacrificeJob(this, p); pawns.Add(p); //this.Map.GetComponent<MapComponent_SacrificeTracker>().lastSacrificeCongregation.Add(p); } return pawns; } // RimWorld.WorkGiver_DoBill // Vanilla Code private bool TryFindBestOfferingIngredients(RecipeDef recipe, Pawn pawn, Building_SacrificialAltar billGiver, List<ThingCount> chosen) { chosen.Clear(); var relevantThings = new List<Thing>(); var ingredientsOrdered = new List<IngredientCount>(); var newRelevantThings = new List<Thing>(); if (recipe.ingredients.Count == 0) { //resultThings = relevantThings; return true; } var billGiverRootCell = billGiver.InteractionCell; var validRegionAt = Map.regionGrid.GetValidRegionAt(billGiverRootCell); if (validRegionAt == null) { Utility.DebugReport("Invalid Region"); //resultThings = relevantThings; return false; } ingredientsOrdered.Clear(); if (recipe.productHasIngredientStuff) { Utility.DebugReport(recipe.ingredients[0].ToString()); ingredientsOrdered.Add(recipe.ingredients[0]); } for (var i = 0; i < recipe.ingredients.Count; i++) { if (recipe.productHasIngredientStuff && i == 0) { continue; } var ingredientCount = recipe.ingredients[i]; if (ingredientCount.filter.AllowedDefCount != 1) { continue; } Utility.DebugReport(ingredientCount.ToString()); ingredientsOrdered.Add(ingredientCount); } foreach (var item in recipe.ingredients) { if (ingredientsOrdered.Contains(item)) { continue; } Utility.DebugReport(item.ToString()); ingredientsOrdered.Add(item); } relevantThings.Clear(); var foundAll = false; bool BaseValidator(Thing t) { return t.Spawned && !t.IsForbidden(pawn) && (t.Position - billGiver.Position).LengthHorizontalSquared < 999 * 999 && recipe.fixedIngredientFilter.Allows(t) && recipe.defaultIngredientFilter.Allows(t) && recipe.ingredients.Any(ingNeed => ingNeed.filter.Allows(t)) && pawn.CanReserve(t); } bool RegionProcessor(Region r) { newRelevantThings.Clear(); var list = r.ListerThings.ThingsMatching(ThingRequest.ForGroup(ThingRequestGroup.HaulableEver)); foreach (var thing in list) { if (!BaseValidator(thing)) { continue; } Utility.DebugReport(thing.ToString()); newRelevantThings.Add(thing); } if (newRelevantThings.Count <= 0) { return false; } int comparison(Thing t1, Thing t2) { float lengthHorizontalSquared = (t1.Position - pawn.Position).LengthHorizontalSquared; float lengthHorizontalSquared2 = (t2.Position - pawn.Position).LengthHorizontalSquared; return lengthHorizontalSquared.CompareTo(lengthHorizontalSquared2); } newRelevantThings.Sort(comparison); relevantThings.AddRange(newRelevantThings); newRelevantThings.Clear(); var flag = true; foreach (var ingredientCount in recipe.ingredients) { var num = ingredientCount.GetBaseCount(); foreach (var thing in relevantThings) { if (!ingredientCount.filter.Allows(thing)) { continue; } Utility.DebugReport(thing.ToString()); var num2 = recipe.IngredientValueGetter.ValuePerUnitOf(thing.def); var num3 = Mathf.Min(Mathf.CeilToInt(num / num2), thing.stackCount); ThingCountUtility.AddToList(chosen, thing, num3); num -= num3 * num2; if (num <= 0.0001f) { break; } } if (num > 0.0001f) { flag = false; } } if (!flag) { return false; } foundAll = true; return true; } var traverseParams = TraverseParms.For(pawn); bool entryCondition(Region from, Region r) { return r.Allows(traverseParams, false); } RegionTraverser.BreadthFirstTraverse(validRegionAt, entryCondition, RegionProcessor, 99999); return foundAll; } public bool TryDetermineOffering(CultUtility.SacrificeType type, CultUtility.OfferingSize size, Pawn pawn, Building_SacrificialAltar altar, out List<ThingCount> result, out RecipeDef resultRecipe) { var list = new List<ThingCount>(); var recipeDefName = "OfferingOf"; switch (type) { case CultUtility.SacrificeType.plants: recipeDefName += "Plants"; MapComponent_SacrificeTracker.Get(Map).lastSacrificeType = CultUtility.SacrificeType.plants; break; case CultUtility.SacrificeType.meat: recipeDefName += "Meat"; MapComponent_SacrificeTracker.Get(Map).lastSacrificeType = CultUtility.SacrificeType.meat; break; case CultUtility.SacrificeType.meals: recipeDefName += "Meals"; MapComponent_SacrificeTracker.Get(Map).lastSacrificeType = CultUtility.SacrificeType.meals; break; } switch (size) { case CultUtility.OfferingSize.meagre: recipeDefName += "_Meagre"; break; case CultUtility.OfferingSize.decent: recipeDefName += "_Decent"; break; case CultUtility.OfferingSize.sizable: recipeDefName += "_Sizable"; break; case CultUtility.OfferingSize.worthy: recipeDefName += "_Worthy"; break; case CultUtility.OfferingSize.impressive: recipeDefName += "_Impressive"; break; } var recipe = DefDatabase<RecipeDef>.GetNamed(recipeDefName); resultRecipe = recipe; if (!TryFindBestOfferingIngredients(recipe, pawn, altar, list)) { Messages.Message("Failed to find offering ingredients", MessageTypeDefOf.RejectInput); result = null; return false; } result = list; return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/ShubNiggurath/CompTransmogrified.cs using RimWorld; using RimWorld.Planet; using Verse; namespace CultOfCthulhu { public class CompTransmogrified : ThingComp { //public BodyPartRecord CorePart //{ // get // { // return Pawn?.health?.hediffSet.GetNotMissingParts().FirstOrDefault(x => x.def == Pawn?.RaceProps?.body?.corePart?.def) ?? null; // } //} private bool isTransmogrified; public Pawn Pawn => parent as Pawn; public Hediff_Transmogrified Hediff => Pawn.health.hediffSet.GetFirstHediffOfDef(CultsDefOf.Cults_MonstrousBody) as Hediff_Transmogrified; public bool IsTransmogrified { get => isTransmogrified; set { if (value && isTransmogrified == false) { Find.LetterStack.ReceiveLetter("Cults_TransmogrifiedLetter".Translate(), "Cults_TransmogrifiedLetterDesc".Translate(parent.LabelShort), LetterDefOf.PositiveEvent, new GlobalTargetInfo(parent)); } //HealthUtility.AdjustSeverity(this.parent as Pawn, CultsDefOf.Cults_MonstrousBody, 1.0f); isTransmogrified = value; MakeHediff(); } } public void MakeHediff() { if (!isTransmogrified || Hediff != null) { return; } var hediff = HediffMaker.MakeHediff(CultsDefOf.Cults_MonstrousBody, Pawn); hediff.Severity = 1.0f; Pawn.health.AddHediff(hediff); } public override void PostExposeData() { base.PostExposeData(); Scribe_Values.Look(ref isTransmogrified, "isTransmogrified"); if (Scribe.mode == LoadSaveMode.PostLoadInit) { MakeHediff(); } } } }<file_sep>/Source/CultOfCthulhu/MentalBreaks/JobGiver_Disillusioned.cs using Verse; using Verse.AI; namespace CultOfCthulhu { public class JobGiver_Disillusioned : JobGiver_Wander { public JobGiver_Disillusioned() { wanderRadius = 7f; ticksBetweenWandersRange = new IntRange(300, 600); locomotionUrgency = LocomotionUrgency.Amble; wanderDestValidator = WanderRoomUtility.IsValidWanderDest; } protected override IntVec3 GetWanderRoot(Pawn pawn) { return pawn.ownership.OwnedBed?.Position ?? pawn.Position; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/PawnFlyersLeaving.cs using System.Collections.Generic; using Cthulhu; using RimWorld; using RimWorld.Planet; using UnityEngine; using Verse; using Verse.AI.Group; using Verse.Sound; namespace CultOfCthulhu { public class PawnFlyersLeaving : Thing, IActiveDropPod, IThingHolder { private const int MinTicksSinceStart = -40; private const int MaxTicksSinceStart = -15; private const int TicksSinceStartToPlaySound = -10; private const int LeaveMapAfterTicks = 220; private static readonly List<Thing> tmpActiveDropPods = new List<Thing>(); private bool alreadyLeft; public PawnsArrivalModeDef arriveMode; public bool attackOnArrival; // RimWorld.Skyfaller private Material cachedShadowMaterial; private ActiveDropPodInfo contents; public IntVec3 destinationCell = IntVec3.Invalid; public int destinationTile = -1; public int groupID = -1; public PawnFlyer pawnFlyer; private bool soundPlayed; private int ticksSinceStart; private PawnFlyerDef PawnFlyerDef => pawnFlyer.def as PawnFlyerDef; public override Vector3 DrawPos => SkyfallerDrawPosUtility.DrawPos_Accelerate(base.DrawPos, ticksSinceStart, -33f, def.skyfaller.speed); //return DropPodAnimationUtility.DrawPosAt(this.ticksSinceStart, base.Position); // RimWorld.Skyfaller private Material ShadowMaterial { get { if (cachedShadowMaterial == null && !def.skyfaller.shadow.NullOrEmpty()) { cachedShadowMaterial = MaterialPool.MatFrom(def.skyfaller.shadow, ShaderDatabase.Transparent); } return cachedShadowMaterial; } } public void GetChildHolders(List<IThingHolder> outChildren) { ThingOwnerUtility.AppendThingHoldersFromThings(outChildren, GetDirectlyHeldThings()); } public ThingOwner GetDirectlyHeldThings() { return contents.innerContainer; } public ActiveDropPodInfo Contents { get => contents; set { if (contents != null) { contents.parent = null; } if (value != null) { value.parent = this; } contents = value; } } public IntVec3 GetPosition() { return PositionHeld; } public Map GetMap() { return MapHeld; } public override void PostMake() { base.PostMake(); ticksSinceStart = Rand.RangeInclusive(-40, -15); } public override void ExposeData() { base.ExposeData(); //PawnFlyer Scribe_References.Look(ref pawnFlyer, "pawnFlyer"); //Vanilla Scribe_Values.Look(ref groupID, "groupID"); Scribe_Values.Look(ref destinationTile, "destinationTile"); Scribe_Values.Look(ref destinationCell, "destinationCell"); Scribe_Values.Look(ref arriveMode, "arriveMode", PawnsArrivalModeDefOf.EdgeDrop); Scribe_Values.Look(ref attackOnArrival, "attackOnArrival"); Scribe_Values.Look(ref ticksSinceStart, "ticksSinceStart"); Scribe_Deep.Look(ref contents, "contents", this); Scribe_Values.Look(ref alreadyLeft, "alreadyLeft"); Scribe_Values.Look(ref soundPlayed, "soundPlayed"); } public override void Tick() { if (!soundPlayed && ticksSinceStart >= -10) { if (PawnFlyerDef.takeOffSound != null) { PawnFlyerDef.takeOffSound.PlayOneShot(new TargetInfo(Position, Map)); } else { Log.Warning("PawnFlyersLeaving :: Take off sound not set"); } soundPlayed = true; } ticksSinceStart++; if (!alreadyLeft && ticksSinceStart >= 220) { GroupLeftMap(); } } public override void DrawAt(Vector3 drawLoc, bool flip) { if (!drawLoc.InBounds(Map)) { return; } pawnFlyer.Drawer.DrawAt(drawLoc); var shadowMaterial = ShadowMaterial; if (!(shadowMaterial == null)) { Skyfaller.DrawDropSpotShadow(base.DrawPos, Rotation, shadowMaterial, def.skyfaller.shadowSize, ticksSinceStart); } //DropPodAnimationUtility.DrawDropSpotShadow(this, this.ticksSinceStart); } private void GroupLeftMap() { if (groupID < 0) { Log.Error("Drop pod left the map, but its group ID is " + groupID); Destroy(); return; } if (destinationTile < 0) { Log.Error("Drop pod left the map, but its destination tile is " + destinationTile); Destroy(); return; } var lord = FindLord(groupID, Map); if (lord != null) { Map.lordManager.RemoveLord(lord); } var PawnFlyersTraveling = (PawnFlyersTraveling) WorldObjectMaker.MakeWorldObject(PawnFlyerDef.travelingDef); PawnFlyersTraveling.pawnFlyer = pawnFlyer; PawnFlyersTraveling.Tile = Map.Tile; PawnFlyersTraveling.destinationTile = destinationTile; PawnFlyersTraveling.destinationCell = destinationCell; PawnFlyersTraveling.arriveMode = arriveMode; PawnFlyersTraveling.attackOnArrival = attackOnArrival; Find.WorldObjects.Add(PawnFlyersTraveling); tmpActiveDropPods.Clear(); tmpActiveDropPods.AddRange(Map.listerThings.ThingsInGroup(ThingRequestGroup.ActiveDropPod)); foreach (var thing in tmpActiveDropPods) { if (thing is not PawnFlyersLeaving pawnFlyerLeaving || pawnFlyerLeaving.groupID != groupID) { continue; } Utility.DebugReport("Transport Already Left"); pawnFlyerLeaving.alreadyLeft = true; PawnFlyersTraveling.AddPod(pawnFlyerLeaving.contents, true); pawnFlyerLeaving.contents = null; pawnFlyerLeaving.Destroy(); } } // RimWorld.TransporterUtility public static Lord FindLord(int transportersGroup, Map map) { var lords = map.lordManager.lords; foreach (var findLord in lords) { if (findLord.LordJob is LordJob_LoadAndEnterTransportersPawn lordJob_LoadAndEnterTransporters && lordJob_LoadAndEnterTransporters.transportersGroup == transportersGroup) { return findLord; } } return null; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Hastur/SpellWorker_SummonByakhee.cs using Cthulhu; using RimWorld; using Verse; namespace CultOfCthulhu { public class SpellWorker_SummonByakhee : SpellWorker { public override bool CanSummonNow(Map map) { return true; } protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } protected override bool TryExecuteWorker(IncidentParms parms) { if (!(parms.target is Map map)) { return false; } //Find a drop spot if (!CultUtility.TryFindDropCell(map.Center, map, 70, out var intVec)) { return false; } parms.spawnCenter = intVec; Utility.SpawnPawnsOfCountAt(CultsDefOf.Cults_Byakhee, intVec, map, 1, Faction.OfPlayer); map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = intVec; return true; } } }<file_sep>/Source/CultOfCthulhu/MentalBreaks/MentalStateWorker_Disillusioned.cs using Verse; using Verse.AI; namespace CultOfCthulhu { public class MentalStateWorker_Disillusioned : MentalStateWorker { public override bool StateCanOccur(Pawn pawn) { if (!base.StateCanOccur(pawn)) { return false; } if (!pawn.Spawned) { return false; } var cultMind = pawn.needs.TryGetNeed<Need_CultMindedness>(); if (cultMind == null) { return false; } return cultMind.CurLevel > 0.8; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/ShubNiggurath/Building_WombBetweenWorlds.cs using System.Collections.Generic; using System.Diagnostics; using System.Text; using Cthulhu; using RimWorld; using Verse; using Verse.AI.Group; namespace CultOfCthulhu { public class Building_WombBetweenWorlds : ThingWithComps { private const int InitialPawnSpawnDelay = 960; private const int PawnSpawnRadius = 5; private const float MaxSpawnedPawnsPoints = 500f; private const int InitialPawnsPoints = 260; //private static readonly FloatRange PawnSpawnIntervalDays = new FloatRange(0.85f, 1.1f); private static readonly FloatRange PawnSpawnIntervalDays = new FloatRange(3.85f, 3.1f); public bool active = true; private Lord lord; public int nextPawnSpawnTick = -1; public List<Pawn> spawnedPawns = new List<Pawn>(); private int ticksToSpawnInitialPawns = -1; private float SpawnedPawnsPoints { get { FilterOutUnspawnedPawns(); var num = 0f; foreach (var pawn in spawnedPawns) { num += pawn.kindDef.combatPower; } return num; } } public override void SpawnSetup(Map map, bool bla) { base.SpawnSetup(map, bla); if (Faction == null) { SetFaction(Faction.OfInsects); } } public void StartInitialPawnSpawnCountdown() { ticksToSpawnInitialPawns = 960; } private void SpawnInitialPawnsNow() { ticksToSpawnInitialPawns = -1; while (SpawnedPawnsPoints < 260f) { if (!TrySpawnPawn(out _, Map)) { return; } } CalculateNextPawnSpawnTick(); } public override void TickRare() { base.TickRare(); FilterOutUnspawnedPawns(); if (!active && !Position.Fogged(Map)) { Activate(); } if (!active) { return; } if (ticksToSpawnInitialPawns > 0) { ticksToSpawnInitialPawns -= 250; if (ticksToSpawnInitialPawns <= 0) { SpawnInitialPawnsNow(); } } if (Find.TickManager.TicksGame < nextPawnSpawnTick) { return; } if (SpawnedPawnsPoints < MaxSpawnedPawnsPoints) { var flag = TrySpawnPawn(out var pawn, Map); if (flag) { pawn.caller?.DoCall(); } } CalculateNextPawnSpawnTick(); } public override void PostApplyDamage(DamageInfo dinfo, float totalDamageDealt) { if (dinfo.Def.ExternalViolenceFor(dinfo.IntendedTarget) && dinfo.Instigator != null) { if (ticksToSpawnInitialPawns > 0) { SpawnInitialPawnsNow(); } //Lord lord = this.Lord; //if (lord != null) //{ // lord.ReceiveMemo("HiveAttacked"); //} } base.PostApplyDamage(dinfo, totalDamageDealt); } public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref active, "active"); Scribe_Values.Look(ref nextPawnSpawnTick, "nextPawnSpawnTick"); Scribe_Collections.Look(ref spawnedPawns, "spawnedPawns", LookMode.Reference); Scribe_Values.Look(ref ticksToSpawnInitialPawns, "ticksToSpawnInitialPawns"); if (Scribe.mode == LoadSaveMode.PostLoadInit) { spawnedPawns.RemoveAll(x => x == null); } } private void Activate() { active = true; nextPawnSpawnTick = Find.TickManager.TicksGame + Rand.Range(200, 400); //CompSpawnerHives comp = base.GetComp<CompSpawnerHives>(); //if (comp != null) //{ // comp.CalculateNextHiveSpawnTick(); //} } public override string GetInspectString() { var s = new StringBuilder(); s.Append(base.GetInspectString()); var text = string.Empty; if (CanSpawnPawns()) { text = text + "DarkYoungSpawnsIn".Translate() + ": " + (nextPawnSpawnTick - Find.TickManager.TicksGame).ToStringTicksToPeriodVague(); } s.Append(text); return s.ToString(); } public bool CanSpawnPawns() { return SpawnedPawnsPoints < MaxSpawnedPawnsPoints; } private void CalculateNextPawnSpawnTick() { var num = GenMath.LerpDouble(0f, 5f, 1f, 0.5f, spawnedPawns.Count); nextPawnSpawnTick = Find.TickManager.TicksGame + (int) (PawnSpawnIntervalDays.RandomInRange * 60000f / (num * Find.Storyteller.difficulty .enemyReproductionRateFactor)); //this.nextPawnSpawnTick = Find.TickManager.TicksGame + (int)(Building_WombBetweenWorlds.PawnSpawnIntervalDays.RandomInRange * 60000f); } private void FilterOutUnspawnedPawns() { spawnedPawns.RemoveAll(x => !x.Spawned); } private bool TrySpawnPawn(out Pawn pawn, Map map) { var kindDef = Utility.IsCosmicHorrorsLoaded() ? PawnKindDef.Named("ROM_DarkYoung") : PawnKindDefOf.Megaspider; pawn = PawnGenerator.GeneratePawn(kindDef, Faction); try { var pos = Position; for (var i = 0; i < 3; i++) { pos += GenAdj.CardinalDirections[2]; } GenSpawn.Spawn(pawn, CellFinder.RandomClosewalkCellNear(pos, map, 1), map); // spawnedPawns.Add(pawn); if (Faction != Faction.OfPlayer) { if (lord == null) { lord = CreateNewLord(); } lord.AddPawn(pawn); } Messages.Message("Cults_NewDarkYoung".Translate(), pawn, MessageTypeDefOf.PositiveEvent); return true; } catch { return true; } } [DebuggerHidden] public override IEnumerable<Gizmo> GetGizmos() { using var enumerator = base.GetGizmos().GetEnumerator(); while (enumerator.MoveNext()) { var current = enumerator.Current; yield return current; } if (Prefs.DevMode) { yield return new Command_Action { defaultLabel = "DEBUG: Spawn pawn", icon = TexCommand.ReleaseAnimals, action = delegate { TrySpawnPawn(out _, Map); } }; } } public override bool PreventPlayerSellingThingsNearby(out string reason) { if (spawnedPawns.Count > 0) { if (spawnedPawns.Any(p => !p.Downed)) { reason = def.label; return true; } } reason = null; return false; } private Lord CreateNewLord() { //Log.Message("Building_WombBetweenWorlds LordJob_DefendPoint"); return LordMaker.MakeNewLord(Faction, new LordJob_DefendPoint(Position), null); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Reanimation/MapComponent_SacrificeTracker_Resurrection.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public partial class MapComponent_SacrificeTracker : MapComponent { /// <summary> /// This keeps track of dead colonists who have taken the Unspeakable Oath. /// They will need to be resurrected. This begins the process. /// </summary> public void ResolveHasturOathtakers() { try { if (Find.TickManager.TicksGame % 100 != 0) { return; } if (unspeakableOathPawns.NullOrEmpty()) { return; } var tempOathList = new List<Pawn>(unspeakableOathPawns); foreach (var oathtaker in tempOathList) { if (!oathtaker.Dead) { continue; } unspeakableOathPawns?.Remove(oathtaker); if ((toBeResurrected?.Count ?? 0) > 0) { toBeResurrected = new List<Pawn>(); } toBeResurrected?.Add(oathtaker); Utility.DebugReport("Started Resurrection Process"); ticksUntilResurrection = resurrectionTicks; } } catch { // ignored } } /// <summary> /// When Oathtakers die, they need to be resurrected after a period of time. /// </summary> public void ResolveHasturResurrections() { //Check ticks if (ticksUntilResurrection == -999) { return; } if (ticksUntilResurrection > 0) { ticksUntilResurrection--; return; } ticksUntilResurrection = -999; //Ticks passed. Commence resurrection! HasturResurrection(); //Do we still have colonists that need resurrection? If so, let's proceed with another round of resurrection. //Reset the timer, and let's get to work. if ((toBeResurrected?.Count ?? 0) > 0) { ticksUntilResurrection = resurrectionTicks; } } public void HasturResurrection() { var sourceCorpse = toBeResurrected.RandomElement(); toBeResurrected.Remove(sourceCorpse); var unused = IntVec3.Invalid; if (sourceCorpse.Corpse == null) { return; } //Use B18's Resurrect Feature ResurrectionUtility.Resurrect(sourceCorpse); //Remove everything that conflicts with Psychopathic behavior sourceCorpse.story.traits.allTraits.RemoveAll( x => x.def.conflictingTraits is List<TraitDef> conflicts && !conflicts.NullOrEmpty() && conflicts.Contains(TraitDefOf.Psychopath) || x.def.defName == "Cults_OathtakerHastur"); //Remove a random trait and add Psychopath if (sourceCorpse.story.traits.allTraits is List<Trait> {Count: > 1} allTraits && allTraits.FirstOrDefault(x => x.def == TraitDefOf.Psychopath) == null) { sourceCorpse.story.traits.allTraits.RemoveLast(); sourceCorpse.story.traits.GainTrait(new Trait(TraitDefOf.Psychopath, 0, true)); } //Adds the "Reanimated" trait sourceCorpse.story.traits.GainTrait(new Trait(TraitDef.Named("Cults_OathtakerHastur2"), 0, true)); //Message to the player #pragma warning disable CS0618 // Type or member is obsolete Messages.Message("ReanimatedOath".Translate(sourceCorpse.Name), MessageTypeDefOf.PositiveEvent); #pragma warning restore CS0618 // Type or member is obsolete } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Sacrifice/JobDriver_AttendSacrifice.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using RimWorld; using Verse; using Verse.AI; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class JobDriver_AttendSacrifice : JobDriver { private readonly TargetIndex Build = TargetIndex.A; private readonly TargetIndex Facing = TargetIndex.B; private readonly TargetIndex Spot = TargetIndex.C; private string report = ""; private Pawn setExecutioner; protected Building_SacrificialAltar Altar => (Building_SacrificialAltar) job.GetTarget(TargetIndex.A).Thing; protected Pawn ExecutionerPawn { get { if (setExecutioner != null) { return setExecutioner; } if (Altar.SacrificeData.Executioner != null) { setExecutioner = Altar.SacrificeData.Executioner; return Altar.SacrificeData.Executioner; } foreach (var executionerPawn in pawn.Map.mapPawns.FreeColonistsSpawned) { if (executionerPawn.CurJob.def != CultsDefOf.Cults_HoldSacrifice) { continue; } setExecutioner = executionerPawn; return executionerPawn; } return null; } } public override bool TryMakePreToilReservations(bool errorOnFailed) { return true; } public override void ExposeData() { Scribe_References.Look(ref setExecutioner, "setExecutioner"); base.ExposeData(); } public override string GetReport() { return report != "" ? ReportStringProcessed(report) : base.GetReport(); } protected override IEnumerable<Toil> MakeNewToils() { rotateToFace = Facing; AddEndCondition(delegate { if (ExecutionerPawn?.CurJob == null) { return JobCondition.Incompletable; } if (ExecutionerPawn.CurJob.def == CultsDefOf.Cults_ReflectOnResult) { return JobCondition.Succeeded; } if (ExecutionerPawn.CurJob.def != CultsDefOf.Cults_HoldSacrifice) { return JobCondition.Incompletable; } return JobCondition.Ongoing; }); this.EndOnDespawnedOrNull(Spot); this.EndOnDespawnedOrNull(Build); yield return Toils_Reserve.Reserve(Spot); //Toil 1: Go to the locations var gotoExecutioner = TargetC.HasThing ? Toils_Goto.GotoThing(Spot, PathEndMode.OnCell) : Toils_Goto.GotoCell(Spot, PathEndMode.OnCell); yield return gotoExecutioner; //Toil 2: 'Attend' var altarToil = new Toil { defaultCompleteMode = ToilCompleteMode.Delay, defaultDuration = CultUtility.ritualDuration }; altarToil.AddPreTickAction(() => { pawn.GainComfortFromCellIfPossible(); pawn.rotationTracker.FaceCell(TargetB.Cell); if (report == "") { report = "Cults_AttendingSacrifice".Translate(); } if (ExecutionerPawn?.CurJob == null) { return; } if (ExecutionerPawn.CurJob.def != CultsDefOf.Cults_HoldSacrifice) { ReadyForNextToil(); } }); altarToil.JumpIf(() => ExecutionerPawn.CurJob.def == CultsDefOf.Cults_HoldSacrifice, altarToil); yield return altarToil; //ToDo -- Add random Ia! Ia! yield return new Toil { initAction = delegate { //Do something? Ia ia! }, defaultCompleteMode = ToilCompleteMode.Instant }; //Toil 3 Reflect on worship var reflectingTime = new Toil { defaultCompleteMode = ToilCompleteMode.Delay, defaultDuration = CultUtility.reflectDuration }; reflectingTime.AddPreTickAction(() => report = "Cults_ReflectingOnSacrifice".Translate()); yield return reflectingTime; //Toil 3 Reset the altar and clear variables. yield return new Toil { initAction = delegate { if (Altar == null) { return; } if (Altar.currentSacrificeState != Building_SacrificialAltar.SacrificeState.finished) { Altar.ChangeState(Building_SacrificialAltar.State.sacrificing, Building_SacrificialAltar.SacrificeState.finished); } }, defaultCompleteMode = ToilCompleteMode.Instant }; AddFinishAction(() => { //When the ritual is finished -- then let's give the thoughts /* if (Altar.currentSacrificeState == Building_SacrificialAltar.SacrificeState.finished) { if (this.pawn == null) return; if (Altar.sacrifice != null) { CultUtility.AttendSacrificeTickCheckEnd(this.pawn, Altar.sacrifice); } else { CultUtility.AttendSacrificeTickCheckEnd(this.pawn, null); } } */ if (TargetC.Cell.GetEdifice(pawn.Map) != null) { if (pawn.Map.reservationManager.ReservedBy(TargetC.Cell.GetEdifice(pawn.Map), pawn)) { pawn.ClearAllReservations(); // this.pawn.Map.reservationManager.Release(this.TargetC.Cell.GetEdifice(this.pawn.Map), pawn); } } else { if (pawn.Map.reservationManager.ReservedBy(TargetC.Cell.GetEdifice(pawn.Map), pawn)) { pawn.ClearAllReservations(); //this.pawn.Map.reservationManager.Release(this.job.targetC.Cell, this.pawn); } } }); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/WorkGiver_LoadTransportersPawn.cs using RimWorld; using Verse; using Verse.AI; namespace CultOfCthulhu { public class WorkGiver_LoadTransportersPawn : WorkGiver_Scanner { public override ThingRequest PotentialWorkThingRequest => ThingRequest.ForGroup(ThingRequestGroup.Pawn); public override PathEndMode PathEndMode => PathEndMode.Touch; public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { if (t == null) { return false; } if (!(t is Pawn pawn2) || pawn2 == pawn) { return false; } if (!pawn.CanReserveAndReach(t, PathEndMode.ClosestTouch, Danger.Deadly)) { return false; } var transporter = t.TryGetComp<CompTransporterPawn>(); return transporter != null && LoadTransportersPawnJobUtility.HasJobOnTransporter(pawn, transporter); } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { var transporter = t.TryGetComp<CompTransporterPawn>(); return t == null ? null : LoadTransportersPawnJobUtility.JobOnTransporter(pawn, transporter); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Cthulhu/SpellWorker_OrbitalInsanityWave.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_OrbitalInsanityWave : SpellWorker { private const float FogClearRadius = 4.5f; private const float RelationWithColonistWeight = 20f; public List<Thing> ThingsToAdd(ThingDef def, int count) { var tempList = new List<Thing>(); if (count == 0) { return tempList; } for (var i = 0; i <= count; i++) { var thingWithComps = (ThingWithComps) ThingMaker.MakeThing(def); tempList.Add(thingWithComps); } return tempList; } public override bool CanSummonNow(Map map) { return true; } protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; float chance = Rand.Range(1, 100); var container = new List<Thing>(); string label; string text; //Get a random cell. var intVec = DropCellFinder.RandomDropSpot(map); //Set the faction of the dude. var unused = Find.FactionManager.FirstFactionOfDef(FactionDefOf.Ancients ); ////Chance of generating soldiers //for (int i = 0; i < (int)Rand.Range(0, 2); i++) //{ // PawnGenerationRequest request = new PawnGenerationRequest(PawnKindDefOf.SpaceSoldier, faction, PawnGenerationContext.NonPlayer, map, false, false, false, false, true, true, 20f, false, true, true, null, null, null, null, null, null); // Pawn pawn = PawnGenerator.GeneratePawn(request); // Cthulhu.Utility.ApplySanityLoss(pawn, 1.0f); // container.TryAdd(pawn); //} ////Chance of generating survivors. One is required to start the pod! //for (int i = 0; i < (int)Rand.Range(1, 2); i++) //{ // PawnGenerationRequest request = new PawnGenerationRequest(PawnKindDefOf.SpaceRefugee, faction, PawnGenerationContext.NonPlayer, map, false, false, false, false, true, false, 20f, false, true, true, null, null, null, null, null, null); // Pawn pawn = PawnGenerator.GeneratePawn(request); // Cthulhu.Utility.ApplySanityLoss(pawn, 1.0f); // container.TryAdd(pawn); //} //Chance of generating downed survivors. //for (int i = 0; i < (int)Rand.Range(0, 2); i++) //{ // PawnGenerationRequest request = new PawnGenerationRequest(PawnKindDefOf.SpaceRefugee, faction, PawnGenerationContext.NonPlayer, map, false, false, false, false, true, false, 20f, false, true, true, null, null, null, null, null, null); // Pawn pawn = PawnGenerator.GeneratePawn(request); // Cthulhu.Utility.ApplySanityLoss(pawn, 1.0f); // HealthUtility.GiveInjuriesToForceDowned(pawn); // container.TryAdd(pawn); //} //Chance of generating dead bodies //for (int i = 0; i < (int)Rand.Range(0, 3); i++) //{ // PawnGenerationRequest request = new PawnGenerationRequest(PawnKindDefOf.SpaceRefugee, faction, PawnGenerationContext.NonPlayer, false, false, false, false, true, false, 20f, false, true, true, null, null, null, null, null, null); // Pawn pawn = PawnGenerator.GeneratePawn(request); // HealthUtility.GiveInjuriesToKill(pawn); // container.TryAdd(pawn); // } //What kind of trade ship was it? //Combat Supplier if (chance > 66) { label = "LetterLabelForcedCrashCombatSuplier".Translate(); text = "ForcedCrashCombatSuplier".Translate(); container.AddRange(ThingsToAdd(ThingDefOf.Silver, Rand.Range(40, 60))); //Orig 4000-6000 container.AddRange(ThingsToAdd(ThingDefOf.ComponentSpacer, Rand.Range(-1, 10))); //Original -1~10 container.AddRange(ThingsToAdd(ThingDefOf.Shell_HighExplosive, Rand.Range(5, 10))); //Original 30-60 container.AddRange(ThingsToAdd(ThingDefOf.MedicineUltratech, Rand.Range(1, 3))); //Original 30-50 AddThingsToContainerByTag(container, "BodyPartOrImplant", Rand.Range(-8, 2)); //Original 0~5 AddThingsToContainerByTag(container, "Drugs", Rand.Range(-2, 2)); //Original 0~5 var randomInRange = Rand.Range(3, 6); //Orig 4~8 guns //Weapons Ranged for (var i = 0; i < randomInRange; i++) { if (!(from t in DefDatabase<ThingDef>.AllDefs where t.IsRangedWeapon && t.tradeability != Tradeability.None && t.techLevel <= TechLevel.Archotech && t.BaseMarketValue <= 500 select t).TryRandomElement(out var thingDef)) { break; } ThingDef stuff = null; if (thingDef.MadeFromStuff) { stuff = (from st in DefDatabase<ThingDef>.AllDefs where st.IsStuff && st.stuffProps.CanMake(thingDef) select st).RandomElementByWeight(st => st.stuffProps.commonality); } var thingWithComps = (ThingWithComps) ThingMaker.MakeThing(thingDef, stuff); container.Add(thingWithComps); } //Weapons Melee randomInRange = Rand.Range(1, 3); //Orig 3~5 guns for (var i = 0; i < randomInRange; i++) { if (!(from t in DefDatabase<ThingDef>.AllDefs where t.IsRangedWeapon && t.tradeability != Tradeability.None && t.techLevel <= TechLevel.Archotech select t).TryRandomElement(out var thingDef)) { break; } ThingDef stuff = null; if (thingDef.MadeFromStuff) { stuff = (from st in DefDatabase<ThingDef>.AllDefs where st.IsStuff && st.stuffProps.CanMake(thingDef) select st).RandomElementByWeight(st => st.stuffProps.commonality); } var thingWithComps = (ThingWithComps) ThingMaker.MakeThing(thingDef, stuff); container.Add(thingWithComps); } //Armor randomInRange = Rand.Range(1, 2); //Orig 2~4 armor for (var i = 0; i < randomInRange; i++) { if (!(from t in DefDatabase<ThingDef>.AllDefs where t.IsApparel && t.tradeability != Tradeability.None && t.techLevel <= TechLevel.Archotech && (t.GetStatValueAbstract(StatDefOf.ArmorRating_Blunt) > 0.15f || t.GetStatValueAbstract(StatDefOf.ArmorRating_Sharp) > 0.15f) select t).TryRandomElement(out var thingDef)) { break; } ThingDef stuff = null; if (thingDef.MadeFromStuff) { stuff = (from st in DefDatabase<ThingDef>.AllDefs where st.IsStuff && st.stuffProps.CanMake(thingDef) select st).RandomElementByWeight(st => st.stuffProps.commonality); } var thingWithComps = (ThingWithComps) ThingMaker.MakeThing(thingDef, stuff); container.Add(thingWithComps); } //Clothes randomInRange = Rand.Range(1, 2); //Orig 4~8 clothes for (var i = 0; i < randomInRange; i++) { if (!(from t in DefDatabase<ThingDef>.AllDefs where t.IsApparel && t.tradeability != Tradeability.None && t.techLevel <= TechLevel.Archotech select t).TryRandomElement(out var thingDef)) { break; } ThingDef stuff = null; if (thingDef.MadeFromStuff) { stuff = (from st in DefDatabase<ThingDef>.AllDefs where st.IsStuff && st.stuffProps.CanMake(thingDef) select st).RandomElementByWeight(st => st.stuffProps.commonality); } var thingWithComps = (ThingWithComps) ThingMaker.MakeThing(thingDef, stuff); container.Add(thingWithComps); } } else if (chance > 33 && chance <= 66) { label = "LetterLabelForcedCrashBulkGoods".Translate(); text = "ForcedCrashBulkGoods".Translate(); //Basic Stuff container.AddRange(ThingsToAdd(ThingDefOf.Silver, Rand.Range(20, 100))); //Original 4000-6000 container.AddRange(ThingsToAdd(ThingDefOf.ComponentIndustrial, Rand.Range(5, 15))); //Original 5-30 container.AddRange(ThingsToAdd(ThingDefOf.ComponentSpacer, Rand.Range(-5, 5))); //Original 5-30 container.AddRange(ThingsToAdd(ThingDefOf.Steel, Rand.Range(20, 100))); //Original 800-1500 //Luxury Goods container.AddRange(ThingsToAdd(ThingDefOf.Gold, Rand.Range(5, 50))); //Original 500-2000 container.AddRange(ThingsToAdd(CultsDefOf.Neutroamine, Rand.Range(5, 15))); //Original 400-800 container.AddRange(ThingsToAdd(ThingDefOf.Plasteel, Rand.Range(5, 15))); //Original 300-700 container.AddRange(ThingsToAdd(ThingDefOf.Beer, Rand.Range(-70, 30))); //Original -700-2000 container.AddRange(ThingsToAdd(ThingDefOf.Chocolate, Rand.Range(-70, 30))); //Original -700-2000 AddThingsToContainerByTag(container, "Furniture", Rand.Range(0, 1)); //(0-3 kinds) Furniture -1~2 //Sensitive Materials container.AddRange(ThingsToAdd(ThingDefOf.Cloth, Rand.Range(-20, 50))); //Original -200-600 container.AddRange(ThingsToAdd(ThingDefOf.MedicineIndustrial, Rand.Range(1, 5))); //Original 10-30 container.AddRange(ThingsToAdd(ThingDefOf.MedicineUltratech, Rand.Range(-10, 5))); //Original 10-30 AddThingsToContainerByTag(container, "Apparel", Rand.Range(4, 8)); //Original 10-20 container.AddRange(ThingsToAdd(ThingDefOf.WoodLog, Rand.Range(10, 60))); //Original 800-1500 //Foodstuffs container.AddRange(ThingsToAdd(ThingDef.Named("Pemmican"), Rand.Range(-20, 40))); //NA container.AddRange(ThingsToAdd(ThingDef.Named("Kibble"), Rand.Range(-20, 40))); //NA //Food meals 2-4 //AddThingsToContainerByTag(container, "", Rand.Range(0, 1)); //ResourcesRaw 1500 - 3000 //AddThingsToContainerByTag(container, "", Rand.Range(0, 1)); //(2-8 kinds) FoodRaw 1600 - 5000 //Animals Original - 2-4 types, 10-20 number, max wildness 0.70 AddThingsToContainerByTag(container, "Drugs", Rand.Range(2, 4)); //Original 2-4 types, max price of 8000 //Textiles - Original 2200 - 4000. //New Range - 270 - 1100 container.AddRange(ThingsToAdd(CultsDefOf.BlocksSlate, Rand.Range(-100, 200))); container.AddRange(ThingsToAdd(CultsDefOf.BlocksLimestone, Rand.Range(-100, 200))); container.AddRange(ThingsToAdd(CultsDefOf.BlocksMarble, Rand.Range(-100, 200))); container.AddRange(ThingsToAdd(ThingDef.Named("BlocksGranite"), Rand.Range(-100, 200))); container.AddRange(ThingsToAdd(ThingDefOf.Plasteel, Rand.Range(-20, 20))); container.AddRange(ThingsToAdd(ThingDefOf.Steel, Rand.Range(-100, 200))); } //Exotic else { label = "LetterLabelForcedCrashExotic".Translate(); text = "ForcedCrashExotic".Translate(); container.AddRange(ThingsToAdd(ThingDefOf.Silver, Rand.Range(50, 100))); //Original 1500-3000 container.AddRange(ThingsToAdd(ThingDefOf.ComponentIndustrial, Rand.Range(6, 20))); //Original 6-20 container.AddRange(ThingsToAdd(ThingDefOf.ComponentSpacer, Rand.Range(-20, 5))); //Original 6-20 container.AddRange(ThingsToAdd(ThingDefOf.Plasteel, Rand.Range(10, 30))); //Original 50-150 container.AddRange(ThingsToAdd(ThingDefOf.Gold, Rand.Range(10, 20))); //Original 100-300 container.AddRange(ThingsToAdd(CultsDefOf.Neutroamine, Rand.Range(5, 20))); //Original 25-100 container.AddRange(ThingsToAdd(CultsDefOf.Penoxycyline, Rand.Range(-25, 25))); //Original (0) container.AddRange(ThingsToAdd(ThingDef.Named("Telescope"), Rand.Range(-3, 2))); //Original -2 - 2 //AddThingsToContainerByTag(container, "Television", Rand.Range(-2, 2)); //Original -2~2 AddThingsToContainerByTag(container, "BodyPartOrImplant", Rand.Range(1, 2)); //Original 2~4 //AddThingsToContainerByTag(container, "StandardAnimal", Rand.Range(1, 2)); //Animals - Original 1-3 kinds, 2-6 number. Wildness 0.6 AddThingsToContainerByTag(container, "Furniture", Rand.Range(0, 3)); //Furniture - Original 0-3 kinds, -1-3 number AddThingsToContainerByTag(container, "Apparel", Rand.Range(1, 2)); //Original 1-2, 3-4 duplicates AddThingsToContainerByTag(container, "Artifact", Rand.Range(-2, 1)); //Original 1-1 AddThingsToContainerByTag(container, "Drugs", Rand.Range(2, 4)); //Original 2-4 AddThingsToContainerByTag(container, "Exotic", Rand.Range(1, 2)); //Original 2-4 kinds, 1-2 //Art not included, due to crash. } //Misc ship crash pieces. container.AddRange(ThingsToAdd(ThingDefOf.Steel, Rand.Range(20, 100))); container.AddRange(ThingsToAdd(ThingDefOf.ComponentIndustrial, Rand.Range(10, 20))); container.AddRange(ThingsToAdd(ThingDefOf.ComponentSpacer, Rand.Range(-20, 5))); container.AddRange(ThingsToAdd(ThingDefOf.Steel, Rand.Range(20, 100))); //PawnRelationUtility.TryAppendRelationsWithColonistsInfo(ref text, ref label, pawn); Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.PositiveEvent, new TargetInfo(intVec, map)); var adpInfo = new ActiveDropPodInfo(); foreach (var thing in container) { adpInfo.innerContainer.TryAdd(thing); } DropPodUtility.MakeDropPodAt(intVec, map, adpInfo); Utility.ApplyTaleDef("Cults_SpellOrbitalInsanityWave", map); return true; } public void AddThingsToContainerByTag(List<Thing> container, string tag, int counter) { if (counter <= 0) { return; } for (var i = 0; i < counter; i++) { if (!(from t in DefDatabase<ThingDef>.AllDefs where t.tradeTags != null && t.tradeTags.Contains(tag) select t).TryRandomElement(out var thingDef)) { break; } ThingDef stuff = null; if (thingDef.MadeFromStuff) { stuff = (from st in DefDatabase<ThingDef>.AllDefs where st.IsStuff && st.stuffProps.CanMake(thingDef) select st).RandomElementByWeight(st => st.stuffProps.commonality); } var thingWithComps = (ThingWithComps) ThingMaker.MakeThing(thingDef, stuff); container.Add(thingWithComps); } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/CultTableOfFun.cs using System.Collections.Generic; using Cthulhu; using RimWorld; using Verse; namespace CultOfCthulhu { public class FunSpell { public FunSpell(string newName, float newWeight) { defName = newName; weight = newWeight; } public string defName { get; set; } public float weight { get; set; } } public class CultTableOfFun { public List<FunSpell> TableOfFun; public CultTableOfFun() { TableOfFun = new List<FunSpell> { new FunSpell("Cults_SpellDoubleTheFun", 1), // FINISHED new FunSpell("Cults_SpellReanimator", 2), // FINISHED new FunSpell("Cults_SpellFlashstorm", 10), // No code required new FunSpell("Cults_SpellEcstaticFrenzy", 2), //FINISHED new FunSpell("Cults_SpellStarVampireVisit", 5), //FINISHED new FunSpell("Cults_SpellBlight", 10), // No code required new FunSpell("Cults_SpellNoLongerDomesticated", 2), //FINISHED new FunSpell("Cults_SpellEclipse", 10), //FINISHED new FunSpell("Cults_SpellFoodSpoilage", 10), //FINISHED new FunSpell("Cults_SpellReincarnation", 5), //FINISHED new FunSpell("Cults_SpellAuroraEffect", 5), // FINISHED new FunSpell("Cults_SpellNeedAHand", 5), // FINISHED new FunSpell("Cults_SpellRatsInTheWalls", 5) // FINISHED }; } public void RollTableOfFun(Map map) { var result = TableOfFun.RandomElementByWeight(GetWeight); if (result.defName == "Cults_SpellDoubleTheFun") { Utility.DebugReport("Double The Fun!"); DoubleTheFun(map); return; } var temp = DefDatabase<IncidentDef>.GetNamed(result.defName); if (temp != null) { map.GetComponent<MapComponent_SacrificeTracker>().lastSideEffect = temp; CultUtility.CastSpell(temp, map); return; } Utility.DebugReport("Failed to utilize"); } private void DoubleTheFun(Map map) { var result = TableOfFun.RandomElementByWeight(GetWeight); while (result.defName == "Cults_SpellDoubleTheFun") { result = TableOfFun.RandomElementByWeight(GetWeight); } var temp = DefDatabase<IncidentDef>.GetNamed(result.defName); var result2 = TableOfFun.RandomElementByWeight(GetWeight); while (result2.defName == "Cults_SpellDoubleTheFun") { result2 = TableOfFun.RandomElementByWeight(GetWeight); } var temp2 = DefDatabase<IncidentDef>.GetNamed(result2.defName); if (temp != null && temp2 != null) { map.GetComponent<MapComponent_SacrificeTracker>().wasDoubleTheFun = true; map.GetComponent<MapComponent_SacrificeTracker>().lastSideEffect = temp; map.GetComponent<MapComponent_SacrificeTracker>().lastDoubleSideEffect = temp2; CultUtility.CastSpell(temp, map); CultUtility.CastSpell(temp2, map); return; } Utility.DebugReport("Failed to utilize " + temp); Utility.DebugReport("Failed to utilize " + temp2); } private static float GetWeight(FunSpell spell) { return spell.weight; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/JobGiver_EnterTransporterPawn.cs using System.Collections.Generic; using System.Linq; using Cthulhu; using Verse; using Verse.AI; namespace CultOfCthulhu { // RimWorld.JobGiver_EnterTransporter public class JobGiver_EnterTransportersPawn : ThinkNode_JobGiver { private static readonly List<CompTransporterPawn> tmpTransporters = new List<CompTransporterPawn>(); // I decided to just take one method instead of the entire utility. // RimWorld.TransporterUtility public static void GetTransportersInGroup(int transportersGroup, Map map, List<CompTransporterPawn> outTransporters) { outTransporters.Clear(); if (transportersGroup < 0) { return; } var listSel = from Pawn pawns in map.mapPawns.AllPawnsSpawned where pawns is PawnFlyer select pawns; var list = new List<Pawn>(listSel); foreach (var pawn in list) { var compTransporter = pawn.TryGetComp<CompTransporterPawn>(); if (compTransporter.groupID == transportersGroup) { //Cthulhu.Utility.DebugReport("Added Transporter: " + list[i].Label); outTransporters.Add(compTransporter); } } } //Back to RimWorld.JobGiver_EnterTransporter protected override Job TryGiveJob(Pawn pawn) { Utility.DebugReport("JobGiver_EnterTransporterPawn Called"); var transportersGroup = pawn.mindState.duty.transportersGroup; GetTransportersInGroup(transportersGroup, pawn.Map, tmpTransporters); var compTransporter = FindMyTransporter(tmpTransporters, pawn); return compTransporter == null || !pawn.CanReserveAndReach(compTransporter.parent, PathEndMode.Touch, Danger.Deadly) ? null : new Job(CultsDefOf.Cults_EnterTransporterPawn, compTransporter.parent); } private CompTransporterPawn FindMyTransporter(List<CompTransporterPawn> transporters, Pawn me) { foreach (var compTransporterPawn in transporters) { var leftToLoad = compTransporterPawn.leftToLoad; if (leftToLoad == null) { continue; } foreach (var transferableOneWay in leftToLoad) { if (transferableOneWay.AnyThing is not Pawn) { continue; } var things = transferableOneWay.things; foreach (var thing in things) { if (thing == me) { return compTransporterPawn; } } } } return null; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/LordJob_LoadAndEnterTransportersPawn.cs using Cthulhu; using Verse; using Verse.AI.Group; namespace CultOfCthulhu { public class LordJob_LoadAndEnterTransportersPawn : LordJob { public int transportersGroup = -1; public LordJob_LoadAndEnterTransportersPawn() { Utility.DebugReport("LoadAndEnterTransportersPawn LordJob Constructed"); } public LordJob_LoadAndEnterTransportersPawn(int transportersGroup) { Utility.DebugReport("LoadAndEnterTransportersPawn LordJob Constructed"); this.transportersGroup = transportersGroup; } public override void ExposeData() { Scribe_Values.Look(ref transportersGroup, "transportersGroup"); } public override StateGraph CreateGraph() { var stateGraph = new StateGraph(); var lordToil_LoadAndEnterTransporters = new LordToil_LoadAndEnterTransportersPawn(transportersGroup); stateGraph.StartingToil = lordToil_LoadAndEnterTransporters; var lordToil_End = new LordToil_End(); stateGraph.AddToil(lordToil_End); var transition = new Transition(lordToil_LoadAndEnterTransporters, lordToil_End); transition.AddTrigger(new Trigger_PawnLost()); //transition.AddPreAction(new TransitionAction_Message("MessageFailedToLoadTransportersBecauseColonistLost".Translate(), MessageTypeDefOf.NegativeEvent)); transition.AddPreAction(new TransitionAction_Custom(CancelLoadingProcess)); stateGraph.AddTransition(transition); return stateGraph; } private void CancelLoadingProcess() { var list = lord.Map.listerThings.ThingsInGroup(ThingRequestGroup.Pawn); foreach (var thing in list) { if (thing == null) { continue; } if (thing is not Pawn) { continue; } var compTransporter = thing.TryGetComp<CompTransporterPawn>(); if (compTransporter == null) { continue; } if (compTransporter.groupID != transportersGroup) { continue; } compTransporter.CancelLoad(); break; } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Seed/IncidentWorker_CultSeed_NightmareTree.cs using Cthulhu; using RimWorld; using Verse; namespace CultOfCthulhu { internal class IncidentWorker_CultSeed_NightmareTree : IncidentWorker_CultSeed { public static bool TryFindRandomSpawnCellForPawnNear(IntVec3 root, Map map, out IntVec3 result, int firstTryWithRadius = 4) { if (root.Standable(map) && root.GetFirstPawn(map) == null) { result = root; } else { var rootFogged = root.Fogged(map); var num = firstTryWithRadius; for (var i = 0; i < 3; i++) { if (CellFinder.TryFindRandomReachableCellNear(root, map, num, TraverseParms.For(TraverseMode.NoPassClosedDoors), c => c.Standable(map) && (rootFogged || !c.Fogged(map)) && c.GetFirstPawn(map) == null, null, out result)) { return true; } num *= 2; } num = firstTryWithRadius + 1; while (!CellFinder.TryRandomClosewalkCellNear(root, map, num, out result)) { if (num > map.Size.x / 2 && num > map.Size.z / 2) { result = root; return false; } num *= 2; } } return true; } protected override bool TryExecuteWorker(IncidentParms parms) { if (!(parms.target is Map map)) { return false; } //Create a spawn point for our nightmare Tree if (!Utility.TryFindSpawnCell(CultsDefOf.Cults_MonolithNightmare, map.Center, map, 60, out var intVec)) { Log.Warning("Failed to find spawn point for nightmare tree."); return false; } //Spawn in the nightmare tree. var thing = (Plant) ThingMaker.MakeThing(CultsDefOf.Cults_PlantTreeNightmare); thing.Growth = 1f; GenSpawn.Spawn(thing, intVec.RandomAdjacentCell8Way(), map); //GenPlace.TryPlaceThing(thing, intVec.RandomAdjacentCell8Way(), map, ThingPlaceMode.Near); ////Find the best researcher //Pawn researcher = CultUtility.DetermineBestResearcher(map); ////Clear all jobs for the researcher. ////Give them a new job to investigate the nightmare tree. //if (ModSettings_Data.cultsForcedInvestigation) //If forced investigation is allowed. //{ // Job J = new Job(CultsDefOf.Cults_Investigate, researcher, thing); // researcher.jobs.TryTakeOrderedJob(J); // //researcher.jobs.EndCurrentJob(JobCondition.InterruptForced); //} Find.World.GetComponent<WorldComponent_GlobalCultTracker>().currentSeedState = CultSeedState.NeedSeeing; //map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedPawn = researcher; //map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedTarget = thing; return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Bast/SpellWorker_Inspiration.cs using CultOfCthulhu; using RimWorld; using Verse; namespace BastCult { /// <summary> /// Inspires all colonists with random inspirations. /// </summary> public class SpellWorker_Inspiration : SpellWorker { public override bool CanSummonNow(Map map) { return true; } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; var inspirations = DefDatabase<InspirationDef>.AllDefsListForReading; //Grab all colonists. if (map?.PlayerPawnsForStoryteller == null) { return true; } foreach (var colonist in map.PlayerPawnsForStoryteller) { //Try twice. if (!colonist.mindState.inspirationHandler.TryStartInspiration( inspirations[Rand.Range(0, inspirations.Count)])) { colonist.mindState.inspirationHandler.TryStartInspiration( inspirations[Rand.Range(0, inspirations.Count)]); } } return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Seed/JobDriver_WriteTheBook.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using Cthulhu; using RimWorld; using Verse; using Verse.AI; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class JobDriver_WriteTheBook : JobDriver { private readonly TargetIndex Executioner = TargetIndex.A; private bool atTypeWriter; public override bool TryMakePreToilReservations(bool errorOnFailed) { return true; } protected override IEnumerable<Toil> MakeNewToils() { this.EndOnDespawnedOrNull(Executioner); if (CultUtility.AreOccultGrimoiresAvailable(pawn.Map)) { pawn.Map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedState = CultSeedState.NeedTable; } else { //First, let's try and find a typewriter. //If we find one, let's go to it and start typing. Thing Typewriter = null; if (Utility.IsIndustrialAgeLoaded()) { Utility.DebugReport("Industrial age check"); if (pawn.Map?.listerBuildings != null) { foreach (var thing in pawn.Map.listerBuildings.allBuildingsColonist) { if (thing.def.defName != "Estate_TableTypewriter") { continue; } Typewriter = thing; Utility.DebugReport("Found typewriter"); var gotoDestination = Toils_Goto.GotoCell(Typewriter.InteractionCell, PathEndMode.OnCell); atTypeWriter = true; yield return gotoDestination; goto SkipRoom; } } } //If we don't have a typewriter, then let's go to our personal room or near our bed. var destinationRoom = pawn.ownership.OwnedRoom; Building destinationBed = pawn.ownership.OwnedBed; if (destinationRoom != null) { if (destinationRoom.Cells.TryRandomElement(out var destination)) { if (Utility.IsRandomWalkable8WayAdjacentOf(destination, Map, out var cellInsideRoom)) { var gotoRoom = Toils_Goto.GotoCell(cellInsideRoom, PathEndMode.OnCell); yield return gotoRoom; } } } else if (destinationBed != null) { if (Utility.IsRandomWalkable8WayAdjacentOf(destinationBed.Position, Map, out var cellNearBed)) { var gotoBedArea = Toils_Goto.GotoCell(cellNearBed, PathEndMode.OnCell); yield return gotoBedArea; } } SkipRoom: var altarToil = new Toil {defaultCompleteMode = ToilCompleteMode.Delay}; altarToil.PlaySustainerOrSound(atTypeWriter ? SoundDef.Named("Estate_SoundManualTypewriter") : SoundDef.Named("PencilWriting")); altarToil.WithProgressBarToilDelay(TargetIndex.A); altarToil.defaultDuration = job.def.joyDuration; altarToil.AddPreTickAction(() => { if (Typewriter == null) { return; } pawn.rotationTracker.FaceCell(Typewriter.Position); pawn.GainComfortFromCellIfPossible(); }); altarToil.AddPreInitAction(() => Messages.Message(pawn.LabelCap + "WritingStrangeSymbols".Translate(), MessageTypeDefOf.NeutralEvent)); yield return altarToil; var finishedAction = new Toil { defaultCompleteMode = ToilCompleteMode.Instant, initAction = delegate { Map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedState = CultSeedState.FinishedWriting; } }; yield return finishedAction; AddFinishAction(() => { if (Map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedState == CultSeedState.FinishedWriting) { CultUtility.FinishedTheBook(pawn); } }); } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Hastur/CompTargetEffect_CultMinded.cs using Cthulhu; using RimWorld; using Verse; namespace CultOfCthulhu { public class CompTargetEffect_CultMinded : CompTargetEffect { public override void DoEffectOn(Pawn user, Thing target) { var pawn = (Pawn) target; if (pawn.Dead) { return; } Utility.ApplySanityLoss(pawn, 0.9f); CultUtility.AffectCultMindedness(pawn, 0.99f); Messages.Message("CompTargetEffectCultMinded".Translate( pawn.Label ), MessageTypeDefOf.NeutralEvent); //pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk, null, false, false, null); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Cthulhu/SpellWorker_TerrestrialInsanityWave.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_TerrestrialInsanityWave : SpellWorker { protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport(" //: " + this.def.defName); return true; } public override bool CanSummonNow(Map map) { return true; } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; var listeners = map?.mapPawns.AllPawnsSpawned.FindAll(x => x.RaceProps.intelligence == Intelligence.Humanlike); if (listeners != null) { var unused = new bool[listeners.Count]; } if (listeners == null) { return true; } foreach (var pawn in listeners) { if (pawn.Faction == Faction.OfPlayer || !pawn.Faction.HostileTo(Faction.OfPlayer) || pawn.guest.IsPrisoner) { Utility.ApplySanityLoss(pawn, Rand.Range(0.2f, 0.8f)); } else { var defaultState = MentalStateDefOf.Berserk; var tempRand = Rand.Range(1, 10); switch (tempRand) { case 1: case 2: case 3: case 4: case 5: case 6: break; case 7: case 8: case 9: defaultState = MentalStateDefOf.PanicFlee; break; case 10: defaultState = CultsDefOf.FireStartingSpree; break; } Utility.ApplySanityLoss(pawn, 1.0f); pawn.mindState.mentalStateHandler.TryStartMentalState(defaultState); } } return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/WorldComponent_GlobalCultTracker.cs using System.Collections.Generic; using System.Linq; using RimWorld; using RimWorld.Planet; using Verse; namespace CultOfCthulhu { public static class CultTracker { public static WorldComponent_GlobalCultTracker Get => Find.World.GetComponent<WorldComponent_GlobalCultTracker>(); } public enum CultSeedState { NeedSeed = 0, NeedSeeing = 1, FinishedSeeing = 2, NeedWriting = 3, FinishedWriting = 4, NeedTable = 5 } public class WorldComponent_GlobalCultTracker : WorldComponent { public readonly List<ResearchProjectDef> cultResearch = new List<ResearchProjectDef> { ResearchProjectDef.Named("Forbidden_Studies"), ResearchProjectDef.Named("Forbidden_Deities"), ResearchProjectDef.Named("Forbidden_Lore"), ResearchProjectDef.Named("Forbidden_Sculptures"), ResearchProjectDef.Named("Forbidden_Attire"), ResearchProjectDef.Named("Forbidden_Altar"), ResearchProjectDef.Named("Forbidden_Sacrifice"), ResearchProjectDef.Named("Forbidden_Human"), ResearchProjectDef.Named("Forbidden_Obelisks"), ResearchProjectDef.Named("Forbidden_Reports") }; public List<Pawn> antiCultists = new List<Pawn>(); public Dictionary<Pawn, CultistExperience> cultistExperiences = new Dictionary<Pawn, CultistExperience>(); public CultSeedState currentSeedState = CultSeedState.NeedSeed; public bool doingInquisition = false; public bool exposedToCults; public bool needPreacher = false; public int numHumanSacrifices = 0; private List<CultistExperience> workingInts = new List<CultistExperience>(); private List<Pawn> workingPawns = new List<Pawn>(); public List<Cult> worldCults; public WorldComponent_GlobalCultTracker(World world) : base(world) { worldCults = new List<Cult>(); } public bool ExposedToCults { get => exposedToCults; set { if (value != exposedToCults && value) { Find.LetterStack.ReceiveLetter("Cults_InitialExposureLabel".Translate(), "Cults_InitialExposureDesc".Translate(), CultsDefOf.Cults_StandardMessage, null); } exposedToCults = value; } } public Cult PlayerCult { get { Cult result = null; if (worldCults != null && worldCults.Count > 0) { result = worldCults.FirstOrDefault(x => x.foundingFaction == Faction.OfPlayerSilentFail); } return result; } } public override void ExposeData() { base.ExposeData(); Scribe_Collections.Look(ref worldCults, "worldCults", LookMode.Deep); Scribe_Collections.Look(ref antiCultists, "antiCultists", LookMode.Reference); Scribe_Values.Look(ref currentSeedState, "CurrentSeedState"); Scribe_Values.Look(ref exposedToCults, "exposedToCults"); //Scribe_Collections.Look<Pawn, int[]>(ref this.cultistExperiences, "cultistExperiences", LookMode.Reference, LookMode.Value); if (Scribe.mode == LoadSaveMode.Saving) { workingPawns = new List<Pawn>(); workingInts = new List<CultistExperience>(); if (cultistExperiences != null && cultistExperiences?.Count > 0) { foreach (var keyPair in cultistExperiences) { workingPawns.Add(keyPair.Key); workingInts.Add(keyPair.Value); } } } Scribe_Collections.Look(ref workingPawns, "workingPawns", LookMode.Reference); Scribe_Collections.Look(ref workingInts, "workingInts", LookMode.Deep); if (Scribe.mode != LoadSaveMode.PostLoadInit) { return; } cultistExperiences = new Dictionary<Pawn, CultistExperience>(); for (var i = 0; i < workingPawns.Count; i++) { cultistExperiences.Add(workingPawns[i], workingInts[i]); } } public void GainExperience(Pawn p, bool carriedOutSacrifice = false) { if (cultistExperiences == null || cultistExperiences?.Count == 0) { cultistExperiences = new Dictionary<Pawn, CultistExperience>(); } if (!cultistExperiences?.ContainsKey(p) ?? true) { cultistExperiences.Add(p, new CultistExperience(0, 0)); } if (!carriedOutSacrifice) { cultistExperiences[p].PreachCount += 1; } else { cultistExperiences[p].SacrificeCount += 1; } } public int GetExperience(Pawn p, bool sacrifice = false) { if (cultistExperiences == null) { cultistExperiences = new Dictionary<Pawn, CultistExperience>(); } if (!cultistExperiences.ContainsKey(p)) { cultistExperiences.Add(p, new CultistExperience(0, 0)); } return !sacrifice ? cultistExperiences[p].PreachCount : cultistExperiences[p].SacrificeCount; } public Cult LocalDominantCult(Map map) { Cult result = null; var settlement = Find.WorldObjects.SettlementAt(map.Tile); if (settlement == null) { return null; } if (worldCults.Count > 0) { result = worldCults.FirstOrDefault(x => x.influences.FirstOrDefault(y => y.settlement == settlement && y.dominant) != null); } return result; } public void RemoveInquisitor(Pawn inquisitor) { if (antiCultists == null) { return; } if (antiCultists.Count == 0) { return; } var tempList = new List<Pawn>(antiCultists); foreach (var current in tempList) { if (current == inquisitor) { antiCultists.Remove(inquisitor); } } } public void SetInquisitor(Pawn antiCultist) { // Is the list missing? Let's fix that. if (antiCultists == null) { antiCultists = new List<Pawn>(); } //Does this member already exist as part of the anti cultists? //If so, don't add them. if (Enumerable.Any(antiCultists, current => current == antiCultist)) { return; } //Are they a prisoner? We don't want those in the list. if (!antiCultist.IsColonist) { return; } //Add the anti-cultist to the list. antiCultists.Add(antiCultist); //If the cult already exists, show a message to initiate the pawn into the inquisitor faction. if (PlayerCult == null || !PlayerCult.active) { return; } Messages.Message( "Cults_InquisitionPlotBegins".Translate(antiCultist.LabelShort, PlayerCult.name), MessageTypeDefOf.PositiveEvent); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Seed/Building_Monolith.cs using System.Collections.Generic; using System.Reflection; using RimWorld; using UnityEngine; using Verse; using Verse.AI; using Verse.Sound; namespace CultOfCthulhu { public class Building_Monolith : Building { private bool isMuted; public Thought_Memory GiveObservedThought() { if (this.StoringThing() != null) { return null; } var thought_MemoryObservation = (Thought_MemoryObservation) ThoughtMaker.MakeThought( DefDatabase<ThoughtDef>.GetNamed("Cults_ObservedNightmareMonolith")); thought_MemoryObservation.Target = this; var Dave = thought_MemoryObservation.pawn; if (Dave == null) { return null; } if (!Dave.IsColonist) { return thought_MemoryObservation; } if (Dave.needs.TryGetNeed<Need_CultMindedness>().CurLevel > 0.7) { thought_MemoryObservation = (Thought_MemoryObservation) ThoughtMaker.MakeThought( DefDatabase<ThoughtDef>.GetNamed("Cults_ObservedNightmareMonolithCultist")); } return thought_MemoryObservation; } public override IEnumerable<FloatMenuOption> GetFloatMenuOptions(Pawn myPawn) { using var enumerator = base.GetFloatMenuOptions(myPawn).GetEnumerator(); while (enumerator.MoveNext()) { var current = enumerator.Current; yield return current; } if (def == null || this is not Building_Monolith) { yield break; } if (!def.hasInteractionCell) { yield break; } if (CultUtility.AreCultObjectsAvailable(Map)) { yield break; } if (CultUtility.IsSomeoneInvestigating(Map)) { yield break; } if (!Map.reservationManager.CanReserve(myPawn, this)) { yield break; } void action0() { var job = new Job(CultsDefOf.Cults_Investigate, myPawn, this) { playerForced = true }; myPawn.jobs.TryTakeOrderedJob(job); //mypawn.CurJob.EndCurrentJob(JobCondition.InterruptForced); } yield return new FloatMenuOption("Investigate", action0); } private void MuteToggle() { isMuted = !isMuted; if (isMuted) { var sustainer = (Sustainer) typeof(Building) .GetField("sustainerAmbient", BindingFlags.Instance | BindingFlags.NonPublic) ?.GetValue(this); sustainer?.End(); } else { _ = (Sustainer) typeof(Building) .GetField("sustainerAmbient", BindingFlags.Instance | BindingFlags.NonPublic) ?.GetValue(this); var info = SoundInfo.InMap(this); _ = new Sustainer(def.building.soundAmbient, info); } } public override IEnumerable<Gizmo> GetGizmos() { using var enumerator = base.GetGizmos().GetEnumerator(); while (enumerator.MoveNext()) { var current = enumerator.Current; yield return current; } var toggleDef = new Command_Toggle { hotKey = KeyBindingDefOf.Command_TogglePower, icon = ContentFinder<Texture2D>.Get("UI/Icons/Commands/Mute"), defaultLabel = "Mute".Translate(), defaultDesc = "MuteDesc".Translate(), isActive = () => isMuted, toggleAction = MuteToggle }; yield return toggleDef; } public override void ExposeData() { base.ExposeData(); // Save and load the work variables, so they don't default after loading Scribe_Values.Look(ref isMuted, "isMuted"); } } }<file_sep>/Source/CultOfCthulhu/Unused/IncidentWorker_MakeCultMapCondition.cs using RimWorld; using Verse; namespace CultOfCthulhu { public class IncidentWorker_MakeCultGameCondition : IncidentWorker_MakeGameCondition { protected override bool CanFireNowSub(IncidentParms parms) { //Map map = (Map)parms.target; _ = Find.Maps; var cultConditionActive = Find.World.GameConditionManager.ConditionIsActive(CultsDefOf.CultgameCondition_StarsAreWrong) || Find.World.GameConditionManager.ConditionIsActive(CultsDefOf.CultgameCondition_StarsAreRight); var cultAvailable = CultTracker.Get.PlayerCult != null && CultTracker.Get.PlayerCult.active; return cultAvailable && !cultConditionActive && base.CanFireNowSub(parms); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/GameCondition_AuroraEffect.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using RimWorld; using UnityEngine; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class GameCondition_AuroraEffect : GameCondition { private static ColorInt colorInt = new ColorInt(0, 141, 153); //Green private static ColorInt colorInt2 = new ColorInt(141, 0, 153); //Purple private static ColorInt transition = new ColorInt(0, 141, 153); //Green private readonly int LerpTicks = 200; private readonly int switchTicks = 5000; private SkyColorSet AuroraSkyColors = new SkyColorSet(transition.ToColor, Color.white, new Color(0.6f, 0.6f, 0.6f), 0.8f); private bool firstTick = true; private float Green; private float Red = 141f; private int switchCount = 5000; private bool switchTime; public override string Label { get { string temp; if (Find.WorldGrid.LongLatOf(Find.CurrentMap.Tile).y >= 74) { temp = " " + "Borealis".Translate(); } else { temp = " " + "Australis".Translate(); } return def.label + temp; } } public override float SkyTargetLerpFactor(Map map) { return GameConditionUtility.LerpInOutValue(TicksPassed, TicksLeft, LerpTicks); } public override void GameConditionTick() { base.GameConditionTick(); var affectedMaps = AffectedMaps; if (firstTick) { foreach (var map in affectedMaps) { foreach (var pawn in map.mapPawns.FreeColonistsAndPrisoners) { if (!pawn.Position.Roofed(map) && pawn.def.race.IsFlesh) { pawn.needs.mood.thoughts.memories.TryGainMemory(CultsDefOf.Cults_SawAurora); } } } firstTick = false; } foreach (var map in affectedMaps) { foreach (var unused in map.mapPawns.FreeColonistsAndPrisoners) { if (!switchTime) { Red -= 0.03f; Green += 0.03f; transition.r = (int) Red; transition.g = (int) Green; AuroraSkyColors = new SkyColorSet(transition.ToColor, Color.white, new Color(0.6f, 0.6f, 0.6f), 0.8f); SkyTarget(map); } if (switchTime) { Red += 0.03f; Green -= 0.03f; transition.r = (int) Red; transition.g = (int) Green; AuroraSkyColors = new SkyColorSet(transition.ToColor, Color.white, new Color(0.6f, 0.6f, 0.6f), 0.8f); SkyTarget(map); } if (switchCount >= 0) { switchCount -= 1; } else { switchCount = switchTicks; switchTime = !switchTime; } } } } public override SkyTarget? SkyTarget(Map map) { return new SkyTarget(0.85f, AuroraSkyColors, 1f, 1f); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Sacrifice/MapComponent_SacrificeTracker.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using System.Text; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public partial class MapComponent_SacrificeTracker : MapComponent { public static int resurrectionTicks = 10000; public bool ASMwasBonded; public bool ASMwasExcMaster; public bool ASMwasPet; /// Defend the Brood Variables public List<Pawn> defendTheBroodPawns = new List<Pawn>(); public bool HSMwasFamily; public IncidentDef lastDoubleSideEffect; public IntVec3 lastLocation = IntVec3.Invalid; public CultUtility.OfferingSize lastOfferingSize = CultUtility.OfferingSize.none; public PawnRelationDef lastRelation; public CultUtility.SacrificeResult lastResult = CultUtility.SacrificeResult .success; // Default is a success, so that in-case of a bug, it's a positive bug. public string lastSacrificeName = ""; public CultUtility.SacrificeType lastSacrificeType = CultUtility.SacrificeType.none; public IncidentDef lastSideEffect; public IncidentDef lastSpell; public Building_SacrificialAltar lastUsedAltar; //Default public int ticksUntilResurrection = -999; /// Unspeakable Oath Variables public List<Pawn> toBeResurrected = new List<Pawn>(); /// Sacrifice Tracker Variables //public List<Pawn> lastSacrificeCongregation = new List<Pawn>(); public List<Pawn> unspeakableOathPawns = new List<Pawn>(); public bool wasDoubleTheFun; public MapComponent_SacrificeTracker(Map map) : base(map) { this.map = map; } public override void MapComponentTick() { base.MapComponentTick(); ResolveHasturOathtakers(); ResolveHasturResurrections(); } public override void ExposeData() { //Unspeakable Oath Spell Scribe_Values.Look(ref ticksUntilResurrection, "ticksUntilResurrection", -999); //Scribe_Collections.Look<Corpse>(ref this.toBeResurrected, "toBeResurrected", LookMode.Reference); Scribe_Collections.Look(ref unspeakableOathPawns, "unspeakableOathPawns", LookMode.Reference); //Defend the Brood Spell Scribe_Collections.Look(ref defendTheBroodPawns, "defendTheBroodPawns", LookMode.Reference); //Sacrifice Variables Scribe_Values.Look(ref lastSacrificeName, "lastSacrificeName", "None"); Scribe_Values.Look(ref wasDoubleTheFun, "wasDoubleTheFun"); Scribe_Values.Look(ref ASMwasPet, "ASMwasPet"); Scribe_Values.Look(ref ASMwasBonded, "ASMwasBonded"); Scribe_Values.Look(ref ASMwasExcMaster, "ASMwasExcMaster"); Scribe_Values.Look(ref HSMwasFamily, "HSMwasFamily"); Scribe_Values.Look(ref lastLocation, "lastLocation", IntVec3.Invalid); Scribe_Defs.Look(ref lastRelation, "lastRelation"); Scribe_Defs.Look(ref lastDoubleSideEffect, "lastDoubleSideEffect"); Scribe_Defs.Look(ref lastSideEffect, "lastSideEffect"); Scribe_Defs.Look(ref lastSpell, "lastSpell"); Scribe_References.Look(ref lastUsedAltar, "lastUsedAltar"); Scribe_Values.Look(ref lastResult, "lastResult", CultUtility.SacrificeResult.success); Scribe_Values.Look(ref lastSacrificeType, "lastSacrificeType"); Scribe_Values.Look(ref lastOfferingSize, "lastOfferingSize"); base.ExposeData(); } //In-case our component injector doesn't pick up the map component, //this method causes a new map component to be generated from a static method. public static MapComponent_SacrificeTracker Get(Map map) { var mapComponent_SacrificeTracker = map.components.OfType<MapComponent_SacrificeTracker>().FirstOrDefault(); if (mapComponent_SacrificeTracker != null) { return mapComponent_SacrificeTracker; } mapComponent_SacrificeTracker = new MapComponent_SacrificeTracker(map); map.components.Add(mapComponent_SacrificeTracker); return mapComponent_SacrificeTracker; } public void ClearSacrificeVariables() { lastUsedAltar.tempSacrifice = null; lastResult = CultUtility.SacrificeResult.none; // Default lastSacrificeType = CultUtility.SacrificeType.none; lastUsedAltar = null; //Default lastSideEffect = null; lastLocation = IntVec3.Invalid; wasDoubleTheFun = false; lastDoubleSideEffect = null; //lastSacrificeCongregation = null; lastRelation = null; lastSacrificeName = ""; ASMwasPet = false; ASMwasBonded = false; ASMwasExcMaster = false; HSMwasFamily = false; } public string GenerateFailureString() { var s = new StringBuilder(); var ran = Rand.Range(1, 40); var message = "SacrificeFailMessage" + ran; string messageObject = message.Translate(lastUsedAltar.SacrificeData.Executioner); s.Append(messageObject); return s.ToString(); } public void GenerateSacrificeMessage() { var s = new StringBuilder(); var letterDef = LetterDefOf.ThreatSmall; s.Append("SacrificeIntro".Translate()); s.Append(" " + lastUsedAltar.SacrificeData.Entity.Label); string labelToTranslate; string textLabel; //The sacrifice is human if (lastUsedAltar.SacrificeData.Type == CultUtility.SacrificeType.human) { s.Append(" " + lastUsedAltar.SacrificeData.Spell.letterLabel + ". "); //Was the executioner a family member? if (HSMwasFamily) { if (lastUsedAltar.SacrificeData.Executioner == null) { Log.Error("Executioner null"); } if (lastRelation == null) { Log.Error("Null relation"); } if (lastSacrificeName == null) { Log.Error("Null name"); } string familyString = "HumanSacrificeWasFamily".Translate( lastUsedAltar.SacrificeData.Executioner?.LabelShort, lastUsedAltar.SacrificeData.Executioner?.gender.GetPossessive(), lastRelation?.label, lastSacrificeName ); s.Append(familyString + ". "); } if (lastResult != CultUtility.SacrificeResult.success) { s.Append(GenerateFailureString()); } if ((int) lastResult <= 3 && (int) lastResult > 1) { s.Append(" " + lastSideEffect.letterText); if (wasDoubleTheFun) { s.Append(" " + lastDoubleSideEffect.letterText); } } if (lastResult == CultUtility.SacrificeResult.mixedsuccess) { var buts = new List<string> { "Cults_butsOne".Translate(), "Cults_butsTwo".Translate(), "Cults_butsThree".Translate(), "Cults_butsFour".Translate() }; s.Append(". " + buts.RandomElement() + ", "); } if ((int) lastResult > 2) { s.Append(lastUsedAltar.SacrificeData.Executioner + " " + lastUsedAltar.SacrificeData.Spell.letterText + "."); } s.Append(" " + "Cults_ritualWas".Translate()); switch (lastResult) { case CultUtility.SacrificeResult.success: s.Append("Cults_ritualSuccess".Translate()); letterDef = CultsDefOf.Cults_StandardMessage; break; case CultUtility.SacrificeResult.mixedsuccess: letterDef = CultsDefOf.Cults_StandardMessage; s.Append("Cults_ritualMixedSuccess".Translate()); break; case CultUtility.SacrificeResult.failure: s.Append("Cults_ritualFailure".Translate()); break; case CultUtility.SacrificeResult.criticalfailure: s.Append("Cults_ritualCompleteFailure".Translate()); break; case CultUtility.SacrificeResult.none: s.Append("this should never happen"); break; } labelToTranslate = "SacrificeLabel" + lastResult; } else if (lastUsedAltar.SacrificeData.Type == CultUtility.SacrificeType.animal) { s.Append(" " + "AnimalSacrificeReason".Translate() + "."); if (ASMwasPet) { s.Append(" " + "AnimalSacrificeWasPet".Translate() + lastUsedAltar.SacrificeData.Entity.Label + "."); } if (ASMwasBonded) { string bondString = "AnimalSacrificeWasBonded".Translate( lastSacrificeName, lastUsedAltar.SacrificeData.Executioner.LabelShort ); s.Append(" " + bondString + "."); } if (ASMwasExcMaster) { string bondString = "AnimalSacrificeWasExcMaster".Translate( lastSacrificeName, lastUsedAltar.SacrificeData.Executioner.LabelShort ); s.Append(" " + bondString + "."); } if (ASMwasBonded || ASMwasPet || ASMwasExcMaster) { s.Append(" " + "GreedilyReceived".Translate() + lastUsedAltar.SacrificeData.Entity.Label + "."); } else { s.Append(" " + "ReadilyReceived".Translate() + "."); } textLabel = "AnimalSacrificeLabel".Translate(); goto LetterStack; } else { s.Append(" " + "OfferingReason".Translate() + "."); s.Append(" " + "ReadilyReceived".Translate() + "."); textLabel = "OfferingLabel".Translate(); goto LetterStack; } textLabel = labelToTranslate.Translate(); LetterStack: Find.LetterStack.ReceiveLetter(textLabel, s.ToString(), letterDef, new TargetInfo(lastLocation, map)); } } }<file_sep>/Source/CultOfCthulhu/MentalBreaks/MentalState_Disillusioned.cs using RimWorld; using Verse; using Verse.AI; namespace CultOfCthulhu { public class MentalState_Disillusioned : MentalState { public override RandomSocialMode SocialModeMax() { return RandomSocialMode.Off; } public override void MentalStateTick() { base.MentalStateTick(); if (pawn.IsHashIntervalTick(1000)) { CultUtility.AffectCultMindedness(pawn, -0.05f); //Cthulhu.Utility.ApplySanityLoss(this.pawn, -0.05f); } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Building_ForbiddenReserachCenter.cs using System.Text; using Cthulhu; using RimWorld; using Verse; using Verse.AI; namespace CultOfCthulhu { internal class Building_ForbiddenReserachCenter : Building_ResearchBench { private const float MaxCultMindedBoost = 0.9f; private const float MaxSanityLoss = 0.9f; private const float SocialSkillBoost = 75f; private bool initialTick; private bool StartedUse; private Pawn storedPawn; private WarningLevel warningLevel = WarningLevel.None; private Pawn InteractingPawn { get { Pawn pawn = null; foreach (var p in Map.mapPawns.FreeColonistsSpawned) { if (p.Position != InteractionCell || p.CurJob.def != JobDefOf.Research) { continue; } pawn = p; break; } if (pawn == null) { StartedUse = false; } return pawn; } } public override void ExposeData() { base.ExposeData(); Scribe_References.Look(ref storedPawn, "storedPawn"); } public override void SpawnSetup(Map map, bool bla) { base.SpawnSetup(map, bla); DeityTracker.Get.orGenerate(); } public override void TickRare() { base.TickRare(); InitialTickHandler(); ForbiddenChecker(); ResolveNonOccultProjects(); GiveInteractionSanityLoss(); } private void InitialTickHandler() { if (initialTick) { return; } initialTick = true; CultTracker.Get.ExposedToCults = true; } private void ForbiddenChecker() { var currentProject = Find.ResearchManager.currentProj; if (currentProject == null) { return; } this.SetForbidden(false); if (IsThisCultistResearch(currentProject)) { return; } this.SetForbidden(true); } public override string GetInspectString() { var s = new StringBuilder(); s.Append(base.GetInspectString()); //s.AppendLine(); s.AppendLine("Cults_AutoForbidWarning".Translate()); var result = s.ToString(); result = result.TrimEndNewlines(); return result; } private void ResolveNonOccultProjects() { //First, declare our variables. var currentProject = Find.ResearchManager.currentProj; var interactingPawn = InteractingPawn; if (currentProject == null) { return; } if (interactingPawn == null) { return; } if (Find.World.GetComponent<WorldComponent_GlobalCultTracker>().cultResearch == null) { return; } //Are we using this for the correct project type? this.SetForbidden(false); if (IsThisCultistResearch(currentProject)) { return; } this.SetForbidden(true); //Uh oh. //Let's try and find another research station to research this at. Building_ResearchBench bench = null; foreach (var bld in Map.listerBuildings.allBuildingsColonist) { if (bld == this || bld.def == def) { continue; } if (bld is Building_ResearchBench researchBench) { bench = researchBench; } } //No building found? Cancel the research projects. if (bench == null) { CancelResearch("Cannot use the grimoire to research standard research projects."); return; } //We found a research bench! Can we send the researcher there? if (!currentProject.CanBeResearchedAt(bench, false)) { CancelResearch("Cannot research this project at the forbidden center."); } if (!interactingPawn.CanReach(bench, PathEndMode.ClosestTouch, Danger.Deadly)) { CancelResearch("Cannot research this project at the forbidden center."); } if (!interactingPawn.CanReserve(bench)) //Map.reservationManager.IsReserved(bench, Faction.OfPlayer)) { this.SetForbidden(true); interactingPawn.jobs.EndCurrentJob(JobCondition.InterruptForced); return; } //Okay, assign a job over there instead of here. var J = new Job(JobDefOf.Research, bench); Map.reservationManager.ReleaseAllClaimedBy(interactingPawn); interactingPawn.jobs.TryTakeOrderedJob(J); //interactingpawn.CurJob.EndCurrentJob(JobCondition.InterruptForced); } private void CancelResearch(string reason) { if (reason != null) { Messages.Message(reason, MessageTypeDefOf.RejectInput); } Find.ResearchManager.currentProj = null; Find.ResearchManager.ReapplyAllMods(); Messages.Message("Research cancelled.", MessageTypeDefOf.SilentInput); } private bool IsThisCultistResearch(ResearchProjectDef currentProject) { foreach (var researchProjectDef in Find.World.GetComponent<WorldComponent_GlobalCultTracker>().cultResearch) { if (currentProject == researchProjectDef) { return true; } } return false; } private void GiveInteractionSanityLoss() { var temp = InteractingPawn; var currentProject = Find.ResearchManager.currentProj; var modifier = 0.0040f; if (temp == null) { return; } if (currentProject == null) { return; } if (!IsThisCultistResearch(currentProject)) { return; } UsageWarning(temp); if (Find.ResearchManager.currentProj == ResearchProjectDef.Named("Forbidden_Lore")) { modifier *= 1.2f; temp.skills.Learn(SkillDefOf.Social, SocialSkillBoost); } Utility.ApplySanityLoss(temp, modifier, MaxSanityLoss); CultUtility.AffectCultMindedness(temp, modifier, MaxCultMindedBoost); } private void UsageWarning(Pawn temp) { var sanityLevel = Utility.CurrentSanityLoss(temp); if (storedPawn != temp) { storedPawn = temp; warningLevel = WarningLevel.None; } SetWarningLevel(sanityLevel); if (StartedUse) { return; } StartedUse = true; var stringToTranslate = "OccultCenterWarning" + warningLevel; if (stringToTranslate == "OccultCenterWarningNone") { return; } Messages.Message(stringToTranslate.Translate( InteractingPawn.Name.ToStringShort, InteractingPawn.gender.GetPronoun(), InteractingPawn.gender.GetObjective(), InteractingPawn.gender.GetPossessive() ), MessageTypeDefOf.NeutralEvent); } private void SetWarningLevel(float sanityLevel) { if ((int) warningLevel < 1 && sanityLevel > SanityLossSeverity.Initial) { StartedUse = false; warningLevel = WarningLevel.One; } if ((int) warningLevel < 2 && sanityLevel > SanityLossSeverity.Minor) { StartedUse = false; warningLevel = WarningLevel.Two; } if ((int) warningLevel < 3 && sanityLevel > SanityLossSeverity.Major) { StartedUse = false; warningLevel = WarningLevel.Three; } if ((int) warningLevel >= 4 || !(sanityLevel > SanityLossSeverity.Severe)) { return; } StartedUse = false; warningLevel = WarningLevel.Four; } private enum WarningLevel { None = 0, One = 1, Two = 2, Three = 3, Four = 4 } } }<file_sep>/Source/CultOfCthulhu/MapComponentInjector.cs using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using Verse; namespace Cthulhu { [StaticConstructorOnStartup] public class MapComponentInjectorBehavior : MonoBehaviour { private static readonly List<Type> mapComponents; private int lastTicks; protected bool monstrousDefsAdded = false; private float reinjectTime; static MapComponentInjectorBehavior() { var initializer = new GameObject("JecrellMapCompInjector"); initializer.AddComponent<MapComponentInjectorBehavior>(); DontDestroyOnLoad(initializer); mapComponents = new List<Type>(); typeof(MapComponentInjectorBehavior).Assembly.GetTypes() .Where(t => t.IsClass && t.IsSubclassOf(typeof(MapComponent))).ToList() .ForEach(t => mapComponents.Add(t)); //mapComponents.ForEach((Type t) => Log.Message(t.Name + "found for MapComponentInjector")); } public void FixedUpdate() { try { if (Find.TickManager == null) { return; } if (Find.TickManager.TicksGame <= lastTicks + 10) { return; } lastTicks = Find.TickManager.TicksGame; reinjectTime -= Time.fixedDeltaTime; if (!(reinjectTime <= 0)) { return; } reinjectTime = 0; if (Find.Maps != null) { Find.Maps.ForEach(delegate(Map map) { if (map.components != null) { mapComponents.ForEach(delegate(Type t) { if (map.components.Any(mp => mp.GetType() == t)) { return; } var comp = (MapComponent) typeof(MapComponent) .GetConstructor(Type.EmptyTypes) ?.Invoke(new object[] {map}); map.components.Add(comp); }); } }); } } catch { // ignored } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Fertility/Building_TotemFertility.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using RimWorld; using UnityEngine; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') //using Verse.AI; // Needed when you do something with the AI //using Verse.AI.Group; //using Verse.Sound; // Needed when you do something with Sound //using Verse.Noise; // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') //using RimWorld.Planet; // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class Building_TotemFertility : Building { public bool cellsDirty; public float daysUntilDestroyed = GenDate.DaysPerQuadrum * 2; public float fertilityBonus = 0.5f; public float fertilityMax = 2.0f; private List<IntVec3> tempCells; public float ticksUntilDestroyed = float.MinValue; public List<IntVec3> GrowableCells { get { if (!tempCells.NullOrEmpty() && !cellsDirty) { return tempCells; } cellsDirty = false; tempCells = new List<IntVec3>(GenRadial.RadialCellsAround(Position, def.specialDisplayRadius, true)); return tempCells; } } private int TicksUntilDisappearing { get { if (ticksUntilDestroyed == float.MinValue) { ticksUntilDestroyed = ticksUntilDestroyed = daysUntilDestroyed * 60000f; } return Mathf.RoundToInt(ticksUntilDestroyed); } } public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref ticksUntilDestroyed, "ticksUntilDestroyed", -1f); Scribe_Values.Look(ref daysUntilDestroyed, "daysUntilDestroyed", 7f); Scribe_Values.Look(ref fertilityBonus, "fertilityBonus", 1.5f); } public override void Tick() { base.Tick(); if (!(ticksUntilDestroyed > 0)) { return; } if (ticksUntilDestroyed < 100) { DeSpawn(); } else { ticksUntilDestroyed -= 1; } } public override string GetInspectString() { var stringBuilder = new StringBuilder(); // Add the inspections string from the base stringBuilder.Append(base.GetInspectString()); if (stringBuilder.Length != 0) { stringBuilder.AppendLine(); } if (!stringBuilder.ToString().Contains("installed")) { stringBuilder.Append("FertilityTotemTimer".Translate( TicksUntilDisappearing.ToStringTicksToPeriodVague() )); } return stringBuilder.ToString().TrimEndNewlines(); } public override void SpawnSetup(Map map, bool bla) { base.SpawnSetup(map, bla); var temp = new List<IntVec3>(); foreach (var vec in GrowableCells) { temp.Add(vec); } map.GetComponent<MapComponent_FertilityMods>().FertilityTotems.Add(this); map.GetComponent<MapComponent_FertilityMods>().FertilizeCells(temp); cellsDirty = true; } public override void DeSpawn(DestroyMode mode = DestroyMode.Vanish) { var map = Map; base.DeSpawn(mode); var temp = new List<IntVec3>(); foreach (var vec in GrowableCells) { temp.Add(vec); } map.GetComponent<MapComponent_FertilityMods>().FertilityTotems.Remove(this); map.GetComponent<MapComponent_FertilityMods>().UnfertilizeCells(temp); cellsDirty = true; } [DebuggerHidden] public override IEnumerable<Gizmo> GetGizmos() { using var enumerator = base.GetGizmos().GetEnumerator(); while (enumerator.MoveNext()) { var current = enumerator.Current; yield return current; } yield return new Command_Action { action = MakeMatchingGrowZone, hotKey = KeyBindingDefOf.Misc2, defaultDesc = "CommandSunLampMakeGrowingZoneDesc".Translate(), icon = ContentFinder<Texture2D>.Get("UI/Designators/ZoneCreate_Growing"), defaultLabel = "CommandSunLampMakeGrowingZoneLabel".Translate() }; } private void MakeMatchingGrowZone() { var designator = new Designator_ZoneAdd_Growing(); designator.DesignateMultiCell(from tempCell in GrowableCells where designator.CanDesignateCell(tempCell).Accepted select tempCell); } } }<file_sep>/Source/CultOfCthulhu/UI/Dialog_RenameTemple.cs using Verse; namespace CultOfCthulhu { public class Dialog_RenameTemple : Dialog_Rename { private readonly Building_SacrificialAltar altar; private readonly Map map; public Dialog_RenameTemple(Building_SacrificialAltar altar) { this.altar = altar; curName = altar.RoomName; map = altar.Map; } protected override AcceptanceReport NameIsValid(string name) { var result = base.NameIsValid(name); if (!result.Accepted) { return result; } return name.Length == 0 || name.Length > 27 ? "NameIsInvalid".Translate() : (AcceptanceReport) true; } protected override void SetName(string name) { altar.RoomName = name; } } }<file_sep>/Source/CultOfCthulhu/Cults_Screen_Credits.cs using System.Collections.Generic; using System.Linq; using RimWorld; using UnityEngine; using Verse; namespace CultOfCthulhu { public class Cults_Screen_Credits : Window { private const int ColumnWidth = 800; private const float InitialAutoScrollDelay = 1f; private const float InitialAutoScrollDelayWonGame = 6f; private const float AutoScrollDelayAfterManualScroll = 3f; private const float SongStartDelay = 5f; private readonly List<CreditsEntry> creds; private readonly float MessageDelay; private float creationRealtime = -1f; private bool playedMusic; private float scrollPosition; private float timeUntilAutoScroll; public bool wonGame; public Cults_Screen_Credits() : this(string.Empty) { } public Cults_Screen_Credits(string preCreditsMessage, float DelayBooster = 0f) { doWindowBackground = false; doCloseButton = false; doCloseX = false; forcePause = true; creds = CreditsAssembler.AllCredits().ToList(); creds.Insert(0, new CreditRecord_Space(100f)); if (!preCreditsMessage.NullOrEmpty()) { creds.Insert(1, new CreditRecord_Space(100f)); creds.Insert(2, new CreditRecord_Text(preCreditsMessage)); creds.Insert(3, new CreditRecord_Space(50f)); } //Main team creds.Insert(4, new CreditRecord_Space(100f)); creds.Insert(5, new CreditRecord_Title("Rim of Madness")); creds.Insert(6, new CreditRecord_Space(50f)); creds.Insert(7, new CreditRecord_Text("Team Members (In Alphabetical Order)", TextAnchor.UpperCenter)); creds.Insert(8, new CreditRecord_Space(50f)); creds.Insert(9, new CreditRecord_Role("CoercionRole".Translate(), "Coercion")); creds.Insert(10, new CreditRecord_Space(50f)); creds.Insert(11, new CreditRecord_Role("DrynynRole".Translate(), "Drynyn")); creds.Insert(12, new CreditRecord_Space(50f)); creds.Insert(13, new CreditRecord_Role("erdelfRole".Translate(), "erdelf")); // new creds.Insert(14, new CreditRecord_Space(50f)); creds.Insert(15, new CreditRecord_Role("JareixRole".Translate(), "Jareix")); creds.Insert(16, new CreditRecord_Space(50f)); creds.Insert(17, new CreditRecord_Role("JecrellRole".Translate(), "Jecrell")); creds.Insert(18, new CreditRecord_Space(50f)); creds.Insert(19, new CreditRecord_Role("JunkyardJoeRole".Translate(), "<NAME>")); creds.Insert(20, new CreditRecord_Space(50f)); creds.Insert(21, new CreditRecord_Role("spoonshortageRole".Translate(), "spoonshortage")); // new creds.Insert(22, new CreditRecord_Space(50f)); creds.Insert(23, new CreditRecord_Role("SticksNTricksRole".Translate(), "SticksNTricks")); // new creds.Insert(24, new CreditRecord_Space(50f)); creds.Insert(25, new CreditRecord_Role("PlymouthRole".Translate(), "Plymouth")); // new creds.Insert(26, new CreditRecord_Space(50f)); creds.Insert(27, new CreditRecord_Role("SeraRole".Translate(), "Sera")); // new creds.Insert(28, new CreditRecord_Space(50f)); creds.Insert(29, new CreditRecord_Role("NackbladRole".Translate(), "Nackblad")); creds.Insert(30, new CreditRecord_Space(50f)); // Patreon Supporters creds.Insert(31, new CreditRecord_Text("Patreon Supporters (In No Particular Order)", TextAnchor.UpperCenter)); creds.Insert(32, new CreditRecord_Space(50f)); creds.Insert(33, new CreditRecord_Role("PatreonProducer".Translate(), "XboxOneNoob")); //<NAME>. creds.Insert(34, new CreditRecord_Space(50f)); creds.Insert(35, new CreditRecord_Role("PatreonProducer".Translate(), "<NAME>")); // slick liuid creds.Insert(36, new CreditRecord_Space(50f)); creds.Insert(37, new CreditRecord_Role("PatreonProducer".Translate(), "Thom Black")); // Thom Black creds.Insert(38, new CreditRecord_Space(50f)); creds.Insert(39, new CreditRecord_Role("PatreonSupporter".Translate(), "<NAME>")); creds.Insert(40, new CreditRecord_Space(50f)); creds.Insert(41, new CreditRecord_Role("PatreonSupporter".Translate(), "<NAME>")); creds.Insert(42, new CreditRecord_Space(50f)); creds.Insert(43, new CreditRecord_Role("PatreonSupporter".Translate(), "Populous25")); creds.Insert(44, new CreditRecord_Space(50f)); creds.Insert(45, new CreditRecord_Role("PatreonSupporter".Translate(), "<NAME>")); creds.Insert(46, new CreditRecord_Space(50f)); creds.Insert(47, new CreditRecord_Role("PatreonSupporter".Translate(), "<NAME>")); creds.Insert(48, new CreditRecord_Space(50f)); creds.Insert(49, new CreditRecord_Role("PatreonSupporter".Translate(), "<NAME>")); creds.Insert(50, new CreditRecord_Space(50f)); creds.Insert(51, new CreditRecord_Role("PatreonSupporter".Translate(), "Geth")); creds.Add(new CreditRecord_Space(100f)); creds.Add(new CreditRecord_Text("ThanksForPlaying".Translate(), TextAnchor.UpperCenter)); if (DelayBooster != 0f) { MessageDelay = DelayBooster; } } public override Vector2 InitialSize => new Vector2(Screen.width, Screen.height); protected override float Margin => 0f; private float ViewWidth => 800f; private float ViewHeight => creds.Sum(c => c.DrawHeight(ViewWidth)) + 200f; private float MaxScrollPosition => ViewHeight - 400f; private float AutoScrollRate { get { if (!wonGame) { return 30f; } var num = SongDefOf.EndCreditsSong.clip.length + 5f - 6f; return MaxScrollPosition / num; } } public override void PreOpen() { base.PreOpen(); creationRealtime = Time.realtimeSinceStartup; if (wonGame) { timeUntilAutoScroll = InitialAutoScrollDelayWonGame + MessageDelay; } else { timeUntilAutoScroll = InitialAutoScrollDelay + MessageDelay; } } public override void WindowUpdate() { base.WindowUpdate(); if (timeUntilAutoScroll > 0f) { timeUntilAutoScroll -= Time.deltaTime; } else { scrollPosition += AutoScrollRate * Time.deltaTime; } if (!wonGame || playedMusic || !(Time.realtimeSinceStartup > creationRealtime + 5f)) { return; } Find.MusicManagerPlay.ForceStartSong(SongDefOf.EndCreditsSong, true); playedMusic = true; } public override void DoWindowContents(Rect inRect) { var rect = new Rect(0f, 0f, Screen.width, Screen.height); GUI.DrawTexture(rect, BaseContent.BlackTex); var position = new Rect(rect); position.yMin += 30f; position.yMax -= 30f; position.xMin = rect.center.x - 400f; position.width = 800f; var viewWidth = ViewWidth; var viewHeight = ViewHeight; scrollPosition = Mathf.Clamp(scrollPosition, 0f, MaxScrollPosition); GUI.BeginGroup(position); var position2 = new Rect(0f, 0f, viewWidth, viewHeight); position2.y -= scrollPosition; GUI.BeginGroup(position2); Text.Font = GameFont.Medium; var num = 0f; foreach (var current in creds) { var num2 = current.DrawHeight(position2.width); var rect2 = new Rect(0f, num, position2.width, num2); current.Draw(rect2); num += num2; } GUI.EndGroup(); GUI.EndGroup(); if (Event.current.type == EventType.ScrollWheel) { Scroll(Event.current.delta.y * 25f); Event.current.Use(); } if (Event.current.type != EventType.KeyDown) { return; } if (Event.current.keyCode == KeyCode.DownArrow) { Scroll(250f); Event.current.Use(); } if (Event.current.keyCode != KeyCode.UpArrow) { return; } Scroll(-250f); Event.current.Use(); } private void Scroll(float offset) { scrollPosition += offset; timeUntilAutoScroll = 3f; } } }<file_sep>/Source/CultOfCthulhu/UI/Dialog_NameCult.cs using System; using RimWorld; using UnityEngine; using Verse; namespace CultOfCthulhu { public class Dialog_NameCult : Window { private readonly Map map; private readonly Pawn suggestingPawn; private string curName = NameGenerator.GenerateName(RulePackDef.Named("NamerCults")); public Dialog_NameCult(Map map) { if (map != null) { if (map.mapPawns.FreeColonistsCount != 0) { suggestingPawn = map.mapPawns.FreeColonistsSpawnedCount != 0 ? map.mapPawns.FreeColonistsSpawned.RandomElement() : map.mapPawns.FreeColonists.RandomElement(); } else { suggestingPawn = PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Alive_FreeColonists .RandomElement(); } } forcePause = true; //this.closeOnEscapeKey = false; absorbInputAroundWindow = true; this.map = map; } public override Vector2 InitialSize => new Vector2(500f, 200f); public override void DoWindowContents(Rect rect) { Text.Font = GameFont.Small; var flag = false; if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return) { flag = true; Event.current.Use(); } if (suggestingPawn != null) { Widgets.Label(new Rect(0f, 0f, rect.width, rect.height), "NameCultMessage".Translate( suggestingPawn.Name.ToStringShort )); } else { Widgets.Label(new Rect(0f, 0f, rect.width, rect.height), "NameCultMessageNullHandler".Translate()); } curName = Widgets.TextField(new Rect(0f, rect.height - 35f, (rect.width / 2f) - 20f, 35f), curName); if (!Widgets.ButtonText(new Rect((rect.width / 2f) + 20f, rect.height - 35f, (rect.width / 2f) - 20f, 35f), "OK".Translate(), true, false) && !flag) { return; } if (IsValidCultName(curName)) { if (map != null) { CultTracker.Get.PlayerCult.name = curName; //Faction.OfPlayer.Name = this.curName; Find.WindowStack.TryRemove(this); Messages.Message("CultGainsName".Translate( curName ), MessageTypeDefOf.PositiveEvent); } else { throw new InvalidOperationException(); } } else { Messages.Message("ColonyNameIsInvalid".Translate(), MessageTypeDefOf.RejectInput); } Event.current.Use(); } private bool IsValidCultName(string s) { return s.Length != 0 && CultUtility.CheckValidCultName(s); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Bast/Deathworkers/DeathActionWorker_BastGuardian.cs using System.Collections.Generic; using RimWorld; using Verse; namespace BastCult { /// <summary> /// Death worker for Bast Guardians. /// </summary> public class DeathActionWorker_BastGuardian : DeathActionWorker { public override void PawnDied(Corpse corpse) { //Fancy death effect. MoteMaker.MakePowerBeamMote(corpse.Position, corpse.Map); //Hurt all nearby enemy pawns. foreach (var cell in GenRadial.RadialCellsAround(corpse.Position, 3f, true)) { var thingList = new List<Thing>(cell.GetThingList(corpse.Map)); foreach (var thing in thingList) { if (thing.HostileTo(corpse.InnerPawn.Faction)) { //Damage. thing.TakeDamage(new DamageInfo(DamageDefOf.Burn, 40)); } } } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Dagon/Building_SignOfDagon.cs using Cthulhu; using RimWorld; using Verse; using Verse.AI.Group; namespace CultOfCthulhu { public class Building_SignOfDagon : Building { public override void SpawnSetup(Map map, bool bla) { //Log.Message("Building_SignOfDagon SpawnSetup"); base.SpawnSetup(map, bla); Building_SignOfDagon toDestroy = null; foreach (var bld in map.listerBuildings.allBuildingsColonist) { if (bld == this) { continue; } if (bld is Building_SignOfDagon dagon) { toDestroy = dagon; } } toDestroy?.Destroy(); var list = map.GetComponent<MapComponent_SacrificeTracker>().defendTheBroodPawns; if (list == null) { return; } if (list.Count <= 0) { return; } Faction f; if (Utility.IsCosmicHorrorsLoaded()) { f = Find.FactionManager.FirstFactionOfDef(FactionDef.Named("ROM_DeepOne")); } else { Messages.Message("Cosmic horrors mod is not loaded. Using insectoids instead.", MessageTypeDefOf.NegativeEvent); f = Find.FactionManager.FirstFactionOfDef(FactionDef.Named("ROM_DeepOneAlt")); } Lord lord = null; //Log.Message("Building_SignOfDagon LordJob_DefendPoint"); var lordJob = new LordJob_DefendPoint(Position); Utility.TemporaryGoodwill(f); foreach (var current in list) { if (lord == null) { lord = current.GetLord(); } if (lord != null) { map.lordManager.RemoveLord(lord); } } LordMaker.MakeNewLord(f, lordJob, map, list); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Dagon/SpellWorker_BountyOfTheSea.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_BountyOfTheSea : SpellWorker { protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } public override bool CanSummonNow(Map map) { return true; } protected override bool TryExecuteWorker(IncidentParms parms) { if (!(parms.target is Map map)) { return false; } //Find a drop spot if (!CultUtility.TryFindDropCell(map.Center, map, 999999, out var intVec)) { return false; } //Spawn 1 relic var thing = (Building_LandedShip) ThingMaker.MakeThing(CultsDefOf.Cults_LandedShip); GenPlace.TryPlaceThing(thing, intVec.RandomAdjacentCell8Way(), map, ThingPlaceMode.Near); //Spawn 2 treasure chest var thing2 = (Building_TreasureChest) ThingMaker.MakeThing(CultsDefOf.Cults_TreasureChest); GenPlace.TryPlaceThing(thing2, intVec.RandomAdjacentCell8Way(), map, ThingPlaceMode.Near); var thing3 = (Building_TreasureChest) ThingMaker.MakeThing(CultsDefOf.Cults_TreasureChest); GenPlace.TryPlaceThing(thing3, intVec.RandomAdjacentCell8Way(), map, ThingPlaceMode.Near); map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = intVec; Messages.Message("Treasures from the deep mysteriously appear.", new TargetInfo(intVec, map), MessageTypeDefOf.PositiveEvent); Utility.ApplyTaleDef("Cults_SpellBountyOfTheSea", map); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Sacrifice/Bill_Sacrifice.cs using System.Collections.Generic; using RimWorld; using Verse; namespace CultOfCthulhu { public class Bill_Sacrifice : IExposable { private List<Pawn> congregation; private CosmicEntity entity; private Pawn executioner; private Pawn sacrifice; private IncidentDef spell; public Bill_Sacrifice() { } public Bill_Sacrifice(Pawn newSacrifice, Pawn newExecutioner, CosmicEntity newEntity, IncidentDef newSpell) { sacrifice = newSacrifice; executioner = newExecutioner; entity = newEntity; spell = newSpell; } public Pawn Sacrifice => sacrifice; public Pawn Executioner => executioner; public List<Pawn> Congregation { get => congregation; set => congregation = value; } public CosmicEntity Entity => entity; public IncidentDef Spell => spell; public CultUtility.SacrificeType Type => Sacrifice?.RaceProps?.Animal ?? false ? CultUtility.SacrificeType.animal : CultUtility.SacrificeType.human; public void ExposeData() { Scribe_References.Look(ref sacrifice, "sacrifice"); Scribe_References.Look(ref executioner, "executioner"); Scribe_Collections.Look(ref congregation, "congregation", LookMode.Reference); Scribe_References.Look(ref entity, "entity"); Scribe_Defs.Look(ref spell, "spell"); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/LoadTransportersPawnJobUtility.cs using System.Collections.Generic; using System.Linq; using Cthulhu; using RimWorld; using UnityEngine; using Verse; using Verse.AI; namespace CultOfCthulhu { public static class LoadTransportersPawnJobUtility { private static readonly HashSet<Thing> neededThings = new HashSet<Thing>(); // RimWorld.TransporterUtility public static void GetTransportersInGroup(int transportersGroup, Map map, List<CompTransporterPawn> outTransporters) { outTransporters.Clear(); if (transportersGroup < 0) { return; } var listSel = from Pawn pawns in map.mapPawns.AllPawnsSpawned where pawns is PawnFlyer select pawns; var list = new List<Pawn>(listSel); foreach (var pawn in list) { var compTransporter = pawn.TryGetComp<CompTransporterPawn>(); if (compTransporter.groupID != transportersGroup) { continue; } Utility.DebugReport("Outlist Added: " + pawn.Label); outTransporters.Add(compTransporter); } } public static Job JobOnTransporter(Pawn p, CompTransporterPawn transporter) { Utility.DebugReport("JobOnTransporter Called"); var thing = FindThingToLoad(p, transporter); return new Job(JobDefOf.HaulToContainer, thing, transporter.parent) { count = Mathf.Min( TransferableUtility.TransferableMatching(thing, transporter.leftToLoad, TransferAsOneMode.PodsOrCaravanPacking).CountToTransfer, thing.stackCount), ignoreForbidden = true }; } // RimWorld.LoadTransportersJobUtility public static bool HasJobOnTransporter(Pawn pawn, CompTransporterPawn transporter) { var result = !transporter.parent.IsForbidden(pawn) && transporter.AnythingLeftToLoad && pawn.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation) && pawn.CanReserveAndReach(transporter.parent, PathEndMode.Touch, pawn.NormalMaxDanger()) && FindThingToLoad(pawn, transporter) != null; Utility.DebugReport(pawn.Label + " HasJobOnTransporter: " + result); return result; } // RimWorld.LoadTransportersJobUtility private static Thing FindThingToLoad(Pawn p, CompTransporterPawn transporter) { neededThings.Clear(); var leftToLoad = transporter.leftToLoad; if (leftToLoad != null) { foreach (var transferableOneWay in leftToLoad) { if (transferableOneWay.CountToTransfer <= 0) { continue; } foreach (var item in transferableOneWay.things) { neededThings.Add(item); } } } if (!neededThings.Any()) { return null; } bool validator(Thing x) { return neededThings.Contains(x) && p.CanReserve(x); } var thing = GenClosest.ClosestThingReachable(p.Position, p.Map, ThingRequest.ForGroup(ThingRequestGroup.HaulableEver), PathEndMode.Touch, TraverseParms.For(p), 9999f, validator); if (thing == null) { foreach (var current in neededThings) { if (current is not Pawn pawn || pawn.IsColonist && !pawn.Downed || !p.CanReserveAndReach(pawn, PathEndMode.Touch, Danger.Deadly)) { continue; } Utility.DebugReport("Pawn to load : " + pawn.Label); return pawn; } } if (thing != null) { Utility.DebugReport("Thing to load : " + thing.Label); } neededThings.Clear(); return thing; } } }<file_sep>/Source/CultOfCthulhu/ModSettings.cs using UnityEngine; using Verse; namespace CultOfCthulhu { [StaticConstructorOnStartup] public static class ModSettings_Data { public static bool cultsForcedInvestigation = true; public static bool cultsStudySuccessfulCultsIsRepeatable = true; public static bool cultsShowDebugCode; public static bool makeWorshipsVoluntary; } public class ModMain : Mod { private readonly Settings settings; public ModMain(ModContentPack content) : base(content) { settings = GetSettings<Settings>(); ModSettings_Data.cultsForcedInvestigation = settings.cultsForcedInvestigation; ModSettings_Data.makeWorshipsVoluntary = settings.makeWorshipsVoluntary; ModSettings_Data.cultsStudySuccessfulCultsIsRepeatable = settings.cultsStudySuccessfulCultsIsRepeatable; ModSettings_Data.cultsShowDebugCode = settings.cultsShowDebugCode; } public override string SettingsCategory() { return "Call of Cthulhu - Cults"; } public override void DoSettingsWindowContents(Rect inRect) { var offset = 30; var spacer = 5; var height = 30; Widgets.CheckboxLabeled(new Rect(inRect.x + offset, inRect.y, inRect.width - offset, height), "ForcedInvestigation".Translate(), ref settings.cultsForcedInvestigation); Widgets.CheckboxLabeled( new Rect(inRect.x + offset, inRect.y + offset + spacer, inRect.width - offset, height), "StudySuccessfulCultsIsRepeatable".Translate(), ref settings.cultsStudySuccessfulCultsIsRepeatable); Widgets.CheckboxLabeled( new Rect(inRect.x + offset, inRect.y + offset + spacer + offset + spacer, inRect.width - offset, height), "Cults_MakeWorshipsVoluntary".Translate(), ref settings.makeWorshipsVoluntary); Widgets.CheckboxLabeled( new Rect(inRect.x + offset, inRect.y + offset + spacer + offset + spacer + offset + spacer, inRect.width - offset, height), "ShowDebugCode".Translate(), ref settings.cultsShowDebugCode); settings.Write(); } } public class Settings : ModSettings { public bool cultsForcedInvestigation = true; public bool cultsShowDebugCode; public bool cultsStudySuccessfulCultsIsRepeatable = true; public bool makeWorshipsVoluntary; public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref cultsForcedInvestigation, "cultsForcedInvestigation", true); Scribe_Values.Look(ref cultsStudySuccessfulCultsIsRepeatable, "cultsStudySuccessfulCultsIsRepeatable", true); Scribe_Values.Look(ref cultsShowDebugCode, "cultsShowDebugCode", true); Scribe_Values.Look(ref makeWorshipsVoluntary, "makeWorshipsVoluntary"); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Nyarlathotep/SpellWorker_DarkEmissary.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_DarkEmissary : SpellWorker { private const float RelationWithColonistWeight = 20f; protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; for (var i = 0; i < 2; i++) { if (!CultUtility.TrySpawnWalkInCultist(map, CultUtility.CultistType.DarkEmmisary, false)) { //Log.Messag("Failed to spawn walk in cultist"); return false; } } return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/SpellWorker_NoLongerDomesticated.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_NoLongerDomesticated : SpellWorker { protected IEnumerable<Pawn> Animals(Map map) { return from Pawn animal in map.mapPawns.AllPawns where animal.RaceProps.Animal && animal.Faction == Faction.OfPlayer select animal; } protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } protected override bool TryExecuteWorker(IncidentParms parms) { for (var i = 0; i < Rand.Range(3, 6); i++) { if (Animals((Map) parms.target).Count() != 0) { if (Animals((Map) parms.target).TryRandomElement(out var animal)) { //Cthulhu.Utility.DebugReport("Destroyed: " + item.ToString()); animal.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Manhunter); } } else { Utility.DebugReport("No animals to drive insane."); } } return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/CompLaunchablePawn.cs using System.Collections.Generic; using System.Diagnostics; using Cthulhu; using RimWorld; using RimWorld.Planet; using UnityEngine; using Verse; namespace CultOfCthulhu { [StaticConstructorOnStartup] public class CompLaunchablePawn : ThingComp { private static readonly int maxTileDistance = 120; private static readonly Texture2D TargeterMouseAttachment = ContentFinder<Texture2D>.Get("UI/Overlays/LaunchableMouseAttachment"); private static readonly Texture2D LaunchCommandTex = ContentFinder<Texture2D>.Get("UI/Commands/LaunchShip"); private CompTransporterPawn cachedCompTransporter; public bool LoadingInProgressOrReadyToLaunch => Transporter.LoadingInProgressOrReadyToLaunch; public bool AnythingLeftToLoad => Transporter.AnythingLeftToLoad; public Thing FirstThingLeftToLoad => Transporter.FirstThingLeftToLoad; public List<CompTransporterPawn> TransportersInGroup => Transporter.TransportersInGroup(parent.Map); public bool AnyInGroupHasAnythingLeftToLoad => Transporter.AnyInGroupHasAnythingLeftToLoad; public Thing FirstThingLeftToLoadInGroup => Transporter.FirstThingLeftToLoadInGroup; public bool AnyInGroupIsUnderRoof { get { var transportersInGroup = TransportersInGroup; foreach (var compTransporterPawn in transportersInGroup) { if (compTransporterPawn.parent.Position.Roofed(parent.Map)) { return true; } } return false; } } public CompTransporterPawn Transporter { get { if (cachedCompTransporter == null) { cachedCompTransporter = parent.GetComp<CompTransporterPawn>(); } return cachedCompTransporter; } } public PawnFlyerDef PawnFlyerDef { get { var result = parent.def as PawnFlyerDef; if (result == null) { Log.Error("PawnFlyerDef is null"); } return result; } } public int MaxLaunchDistance => !LoadingInProgressOrReadyToLaunch ? 0 : PawnFlyerDef.flyableDistance; [DebuggerHidden] public override IEnumerable<Gizmo> CompGetGizmosExtra() { using var enumerator = base.CompGetGizmosExtra().GetEnumerator(); while (enumerator.MoveNext()) { var current = enumerator.Current; yield return current; } if (LoadingInProgressOrReadyToLaunch) { var command_Action = new Command_Action { defaultLabel = "CommandLaunchGroup".Translate(), defaultDesc = "CommandLaunchGroupDesc".Translate(), icon = LaunchCommandTex, action = delegate { if (AnyInGroupHasAnythingLeftToLoad) { Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation( "ConfirmSendNotCompletelyLoadedPods".Translate( FirstThingLeftToLoadInGroup.LabelCap ), StartChoosingDestination)); } else { StartChoosingDestination(); } } }; if (AnyInGroupIsUnderRoof) { command_Action.Disable("CommandLaunchGroupFailUnderRoof".Translate()); } yield return command_Action; } else { var command_Action = new Command_Action { defaultLabel = "DEBUG", defaultDesc = "CommandLaunchGroupDesc".Translate(), icon = LaunchCommandTex, action = delegate { if (AnyInGroupHasAnythingLeftToLoad) { Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation( "ConfirmSendNotCompletelyLoadedPods".Translate( FirstThingLeftToLoadInGroup.LabelCap ), StartChoosingDestination)); } else { StartChoosingDestination(); } } }; if (AnyInGroupIsUnderRoof) { command_Action.Disable("CommandLaunchGroupFailUnderRoof".Translate()); } yield return command_Action; } } public override string CompInspectStringExtra() { if (!LoadingInProgressOrReadyToLaunch) { return null; } return AnyInGroupHasAnythingLeftToLoad ? (string) ("NotReadyForLaunch".Translate() + ": " + "TransportPodInGroupHasSomethingLeftToLoad".Translate() + ".") : (string) "ReadyForLaunch".Translate(); } public void StartChoosingDestination() { CameraJumper.TryJump(CameraJumper.GetWorldTarget(parent)); Find.WorldSelector.ClearSelection(); var tile = parent.Map.Tile; Find.WorldTargeter.BeginTargeting(ChoseWorldTarget, true, TargeterMouseAttachment, true, delegate { GenDraw.DrawWorldRadiusRing(tile, MaxLaunchDistance); }, delegate(GlobalTargetInfo target) { if (!target.IsValid) { return null; } var num = Find.WorldGrid.TraversalDistanceBetween(tile, target.Tile); if (num <= MaxLaunchDistance) { return null; } return num > maxTileDistance ? (string) "TransportPodDestinationBeyondMaximumRange".Translate() : (string) "TransportPodNotEnoughFuel".Translate(); }); } private bool ChoseWorldTarget(GlobalTargetInfo target) { Utility.DebugReport("ChooseWorldTarget Called"); if (!LoadingInProgressOrReadyToLaunch) { return true; } if (!target.IsValid) { Messages.Message("MessageTransportPodsDestinationIsInvalid".Translate(), MessageTypeDefOf.RejectInput); return false; } var num = Find.WorldGrid.TraversalDistanceBetween(parent.Map.Tile, target.Tile); if (num > MaxLaunchDistance) { //Messages.Message("MessageTransportPodsDestinationIsTooFar".Translate(new object[] //{ // CompLaunchable.FuelNeededToLaunchAtDist((float)num).ToString("0.#") //}), MessageTypeDefOf.RejectInput); return false; } if (target.WorldObject is MapParent {HasMap: true} mapParent) { var myMap = parent.Map; var map = mapParent.Map; Current.Game.CurrentMap = map; var arg_139_0 = Find.Targeter; void ActionWhenFinished() { if (Find.Maps.Contains(myMap)) { Current.Game.CurrentMap = myMap; } } arg_139_0.BeginTargeting(TargetingParameters.ForDropPodsDestination(), delegate(LocalTargetInfo x) { if (!LoadingInProgressOrReadyToLaunch) { Utility.DebugReport("ChooseTarget Exited - LoadingInProgressOrReadyToLaunch"); return; } TryLaunch(x.ToGlobalTargetInfo(map), PawnsArrivalModeDefOf.EdgeDrop, false); }, null, ActionWhenFinished, TargeterMouseAttachment); return true; } if (target.WorldObject is Settlement && target.WorldObject.Faction != Faction.OfPlayer) { Find.WorldTargeter.closeWorldTabWhenFinished = false; var list = new List<FloatMenuOption>(); if (!target.WorldObject.Faction.HostileTo(Faction.OfPlayer)) { list.Add(new FloatMenuOption("VisitFactionBase".Translate( target.WorldObject.Label ), delegate { if (!LoadingInProgressOrReadyToLaunch) { return; } TryLaunch(target, PawnsArrivalModeDefOf.EdgeDrop, false); CameraJumper.TryHideWorld(); })); } list.Add(new FloatMenuOption("DropAtEdge".Translate(), delegate { if (!LoadingInProgressOrReadyToLaunch) { return; } TryLaunch(target, PawnsArrivalModeDefOf.EdgeDrop, true); CameraJumper.TryHideWorld(); })); list.Add(new FloatMenuOption("DropInCenter".Translate(), delegate { if (!LoadingInProgressOrReadyToLaunch) { return; } TryLaunch(target, PawnsArrivalModeDefOf.CenterDrop, true); CameraJumper.TryHideWorld(); })); Find.WindowStack.Add(new FloatMenu(list)); return true; } Messages.Message("MessageTransportPodsDestinationIsInvalid".Translate(), MessageTypeDefOf.RejectInput); return false; //this.TryLaunch(target, PawnsArrivalModeDefOf.Undecided, false); //return true; } private void TryLaunch(GlobalTargetInfo target, PawnsArrivalModeDef arriveMode, bool attackOnArrival) { Utility.DebugReport("TryLaunch Called"); if (!parent.Spawned) { Log.Error("Tried to launch " + parent + ", but it's unspawned."); return; } var transportersInGroup = TransportersInGroup; if (transportersInGroup == null) { Log.Error("Tried to launch " + parent + ", but it's not in any group."); return; } if (!LoadingInProgressOrReadyToLaunch) { Utility.DebugReport("TryLaunch Failed"); return; } var map = parent.Map; var num = Find.WorldGrid.TraversalDistanceBetween(map.Tile, target.Tile); if (num > MaxLaunchDistance) { Utility.DebugReport("TryLaunch Failed #2"); return; } Transporter.TryRemoveLord(map); var groupID = Transporter.groupID; foreach (var compTransporterPawn in transportersInGroup) { Utility.DebugReport("Transporter Outspawn Attempt"); var compTransporter = compTransporterPawn; Utility.DebugReport("Transporter Outspawn " + compTransporter.parent.Label); var pawnFlyerLeaving = (PawnFlyersLeaving) ThingMaker.MakeThing(PawnFlyerDef.leavingDef); pawnFlyerLeaving.groupID = groupID; pawnFlyerLeaving.pawnFlyer = parent as PawnFlyer; pawnFlyerLeaving.destinationTile = target.Tile; pawnFlyerLeaving.destinationCell = target.Cell; pawnFlyerLeaving.arriveMode = arriveMode; pawnFlyerLeaving.attackOnArrival = attackOnArrival; var innerContainer = compTransporter.GetDirectlyHeldThings(); pawnFlyerLeaving.Contents = new ActiveDropPodInfo(); innerContainer.TryTransferAllToContainer(pawnFlyerLeaving.Contents.innerContainer); //pawnFlyerLeaving.Contents.innerContainer. //TryAddMany(innerContainer); innerContainer.Clear(); compTransporter.CleanUpLoadingVars(map); compTransporter.parent.DeSpawn(); pawnFlyerLeaving.Contents.innerContainer.TryAdd(compTransporter.parent); GenSpawn.Spawn(pawnFlyerLeaving, compTransporter.parent.Position, map); } } public void Notify_FuelingPortSourceDeSpawned() { if (Transporter.CancelLoad()) { Messages.Message("MessageTransportersLoadCanceled_FuelingPortGiverDeSpawned".Translate(), parent, MessageTypeDefOf.NegativeEvent); } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/MapComponent_LocalCultTracker.cs using System.Collections.Generic; using Cthulhu; using RimWorld; using Verse; using Verse.AI; namespace CultOfCthulhu { internal partial class MapComponent_LocalCultTracker : MapComponent { public const int OneMinute = 3600; public const int OneDay = 60000; public const int ThreeDays = 180000; //public int ticksToSpawnCultSeed = (OneMinute + 1000) + Rand.Range(-OneMinute, OneMinute); //Between 2-4 days. 1 day = 60000 public readonly List<IncidentDef> seedIncidents = new List<IncidentDef> { IncidentDef.Named("CultSeedIncident_TreeOfNightmares"), IncidentDef.Named("CultSeedIncident_NightmareMonolith") }; //Cult seed stuff public Pawn CurrentSeedPawn; public Thing CurrentSeedTarget; public bool doingInquisition; public bool needPreacher; public int ticksToCheckCultists; public int ticksToSpawnCultSeed = ThreeDays + Rand.Range(-OneDay, OneDay); //Between 2-4 days. 1 day = 60000 public int ticksToSpawnHelpfulPreacher = OneMinute + Rand.Range(OneMinute, OneDay); public int ticksToTryJobAgain = OneMinute; //1 minute public int ticksUntilInquisition; public MapComponent_LocalCultTracker(Map map) : base(map) { this.map = map; } //WorldComponent_GlobalCultTracker globalCultTracker = Find.World.GetComponent<WorldComponent_GlobalCultTracker>(); public CultSeedState CurrentSeedState { get => CultTracker.Get.currentSeedState; set => CultTracker.Get.currentSeedState = value; } public List<Pawn> antiCultists => CultTracker.Get.antiCultists; public void ResolveTerribleCultFounder(Pawn founder) { if (founder == null) { return; } if (founder.skills.GetSkill(SkillDefOf.Social).Level > 5) { return; //A preacher with at least 5 preaching skill can be a good preacher for a cultist colony. } //We need a preacher! needPreacher = true; ticksToSpawnHelpfulPreacher = OneMinute + Rand.Range(OneMinute, OneDay); } public override void MapComponentTick() { base.MapComponentTick(); CultSeedCheck(); NewCultistCheck(); ResetResearchCheck(); PreacherCheck(); InquisitionCheck(); } private bool TryFindPreacher(out Pawn preacher) { preacher = null; if (CultTracker.Get.PlayerCult == null) { return false; } var tempList = new List<Pawn>(CultTracker.Get.PlayerCult.members); foreach (var current in tempList.InRandomOrder()) { if (current == null) { continue; } if (current.Dead) { CultTracker.Get.PlayerCult.RemoveMember(current); continue; } if (preacher == null) { preacher = current; } if (current.skills.GetSkill(SkillDefOf.Social).Level > preacher.skills.GetSkill(SkillDefOf.Social).Level) { preacher = current; } } if (preacher != null) { return true; } return false; } private void PreacherCheck() { if (!needPreacher) { return; } if (ticksToSpawnHelpfulPreacher > 0) { ticksToSpawnHelpfulPreacher--; } else { if (!CultUtility.TrySpawnWalkInCultist(map, CultUtility.CultistType.Preacher)) { //Log.Messag("Failed to spawn walk-in cultist"); } needPreacher = false; } } private void ResetResearchCheck() { try { var repeatableResearch = ResearchProjectDef.Named("Forbidden_Lore"); if (repeatableResearch == null) { return; } if (!ModSettings_Data.cultsStudySuccessfulCultsIsRepeatable) { return; } if (!repeatableResearch.IsFinished) { return; } Utility.ChangeResearchProgress(repeatableResearch, 0f, true); Messages.Message("RepeatableResearch".Translate( repeatableResearch.LabelCap ), MessageTypeDefOf.PositiveEvent); } catch { // ignored } } private void NewCultistCheck() { if (CurrentSeedState < CultSeedState.FinishedWriting) { return; } //Cult Tick (500 ticks) if (ticksToCheckCultists == 0) { ticksToCheckCultists = Find.TickManager.TicksGame + 500; } if (ticksToCheckCultists >= Find.TickManager.TicksGame) { return; } ticksToCheckCultists = Find.TickManager.TicksGame + 500; var spawnedColonyMembers = new List<Pawn>(map.mapPawns.FreeColonistsAndPrisonersSpawned); var playerCult = CultTracker.Get.PlayerCult; if (spawnedColonyMembers.Count == 0) { return; } foreach (var colonist in spawnedColonyMembers) { if (!colonist.RaceProps.Humanlike || colonist.IsPrisoner || colonist.RaceProps.intelligence != Intelligence.Humanlike || colonist.Dead) { playerCult?.RemoveMember(colonist); CultTracker.Get.RemoveInquisitor(colonist); continue; } if (colonist.needs.TryGetNeed<Need_CultMindedness>() is not Need_CultMindedness cultMind) { continue; } //Cult-Mindedness Above 70%? You will join the cult. if (cultMind.CurLevelPercentage > CultLevel.Cultist) { if (playerCult == null) { playerCult = new Cult(colonist); } playerCult.SetMember(colonist); } //Otherwise, you will be removed from the cult. else if (cultMind.CurInstantLevelPercentage > CultLevel.AntiCultist && cultMind.CurInstantLevelPercentage < CultLevel.Cultist) { if (playerCult == null) { continue; } playerCult.RemoveMember(colonist); CultTracker.Get.RemoveInquisitor(colonist); } //Those with cult mindedness below 30% will be inquisitors. else if (cultMind.CurInstantLevelPercentage < CultLevel.AntiCultist) { CultTracker.Get.SetInquisitor(colonist); } } } private void CanDoJob(JobDef job, Pawn pawn, Thing target = null, bool targetRequired = false) { if (pawn == null) { return; } if (target == null && targetRequired) { return; } if (ModSettings_Data.cultsForcedInvestigation == false && job != CultsDefOf.Cults_WriteTheBook) { return; } //Toxic Fallout? Let's not force the colonist to do this job. if (map.GameConditionManager.GetActiveCondition(GameConditionDefOf.ToxicFallout) != null) { return; } if (ticksToSpawnCultSeed > 0) { ticksToTryJobAgain -= 1; } if (CurrentSeedPawn.CurJob.def == job || ticksToTryJobAgain > 0) { return; } var J = new Job(job, pawn); if (CurrentSeedTarget != null) { J.SetTarget(TargetIndex.B, target); } pawn.jobs.TryTakeOrderedJob(J); //pawn.CurJob.EndCurrentJob(JobCondition.InterruptForced); ticksToTryJobAgain = OneMinute; } public override void ExposeData() { //Cult Variables Scribe_Values.Look(ref needPreacher, "needPreacher"); Scribe_Values.Look(ref doingInquisition, "doingInquisition"); Scribe_Values.Look(ref ticksToSpawnHelpfulPreacher, "ticksToSpawnHelpfulPreacher"); Scribe_Values.Look(ref ticksToCheckCultists, "ticksToCheckCultists"); Scribe_Values.Look(ref ticksUntilInquisition, "ticksUntilInquisition"); //Cult Seed Variables Scribe_References.Look(ref CurrentSeedPawn, "CurrentSeedPawn"); Scribe_References.Look(ref CurrentSeedTarget, "CurrentSeedTarget"); Scribe_Values.Look(ref ticksToSpawnCultSeed, "ticksToSpawnCultSeed"); base.ExposeData(); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Psionics/CompPsionicUser.cs using AbilityUser; using Verse; namespace CultOfCthulhu { public class CompPsionicUser : CompAbilityUser { public bool firstTick; public bool IsPsionic { get { if (AbilityUser?.health?.hediffSet == null) { return false; } if (AbilityUser.health.hediffSet.HasHediff(CultsDefOf.Cults_PsionicBrain)) { return true; } return false; } } public override bool TryTransformPawn() { return IsPsionic; } public void PostInitializeTick() { if (AbilityUser == null) { return; } if (!AbilityUser.Spawned) { return; } if (AbilityUser.story == null) { return; } firstTick = true; Initialize(); AddPawnAbility(CultsDefOf.Cults_PsionicBlast); AddPawnAbility(CultsDefOf.Cults_PsionicShock); AddPawnAbility(CultsDefOf.Cults_PsionicBurn); } public override void CompTick() { if (AbilityUser == null) { return; } if (!AbilityUser.Spawned) { return; } if (Find.TickManager.TicksGame <= 200) { return; } if (!IsPsionic) { return; } if (!firstTick) { PostInitializeTick(); } base.CompTick(); } } }<file_sep>/Source/CultOfCthulhu/Utilities/CultUtility.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Cthulhu; using RimWorld; using RimWorld.Planet; using UnityEngine; using Verse; using Verse.AI; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public static class CultLevel { public const float PureAntiCultist = 0.1f; public const float AntiCultist = 0.3f; public const float Middling = 0.5f; public const float Cultist = 0.7f; public const float PureCultist = 0.9f; } public static class CultUtility { //TraitDef.Named("Masochist") //TraitDef.Named("PsychicSensitivity"), //TraitDef.Named("Nerves"), //TraitDefOf.DrugDesire public enum CultistType { None, Preacher, DarkEmmisary } public enum OfferingSize { none = 0, meagre = 5, decent = 10, sizable = 20, worthy = 50, impressive = 100 } public enum SacrificeResult { none = 0, criticalfailure, failure, mixedsuccess, success } public enum SacrificeType { none, meat, plants, meals, animal, human } public static List<TraitDef> immoralistTraits = new List<TraitDef> { TraitDefOf.Psychopath, TraitDefOf.Bloodlust, TraitDefOf.Cannibal }; public static readonly int ritualDuration = 740; // 15 seconds max public static readonly int reflectDuration = 600; // 10 seconds max // RimWorld.IncidentWorker_ShipChunkDrop public static bool TryFindDropCell(IntVec3 nearLoc, Map map, int maxDist, out IntVec3 pos, ThingDef defToCheck = null) { if (defToCheck == null) { defToCheck = ThingDefOf.ShipChunkIncoming; } return CellFinderLoose.TryFindSkyfallerCell(defToCheck, map, out pos, 10, nearLoc, maxDist, true, false, false, false, false); } public static float GetBaseCultistModifier(Pawn pawn) { float result = 0; var bigMod = Rand.Range(0.2f, 0.25f); var smallMod = Rand.Range(0.05f, 0.1f); if (pawn?.story?.adulthood == null || pawn.story?.childhood == null) { return result; } string adultStory = pawn.story.adulthood.FullDescriptionFor(pawn); string childStory = pawn.story.childhood.FullDescriptionFor(pawn); //Immoralist modifiers //Immoral Traits: // I do eat human flesh. // I like to kill. // I don't care about others. result = (from trait in pawn.story.traits.allTraits from def in immoralistTraits where trait.def == def select bigMod).Sum(); //Cult inclined. // Midworlders are more open to superstition. // Abandoned children, looking for 'family.' if (adultStory.Contains("midworld") || adultStory.Contains("Midworld")) { result += smallMod; } if (childStory.Contains("midworld") || childStory.Contains("Midworld")) { result += smallMod; } if (childStory.Contains("abandoned")) { result += smallMod; } //Moralist modifiers //Moral: I am not a violent person. if (pawn.story.adulthood.workDisables == WorkTags.Violent || pawn.story.childhood.workDisables == WorkTags.Violent) { result -= bigMod; } //Cult disinclined. // Glitterworlders. Morality is paramount. if (adultStory.Contains("glitterworld") || adultStory.Contains("Glitterworld")) { result -= smallMod; } if (childStory.Contains("glitterworld") || childStory.Contains("Glitterworld")) { result -= smallMod; } //Randomness // Evangelists can be cultist or moralists. if (pawn.story.adulthood.title.Contains("Evangelist")) { if (Rand.Range(0, 100) > 50) { result += bigMod; } result -= bigMod; } if (Rand.Range(0, 100) > 50) { result += smallMod; } else { result -= smallMod; } return Mathf.Clamp(result, -0.5f, 0.2f); } public static bool TrySpawnWalkInCultist(Map map, CultistType type = CultistType.None, bool showMessage = true) { try { if (map == null) { map = Find.CurrentMap; } if (map == null) { return false; } if (!CellFinder.TryFindRandomEdgeCellWith(c => map.reachability.CanReachColony(c), map, CellFinder.EdgeRoadChance_Neutral, out var loc)) { return false; } if (!TryGenerateCultist(out var p, map, type)) { //Log.Messag("Unable to generate cultist"); return false; } if (p == null) { //Log.Messag("Pawn is null"); return false; } GenSpawn.Spawn(p, loc, map); var text = "CultistJoin".Translate(p.kindDef.label, p.story.adulthood.title.ToLower()); text = text.AdjustedFor(p); var label = "LetterLabelCultistJoin".Translate(); if (showMessage) { Find.LetterStack.ReceiveLetter(label, text, CultsDefOf.Cults_StandardMessage); } PawnRelationUtility.TryAppendRelationsWithColonistsInfo(ref text, ref label, p); return true; } #pragma warning disable CS0168 // Variable is declared but never used catch (Exception e) #pragma warning restore CS0168 // Variable is declared but never used { return false; } } public static bool TryGenerateCultist(out Pawn cultist, Map map, CultistType type = CultistType.None) { var pawnKindDef = new List<PawnKindDef> { PawnKindDefOf.Villager }.RandomElement(); Pawn p = null; PawnGenerationRequest request; //Resolve the type of cultist. //If it's a preacher, we need a high speaking skill. if (type == CultistType.Preacher) { for (var i = 0; i < 999; i++) { request = new PawnGenerationRequest(pawnKindDef, Faction.OfPlayer, PawnGenerationContext.NonPlayer, map.Tile, false, false, false, false, true, true, 20f, false, true, true, false); p = PawnGenerator.GeneratePawn(request); if (p.skills.GetSkill(SkillDefOf.Social).TotallyDisabled) { continue; } if (p.skills.GetSkill(SkillDefOf.Social).Level < 5) { continue; } if (p.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Social)) { continue; } break; } } //If it's a dark emissary of Nyarlathotep, we need to add clothing. else if (type == CultistType.DarkEmmisary) { request = new PawnGenerationRequest(pawnKindDef, Faction.OfPlayer, PawnGenerationContext.NonPlayer, map.Tile, false, false, false, false, true, true, 20f, false, true, true, false); p = PawnGenerator.GeneratePawn(request); var tHood = ThingMaker.MakeThing(ThingDef.Named("Apparel_NyarlathotepHood"), ThingDef.Named("DevilstrandCloth")); var tRobe = ThingMaker.MakeThing(ThingDef.Named("Apparel_CultistRobes"), ThingDef.Named("DevilstrandCloth")); var Hood = tHood as Apparel; var Robe = tRobe as Apparel; p.apparel.Wear(Hood, false); p.apparel.Wear(Robe, false); } else { request = new PawnGenerationRequest(pawnKindDef, Faction.OfPlayer, PawnGenerationContext.NonPlayer, map.Tile, false, false, false, false, true, true, 20f, false, true, true, false); p = PawnGenerator.GeneratePawn(request); } //We need psychopathic cannibals //GenSpawn.Spawn(p, loc); if (p == null) { cultist = null; return false; } //Add cultist traits. var traitToAdd = TraitDefOf.Psychopath; if (!p.story.traits.HasTrait(TraitDefOf.Cannibal)) { traitToAdd = TraitDefOf.Cannibal; } if (!p.story.traits.HasTrait(TraitDefOf.Psychopath)) { traitToAdd = TraitDefOf.Psychopath; } if (p.story.traits.allTraits.Count < 3) { p.story.traits.GainTrait(new Trait(traitToAdd)); } else { foreach (var t in p.story.traits.allTraits) { if (t.def == TraitDefOf.Cannibal || t.def == TraitDefOf.Psychopath) { continue; } p.story.traits.allTraits.Remove(t); break; //Remove 1 trait and get out } p.story.traits.GainTrait(new Trait(traitToAdd)); } //Add cult-mindedness. AffectCultMindedness(p, 0.8f); cultist = p; return true; } public static SacrificeResult GetSacrificeResult(Map map) { //Temporary //return SacrificeResult.success; var s = new StringBuilder(); s.AppendLine("Sacrifice Success Calculation"); var Success = false; var TableOfFun = false; var diceRoll = Rand.Range(1, 100); var baseDifficulty = 40; var failDifficulty = 0; var altar = map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar; if (altar?.SacrificeData?.Entity != null) { if (altar.SacrificeData.Spell != null) { //Setup a Report /////////////////// altar.LastReport = ""; var reportHeader = new StringBuilder(); var reportFavorables = new StringBuilder(); var reportUnfavorables = new StringBuilder(); var reportResult = new StringBuilder(); //Start the Header /////////////////// var date = GenDate.DateFullStringAt(GenDate.TickGameToAbs(Find.TickManager.TicksGame), Find.WorldGrid.LongLatOf(map.Tile)); reportHeader.AppendLine("Cults_LRHeading".Translate(date)); reportHeader.AppendLine("Cults_LRSacrifice".Translate(altar.SacrificeData.Sacrifice.def.label, altar.SacrificeData.Entity.LabelCap, altar.SacrificeData.Spell.label)); reportHeader.AppendLine( "Cults_LRAttendance".Translate(altar.SacrificeData?.Congregation?.Count ?? 0)); reportFavorables.AppendLine("Cults_LRFactorsFavorable".Translate()); reportUnfavorables.AppendLine("Cults_LRFactorsUnfavorable".Translate()); /////////////////// if (altar.SacrificeData.Spell.defName != "Cults_SpellFavor") { s.AppendLine("Initial Failure Difficulty: " + baseDifficulty); //Difficulty modifiers failDifficulty += SpellCalc_TierDifficulty(altar, s, reportUnfavorables, reportFavorables); //Tier 2 +10, Tier 3 + 20, Final +50 failDifficulty += SpellCalc_GameConditions(altar, s, reportUnfavorables, reportFavorables, out var successModifier); //+50 stars are wrong / -20 stars are right failDifficulty += SpellCalc_Characters(altar, s, reportUnfavorables, reportFavorables, successModifier, out successModifier); //+50 stars are wrong / -20 stars are right s.AppendLine("Adjusted Failure Difficulty: " + baseDifficulty + failDifficulty); //Success modifiers successModifier += SpellCalc_CongregationQuality(altar, s, reportFavorables); //Some robes +10, Dagger equipped +5, All robed and hooded +15 successModifier += SpellCalc_StatuesNearby(altar, s, reportFavorables); //Minimum one statue of normal quality +10, Statue of deity +10 successModifier += SpellCalc_TempleQuality(altar, s, reportFavorables); //Some quality +10, Great quality +20, Outdoors when deity favors it +20 s.AppendLine("Success Modifier: " + successModifier); //Difficulty check s.AppendLine("Difficulty check: (Rolling d100. " + diceRoll + " result + Success Modifier: " + successModifier + ") vs (Difficulty: " + baseDifficulty + " + Modifier: " + failDifficulty + ")"); if (diceRoll + successModifier >= baseDifficulty + failDifficulty) { Success = true; } s.AppendLine("Success = " + Success.ToString().CapitalizeFirst()); reportResult.AppendLine("Cults_LRCheck".Translate( diceRoll, successModifier, baseDifficulty, failDifficulty)); reportResult.AppendLine(Success ? "Cults_LRResultSuccess".Translate() : "Cults_LRResultFailure".Translate()); //Table of fun var randFun = Rand.Range(1, 10); if (randFun >= 6) { TableOfFun = true; //40% chance } s.AppendLine("Side Effect = " + TableOfFun); altar.LastReport = reportHeader + "\n" + reportFavorables + "\n" + reportUnfavorables + "\n" + reportResult; Utility.DebugReport(s.ToString()); if (Success && TableOfFun) { return SacrificeResult.mixedsuccess; } if (!Success && TableOfFun) { return SacrificeResult.failure; } if (Success) { return SacrificeResult.success; } } else if (altar.SacrificeData.Spell.defName == "Cults_SpellFavor") { return SacrificeResult.success; } } } Utility.DebugReport(s.ToString()); return SacrificeResult.criticalfailure; } private static int SpellCalc_Characters(Building_SacrificialAltar altar, StringBuilder debugString, StringBuilder reportUnfavorables, StringBuilder reportFavorables, int successModifierIn, out int successModifierOut) { var modifier = 0; successModifierOut = successModifierIn; var executioner = altar.tempExecutioner; var worldComponentGlobalCultTracker = Find.World.GetComponent<WorldComponent_GlobalCultTracker>(); var experience = worldComponentGlobalCultTracker.GetExperience(executioner, true); if (experience == 0) { modifier += 10; debugString.AppendLine("Executioner Difficulty: +10 First time"); reportUnfavorables.AppendLine("+10 / 10: " + "Cults_LRExecFirstTime".Translate(executioner.LabelShort)); } else if (experience < 3) { modifier += 5; debugString.AppendLine("Executioner Difficulty: +10 Inexperienced executioner"); reportUnfavorables.AppendLine("+ 5 / 10: " + "Cults_LRExecInex".Translate( executioner.LabelShort, experience)); } else if (experience < 10) { debugString.AppendLine("Executioner Success: +0 Somewhat-lacking executioner"); reportFavorables.AppendLine("+ 0 / 10: " + "Cults_LRExecEven".Translate( executioner.LabelShort, experience)); } else if (experience < 24) { successModifierOut += 5; debugString.AppendLine("Executioner Success: +5 Experienced executioner"); reportFavorables.AppendLine("+ 5 / 10: " + "Cults_LRExecExp".Translate( executioner.LabelShort, experience)); } else { successModifierOut += 10; debugString.AppendLine("Executioner Success: +10 Expert executioner"); reportFavorables.AppendLine("+10 / 10: " + "Cults_LRExecVeryExp".Translate(executioner.LabelShort, experience)); var executionerBonus = new IntRange(0, 5).RandomInRange; successModifierOut += executionerBonus; debugString.AppendLine("Executioner Success: +" + executionerBonus + " Executioner finesse bonus"); reportFavorables.AppendLine("+" + executionerBonus + " / 5: " + "Cults_LRExecBonus".Translate(executioner.LabelShort)); } worldComponentGlobalCultTracker.GainExperience(executioner, true); return modifier; } private static int SpellCalc_GameConditions(Building_SacrificialAltar altar, StringBuilder s, StringBuilder reportUnfavorables, StringBuilder reportFavorables, out int successModifier) { var modifier = 0; successModifier = 0; var starsAreRight = altar.Map.GameConditionManager.GetActiveCondition<GameCondition_StarsAreRight>(); var starsAreWrong = altar.Map.GameConditionManager.GetActiveCondition<GameCondition_StarsAreWrong>(); var eclipseActive = altar.Map.GameConditionManager.GetActiveCondition(GameConditionDefOf.Eclipse); var auroraActive = altar.Map.GameConditionManager.GetActiveCondition(GameConditionDefOf.Aurora); //Astral events ///////////// if (starsAreRight != null) { s.AppendLine("Map Condition Difficulty: +20 Stars Are Right"); successModifier += 20; reportFavorables.AppendLine("+20 / 20: " + "Cults_LRStarsAreRight".Translate(altar.SacrificeData.Entity.LabelCap)); } else if (starsAreWrong != null) { s.AppendLine("Map Condition Difficulty: +50 Stars Are Wrong"); modifier += 50; reportUnfavorables.AppendLine("+50 / 50: " + "Cults_LRStarsAreWrong".Translate(altar.SacrificeData.Entity.LabelCap)); } else { s.AppendLine("Map Condition Difficulty: +0 No Astral Event"); reportUnfavorables.AppendLine("+ 0 / 50: " + "Cults_LRNoAstralEvents".Translate()); } //Eclipse /////////// if (eclipseActive != null) { s.AppendLine("Map Condition Difficulty: +5 Eclipse Active"); successModifier += 5; reportFavorables.AppendLine("+ 5 / 5: " + "Cults_LREclipseActive".Translate()); } else { s.AppendLine("Map Condition Difficulty: +0 No Eclipse Active"); reportFavorables.AppendLine("+ 0 / 5: " + "Cults_LRNoEclipseActive".Translate()); } //Aurora /////////// if (auroraActive != null) { s.AppendLine("Map Condition Difficulty: +5 Aurora Active"); successModifier += 5; reportFavorables.AppendLine("+ 5 / 5: " + "Cults_LRAuroraActive".Translate()); } else { s.AppendLine("Map Condition Difficulty: +0 No Aurora Active"); reportFavorables.AppendLine("+ 0 / 5: " + "Cults_LRNoAuroraActive".Translate()); } return modifier; } // RimWorld.BaseGen.SymbolResolver_Doors private static bool IsOutdoorsAt(Map map, IntVec3 c) { return c.GetRegion(map) != null && c.GetRegion(map).Room.PsychologicallyOutdoors; } private static int SpellCalc_TempleQuality(Building_SacrificialAltar altar, StringBuilder s, StringBuilder reportFavorables) { var modifier = 0; var deity = altar.SacrificeData.Entity; if (!IsOutdoorsAt(altar.Map, altar.Position)) { var temple = altar.GetRoom(); if (temple == null) { return modifier; } var impressiveScore = temple.GetStat(RoomStatDefOf.Impressiveness); var wealthScore = temple.GetStat(RoomStatDefOf.Wealth); var spaceScore = temple.GetStat(RoomStatDefOf.Space); var beautyScore = temple.GetStat(RoomStatDefOf.Beauty); //Expected quality. 13x13 tiles. Pews. Altar. 2 objects of Lighting. //WEALTH ////////////// if (wealthScore < 2000) { s.AppendLine("Temple Wealth Bonus: +0 - Not good"); reportFavorables.AppendLine("+ 0 / 5: " + "Cults_LRTempWealthNo".Translate()); } if (wealthScore < 4000) { modifier += 3; s.AppendLine("Temple Wealth Bonus: +3 - Good"); reportFavorables.AppendLine("+ 3 / 5: " + "Cults_LRTempWealthDecent".Translate()); } else if (wealthScore >= 4000) { modifier += 5; s.AppendLine("Temple Wealth Bonus: +5 - Great"); reportFavorables.AppendLine("+ 5 / 5: " + "Cults_LRTempWealth".Translate()); } //SPACE ////////////////// if (spaceScore < 160) { s.AppendLine("Temple Space Bonus: +0 - Not good"); reportFavorables.AppendLine("+ 0 / 5: " + "Cults_LRTempSpaceNo".Translate()); } else if (spaceScore < 400) { modifier += 3; s.AppendLine("Temple Space Bonus: +3 - Good"); reportFavorables.AppendLine("+ 3 / 5: " + "Cults_LRTempSpaceDecent".Translate()); } else if (spaceScore >= 400) { modifier += 5; s.AppendLine("Temple Space Bonus: +5 - Great"); reportFavorables.AppendLine("+ 5 / 5: " + "Cults_LRTempSpace".Translate()); } //BEAUTY //////////////// if (beautyScore < 1.59) { s.AppendLine("Temple Beauty Bonus: +0 - Not good"); reportFavorables.AppendLine("+ 0 / 5: " + "Cults_LRTempBeautyNo".Translate()); } else if (beautyScore <= 2.0) { modifier += 3; s.AppendLine("Temple Beauty Bonus: +3 - Good"); reportFavorables.AppendLine("+ 3 / 5: " + "Cults_LRTempBeautyDecent".Translate()); } else if (beautyScore >= 2.0) { modifier += 5; s.AppendLine("Temple Beauty Bonus: +5 - Great"); reportFavorables.AppendLine("+ 5 / 5: " + "Cults_LRTempBeauty".Translate()); } //IMPRESSIVENESS //////////////// if (impressiveScore < 80) { s.AppendLine("Temple Quality Bonus: +0 - Not good"); reportFavorables.AppendLine("+ 0 / 5: " + "Cults_LRTempImpressNo".Translate()); } else if (impressiveScore < 150) { modifier += 3; s.AppendLine("Temple Quality Bonus: + 3 - Good"); reportFavorables.AppendLine("+ 3 / 5: " + "Cults_LRTempImpressDecent".Translate()); } else if (impressiveScore > 150) { modifier += 5; s.AppendLine("Temple Quality Bonus: +5 - Great"); reportFavorables.AppendLine("+ 5 / 5: " + "Cults_LRTempImpress".Translate()); } } else { if (deity.FavorsOutdoorWorship) { modifier += 20; s.AppendLine("Temple Quality Bonus: +20 Outside Deity Favor"); reportFavorables.AppendLine("+20 / 20: " + "Cults_LRTempOutdoorFavored".Translate(deity.LabelCap)); } else { s.AppendLine("Temple Quality Bonus: +0 - No Outside Deity Favor"); reportFavorables.AppendLine("+ 0 / 20: " + "Cults_LRTempNoOutdoorFavored".Translate(deity.LabelCap)); } } return modifier; } private static int SpellCalc_StatuesNearby(Building_SacrificialAltar altar, StringBuilder s, StringBuilder reportFavorables) { var modifier = 0; var statueOfDeityExists = false; var qualityExists = false; var temple = altar.GetRoom(); var deity = altar.SacrificeData.Entity; var sculptures = temple?.ContainedAndAdjacentThings.FindAll(x => x is ThingWithComps y && y.TryGetComp<CompFavoredObject>() != null); if (sculptures != null && sculptures.Count > 0) { foreach (var sculpture in sculptures) { var compFavoredObject = sculpture.TryGetComp<CompFavoredObject>(); if (compFavoredObject?.Deities.FirstOrDefault(y => y.deityDef == deity.def.defName) != null) { statueOfDeityExists = true; } if (!sculpture.TryGetQuality(out var qc)) { continue; } if (qc >= QualityCategory.Normal) { qualityExists = true; } } } if (statueOfDeityExists) { modifier += 10; s.AppendLine("Deity Statue Bonus: Sacrifice modifier + 10"); reportFavorables.AppendLine("+10 / 10: " + "Cults_LRDeityStatue".Translate(deity.LabelCap)); } else { s.AppendLine("No Deity Statue Bonus: Sacrifice modifier + 0"); reportFavorables.AppendLine("+ 0 / 10: " + "Cults_LRNoDeityStatue".Translate(deity.LabelCap)); } if (qualityExists) { modifier += 10; s.AppendLine("Quality Statue Bonus: Sacrifice modifier + 10"); reportFavorables.AppendLine("+10 / 10: " + "Cults_LRQualityStatue".Translate()); } else { s.AppendLine("No Quality Statue Bonus: Sacrifice modifier + 0"); reportFavorables.AppendLine("+ 0 / 10: " + "Cults_LRNoQualityStatue".Translate()); } return modifier; } public static int SpellCalc_CongregationQuality(Building_SacrificialAltar altar, StringBuilder debugLog, StringBuilder reportFavorables) { var modifier = 0; if (altar?.SacrificeData?.Congregation == null) { return modifier; } var deity = altar.SacrificeData.Entity; _ = altar.SacrificeData.Spell; var value = CongregationBonus(altar.SacrificeData.Congregation, deity, out var perfect, out var sacrificialDagger, debugLog); if (value > 0) { modifier += 10; reportFavorables.AppendLine("+10 / 10: " + "Cults_LRAttireBonus".Translate()); debugLog.AppendLine("Attire Bonus: Sacrifice modifier + 10"); } else { reportFavorables.AppendLine("+ 0 / 10: " + "Cults_LRNoAttireBonus".Translate()); debugLog.AppendLine("No Attire Bonus: Sacrifice modifier + 0"); } if (sacrificialDagger) { modifier += 5; reportFavorables.AppendLine("+ 5 / 5: " + "Cults_LRDaggerBonus".Translate()); debugLog.AppendLine("Dagger Bonus: Sacrifice modifier + 5"); } else { reportFavorables.AppendLine("+ 0 / 5: " + "Cults_LRNoDaggerBonus".Translate()); debugLog.AppendLine("No Dagger Bonus: Sacrifice modifier + 0"); } if (perfect) { modifier += 15; reportFavorables.AppendLine("+15 / 15: " + "Cults_LRPerfectBonus".Translate()); debugLog.AppendLine("Perfect Attire Bonus: Sacrifice modifier + 15"); } else { reportFavorables.AppendLine("+ 0 / 15: " + "Cults_LRNoPerfectBonus".Translate()); debugLog.AppendLine("No Perfect Attire Bonus: Sacrifice modifier + 0"); } return modifier; } public static int SpellCalc_TierDifficulty(Building_SacrificialAltar altar, StringBuilder debugLog, StringBuilder reportUnfavorables, StringBuilder reportFavorables) { var modifier = 0; if (altar?.SacrificeData?.Congregation != null ) //Map.GetComponent<MapComponent_SacrificeTracker>().lastSacrificeCongregation != null) { var deity = altar.SacrificeData.Entity; // currentSacrificeDeity; var spell = altar.SacrificeData.Spell; // currentSpell; //Is tier 1? foreach (var current in deity.tier1Spells) { if (current != spell) { continue; } debugLog.AppendLine(current.defName + " is a tier 1 spell. No difficulty modifier added."); reportFavorables.AppendLine("+ 0 / 50: " + "Cults_LRSpellDifficultyOne".Translate()); goto GoToTheEnd; } //Is tier 2? +10% difficulty foreach (var current in deity.tier2Spells) { if (current != spell) { continue; } debugLog.AppendLine(current.defName + " is a tier 2 spell. +10 sacrifice failure rate."); modifier = 10; reportUnfavorables.AppendLine("+10 / 50: " + "Cults_LRSpellDifficultyTwo".Translate()); goto GoToTheEnd; } //Is tier 3? +20% difficulty foreach (var current in deity.tier3Spells) { if (current != spell) { continue; } debugLog.AppendLine(current.defName + " is a tier 3 spell. +20% sacrifice failure rate."); modifier = 20; reportUnfavorables.AppendLine("+20 / 50: " + "Cults_LRSpellDifficultyThree".Translate()); goto GoToTheEnd; } //Is final spell? +50% difficulty if (spell == deity.finalSpell) { debugLog.AppendLine(spell.defName + " is a final spell. +50% sacrifice failure rate."); modifier = 50; reportUnfavorables.AppendLine("+50 / 50: " + "Cults_LRSpellDifficultyFour".Translate()); } //Nothing } GoToTheEnd: return modifier; } public static float CongregationBonus(List<Pawn> congregationIn, CosmicEntity entity, out bool perfect, out bool sacrificialDagger, StringBuilder s2 = null) { var s = new StringBuilder(); if (s2 != null) { s = s2; } s.AppendLine("Congregation Bonus Report"); s.AppendLine("========================="); s.AppendLine(); var congregation = new List<Pawn>(congregationIn); perfect = false; sacrificialDagger = false; var result = 0f; var count = 0; if (congregation.Count == 0) { return result; } if (entity == null) { return result; } //Are they wearing the right outfits? foreach (var member in congregation) { var wearingHood = false; var wearingRobes = false; if (member == null) { count++; continue; } if (member.Dead) { count++; continue; } if (!member.IsColonist) { count++; continue; } if (member.apparel?.WornApparel == null) { continue; } if (member.apparel.WornApparelCount == 0) { continue; } if (member.equipment == null) { continue; } foreach (var clothing in member.apparel.WornApparel) { var favoredObject = clothing.GetComp<CompFavoredObject>(); if (favoredObject != null) { var deities = favoredObject.Deities; if (deities == null || deities.Count <= 0) { continue; } var entry = deities.FirstOrDefault(x => x.deityDef == entity.def.defName); if (entry == null) { continue; } result += entry.favorBonus; if (entry.favorBonus != 0) { s.AppendLine(member.Label + " is wearing " + clothing.Label + " that gives a bonus of " + entry.favorBonus + " for " + entity.Label); } if (!wearingRobes && clothing.def.apparel.layers.Contains(ApparelLayerDefOf.Shell)) { wearingRobes = true; } if (!wearingHood && clothing.def.apparel.layers.Contains(ApparelLayerDefOf.Overhead)) { wearingHood = true; } } else { if (clothing.def.defName == "Apparel_CultistRobes") { wearingRobes = true; result += 0.005f; } if (clothing.def.defName == "Apparel_CultistHood" || clothing.def.defName == "Apparel_StandardHood" || clothing.def.defName == "Apparel_CthulhuMaskHood" || clothing.def.defName == "Apparel_NyarlathotepHood" || clothing.def.defName == "Apparel_DagonMitre" || clothing.def.defName == "Apparel_ShubMask") { wearingHood = true; result += 0.005f; } if (entity.favoredApparel == null) { continue; } if (entity.favoredApparel.Count == 0) { continue; } foreach (var def in entity.favoredApparel) { if (def == null) { continue; } if (clothing.def == def) { result += 0.025f; } } } } if (member.equipment.AllEquipmentListForReading != null && member.equipment.AllEquipmentListForReading.Count > 0) { foreach (var eq in member.equipment.AllEquipmentListForReading) { if (eq.def.defName != "MeleeWeapon_CultKris") { continue; } sacrificialDagger = true; result += 0.005f; s.AppendLine(member.LabelShort + " is wielding a sacrificial dagger."); } } if (wearingHood && wearingRobes) { count++; s.Append(member.LabelShort + " is perfectly attired for the congregation."); s.AppendLine(); } else { s.Append(member.LabelShort + " is not perfectly attired for the congregation."); s.AppendLine(); } } if (result == 0) { RemindPlayerAboutCongregationBonuses(); } if (count >= congregation.Count) { perfect = true; s.Append("Perfect Bonus: +0.05"); s.AppendLine(); result += 0.05f; } s.AppendLine("Congregation Bonus: " + result.ToString("F")); s.AppendLine("========================="); Utility.DebugReport(s.ToString()); return result; } /// <summary> /// When an execution completes, this method should trigger. /// </summary> /// <param name="altar"></param> public static void SacrificeExecutionComplete(Building_SacrificialAltar altar) { altar.ChangeState(Building_SacrificialAltar.State.sacrificing, Building_SacrificialAltar.SacrificeState.finishing); var starsAreRight = altar.Map.GameConditionManager.GetActiveCondition<GameCondition_StarsAreRight>(); var starsAreWrong = altar.Map.GameConditionManager.GetActiveCondition<GameCondition_StarsAreWrong>(); var bstarsAreRight = starsAreRight != null; var bstarsAreWrong = starsAreWrong != null; altar.SacrificeData.Entity.ReceiveSacrifice(altar.SacrificeData.Sacrifice, altar.Map, bstarsAreRight, bstarsAreWrong); var SuccessMod = Rand.Range(0.03f, 0.035f); var FailureMod = Rand.Range(-0.035f, 0.03f); var tracker = altar.Map.GetComponent<MapComponent_SacrificeTracker>(); if (tracker != null) { tracker.lastUsedAltar = altar; if (tracker.lastSacrificeType == SacrificeType.human) { tracker.lastSpell = altar.SacrificeData.Spell; tracker.lastResult = altar.debugAlwaysSucceed ? SacrificeResult.success : GetSacrificeResult(altar.Map); var funTable = new CultTableOfFun(); var result = tracker.lastResult; switch (result) { case SacrificeResult.success: Utility.DebugReport("Sacrifice: Success"); CastSpell(altar.SacrificeData.Spell, altar.Map, true); AffectCultMindedness(altar.SacrificeData.Executioner, SuccessMod); break; case SacrificeResult.mixedsuccess: Utility.DebugReport("Sacrifice: Mixed Success"); CastSpell(altar.SacrificeData.Spell, altar.Map, true); AffectCultMindedness(altar.SacrificeData.Executioner, SuccessMod); funTable.RollTableOfFun(altar.Map); break; case SacrificeResult.failure: Utility.DebugReport("Sacrifice: Failure"); funTable.RollTableOfFun(altar.Map); AffectCultMindedness(altar.SacrificeData.Executioner, FailureMod); SacrificeSpellComplete(altar.SacrificeData.Executioner, altar); break; case SacrificeResult.criticalfailure: Utility.DebugReport("Sacrifice: Critical failure"); AffectCultMindedness(altar.SacrificeData.Executioner, FailureMod); SacrificeSpellComplete(altar.SacrificeData.Executioner, altar); break; } //If it's a prisoner, oh lordy~ var prisoners = altar.Map.mapPawns.PrisonersOfColonySpawned; if (prisoners != null) { foreach (var prisoner in prisoners) { if (prisoner == null) { continue; } if (GenSight.LineOfSight(prisoner.Position, altar.Position, altar.Map, true)) { prisoner.needs?.mood.thoughts.memories.TryGainMemory(CultsDefOf .Cults_OtherPrisonerWasSacrificed); } } } } //Tell the player! MakeSacrificeThoughts(altar.SacrificeData.Executioner, altar.SacrificeData.Sacrifice, true); if (!altar.SacrificeData.Congregation.NullOrEmpty() ) //tracker.lastSacrificeCongregation != null && tracker.lastSacrificeCongregation.Count > 0) { foreach (var pawn in altar.SacrificeData.Congregation) { if (!pawn.Spawned || pawn.Dead || pawn == altar.SacrificeData.Sacrifice) { continue; } TryGainTempleRoomThought(pawn); if (pawn != altar.SacrificeData.Executioner) { MakeSacrificeThoughts(pawn, altar.SacrificeData.Sacrifice); } } } tracker.GenerateSacrificeMessage(); altar.ChangeState(Building_SacrificialAltar.State.sacrificing, Building_SacrificialAltar.SacrificeState.finished); } //Increase the tally Find.World.GetComponent<WorldComponent_GlobalCultTracker>().numHumanSacrifices++; } public static void WorshipComplete(Pawn preacher, Building_SacrificialAltar altar, CosmicEntity deity) { altar.ChangeState(Building_SacrificialAltar.State.worshipping, Building_SacrificialAltar.WorshipState.finishing); deity.ReceiveWorship(preacher); altar.ChangeState(Building_SacrificialAltar.State.worshipping, Building_SacrificialAltar.WorshipState.finished); //altar.currentState = Building_SacrificialAltar.State.finished; var CultistMod = Rand.Range(0.01f, 0.02f); AffectCultMindedness(preacher, CultistMod); var factionBase = (Settlement) altar.Map.info.parent; Messages.Message("WorshipFinished".Translate(factionBase.Label), TargetInfo.Invalid, MessageTypeDefOf.PositiveEvent); } public static void OfferingComplete(Pawn offerer, Building_SacrificialAltar altar, CosmicEntity deity, List<Thing> offering) { //altar.ChangeState(Building_SacrificialAltar.State.worshipping, Building_SacrificialAltar.WorshipState.finishing); altar.ChangeState(Building_SacrificialAltar.State.offering, Building_SacrificialAltar.OfferingState.finished); deity.ReceiveOffering(offerer, altar, offering); var CultistMod = Rand.Range(0.01f, 0.02f); AffectCultMindedness(offerer, CultistMod); if (Utility.IsActorAvailable(offerer)) { var job = new Job(CultsDefOf.Cults_ReflectOnOffering) { targetA = altar }; offerer.jobs.TryTakeOrderedJob(job); //offerer.jobs.EndCurrentJob(JobCondition.InterruptForced); } var factionBase = (Settlement) altar.Map.info.parent; Messages.Message("WorshipFinished".Translate(factionBase.Label), TargetInfo.Invalid, MessageTypeDefOf.PositiveEvent); } public static bool IsSomeoneInvestigating(Map map) { if (map.GetComponent<MapComponent_LocalCultTracker>() != null) { if (map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedState == CultSeedState.NeedWriting) { return true; } } if (map.mapPawns.FreeColonists == null) { return false; } foreach (var colonist in map.mapPawns.FreeColonists) { if (colonist.CurJob == null) { continue; } if (colonist.CurJob.def.defName == "Investigate" || colonist.CurJob.def.defName == "WriteTheBook") { return true; } } return false; } public static bool AreCultObjectsAvailable(Map map) { Utility.DebugReport("Cult Objects Check"); //Do we have a forbidden knowledge center? if (AreForbiddenKnowledgeCentersAvailable(map)) { Utility.DebugReport("FKC Exists"); return true; } //Do we have a book available? if (!AreOccultGrimoiresAvailable(map)) { return false; } Utility.DebugReport("Grimoire Exists"); return true; } public static bool AreOccultGrimoiresAvailable(Map map) { return map?.listerThings.AllThings != null && map.listerThings.ThingsOfDef(ThingDef.Named("Cults_Grimoire")).Count > 0; } public static bool AreForbiddenKnowledgeCentersAvailable(Map map) { return map?.listerBuildings.AllBuildingsColonistOfClass<Building_ForbiddenReserachCenter>() != null && map.listerBuildings.AllBuildingsColonistOfClass<Building_ForbiddenReserachCenter>().Any(); } public static bool AreAltarsAvailable(Map map) { return map.listerBuildings.AllBuildingsColonistOfClass<Building_SacrificialAltar>() != null && map.listerBuildings.AllBuildingsColonistOfClass<Building_SacrificialAltar>().Any(); } public static bool CheckValidCultName(string str) { if (str.Length > 40) { return false; } var str2 = new string(Path.GetInvalidFileNameChars()); var regex = new Regex("[" + Regex.Escape(str2) + "]"); return !regex.IsMatch(str); } public static bool IsPreacher(Pawn p) { var list = p.Map.listerThings.AllThings.FindAll(s => s.GetType() == typeof(Building_SacrificialAltar)); foreach (var thing in list) { var b = (Building_SacrificialAltar) thing; if (b.preacher == p) { return true; } } return false; } public static bool IsExecutioner(Pawn p) { var list = p.Map.listerThings.AllThings.FindAll(s => s.GetType() == typeof(Building_SacrificialAltar)); foreach (var thing in list) { var b = (Building_SacrificialAltar) thing; if (b.SacrificeData?.Executioner == p) { return true; } } return false; } public static bool IsSacrifice(Pawn p) { var list = p.Map.listerThings.AllThings.FindAll(s => s.GetType() == typeof(Building_SacrificialAltar)); foreach (var thing in list) { var b = (Building_SacrificialAltar) thing; if (b.SacrificeData?.Sacrifice == p) { return true; } } return false; } public static bool ResultFalseWithReport(StringBuilder s) { s.Append("ActorAvailble: Result = Unavailable"); Utility.DebugReport(s.ToString()); return false; } public static bool IsCultistAvailable(Pawn pawn) { if (!Utility.IsActorAvailable(pawn)) { return false; } return IsCultMinded(pawn); } public static bool IsCultMinded(Pawn pawn) { if (pawn == null) { Utility.DebugReport("IsCultMinded :: Pawn Null Exception"); return false; } if (pawn.needs == null) { Utility.DebugReport("IsCultMinded :: Pawn Needs Null Exception"); return false; } if (pawn.needs.TryGetNeed<Need_CultMindedness>() != null) { return pawn.needs.TryGetNeed<Need_CultMindedness>().CurLevel > Need_CultMindedness.ThreshHigh; } Utility.DebugReport("IsCultMinded :: Pawn has no cult mind"); return false; } public static bool ShouldAttendSacrifice(Pawn p, Building_SacrificialAltar altar) { if (Utility.IsActorAvailable(altar.SacrificeData.Executioner)) { return p != altar.SacrificeData.Executioner && p != altar.SacrificeData.Sacrifice; } AbortCongregation(altar); return false; //Everyone get over here! } public static bool ShouldAttendWorship(Pawn p, Building_SacrificialAltar altar) { if (Utility.IsActorAvailable(altar.preacher)) { return p != altar.preacher; } AbortCongregation(altar); return false; //Everyone get over here! } public static void RemindPlayerAboutCongregationBonuses() { if (Rand.Range(0, 100) < 20) { Messages.Message("Tip: Wear cultist apparel for a worship bonus.", MessageTypeDefOf.SilentInput); } } public static void AffectCultMindedness(Pawn pawn, float amount = 0f, float max = 0.99f) { var trueMax = max; var cultMindedNeed = pawn?.needs.TryGetNeed<Need_CultMindedness>(); if (cultMindedNeed == null) { return; } var result = pawn.needs.TryGetNeed<Need_CultMindedness>().CurLevel; if (result > trueMax) { trueMax = result; } result += amount; result = Mathf.Clamp(result, 0.01f, trueMax); pawn.needs.TryGetNeed<Need_CultMindedness>().CurLevel = result; } public static void InvestigatedCultSeed(Pawn pawn, Thing investigatee) { //It's a day to remember var taleToAdd = TaleDef.Named("ObservedNightmareMonolith"); if (investigatee is Plant_TreeOfMadness) { taleToAdd = TaleDef.Named("ObservedNightmareTree"); } if ((pawn.IsColonist || pawn.HostFaction == Faction.OfPlayer) && taleToAdd != null) { TaleRecorder.RecordTale(taleToAdd, pawn); } //Internal memory pawn.needs.mood.thoughts.memories.TryGainMemory(CultsDefOf.Cults_MadeInvestigation); Utility.ApplySanityLoss(pawn); AffectCultMindedness(pawn, 0.10f); pawn.Map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedState = CultSeedState.NeedWriting; pawn.Map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedPawn = pawn; } public static void FinishedTheBook(Pawn pawn) { pawn.needs.mood.thoughts.memories.TryGainMemory(CultsDefOf.Cults_BlackoutBook); Utility.ApplySanityLoss(pawn); pawn.Map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedState = CultSeedState.NeedTable; pawn.Map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedPawn = pawn; //Spawn in the book. var spawnLoc = pawn.Position + GenAdj.AdjacentCells[(int) Direction8Way.South]; var unused = pawn.Map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedTarget; var thing = (ThingWithComps) ThingMaker.MakeThing(CultsDefOf.Cults_Grimoire); //thing.SetFaction(Faction.OfPlayer); GenPlace.TryPlaceThing(thing, spawnLoc, pawn.Map, ThingPlaceMode.Near); Find.WindowStack.Add(new Dialog_MessageBox("CultBookSummary".Translate(pawn.Name.ToStringShort), "CultBookLabel".Translate())); } /* public static void AttendSacrificeTickCheckEnd(Pawn pawn, Pawn pawn2, bool isExecutioner = false) { if (pawn == null) return; if (pawn.RaceProps.Animal) return; } */ public static void AttendWorshipTickCheckEnd(Pawn preacher, Pawn pawn) { if (preacher == null) { return; } if (pawn == null) { return; } TryGainTempleRoomThought(pawn); var newThought = GetAttendWorshipThoughts(preacher, pawn); if (newThought != null) { pawn.needs.mood.thoughts.memories.TryGainMemory(newThought); } } public static void HoldWorshipTickCheckEnd(Pawn preacher) { if (preacher == null) { return; } TryGainTempleRoomThought(preacher); AffectCultMindedness(preacher, 0.1f); var newThought = CultsDefOf.Cults_HeldSermon; // DefDatabase<ThoughtDef>.GetNamed("HeldSermon"); if (newThought != null) { preacher.needs.mood.thoughts.memories.TryGainMemory(newThought); } } public static void MakeSacrificeThoughts(Pawn attendee, Pawn other = null, bool isExcutioner = false) { if (attendee == null) { return; } var lastSacrifice = attendee.Map.GetComponent<MapComponent_SacrificeTracker>().lastSacrificeType; //Human sacrifices if (lastSacrifice == SacrificeType.human) { //Sacrifice Thought ThoughtDef resultThought = null; switch (attendee.Map.GetComponent<MapComponent_SacrificeTracker>().lastResult) { case SacrificeResult.mixedsuccess: case SacrificeResult.success: resultThought = IsCultMinded(attendee) ? CultsDefOf.Cults_AttendedSuccessfulSacrifice : CultsDefOf.Cults_InnocentAttendedSuccessfulSacrifice; break; case SacrificeResult.failure: case SacrificeResult.criticalfailure: resultThought = IsCultMinded(attendee) ? CultsDefOf.Cults_AttendedFailedSacrifice : CultsDefOf.Cults_InnocentAttendedFailedSacrifice; break; case SacrificeResult.none: break; } attendee.needs.mood.thoughts.memories.TryGainMemory(resultThought); //Relationship Thoughts if (other == null) { return; } //Family ThoughtDef familyThought = null; if (attendee.relations.FamilyByBlood.Contains(other)) { familyThought = isExcutioner ? CultsDefOf.Cults_ExecutedFamily : CultsDefOf.Cults_SacrificedFamily; } if (familyThought != null) { attendee.needs.mood.thoughts.memories.TryGainMemory(familyThought); } //Friends and Rivals ThoughtDef relationThought = null; var num = attendee.relations.OpinionOf(other); if (num >= 20) { relationThought = isExcutioner ? ThoughtDefOf.KilledMyFriend : CultsDefOf.Cults_SacrificedFriend; } else if (num <= -20) { relationThought = isExcutioner ? ThoughtDefOf.KilledMyRival : CultsDefOf.Cults_SacrificedRival; } if (relationThought != null) { attendee.needs.mood.thoughts.memories.TryGainMemory(relationThought); } //Bloodlust if (!attendee.story.traits.HasTrait(TraitDefOf.Bloodlust)) { return; } attendee.needs.mood.thoughts.memories.TryGainMemory( isExcutioner ? ThoughtDefOf.KilledHumanlikeBloodlust : ThoughtDefOf.WitnessedDeathBloodlust, other); } //Animal Sacrifices else if (lastSacrifice == SacrificeType.animal) { if (other?.RaceProps == null) { return; } if (!other.RaceProps.Animal) { return; } //Pet checker if (other.relations.GetFirstDirectRelationPawn(PawnRelationDefOf.Bond) != attendee) { return; } attendee.needs.mood.thoughts.memories.TryGainMemory( isExcutioner ? CultsDefOf.Cults_ExecutedPet : CultsDefOf.Cults_SacrificedPet, other); } } public static ThoughtDef GetAttendWorshipThoughts(Pawn preacher, Pawn attendee) { //The grades of a sermon are categorized like this internally. const float S_Effect = 0.3f; const float A_Effect = 0.25f; const float B_Effect = 0.1f; const float C_Effect = 0.05f; const float F_Effect = 0.01f; var CultistMod = Rand.Range(0.01f, 0.02f); var InnocentMod = Rand.Range(-0.005f, 0.1f); if (attendee == null) { return null; } var num = preacher.skills.GetSkill(SkillDefOf.Social).Level; num += Rand.Range(-6, 6); //Randomness switch (num) { //S-Ranked Sermon: WOW! case > 20 when IsCultMinded(attendee): AffectCultMindedness(attendee, S_Effect + CultistMod); return CultsDefOf.Cults_AttendedIncredibleSermonAsCultist; case > 20: AffectCultMindedness(attendee, S_Effect + InnocentMod); return CultsDefOf.Cults_AttendedIncredibleSermonAsInnocent; //A-Ranked Sermon: Fantastic case <= 20 and > 15 when IsCultMinded(attendee): AffectCultMindedness(attendee, A_Effect + CultistMod); return CultsDefOf.Cults_AttendedGreatSermonAsCultist; case <= 20 and > 15: AffectCultMindedness(attendee, A_Effect + InnocentMod); return CultsDefOf.Cults_AttendedGreatSermonAsInnocent; //B-Ranked Sermon: Alright case <= 15 and > 10 when IsCultMinded(attendee): AffectCultMindedness(attendee, B_Effect + CultistMod); return CultsDefOf.Cults_AttendedGoodSermonAsCultist; case <= 15 and > 10: AffectCultMindedness(attendee, B_Effect + InnocentMod); return CultsDefOf.Cults_AttendedGoodSermonAsInnocent; //C-Ranked Sermon: Average case <= 10 and > 5 when IsCultMinded(attendee): AffectCultMindedness(attendee, C_Effect + CultistMod); return CultsDefOf.Cults_AttendedDecentSermonAsCultist; case <= 10 and > 5: AffectCultMindedness(attendee, C_Effect + InnocentMod); return CultsDefOf.Cults_AttendedDecentSermonAsInnocent; } //F-Ranked Sermon: Garbage if (IsCultMinded(attendee)) { AffectCultMindedness(attendee, F_Effect + CultistMod); return CultsDefOf.Cults_AttendedAwfulSermonAsCultist; } AffectCultMindedness(attendee, F_Effect + InnocentMod); return CultsDefOf.Cults_AttendedAwfulSermonAsInnocent; } // RimWorld.JoyUtility public static void TryGainTempleRoomThought(Pawn pawn) { var room = pawn.GetRoom(); var def = CultsDefOf.Cults_PrayedInImpressiveTemple; if (pawn == null) { return; } if (room?.Role == null) { return; } if (def == null) { return; } if (room.Role != CultsDefOf.Cults_Temple) { return; } var scoreStageIndex = RoomStatDefOf.Impressiveness.GetScoreStageIndex(room.GetStat(RoomStatDefOf.Impressiveness)); if (def.stages[scoreStageIndex] == null) { return; } pawn.needs.mood.thoughts.memories.TryGainMemory(ThoughtMaker.MakeThought(def, scoreStageIndex)); } public static void GiveAttendSacrificeJob(Building_SacrificialAltar altar, Pawn attendee) { if (IsExecutioner(attendee)) { return; } if (IsSacrifice(attendee)) { return; } if (!Utility.IsActorAvailable(attendee)) { return; } if (attendee.jobs.curJob.def == CultsDefOf.Cults_ReflectOnResult) { return; } if (attendee.jobs.curJob.def == CultsDefOf.Cults_AttendSacrifice) { return; } if (attendee.Drafted) { return; } if (attendee.IsPrisoner) { return; } if (!WatchBuildingUtility.TryFindBestWatchCell(altar, attendee, true, out var result, out var chair)) { if (!WatchBuildingUtility.TryFindBestWatchCell(altar, attendee, false, out result, out chair)) { return; } } var dir = altar.Rotation.Opposite.AsInt; if (chair != null) { var newPos = chair.Position + GenAdj.CardinalDirections[dir]; var J = new Job(CultsDefOf.Cults_AttendSacrifice, altar, newPos, chair) { playerForced = true, ignoreJoyTimeAssignment = true, expiryInterval = 9999, ignoreDesignations = true, ignoreForbidden = true }; //Cthulhu.Utility.DebugReport("Cults :: Original Position " + chair.Position.ToString() + " :: Modded Position " + newPos.ToString()); attendee.jobs.TryTakeOrderedJob(J); //attendee.jobs.EndCurrentJob(JobCondition.Incompletable); } else { var newPos = result + GenAdj.CardinalDirections[dir]; var J = new Job(CultsDefOf.Cults_AttendSacrifice, altar, newPos, result) { playerForced = true, ignoreJoyTimeAssignment = true, expiryInterval = 9999, ignoreDesignations = true, ignoreForbidden = true }; //Cthulhu.Utility.DebugReport("Cults :: Original Position " + result.ToString() + " :: Modded Position " + newPos.ToString()); attendee.jobs.TryTakeOrderedJob(J); //attendee.jobs.EndCurrentJob(JobCondition.Incompletable); } } public static Pawn DetermineBestResearcher(Map map) { Pawn result = null; foreach (var p in map.mapPawns.FreeColonistsSpawned) { if (result == null) { result = p; } if (Utility.GetResearchSkill(result) < Utility.GetResearchSkill(p)) { result = p; } } return result; } public static Pawn DetermineBestPreacher(Map map) { Pawn result = null; foreach (var p in map.mapPawns.FreeColonistsSpawned) { if (result == null) { result = p; } if (IsCultMinded(p) && Utility.GetSocialSkill(result) < Utility.GetSocialSkill(p)) { result = p; } } if (!IsCultMinded(result)) { result = null; } return result; } //Checkyoself public static void GiveAttendWorshipJob(Building_SacrificialAltar altar, Pawn attendee) { //Log.Message("1"); if (IsPreacher(attendee)) { return; } if (!GatheringsUtility.ShouldGuestKeepAttendingGathering(attendee)) { return; } if (attendee.Drafted) { return; } if (attendee.IsPrisoner) { return; } if (attendee.jobs.curJob.def.defName == "ReflectOnWorship") { return; } if (attendee.jobs.curJob.def.defName == "AttendWorship") { return; } if (!WatchBuildingUtility.TryFindBestWatchCell(altar, attendee, true, out var result, out var chair)) { if (!WatchBuildingUtility.TryFindBestWatchCell(altar, attendee, false, out result, out chair)) { return; } } //Log.Message("2"); var dir = altar.Rotation.Opposite.AsInt; Job attendJob; IntVec3 newPos; if (chair != null) { newPos = chair.Position + GenAdj.CardinalDirections[dir]; //Log.Message("3a"); attendJob = new Job(CultsDefOf.Cults_AttendWorship, altar, newPos, chair) { playerForced = true, ignoreJoyTimeAssignment = true, expiryInterval = 9999, ignoreDesignations = true, ignoreForbidden = true }; } else { //Log.Message("3b"); newPos = result + GenAdj.CardinalDirections[dir]; attendJob = new Job(CultsDefOf.Cults_AttendWorship, altar, newPos, result) { playerForced = true, ignoreJoyTimeAssignment = true, expiryInterval = 9999, ignoreDesignations = true, ignoreForbidden = true }; } if (!ModSettings_Data.makeWorshipsVoluntary) { attendee.jobs.EndCurrentJob(JobCondition.Incompletable); attendee.jobs.TryTakeOrderedJob(attendJob); } else { attendee.jobs.jobQueue.EnqueueLast(attendJob); if (attendee.CurJobDef?.defName.Contains("Haul") != true) { attendee.jobs.EndCurrentJob(JobCondition.Incompletable); } } } public static void AbortCongregation(Building_SacrificialAltar altar) { altar?.ChangeState(Building_SacrificialAltar.State.notinuse); } public static void AbortCongregation(Building_SacrificialAltar altar, string reason) { altar?.ChangeState(Building_SacrificialAltar.State.notinuse); Messages.Message(reason + " Aborting congregation.", MessageTypeDefOf.NegativeEvent); } public static void CastSpell(IncidentDef spell, Map map, bool fromAltar = false) { if (spell != null) { var parms = StorytellerUtility.DefaultParmsNow(spell.category, map); spell.Worker.TryExecute(parms); Utility.DebugReport("Cults_Spell cast: " + spell); } if (!fromAltar) { return; } var lastAltar = map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar; SacrificeSpellComplete(lastAltar.SacrificeData.Executioner, lastAltar); } public static void SacrificeSpellComplete(Pawn executioner, Building_SacrificialAltar altar) { if (altar == null) { Utility.DebugReport("Altar Null Exception"); return; } if (executioner == null) { Utility.DebugReport("Executioner null exception"); } if (Utility.IsActorAvailable(executioner)) { var job = new Job(CultsDefOf.Cults_ReflectOnResult) { targetA = altar }; executioner?.jobs.TryTakeOrderedJob(job); //executioner.jobs.EndCurrentJob(JobCondition.InterruptForced); } altar.ChangeState(Building_SacrificialAltar.State.sacrificing, Building_SacrificialAltar.SacrificeState.finished); //altar.currentState = Building_SacrificialAltar.State.finished; //Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar.ChangeState(Building_SacrificialAltar.State.sacrificing, Building_SacrificialAltar.SacrificeState.finished); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/WorkGiver_PruneAndRepair.cs using System.Collections.Generic; using System.Linq; using RimWorld; using Verse; using Verse.AI; namespace CultOfCthulhu { public class WorkGiver_PruneAndRepair : WorkGiver_Scanner { public override ThingRequest PotentialWorkThingRequest => ThingRequest.ForGroup(ThingRequestGroup.BuildingArtificial); public override PathEndMode PathEndMode => PathEndMode.Touch; public IEnumerable<Thing> NightmareAltars(Pawn pawn) { var thingsToCheck = new List<Thing>(from Thing things in pawn.Map.listerBuildings.allBuildingsColonist where things.def.defName == "Cult_NightmareSacrificeAltar" select things); return thingsToCheck; } public override IEnumerable<Thing> PotentialWorkThingsGlobal(Pawn pawn) { return NightmareAltars(pawn); } public override bool ShouldSkip(Pawn pawn, bool forced = false) { return !NightmareAltars(pawn).Any(); } public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { if (!(t is Building_SacrificialAltar building)) { return false; } if (!building.toBePrunedAndRepaired) { return false; } if (t.Faction != pawn.Faction) { return false; } if (pawn.Faction == Faction.OfPlayer && !pawn.Map.areaManager.Home[t.Position]) { JobFailReason.Is(WorkGiver_FixBrokenDownBuilding.NotInHomeAreaTrans); return false; } if (!pawn.CanReserve(t)) { return false; // pawn.Map.reservationManager.IsReserved(t, pawn.Faction)) return false; } return true; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { return new Job(CultsDefOf.Cults_PruneAndRepair, t); } } }<file_sep>/Source/CultOfCthulhu/UI/ITab_AltarHumanSacrificeCardUtility.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using UnityEngine; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { [StaticConstructorOnStartup] public class ITab_AltarHumanSacrificeCardUtility { public static void DrawTempleCard(Rect rect, Building_SacrificialAltar altar) { GUI.BeginGroup(rect); var rect3 = new Rect(2f, 0f, ITab_AltarSacrificesCardUtility.ColumnSize, ITab_AltarSacrificesCardUtility.ButtonSize); Widgets.Label(rect3, "Deity".Translate() + ": "); rect3.xMin = rect3.center.x - 15f; var label2 = ITab_AltarCardUtility.DeityLabel(altar, ITab_AltarCardUtility.DeityType.SacrificeDeity); if (Widgets.ButtonText(rect3, label2, true, false)) { ITab_AltarCardUtility.OpenDeitySelectMenu(altar, ITab_AltarCardUtility.DeityType.SacrificeDeity); } TooltipHandler.TipRegion(rect3, "DeityDesc".Translate()); ITab_AltarCardUtility.DrawDeity(altar.tempCurrentSacrificeDeity, rect3, SpellDescription(altar)); var rect4 = rect3; rect4.y += ITab_AltarSacrificesCardUtility.ButtonSize + 15f; rect4.width = ITab_AltarSacrificesCardUtility.ColumnSize; rect4.x -= rect3.x; rect4.x += 2f; Widgets.Label(rect4, "Executioner".Translate() + ": "); rect4.xMin = rect4.center.x - 15f; var label3 = ITab_AltarCardUtility.ExecutionerLabel(altar); if (Widgets.ButtonText(rect4, label3, true, false)) { ITab_AltarCardUtility.OpenActorSelectMenu(altar, ITab_AltarCardUtility.ActorType.executioner); } TooltipHandler.TipRegion(rect4, "ExecutionerDesc".Translate()); var rect5 = rect4; rect5.y += ITab_AltarSacrificesCardUtility.ButtonSize + 15f; rect5.x -= rect4.x; rect5.x += 2f; rect5.width = ITab_AltarSacrificesCardUtility.ColumnSize; Widgets.Label(rect5, "Sacrifice".Translate() + ": "); rect5.xMin = rect5.center.x - 15f; var label4 = ITab_AltarCardUtility.SacrificeLabel(altar); if (Widgets.ButtonText(rect5, label4, true, false)) { ITab_AltarCardUtility.OpenActorSelectMenu(altar, ITab_AltarCardUtility.ActorType.prisoner); } TooltipHandler.TipRegion(rect5, "SacrificeDesc".Translate()); var rect6 = rect5; rect6.y += ITab_AltarSacrificesCardUtility.ButtonSize + 15f; rect6.x -= rect5.x; rect6.x += 2f; rect6.width = ITab_AltarSacrificesCardUtility.ColumnSize; rect6.yMax += ITab_AltarSacrificesCardUtility.ButtonSize + 15f; Widgets.Label(rect6, "Cults_Spell".Translate() + ": "); rect6.xMin = rect6.center.x - 15f; var label5 = SpellLabel(altar); if (Widgets.ButtonText(rect6, label5, true, false)) { OpenSpellSelectMenu(altar); } TooltipHandler.TipRegion(rect6, "Cults_SpellDesc".Translate()); GUI.EndGroup(); } //private static string SacrificeLabel(Building_SacrificialAltar altar) //{ // if (altar.tempSacrifice == null) // { // return "None"; // } // else // { // return altar.tempSacrifice.Name.ToStringShort; // } //} //private static string ExecutionerLabel(Building_SacrificialAltar altar) //{ // if (altar.tempExecutioner == null) // { // return "None"; // } // else // { // return altar.tempExecutioner.Name.ToStringShort; // } //} //private static string DeityLabel(Building_SacrificialAltar altar) //{ // if (altar.tempCurrentSacrificeDeity == null) // { // return "None"; // } // else // { // return altar.tempCurrentSacrificeDeity.LabelCap; // } //} private static string SpellLabel(Building_SacrificialAltar altar) { return altar.tempCurrentSacrificeDeity == null || altar.tempCurrentSpell == null ? "None" : (string) altar.tempCurrentSpell.LabelCap; } private static string SpellDescription(Building_SacrificialAltar altar) { return altar.tempCurrentSacrificeDeity == null || altar.tempCurrentSpell == null ? "None" : altar.tempCurrentSpell.description; } //private static string DeityDescription(Building_SacrificialAltar altar) //{ // if (altar.tempCurrentSacrificeDeity == null) // { // return "None"; // } // else // { // StringBuilder stringBuilder = new StringBuilder(); // //stringBuilder.Append(altar.tempCurrentSacrificeDeity.LabelCap); // stringBuilder.AppendLine(); // stringBuilder.Append(altar.tempCurrentSacrificeDeity.def.description); // //stringBuilder.AppendLine(); // //stringBuilder.Append("Standing: " + altar.tempCurrentSacrificeDeity.PlayerFavor.ToString()); // //stringBuilder.AppendLine(); // //stringBuilder.Append("Tier: " + altar.tempCurrentSacrificeDeity.PlayerTier.ToString()); // return stringBuilder.ToString(); // } //} /* private static void ForceListenersTest(Building_SacrificialAltar altar) { IntVec3 result; Building chair; foreach (Pawn p in Find.MapPawns.AllPawnsSpawned.FindAll(x => x.RaceProps.intelligence == Intelligence.Humanlike)) { if (!SermonUtility.IsPreacher(p)) { if (!WatchBuildingUtility.TryFindBestWatchCell(altar, p, true, out result, out chair)) { if (!WatchBuildingUtility.TryFindBestWatchCell(altar as Thing, p, false, out result, out chair)) { return; } } if (chair != null) { Job J = new Job(CorruptionDefOfs.AttendSermon, altar.preacher, altar, chair); p.QueueJob(J); p.CurJob.EndCurrentJob(JobCondition.InterruptForced); } else { Job J = new Job(CorruptionDefOfs.AttendSermon, altar.preacher, altar, result); p.QueueJob(J); p.CurJob.EndCurrentJob(JobCondition.InterruptForced); } } } } */ //public static void OpenSacrificeSelectMenu(Building_SacrificialAltar altar) //{ // List<FloatMenuOption> list = new List<FloatMenuOption>(); // list.Add(new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate // { // altar.tempSacrifice = null; // }, MenuOptionPriority.Default, null, null, 0f, null)); // foreach (Pawn current in altar.Map.mapPawns.PrisonersOfColonySpawned) // { // if (!current.Dead && !current.InAggroMentalState) // { // Action action; // Pawn localCol = current; // action = delegate // { // altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; // altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastSacrificeType = CultUtility.SacrificeType.human; // altar.tempSacrifice = localCol; // }; // list.Add(new FloatMenuOption(localCol.LabelShort, action, MenuOptionPriority.Default, null, null, 0f, null)); // } // } // Find.WindowStack.Add(new FloatMenu(list)); //} //public static void OpenExecutionerSelectMenu(Building_SacrificialAltar altar) //{ // List<FloatMenuOption> list = new List<FloatMenuOption>(); // list.Add(new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate // { // altar.tempExecutioner = null; // }, MenuOptionPriority.Default, null, null, 0f, null)); // if (altar != null) // { // list.Add(new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate // { // altar.tempExecutioner = null; // }, MenuOptionPriority.Default, null, null, 0f, null)); // foreach (Pawn current in altar.Map.mapPawns.FreeColonists) // { // if (CultUtility.IsCultMinded(current)) // { // if (current == null) continue; // if (current.Dead) continue; // if (current.IsPrisoner) continue; // if (current.health.capacities.CapableOf(PawnCapacityDefOf.Manipulation) && // current.health.capacities.CapableOf(PawnCapacityDefOf.Moving)) // { // Action action; // Pawn localCol = current; // action = delegate // { // altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; // altar.tempExecutioner = localCol; // }; // list.Add(new FloatMenuOption(localCol.LabelShort, action, MenuOptionPriority.Default, null, null, 0f, null)); // } // } // } // } // Find.WindowStack.Add(new FloatMenu(list)); //} //public static void OpenDeitySelectMenu(Building_SacrificialAltar altar) //{ // List<FloatMenuOption> list = new List<FloatMenuOption>(); // list.Add(new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate // { // altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; // altar.tempCurrentSacrificeDeity = null; // }, MenuOptionPriority.Default, null, null, 0f, null)); // foreach (CosmicEntity current in DeityTracker.Get.DeityCache.Keys) // { // if (current.discovered == false) continue; // Action action; // CosmicEntity localDeity = current; // action = delegate // { // altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; // altar.tempCurrentSacrificeDeity = localDeity; // altar.tempCurrentSpell = null; // }; // list.Add(new FloatMenuOption(localDeity.LabelCap, action, MenuOptionPriority.Default, null, null, 0f, null)); // } // Find.WindowStack.Add(new FloatMenu(list)); //} public static void OpenSpellSelectMenu(Building_SacrificialAltar altar) { var list = new List<FloatMenuOption> { new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate { altar.tempCurrentSpell = null; }) }; if (altar.tempCurrentSacrificeDeity != null) { if (altar.tempCurrentSacrificeDeity.tier1Spells != null && altar.tempCurrentSacrificeDeity.PlayerTier > 0) { foreach (var spell in altar.tempCurrentSacrificeDeity.tier1Spells) { var localSpell = spell; void Action() { altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; altar.tempCurrentSpell = localSpell; } list.Add(new FloatMenuOption(localSpell.LabelCap, Action)); } } if (altar.tempCurrentSacrificeDeity.tier2Spells != null && altar.tempCurrentSacrificeDeity.PlayerTier > CosmicEntity.Tier.One) { foreach (var spell in altar.tempCurrentSacrificeDeity.tier2Spells) { var localSpell = spell; void Action2() { altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; altar.tempCurrentSpell = localSpell; } list.Add(new FloatMenuOption(localSpell.LabelCap, Action2)); } } if (altar.tempCurrentSacrificeDeity.tier3Spells != null && altar.tempCurrentSacrificeDeity.PlayerTier > CosmicEntity.Tier.Two) { foreach (var spell in altar.tempCurrentSacrificeDeity.tier3Spells) { var localSpell = spell; void Action3() { altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; altar.tempCurrentSpell = localSpell; } list.Add(new FloatMenuOption(localSpell.LabelCap, Action3)); } } if (altar.tempCurrentSacrificeDeity.finalSpell != null && altar.tempCurrentSacrificeDeity.PlayerTier > CosmicEntity.Tier.Three) { var localSpell = altar.tempCurrentSacrificeDeity.finalSpell; void Action4() { altar.Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; altar.tempCurrentSpell = localSpell; } list.Add(new FloatMenuOption(localSpell.LabelCap, Action4)); } } Find.WindowStack.Add(new FloatMenu(list)); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/ShubNiggurath/SpellWorker_TransmogrifyPets.cs using System.Collections.Generic; using System.Linq; using RimWorld; using Verse; //using RimWorld.SquadAI; namespace CultOfCthulhu { public class SpellWorker_TransmogrifyPets : SpellWorker { public override bool CanSummonNow(Map map) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); if (PetsToTransmogrify(map).Any()) { return true; } Messages.Message("No pets to transmogrify", MessageTypeDefOf.RejectInput); return false; } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; Transmogrify(map); return true; } public IEnumerable<Pawn> PetsToTransmogrify(Map map) { //Get a pet with a master. var one = from Pawn pets in map.mapPawns.AllPawnsSpawned where !(pets?.GetComp<CompTransmogrified>()?.IsTransmogrified ?? true) && pets.RaceProps.Animal && pets.Faction == Faction.OfPlayer && !pets.Dead && !pets.Downed && pets.RaceProps.petness > 0f && pets.playerSettings.Master != null select pets; //No master? Okay, still search for pets. if (!one.Any()) { one = from Pawn pets in map.mapPawns.AllPawnsSpawned where !(pets?.GetComp<CompTransmogrified>()?.IsTransmogrified ?? true) && pets.RaceProps.Animal && pets.Faction == Faction.OfPlayer && !pets.Dead && !pets.Downed && pets.RaceProps.petness > 0f select pets; } //No pets? Okay, search for player animals. if (!one.Any()) { one = from Pawn pets in map.mapPawns.AllPawnsSpawned where !(pets?.GetComp<CompTransmogrified>()?.IsTransmogrified ?? true) && pets.RaceProps.Animal && pets.Faction == Faction.OfPlayer && !pets.Dead && !pets.Downed select pets; } //Return anything if we find anything, or return a null, it's all good. return one; } public void Transmogrify(Map map, Pawn pawn = null, int count = 3) { if (count <= 0) { return; } //No pawn? Okay, find one. if (pawn == null) { pawn = PetsToTransmogrify(map).RandomElement(); } Messages.Message("Cults_TransmogrifyAnimalsOnly".Translate( pawn.LabelShort ), MessageTypeDefOf.NeutralEvent); var parms = new TargetingParameters { canTargetPawns = true }; var foundTarget = false; var thisCount = count; Find.Targeter.BeginTargeting(parms, delegate(LocalTargetInfo t) { if (t.Thing is not Pawn tP) { return; } if (!(tP.RaceProps?.Animal ?? false)) { return; } pawn = tP; var compTrans = tP.GetComp<CompTransmogrified>(); if (compTrans == null) { return; } compTrans.IsTransmogrified = true; foundTarget = true; Messages.Message("Cults_TransmogrifyMessage".Translate( pawn.LabelShort ), MessageTypeDefOf.PositiveEvent); }, null, delegate { if (!foundTarget) { LongEventHandler.QueueLongEvent(delegate { Transmogrify(map, pawn, thisCount - 1); }, "transmogrify", false, null); } }); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Cthulhu/SpellWorker_AspectOfCthulhu.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_AspectOfCthulhu : SpellWorker { protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport(" //: " + this.def.defName); return true; } //protected Pawn TestPawn(Map map) //{ // //IEnumerable<Pawn> list = PawnsToTransmogrify(map).InRandomOrder<Pawn>(); // //Pawn pawn; // //if (!list.TryRandomElement<Pawn>(out pawn)) // //{ // // if (altar(map) != null) // // { // // if (altar(map).executioner != null) // return // // } // //} // //return pawn; //} //public IEnumerable<Pawn> PawnsToTransmogrify(Map map) //{ // //Get a colonist downed or bed-ridden incapable of moving // IEnumerable<Pawn> one = from Pawn peeps in map.mapPawns.FreeColonists // where (peeps.RaceProps.Humanlike && peeps.Faction == Faction.OfPlayer && !peeps.Dead) && (peeps.Downed || peeps.InBed()) && !peeps.health.capacities.CapableOf(PawnCapacityDefOf.Moving) // select peeps; // if (one.Count<Pawn>() > 0) // { // return one; // } // //Get a colonist. // IEnumerable<Pawn> two = from Pawn peeps in map.mapPawns.FreeColonists // where (peeps.RaceProps.Humanlike && peeps.Faction == Faction.OfPlayer && !peeps.Dead) // select peeps; // return two; //} public void ApplyAspect(Pawn p, int count = 3) { if (count <= 0) { return; } var parms = new TargetingParameters { canTargetPawns = true }; var foundPawn = false; Messages.Message("Cults_AspectOfCthulhu_TargetACharacter".Translate(), MessageTypeDefOf.NeutralEvent); Find.Targeter.BeginTargeting(parms, delegate(LocalTargetInfo t) { if (t.Thing is not Pawn pawn) { return; } BodyPartRecord tempRecord = null; var isEye = false; foreach (var current in pawn.RaceProps.body.AllParts.InRandomOrder()) { if (current.def == BodyPartDefOf.Eye) { if (pawn.health.hediffSet.PartIsMissing(current)) { isEye = true; pawn.health.RestorePart(current); tempRecord = current; goto Leap; } } if (current.def != BodyPartDefOf.Leg && current.def != BodyPartDefOf.Arm && current.def != BodyPartDefOf.Hand) { continue; } if (!pawn.health.hediffSet.PartIsMissing(current)) { continue; } pawn.health.RestorePart(current); tempRecord = current; goto Leap; } foreach (var current in pawn.RaceProps.body.AllParts.InRandomOrder()) { if (current.def == BodyPartDefOf.Eye) { isEye = true; tempRecord = current; break; } if (current.def != BodyPartDefOf.Leg && current.def != BodyPartDefOf.Arm && current.def != BodyPartDefOf.Hand) { continue; } tempRecord = current; break; } Leap: //Error catch: Missing parts! if (tempRecord == null) { Log.Error("Couldn't find part of the pawn to replace."); return; } pawn.health.AddHediff(isEye ? CultsDefOf.Cults_CthulhidEyestalk : CultsDefOf.Cults_CthulhidTentacle, tempRecord); Messages.Message("Cults_AspectOfCthulhuDesc".Translate( pawn.LabelShort, tempRecord.def.label), MessageTypeDefOf.PositiveEvent); pawn.Map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = pawn.Position; foundPawn = true; }, null, delegate { if (!foundPawn) { LongEventHandler.QueueLongEvent(delegate { ApplyAspect(p, count - 1); }, "aspectOfCthulhu", false, null); } }); } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; var pawn = altar(map).SacrificeData.Executioner; ApplyAspect(pawn); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/SpellWorker_Reincarnation.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_Reincarnation : SpellWorker { private static Map map; private static IntVec3 pos; private static Pawn exSacrifice; private static Corpse deadBody; protected Corpse corpse(Map map) { var c = map.thingGrid.ThingAt<Corpse>(altar(map).Position); return c; } protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport(" //: " + this.def.defName); return true; } protected override bool TryExecuteWorker(IncidentParms parms) { map = parms.target as Map; pos = altar(map).Position; exSacrifice = corpse(map).InnerPawn; deadBody = corpse(map); LongEventHandler.QueueLongEvent(delegate { //Throw some smoke MoteMaker.ThrowDustPuff(pos, map, 2f); //Make the body strip and despawn around the altar deadBody.Strip(); deadBody.DeSpawn(); //Trigger the nightmare event on the altar altar(map).NightmareEvent(); Utility.ApplyTaleDef("Cults_SpellReincarnation", deadBody.InnerPawn); }, "Cults_SpellReincarnation", false, null); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Hastur/SpellWorker_VisionsOfCarcosa.cs using System.Collections.Generic; using RimWorld; using UnityEngine; using Verse; namespace CultOfCthulhu { internal class SpellWorker_VisionsOfCarcosa : SpellWorker { public override bool CanSummonNow(Map map) { return true; } protected override bool TryExecuteWorker(IncidentParms parms) { if (!(parms.target is Map map)) { return false; } var colonistCount = (float) map.mapPawns.FreeColonistsSpawned.Count; var sleeperPercent = 0.8f; var math = colonistCount * sleeperPercent; var numberToSleep = Mathf.CeilToInt(Mathf.Clamp(math, 1, colonistCount)); var sleepers = new List<Pawn>(map.mapPawns.FreeColonistsSpawned.InRandomOrder()); for (var i = 0; i < numberToSleep; i++) { sleepers[i].mindState.mentalStateHandler.TryStartMentalState(CultsDefOf.Cults_DeepSleepCarcosa, "Sacrifice".Translate(), false, true); } return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/AntiCult/JobDriver_MidnightInquisition.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using RimWorld; using Verse; using Verse.AI; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class JobDriver_MidnightInquisition : JobDriver { private readonly TargetIndex InquisitorIndex = TargetIndex.A; private readonly TargetIndex PreacherIndex = TargetIndex.B; private bool firstHit = true; private bool notifiedPlayer; private Pawn Preacher => job.GetTarget(TargetIndex.B).Thing as Pawn; protected Pawn Inquisitor => (Pawn) job.GetTarget(TargetIndex.A).Thing; public override bool TryMakePreToilReservations(bool errorOnFailed) { return true; } protected override IEnumerable<Toil> MakeNewToils() { // var toil = new Toil { initAction = delegate { //Empty } }; this.EndOnDespawnedOrNull(InquisitorIndex); this.EndOnDespawnedOrNull(PreacherIndex); //this.EndOnDespawnedOrNull(Build, JobCondition.Incompletable); yield return Toils_Reserve.Reserve(PreacherIndex, job.def.joyMaxParticipants); var gotoPreacher = Toils_Goto.GotoThing(PreacherIndex, PathEndMode.ClosestTouch); yield return gotoPreacher; if (Preacher.jobs.curDriver.asleep) { var watchToil = new Toil { defaultCompleteMode = ToilCompleteMode.Delay, defaultDuration = job.def.joyDuration }; watchToil.AddPreTickAction(() => { pawn.rotationTracker.FaceCell(Preacher.Position); pawn.GainComfortFromCellIfPossible(); }); yield return watchToil; } void hitAction() { var prey = Preacher; var surpriseAttack = firstHit; if (pawn.meleeVerbs.TryMeleeAttack(prey, job.verbToUse, surpriseAttack)) { if (!notifiedPlayer && PawnUtility.ShouldSendNotificationAbout(prey)) { notifiedPlayer = true; if (Prefs.AutomaticPauseMode > AutomaticPauseMode.Never && !Find.TickManager.Paused) { Find.TickManager.TogglePaused(); } Messages.Message("MessageAttackedByPredator".Translate( prey.LabelShort, pawn.LabelShort ).CapitalizeFirst(), prey, MessageTypeDefOf.ThreatBig); } pawn.Map.attackTargetsCache.UpdateTarget(pawn); } firstHit = false; } yield return Toils_Combat.FollowAndMeleeAttack(TargetIndex.A, hitAction) .JumpIfDespawnedOrNull(TargetIndex.A, toil).FailOn(() => Find.TickManager.TicksGame > startTick + 5000 && (job.GetTarget(TargetIndex.A).Cell - pawn.Position).LengthHorizontalSquared > 4f); yield return toil; AddFinishAction(() => { //if (this.TargetB.HasThing) //{ // Find.Reservations.Release(this.job.targetC.Thing, pawn); //} }); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Bast/SpellWorker_Sanctuary.cs using System.Collections.Generic; using CultOfCthulhu; using RimWorld; using Verse; using Verse.AI; namespace BastCult { /// <summary> /// This spell forces most enemies to flee in terror. /// </summary> public class SpellWorker_Sanctuary : SpellWorker { public override bool CanSummonNow(Map map) { if (GenHostility.AnyHostileActiveThreatToPlayer(map)) { return true; } Messages.Message("Cults_BastNoEnemiesOnMap".Translate(), MessageTypeDefOf.RejectInput); return false; } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; if (!GenHostility.AnyHostileActiveThreatToPlayer(map)) { return true; } //Grab all hostile targets. var hashSet = new HashSet<IAttackTarget>(map?.attackTargetsCache.TargetsHostileToFaction(Faction.OfPlayer)!); if (hashSet.Count <= 0) { return true; } foreach (var target in hashSet) { if (target is Pawn enemyPawn && !enemyPawn.RaceProps.IsMechanoid && enemyPawn.GetStatValue(StatDefOf.PsychicSensitivity) >= 0.5f) { //Force panic fleeing enemyPawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.PanicFlee, "Cults_BastSanctuaryEnemy".Translate(), true); } } return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Sacrifice/JobDriver_TiedDown.cs using System.Collections.Generic; using RimWorld; using Verse; using Verse.AI; namespace CultOfCthulhu { public class JobDriver_TiedDown : JobDriver_Wait { protected Building_SacrificialAltar DropAltar => (Building_SacrificialAltar) job.GetTarget(TargetIndex.A).Thing; protected override IEnumerable<Toil> MakeNewToils() { yield return new Toil { initAction = delegate { pawn.Reserve(pawn.Position, job); // De ReserveDestinationFor(this.pawn, this.pawn.Position); pawn.pather.StopDead(); var curDriver = pawn.jobs.curDriver; pawn.jobs.posture = PawnPosture.LayingOnGroundFaceUp; curDriver.asleep = false; }, tickAction = delegate { if (job.expiryInterval == -1 && job.def == JobDefOf.Wait_Combat && !pawn.Drafted) { Log.Error(pawn + " in eternal WaitCombat without being drafted."); ReadyForNextToil(); return; } if ((Find.TickManager.TicksGame + pawn.thingIDNumber) % 4 == 0) { //base.CheckForAutoAttack(); } }, defaultCompleteMode = ToilCompleteMode.Never }; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Psionics/DamageWorker_PsionicShock.cs using RimWorld; using Verse; namespace CultOfCthulhu { internal class DamageWorker_PsionicShock : DamageWorker { public override DamageResult Apply(DamageInfo dinfo, Thing victim) { var result = new DamageResult(); if (victim is not Pawn pawn) { return result; } if (!pawn.Spawned || pawn.Dead) { return result; } if (pawn.health == null) { return result; } var d20 = Rand.Range(1, 20); if (d20 <= 1) { MoteMaker.ThrowText(dinfo.Instigator.DrawPos, dinfo.Instigator.Map, "Critical Failure", 12.0f); if (dinfo.Instigator == null) { return result; } if (dinfo.Instigator is Pawn pawn2) { pawn2.TakeDamage(new DamageInfo(DamageDefOf.Stun, 60)); } return result; } if (d20 <= 5) { MoteMaker.ThrowText(dinfo.Instigator.DrawPos, dinfo.Instigator.Map, "Failure", 12.0f); if (dinfo.Instigator == null) { return result; } if (dinfo.Instigator is Pawn pawn2) { pawn2.TakeDamage(new DamageInfo(DamageDefOf.Stun, 10)); } return result; } if (d20 <= 10) { MoteMaker.ThrowText(dinfo.Instigator.DrawPos, dinfo.Instigator.Map, "Success", 12.0f); pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Wander_Psychotic, "psionic shock"); return result; } if (d20 <= 15) { MoteMaker.ThrowText(dinfo.Instigator.DrawPos, dinfo.Instigator.Map, "Success", 12.0f); pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk, "psionic shock"); return result; } if (d20 < 18) { MoteMaker.ThrowText(dinfo.Instigator.DrawPos, dinfo.Instigator.Map, "Success", 12.0f); var part = pawn.health.hediffSet.GetBrain(); if (part == null) { Log.ErrorOnce("Cults :: Missing Brain", 6781923); } pawn.TakeDamage(new DamageInfo(CultsDefOf.Cults_Psionic, Rand.Range(5, 8), 1f, -1, dinfo.Instigator, part)); return result; } else { MoteMaker.ThrowText(dinfo.Instigator.DrawPos, dinfo.Instigator.Map, "Critical Success", 12.0f); var part = pawn.health.hediffSet.GetBrain(); if (part == null) { Log.ErrorOnce("Cults :: Missing Brain", 6781923); } victim.TakeDamage(new DamageInfo(CultsDefOf.Cults_Psionic, 9999, 1f, -1, dinfo.Instigator, part)); return result; } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/CultistExperience.cs using Verse; namespace CultOfCthulhu { public class CultistExperience : IExposable { private int preachCount; private int sacrificeCount; public CultistExperience() { } public CultistExperience(CultistExperience copy) { sacrificeCount = copy.SacrificeCount; preachCount = copy.PreachCount; } public CultistExperience(int sacrificeCount, int preachCount) { this.sacrificeCount = sacrificeCount; this.preachCount = preachCount; } public int SacrificeCount { get => sacrificeCount; set => sacrificeCount = value; } public int PreachCount { get => preachCount; set => preachCount = value; } public void ExposeData() { Scribe_Values.Look(ref sacrificeCount, "sacrificeCount"); Scribe_Values.Look(ref preachCount, "preachCount"); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Sacrifice/JobDriver_HoldSacrifice.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Diagnostics; using Cthulhu; using RimWorld; using Verse; using Verse.AI; using Verse.AI.Group; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class JobDriver_HoldSacrifice : JobDriver { private const TargetIndex TakeeIndex = TargetIndex.A; private const TargetIndex AltarIndex = TargetIndex.B; protected Pawn Takee => (Pawn) job.GetTarget(TargetIndex.A).Thing; protected Building_SacrificialAltar DropAltar => (Building_SacrificialAltar) job.GetTarget(TargetIndex.B).Thing; public override bool TryMakePreToilReservations(bool errorOnFailed) { return true; } [DebuggerHidden] protected override IEnumerable<Toil> MakeNewToils() { //Commence fail checks! this.FailOnDestroyedOrNull(TargetIndex.A); this.FailOnDestroyedOrNull(TargetIndex.B); this.FailOnAggroMentalState(TargetIndex.A); yield return Toils_Reserve.Reserve(TakeeIndex); yield return Toils_Reserve.Reserve(AltarIndex, Building_SacrificialAltar.LyingSlotsCount); yield return new Toil { initAction = delegate { DropAltar.ChangeState(Building_SacrificialAltar.State.sacrificing, Building_SacrificialAltar.SacrificeState.gathering); } }; //Toil 1: Go to prisoner. yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch) .FailOnDespawnedNullOrForbidden(TargetIndex.A).FailOnDespawnedNullOrForbidden(TargetIndex.B) .FailOn(() => job.def == JobDefOf.Arrest && !Takee.CanBeArrestedBy(pawn)) .FailOn(() => !pawn.CanReach(DropAltar, PathEndMode.OnCell, Danger.Deadly)) .FailOnSomeonePhysicallyInteracting(TargetIndex.A); yield return new Toil { initAction = delegate { if (!job.def.makeTargetPrisoner) { return; } var targetAThing = (Pawn) job.targetA.Thing; var lord = targetAThing.GetLord(); lord?.Notify_PawnAttemptArrested(targetAThing); GenClamor.DoClamor(targetAThing, 10f, ClamorDefOf.Harm); if (job.def == JobDefOf.Arrest && !targetAThing.CheckAcceptArrest(pawn)) { pawn.jobs.EndCurrentJob(JobCondition.Incompletable); } } }; //Toil 2: Carry prisoner. yield return Toils_Haul.StartCarryThing(TargetIndex.A); //Toil 3: Go to the altar. yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.InteractionCell); //Toil 4: Release the prisoner. yield return Toils_Reserve.Release(TargetIndex.B); //Toil 5: Restrain the prisoner. yield return new Toil { initAction = delegate { //In-case this fails... var position = DropAltar.Position; pawn.carryTracker.TryDropCarriedThing(position, ThingPlaceMode.Direct, out _); if (DropAltar.Destroyed || !DropAltar.AnyUnoccupiedLyingSlot) { return; } Takee.Position = DropAltar.GetLyingSlotPos(); Takee.Notify_Teleported(false); Takee.stances.CancelBusyStanceHard(); var newJob = new Job(CultsDefOf.Cults_WaitTiedDown, DropAltar); Takee.jobs.StartJob(newJob); }, defaultCompleteMode = ToilCompleteMode.Instant }; //Toil 6: Time to chant ominously var chantingTime = new Toil { defaultCompleteMode = ToilCompleteMode.Delay, defaultDuration = CultUtility.ritualDuration }; chantingTime.WithProgressBarToilDelay(TargetIndex.A); chantingTime.PlaySustainerOrSound(CultsDefOf.RitualChanting); var deitySymbol = ((CosmicEntityDef) DropAltar.SacrificeData.Entity.def).Symbol; chantingTime.initAction = delegate { if (deitySymbol != null) { MoteMaker.MakeInteractionBubble(pawn, null, ThingDefOf.Mote_Speech, deitySymbol); } //STATE - SACRIFICING DropAltar.ChangeState(Building_SacrificialAltar.State.sacrificing, Building_SacrificialAltar.SacrificeState.sacrificing); }; yield return chantingTime; //Toil 8: Execution of Prisoner yield return new Toil { initAction = delegate { //BodyPartDamageInfo value = new BodyPartDamageInfo(this.Takee.health.hediffSet.GetBrain(), false, quiet); Takee.TakeDamage(new DamageInfo(DamageDefOf.ExecutionCut, 99999, 0f, -1f, pawn, Utility.GetHeart(Takee.health.hediffSet))); if (!Takee.Dead) { Takee.Kill(null); } //ThoughtUtility.GiveThoughtsForPawnExecuted(this.Takee, PawnExecutionKind.GenericHumane); TaleRecorder.RecordTale(TaleDefOf.ExecutedPrisoner, pawn, Takee); CultUtility.SacrificeExecutionComplete(DropAltar); }, defaultCompleteMode = ToilCompleteMode.Instant }; AddFinishAction(() => { //It's a day to remember var taleToAdd = TaleDef.Named("HeldSermon"); if ((pawn.IsColonist || pawn.HostFaction == Faction.OfPlayer) && taleToAdd != null) { TaleRecorder.RecordTale(taleToAdd, pawn); } //When the ritual is finished -- then let's give the thoughts /* if (DropAltar.currentSacrificeState == Building_SacrificialAltar.SacrificeState.finished) { if (this.pawn == null) return; if (DropAltar.sacrifice != null) { CultUtility.AttendSacrificeTickCheckEnd(this.pawn, DropAltar.sacrifice, true); } else { CultUtility.AttendSacrificeTickCheckEnd(this.pawn, null); } } */ }); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/PawnFlyer.cs using System.Collections.Generic; using RimWorld; using UnityEngine; using Verse; using Verse.Sound; namespace CultOfCthulhu { public class PawnFlyer : Pawn { private CompLaunchablePawn compLaunchablePawn; private CompTransporterPawn compTransporterPawn; public override void SpawnSetup(Map map, bool bla) { compTransporterPawn = this.TryGetComp<CompTransporterPawn>(); compLaunchablePawn = this.TryGetComp<CompLaunchablePawn>(); DecrementMapIndex(); base.SpawnSetup(map, bla); } public override IEnumerable<Gizmo> GetGizmos() { using var enumerator = base.GetGizmos().GetEnumerator(); while (enumerator.MoveNext()) { var current = enumerator.Current; yield return current; } if (Faction != Faction.OfPlayer || Dead || Dead) { yield break; } if (compTransporterPawn.LoadingInProgressOrReadyToLaunch) { var command_Action = new Command_Action { defaultLabel = "CommandLaunchGroup".Translate(), defaultDesc = "CommandLaunchGroupDesc".Translate(), icon = ContentFinder<Texture2D>.Get("UI/Icons/Commands/FlyingTarget"), action = delegate { if (compTransporterPawn.AnyInGroupHasAnythingLeftToLoad) { Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation( "ConfirmSendNotCompletelyLoadedPods".Translate( compTransporterPawn.FirstThingLeftToLoadInGroup.LabelCap ), compLaunchablePawn.StartChoosingDestination)); } else { compLaunchablePawn.StartChoosingDestination(); } } }; if (compLaunchablePawn.AnyInGroupIsUnderRoof) { command_Action.Disable("CommandLaunchGroupFailUnderRoof".Translate()); } yield return command_Action; } if (compTransporterPawn.LoadingInProgressOrReadyToLaunch) { yield return new Command_Action { defaultLabel = "CommandCancelLoad".Translate(), defaultDesc = "CommandCancelLoadDesc".Translate(), icon = CompTransporterPawn.CancelLoadCommandTex, action = delegate { SoundDefOf.Designate_Cancel.PlayOneShotOnCamera(); compTransporterPawn.CancelLoad(); } }; } var command_LoadToTransporter = new Command_LoadToTransporterPawn(); var num = 0; for (var i = 0; i < Find.Selector.NumSelected; i++) { if (Find.Selector.SelectedObjectsListForReading[i] is not Thing thing || thing.def != def) { continue; } var compLaunchable = thing.TryGetComp<CompLaunchablePawn>(); if (compLaunchable != null) { num++; } } command_LoadToTransporter.defaultLabel = "CommandLoadTransporter".Translate( num.ToString() ); command_LoadToTransporter.defaultDesc = "CommandLoadTransporterDesc".Translate(); command_LoadToTransporter.icon = CompTransporterPawn.LoadCommandTex; command_LoadToTransporter.transComp = compTransporterPawn; var launchable = compTransporterPawn.Launchable; yield return command_LoadToTransporter; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Psionics/CompPsionicUserExample.cs using AbilityUser; using Verse; namespace CultOfCthulhu { public class CompPsionicUserExample : CompAbilityUser { private bool firstTick; //A simple check boolean to make sure we don't give abilities twice. //Starts false because we haven't given abilities yet. private bool gaveAbilities; /// <summary> /// To be psionic, the character must have a psionic brain. /// </summary> private bool IsPsionic { get { if (Pawn?.health?.hediffSet == null) { return false; } return Pawn.health.hediffSet.HasHediff(CultsDefOf.Cults_PsionicBrain); } } /// <summary> /// Gives this component class to the character if they are psionic. /// </summary> public override bool TryTransformPawn() { return IsPsionic; } /// <summary> /// After getting the component class, checks 200 ticks /// after the game starts. /// If the character is psionic, give them the abilities in /// the function PostInitalizeTick() /// </summary> public override void CompTick() { if (Pawn?.Spawned != true) { return; } if (Find.TickManager.TicksGame <= 200) { return; } if (!IsPsionic) { return; } if (!firstTick) { PostInitializeTick(); } base.CompTick(); } /// <summary> /// Adds the ability "Psionic Blast" to the character. /// Sets gaveAbilities to true, because we gave the abilties. /// </summary> private void PostInitializeTick() { if (Pawn?.Spawned != true) { return; } if (Pawn?.story == null) { return; } firstTick = true; if (gaveAbilities) { return; } gaveAbilities = true; Initialize(); AddPawnAbility(CultsDefOf.Cults_PsionicBlast); } //Use this area to store any extra data you want to load //with your component. public override void PostExposeData() { base.PostExposeData(); Scribe_Values.Look(ref gaveAbilities, "gaveAbilities"); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Seed/JobDriver_Investigate.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using Cthulhu; using RimWorld; using Verse; using Verse.AI; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class JobDriver_Investigate : JobDriver { private readonly TargetIndex InvestigateeIndex = TargetIndex.B; private readonly TargetIndex InvestigatorIndex = TargetIndex.A; protected Thing Investigatee => job.GetTarget(TargetIndex.B).Thing; protected Pawn Investigator => (Pawn) job.GetTarget(TargetIndex.A).Thing; public override bool TryMakePreToilReservations(bool errorOnFailed) { return true; } protected override IEnumerable<Toil> MakeNewToils() { this.EndOnDespawnedOrNull(InvestigatorIndex); this.EndOnDespawnedOrNull(InvestigateeIndex); //this.EndOnDespawnedOrNull(Build, JobCondition.Incompletable); yield return Toils_Reserve.Reserve(InvestigateeIndex, job.def.joyMaxParticipants); var gotoInvestigatee = Toils_Goto.GotoThing(InvestigateeIndex, PathEndMode.ClosestTouch); yield return gotoInvestigatee; yield return Toils_Goto.GotoCell(Investigatee.InteractionCell, PathEndMode.OnCell); var watchToil = new Toil { defaultCompleteMode = ToilCompleteMode.Delay, defaultDuration = job.def.joyDuration }; watchToil.WithProgressBarToilDelay(InvestigatorIndex); watchToil.AddPreTickAction(() => { pawn.rotationTracker.FaceCell(TargetB.Cell); pawn.GainComfortFromCellIfPossible(); }); watchToil.AddFinishAction(() => Map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedState = CultSeedState.FinishedSeeing); yield return watchToil; AddFinishAction(() => { //When the investigation is finished, apply effects. if (Map.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedState != CultSeedState.FinishedSeeing) { return; } CultUtility.InvestigatedCultSeed(Investigator, Investigatee); Utility.DebugReport("Called end tick check"); //if (this.TargetB.HasThing) //{ // Find.Reservations.Release(this.job.targetC.Thing, pawn); //} }); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Tsathoggua/CompTargetEffect_ElixerOfPower.cs using RimWorld; using Verse; namespace CultOfCthulhu { public class CompTargetEffect_ElixerOfPower : CompTargetEffect { public override void DoEffectOn(Pawn user, Thing target) { var pawn = (Pawn) target; if (pawn.Dead) { return; } HealthUtility.AdjustSeverity(pawn, HediffDef.Named("Cults_BlackIchor"), 1.0f); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/LordToil_LoadAndEnterTransportersPawn.cs using Cthulhu; using Verse.AI; using Verse.AI.Group; namespace CultOfCthulhu { public class LordToil_LoadAndEnterTransportersPawn : LordToil { private readonly int transportersGroup; public LordToil_LoadAndEnterTransportersPawn(int transportersGroup) { Utility.DebugReport("LordToil_LoadAndCenterTranpsortersPawn Called"); this.transportersGroup = transportersGroup; } public override bool AllowSatisfyLongNeeds => false; public override void UpdateAllDuties() { foreach (var pawn in lord.ownedPawns) { var pawnDuty = new PawnDuty(CultsDefOf.Cults_LoadAndEnterTransportersPawn) { transportersGroup = transportersGroup }; pawn.mindState.duty = pawnDuty; } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/PawnFlyersTraveling.cs using System.Collections.Generic; using Cthulhu; using RimWorld; using RimWorld.Planet; using UnityEngine; using Verse; namespace CultOfCthulhu { public class PawnFlyersTraveling : WorldObject { private static readonly List<Pawn> tmpPawns = new List<Pawn>(); private bool arrived; public PawnsArrivalModeDef arriveMode; public bool attackOnArrival; public IntVec3 destinationCell = IntVec3.Invalid; public int destinationTile = -1; private int initialTile = -1; public PawnFlyer pawnFlyer; private List<ActiveDropPodInfo> pods = new List<ActiveDropPodInfo>(); private float traveledPct; private float TravelSpeed => PawnFlyerDef.flightSpeed; private PawnFlyerDef PawnFlyerDef => pawnFlyer.def as PawnFlyerDef; private Vector3 Start => Find.WorldGrid.GetTileCenter(initialTile); private Vector3 End => Find.WorldGrid.GetTileCenter(destinationTile); public override Vector3 DrawPos => Vector3.Slerp(Start, End, traveledPct); private float TraveledPctStepPerTick { get { var start = Start; var end = End; if (start == end) { return 1f; } var num = GenMath.SphericalDistance(start.normalized, end.normalized); return num == 0f ? 1f : 0.00025f / num; } } //There is always the byakhee private bool PodsHaveAnyPotentialCaravanOwner => true; public bool PodsHaveAnyFreeColonist { get { foreach (var activeDropPodInfo in pods) { var innerContainer = activeDropPodInfo.innerContainer; foreach (var thing in innerContainer) { if (thing is Pawn {IsColonist: true, HostFaction: null}) { return true; } } } return false; } } public IEnumerable<Pawn> Pawns { get { foreach (var activeDropPodInfo in pods) { var innerContainer = activeDropPodInfo.innerContainer; foreach (var thing in innerContainer) { if (thing is Pawn pawn) { yield return pawn; } } } } } public override void ExposeData() { base.ExposeData(); //Pawn Scribe_References.Look(ref pawnFlyer, "pawnFlyer"); //Vanilla Scribe_Collections.Look(ref pods, "pods", LookMode.Deep); Scribe_Values.Look(ref destinationTile, "destinationTile"); Scribe_Values.Look(ref destinationCell, "destinationCell"); Scribe_Values.Look(ref arriveMode, "arriveMode", PawnsArrivalModeDefOf.EdgeDrop); Scribe_Values.Look(ref attackOnArrival, "attackOnArrival"); Scribe_Values.Look(ref arrived, "arrived"); Scribe_Values.Look(ref initialTile, "initialTile"); Scribe_Values.Look(ref traveledPct, "traveledPct"); } public override void PostAdd() { base.PostAdd(); initialTile = Tile; } public override void Tick() { base.Tick(); traveledPct += TraveledPctStepPerTick; if (!(traveledPct >= 1f)) { return; } traveledPct = 1f; Arrived(); } public void AddPod(ActiveDropPodInfo contents, bool justLeftTheMap) { contents.parent = null; pods.Add(contents); var innerContainer = contents.innerContainer; foreach (var thing in innerContainer) { if (thing is Pawn pawn && !pawn.IsWorldPawn()) { if (!Spawned) { Log.Warning("Passing pawn " + pawn + " to world, but the TravelingTransportPod is not spawned. This means that WorldPawns can discard this pawn which can cause bugs."); } if (justLeftTheMap) { pawn.ExitMap(false, Rot4.Random); } else { Find.WorldPawns.PassToWorld(pawn); } } if (thing is not PawnFlyer flyer || flyer.IsWorldPawn()) { continue; } if (!Spawned) { Log.Warning("Passing pawn " + flyer + " to world, but the TravelingTransportPod is not spawned. This means that WorldPawns can discard this pawn which can cause bugs."); } if (justLeftTheMap) { flyer.ExitMap(false, Rot4.Random); } else { Find.WorldPawns.PassToWorld(flyer); } } contents.savePawnsWithReferenceMode = true; } public bool ContainsPawn(Pawn p) { foreach (var activeDropPodInfo in pods) { if (activeDropPodInfo.innerContainer.Contains(p)) { return true; } } return false; } public bool ContainsPawnFlyer(PawnFlyer p) { foreach (var activeDropPodInfo in pods) { if (activeDropPodInfo.innerContainer.Contains(p)) { return true; } } return false; } private void Arrived() { Utility.DebugReport("Arrived"); if (arrived) { return; } arrived = true; var map = Current.Game.FindMap(destinationTile); if (map != null) { SpawnDropPodsInMap(map); } else if (!PodsHaveAnyPotentialCaravanOwner) { var caravan = Find.WorldObjects.PlayerControlledCaravanAt(destinationTile); if (caravan != null) { GivePodContentsToCaravan(caravan); } else { foreach (var activeDropPodInfo in pods) { activeDropPodInfo.innerContainer.ClearAndDestroyContentsOrPassToWorld(); } RemoveAllPods(); Find.WorldObjects.Remove(this); Messages.Message("MessageTransportPodsArrivedAndLost".Translate(), new GlobalTargetInfo(destinationTile), MessageTypeDefOf.NegativeEvent); } } else { var mapParent = Find.WorldObjects.MapParentAt(destinationTile); if (mapParent != null && attackOnArrival) { LongEventHandler.QueueLongEvent(delegate { var unused = GetOrGenerateMapUtility.GetOrGenerateMap(mapParent.Tile, null); string extraMessagePart = null; if (!mapParent.Faction.HostileTo(Faction.OfPlayer)) { mapParent.Faction.TrySetRelationKind(Faction.OfPlayer, FactionRelationKind.Hostile); //mapParent.Faction.SetHostileTo(Faction.OfPlayer, true); extraMessagePart = "MessageTransportPodsArrived_BecameHostile".Translate( mapParent.Faction.Name ).CapitalizeFirst(); } Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; SpawnDropPodsInMap(mapParent.Map, extraMessagePart); }, "GeneratingMapForNewEncounter", false, null); } else { SpawnCaravanAtDestinationTile(); } } } private void SpawnDropPodsInMap(Map map, string extraMessagePart = null) { Utility.DebugReport("SpawnDropPodsInMap Called"); RemoveAllPawnsFromWorldPawns(); IntVec3 intVec; if (destinationCell.IsValid && destinationCell.InBounds(map)) { intVec = destinationCell; } else if (arriveMode == PawnsArrivalModeDefOf.CenterDrop) { if (!DropCellFinder.TryFindRaidDropCenterClose(out intVec, map)) { intVec = DropCellFinder.FindRaidDropCenterDistant(map); } } else { if (arriveMode != PawnsArrivalModeDefOf.EdgeDrop && arriveMode != PawnsArrivalModeDefOf.EdgeDrop) { Log.Warning("Unsupported arrive mode " + arriveMode); } intVec = DropCellFinder.FindRaidDropCenterDistant(map); } foreach (var activeDropPodInfo in pods) { Utility.DebugReport("PawnFlyerIncoming Generation Started"); DropCellFinder.TryFindDropSpotNear(intVec, map, out var c, false, true); var pawnFlyerIncoming = (PawnFlyersIncoming) ThingMaker.MakeThing(PawnFlyerDef.incomingDef); pawnFlyerIncoming.pawnFlyer = pawnFlyer; pawnFlyerIncoming.Contents = activeDropPodInfo; GenSpawn.Spawn(pawnFlyerIncoming, c, map); } RemoveAllPods(); Find.WorldObjects.Remove(this); string text = "MessageTransportPodsArrived".Translate(); if (extraMessagePart != null) { text = text + " " + extraMessagePart; } Messages.Message(text, new TargetInfo(intVec, map), MessageTypeDefOf.PositiveEvent); } private void GivePodContentsToCaravan(Caravan caravan) { foreach (var activeDropPodInfo in pods) { var tmpContainedThings = new List<Thing>(); //PawnFlyersTraveling.tmpContainedThing.Clear(); tmpContainedThings.AddRange(activeDropPodInfo.innerContainer); //this.pods[i].innerContainer. foreach (var thing in tmpContainedThings) { activeDropPodInfo.innerContainer.Remove(thing); thing.holdingOwner = null; if (thing is Pawn pawn) { caravan.AddPawn(pawn, true); } else { var pawn2 = CaravanInventoryUtility.FindPawnToMoveInventoryTo(thing, caravan.PawnsListForReading, null); var flag = false; if (pawn2 != null) { flag = pawn2.inventory.innerContainer.TryAdd(thing); } if (!flag) { thing.Destroy(); } } } } RemoveAllPods(); Find.WorldObjects.Remove(this); Messages.Message("MessageTransportPodsArrivedAndAddedToCaravan".Translate(), caravan, MessageTypeDefOf.PositiveEvent); } private void SpawnCaravanAtDestinationTile() { tmpPawns.Clear(); foreach (var activeDropPodInfo in pods) { var innerContainer = activeDropPodInfo.innerContainer; foreach (var thing in innerContainer) { if (thing is Pawn pawn) { tmpPawns.Add(pawn); } } } if (!GenWorldClosest.TryFindClosestPassableTile(destinationTile, out var startingTile)) { startingTile = destinationTile; } var o = CaravanMaker.MakeCaravan(tmpPawns, Faction.OfPlayer, startingTile, true); o.AddPawn(pawnFlyer, false); foreach (var activeDropPodInfo in pods) { var innerContainer2 = activeDropPodInfo.innerContainer; foreach (var thing in innerContainer2) { if (!(thing is Pawn)) { var pawn2 = CaravanInventoryUtility.FindPawnToMoveInventoryTo(thing, tmpPawns, null); pawn2.inventory.innerContainer.TryAdd(thing); } else { var pawn3 = thing as Pawn; if (pawn3.IsPrisoner) { continue; } if (pawn3.Faction != pawnFlyer.Faction) { pawn3.SetFaction(pawnFlyer.Faction); } } } } RemoveAllPods(); Find.WorldObjects.Remove(this); Messages.Message("MessageTransportPodsArrived".Translate(), o, MessageTypeDefOf.PositiveEvent); } private void RemoveAllPawnsFromWorldPawns() { foreach (var activeDropPodInfo in pods) { var innerContainer = activeDropPodInfo.innerContainer; foreach (var thing in innerContainer) { var pawn = thing as Pawn; Pawn flyer = thing as PawnFlyer; if (pawn != null && pawn.IsWorldPawn()) { Find.WorldPawns.RemovePawn(pawn); } else if (flyer != null && pawn.IsWorldPawn()) { Find.WorldPawns.RemovePawn(flyer); } } } } private void RemoveAllPods() { foreach (var activeDropPodInfo in pods) { activeDropPodInfo.savePawnsWithReferenceMode = false; } pods.Clear(); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/SpellWorker_AuroraEffect.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using RimWorld; using UnityEngine; using Verse; using Verse.Sound; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_AuroraEffect : SpellWorker { protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); var map = (Map) parms.target; return !map.GameConditionManager.ConditionIsActive(CultsDefOf.Cults_Aurora); } protected override bool TryExecuteWorker(IncidentParms parms) { DoConditionAndLetter(Mathf.RoundToInt(def.durationDays.RandomInRange * 60000f), parms.target); SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(); return true; } protected void DoConditionAndLetter(int duration, IIncidentTarget target) { var map = (Map) target; //Cthulhu.Utility.DebugReport("Generating Map Condition"); var GameCondition = (GameCondition_AuroraEffect) GameConditionMaker.MakeCondition(CultsDefOf.Cults_Aurora, duration); //Cthulhu.Utility.DebugReport("Getting coords."); var coords = Find.WorldGrid.LongLatOf(map.Tile); var text3 = coords.y >= 74 ? "Borealis" : "Australis"; //Cthulhu.Utility.DebugReport("Getting label"); string textLabel = "LetterLabelAurora".Translate( text3 ); //Cthulhu.Utility.DebugReport("Registering Conditions"); map.GameConditionManager.RegisterCondition(GameCondition); string textDesc = "LetterIncidentAurora".Translate(); //Cthulhu.Utility.DebugReport("Sending letter"); Find.LetterStack.ReceiveLetter(textLabel, textDesc, LetterDefOf.PositiveEvent); map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = IntVec3.Invalid; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Seed/Plant_TreeOfMadness.cs using System.Collections.Generic; using RimWorld; using UnityEngine; using Verse; using Verse.AI; using Verse.Sound; namespace CultOfCthulhu { public class Plant_TreeOfMadness : Plant { private static readonly FloatRange QuietIntervalDays = new FloatRange(1.5f, 2.5f); private bool isMuted; public bool isQuiet; private bool setup; private Sustainer sustainerAmbient; private int ticksUntilQuiet = 960; public override void SpawnSetup(Map map, bool bla) { ticksUntilQuiet += (int) (QuietIntervalDays.RandomInRange * 60000f); base.SpawnSetup(map, bla); } public override void Tick() { base.Tick(); Setup(); DoTickWork(); } private void Setup() { if (setup) { return; } setup = true; if (def.building.soundAmbient.NullOrUndefined() || sustainerAmbient != null) { return; } var info = SoundInfo.InMap(this); sustainerAmbient = def.building.soundAmbient.TrySpawnSustainer(info); } private void DoTickWork() { if (isQuiet) { return; } ticksUntilQuiet--; if (ticksUntilQuiet > 0) { return; } isQuiet = true; sustainerAmbient.End(); } public override void DeSpawn(DestroyMode mode = DestroyMode.Vanish) { base.DeSpawn(mode); sustainerAmbient?.End(); } public Thought_Memory GiveObservedThought() { if (this.StoringThing() != null) { return null; } var thought_MemoryObservation = (Thought_MemoryObservation) ThoughtMaker.MakeThought( DefDatabase<ThoughtDef>.GetNamed("Cults_ObservedNightmareTree")); thought_MemoryObservation.Target = this; var Dave = thought_MemoryObservation.pawn; if (Dave == null) { return null; } if (!Dave.IsColonist) { return thought_MemoryObservation; } if (Dave.needs.TryGetNeed<Need_CultMindedness>().CurLevel > 0.7) { thought_MemoryObservation = (Thought_MemoryObservation) ThoughtMaker.MakeThought( DefDatabase<ThoughtDef>.GetNamed("Cults_ObservedNightmareTreeCultist")); } return thought_MemoryObservation; } public override IEnumerable<FloatMenuOption> GetFloatMenuOptions(Pawn myPawn) { // This code returns all the other float menu options first! using var enumerator = base.GetFloatMenuOptions(myPawn).GetEnumerator(); while (enumerator.MoveNext()) { var current = enumerator.Current; yield return current; } if (CultUtility.AreCultObjectsAvailable(Map)) { yield break; } if (CultUtility.IsSomeoneInvestigating(Map)) { yield break; } void action0() { var job = new Job(CultsDefOf.Cults_Investigate, myPawn, this) { playerForced = true }; myPawn.jobs.TryTakeOrderedJob(job); //mypawn.CurJob.EndCurrentJob(JobCondition.InterruptForced); } yield return new FloatMenuOption("Cults_Investigate".Translate(), action0); } private void MuteToggle() { isMuted = !isMuted; if (sustainerAmbient != null && isMuted) { sustainerAmbient.End(); } else if (!def.building.soundAmbient.NullOrUndefined() && sustainerAmbient == null) { var info = SoundInfo.InMap(this); sustainerAmbient = new Sustainer(def.building.soundAmbient, info); } else { Log.Warning("Cults :: Mute toggle threw an exception on the eerie tree."); } } public override IEnumerable<Gizmo> GetGizmos() { using var enumerator = base.GetGizmos().GetEnumerator(); while (enumerator.MoveNext()) { var current = enumerator.Current; yield return current; } var toggleDef = new Command_Toggle { hotKey = KeyBindingDefOf.Command_TogglePower, icon = ContentFinder<Texture2D>.Get("UI/Icons/Commands/Mute"), defaultLabel = "Mute".Translate(), defaultDesc = "MuteDesc".Translate(), isActive = () => isMuted, toggleAction = MuteToggle }; yield return toggleDef; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Nyarlathotep/SpellWorker_ChaosTheory.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Cthulhu; using HarmonyLib; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_ChaosTheory : SpellWorker { public bool HasIncapableWorkTags(Pawn pawn) { HarmonyPatches.DebugMessage("HasIncapableWorkTags called"); return pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Animals) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Artistic) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Caring) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Cleaning) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Cooking) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Crafting) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Firefighting) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Hauling) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Intellectual) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.ManualDumb) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.ManualSkilled) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Mining) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.PlantWork) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Social) || pawn.story.DisabledWorkTagsBackstoryAndTraits.HasFlag(WorkTags.Violent); } public bool HasIncapableSkills(Pawn pawn) { HarmonyPatches.DebugMessage("HasIncapableSkills called"); var map = pawn.Map; //Check if we have level 0 skills var allDefsListForReading = DefDatabase<SkillDef>.AllDefsListForReading; HarmonyPatches.DebugMessage("AllDefsForReading"); foreach (var skillDef in allDefsListForReading) { var skill = TempExecutioner(map).skills.GetSkill(skillDef); if (skill.Level == 0) { return true; } if (skill.TotallyDisabled) { return true; } } return false; } public override bool CanSummonNow(Map map) { try { if (TempExecutioner(map) == null) { Messages.Message("Executioner does not exist.", MessageTypeDefOf.RejectInput); return false; } if (HasIncapableSkills(TempExecutioner(map)) || HasIncapableWorkTags(TempExecutioner(map))) { return true; } Messages.Message("Executioner is already fully capable.", MessageTypeDefOf.RejectInput); return false; } catch (Exception e) { Utility.DebugReport(e.ToString()); } return true; } protected override bool TryExecuteWorker(IncidentParms parms) { HarmonyPatches.DebugMessage("Chaos Theory attempted"); if (!(parms.target is Map map)) { return false; } var pawn = map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar.SacrificeData.Executioner; HarmonyPatches.DebugMessage("Executioner selected"); if (HasIncapableWorkTags(pawn)) { HarmonyPatches.DebugMessage($"{pawn.Label} has incapable worktags and must be remade."); HarmonyPatches.DebugMessage("Childhood redo"); var fixedChildhood = false; _ = new List<WorkTypeDef>(pawn.story.childhood.DisabledWorkTypes); HarmonyPatches.DebugMessage("childwork list defined"); while (fixedChildhood == false) { IEnumerable<WorkTypeDef> childWorkList; //200 tries to set to 0 disabled work types for (var i = 0; i < 200; i++) { childWorkList = pawn.story.childhood.DisabledWorkTypes; if (!childWorkList.Any()) { goto FirstLeap; } pawn.story.childhood = BackstoryDatabase.RandomBackstory(BackstorySlot.Childhood); } //200 tries to set to 1 disabled work type for (var i = 0; i < 200; i++) { childWorkList = pawn.story.childhood.DisabledWorkTypes; if (childWorkList.Count() <= 1) { goto FirstLeap; } pawn.story.childhood = BackstoryDatabase.RandomBackstory(BackstorySlot.Childhood); } //Give up fixedChildhood = true; } FirstLeap: HarmonyPatches.DebugMessage("First leap"); //Your adulthood is out var fixedAdulthood = false; _ = pawn.story.adulthood.DisabledWorkTypes; while (fixedAdulthood == false) { IEnumerable<WorkTypeDef> adultWorkList; //Try 200 times to get to 0 disabled work types for (var i = 0; i < 200; i++) { adultWorkList = pawn.story.adulthood.DisabledWorkTypes; if (adultWorkList?.Count() == 0) { goto SecondLeap; } pawn.story.adulthood = BackstoryDatabase.RandomBackstory(BackstorySlot.Adulthood); } //Try 200 times to get to 1 disabled work types for (var i = 0; i < 200; i++) { adultWorkList = pawn.story.adulthood.DisabledWorkTypes; if (adultWorkList?.Count() <= 1) { goto SecondLeap; } pawn.story.adulthood = BackstoryDatabase.RandomBackstory(BackstorySlot.Adulthood); } //Give up fixedAdulthood = true; } SecondLeap: HarmonyPatches.DebugMessage("Second leap"); } if (HasIncapableSkills(pawn)) { HarmonyPatches.DebugMessage($"{pawn.Label} has incapable skills"); //pawn.story.GenerateSkillsFromBackstory(); var allDefsListForReading = DefDatabase<SkillDef>.AllDefsListForReading; foreach (var skillDef in allDefsListForReading) { var skill = pawn.skills.GetSkill(skillDef); if (skill.Level <= 3) { skill.Level = 3; } if (skill.TotallyDisabled) { HarmonyPatches.DebugMessage($"{pawn.Label}'s {skill.def.LabelCap} is now 3"); skill.Level = 3; } skill.Notify_SkillDisablesChanged(); } HarmonyPatches.DebugMessage("Skills assigned"); } HarmonyPatches.DebugMessage("Disabled Work Types Attempted"); Traverse.Create(pawn).Field("cachedDisabledWorkTypes").SetValue(null); HarmonyPatches.DebugMessage("Disabled Work Types Succeeded"); //typeof(Pawn).GetField("cachedDisabledWorkTypes", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(pawn, null); map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = pawn.Position; Messages.Message(pawn.Label + " has lived their entire life over again.", MessageTypeDefOf.PositiveEvent); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/CultInfluence.cs using RimWorld.Planet; using Verse; namespace CultOfCthulhu { public class CultInfluence : IExposable { public bool dominant; public float influence; public Settlement settlement; public CultInfluence() { } public CultInfluence(Settlement newSettlement, float newInfluence) { settlement = newSettlement; influence = newInfluence; if (newInfluence == 1.0f) { dominant = true; } } public void ExposeData() { Scribe_References.Look(ref settlement, "settlement"); Scribe_Values.Look(ref influence, "influence"); Scribe_Values.Look(ref dominant, "dominant"); } public override string ToString() { return string.Concat("(", settlement, ", influence=", influence.ToString("F1"), !dominant ? string.Empty : " dominant", ")"); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/AntiCult/MapComponent_LocalCultTracker_Inquisition.cs using System.Collections.Generic; using Cthulhu; using RimWorld; using Verse; using Verse.AI; namespace CultOfCthulhu { internal partial class MapComponent_LocalCultTracker { private void InquisitionCheck() { //Can we have an inquisition? //Are there any altars? if (!CultUtility.AreAltarsAvailable(map)) { return; } //Do we have enough colonists? 5 is a good number to allow for a purge if (map.mapPawns.FreeColonistsSpawnedCount < 5) { return; } //We need inquisitors. At least 2. if (antiCultists == null) { return; } if (antiCultists.Count < 2) { return; } //We need 2 violence-capable inquisitors. var assailants = new List<Pawn>(); foreach (var current in antiCultists) { if (Utility.CapableOfViolence(current) && current.IsColonist) { assailants.Add(current); } } if (assailants.Count < 2) { return; } //We need night conditions. if (!Utility.IsNight(map)) { return; } //We need a preacher if (!TryFindPreacher(out var preacher)) { Utility.DebugReport("Inquisition: Unable to find preacher."); return; } //Check if the assailants equal the preacher... foreach (var current in assailants) { if (current == preacher) { return; } } //Set up ticker. Give our plotters a day or two. if (ticksUntilInquisition == 0) { var ran = Rand.Range(1, 3); ticksUntilInquisition = Find.TickManager.TicksGame + (GenDate.TicksPerDay * ran); Utility.DebugReport("Inquisition: Current Ticks: " + Find.TickManager.TicksGame + " Ticker set to: " + ticksUntilInquisition); } if (ticksUntilInquisition < Find.TickManager.TicksGame) { TryInquisition(assailants, preacher); } } private void TryInquisition(List<Pawn> assailants, Pawn preacher) { //Don't try another inquisition for a long time. ticksUntilInquisition = Find.TickManager.TicksGame + (GenDate.TicksPerDay * Rand.Range(7, 28)); if (assailants.Contains(preacher)) { return; } foreach (var antiCultist in assailants) { if (antiCultist == null) { continue; } if (!Utility.IsActorAvailable(antiCultist)) { continue; } antiCultist.needs.mood.thoughts.memories.TryGainMemory(CultsDefOf.Cults_MidnightInquisitionThought); var J = new Job(CultsDefOf.Cults_MidnightInquisition, antiCultist, preacher); //antiCultist.MentalState.ForceHostileTo(Faction.OfPlayer); antiCultist.jobs.TryTakeOrderedJob(J); //antiCultist.jobs.EndCurrentJob(JobCondition.InterruptForced); } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Dagon/SpellWorker_DefendTheBrood.cs using System.Collections.Generic; using System.Linq; using Cthulhu; using RimWorld; using RimWorld.Planet; using Verse; using Verse.AI.Group; namespace CultOfCthulhu { public class SpellWorker_DefendTheBrood : SpellWorker { private const int NUMTOSPAWN = 3; private const int HARDLIMIT = 8; protected List<Pawn> Brood(Map map) { return map.GetComponent<MapComponent_SacrificeTracker>().defendTheBroodPawns; } public override bool CanSummonNow(Map map) { if (Brood(map) == null) { return true; } var tempPawns = new List<Pawn>(Brood(map)); foreach (var p in tempPawns) { if (p.Dead) { Brood(map).Remove(p); } } if (Brood(map).Count + NUMTOSPAWN <= HARDLIMIT) { return true; } Messages.Message("DefendTheBroodLimit".Translate(), MessageTypeDefOf.RejectInput); return false; } protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } protected List<Pawn> SpawnPawns(IncidentParms parms) { var unused = (Map) parms.target; var list = new List<Pawn>(); var listBugs = new List<PawnKindDef> { PawnKindDefOf.Megascarab, PawnKindDefOf.Spelopede, PawnKindDefOf.Megaspider }; var source = from x in listBugs where x.combatPower <= 500f select x; var maxPawns = NUMTOSPAWN; for (var i = 0; i < maxPawns; i++) { if (Utility.IsCosmicHorrorsLoaded()) { var pawn = PawnGenerator.GeneratePawn(PawnKindDef.Named("ROM_DeepOne"), parms.faction); if (pawn == null) { continue; } list.Add(pawn); } else { if (!source.TryRandomElement(out var kindDef)) { Log.Error("Unable to get pawnkind for Defend the Brood."); break; } var pawn = PawnGenerator.GeneratePawn(kindDef, parms.faction); if (pawn != null) { list.Add(pawn); } } } foreach (var current in list) { var loc = CellFinder.RandomClosewalkCellNear(parms.spawnCenter, (Map) parms.target, 5); if (GenPlace.TryPlaceThing(current, loc, (Map) parms.target, ThingPlaceMode.Near)) { continue; } Find.WorldPawns.PassToWorld(current, PawnDiscardDecideMode.Discard); //GenSpawn.Spawn(current, loc, (Map)parms.target); } //PawnRelationUtility.Notify_PawnsSeenByPlayer(list, out "LetterRelatedPawnsNeutralGroup".Translate(), true); return list; } protected bool TrySetDeepOneFaction(IncidentParms parms) { if (Utility.IsCosmicHorrorsLoaded()) { parms.faction = Find.FactionManager.FirstFactionOfDef(FactionDef.Named("ROM_DeepOne")); } else { Messages.Message("UsingInsectoidsInstead".Translate(), MessageTypeDefOf.NegativeEvent); parms.faction = Find.FactionManager.FirstFactionOfDef(FactionDef.Named("ROM_DeepOneAlt")); } return parms.faction != null; } protected override bool TryExecuteWorker(IncidentParms parms) { //Log.Message("Building_LandedShip TrySetDeepOneFaction"); if (!TrySetDeepOneFaction(parms)) { return false; } if (!(parms.target is Map map)) { return false; } //Find a drop spot if (!CultUtility.TryFindDropCell(map.Center, map, 70, out var intVec)) { return false; } parms.spawnCenter = intVec; var list = SpawnPawns(parms); if (list.Count == 0) { return false; } var unused = RCellFinder.TryFindRandomSpotJustOutsideColony(list[0], out var chillSpot); //LordJob_VisitColony lordJob = new LordJob_VisitColony(parms.faction, chillSpot); //If they have the sign of dagon, then use it. var chillSpot2 = IntVec3.Invalid; var dagonSign = map.listerBuildings.allBuildingsColonist.FirstOrDefault(bld => bld.def == CultsDefOf.Cults_SignOfDagon); if (dagonSign != null) { chillSpot2 = dagonSign.Position; } chillSpot = chillSpot2; //Log.Message("SpellWorker_DefendTheBrood LordJob_DefendPoint"); var lordJob = new LordJob_DefendPoint(chillSpot); Utility.TemporaryGoodwill(parms.faction); LordMaker.MakeNewLord(parms.faction, lordJob, map, list); //Find.LetterStack.ReceiveLetter("DeepOnesArrive".Translate(), "DeepOnesArriveDesc".Translate(), letterDef.Good, list[0]); map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = list[0].Position; map.GetComponent<MapComponent_SacrificeTracker>().defendTheBroodPawns.AddRange(list); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/PawnFlyersLanded.cs using System.Collections.Generic; using Cthulhu; using RimWorld; using UnityEngine; using Verse; using Verse.Sound; namespace CultOfCthulhu { public class PawnFlyersLanded : Thing, IActiveDropPod, IThingHolder { public int age; private ActiveDropPodInfo contents; public PawnFlyer pawnFlyer; public PawnFlyerDef PawnFlyerDef => pawnFlyer.def as PawnFlyerDef; public void GetChildHolders(List<IThingHolder> outChildren) { ThingOwnerUtility.AppendThingHoldersFromThings(outChildren, GetDirectlyHeldThings()); if (contents != null) { outChildren.Add(contents); } } public ThingOwner GetDirectlyHeldThings() { return null; } public ActiveDropPodInfo Contents { get => contents; set { if (contents != null) { contents.parent = null; } if (value != null) { value.parent = this; } contents = value; } } public override void ExposeData() { base.ExposeData(); //Pawn Scribe_References.Look(ref pawnFlyer, "pawnFlyer"); //Vanilla Scribe_Values.Look(ref age, "age"); Scribe_Deep.Look(ref contents, "contents", this); } public IntVec3 GetPosition() { return PositionHeld; } public Map GetMap() { return MapHeld; } public override void DrawAt(Vector3 drawLoc, bool flipped) { if (drawLoc.InBounds(Map)) { pawnFlyer?.Drawer?.DrawAt(drawLoc); } } public override void Tick() { age++; if (contents != null && (int) contents?.openDelay > -1 && age > contents.openDelay) { DismountAll(); } } public override void Destroy(DestroyMode mode = DestroyMode.Vanish) { contents?.innerContainer?.ClearAndDestroyContents(); var map = Map; base.Destroy(mode); if (mode != DestroyMode.KillFinalize) { return; } for (var i = 0; i < 1; i++) { var thing = ThingMaker.MakeThing(ThingDefOf.ChunkSlagSteel); GenPlace.TryPlaceThing(thing, Position, map, ThingPlaceMode.Near); } } private void DismountAll() { if (!pawnFlyer.Spawned) { if (pawnFlyer.Destroyed) { GenSpawn.Spawn(pawnFlyer, Position, Map, Rot4.Random); Utility.DebugReport("Spawned Destroyed PawnFlyer: " + pawnFlyer.Label); } else { GenPlace.TryPlaceThing(pawnFlyer, Position, Map, ThingPlaceMode.Near, out _, delegate { Utility.DebugReport("Successfully Spawned: " + pawnFlyer.Label); }); } } foreach (var thing in contents.innerContainer.InRandomOrder()) { //Log.Message("1"); if (thing.Spawned) { continue; //Avoid errors. We already spawned our pawnFlyer. } //Log.Message("2"); //this.contents.innerContainer.TryDrop(thing, ThingPlaceMode.Near, out thing2); GenPlace.TryPlaceThing(thing, Position, Map, ThingPlaceMode.Near, out var thing2, delegate(Thing placedThing, int _) { //Log.Message("3"); if (Find.TickManager.TicksGame < 1200 && TutorSystem.TutorialMode && placedThing.def.category == ThingCategory.Item) { Find.TutorialState.AddStartingItem(placedThing); } }); //Log.Message("4"); if (thing2 is not Pawn pawn) { continue; } //Log.Message("5"); //if (!pawn.IsPrisoner) //{ // if (pawn.Faction != pawnFlyer.Faction) // pawn.SetFaction(pawnFlyer.Faction); //} if (pawn.RaceProps.Humanlike) { if (PawnFlyerDef.landedTale != null) { TaleRecorder.RecordTale(PawnFlyerDef.landedTale, pawn); } } if (pawn.IsColonist && pawn.Spawned && !Map.IsPlayerHome) { pawn.drafter.Drafted = true; } } if (contents.leaveSlag) { for (var j = 0; j < 1; j++) { var thing3 = ThingMaker.MakeThing(ThingDefOf.ChunkSlagSteel); GenPlace.TryPlaceThing(thing3, Position, Map, ThingPlaceMode.Near); } } if (PawnFlyerDef.dismountSound != null) { PawnFlyerDef.dismountSound.PlayOneShot(new TargetInfo(Position, Map)); } else { Log.Warning("PawnFlyersLanded :: Dismount sound not set"); } Destroy(); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/SpellWorker_Reanimator.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_Reanimator : SpellWorker { protected Pawn innerSacrifice(Map map) { var c = map.thingGrid.ThingAt<Corpse>(altar(map).Position); return c.InnerPawn; } protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } protected override bool TryExecuteWorker(IncidentParms parms) { if (!(parms.target is Map map)) { return false; } //Generate the zombie var pawn = ReanimatedPawnUtility.DoGenerateZombiePawnFromSource(innerSacrifice(map)); var intVec = innerSacrifice(map).Position.RandomAdjacentCell8Way(); GenSpawn.Spawn(pawn, intVec, map); innerSacrifice(map).Corpse.Destroy(); //Destroy the corpse //Replace the innerSacrifice with the new pawn just in-case //altar.innerSacrifice = thing; map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = intVec; Messages.Message("The innerSacrifice reanimates and attacks.", MessageTypeDefOf.ThreatBig); Utility.ApplyTaleDef("Cults_SpellReanimator", pawn); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Bast/SpellWorker_Guardian.cs using System.Collections.Generic; using CultOfCthulhu; using RimWorld; using RimWorld.Planet; using Verse; using Verse.AI; namespace BastCult { /// <summary> /// This spell tries to transform a normal cat into a potent guardian. /// </summary> public class SpellWorker_Guardian : SpellWorker { public override bool CanSummonNow(Map map) { var cat = TryGetClosestCatOnMap(map); if (cat == null) { Messages.Message("Cults_BastNoCatOnMap".Translate(), MessageTypeDefOf.RejectInput); } return cat != null; } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; var closestCat = TryGetClosestCatOnMap(map); var guardianProps = def.GetModExtension<GuardianProperties>(); if (closestCat == null) { return true; } //Transform Cat //Generate guardian var newGuardian = PawnGenerator.GeneratePawn(new PawnGenerationRequest( guardianProps.guardianDef, Faction.OfPlayer, PawnGenerationContext.NonPlayer, -1, true, false, false, false, false, true, 0f, false, true, true, false, false, false, false, false, 0, null, 0, null, null, null, null, null, closestCat.ageTracker.AgeBiologicalYears, closestCat.ageTracker.AgeChronologicalYears, closestCat.gender)); //Transfer over family trees and relations to guardian from old cat. var oldRelations = closestCat.relations; var newRelations = newGuardian.relations; //Transfer over relations. var relationList = new List<DirectPawnRelation>(oldRelations.DirectRelations); foreach (var relation in relationList) { newRelations.AddDirectRelation(relation.def, relation.otherPawn); oldRelations.RemoveDirectRelation(relation); } //Fully train. foreach (var trainableDef in DefDatabase<TrainableDef>.AllDefs) { for (var step = 0; step < trainableDef.steps; step++) { newGuardian.training.Train(trainableDef, null); } } //Make a new name. if (closestCat.Name != null) { newGuardian.Name = closestCat.gender == Gender.Male ? new NameSingle(NameGenerator.GenerateName(RulePackDef.Named("NamerAnimalGenericMale"))) : new NameSingle(NameGenerator.GenerateName(RulePackDef.Named("NamerAnimalGenericFemale"))); } //Dump inventory, if any. closestCat.inventory.DropAllNearPawn(closestCat.Position); Letter letter = LetterMaker.MakeLetter( "Cults_BastGuardianTransformationLabel".Translate(closestCat.Name?.ToStringShort), "Cults_BastGuardianTransformationDescription".Translate(closestCat.Name?.ToStringFull), LetterDefOf.PositiveEvent, new GlobalTargetInfo(newGuardian)); //Remove old cat. var catPosition = closestCat.Position; closestCat.Destroy(); //Spawn in guardian. GenSpawn.Spawn(newGuardian, catPosition, map); MoteMaker.MakePowerBeamMote(catPosition, map); Current.Game.letterStack.ReceiveLetter(letter); return true; } /// <summary> /// Tries to get a cat that is the closest to the altar. /// </summary> /// <param name="map"></param> /// <returns></returns> protected Pawn TryGetClosestCatOnMap(Map map) { var mapAltar = altar(map); var guardianProps = def.GetModExtension<GuardianProperties>(); if (mapAltar == null || guardianProps == null) { return null; } var closestThing = GenClosest.ClosestThingReachable( mapAltar.InteractionCell, map, ThingRequest.ForGroup(ThingRequestGroup.Pawn), PathEndMode.ClosestTouch, TraverseParms.For(TraverseMode.PassDoors), 9999, lookThing => (lookThing?.Faction?.IsPlayer ?? false) && guardianProps.eligiblePawnDefs.Contains(lookThing.def)); //Found a Cat. var pawn = closestThing as Pawn; return pawn; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/JobDriver_EnterTransporterPawn.cs using System.Collections.Generic; using System.Diagnostics; using Cthulhu; using Verse; using Verse.AI; namespace CultOfCthulhu { //RimWorld.JobDriver_EnterTransporter public class JobDriver_EnterTransporterPawn : JobDriver { private readonly TargetIndex TransporterInd = TargetIndex.A; private CompTransporterPawn Transporter { get { var thing = job.GetTarget(TransporterInd).Thing; return thing?.TryGetComp<CompTransporterPawn>(); } } public override bool TryMakePreToilReservations(bool errorOnFailed) { return true; } [DebuggerHidden] protected override IEnumerable<Toil> MakeNewToils() { this.FailOnDespawnedOrNull(TransporterInd); yield return Toils_Reserve.Reserve(TransporterInd); yield return Toils_Goto.GotoThing(TransporterInd, PathEndMode.Touch); yield return new Toil { initAction = delegate { Utility.DebugReport("EnterTransporterPawn Called"); var transporter = Transporter; pawn.DeSpawn(); transporter.GetDirectlyHeldThings().TryAdd(pawn); transporter.Notify_PawnEnteredTransporterOnHisOwn(pawn); } }; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/ShubNiggurath/SpellWorker_WombBetweenWorlds.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_WombBetweenWorlds : SpellWorker { public override bool CanSummonNow(Map map) { if (!Utility.IsCosmicHorrorsLoaded()) { Messages.Message("Note: Cosmic Horrors mod isn't loaded. Megaspiders will be summoned instead.", MessageTypeDefOf.NeutralEvent); } return true; } protected override bool TryExecuteWorker(IncidentParms parms) { if (!(parms.target is Map map)) { return false; } //Find a drop spot if (!CultUtility.TryFindDropCell(map.Center, map, 999999, out var intVec)) { return false; } //Spawn 1 Womb Between Worlds var thing = (Building_WombBetweenWorlds) ThingMaker.MakeThing(CultsDefOf.Cults_WombBetweenWorlds); thing.SetFaction(Faction.OfPlayer); GenPlace.TryPlaceThing(thing, intVec.RandomAdjacentCell8Way(), map, ThingPlaceMode.Near); map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = intVec; //Messages.Message(".", intVec, MessageTypeDefOf.PositiveEvent); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Psionics/DamageWorker_PsionicBlast.cs using AbilityUser; using RimWorld; using UnityEngine; using Verse; namespace CultOfCthulhu { internal class DamageWorker_PsionicBlast : DamageWorker { public Vector3 PushResult(Thing thingToPush, Thing Caster, int pushDist, out bool collision) { var origin = thingToPush.TrueCenter(); var result = origin; var collisionResult = false; for (var i = 1; i <= pushDist; i++) { var pushDistX = i; var pushDistZ = i; if (origin.x < Caster.TrueCenter().x) { pushDistX = -pushDistX; } if (origin.z < Caster.TrueCenter().z) { pushDistZ = -pushDistZ; } var tempNewLoc = new Vector3(origin.x + pushDistX, 0f, origin.z + pushDistZ); if (tempNewLoc.ToIntVec3().Standable(Caster.Map)) { result = tempNewLoc; } else { if (thingToPush is not Pawn) { continue; } //target.TakeDamage(new DamageInfo(DamageDefOf.Blunt, Rand.Range(3, 6), -1, null, null, null)); collisionResult = true; break; } } collision = collisionResult; return result; } public void PushEffect(Thing target, Thing instigator, int distance, bool damageOnCollision = false) { var Caster = instigator as Pawn; if (target is not Pawn) { return; } var loc = PushResult(target, Caster, distance, out var applyDamage); //if (((Pawn)target).RaceProps.Humanlike) ((Pawn)target).needs.mood.thoughts.memories.TryGainMemory(ThoughtDef.Named("PJ_ThoughtPush"), null); var flyingObject = (FlyingObject) GenSpawn.Spawn(ThingDef.Named("Cults_PFlyingObject"), target.Position, target.Map); if (applyDamage && damageOnCollision) { flyingObject.Launch(Caster, new LocalTargetInfo(loc.ToIntVec3()), target, new DamageInfo(DamageDefOf.Blunt, Rand.Range(8, 10))); } else { flyingObject.Launch(Caster, new LocalTargetInfo(loc.ToIntVec3()), target); } } public override DamageResult Apply(DamageInfo dinfo, Thing victim) { PushEffect(victim, dinfo.Instigator, Rand.Range(5, 8), true); return new DamageResult(); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/Dialog_LoadTransportersPawn.cs using System.Collections.Generic; using System.Linq; using System.Text; using Cthulhu; using RimWorld; using RimWorld.Planet; using UnityEngine; using Verse; using Verse.AI; using Verse.AI.Group; using Verse.Sound; namespace CultOfCthulhu { public class Dialog_LoadTransportersPawn : Window { private const float TitleRectHeight = 40f; private const float BottomAreaHeight = 55f; private static readonly List<TabRecord> tabsList = new List<TabRecord>(); private readonly Vector2 BottomButtonSize = new Vector2(160f, 40f); private readonly Map map; private readonly List<CompTransporterPawn> transporters; private Pair<float, float> cachedDaysWorthOfFood; private Pair<ThingDef, float> cachedForagedFoodPerDay; private string cachedForagedFoodPerDayExplanation; private float cachedMassUsage; private float cachedTilesPerDay; private string cachedTilesPerDayExplanation; private float cachedVisibility; private string cachedVisibilityExplanation; private bool daysWorthOfFoodDirty = true; private bool foragedFoodPerDayDirty = true; private TransferableOneWayWidget itemsTransfer; private float lastMassFlashTime = -9999f; private bool massUsageDirty = true; private TransferableOneWayWidget pawnsTransfer; private Tab tab; //private float DaysWorthOfFood //{ // get // { // if (this.daysWorthOfFoodDirty) // { // this.daysWorthOfFoodDirty = false; // this.cachedDaysWorthOfFood = DaysWorthOfFoodCalculator.ApproxDaysWorthOfFood(this.transferables); // } // return this.cachedDaysWorthOfFood; // } //} private bool tilesPerDayDirty = true; private List<TransferableOneWay> transferables; private bool visibilityDirty = true; public Dialog_LoadTransportersPawn(Map map, List<CompTransporterPawn> transporters) { this.map = map; this.transporters = new List<CompTransporterPawn>(); this.transporters.AddRange(transporters); //this.closeOnEscapeKey = true; closeOnAccept = false; closeOnCancel = false; forcePause = true; absorbInputAroundWindow = true; } public override Vector2 InitialSize => new Vector2(1024f, UI.screenHeight); protected override float Margin => 0f; private BiomeDef Biome => map.Biome; private Pair<ThingDef, float> ForagedFoodPerDay { get { if (!foragedFoodPerDayDirty) { return cachedForagedFoodPerDay; } foragedFoodPerDayDirty = false; var stringBuilder = new StringBuilder(); cachedForagedFoodPerDay = ForagedFoodPerDayCalculator.ForagedFoodPerDay(transferables, Biome, Faction.OfPlayer, stringBuilder); cachedForagedFoodPerDayExplanation = stringBuilder.ToString(); return cachedForagedFoodPerDay; } } private float Visibility { get { if (!visibilityDirty) { return cachedVisibility; } visibilityDirty = false; var stringBuilder = new StringBuilder(); cachedVisibility = CaravanVisibilityCalculator.Visibility(transferables, stringBuilder); cachedVisibilityExplanation = stringBuilder.ToString(); return cachedVisibility; } } private int PawnCapacity { get { var num = 0; foreach (var compTransporterPawn in transporters) { var result = 1; //In-case PawnFlyer doesn't work out if (compTransporterPawn.parent is PawnFlyer pawnFlyer) { if (pawnFlyer.def is PawnFlyerDef pawnFlyerDef) { result = pawnFlyerDef.flightPawnLimit; } } num += result; } return num; } } /// <summary> /// Modified to use PawnFlyerDef /// </summary> private float MassCapacity { get { var num = 0f; foreach (var compTransporterPawn in transporters) { var result = 150f; //In-case PawnFlyer doesn't work out if (compTransporterPawn.parent is PawnFlyer pawnFlyer) { result = pawnFlyer.GetStatValue(StatDefOf.CarryingCapacity); //PawnFlyerDef pawnFlyerDef = pawnFlyer.def as PawnFlyerDef; //if (pawnFlyerDef != null) //{ // result = pawnFlyerDef.flightCarryCapacity; //} } num += result; } return num; } } private string TransportersLabel => Find.ActiveLanguageWorker.Pluralize(transporters[0].parent.Label); private string TransportersLabelCap => TransportersLabel.CapitalizeFirst(); private float MassUsage { get { if (!massUsageDirty) { return cachedMassUsage; } massUsageDirty = false; cachedMassUsage = CollectionsMassCalculator.MassUsageTransferables(transferables, IgnorePawnsInventoryMode.DontIgnore, true); return cachedMassUsage; } } private float TilesPerDay { get { if (!tilesPerDayDirty) { return cachedTilesPerDay; } tilesPerDayDirty = false; var stringBuilder = new StringBuilder(); cachedTilesPerDay = TilesPerDayCalculator.ApproxTilesPerDay(transferables, MassUsage, MassCapacity, map.Tile, -1, stringBuilder); cachedTilesPerDayExplanation = stringBuilder.ToString(); return cachedTilesPerDay; } } private Pair<float, float> DaysWorthOfFood { get { if (!daysWorthOfFoodDirty) { return cachedDaysWorthOfFood; } daysWorthOfFoodDirty = false; var first = DaysWorthOfFoodCalculator.ApproxDaysWorthOfFood(transferables, map.Tile, IgnorePawnsInventoryMode.IgnoreIfAssignedToUnload, Faction.OfPlayer, null, 0f, 3500); cachedDaysWorthOfFood = new Pair<float, float>(first, DaysUntilRotCalculator.ApproxDaysUntilRot(transferables, map.Tile, IgnorePawnsInventoryMode.IgnoreIfAssignedToUnload, null, 0f, 3500)); return cachedDaysWorthOfFood; } } public override void PostOpen() { base.PostOpen(); CalculateAndRecacheTransferables(); } public override void DoWindowContents(Rect inRect) { var rect = new Rect(0f, 0f, inRect.width, 35f); Text.Font = GameFont.Medium; Text.Anchor = TextAnchor.MiddleCenter; Widgets.Label(rect, "LoadTransporters".Translate( TransportersLabel )); Text.Font = GameFont.Small; Text.Anchor = TextAnchor.UpperLeft; CaravanUIUtility.DrawCaravanInfo( new CaravanUIUtility.CaravanInfo(MassUsage, MassCapacity, "", TilesPerDay, cachedTilesPerDayExplanation, DaysWorthOfFood, ForagedFoodPerDay, cachedForagedFoodPerDayExplanation, Visibility, cachedVisibilityExplanation), null, map.Tile, null, lastMassFlashTime, new Rect(12f, 35f, inRect.width - 24f, 40f), false); tabsList.Clear(); tabsList.Add(new TabRecord("PawnsTab".Translate(), delegate { tab = Tab.Pawns; }, tab == Tab.Pawns)); tabsList.Add(new TabRecord("ItemsTab".Translate(), delegate { tab = Tab.Items; }, tab == Tab.Items)); inRect.yMin += 119f; Widgets.DrawMenuSection(inRect); TabDrawer.DrawTabs(inRect, tabsList); inRect = inRect.ContractedBy(17f); GUI.BeginGroup(inRect); var rect2 = inRect.AtZero(); DoBottomButtons(rect2); var inRect2 = rect2; inRect2.yMax -= 59f; var flag = false; var tab1 = tab; if (tab1 != Tab.Pawns) { if (tab1 == Tab.Items) { itemsTransfer.OnGUI(inRect2, out flag); } } else { pawnsTransfer.OnGUI(inRect2, out flag); } if (flag) { CountToTransferChanged(); } GUI.EndGroup(); // Rect rect = new Rect(0f, 0f, inRect.width, 40f); // Text.Font = GameFont.Medium; // Text.Anchor = TextAnchor.MiddleCenter; // Widgets.Label(rect, "LoadTransporters".Translate(new object[] // { // this.TransportersLabel // })); // Text.Font = GameFont.Small; // Text.Anchor = TextAnchor.UpperLeft; // Dialog_LoadTransportersPawn.tabsList.Clear(); // Dialog_LoadTransportersPawn.tabsList.Add(new TabRecord("PawnsTab".Translate(), delegate // { // this.tab = Dialog_LoadTransportersPawn.Tab.Pawns; // }, this.tab == Dialog_LoadTransportersPawn.Tab.Pawns)); // //Dialog_LoadTransportersPawn.tabsList.Add(new TabRecord("ItemsTab".Translate(), delegate // //{ // // this.tab = Dialog_LoadTransportersPawn.Tab.Items; // //}, this.tab == Dialog_LoadTransportersPawn.Tab.Items)); // inRect.yMin += 72f; // Widgets.DrawMenuSection(inRect); // TabDrawer.DrawTabs(inRect, Dialog_LoadTransportersPawn.tabsList); // inRect = inRect.ContractedBy(17f); // GUI.BeginGroup(inRect); // Rect rect2 = inRect.AtZero(); // Rect rect3 = rect2; // rect3.xMin += rect2.width - this.pawnsTransfer.TotalNumbersColumnsWidths; // rect3.y += 32f; // TransferableUIUtility.DrawMassInfo(rect3, this.MassUsage, this.MassCapacity, "TransportersMassUsageTooltip".Translate(), this.lastMassFlashTime, true); // //CaravanUIUtility.DrawDaysWorthOfFoodInfo(new Rect(rect3.x, rect3.y + 22f, rect3.width, rect3.height), this.DaysWorthOfFood, true); // this.DoBottomButtons(rect2); // Rect inRect2 = rect2; // inRect2.yMax -= 59f; // bool flag = false; // Dialog_LoadTransportersPawn.Tab tab = this.tab; // if (tab != Dialog_LoadTransportersPawn.Tab.Pawns) // { // if (tab == Dialog_LoadTransportersPawn.Tab.Items) // { // this.itemsTransfer.OnGUI(inRect2, out flag); // } // } // else // { // this.pawnsTransfer.OnGUI(inRect2, out flag); // } // if (flag) // { // this.CountToTransferChanged(); // } // GUI.EndGroup(); } public override bool CausesMessageBackground() { return true; } private void AddToTransferables(Thing t) { var transferableOneWay = TransferableUtility.TransferableMatching(t, transferables, TransferAsOneMode.PodsOrCaravanPacking); if (transferableOneWay == null) { transferableOneWay = new TransferableOneWay(); transferables.Add(transferableOneWay); } transferableOneWay.things.Add(t); } private void DoBottomButtons(Rect rect) { var rect2 = new Rect((rect.width / 2f) - (BottomButtonSize.x / 2f), rect.height - 55f, BottomButtonSize.x, BottomButtonSize.y); if (Widgets.ButtonText(rect2, "AcceptButton".Translate(), true, false) && TryAccept()) { SoundDefOf.Tick_High.PlayOneShotOnCamera(); Close(false); } var rect3 = new Rect(rect2.x - 10f - BottomButtonSize.x, rect2.y, BottomButtonSize.x, BottomButtonSize.y); if (Widgets.ButtonText(rect3, "ResetButton".Translate(), true, false)) { SoundDefOf.Tick_Low.PlayOneShotOnCamera(); CalculateAndRecacheTransferables(); } var rect4 = new Rect(rect2.xMax + 10f, rect2.y, BottomButtonSize.x, BottomButtonSize.y); if (Widgets.ButtonText(rect4, "CancelButton".Translate(), true, false)) { Close(); } if (!Prefs.DevMode) { return; } var num = 200f; var num2 = BottomButtonSize.y / 2f; var rect5 = new Rect(rect.width - num, rect.height - 55f, num, num2); if (Widgets.ButtonText(rect5, "Dev: Load instantly", true, false) && DebugTryLoadInstantly()) { SoundDefOf.Tick_High.PlayOneShotOnCamera(); Close(false); } var rect6 = new Rect(rect.width - num, rect.height - 55f + num2, num, num2); if (!Widgets.ButtonText(rect6, "Dev: Select everything", true, false)) { return; } SoundDefOf.Tick_High.PlayOneShotOnCamera(); SetToLoadEverything(); } private void CalculateAndRecacheTransferables() { transferables = new List<TransferableOneWay>(); AddPawnsToTransferables(); AddItemsToTransferables(); pawnsTransfer = new TransferableOneWayWidget(null, Faction.OfPlayer.Name, TransportersLabelCap, "FormCaravanColonyThingCountTip".Translate(), true, IgnorePawnsInventoryMode.IgnoreIfAssignedToUnload, true, () => MassCapacity - MassUsage, 24f, false, map.Tile, true); CaravanUIUtility.AddPawnsSections(pawnsTransfer, transferables); itemsTransfer = new TransferableOneWayWidget(from x in transferables where x.ThingDef.category != ThingCategory.Pawn select x, Faction.OfPlayer.Name, TransportersLabelCap, "FormCaravanColonyThingCountTip".Translate(), true, IgnorePawnsInventoryMode.IgnoreIfAssignedToUnload, true, () => MassCapacity - MassUsage, 24f, false, map.Tile, true); CountToTransferChanged(); } private bool DebugTryLoadInstantly() { CreateAndAssignNewTransportersGroup(); int i; for (i = 0; i < transferables.Count; i++) { var i1 = i; TransferableUtility.Transfer(transferables[i].things, transferables[i].CountToTransfer, delegate(Thing splitPiece, IThingHolder _) { transporters[i1 % transporters.Count].GetDirectlyHeldThings().TryAdd(splitPiece); }); } return true; } private bool TryAccept() { var pawnsFromTransferables = TransferableUtility.GetPawnsFromTransferables(transferables); if (!CheckForErrors(pawnsFromTransferables)) { Utility.DebugReport("TryAccept Failed"); return false; } Utility.DebugReport("TryAccept Succeeded"); var transportersGroup = CreateAndAssignNewTransportersGroup(); AssignTransferablesToRandomTransporters(); var enumerable = from x in pawnsFromTransferables where x.IsColonist && !x.Downed select x; if (enumerable.Any()) { Utility.DebugReport("Pawn List Succeeded"); LordMaker.MakeNewLord(Faction.OfPlayer, new LordJob_LoadAndEnterTransportersPawn(transportersGroup), map, enumerable); foreach (var current in enumerable) { if (current.Spawned) { current.jobs.EndCurrentJob(JobCondition.InterruptForced); } } } Messages.Message("MessageTransportersLoadingProcessStarted".Translate(), transporters[0].parent, MessageTypeDefOf.PositiveEvent); return true; } private void AssignTransferablesToRandomTransporters() { Utility.DebugReport("AssignTransferablesToRandomTransporters Called"); var transferableOneWay = transferables.MaxBy(x => x.CountToTransfer); var num = 0; foreach (var oneWay in transferables) { if (oneWay == transferableOneWay) { continue; } if (oneWay.CountToTransfer <= 0) { continue; } transporters[num % transporters.Count].AddToTheToLoadList(oneWay, oneWay.CountToTransfer); num++; } if (num < transporters.Count) { var num2 = transferableOneWay.CountToTransfer; var num3 = num2 / (transporters.Count - num); for (var j = num; j < transporters.Count; j++) { var num4 = j != transporters.Count - 1 ? num3 : num2; if (num4 > 0) { transporters[j].AddToTheToLoadList(transferableOneWay, num4); } num2 -= num4; } } else { transporters[num % transporters.Count] .AddToTheToLoadList(transferableOneWay, transferableOneWay.CountToTransfer); } } private int CreateAndAssignNewTransportersGroup() { Utility.DebugReport("CreateAndAssignNewTransportersGroup Called"); var nextTransporterGroupID = Find.UniqueIDsManager.GetNextTransporterGroupID(); foreach (var compTransporterPawn in transporters) { compTransporterPawn.groupID = nextTransporterGroupID; } return nextTransporterGroupID; } private bool CheckForErrors(List<Pawn> pawns) { if (!transferables.Any(x => x.CountToTransfer != 0)) { Messages.Message("CantSendEmptyTransportPods".Translate(), MessageTypeDefOf.RejectInput); return false; } if (MassUsage > MassCapacity) { FlashMass(); Messages.Message("TooBigTransportersMassUsage".Translate(), MessageTypeDefOf.RejectInput); return false; } if (pawns.Count > PawnCapacity) { Messages.Message("OverPawnRiderLimit".Translate( PawnCapacity.ToString() ), MessageTypeDefOf.RejectInput); return false; } var pawn = pawns.Find(x => !x.MapHeld.reachability.CanReach(x.PositionHeld, transporters[0].parent, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors))); if (pawn != null) { Messages.Message("PawnCantReachTransporters".Translate( pawn.LabelShort ).CapitalizeFirst(), MessageTypeDefOf.RejectInput); return false; } var parentMap = transporters[0].parent.Map; foreach (var transferableOneWay in transferables) { if (transferableOneWay.ThingDef.category != ThingCategory.Item) { continue; } var countToTransfer = transferableOneWay.CountToTransfer; var num = 0; if (countToTransfer <= 0) { continue; } foreach (var thing in transferableOneWay.things) { if (!parentMap.reachability.CanReach(thing.Position, transporters[0].parent, PathEndMode.Touch, TraverseParms.For(TraverseMode.PassDoors))) { continue; } num += thing.stackCount; if (num >= countToTransfer) { break; } } if (num >= countToTransfer) { continue; } if (countToTransfer == 1) { Messages.Message("TransporterItemIsUnreachableSingle".Translate( transferableOneWay.ThingDef.label ), MessageTypeDefOf.RejectInput); } else { Messages.Message("TransporterItemIsUnreachableMulti".Translate( countToTransfer, transferableOneWay.ThingDef.label ), MessageTypeDefOf.RejectInput); } return false; } return true; } private void AddPawnsToTransferables() { var list = CaravanFormingUtility.AllSendablePawns(map); foreach (var pawn in list) { if (pawn.TryGetComp<CompLaunchablePawn>() == null) { AddToTransferables(pawn); } } } private void AddItemsToTransferables() { var list = CaravanFormingUtility.AllReachableColonyItems(map); foreach (var thing in list) { AddToTransferables(thing); } } private void FlashMass() { lastMassFlashTime = Time.time; } private void SetToLoadEverything() { foreach (var transferableOneWay in transferables) { transferableOneWay.AdjustTo(transferableOneWay.GetMaximumToTransfer()); // SetToTransferMaxToDest(); //TransferableUIUtility.ClearEditBuffer(this.transferables[i]); } CountToTransferChanged(); } private void CountToTransferChanged() { massUsageDirty = true; daysWorthOfFoodDirty = true; } private enum Tab { Pawns, Items } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Interactions/InteractionWorker_DangerPreach.cs using System.Collections.Generic; using RimWorld; using UnityEngine; using Verse; namespace CultOfCthulhu { /// <summary> /// Cultist shares ideas with a non-cultist for massive failure. /// </summary> public class InteractionWorker_DangerPreach : InteractionWorker { //How great the effect is on the cultminded values. public const float CULTMINDED_EFFECT_MIN = -0.15f; public const float CULTMINDED_EFFECT_MAX = -0.2f; //Almost three times the chance private const float BaseSelectionWeight = 0.8f; public override void Interacted(Pawn initiator, Pawn recipient, List<RulePackDef> extraSentencePacks, out string letterText, out string letterLabel, out LetterDef letterDef, out LookTargets lookTargets) { base.Interacted(initiator, recipient, extraSentencePacks, out letterText, out letterLabel, out letterDef, out lookTargets); CultUtility.AffectCultMindedness(recipient, Rand.Range(CULTMINDED_EFFECT_MIN, CULTMINDED_EFFECT_MAX)); } public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) { //We need two individuals that are part of the colony if (!initiator.IsColonist || !initiator.IsPrisoner) { return 0f; } if (!recipient.IsColonist || !recipient.IsPrisoner) { return 0f; } //If they are sleeping, don't do this. if (initiator.jobs.curDriver.asleep) { return 0f; } if (recipient.jobs.curDriver.asleep) { return 0f; } //We need them to have different mindsets. if (CultUtility.IsCultMinded(recipient)) { return 0f; } if (!CultUtility.IsCultMinded(initiator)) { return 0f; } //Normally, it's double chance of happening. var math = 2f; //Subtract the social skill of the initiator by 10. //A social skill of 20 will return a 0 chance of this happening. math -= (float) initiator.skills.GetSkill(SkillDefOf.Social).Level / 10; //Throw in random chance. math += Rand.Range(-0.5f, 0.5f); //Especially if they don't like the other guy. return initiator.relations.OpinionOf(recipient) < 15 ? Mathf.Clamp(math, 0f, 2f) : 0f; } } }<file_sep>/README.md # CallofCthulhuCults ![Image](https://i.imgur.com/WAEzk68.png) Update of Jecrells mod https://steamcommunity.com/sharedfiles/filedetails/?id=815039373 - This is an unofficial port - This will be removed when/if Jecrell comes back - Added support for Combat Extended - Removed the production-tag on altars so they can be used in thronerooms - Added an option to make sermons voluntary, making pawns complete some types of jobs before joining - Improved the sermon scheduling with some inspiration from the excellent mod https://steamcommunity.com/sharedfiles/filedetails/?id=1565942758]Colony Leadership Now you can select what days to do sermons and also when they should start in the day. - Added support for https://steamcommunity.com/sharedfiles/filedetails/?id=2451324814][SYR] Trait Value ![Image](https://i.imgur.com/7Gzt3Rg.png) [table] [tr] [td]https://invite.gg/Mlie]![Image](https://i.imgur.com/zdzzBrc.png) [/td] [td]https://github.com/emipa606/CallofCthulhuCults]![Image](https://i.imgur.com/kTkpTOE.png) [/td] [/tr] [/table] ![Image](https://i.imgur.com/NOW7jU1.png) # Gameplay expansion for RimWorld. **You can now...** - found a cult. - worship monstrous deities. - make offerings and animal sacrifices. - make human sacrifices in return for powerful spells (6 deitys and 30 spells in total, plus a dozen side effects). # This mod supports these languages: English, Korean 한국어 (밀수업자), and Russian русский язык (kr33man) # ::::: NOTICE ::::: ::::: THIS MOD NOW REQUIRES JECSTOOLS :::::: Download http://steamcommunity.com/sharedfiles/filedetails/?id=932008009 # Recommended mods - Cosmic Horrors (for summoning actual monsters) - Industrial Age (for great lighting) - Realistic Darkness (for great darkness) # How do I start a cult? 1) Load the mod. 2) Play for a few days in-game. 3) One of your pawns will investigate something horrendous. 4) Build the forbidden research center. 5) Research the strange symbols until someone founds the cult. 6) Good luck. # Tips: - Cult-mindedness is a new feature under &apos;needs&apos; that keeps track of how likely colonists are to become cultists. - Better apparel means greater worship results and higher success rates for your sacrifices. - Beware! If too many colonists are plotting against the cult, they might take matters into their own hands. - Want more? Check the https://ludeon.com/forums/index.php?topic=26078.msg263991#msg263991]Call of Cthulhu WIP Thread on the Ludeon forums. # Special Thanks: 1000101 - Religious needs Cpt. Ohu - Altar congregations Skullywag - Helpfulness on #modding Mrofa - Code for two-colored hoods <NAME> - Reanimation Code Everyone on the modding Discord Want to contribute? Get in touch with us in the workshop or Ludeon forums. ![Image](https://i.imgur.com/Rs6T6cr.png) - See if the the error persists if you just have this mod and its requirements active. - If not, try adding your other mods until it happens again. - Post your error-log using https://steamcommunity.com/workshop/filedetails/?id=818773962]HugsLib and command Ctrl+F12 - For best support, please use the Discord-channel for error-reporting. - Do not report errors by making a discussion-thread, I get no notification of that. - If you have the solution for a problem, please post it to the GitHub repository. <file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/JobGiver_LoadTransportersPawn.cs using System.Collections.Generic; using Cthulhu; using Verse; using Verse.AI; namespace CultOfCthulhu { public class JobGiver_LoadTransportersPawn : ThinkNode_JobGiver { private static readonly List<CompTransporterPawn> tmpTransporters = new List<CompTransporterPawn>(); protected override Job TryGiveJob(Pawn pawn) { Utility.DebugReport("JobGiver_LoadTransportersPawn Called"); var transportersGroup = pawn.mindState.duty.transportersGroup; LoadTransportersPawnJobUtility.GetTransportersInGroup(transportersGroup, pawn.Map, tmpTransporters); foreach (var transporter in tmpTransporters) { if (LoadTransportersPawnJobUtility.HasJobOnTransporter(pawn, transporter)) { return LoadTransportersPawnJobUtility.JobOnTransporter(pawn, transporter); } } return null; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/SpellWorker_NeedAHand.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_NeedAHand : SpellWorker { protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport(" //: " + this.def.defName); return true; } protected Pawn TestPawn(Map map) { var list = PawnsToTransmogrify(map).InRandomOrder(); return !list.TryRandomElement(out var pawn) ? null : pawn; } public IEnumerable<Pawn> PawnsToTransmogrify(Map map) { //Get a pawn downed or bed-ridden incapable of moving var one = from Pawn peeps in map.mapPawns.FreeColonistsSpawned where peeps.RaceProps.Humanlike && peeps.Faction == Faction.OfPlayer && !peeps.Dead && (peeps.Downed || peeps.InBed()) && !peeps.health.capacities.CapableOf(PawnCapacityDefOf.Moving) select peeps; if (one.Any()) { return one; } one = from Pawn peeps in map.mapPawns.FreeColonistsSpawned where peeps.RaceProps.Humanlike && peeps.Faction == Faction.OfPlayer && !peeps.Dead select peeps; return one; } protected override bool TryExecuteWorker(IncidentParms parms) { var pawn = TestPawn((Map) parms.target); BodyPartRecord tempRecord = null; foreach (var current in pawn.RaceProps.body.AllParts.InRandomOrder()) { if (current.def != BodyPartDefOf.Leg && current.def != BodyPartDefOf.Arm && current.def != BodyPartDefOf.Hand && current.def != BodyPartDefOf.Eye && current.def != BodyPartDefOf.Jaw) { continue; } if (!pawn.health.hediffSet.PartIsMissing(current)) { continue; } pawn.health.RestorePart(current); tempRecord = current; goto Leap; } foreach (var current in pawn.RaceProps.body.AllParts.InRandomOrder()) { if (current.def != BodyPartDefOf.Leg && current.def != BodyPartDefOf.Arm && current.def != BodyPartDefOf.Hand && current.def != BodyPartDefOf.Eye && current.def != BodyPartDefOf.Jaw) { continue; } tempRecord = current; break; } Leap: //Error catch: Missing parts! if (tempRecord == null) { Log.Error("Couldn't find part of the pawn to replace."); return false; } pawn.health.AddHediff(CultsDefOf.Cults_TentacleArm, tempRecord); Messages.Message( pawn.LabelShort + "'s " + tempRecord.def.label + " has been replaced with an otherworldly tentacle appendage.", MessageTypeDefOf.PositiveEvent); return true; } } }<file_sep>/Source/Description.txt <size=24>Features</size> Gameplay expansion for RimWorld. You can now: *found a cult *worship monstrous deities *make offerings and animal sacrifices *make human sacrifices in return for powerful spells (over 20 in total, plus a dozen side effects) <size=24>Credits</size> Nackblad - Art for outfits for Cthulhu, Dagon, Nyarlathotep, Shub-niggurath cults. Sera - Art for the King in Yellow DianaWinters & ChJees - Guardians, Bast Mask, Bast Apparel 1000101 - Concept for religious needs Cpt. Ohu - Original code for altar congregations Skullywag - Helpfulness on #modding Mrofa - Code for two-colored hoods <NAME> - Reanimation Code https://game-icons.net/ for various icons and templates <size=12>Deity Portraits</size> Cthulhu by <NAME> (https://www.artstation.com/damie_m) Dagon by <NAME> (http://www.templeofdagon.com/artists/jeff-remmer/) Shub Niggurath by Art-Ogre (http://art-ogre.blogspot.com/) Hastur by Aramos Studio (https://www.deviantart.com/aramosstudio) Nyarlathotep by <NAME> (https://www.artstation.com/wall) Bast by Omega Lioness (https://www.furaffinity.net/view/13646451/) Tsathoggua used from Mythos ABC (https://www.amazon.com/Mythos-ABC-Mads-Brynnum-ebook/dp/B075WVTB1L) Everyone on the modding Discord<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Bast/SpellWorker_FelineAspect.cs using CultOfCthulhu; using RimWorld; using Verse; namespace BastCult { /// <summary> /// This spell augments the executioner with the grace and deadliness of a cat. /// </summary> public class SpellWorker_FelineAspect : SpellWorker { public override bool CanSummonNow(Map map) { var felineProps = def.GetModExtension<FelineAspectProperties>(); if (felineProps == null) { return false; } //Get executioner. var executioner = altar(map).tempExecutioner; return ExecutionerIsValid(executioner, felineProps); } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; var felineProps = def.GetModExtension<FelineAspectProperties>(); if (felineProps == null) { return true; } //Get executioner. var executioner = altar(map).tempExecutioner; if (!ExecutionerIsValid(executioner, felineProps)) { return true; } //Apply Hediffs //To body executioner.health.AddHediff(felineProps.hediffToApplyToBody); //To hands foreach (var hand in felineProps.handDefs) { var records = executioner.RaceProps.body.AllParts.FindAll(part => part.def == hand); if (!(records.Count > 0)) { continue; } foreach (var record in records) { executioner.health.AddHediff(felineProps.hediffToApplyToHands, record); } } return true; } public bool ExecutionerIsValid(Pawn preacher, FelineAspectProperties felineProps) { return !preacher.health.hediffSet.HasHediff(felineProps.hediffToApplyToBody); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Cthulhu/SpellWorker_PsionicGrowth.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System; using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_PsionicGrowth : SpellWorker { protected Pawn pawn(Map map) { Pawn pawn = null; if (altar(map) != null) { pawn = altar(map).tempExecutioner; } return pawn; } public BodyPartRecord GetHead(Pawn pawn) { foreach (var current in pawn.health.hediffSet.GetNotMissingParts()) { if (current.def == BodyPartDefOf.Head) { return current; } } return null; } public override bool CanSummonNow(Map map) { if (pawn(map) == null) { Messages.Message("Executioner is missing.", MessageTypeDefOf.RejectInput); return false; } //If they have no brain... don't do this. if (pawn(map).health.hediffSet.GetBrain() == null) { Messages.Message(pawn(map).LabelShort + " is missing a brain to enhance.", MessageTypeDefOf.RejectInput); return false; } //Check if their brain is already upgraded. foreach (var current in pawn(map).health.hediffSet.hediffs) { if (current.def != CultsDefOf.Cults_PsionicBrain) { continue; } Messages.Message(pawn(map).LabelShort + " already posesses a brain with psionic power.", MessageTypeDefOf.RejectInput); return false; } //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; _ = pawn(map).health.hediffSet.GetBrain(); var headRecord = GetHead(pawn(map)); //Error catch: Missing head! //if (tempRecord == null) //{ //Log.Error("Couldn't find head part of the pawn(map) to give random damage."); //return false; //} var rand = new Random().Next(1, 100); switch (rand) { case > 90: // No effect break; case > 50 and <= 90: { //A15 code... //HediffDef quiet = null; //BodyPartDamageInfo value = new BodyPartDamageInfo(tempRecord, false, quiet); //pawn(map).TakeDamage(new DamageInfo(DamageDefOf.Cut, Rand.Range(5, 8), null, new BodyPartDamageInfo?(value), null)); if (headRecord != null) { pawn(map).TakeDamage(new DamageInfo(DamageDefOf.Cut, Rand.Range(5, 8), 1f, -1f, null, headRecord)); } break; } case > 10 and <= 50: { //HediffDef quiet = null; //BodyPartDamageInfo value = new BodyPartDamageInfo(tempRecord, false, quiet); if (headRecord != null) { pawn(map).TakeDamage( new DamageInfo(DamageDefOf.Blunt, Rand.Range(8, 10), 1f, -1f, null, headRecord)); } break; } case <= 10: { //HediffDef quiet = null; //BodyPartDamageInfo value = new BodyPartDamageInfo(tempRecord, false, quiet); if (headRecord != null) { pawn(map).TakeDamage( new DamageInfo(DamageDefOf.Bite, Rand.Range(10, 12), -1f, 1f, null, headRecord)); pawn(map).health.AddHediff(HediffDefOf.WoundInfection, headRecord); } break; } } pawn(map).health.AddHediff(CultsDefOf.Cults_PsionicBrain, pawn(map).health.hediffSet.GetBrain()); Messages.Message(pawn(map).LabelShort + "'s brain has been enhanced with great psionic power.", MessageTypeDefOf.PositiveEvent); if (map == null) { return true; } map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = pawn(map).Position; Utility.ApplyTaleDef("Cults_SpellPsionicGrowth", pawn(map)); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Nyarlathotep/SpellWorker_ForbiddenKnowledge.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_ForbiddenKnowledge : SpellWorker { private Reason failReason = Reason.Null; protected Building_ResearchBench ResearchStation(Map map) { var benches = map.listerBuildings.AllBuildingsColonistOfClass<Building_ResearchBench>(); if (benches == null) { return null; } if (benches.TryRandomElement(out var bench)) { return bench; } return null; } protected ResearchProjectDef ResearchProject() { return Find.ResearchManager.currentProj; } public override bool CanSummonNow(Map map) { var flag = ResearchStation(map) != null && ResearchProject() != null; if (ResearchStation(map) == null) { failReason = Reason.NoBenches; flag = false; } if (ResearchProject() == null) { failReason = Reason.NoResearchProject; flag = false; } if (flag) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } if (failReason == Reason.NoBenches) { Messages.Message("There are no research benches to be found.", MessageTypeDefOf.RejectInput); failReason = Reason.Null; return false; } if (failReason == Reason.NoResearchProject) { Messages.Message("There are no research projects currently being researched.", MessageTypeDefOf.RejectInput); failReason = Reason.Null; return false; } //Cthulhu.Utility.DebugReport(this.ToString() + " Unknown error"); failReason = Reason.Null; return false; } protected override bool TryExecuteWorker(IncidentParms parms) { if (!(parms.target is Map map)) { return false; } //Set up variables var researchFinishedValue = ResearchProject().baseCost; _ = Find.ResearchManager.GetProgress(ResearchProject()); var researchAddedProgress = 0f; researchAddedProgress += (researchFinishedValue + 1) / 2 * 99; //Cthulhu.Utility.DebugReport("Research Added: " + researchAddedProgress.ToString()); //Perform some research Find.ResearchManager.ResearchPerformed(researchAddedProgress, executioner(map)); map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = executioner(map).Position; Messages.Message("Nyarlathotep grants your colony forbidden knowledge.", MessageTypeDefOf.PositiveEvent); return true; } private enum Reason { Null = 0, NoBenches, NoResearchProject } } }<file_sep>/Source/CultOfCthulhu/UI/Dialog_RenameCult.cs using Cthulhu; using Verse; namespace CultOfCthulhu { public class Dialog_RenameCult : Dialog_Rename { private readonly Map map; public Dialog_RenameCult(Map newMap) { map = newMap; if (map != null) { curName = CultTracker.Get.PlayerCult.name; } else { Utility.ErrorReport("Missing map to declare as home area"); } } protected override AcceptanceReport NameIsValid(string name) { var result = base.NameIsValid(name); if (!result.Accepted) { return result; } return name.Length == 0 || !CultUtility.CheckValidCultName(name) ? "NameIsInvalid".Translate() : (AcceptanceReport) true; } protected override void SetName(string name) { if (map != null) { CultTracker.Get.PlayerCult.name = name; } else { Utility.ErrorReport("Map Reference Null Exception"); } } } }<file_sep>/Source/CultOfCthulhu/UI/ITab_AltarAnimalSacrificeCardUtility.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using UnityEngine; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { [StaticConstructorOnStartup] public class ITab_AltarAnimalSacrificeCardUtility { public static void DrawRename(Building_SacrificialAltar altar) { var rectRename = new Rect(ITab_AltarWorshipCardUtility.TempleCardSize.x - 85f, 0f, 30f, 30f); TooltipHandler.TipRegion(rectRename, "RenameTemple".Translate()); if (Widgets.ButtonImage(rectRename, Buttons.RenameTex)) { Find.WindowStack.Add(new Dialog_RenameTemple(altar)); } } public static void DrawTempleCard(Rect rect, Building_SacrificialAltar altar) { GUI.BeginGroup(rect); var rect3 = new Rect(2f, 0f, ITab_AltarSacrificesCardUtility.ColumnSize, ITab_AltarSacrificesCardUtility.ButtonSize); Widgets.Label(rect3, "Deity".Translate() + ": "); rect3.xMin = rect3.center.x - 15f; var label2 = ITab_AltarCardUtility.DeityLabel(altar, ITab_AltarCardUtility.DeityType.SacrificeDeity); if (Widgets.ButtonText(rect3, label2, true, false)) { ITab_AltarCardUtility.OpenDeitySelectMenu(altar, ITab_AltarCardUtility.DeityType.SacrificeDeity); } TooltipHandler.TipRegion(rect3, "DeityDesc".Translate()); ITab_AltarCardUtility.DrawDeity(altar.tempCurrentSacrificeDeity, rect3); var rect4 = rect3; rect4.y += ITab_AltarSacrificesCardUtility.ButtonSize + ITab_AltarSacrificesCardUtility.SpacingOffset; rect4.width = ITab_AltarSacrificesCardUtility.ColumnSize; rect4.x -= rect3.x - 2; Widgets.Label(rect4, "Executioner".Translate() + ": "); rect4.xMin = rect4.center.x - 15f; var label3 = ITab_AltarCardUtility.ExecutionerLabel(altar); if (Widgets.ButtonText(rect4, label3, true, false)) { ITab_AltarCardUtility.OpenActorSelectMenu(altar, ITab_AltarCardUtility.ActorType.executioner); } TooltipHandler.TipRegion(rect4, "ExecutionerDesc".Translate()); var rect5 = rect4; rect5.y += ITab_AltarSacrificesCardUtility.ButtonSize + ITab_AltarSacrificesCardUtility.SpacingOffset; rect5.x -= rect4.x - 2; //rect5.x += 2f; rect5.width = ITab_AltarSacrificesCardUtility.ColumnSize; Widgets.Label(rect5, "Sacrifice".Translate() + ": "); rect5.xMin = rect5.center.x - 15f; var label4 = ITab_AltarCardUtility.SacrificeLabel(altar); if (Widgets.ButtonText(rect5, label4, true, false)) { ITab_AltarCardUtility.OpenActorSelectMenu(altar, ITab_AltarCardUtility.ActorType.animalSacrifice); } TooltipHandler.TipRegion(rect5, "SacrificeAnimalDesc".Translate()); //Rect rect6 = rect5; //rect6.y += 35f; //rect6.x -= (rect5.x - 5); ////rect6.x += 2f; //rect6.width = 210f; //rect6.yMax += 35f; //Widgets.Label(rect6, "Cults_Spell".Translate() + ": "); //rect6.xMin = rect6.center.x - 15f; //string label5 = SpellLabel(altar); //if (Widgets.ButtonText(rect6, label5, true, false, true)) //{ // ITab_AltarHumanSacrificeCardUtility.OpenSpellSelectMenu(altar); //} /* Rect rect4 = rect3; rect4.y += 35f; rect4.width = 150f; if (Widgets.ButtonText(rect4, "RenameTemple".Translate(), true, false, true)) { Find.WindowStack.Add(new Dialog_RenameTemple(altar)); } Rect rectDebug1 = rect4; rectDebug1.y += 25f; if (DebugSettings.godMode) { if (Widgets.ButtonText(rectDebug1, "ForceSermonDebug".Translate(), true, false, true)) { SermonUtility.ForceSermon(altar); } Rect rectDebug2 = rectDebug1; rectDebug2.y += 25f; if (Widgets.ButtonText(rectDebug2, "ForceListenersDebug".Translate(), true, false, true)) { TempleCardUtility.ForceListenersTest(altar); } } Rect rect5 = rect4; rect5.x = rect4.xMax + 5f; rect5.width = 200f; rect5.y -= 20f; Widgets.CheckboxLabeled(rect5, "MorningSermons".Translate(), ref altar.OptionMorning, false); Rect rect6 = rect5; rect6.y += 20f; Widgets.CheckboxLabeled(rect6, "EveningSermons".Translate(), ref altar.OptionEvening, false); */ GUI.EndGroup(); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/ThoughtWorker_AuroraEffect.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class ThoughtWorker_AuroraEffect : ThoughtWorker { protected override ThoughtState CurrentStateInternal(Pawn p) { var activeCondition = p.Map.GameConditionManager.GetActiveCondition<GameCondition_AuroraEffect>(); return activeCondition != null ? ThoughtState.ActiveAtStage(0) : false; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/CompTransporterPawn.cs using System.Collections.Generic; using System.Diagnostics; using System.Linq; using RimWorld; using UnityEngine; using Verse; using Verse.AI.Group; using Verse.Sound; namespace CultOfCthulhu { [StaticConstructorOnStartup] public class CompTransporterPawn : ThingComp, IThingHolder { public static readonly Texture2D CancelLoadCommandTex = ContentFinder<Texture2D>.Get("UI/Designators/Cancel"); public static readonly Texture2D LoadCommandTex = ContentFinder<Texture2D>.Get("UI/Commands/LoadTransporter"); public static readonly Texture2D SelectPreviousInGroupCommandTex = ContentFinder<Texture2D>.Get("UI/Commands/SelectPreviousTransporter"); public static readonly Texture2D SelectAllInGroupCommandTex = ContentFinder<Texture2D>.Get("UI/Commands/SelectAllTransporters"); public static readonly Texture2D SelectNextInGroupCommandTex = ContentFinder<Texture2D>.Get("UI/Commands/SelectNextTransporter"); public static readonly List<CompTransporterPawn> tmpTransportersInGroup = new List<CompTransporterPawn>(); private CompLaunchablePawn cachedCompLaunchablePawn; public int groupID = -1; private ThingOwner innerContainer; public List<TransferableOneWay> leftToLoad; public CompTransporterPawn() { innerContainer = new ThingOwner<Thing>(this, false); } public CompProperties_TransporterPawn Props => (CompProperties_TransporterPawn) props; public Map Map => parent.MapHeld; public bool Spawned => parent.Spawned; public bool AnythingLeftToLoad => FirstThingLeftToLoad != null; public bool LoadingInProgressOrReadyToLaunch => groupID >= 0; public bool AnyInGroupHasAnythingLeftToLoad => FirstThingLeftToLoadInGroup != null; public CompLaunchablePawn Launchable { get { if (cachedCompLaunchablePawn == null) { cachedCompLaunchablePawn = parent.GetComp<CompLaunchablePawn>(); } return cachedCompLaunchablePawn; } } public Thing FirstThingLeftToLoad { get { var transferableOneWay = leftToLoad?.Find(x => x.CountToTransfer != 0 && x.HasAnyThing); return transferableOneWay?.AnyThing; } } public Thing FirstThingLeftToLoadInGroup { get { var list = TransportersInGroup(parent.Map); foreach (var compTransporterPawn in list) { var firstThingLeftToLoad = compTransporterPawn.FirstThingLeftToLoad; if (firstThingLeftToLoad != null) { return firstThingLeftToLoad; } } return null; } } public void GetChildHolders(List<IThingHolder> outChildren) { ThingOwnerUtility.AppendThingHoldersFromThings(outChildren, GetDirectlyHeldThings()); } public ThingOwner GetDirectlyHeldThings() { return innerContainer; } public override void PostExposeData() { base.PostExposeData(); Scribe_Values.Look(ref groupID, "groupID"); Scribe_Deep.Look(ref innerContainer, "innerContainer", this); Scribe_Collections.Look(ref leftToLoad, "leftToLoad", LookMode.Deep); } public IntVec3 GetPosition() { return parent.PositionHeld; } public Map GetMap() { return parent.MapHeld; } public List<CompTransporterPawn> TransportersInGroup(Map map) { if (!LoadingInProgressOrReadyToLaunch) { return null; } tmpTransportersInGroup.Clear(); if (groupID < 0) { return null; } var listSel = from Pawn pawns in map.mapPawns.AllPawnsSpawned where pawns is PawnFlyer select pawns; var list = new List<Pawn>(listSel); foreach (var pawn in list) { var compTransporter = pawn.TryGetComp<CompTransporterPawn>(); if (compTransporter.groupID == groupID) { tmpTransportersInGroup.Add(compTransporter); } } return tmpTransportersInGroup; } [DebuggerHidden] public override IEnumerable<Gizmo> CompGetGizmosExtra() { using var enumerator = base.CompGetGizmosExtra().GetEnumerator(); while (enumerator.MoveNext()) { var current = enumerator.Current; yield return current; } if (LoadingInProgressOrReadyToLaunch) { yield return new Command_Action { defaultLabel = "CommandCancelLoad".Translate(), defaultDesc = "CommandCancelLoadDesc".Translate(), icon = CancelLoadCommandTex, action = delegate { SoundDefOf.Designate_Cancel.PlayOneShotOnCamera(); CancelLoad(); } }; } var Command_LoadToTransporterPawn = new Command_LoadToTransporterPawn(); var num = 0; for (var i = 0; i < Find.Selector.NumSelected; i++) { if (Find.Selector.SelectedObjectsListForReading[i] is not Thing thing || thing.def != parent.def) { continue; } var CompLaunchablePawn = thing.TryGetComp<CompLaunchablePawn>(); if (CompLaunchablePawn == null) { num++; } } Command_LoadToTransporterPawn.defaultLabel = "CommandLoadTransporter".Translate( num.ToString() ); Command_LoadToTransporterPawn.defaultDesc = "CommandLoadTransporterDesc".Translate(); Command_LoadToTransporterPawn.icon = LoadCommandTex; Command_LoadToTransporterPawn.transComp = this; var launchable = Launchable; //if (launchable != null) //{ // if (!launchable.ConnectedToFuelingPort) // { // Command_LoadToTransporterPawn.Disable("CommandLoadTransporterFailNotConnectedToFuelingPort".Translate()); // } // else if (!launchable.FuelingPortSourceHasAnyFuel) // { // Command_LoadToTransporterPawn.Disable("CommandLoadTransporterFailNoFuel".Translate()); // } //} yield return Command_LoadToTransporterPawn; } public override void PostDeSpawn(Map map) { base.PostDeSpawn(map); if (CancelLoad(map)) { Messages.Message("MessageTransportersLoadCanceled_TransporterDestroyed".Translate(), MessageTypeDefOf.NegativeEvent); } } public void AddToTheToLoadList(TransferableOneWay t, int count) { if (!t.HasAnyThing || t.CountToTransfer <= 0) { return; } if (leftToLoad == null) { leftToLoad = new List<TransferableOneWay>(); } if (TransferableUtility.TransferableMatching(t.AnyThing, leftToLoad, TransferAsOneMode.PodsOrCaravanPacking) != null) { Log.Error("Transferable already exists."); return; } var transferableOneWay = new TransferableOneWay(); leftToLoad.Add(transferableOneWay); transferableOneWay.things.AddRange(t.things); transferableOneWay.AdjustTo(count); } public void Notify_ThingAdded(Thing t) { SubtractFromToLoadList(t, t.stackCount); } public void Notify_PawnEnteredTransporterOnHisOwn(Pawn p) { SubtractFromToLoadList(p, 1); } public bool CancelLoad() { return CancelLoad(Map); } public bool CancelLoad(Map map) { if (!LoadingInProgressOrReadyToLaunch) { return false; } TryRemoveLord(map); var list = TransportersInGroup(map); foreach (var compTransporterPawn in list) { compTransporterPawn.CleanUpLoadingVars(map); } CleanUpLoadingVars(map); return true; } // RimWorld.TransporterUtility public static Lord FindLord(int transportersGroup, Map map) { var lords = map.lordManager.lords; foreach (var findLord in lords) { if (findLord.LordJob is LordJob_LoadAndEnterTransportersPawn lordJob_LoadAndEnterTransporters && lordJob_LoadAndEnterTransporters.transportersGroup == transportersGroup) { return findLord; } } return null; } public void TryRemoveLord(Map map) { if (!LoadingInProgressOrReadyToLaunch) { return; } var lord = FindLord(groupID, map); if (lord != null) { map.lordManager.RemoveLord(lord); } } public void CleanUpLoadingVars(Map map) { groupID = -1; innerContainer.TryDropAll(parent.Position, map, ThingPlaceMode.Near); leftToLoad?.Clear(); } private void SubtractFromToLoadList(Thing t, int count) { if (leftToLoad == null) { return; } var transferableOneWay = TransferableUtility.TransferableMatching(t, leftToLoad, TransferAsOneMode.PodsOrCaravanPacking); if (transferableOneWay == null) { return; } transferableOneWay.AdjustBy(-count); if (transferableOneWay.CountToTransfer <= 0) { leftToLoad.Remove(transferableOneWay); } if (!AnyInGroupHasAnythingLeftToLoad) { Messages.Message("MessageFinishedLoadingTransporters".Translate(), parent, MessageTypeDefOf.PositiveEvent); } } private void SelectPreviousInGroup() { var list = TransportersInGroup(Map); var num = list.IndexOf(this); CameraJumper.TryJumpAndSelect(list[GenMath.PositiveMod(num - 1, list.Count)].parent); } private void SelectAllInGroup() { var list = TransportersInGroup(Map); var selector = Find.Selector; selector.ClearSelection(); foreach (var compTransporterPawn in list) { selector.Select(compTransporterPawn.parent); } } private void SelectNextInGroup() { var list = TransportersInGroup(Map); var num = list.IndexOf(this); CameraJumper.TryJumpAndSelect(list[(num + 1) % list.Count].parent); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/CosmicEntities/Dialog_CosmicEntityInfoBox.cs using System; using CultOfCthulhu; using UnityEngine; using Verse; namespace CallOfCthulhu { public class Dialog_CosmicEntityInfoBox : Window { private const float InitialWidth = 640f; private const float InitialHeight = 800f; private readonly float creationRealTime; public Action acceptAction; public Action buttonAAction; public bool buttonADestructive; public string buttonAText; public Action buttonBAction; public string buttonBText; public Action buttonCAction; public bool buttonCClose = true; public string buttonCText; public Action cancelAction; public Texture2D image; public float interactionDelay = 0f; private Vector2 scrollPosition = Vector2.zero; public string text; public string title; public Dialog_CosmicEntityInfoBox(CosmicEntity entity) { text = entity.Info(); title = entity.LabelCap; if (buttonAText.NullOrEmpty()) { buttonAText = "OK".Translate(); } if (entity.Def.portrait != "") { image = ContentFinder<Texture2D>.Get(entity.Def.portrait); } forcePause = true; absorbInputAroundWindow = true; creationRealTime = RealTime.LastRealTime; onlyOneOfTypeAllowed = false; closeOnAccept = true; closeOnCancel = true; } public override Vector2 InitialSize => new Vector2(InitialWidth, InitialHeight); private float get_TimeUntilInteractive() { return interactionDelay - (Time.realtimeSinceStartup - creationRealTime); } private bool get_InteractionDelayExpired() { return get_TimeUntilInteractive() <= 0f; } public override void DoWindowContents(Rect inRect) { var num = inRect.y; if (!title.NullOrEmpty()) { Text.Font = (GameFont) 2; var nameSize = Text.CalcSize(title); var startingX = (inRect.width / 2) - (nameSize.x / 2); Widgets.Label(new Rect(startingX, num, inRect.width - startingX, 42f), title); num += 42f; } Text.Font = GameFont.Small; if (image != null) { var startingX = (inRect.width / 2) - (image.width * 0.5f); Widgets.ButtonImage(new Rect(startingX, num, inRect.width - startingX, image.height), image, Color.white, Color.white); num += image.height; num += 42f; } Text.Font = GameFont.Small; var outRect = new Rect(inRect.x, num, inRect.width, inRect.height - 35f - 5f - num); var width = outRect.width - 16f; var viewRect = new Rect(0f, num, width, Text.CalcHeight(text, width)); Widgets.BeginScrollView(outRect, ref scrollPosition, viewRect); Widgets.Label(new Rect(0f, num, viewRect.width, viewRect.height), text); Widgets.EndScrollView(); var num2 = !buttonCText.NullOrEmpty() ? 3 : 2; var num3 = inRect.width / num2; var width2 = num3 - 20f; if (buttonADestructive) { GUI.color = new Color(1f, 0.3f, 0.35f); } var label = !get_InteractionDelayExpired() ? buttonAText + "(" + Mathf.Ceil(get_TimeUntilInteractive()).ToString("F0") + ")" : buttonAText; if (Widgets.ButtonText(new Rect((num3 * (num2 - 1)) + 10f, inRect.height - 35f, width2, 35f), label, true, false)) { if (get_InteractionDelayExpired()) { Close(); } } GUI.color = Color.white; } public override void OnCancelKeyPressed() { if (cancelAction != null) { cancelAction(); Close(); } else { base.OnCancelKeyPressed(); } } public override void OnAcceptKeyPressed() { if (acceptAction != null) { acceptAction(); Close(); } else { base.OnAcceptKeyPressed(); } } private static void CreateConfirmation() { } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Seed/WorkGiver_Investigate.cs using RimWorld; using Verse; using Verse.AI; namespace CultOfCthulhu { public class WorkGiver_Investigate : WorkGiver_Scanner { //public static IEnumerable<Thing> MysteriousObjects(Pawn pawn) //{ // List<Thing> thingsToCheck = new List<Thing>(from Thing things in pawn.Map.spawnedThings // where things.def == CultsDefOf.Cults_PlantTreeNightmare || // things.def == CultsDefOf.Cults_MonolithNightmare // select things); // return thingsToCheck; //} public override PathEndMode PathEndMode => PathEndMode.Touch; //public override IEnumerable<Thing> PotentialWorkThingsGlobal(Pawn pawn) //{ // return MysteriousObjects(pawn); //} public override ThingRequest PotentialWorkThingRequest => ThingRequest.ForDef(CultsDefOf.Cults_MonolithNightmare); //public override bool ShouldSkip(Pawn pawn) //{ // return MysteriousObjects(pawn).Count<Thing>() == 0; //} public override bool Prioritized => true; public override bool HasJobOnThing(Pawn pawn, Thing t, bool forced = false) { if (t == null) { return false; } if (t.def != CultsDefOf.Cults_PlantTreeNightmare && t.def != CultsDefOf.Cults_MonolithNightmare) { return false; } //Log.Message("1"); //Log.Message("2"); var cultTracker = pawn.MapHeld.GetComponent<MapComponent_LocalCultTracker>(); if (cultTracker != null && cultTracker.CurrentSeedState > CultSeedState.NeedSeeing) { return false; } //Log.Message("3"); if (CultUtility.AreCultObjectsAvailable(pawn.MapHeld) == false) { if (CultUtility.IsSomeoneInvestigating(pawn.MapHeld)) { return false; } } //Log.Message("4"); if (pawn.Faction != Faction.OfPlayerSilentFail) { return false; } //if (pawn.Faction == Faction.OfPlayer && !pawn.Map.areaManager.Home[t.Position]) //{ // JobFailReason.Is(WorkGiver_FixBrokenDownBuilding.NotInHomeAreaTrans); // return false; //} //Log.Message("5"); if (!pawn.CanReserveAndReach(t, PathEndMode.ClosestTouch, Danger.None)) { return false; // pawn.Map.reservationManager.IsReserved(t, pawn.Faction)) return false; } //Log.Message("6"); return true; } public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false) { //Log.Message("JobOnThing"); pawn.MapHeld.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedPawn = pawn; pawn.MapHeld.GetComponent<MapComponent_LocalCultTracker>().CurrentSeedTarget = t; return new Job(CultsDefOf.Cults_Investigate, pawn, t); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/SpellWorker_EcstaticFrenzy.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_EcstaticFrenzy : SpellWorker { protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } protected IEnumerable<Pawn> Colonists(Map map) { return from Pawn colonist in map.mapPawns.FreeColonists where !colonist.RaceProps.Animal && !(colonist.Downed || colonist.Dead) && colonist.Faction == Faction.OfPlayer select colonist; } protected override bool TryExecuteWorker(IncidentParms parms) { for (var i = 0; i < Rand.Range(1, 2); i++) { if (Colonists((Map) parms.target).Count() != 0) { if (!Colonists((Map) parms.target).TryRandomElement(out var colonist)) { continue; } //Cthulhu.Utility.DebugReport("Destroyed: " + item.ToString()); colonist?.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk); } else { Utility.DebugReport("No colonists to drive insane."); } } return true; } } }<file_sep>/Source/CultOfCthulhu/UI/Buttons.cs using UnityEngine; using Verse; namespace CultOfCthulhu { [StaticConstructorOnStartup] internal class Buttons { public static readonly Texture2D TierBarFillTex = SolidColorMaterials.NewSolidColorTexture(new Color(1f, 1f, 1f, 0.25f)); public static readonly Texture2D RenameTex = ContentFinder<Texture2D>.Get("UI/SorryTynan_Rename"); public static readonly Texture2D RedTex = SolidColorMaterials.NewSolidColorTexture(Color.red); } }<file_sep>/Source/CultOfCthulhu/NewSystems/Reanimation/ReanimatedPawnUtility.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System; using System.Reflection; using Cthulhu; using RimWorld; using UnityEngine; using Verse; using Verse.AI; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { internal class ReanimatedPawnUtility { public static Color zombieSkin = new Color(0.37f, 0.48f, 0.35f, 1f); public static ReanimatedPawn DoGenerateZombiePawnFromSource(Pawn sourcePawn, bool isBerserk = true, bool oathOfHastur = false) { var pawnKindDef = PawnKindDef.Named("ReanimatedCorpse"); var factionDirect = isBerserk ? Find.FactionManager.FirstFactionOfDef(FactionDefOf.AncientsHostile) : Faction.OfPlayer; var pawn = (ReanimatedPawn) ThingMaker.MakeThing(pawnKindDef.race); try { pawn.kindDef = pawnKindDef; pawn.SetFactionDirect(factionDirect); PawnComponentsUtility.CreateInitialComponents(pawn); pawn.gender = sourcePawn.gender; pawn.ageTracker.AgeBiologicalTicks = sourcePawn.ageTracker.AgeBiologicalTicks; pawn.ageTracker.AgeChronologicalTicks = sourcePawn.ageTracker.AgeChronologicalTicks; pawn.workSettings = new Pawn_WorkSettings(pawn); if (pawn.workSettings != null && sourcePawn.Faction.IsPlayer) { pawn.workSettings.EnableAndInitialize(); } pawn.needs.SetInitialLevels(); //Add hediffs? //Add relationships? if (pawn.RaceProps.Humanlike) { pawn.story.melanin = sourcePawn.story.melanin; pawn.story.crownType = sourcePawn.story.crownType; pawn.story.hairColor = sourcePawn.story.hairColor; pawn.story.childhood = sourcePawn.story.childhood; pawn.story.adulthood = sourcePawn.story.adulthood; pawn.story.bodyType = sourcePawn.story.bodyType; pawn.story.hairDef = sourcePawn.story.hairDef; if (!oathOfHastur) { foreach (var current in sourcePawn.story.traits.allTraits) { pawn.story.traits.GainTrait(current); } } else { pawn.story.traits.GainTrait(new Trait(TraitDef.Named("Cults_OathtakerHastur2"), 0, true)); pawn.story.traits.GainTrait(new Trait(TraitDefOf.Psychopath, 0, true)); SkillFixer(pawn, sourcePawn); RelationshipFixer(pawn, sourcePawn); AddedPartFixer(pawn, sourcePawn); } //pawn.story.GenerateSkillsFromBackstory(); var nameTriple = sourcePawn.Name as NameTriple; if (!oathOfHastur) { pawn.Name = new NameTriple(nameTriple?.First, string.Concat("* ", "Reanimated".Translate(), " ", nameTriple?.Nick, " *"), nameTriple?.Last); } else { pawn.Name = nameTriple; } } var headGraphicPath = sourcePawn.story.HeadGraphicPath; typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic) ?.SetValue(pawn.story, headGraphicPath); GenerateZombieApparelFromSource(pawn, sourcePawn); var con = new PawnGenerationRequest(); PawnInventoryGenerator.GenerateInventoryFor(pawn, con); GiveZombieSkinEffect(pawn, sourcePawn as ReanimatedPawn, oathOfHastur); if (isBerserk) { pawn.mindState.mentalStateHandler.TryStartMentalState(MentalStateDefOf.Berserk); } //Log.Message(pawn.Name.ToStringShort); return pawn; } catch (Exception e) { Utility.DebugReport(e.ToString()); } return null; } public static void AddedPartFixer(ReanimatedPawn pawn, Pawn sourcePawn = null) { if (sourcePawn?.health.hediffSet.hediffs == null) { return; } foreach (var hediff in sourcePawn.health.hediffSet.hediffs) { if (hediff is Hediff_AddedPart || hediff is Hediff_Implant) { pawn.health.AddHediff(hediff); } } } public static void SkillFixer(ReanimatedPawn pawn, Pawn sourcePawn = null) { //Add in and fix skill levels if (sourcePawn == null) { return; } foreach (var skill in sourcePawn.skills.skills) { var pawnSkill = pawn.skills.GetSkill(skill.def); if (pawnSkill == null) { pawn.skills.skills.Add(skill); } else { pawnSkill.Level = skill.Level; pawnSkill.passion = skill.passion; } } } public static void RelationshipFixer(ReanimatedPawn pawn, Pawn sourcePawn = null) { //Add in and fix all blood relationships if (sourcePawn != null && (sourcePawn.relations.DirectRelations == null || sourcePawn.relations.DirectRelations.Count <= 0)) { return; } if (sourcePawn == null) { return; } foreach (var pawnRel in sourcePawn.relations.DirectRelations) { if (pawnRel.otherPawn != null && pawnRel.def != null) { pawn.relations.AddDirectRelation(pawnRel.def, pawnRel.otherPawn); } } sourcePawn.relations.ClearAllRelations(); } public static void GiveZombieSkinEffect(ReanimatedPawn pawn, ReanimatedPawn sourcePawn = null, bool oathOfHastur = false) { if (sourcePawn == null) { sourcePawn = pawn; } var newSkin = oathOfHastur ? new Color(1, 1, 1) : zombieSkin; var nakedBodyGraphic = GraphicDatabase.Get<Graphic_Multi>(sourcePawn.story.bodyType.bodyNakedGraphicPath, ShaderDatabase.CutoutSkin, Vector2.one, newSkin); var headGraphic = GraphicDatabase.Get<Graphic_Multi>(sourcePawn.story.HeadGraphicPath, ShaderDatabase.CutoutSkin, Vector2.one, newSkin); var hairGraphic = GraphicDatabase.Get<Graphic_Multi>(sourcePawn.story.hairDef.texPath, ShaderDatabase.Cutout, Vector2.one, sourcePawn.story.hairColor); pawn.Drawer.renderer.graphics.headGraphic = headGraphic; pawn.Drawer.renderer.graphics.nakedGraphic = nakedBodyGraphic; pawn.Drawer.renderer.graphics.hairGraphic = hairGraphic; } public static bool Zombify(ReanimatedPawn pawn) { if (pawn.Drawer?.renderer?.graphics == null) { return false; } if (!pawn.Drawer.renderer.graphics.AllResolved) { pawn.Drawer.renderer.graphics.ResolveAllGraphics(); } if (pawn.Drawer.renderer.graphics.headGraphic == null) { return false; } if (pawn.Drawer.renderer.graphics.nakedGraphic == null) { return false; } if (pawn.Drawer.renderer.graphics.headGraphic.path == null) { return false; } if (pawn.Drawer.renderer.graphics.nakedGraphic.path == null) { return false; } GiveZombieSkinEffect(pawn); return true; } // Credit goes to <NAME> for the Zombie Apocalypse code. // Taken from Verse.ZombieMod_Utility public static Pawn GenerateZombiePawnFromSource(Pawn sourcePawn) { var pawnKindDef = PawnKindDef.Named("ReanimatedCorpse"); var factionDirect = Find.FactionManager.FirstFactionOfDef(FactionDefOf.AncientsHostile); var pawn = (Pawn) ThingMaker.MakeThing(pawnKindDef.race); pawn.kindDef = pawnKindDef; pawn.SetFactionDirect(factionDirect); pawn.pather = new Pawn_PathFollower(pawn); pawn.ageTracker = new Pawn_AgeTracker(pawn); pawn.health = new Pawn_HealthTracker(pawn); pawn.jobs = new Pawn_JobTracker(pawn); pawn.mindState = new Pawn_MindState(pawn); pawn.filth = new Pawn_FilthTracker(pawn); pawn.needs = new Pawn_NeedsTracker(pawn); pawn.stances = new Pawn_StanceTracker(pawn); pawn.natives = new Pawn_NativeVerbs(pawn); PawnComponentsUtility.CreateInitialComponents(pawn); if (pawn.RaceProps.ToolUser) { pawn.equipment = new Pawn_EquipmentTracker(pawn); pawn.carryTracker = new Pawn_CarryTracker(pawn); pawn.apparel = new Pawn_ApparelTracker(pawn); pawn.inventory = new Pawn_InventoryTracker(pawn); } if (pawn.RaceProps.Humanlike) { pawn.ownership = new Pawn_Ownership(pawn); pawn.skills = new Pawn_SkillTracker(pawn); pawn.relations = new Pawn_RelationsTracker(pawn); pawn.story = new Pawn_StoryTracker(pawn); pawn.workSettings = new Pawn_WorkSettings(pawn); } if (pawn.RaceProps.intelligence <= Intelligence.ToolUser) { pawn.caller = new Pawn_CallTracker(pawn); } //pawn.gender = Gender.None; pawn.gender = sourcePawn.gender; Utility.GenerateRandomAge(pawn, pawn.Map); pawn.needs.SetInitialLevels(); if (pawn.RaceProps.Humanlike) { var headGraphicPath = sourcePawn.story.HeadGraphicPath; typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic) ?.SetValue(pawn.story, headGraphicPath); pawn.story.melanin = sourcePawn.story.melanin; pawn.story.crownType = sourcePawn.story.crownType; pawn.story.hairColor = sourcePawn.story.hairColor; var name = sourcePawn.Name as NameTriple; pawn.Name = name; pawn.story.childhood = sourcePawn.story.childhood; pawn.story.adulthood = sourcePawn.story.adulthood; pawn.story.hairDef = sourcePawn.story.hairDef; foreach (var current in sourcePawn.story.traits.allTraits) { pawn.story.traits.GainTrait(current); } //pawn.story.GenerateSkillsFromBackstory(); } GenerateZombieApparelFromSource(pawn, sourcePawn); var con = new PawnGenerationRequest(); PawnInventoryGenerator.GenerateInventoryFor(pawn, con); //Graphic nakedBodyGraphic = GraphicGetter_NakedHumanlike.GetNakedBodyGraphic(sourcePawn.story.bodyType, ShaderDatabase.CutoutSkin, new Color(0.37f, 0.48f, 0.35f, 1f)); var nakedBodyGraphic = GraphicDatabase.Get<Graphic_Multi>(sourcePawn.story.bodyType.bodyNakedGraphicPath, ShaderDatabase.CutoutSkin, Vector2.one, new Color(0.37f, 0.48f, 0.35f, 1f)); var headGraphic = GraphicDatabase.Get<Graphic_Multi>(sourcePawn.story.HeadGraphicPath, ShaderDatabase.CutoutSkin, Vector2.one, new Color(0.37f, 0.48f, 0.35f, 1f)); var hairGraphic = GraphicDatabase.Get<Graphic_Multi>(sourcePawn.story.hairDef.texPath, ShaderDatabase.Cutout, Vector2.one, sourcePawn.story.hairColor); pawn.Drawer.renderer.graphics.headGraphic = headGraphic; pawn.Drawer.renderer.graphics.nakedGraphic = nakedBodyGraphic; pawn.Drawer.renderer.graphics.hairGraphic = hairGraphic; return pawn; } // More of <NAME>'s work. I can't take credit for this. // Verse.ZombieMod_Utility public static void GenerateZombieApparelFromSource(Pawn zombie, Pawn sourcePawn) { if (sourcePawn.apparel == null || sourcePawn.apparel.WornApparelCount == 0) { return; } foreach (var current in sourcePawn.apparel.WornApparel) { Apparel apparel; if (current.def.MadeFromStuff) { apparel = (Apparel) ThingMaker.MakeThing(current.def, current.Stuff); } else { apparel = (Apparel) ThingMaker.MakeThing(current.def); } apparel.DrawColor = new Color(current.DrawColor.r, current.DrawColor.g, current.DrawColor.b, current.DrawColor.a); zombie.apparel.Wear(apparel); } } } }<file_sep>/Source/CultOfCthulhu/Unused/Building_BurstingTentacle.cs using Verse; namespace CultOfCthulhu { internal class Building_BurstingTentacle : Building { public const int defaultTicksUntilFlicker = 500; public int ticksUntilFlicker = 500; public override void Tick() { flickerCheck(); base.Tick(); } public void flickerCheck() { if (ticksUntilFlicker > 0) { ticksUntilFlicker -= 1; } else { ticksUntilFlicker = defaultTicksUntilFlicker; Thing newTentacle = (Building_BurstingTentacle) ThingMaker.MakeThing(ThingDef.Named("BurstingTentacle")); GenPlace.TryPlaceThing(newTentacle, Position, Map, ThingPlaceMode.Direct); } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/PawnFlyerDef.cs using RimWorld; using Verse; namespace CultOfCthulhu { public class PawnFlyerDef : ThingDef { public SoundDef dismountSound; public int flightPawnLimit; public float flightSpeed; public int flyableDistance; public ThingDef incomingDef; public ThingDef landedDef; public TaleDef landedTale; public SoundDef landingSound; public ThingDef leavingDef; public SoundDef takeOffSound; public WorldObjectDef travelingDef; } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Dagon/SpellWorker_SunkenShip.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_SunkenShip : SpellWorker { protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } public override bool CanSummonNow(Map map) { return true; } protected override bool TryExecuteWorker(IncidentParms parms) { if (!(parms.target is Map map)) { return false; } if (!CultUtility.TryFindDropCell(map.Center, map, 999999, out var intVec)) { return false; } GenSpawn.Spawn(CultsDefOf.Cults_SunkenShipChunk, intVec, map); map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = intVec; Messages.Message("MessageSunkenShipChunkDrop".Translate(), new TargetInfo(intVec, map), MessageTypeDefOf.NeutralEvent); Utility.ApplyTaleDef("Cults_SpellSunkenShip", map); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/PawnFlyer/PawnFlyersIncoming.cs using System.Collections.Generic; using System.Linq; using Cthulhu; using RimWorld; using UnityEngine; using Verse; using Verse.Sound; namespace CultOfCthulhu { public class PawnFlyersIncoming : Thing, IActiveDropPod, IThingHolder { protected const int MinTicksToImpact = 120; protected const int MaxTicksToImpact = 200; protected const int RoofHitPreDelay = 15; private const int SoundAnticipationTicks = 100; private float angle; // RimWorld.Skyfaller private Material cachedShadowMaterial; private ActiveDropPodInfo contents; public PawnFlyer pawnFlyer; private bool soundPlayed; protected int ticksToImpact = 120; public override Vector3 DrawPos { get { //switch (this.def.skyfaller.movementType) //{ // case SkyfallerMovementType.Accelerate: // result = SkyfallerDrawPosUtility.DrawPos_Accelerate(base.DrawPos, this.ticksToImpact, this.angle, this.def.skyfaller.speed); // break; // case SkyfallerMovementType.ConstantSpeed: // result = SkyfallerDrawPosUtility.DrawPos_ConstantSpeed(base.DrawPos, this.ticksToImpact, this.angle, this.def.skyfaller.speed); // break; // case SkyfallerMovementType.Decelerate: // result = SkyfallerDrawPosUtility.DrawPos_Decelerate(base.DrawPos, this.ticksToImpact, this.angle, this.def.skyfaller.speed); // break; // default: // Log.ErrorOnce("SkyfallerMovementType not handled: " + this.def.skyfaller.movementType, this.thingIDNumber ^ 1948576711); var result = SkyfallerDrawPosUtility.DrawPos_Accelerate(base.DrawPos, ticksToImpact, angle, def.skyfaller.speed); //break; //} return result; //return DropPodAnimationUtility.DrawPosAt(this.ticksToImpact, base.Position); } } private PawnFlyerDef PawnFlyerDef => pawnFlyer.def as PawnFlyerDef; // RimWorld.Skyfaller private Material ShadowMaterial { get { if (cachedShadowMaterial == null && !def.skyfaller.shadow.NullOrEmpty()) { cachedShadowMaterial = MaterialPool.MatFrom(def.skyfaller.shadow, ShaderDatabase.Transparent); } return cachedShadowMaterial; } } public ActiveDropPodInfo Contents { get => contents; set { if (contents != null) { contents.parent = null; } if (value != null) { value.parent = this; } contents = value; } } public void GetChildHolders(List<IThingHolder> outChildren) { ThingOwnerUtility.AppendThingHoldersFromThings(outChildren, GetDirectlyHeldThings()); } public ThingOwner GetDirectlyHeldThings() { return contents.innerContainer; } public override void SpawnSetup(Map map, bool respawningAfterLoad) { base.SpawnSetup(map, respawningAfterLoad); // RimWorld.Skyfaller base.SpawnSetup(map, respawningAfterLoad); if (respawningAfterLoad) { return; } ticksToImpact = def.skyfaller.ticksToImpactRange.RandomInRange; angle = -33.7f; if (def.rotatable && this.TryGetInnerInteractableThingOwner().Any) { Rotation = this.TryGetInnerInteractableThingOwner()[0].Rotation; } } public IntVec3 GetPosition() { return PositionHeld; } public Map GetMap() { return MapHeld; } public override void PostMake() { base.PostMake(); ticksToImpact = Rand.RangeInclusive(120, 200); } public override void ExposeData() { base.ExposeData(); //PawnFlyer Scribe_References.Look(ref pawnFlyer, "pawnFlyer"); //Vanilla Scribe_Values.Look(ref ticksToImpact, "ticksToImpact"); Scribe_Deep.Look(ref contents, "contents", this); } public override void Tick() { ticksToImpact--; if (ticksToImpact == 15) { HitRoof(); } if (ticksToImpact <= 0) { Impact(); } if (soundPlayed || ticksToImpact >= 100) { return; } soundPlayed = true; if (PawnFlyerDef.landingSound != null) { PawnFlyerDef.landingSound.PlayOneShot(new TargetInfo(Position, Map)); } else { Log.Warning("PawnFlyersIncoming :: Landing sound not set"); } } private void HitRoof() { if (!Position.Roofed(Map)) { return; } RoofCollapserImmediate.DropRoofInCells(this.OccupiedRect().ExpandedBy(1).Cells.Where(delegate(IntVec3 c) { if (!c.InBounds(Map)) { return false; } if (c == Position) { return true; } if (Map.thingGrid.CellContains(c, ThingCategory.Pawn)) { return false; } var edifice = c.GetEdifice(Map); return edifice == null || !edifice.def.holdsRoof; }), Map); } public override void DrawAt(Vector3 drawLoc, bool flipped) { if (!drawLoc.InBounds(Map)) { return; } pawnFlyer.Drawer.DrawAt(drawLoc); var shadowMaterial = ShadowMaterial; if (!(shadowMaterial == null)) { Skyfaller.DrawDropSpotShadow(base.DrawPos, Rotation, shadowMaterial, def.skyfaller.shadowSize, ticksToImpact); } //DropPodAnimationUtility.DrawDropSpotShadow(this, this.ticksToImpact); } private void Impact() { Utility.DebugReport("Impacted Called"); for (var i = 0; i < 6; i++) { var loc = Position.ToVector3Shifted() + Gen.RandomHorizontalVector(1f); MoteMaker.ThrowDustPuff(loc, Map, 1.2f); } MoteMaker.ThrowLightningGlow(Position.ToVector3Shifted(), Map, 2f); var pawnFlyerLanded = (PawnFlyersLanded) ThingMaker.MakeThing(PawnFlyerDef.landedDef); pawnFlyerLanded.pawnFlyer = pawnFlyer; pawnFlyerLanded.Contents = contents; if (!pawnFlyerLanded.Contents.innerContainer.Contains(pawnFlyer)) { pawnFlyerLanded.Contents.innerContainer.TryAdd(pawnFlyer); } GenSpawn.Spawn(pawnFlyerLanded, Position, Map, Rotation); var roof = Position.GetRoof(Map); if (roof != null) { if (!roof.soundPunchThrough.NullOrUndefined()) { roof.soundPunchThrough.PlayOneShot(new TargetInfo(Position, Map)); } if (roof.filthLeaving != null) { for (var j = 0; j < 3; j++) { FilthMaker.TryMakeFilth(Position, Map, roof.filthLeaving); } } } Destroy(); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Need_CultMindedness.cs using System.Collections.Generic; using Cthulhu; using RimWorld; using UnityEngine; using Verse; namespace CultOfCthulhu { public class Need_CultMindedness : Need { //public static ThingDef ColanderThingDef; public const float BaseGainPerTickRate = 150f; public const float BaseFallPerTick = 1E-05f; public const float ThreshVeryLow = CultLevel.PureAntiCultist; public const float ThreshLow = CultLevel.AntiCultist; public const float ThreshSatisfied = CultLevel.Middling; public const float ThreshHigh = CultLevel.Cultist; public const float ThreshVeryHigh = CultLevel.PureCultist; private readonly WorldComponent_GlobalCultTracker globalCultTracker = Find.World.GetComponent<WorldComponent_GlobalCultTracker>(); private bool baseSet; private int lastGainTick; public int ticksUntilBaseSet = 500; public Need_CultMindedness(Pawn pawn) : base(pawn) { lastGainTick = -999; threshPercents = new List<float> { ThreshLow, ThreshHigh }; } public override int GUIChangeArrow => GainingNeed ? 1 : -1; public override float CurInstantLevel => CurLevel; private bool GainingNeed => Find.TickManager.TicksGame < lastGainTick + 10; public override void SetInitialLevel() { CurLevel = ThreshSatisfied; } public void GainNeed(float amount) { amount /= 120f; amount *= 0.01f; amount = Mathf.Min(amount, 1f - CurLevel); curLevelInt += amount; lastGainTick = Find.TickManager.TicksGame; } public override void NeedInterval() { ////Log.Messag("Need Interval"); if (!CultTracker.Get.ExposedToCults) { return; } if (pawn == null) { return; } if (!pawn.IsPrisonerOfColony && !pawn.IsColonist) { return; } if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Talking)) { return; } if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Hearing)) { return; } if (!pawn.health.capacities.CapableOf(PawnCapacityDefOf.Moving)) { return; } if (!baseSet) { if (ticksUntilBaseSet <= 0) { SetBaseLevels(); } ticksUntilBaseSet -= 150; return; } if (CultTracker.Get.PlayerCult != null) { if (CultTracker.Get.PlayerCult.founder == pawn || CultTracker.Get.PlayerCult.leader == pawn) { return; } } curLevelInt -= 0.00005f; if (curLevelInt <= 0) { curLevelInt = 0; } } private void SetBaseLevels() { baseSet = true; var temp = CurLevel; if (pawn == null) { return; } temp += CultUtility.GetBaseCultistModifier(pawn); if (temp > 0.99f) { temp = 0.99f; } if (temp < 0.01f) { temp = 0.01f; } if (pawn?.Faction?.def?.defName == "ROM_TheAgency") { Utility.DebugReport(pawn.Name.ToStringFull + " is a member of the agency. Cult levels set to 1%."); temp = 0.01f; } CurLevel = temp; } public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref baseSet, "baseSet"); Scribe_Values.Look(ref ticksUntilBaseSet, "ticksUntilBaseSet", 1000); } public override string GetTipString() { return base.GetTipString(); } public override void DrawOnGUI(Rect rect, int maxThresholdMarkers = int.MaxValue, float customMargin = -1F, bool drawArrows = true, bool doTooltip = true) { if (!CultTracker.Get.ExposedToCults) { return; } //base.DrawOnGUI(rect, maxThresholdMarkers, customMargin, drawArrows, doTooltip); if (rect.height > 70f) { var num = (rect.height - 70f) / 2f; rect.height = 70f; rect.y += num; } if (Mouse.IsOver(rect)) { Widgets.DrawHighlight(rect); } TooltipHandler.TipRegion(rect, new TipSignal(GetTipString, rect.GetHashCode())); var num2 = 14f; var num3 = num2 + 15f; if (rect.height < 50f) { num2 *= Mathf.InverseLerp(0f, 50f, rect.height); } Text.Font = rect.height <= 55f ? GameFont.Tiny : GameFont.Small; Text.Anchor = TextAnchor.LowerLeft; var rect2 = new Rect(rect.x + num3 + (rect.width * 0.1f), rect.y, rect.width - num3 - (rect.width * 0.1f), rect.height / 2f); Widgets.Label(rect2, LabelCap); Text.Anchor = TextAnchor.UpperLeft; var rect3 = new Rect(rect.x, rect.y + (rect.height / 2f), rect.width, rect.height / 2f); rect3 = new Rect(rect3.x + num3, rect3.y, rect3.width - (num3 * 2f), rect3.height - num2); Widgets.FillableBar(rect3, CurLevelPercentage, Buttons.RedTex); //else Widgets.FillableBar(rect3, this.CurLevelPercentage); //Widgets.FillableBarChangeArrows(rect3, this.GUIChangeArrow); if (threshPercents != null) { foreach (var threshPct in threshPercents) { DrawBarThreshold(rect3, threshPct); } } var curInstantLevelPercentage = CurInstantLevelPercentage; if (curInstantLevelPercentage >= 0f) { DrawBarInstantMarkerAt(rect3, curInstantLevelPercentage); } if (!def.tutorHighlightTag.NullOrEmpty()) { UIHighlighter.HighlightOpportunity(rect, def.tutorHighlightTag); } Text.Font = GameFont.Small; } private void DrawBarThreshold(Rect barRect, float threshPct) { var num = (float) (barRect.width <= 60f ? 1 : 2); var position = new Rect(barRect.x + (barRect.width * threshPct) - (num - 1f), barRect.y + (barRect.height / 2f), num, barRect.height / 2f); Texture2D image; if (threshPct < CurLevelPercentage) { image = BaseContent.BlackTex; GUI.color = new Color(1f, 1f, 1f, 0.9f); } else { image = BaseContent.GreyTex; GUI.color = new Color(1f, 1f, 1f, 0.5f); } GUI.DrawTexture(position, image); GUI.color = Color.white; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Nyarlathotep/SpellWorker_StarryWisdom.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System; using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_StarryWisdom : SpellWorker { public override bool CanSummonNow(Map map) { try { if (TempExecutioner(map) == null) { Messages.Message("Null executioner.", MessageTypeDefOf.RejectInput); return false; } if (TempExecutioner(map).story.traits.HasTrait(TraitDefOf.Psychopath) && TempExecutioner(map).story.traits.HasTrait(TraitDefOf.Cannibal)) { Messages.Message("The executioner already has both psychopath and cannibal traits.", MessageTypeDefOf.RejectInput); return false; } } catch (Exception e) { Utility.DebugReport(e.ToString()); } return true; } protected override bool TryExecuteWorker(IncidentParms parms) { if (!(parms.target is Map map)) { return false; } var p = map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar.SacrificeData.Executioner; TraitDef traitToAdd = null; if (!p.story.traits.HasTrait(TraitDefOf.Cannibal)) { traitToAdd = TraitDefOf.Cannibal; } if (!p.story.traits.HasTrait(TraitDefOf.Psychopath)) { traitToAdd = TraitDefOf.Psychopath; } p.story.traits.GainTrait(new Trait(traitToAdd)); //if (p.story.traits.allTraits.Count < 3) p.story.traits.GainTrait(new Trait(traitToAdd)); //else //{ // foreach (Trait t in p.story.traits.allTraits) // { // if(t.def != TraitDefOf.Cannibal && t.def != TraitDefOf.Psychopath) // { // p.story.traits.allTraits.Remove(t); // break; //Remove 1 trait and get out // } // } // p.story.traits.GainTrait(new Trait(traitToAdd)); //} map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = p.Position; Utility.ApplyTaleDef("Cults_SpellStarryWisdom", p); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/SanityLoss/Need_Sanity.cs using RimWorld; using UnityEngine; namespace CultOfCthulhu { // <summary> // Sanity meter /* If individuals experience strange circumstances, they will lose sanity. This insanity can spread like a virus in colonies without good social networks, outlets for expression, or anti-psychotics, as rejection to express onesself will further increase sanity loss. When sanity loss reaches its lowest threshold, the character is permanently marked by madness and receives an insanity trait. Changed forever, when other colonists observe this individual marked with insanity, they too will be affected with sanity loss -- and so begins the spiral into madness.*/ // </summary> public class Need_Sanity : Need { public float InsanityTraitTreshold => 0.15f; //Sanity is static. public override int GUIChangeArrow { get; } = 0; //Sanity has no interval of change. public override void NeedInterval() { } //Characters start fully sane. public override void SetInitialLevel() { CurLevelPercentage = 1.0f; } //Social interactions / Strange circumstances use this method to adjust sanity. public void AdjustSanity(float amt) { CurLevelPercentage = Mathf.Clamp01(CurLevelPercentage + amt); } } }<file_sep>/Source/CultOfCthulhu/UI/ITab_AltarWorshipCardUtility.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Text; using CallOfCthulhu; using HarmonyLib; using RimWorld; using UnityEngine; using Verse; using Verse.Sound; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { [StaticConstructorOnStartup] public class ITab_AltarWorshipCardUtility { public static Vector2 TempleCardSize = new Vector2(600f, 500f); public static void DrawTempleCard(Rect rect, Building_SacrificialAltar altar) { GUI.BeginGroup(rect); if (CultTracker.Get.PlayerCult != null) { var cultLabelWidth = Text.CalcSize(CultTracker.Get.PlayerCult.name).x + 15; //Headings _ = new Rect(rect); var rect1 = rect.ContractedBy(14f); rect1.height = 30f; //Unnamed Temple Text.Font = GameFont.Medium; Widgets.Label(rect1, altar.RoomName); Text.Font = GameFont.Small; //Rename Icon ITab_AltarCardUtility.DrawRename(altar); var rect2 = new Rect(rect1) { yMin = rect1.yMax + 10, height = 25f, width = cultLabelWidth + 5 }; //Esoteric Order of Dagon Widgets.Label(rect2, CultTracker.Get.PlayerCult.name); if (Mouse.IsOver(rect2)) { Widgets.DrawHighlight(rect2); } if (Mouse.IsOver(rect2) && Event.current.type == EventType.MouseDown) { Find.WindowStack.Add(new Dialog_RenameCult(altar.Map)); } Widgets.DrawLineHorizontal(rect2.x - 10, rect2.yMax, rect.width - 15f); //--------------------------------------------------------------------- var rectMain = new Rect(0 + 15f, 0 + 30f, TempleCardSize.x, ITab_AltarSacrificesCardUtility.ButtonSize * 1.15f); //Deity -> Cthulhu var rect4 = rectMain; rect4.yMin = rectMain.yMax + 5f; rect4.y = rectMain.yMax + 20f; rect4.x += 5f; rect4.width = ITab_AltarSacrificesCardUtility.ColumnSize; rect4.height = ITab_AltarSacrificesCardUtility.ButtonSize; Widgets.Label(rect4, "Deity".Translate() + ": "); rect4.xMin = rect4.center.x; var label4 = DeityLabel(altar); if (Widgets.ButtonText(rect4, label4, true, false)) { OpenDeitySelectMenu(altar); } TooltipHandler.TipRegion(rect4, "DeityDesc".Translate()); //Cthulhu - He who waits dreaming. ITab_AltarCardUtility.DrawDeity(altar.tempCurrentWorshipDeity, rect4, null, -30f); //Preacher var rect5 = rect4; rect5.y += ITab_AltarSacrificesCardUtility.ButtonSize + 15f; //rect5.y = rect4.yMax + 30f; rect5.x -= rect4.x - 5; rect5.x += 15f; rect5.width = ITab_AltarSacrificesCardUtility.ColumnSize; Widgets.Label(rect5, "Preacher".Translate() + ": "); rect5.xMin = rect5.center.x; var label2 = PreacherLabel(altar); if (Widgets.ButtonText(rect5, label2, true, false)) { OpenPreacherSelectMenu(altar); } TooltipHandler.TipRegion(rect5, "PreacherDesc".Translate()); var rect6 = rect5; rect6.y += ITab_AltarSacrificesCardUtility.ButtonSize + ITab_AltarSacrificesCardUtility.SpacingOffset; rect6.height = ITab_AltarSacrificesCardUtility.ButtonSize * 2; rect6.width = ITab_AltarSacrificesCardUtility.ColumnSize; rect6.x -= rect5.x - 5; rect6.x += 15f; if (altar.tempCurrentWorshipDeity != null) { Widgets.Label(rect6.BottomHalf(), "Cults_SeasonDays".Translate()); Text.Font = GameFont.Tiny; //Text.Anchor = TextAnchor.LowerLeft; var num = 15f; var num2 = 270f; var hourWidth = 20.833334f; for (var day = 0; day <= 14; day++) { var rect9 = new Rect(num + 4f, num2 + 0f, hourWidth, 20f); Widgets.Label(rect9, (day + 1).ToString()); var rect10 = new Rect(num, num2 + 20f, hourWidth, 30f); rect10 = rect10.ContractedBy(1f); var texture = TimeAssignmentDefOf.Anything.ColorTexture; switch (altar.seasonSchedule[day]) { case 1: texture = SolidColorMaterials.NewSolidColorTexture(Color.red); break; case 2: texture = SolidColorMaterials.NewSolidColorTexture(Color.blue); break; case 3: texture = SolidColorMaterials.NewSolidColorTexture(Color.magenta); break; } GUI.DrawTexture(rect10, texture); if (Mouse.IsOver(rect10)) { Widgets.DrawBox(rect10, 2); //if (Input.GetMouseButton(0)) if (Widgets.ButtonInvisible(rect10)) { altar.seasonSchedule[day] = (altar.seasonSchedule[day] % 4) + 1; SoundDefOf.Designate_DragStandard_Changed.PlayOneShotOnCamera(); //p.timetable.SetAssignment(hour, this.selectedAssignment); } } num += hourWidth; } num2 += 60f; var rect11 = new Rect(15f, num2 + 3, hourWidth / 2, hourWidth / 2); rect11 = rect11.ContractedBy(1f); GUI.DrawTexture(rect11, TimeAssignmentDefOf.Anything.ColorTexture); var rect12 = new Rect(15f + hourWidth, num2, 150f, (hourWidth / 2) + 6); Widgets.Label(rect12, "NoSermonLabel".Translate()); var rect13 = new Rect(15f + 170f, num2 + 3, hourWidth / 2, hourWidth / 2); rect13 = rect13.ContractedBy(1f); GUI.DrawTexture(rect13, SolidColorMaterials.NewSolidColorTexture(Color.magenta)); var rect14 = new Rect(15f + hourWidth + 170f, num2, 150f, (hourWidth / 2) + 6); Widgets.Label(rect14, "BothSermonLabel".Translate()); num2 += 30f; var rect15 = new Rect(15f, num2 + 3, hourWidth / 2, hourWidth / 2); rect15 = rect15.ContractedBy(1f); GUI.DrawTexture(rect15, SolidColorMaterials.NewSolidColorTexture(Color.red)); var rect16 = new Rect(15f + hourWidth, num2, 150f, (hourWidth / 2) + 6); Widgets.Label(rect16, "MorningSermonLabel".Translate()); var rect17 = new Rect(15f + 170f, num2 + 3, hourWidth / 2, hourWidth / 2); rect17 = rect17.ContractedBy(1f); GUI.DrawTexture(rect17, SolidColorMaterials.NewSolidColorTexture(Color.blue)); var rect18 = new Rect(15f + hourWidth + 170f, num2, 150f, (hourWidth / 2) + 6); Widgets.Label(rect18, "EveningSermonLabel".Translate()); num2 += 35f; var rect19 = new Rect(15f, num2, 150f, (hourWidth / 2) + 6); Widgets.Label(rect19, "Cults_SermonStartLabel".Translate()); var dist = 5f; var button3 = new Rect(rect6.x + dist, rect6.y + 215f, 140f, 30f); var morningHour = altar.morningHour + ":00h"; if (Widgets.ButtonText(button3, "Cults_MorningSermonStart".Translate() + morningHour, true, false)) { listHours(altar, true); } var button4 = new Rect(rect6.x + dist + 150f, rect6.y + 215f, 140f, 30f); var eveningHour = altar.eveningHour + ":00h"; if (Widgets.ButtonText(button4, "Cults_EveningSermonStart".Translate() + eveningHour, true, false)) { listHours(altar, false); } } // Old code with only morning/evening setting //Widgets.CheckboxLabeled(rect6.BottomHalf(), "MorningSermons".Translate(), ref altar.OptionMorning, disabled); //if (Mouse.IsOver(rect6) && Event.current.type == EventType.MouseDown && !disabled) //{ // altar.TryChangeWorshipValues(Building_SacrificialAltar.ChangeWorshipType.MorningWorship, altar.OptionMorning); //} //Rect rect7 = rect6; //rect7.y += ITab_AltarSacrificesCardUtility.ButtonSize + ITab_AltarSacrificesCardUtility.SpacingOffset; //rect7.height = ITab_AltarSacrificesCardUtility.ButtonSize; //Widgets.CheckboxLabeled(rect7.TopHalf(), "EveningSermons".Translate(), ref altar.OptionEvening, disabled); //if (Mouse.IsOver(rect7) && Event.current.type == EventType.MouseDown && !disabled) //{ // altar.TryChangeWorshipValues(Building_SacrificialAltar.ChangeWorshipType.EveningWorship, altar.OptionEvening); //} //TooltipHandler.TipRegion(rect6, "MorningSermonsDesc".Translate()); //TooltipHandler.TipRegion(rect7, "EveningSermonsDesc".Translate()); } else { var newRect = new Rect(rect); newRect = newRect.ContractedBy(14f); newRect.height = 30f; Text.Font = GameFont.Medium; Widgets.Label(newRect, "Cults_NoPlayerCultAvailable".Translate()); Text.Font = GameFont.Small; } GUI.EndGroup(); } public static void listHours(Building_SacrificialAltar altar, bool morning) { var list = new List<FloatMenuOption>(); var availableHours = new List<int>(new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}); if (!morning) { availableHours = new List<int>(new[] {12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}); } foreach (var i in availableHours) { list.Add(new FloatMenuOption(i + ":00h", delegate { if (morning) { altar.morningHour = i; } else { altar.eveningHour = i; } })); } Find.WindowStack.Add(new FloatMenu(list)); } private static string PreacherLabel(Building_SacrificialAltar altar) { if (altar.tempPreacher != null) { return altar.tempPreacher.Name.ToStringShort; } altar.tempPreacher = CultUtility.DetermineBestPreacher(altar.Map); return altar.tempPreacher == null ? "None" : altar.tempPreacher.Name.ToStringShort; } private static string DeityLabel(Building_SacrificialAltar altar) { return altar.tempCurrentWorshipDeity == null ? "None" : altar.tempCurrentWorshipDeity.LabelCap; } private static string DeityDescription(Building_SacrificialAltar altar) { if (altar.tempCurrentWorshipDeity == null) { return "None"; } var stringBuilder = new StringBuilder(); stringBuilder.Append(altar.tempCurrentWorshipDeity.def.description); return stringBuilder.ToString(); } public static void OpenPreacherSelectMenu(Building_SacrificialAltar altar) { var list = new List<FloatMenuOption> { new FloatMenuOption("(" + "Auto".Translate() + ")", delegate { altar.tempPreacher = CultUtility.DetermineBestPreacher(altar.Map); }) }; foreach (var current in CultTracker.Get.PlayerCult.MembersAt(altar.Map)) { if (!current.health.capacities.CapableOf(PawnCapacityDefOf.Talking) || !current.health.capacities.CapableOf(PawnCapacityDefOf.Moving)) { continue; } var localCol = current; void Action() { //Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; altar.tempPreacher = localCol; } list.Add(new FloatMenuOption(localCol.LabelShort, Action)); } Find.WindowStack.Add(new FloatMenu(list)); } public static void OpenDeitySelectMenu(Building_SacrificialAltar altar) { var list = new List<FloatMenuOption> { new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate { //Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; altar.tempCurrentWorshipDeity = null; }) }; foreach (var current in DeityTracker.Get.DeityCache.Keys) { if (!current.discovered) { continue; } var localDeity = current; void Action() { //Map.GetComponent<MapComponent_SacrificeTracker>().lastUsedAltar = altar; altar.tempCurrentWorshipDeity = localDeity; //altar.tempCurrentSpell = null; } bool extraPartOnGUI(Rect rect) { return DeityInfoCardButton(rect.x + 5f, rect.y + ((rect.height - 24f) / 2f), current); } list.Add(new FloatMenuOption(localDeity.LabelCap, Action, MenuOptionPriority.Default, null, null, 29f, extraPartOnGUI)); } Find.WindowStack.Add(new FloatMenu(list)); } public static bool DeityInfoCardButton(float x, float y, CosmicEntity entity) { bool result; if ((bool) AccessTools.Method(typeof(Widgets), "InfoCardButtonWorker").Invoke(null, new object[] {x, y})) { Find.WindowStack.Add(new Dialog_CosmicEntityInfoBox(entity)); result = true; } else { result = false; } return result; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Worship/Building_SacrificialAltar_Worship.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using Cthulhu; using RimWorld; using RimWorld.Planet; using Verse; using Verse.AI; //using System.Diagnostics; //using System.Linq; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI //using Verse.AI.Group; //using Verse.Sound; // Needed when you do something with Sound //using Verse.Noise; // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') //using RimWorld.Planet; // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public partial class Building_SacrificialAltar : Building, IBillGiver { public enum ChangeWorshipType { MorningWorship, EveningWorship } public bool UsableForBillsAfterFueling() { return CurrentlyUsableForBills(); } public void TryChangeWorshipValues(ChangeWorshipType type, bool value) { Utility.DebugReport("Attempting to change worship values: " + type + " " + value); //Disabling auto-worship is not a hard thing. if (value == false) { if (type == ChangeWorshipType.EveningWorship) { OptionEvening = false; } if (type == ChangeWorshipType.MorningWorship) { OptionMorning = false; } return; } var canChange = true; //Check if another altar exists. foreach (var bld in Map.listerBuildings.allBuildingsColonist) { //Check all other altars if (bld is not Building_SacrificialAltar) { continue; } var altar2 = bld as Building_SacrificialAltar; //You want to enable evening worship here? if (type == ChangeWorshipType.EveningWorship) { if (altar2.OptionEvening) { canChange = false; } } if (type != ChangeWorshipType.MorningWorship) { continue; } if (altar2.OptionMorning) { canChange = false; } } if (!canChange) { return; } if (type == ChangeWorshipType.MorningWorship) { OptionMorning = true; } if (type == ChangeWorshipType.EveningWorship) { OptionEvening = true; } } private void CancelWorship() { var listeners = Map.mapPawns.AllPawnsSpawned.FindAll(x => x.RaceProps.intelligence == Intelligence.Humanlike); var flag = new bool[listeners.Count]; foreach (var pawn in listeners) { if (pawn.Faction != Faction.OfPlayer) { continue; } if (pawn.CurJob.def == CultsDefOf.Cults_HoldWorship || pawn.CurJob.def == CultsDefOf.Cults_AttendWorship || pawn.CurJob.def == CultsDefOf.Cults_ReflectOnWorship) { pawn.jobs.StopAll(); } } ChangeState(State.notinuse); //this.currentState = State.off; Messages.Message("Cults_CancellingSermon".Translate(), MessageTypeDefOf.NegativeEvent); } private void TryTimedWorship() { if (tempCurrentWorshipDeity == null) { Messages.Message("Cults_NoWorshipWithoutDeity".Translate(), MessageTypeDefOf.RejectInput); //CancelWorship(); return; } if (tempPreacher == null) { tempPreacher = CultUtility.DetermineBestPreacher(Map); } if (Utility.IsMorning(Map)) { didMorningRitual = true; } if (Utility.IsEvening(Map)) { didEveningRitual = true; } TryWorship(); } private void TryWorshipForced() { TryWorship(true); } private void TryWorship(bool forced = false) { if (!CanGatherToWorshipNow()) { return; } switch (currentWorshipState) { case WorshipState.finished: case WorshipState.off: if (IsSacrificing()) { string timeOfDay = "Cults_Morning".Translate(); if (Utility.IsEvening(Map)) { timeOfDay = "Cults_Evening".Translate(); } Messages.Message("Cults_MorningEveningSermonInterrupted".Translate(timeOfDay), MessageTypeDefOf.RejectInput); } StartToWorship(forced); return; case WorshipState.started: case WorshipState.gathering: case WorshipState.finishing: Messages.Message("Cults_AlreadyGatheringForASermon".Translate(), TargetInfo.Invalid, MessageTypeDefOf.RejectInput); return; } } private bool CanGatherToWorshipNow() { if (tempPreacher == null) { return RejectMessage("Cults_NoPreacher".Translate()); } if (tempCurrentWorshipDeity == null) { return RejectMessage("Cults_NoCosmicEntity".Translate()); } if (tempPreacher.Drafted) { return RejectMessage("Cults_NoPreacherDrafted".Translate()); } if (tempPreacher.Dead || tempPreacher.Downed) { return RejectMessage("Cults_SelectAblebodiedPreacher".Translate(), tempPreacher); } if (!tempPreacher.CanReserve(this)) { return RejectMessage("Cults_AltarIsReserved".Translate()); } foreach (var thing in Position.GetThingList(Map)) { if (thing is Corpse) { return RejectMessage("Cults_AltarNeedsToBeCleared".Translate()); } } return true; } public void StartToWorship(bool forced = false) { preacher = tempPreacher; currentWorshipDeity = tempCurrentWorshipDeity; if (Destroyed || !Spawned) { CultUtility.AbortCongregation(null, "The altar is unavailable."); return; } if (!Utility.IsActorAvailable(preacher)) { CultUtility.AbortCongregation(this, "The preacher, " + preacher.LabelShort + ", is unavaialable."); preacher = null; return; } var factionBase = (Settlement) Map.info.parent; Messages.Message("WorshipGathering".Translate(factionBase.Label), TargetInfo.Invalid, MessageTypeDefOf.NeutralEvent); ChangeState(State.worshipping, WorshipState.started); //this.currentState = State.started; //Map.GetComponent<MapComponent_SacrificeTracker>().lastResult = CultUtility.SacrificeResult.none; Utility.DebugReport("Force worship called"); var job = new Job(CultsDefOf.Cults_HoldWorship, this) { playerForced = forced }; preacher.jobs.TryTakeOrderedJob(job); //preacher.jobs.EndCurrentJob(JobCondition.InterruptForced); //GetWorshipGroup(this, Map, forced); } public static void GetWorshipGroup(Building_SacrificialAltar altar, IEnumerable<IntVec3> inRangeCells, bool forced = false) { altar.GetWorshipGroup(inRangeCells); } public void GetWorshipGroup(IEnumerable<IntVec3> inRangeCells, bool forced = false) { _ = Faction; _ = this.GetRoom(); if (AvailableWorshippers == null || AvailableWorshippers.Count <= 0) { return; } foreach (var p in AvailableWorshippers) { if (CultUtility.ShouldAttendWorship(p, this)) { CultUtility.GiveAttendWorshipJob(this, p); } } } public static bool ShouldAttendWorship(Pawn p, Pawn preacher) { var num = 100; //Forced for testing purposes if (p.CurJob.def == CultsDefOf.Cults_AttendWorship) { num = 0; } return Rand.RangeInclusive(0, 15) + num >= 20; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Seed/IncidentWorker_CultSeed.cs using RimWorld; using Verse; namespace CultOfCthulhu { internal class IncidentWorker_CultSeed : IncidentWorker { protected override bool CanFireNowSub(IncidentParms parms) { var map = (Map) parms.target; var tracker = GetTracker(map); return tracker.CurrentSeedState <= CultSeedState.NeedSeed; } private MapComponent_LocalCultTracker GetTracker(Map map) { var result = map.GetComponent<MapComponent_LocalCultTracker>(); if (map.GetComponent<MapComponent_LocalCultTracker>() != null) { return result; } result = new MapComponent_LocalCultTracker(map); map.components.Add(result); return result; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Fertility/MapComponent_FertilityMods.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class MapComponent_FertilityMods : MapComponent { public static float fertilityBonus = 1.0f; public static float fertilityMax = 1.75f; public List<Building_TotemFertility> fertilityTotems; public bool listNeedsUpdate; private List<IntVec3> tempList; public MapComponent_FertilityMods(Map map) : base(map) { this.map = map; } public List<Building_TotemFertility> FertilityTotems { get { if (fertilityTotems.NullOrEmpty()) { fertilityTotems = new List<Building_TotemFertility>(); } return fertilityTotems; } set => fertilityTotems = value; } public List<IntVec3> ActiveCells { get { if (!tempList.NullOrEmpty() && !listNeedsUpdate) { return tempList; } listNeedsUpdate = false; tempList = new List<IntVec3>(); foreach (var totem in FertilityTotems) { foreach (var cell in totem.GrowableCells) { tempList.Add(cell); } } return tempList; } } public MapComponent_FertilityMods Get { get { var MapComponent_FertilityMods = map.components.OfType<MapComponent_FertilityMods>().FirstOrDefault(); if (MapComponent_FertilityMods != null) { return MapComponent_FertilityMods; } MapComponent_FertilityMods = new MapComponent_FertilityMods(map); map.components.Add(MapComponent_FertilityMods); return MapComponent_FertilityMods; } } public void FertilizeCells(List<IntVec3> GrowableCells) { listNeedsUpdate = true; if (GrowableCells == null) { Log.Error("Missing Growable Cells List"); } } public void UnfertilizeCells(List<IntVec3> GrowableCells) { listNeedsUpdate = true; var cells = GrowableCells.ToList(); GrowableCells.RemoveAll(x => cells.Contains(x)); listNeedsUpdate = true; } //public static void CopyTerrain(TerrainDef oldTerrain, TerrainDef newTerrain) //{ // //Copy BuildableDef parts // StringBuilder s = new StringBuilder(); // s.Append("Copy BuildableDef parts"); // s.AppendLine(); // newTerrain.passability = oldTerrain.passability; // s.Append("CostList"); // s.AppendLine(); // if (oldTerrain.costList != null) // { // newTerrain.costList = new List<ThingCountClass>(); // foreach (ThingCountClass count in oldTerrain.costList) // { // newTerrain.costList.Add(count); // } // } // newTerrain.costStuffCount = oldTerrain.costStuffCount; // s.Append("StuffCategories"); // s.AppendLine(); // if (oldTerrain.stuffCategories != null) // { // newTerrain.stuffCategories = new List<StuffCategoryDef>(); // foreach (StuffCategoryDef stuff in oldTerrain.stuffCategories) // { // newTerrain.stuffCategories.Add(stuff); // } // } // s.Append("BuildingPrerequisites"); // s.AppendLine(); // if (oldTerrain.buildingPrerequisites != null) // { // newTerrain.buildingPrerequisites = new List<ThingDef>(); // foreach (ThingDef def in oldTerrain.buildingPrerequisites) // { // newTerrain.buildingPrerequisites.Add(def); // } // } // s.Append("ResearchPrerequisities"); // s.AppendLine(); // if (oldTerrain.researchPrerequisites != null) // { // newTerrain.researchPrerequisites = new List<ResearchProjectDef>(); // foreach (ResearchProjectDef def in oldTerrain.researchPrerequisites) // { // newTerrain.researchPrerequisites.Add(def); // } // } // newTerrain.placingDraggableDimensions = oldTerrain.placingDraggableDimensions; // newTerrain.repairEffect = oldTerrain.repairEffect; // newTerrain.defaultPlacingRot = oldTerrain.defaultPlacingRot; // newTerrain.blueprintDef = oldTerrain.blueprintDef; // newTerrain.installBlueprintDef = oldTerrain.installBlueprintDef; // newTerrain.frameDef = oldTerrain.frameDef; // newTerrain.uiIconPath = oldTerrain.uiIconPath; // newTerrain.altitudeLayer = oldTerrain.altitudeLayer; // newTerrain.uiIcon = oldTerrain.uiIcon; // newTerrain.graphic = oldTerrain.graphic; // newTerrain.menuHidden = true; // newTerrain.specialDisplayRadius = oldTerrain.specialDisplayRadius; // s.Append("Placeworkers"); // s.AppendLine(); // if (oldTerrain.placeWorkers != null) // { // newTerrain.placeWorkers = new List<Type>(); // foreach (Type worker in oldTerrain.placeWorkers) // { // newTerrain.placeWorkers.Add(worker); // } // } // newTerrain.designationHotKey = oldTerrain.designationHotKey; // //Floor Base-like // newTerrain.layerable = oldTerrain.layerable; // s.Append("Affordances"); // s.AppendLine(); // if (oldTerrain.affordances != null) // { // newTerrain.affordances = new List<TerrainAffordance>(); // foreach (TerrainAffordance affordance in oldTerrain.affordances) // { // newTerrain.affordances.Add(affordance); // } // } // s.Append("StatBases"); // s.AppendLine(); // if (oldTerrain.statBases != null) // { // newTerrain.statBases = new List<StatModifier>(); // foreach (StatModifier modifier in oldTerrain.statBases) // { // newTerrain.statBases.Add(modifier); // } // } // newTerrain.designationCategory = oldTerrain.designationCategory; // newTerrain.fertility = oldTerrain.fertility; // newTerrain.constructEffect = oldTerrain.constructEffect; // newTerrain.acceptTerrainSourceFilth = oldTerrain.acceptTerrainSourceFilth; // newTerrain.terrainAffordanceNeeded = oldTerrain.terrainAffordanceNeeded; // //Floor defs // newTerrain.defName = oldTerrain.defName; // newTerrain.label = oldTerrain.label; // newTerrain.description = oldTerrain.description; // newTerrain.color = oldTerrain.color; // newTerrain.texturePath = oldTerrain.texturePath; // newTerrain.edgeType = oldTerrain.edgeType; // newTerrain.renderPrecedence = oldTerrain.renderPrecedence; // newTerrain.pathCost = oldTerrain.pathCost; // newTerrain.statBases = oldTerrain.statBases; // newTerrain.scatterType = oldTerrain.scatterType; // newTerrain.takeFootprints = oldTerrain.takeFootprints; // newTerrain.driesTo = oldTerrain.driesTo; // Cthulhu.Utility.DebugReport(s.ToString()); //} } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Seed/MapComponent_LocalCultTracker_Seed.cs using System.Linq; using RimWorld; using Verse; namespace CultOfCthulhu { internal partial class MapComponent_LocalCultTracker : MapComponent { private void CultSeedCheck() { //Check for god-mode spawned things. if (CurrentSeedState < CultSeedState.FinishedWriting) { if (CultUtility.AreOccultGrimoiresAvailable(map)) { CurrentSeedState = CultSeedState.FinishedWriting; } } if (CurrentSeedState < CultSeedState.NeedTable) { if (map.listerBuildings.allBuildingsColonist.FirstOrDefault(bld => bld is Building_SacrificialAltar || bld is Building_ForbiddenReserachCenter) != null) { CurrentSeedState = CultSeedState.NeedTable; } } switch (CurrentSeedState) { case CultSeedState.NeedSeed: NeedSeedCountDown(); return; case CultSeedState.FinishedSeeing: return; case CultSeedState.NeedSeeing: CanDoJob(CultsDefOf.Cults_Investigate, CurrentSeedPawn, CurrentSeedTarget, true); return; case CultSeedState.NeedWriting: CanDoJob(CultsDefOf.Cults_WriteTheBook, CurrentSeedPawn); return; case CultSeedState.FinishedWriting: case CultSeedState.NeedTable: return; } } private void NeedSeedCountDown() { if (ticksToSpawnCultSeed > 0) { ticksToSpawnCultSeed -= 1; } else { if (GenLocalDate.HourInteger(map) > 21 || GenLocalDate.HourInteger(map) < 6) { ticksToSpawnCultSeed = OneDay + Rand.Range(-20000, +20000); var seed = seedIncidents.RandomElement(); var parms = StorytellerUtility.DefaultParmsNow(seed.category, map); seed.Worker.TryExecute(parms); return; } ticksToSpawnCultSeed += GenDate.TicksPerHour; } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Sacrifice/JobDriver_GiveOffering.cs using System; using System.Collections.Generic; using System.Diagnostics; using RimWorld; using UnityEngine; using Verse; using Verse.AI; namespace CultOfCthulhu { public class JobDriver_GiveOffering : JobDriver { public const TargetIndex BillGiverInd = TargetIndex.A; public const TargetIndex IngredientInd = TargetIndex.B; public const TargetIndex IngredientPlaceCellInd = TargetIndex.C; public int billStartTick; public List<Thing> offerings; public int ticksSpentDoingRecipeWork; public float workLeft; public IBillGiver BillGiver => !(pawn.jobs.curJob.GetTarget(TargetIndex.A).Thing is IBillGiver billGiver) ? throw new InvalidOperationException("DoBill on non-Billgiver.") : billGiver; public Building_SacrificialAltar DropAltar => !(pawn.jobs.curJob.GetTarget(TargetIndex.A).Thing is Building_SacrificialAltar result) ? throw new InvalidOperationException("Altar is missing.") : result; public override bool TryMakePreToilReservations(bool errorOnFailed) { return true; } public override string GetReport() { return pawn.jobs.curJob.RecipeDef != null ? ReportStringProcessed(pawn.jobs.curJob.RecipeDef.jobString) : base.GetReport(); } public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref workLeft, "workLeft"); Scribe_Collections.Look(ref offerings, "offerings", LookMode.Reference); Scribe_Values.Look(ref billStartTick, "billStartTick"); Scribe_Values.Look(ref ticksSpentDoingRecipeWork, "ticksSpentDoingRecipeWork"); } [DebuggerHidden] protected override IEnumerable<Toil> MakeNewToils() { AddEndCondition(delegate { var thing = GetActor().jobs.curJob.GetTarget(TargetIndex.A).Thing; return thing is Building && !thing.Spawned ? JobCondition.Incompletable : JobCondition.Ongoing; }); this.FailOnBurningImmobile(TargetIndex.A); //this.FailOn(delegate //{ // IBillGiver billGiver = this.pawn.jobs.curJob.GetTarget(TargetIndex.A).Thing as IBillGiver; // if (billGiver != null) // { // if (this.pawn.jobs.curJob.bill.DeletedOrDereferenced) // { // return true; // } // if (!billGiver.CurrentlyUsable()) // { // return true; // } // } // return false; //}); //yield return ToilLogMessage("Pass 0 - Start"); var toil = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell); yield return new Toil {initAction = delegate { offerings = new List<Thing>(); }}; yield return Toils_Reserve.Reserve(TargetIndex.A); //yield return new Toil {initAction = delegate {Log.Message("Pass 2");}}; yield return Toils_Reserve.ReserveQueue(TargetIndex.B); //yield return new Toil {initAction = delegate {Log.Message("Pass 3");}}; yield return new Toil { initAction = delegate { if (job.targetQueueB == null || job.targetQueueB.Count != 1) { return; } if (job.targetQueueB[0].Thing is UnfinishedThing unfinishedThing) { unfinishedThing.BoundBill = (Bill_ProductionWithUft) job.bill; } } }; //yield return new Toil {initAction = delegate {Log.Message("Pass 4");}}; yield return Toils_Jump.JumpIf(toil, () => job.GetTargetQueue(TargetIndex.B).NullOrEmpty()); //yield return new Toil {initAction = delegate {Log.Message("Pass 5");}}; var toil2 = Toils_JobTransforms.ExtractNextTargetFromQueue(TargetIndex.B, false); yield return toil2; //yield return new Toil {initAction = delegate {Log.Message("Pass 6");}}; var toil3 = Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch) .FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnSomeonePhysicallyInteracting(TargetIndex.B); yield return toil3; //yield return new Toil {initAction = delegate {Log.Message("Pass 7");}}; yield return Toils_Haul.StartCarryThing(TargetIndex.B, true); //yield return new Toil {initAction = delegate {Log.Message("Pass 8");}}; yield return JumpToCollectNextIntoHandsForBill(toil3, TargetIndex.B); //yield return new Toil {initAction = delegate {Log.Message("Pass 9");}}; yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.ClosestTouch) .FailOnDestroyedOrNull(TargetIndex.B); //yield return new Toil {initAction = delegate {Log.Message("Pass 10");}}; var toil4 = Toils_JobTransforms.SetTargetToIngredientPlaceCell(TargetIndex.A, TargetIndex.B, TargetIndex.C); yield return toil4; //yield return new Toil {initAction = delegate {Log.Message("Pass 11");}}; yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.C, toil4, false); //yield return new Toil {initAction = delegate {Log.Message("Pass 12");}}; yield return new Toil { initAction = delegate { if (offerings.Count > 0) { offerings.RemoveAll(x => x.DestroyedOrNull()); } offerings.Add(TargetB.Thing); } }; yield return Toils_Jump.JumpIfHaveTargetInQueue(TargetIndex.B, toil2); yield return toil; //yield return ToilLogMessage("Pass 13"); var chantingTime = new Toil { defaultCompleteMode = ToilCompleteMode.Delay, defaultDuration = CultUtility.ritualDuration }; chantingTime.WithProgressBarToilDelay(TargetIndex.A); chantingTime.PlaySustainerOrSound(CultsDefOf.RitualChanting); var deitySymbol = ((CosmicEntityDef) DropAltar.currentOfferingDeity.def).Symbol; chantingTime.initAction = delegate { if (deitySymbol != null) { MoteMaker.MakeInteractionBubble(pawn, null, ThingDefOf.Mote_Speech, deitySymbol); } }; yield return chantingTime; //yield return ToilLogMessage("Pass 14"); //Toil 8: Execution of Prisoner yield return new Toil { initAction = delegate { CultUtility.OfferingComplete(pawn, DropAltar, DropAltar.currentOfferingDeity, offerings); }, defaultCompleteMode = ToilCompleteMode.Instant }; //yield return ToilLogMessage("Pass 15 - Final"); //this.AddEndCondition(delegate //{ // Thing thing = this.GetActor().jobs.curJob.GetTarget(TargetIndex.A).Thing; // if (thing is Building && !thing.Spawned) // { // return JobCondition.Incompletable; // } // return JobCondition.Ongoing; //}); //this.FailOnBurningImmobile(TargetIndex.A); //Toil toil = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell); //yield return Toils_Reserve.Reserve(TargetIndex.A, 1); //yield return Toils_Reserve.ReserveQueue(TargetIndex.B, 1); //yield return new Toil //{ // initAction = delegate // { // if (this.job.targetQueueB != null && this.job.targetQueueB.Count == 1) // { // UnfinishedThing unfinishedThing = this.job.targetQueueB[0].Thing as UnfinishedThing; // if (unfinishedThing != null) // { // unfinishedThing.BoundBill = (Bill_ProductionWithUft)this.job.bill; // } // } // } //}; //yield return Toils_Jump.JumpIf(toil, () => this.job.GetTargetQueue(TargetIndex.B).NullOrEmpty<LocalTargetInfo>()); //Toil toil2 = Toils_JobTransforms.ExtractNextTargetFromQueue(TargetIndex.B); //yield return toil2; //Toil toil3 = Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch).FailOnDespawnedNullOrForbidden(TargetIndex.B).FailOnSomeonePhysicallyInteracting(TargetIndex.B); //yield return toil3; //yield return Toils_Haul.StartCarryThing(TargetIndex.B); //yield return JumpToCollectNextIntoHandsForBill(toil3, TargetIndex.B); //yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell).FailOnDestroyedOrNull(TargetIndex.B); //Toil toil4 = Toils_JobTransforms.SetTargetToIngredientPlaceCell(TargetIndex.A, TargetIndex.B, TargetIndex.C); //yield return toil4; //yield return Toils_Haul.PlaceHauledThingInCell(TargetIndex.C, toil4, false); //yield return Toils_Jump.JumpIfHaveTargetInQueue(TargetIndex.B, toil2); //yield return toil; //Toil chantingTime = new Toil(); //chantingTime.defaultCompleteMode = ToilCompleteMode.Delay; //CultUtility.remainingDuration = CultUtility.ritualDuration; //chantingTime.defaultDuration = CultUtility.remainingDuration - 360; //chantingTime.WithProgressBarToilDelay(TargetIndex.A, false, -0.5f); //chantingTime.PlaySustainerOrSound(CultDefOfs.RitualChanting); //Texture2D deitySymbol = ((CosmicEntityDef)DropAltar.currentOfferingDeity.def).Symbol; //chantingTime.initAction = delegate //{ // if (deitySymbol != null) // MoteMaker.MakeInteractionBubble(this.pawn, null, ThingDefOf.Mote_Speech, deitySymbol); //}; //yield return chantingTime; ////Toil 8: Execution of Prisoner //yield return new Toil //{ // initAction = delegate // { // CultUtility.OfferingComplete(this.pawn, DropAltar, DropAltar.currentOfferingDeity); // }, // defaultCompleteMode = ToilCompleteMode.Instant //}; ////this.AddFinishAction(() => ////{ //// if (this.pawn.CurJob.targetQueueB.Count == 0 && //// DropAltar.currentOfferingState == Building_SacrificialAltar.OfferingState.started) //// //When the ritual is finished -- then let's give the thoughts //// CultUtility.OfferingReady(this.pawn, DropAltar); ////}); } private static Toil ToilLogMessage(string message) { return new Toil {initAction = delegate { Log.Message(message); }}; } private static Toil JumpToCollectNextIntoHandsForBill(Toil gotoGetTargetToil, TargetIndex ind) { var toil = new Toil(); toil.initAction = delegate { var actor = toil.actor; if (actor.carryTracker.CarriedThing == null) { Log.Error("JumpToAlsoCollectTargetInQueue run on " + actor + " who is not carrying something."); return; } if (actor.carryTracker.Full) { return; } var curJob = actor.jobs.curJob; var targetQueue = curJob.GetTargetQueue(ind); if (targetQueue.NullOrEmpty()) { return; } for (var i = 0; i < targetQueue.Count; i++) { if (!GenAI.CanUseItemForWork(actor, targetQueue[i].Thing)) { continue; } if (!targetQueue[i].Thing.CanStackWith(actor.carryTracker.CarriedThing)) { continue; } if (!((actor.Position - targetQueue[i].Thing.Position).LengthHorizontalSquared <= 64f)) { continue; } var num = actor.carryTracker.CarriedThing?.stackCount ?? 0; var num2 = curJob.countQueue[i]; num2 = Mathf.Min(num2, targetQueue[i].Thing.def.stackLimit - num); num2 = Mathf.Min(num2, actor.carryTracker.AvailableStackSpace(targetQueue[i].Thing.def)); if (num2 <= 0) { continue; } curJob.count = num2; curJob.SetTarget(ind, targetQueue[i].Thing); List<int> countQueue; var expr_1B2 = countQueue = curJob.countQueue; int num3; var expr_1B6 = num3 = i; num3 = countQueue[num3]; expr_1B2[expr_1B6] = num3 - num2; if (curJob.countQueue[i] == 0) { curJob.countQueue.RemoveAt(i); targetQueue.RemoveAt(i); } actor.jobs.curDriver.JumpToToil(gotoGetTargetToil); return; } }; return toil; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/CosmicEntities/CosmicEntityDef.cs using System.Collections.Generic; using RimWorld; using UnityEngine; using Verse; namespace CultOfCthulhu { public class CosmicEntityDef : ThingDef { public readonly string descriptionLong = string.Empty; public readonly string domains = string.Empty; public readonly List<ThingDef> favoredApparel = new List<ThingDef>(); public readonly bool favorsOutdoorWorship = false; public readonly string portrait = string.Empty; public readonly string symbol = string.Empty; public readonly List<IncidentDef> tier1SpellDefs = new List<IncidentDef>(); public readonly List<IncidentDef> tier2SpellDefs = new List<IncidentDef>(); public readonly List<IncidentDef> tier3SpellDefs = new List<IncidentDef>(); public readonly string titles = string.Empty; private readonly string version = "0"; public List<FavoredThing> displeasingOfferings = new List<FavoredThing>(); public List<FavoredThing> favoredWorshipperRaces = new List<FavoredThing>(); public IncidentDef finalSpellDef; public List<FavoredThing> hereticWorshipperRaces = new List<FavoredThing>(); public List<FavoredThing> pleasingOfferings = new List<FavoredThing>(); [Unsaved] private Texture2D symbolTex; public Texture2D Symbol { get { if (symbolTex == null) { symbolTex = ContentFinder<Texture2D>.Get(symbol); } return symbolTex; } } public int Version => int.TryParse(version, out var x) ? x : 0; } }<file_sep>/Source/CultOfCthulhu/NewSystems/Sacrifice/JobDriver_ReflectOnResult.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Diagnostics; using Verse.AI; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { internal class JobDriver_ReflectOnResult : JobDriver { protected Building_SacrificialAltar altar => (Building_SacrificialAltar) job.GetTarget(TargetIndex.A).Thing; public override bool TryMakePreToilReservations(bool errorOnFailed) { return true; } [DebuggerHidden] protected override IEnumerable<Toil> MakeNewToils() { //Toil 0 -- Go here first to reflect. if (altar?.SacrificeData?.Executioner != null) { if (pawn == altar.SacrificeData.Executioner) { yield return Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell); } } //Toil 9 Celebrate or recoil yield return new Toil { initAction = delegate { if (Map.GetComponent<MapComponent_SacrificeTracker>().lastResult == CultUtility.SacrificeResult.success) { //Do something? Ia Ia! } }, defaultCompleteMode = ToilCompleteMode.Instant }; //Toil 10 Reflect on result var reflectingTime = new Toil { defaultCompleteMode = ToilCompleteMode.Delay, defaultDuration = CultUtility.reflectDuration }; //chantingTime.PlaySustainerOrSound(DefDatabase<SoundDef>.GetNamed("Estate_GramophoneWindup")); yield return reflectingTime; //Toil 11 Reset the altar and clear variables. yield return new Toil { initAction = delegate { if (altar == null) { return; } if (altar.currentSacrificeState == Building_SacrificialAltar.SacrificeState.finished) { return; } altar.ChangeState(Building_SacrificialAltar.State.sacrificing, Building_SacrificialAltar.SacrificeState.finished); Map.GetComponent<MapComponent_SacrificeTracker>().ClearSacrificeVariables(); }, defaultCompleteMode = ToilCompleteMode.Instant }; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/SpellWorker_RatsInTheWalls.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Linq; using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_RatsInTheWalls : SpellWorker { private readonly List<IntVec3> AvailableFloors = new List<IntVec3>(); protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport(" //: " + this.def.defName); return true; } protected override bool TryExecuteWorker(IncidentParms parms) { if (!(parms.target is Map map)) { return false; } var num = 0; var countToSpawn = 10; for (var i = 0; i < countToSpawn; i++) { //Find floors in the home area var intVec = CellFinderLoose.RandomCellWith(c => c.InBounds(map) && c.Standable(map) && !c.InNoBuildEdgeArea(map) && map.terrainGrid.TerrainAt(c).layerable && map.areaManager.Home.ActiveCells.Contains(c) && !c.Fogged(map), map); if (intVec == IntVec3.Invalid) { //Find smoothed floors in the home area intVec = CellFinderLoose.RandomCellWith(c => c.InBounds(map) && c.Standable(map) && !c.InNoBuildEdgeArea(map) && map.terrainGrid.TerrainAt(c).defName .Contains("_Smooth") && map.areaManager.Home.ActiveCells.Contains(c) && !c.Fogged(map), map); if (intVec == IntVec3.Invalid) { //Find floors... anywhere intVec = CellFinderLoose.RandomCellWith(c => c.InBounds(map) && c.Standable(map) && !c.InNoBuildEdgeArea(map) && map.terrainGrid.TerrainAt(c).layerable && !c.Fogged(map), map); if (intVec == IntVec3.Invalid) { //Find the ground near the players then. if (intVec == IntVec3.Invalid) { intVec = CellFinderLoose.RandomCellWith(c => c.InBounds(map) && c.Standable(map) && !c.InNoBuildEdgeArea(map) && map.areaManager.Home.ActiveCells.Contains( c) && !c.Fogged(map), map); if (intVec == IntVec3.Invalid) { Utility.DebugReport("Error: Can't assign cell for Rats in the Walls spell."); continue; } } } } } //Throw some smoke MoteMaker.ThrowDustPuff(intVec, map, 1f); //Break the floor if (intVec.InBounds(map) && map.terrainGrid.TerrainAt(intVec).layerable) { map.terrainGrid.RemoveTopLayer(intVec, false); } //Spawn the rat Utility.SpawnPawnsOfCountAt(CultsDefOf.Rat, intVec, map, Rand.Range(1, 5), null, false, true); num++; } if (num <= 0) { return false; } Find.CameraDriver.shaker.DoShake(1f); Find.LetterStack.ReceiveLetter(def.letterLabel, def.letterText, def.letterDef, new TargetInfo(map.GetComponent<MapComponent_SacrificeTracker>().lastLocation, map)); Messages.Message("Cults_RatsMessage".Translate(), MessageTypeDefOf.NegativeEvent); Utility.ApplyTaleDef("Cults_SpellRatsInTheWalls", map); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Dagon/Building_TreasureChest.cs using System.Collections.Generic; using System.Linq; using RimWorld; using Verse; //using System.Diagnostics; namespace CultOfCthulhu { public class Building_TreasureChest : Building, IOpenable, IThingHolder, IStoreSettingsParent { protected bool contentsKnown; protected ThingOwner innerContainer; protected bool SpawnedStorage; protected StorageSettings storageSettings; public Building_TreasureChest() { innerContainer = new ThingOwner<Thing>(this, false); } public bool HasAnyContents => innerContainer.Count > 0; public Thing ContainedThing => innerContainer.Count != 0 ? innerContainer[0] : null; public bool CanOpen => HasAnyContents; public virtual void Open() { if (!HasAnyContents) { return; } EjectContents(); } public bool StorageTabVisible => false; //public virtual IThingHolder ParentHolder //{ // get // { // return base.ParentHolder; // } //} public StorageSettings GetStoreSettings() { return storageSettings; } public StorageSettings GetParentStoreSettings() { return def.building.fixedStorageSettings; } public ThingOwner GetDirectlyHeldThings() { return innerContainer; } public void GetChildHolders(List<IThingHolder> outChildren) { ThingOwnerUtility.AppendThingHoldersFromThings(outChildren, GetDirectlyHeldThings()); } public override IEnumerable<Gizmo> GetGizmos() { foreach (var g in base.GetGizmos()) { yield return g; } //foreach (Gizmo g2 in StorageSettingsClipboard.CopyPasteGizmosFor(this.storageSettings)) //{ // yield return g2; //} } public override void PostMake() { base.PostMake(); //this.innerContainer = new ThingOwner<Thing>(this, false); storageSettings = new StorageSettings(this); if (def.building.defaultStorageSettings != null) { storageSettings.CopyFrom(def.building.defaultStorageSettings); } if (SpawnedStorage) { return; } SpawnedStorage = true; if (def == CultsDefOf.Cults_TreasureChest) { for (var i = 0; i < 5; i++) { var thing1 = ThingMaker.MakeThing(ThingDefOf.Gold); thing1.stackCount = Rand.Range(20, 40); GetDirectlyHeldThings().TryAdd(thing1); var thing2 = ThingMaker.MakeThing(ThingDefOf.Silver); thing2.stackCount = Rand.Range(40, 60); GetDirectlyHeldThings().TryAdd(thing2); var thing3 = ThingMaker.MakeThing(ThingDef.Named("Jade")); thing3.stackCount = Rand.Range(10, 40); GetDirectlyHeldThings().TryAdd(thing3); } if (Rand.Value > 0.8f) { var thing4 = ThingMaker.MakeThing(ThingDef.Named("SculptureSmall"), ThingDefOf.Gold); thing4.stackCount = 1; GetDirectlyHeldThings().TryAdd(thing4); } } if (def != CultsDefOf.Cults_TreasureChest_Relic) { return; } GetDirectlyHeldThings() .TryAdd(Rand.Range(1, 100) > 50 ? GenerateLegendaryWeapon() : GenerateLegendaryArmor()); } //Selects a random weapon type and improves it to a legendary status public ThingWithComps GenerateLegendaryWeapon() { if (!(from td in DefDatabase<ThingDef>.AllDefs where HandlesWeaponDefs(td) select td).TryRandomElement(out var thingDef)) { return null; } var thingWithComps = (ThingWithComps) ThingMaker.MakeThing(thingDef); var compQuality = thingWithComps.TryGetComp<CompQuality>(); compQuality.SetQuality(QualityCategory.Legendary, ArtGenerationContext.Outsider); return thingWithComps; } //Industrial Level Legendary Weapons public bool HandlesWeaponDefs(ThingDef thingDef) { return thingDef.IsRangedWeapon && thingDef.tradeability != Tradeability.None && thingDef.techLevel <= TechLevel.Industrial; } //Same as weapon generation code public ThingWithComps GenerateLegendaryArmor() { if (!(from td in DefDatabase<ThingDef>.AllDefs where HandlesArmorDefs(td) select td).TryRandomElement(out var thingDef)) { return null; } var thingWithComps = (ThingWithComps) ThingMaker.MakeThing(thingDef); thingWithComps.stackCount = 1; var compQuality = thingWithComps.TryGetComp<CompQuality>(); compQuality.SetQuality(QualityCategory.Legendary, ArtGenerationContext.Outsider); return thingWithComps; } //Industrial Level Legendary Armor private bool HandlesArmorDefs(ThingDef td) { return td == ThingDefOf.Apparel_ShieldBelt || td.tradeability != Tradeability.None && td.techLevel <= TechLevel.Industrial && td.IsApparel && (td.GetStatValueAbstract(StatDefOf.ArmorRating_Blunt) > 0.15f || td.GetStatValueAbstract(StatDefOf.ArmorRating_Sharp) > 0.15f); } public override void TickRare() { base.TickRare(); innerContainer.ThingOwnerTickRare(); } public override void Tick() { base.Tick(); innerContainer.ThingOwnerTick(); } public override void ExposeData() { base.ExposeData(); Scribe_Deep.Look(ref innerContainer, "innerContainer", this); Scribe_Values.Look(ref contentsKnown, "contentsKnown"); Scribe_Deep.Look(ref storageSettings, "storageSettings", this); Scribe_Values.Look(ref SpawnedStorage, "SpawnedStorage"); } public override void SpawnSetup(Map map, bool respawningAfterLoad) { base.SpawnSetup(map, respawningAfterLoad); if (Faction != null && Faction.IsPlayer) { contentsKnown = true; } } public override bool ClaimableBy(Faction fac) { if (!innerContainer.Any) { return base.ClaimableBy(fac); } foreach (var thing in innerContainer) { if (thing.Faction == fac) { return true; } } return false; } public virtual bool Accepts(Thing thing) { return innerContainer.Count < 10 && innerContainer.CanAcceptAnyOf(thing); } public virtual bool TryAcceptThing(Thing thing, bool allowSpecialEffects = true) { if (!Accepts(thing)) { return false; } bool flag; if (thing.holdingOwner != null) { thing.holdingOwner.TryTransferToContainer(thing, innerContainer, thing.stackCount); flag = true; } else { flag = innerContainer.TryAdd(thing); } if (!flag) { return false; } if (thing.Faction != null && thing.Faction.IsPlayer) { contentsKnown = true; } return true; } public override void Destroy(DestroyMode mode = DestroyMode.Vanish) { if (innerContainer.Count > 0 && (mode == DestroyMode.Deconstruct || mode == DestroyMode.KillFinalize)) { if (mode != DestroyMode.Deconstruct) { var list = new List<Pawn>(); foreach (var current in innerContainer) { if (current is Pawn pawn) { list.Add(pawn); } } foreach (var current2 in list) { HealthUtility.DamageUntilDowned(current2); } } EjectContents(); } innerContainer.ClearAndDestroyContents(); base.Destroy(mode); } public virtual void EjectContents() { innerContainer.TryDropAll(InteractionCell, Map, ThingPlaceMode.Near); contentsKnown = true; } public override string GetInspectString() { var text = base.GetInspectString(); string str; if (!contentsKnown) { str = "UnknownLower".Translate(); } else { str = innerContainer.ContentsString; } if (!text.NullOrEmpty()) { text += "\n"; } return text + "CasketContains".Translate() + ": " + str; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/CosmicEntities/CosmicEntity.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class CosmicEntity : Thing { public enum Tier { Zero = 0, One = 1, Two = 2, Three = 3, Final = 4 } private const float MODIFIER_HUMAN = 0.5f; private const float MODIFIER_ANIMAL = 0.2f; private const float DIVIDER_HUMAN = 300f; private const float DIVIDER_FOOD = 700f; public readonly List<ThingDef> favoredApparel = new List<ThingDef>(); private readonly float favorMax = 50f; public bool discovered; private float favor; public IncidentDef finalSpell; private bool hostileToPlayer; private float lastFavor; public List<IncidentDef> tier1Spells; //public IncidentDef tier2Spell; public List<IncidentDef> tier2Spells; //public IncidentDef tier3Spell; public List<IncidentDef> tier3Spells; public CosmicEntity() { } public CosmicEntity(ThingDef newDef) { if (!(newDef is CosmicEntityDef currentDef)) { return; } def = newDef; tier1Spells = currentDef.tier1SpellDefs; tier2Spells = currentDef.tier2SpellDefs; tier3Spells = currentDef.tier3SpellDefs; finalSpell = currentDef.finalSpellDef; favoredApparel = currentDef.favoredApparel; } public float LastFavor => lastFavor; private float favorTier0Max => favorMax * 0.05f; private float favorTier1Max => favorMax * 0.10f; private float favorTier2Max => favorMax * 0.5f; private float favorTier3Max => favorMax * 0.85f; public CosmicEntityDef Def => def as CosmicEntityDef; public override string Label => Def.label; public override string LabelCap => Def.label.CapitalizeFirst(); public string TierString { get { switch (PlayerTier) { case Tier.Zero: return "TierStringZero".Translate(); case Tier.One: return "TierStringOne".Translate(); case Tier.Two: return "TierStringTwo".Translate(); case Tier.Three: return "TierStringThree".Translate(); case Tier.Final: return "TierStringFinal".Translate(); } return ""; } } public Tier PlayerTier { get { if (favor <= favorTier0Max) { return Tier.Zero; } if (favor > favorTier0Max && favor <= favorTier1Max) { return Tier.One; } if (favor > favorTier1Max && favor <= favorTier2Max) { return Tier.Two; } if (favor > favorTier2Max && favor < favorTier3Max) { return Tier.Three; } return favor >= favorTier3Max ? Tier.Final : Tier.Zero; } } public float currentTierMax { get { switch (PlayerTier) { case Tier.Zero: return favorTier0Max; case Tier.One: return favorTier1Max; case Tier.Two: return favorTier2Max; case Tier.Three: return favorTier3Max; case Tier.Final: return favorMax; } return favorMax; } } public float prevTierMax { get { switch (PlayerTier) { case Tier.Zero: return 0; case Tier.One: return favorTier0Max; case Tier.Two: return favorTier1Max; case Tier.Three: return favorTier2Max; case Tier.Final: return favorTier2Max; } return favorMax; } } public int Version { get { if (!(def is CosmicEntityDef currentDef)) { return 0; } var i = currentDef.Version; Utility.DebugReport(Label + " version retrieved " + i); return i; } } public float PlayerFavor => favor; public bool FavorsOutdoorWorship => ((CosmicEntityDef) def).favorsOutdoorWorship; public override void ExposeData() { base.ExposeData(); Scribe_Collections.Look(ref tier1Spells, "tier1spells"); Scribe_Collections.Look(ref tier2Spells, "tier2spells"); Scribe_Collections.Look(ref tier3Spells, "tier3spells"); Scribe_Defs.Look(ref finalSpell, "finalSpell"); Scribe_Values.Look(ref hostileToPlayer, "hostileToPlayer"); Scribe_Values.Look(ref favor, "favor"); Scribe_Values.Look(ref lastFavor, "lastFavor"); Scribe_Values.Look(ref discovered, "discovered"); //Scribe_Deep.Look<KidnappedPawnsTracker>(ref this.kidnapped, "kidnapped", new object[] //{ // this //}); } public bool IsOffering(Thing thingToCheck, Building_SacrificialAltar altarDictionary) { foreach (var dictionary in altarDictionary.determinedOfferings) { if (thingToCheck.def == dictionary.Thing.def) { return true; } } return false; } private void ConsumeOfferings(Thing offering) { var tierModifier = (float) ((int) PlayerTier + 1); var foodModifier = DIVIDER_FOOD; var math = offering.MarketValue * offering.stackCount / (foodModifier * tierModifier); offering.Destroy(); AffectFavor(math); } public void ReceiveOffering(Pawn offerer, Building_SacrificialAltar altar, List<Thing> offerings) { var s = new StringBuilder(); s.Append("Offering Report"); s.AppendLine(); s.Append("==============="); foreach (var offering in offerings) { s.AppendLine(); s.Append(offering.stackCount + " " + offering + ": $" + offering.MarketValue + " each. Total: $" + (offering.MarketValue * offering.stackCount)); ConsumeOfferings(offering); } Utility.DebugReport(s.ToString()); } private float SacrificeBonus(Pawn sacrifice, Map map, bool favorSpell = false, bool starsAreRight = false, bool starsAreWrong = false) { var s = new StringBuilder(); s.Append("Sacrifice Bonus Calculation:"); var result = 0f; if (sacrifice == null) { return result; } if (sacrifice.RaceProps == null) { return result; } var tracker = map.GetComponent<MapComponent_SacrificeTracker>(); if (tracker == null) { return result; } tracker.lastSacrificeName = sacrifice.LabelShort; //Divide by 0 exception if (sacrifice.MarketValue == 0f) { return result; } //Animal Sacrifice Bonuses if (tracker.lastSacrificeType == CultUtility.SacrificeType.animal) { //Default Animal Sacrifice Bonus result += sacrifice.MarketValue * MODIFIER_ANIMAL; // 20% bonus for animal sacrifice //Pet Bonus handling code if (sacrifice.RaceProps.petness > 0f) { result += sacrifice.MarketValue * 3; //Triple the sacrifice value of pets sacrificed s.AppendLine(); s.Append("Subtotal: " + result + " Applied Pet-like Modifier"); tracker.ASMwasPet = true; if (sacrifice.playerSettings.Master != null) { result += sacrifice.MarketValue * 2; //Add even more sacrifice value to pets with masters s.AppendLine(); s.Append("Subtotal: " + result + " Applied Bonded Modifier"); tracker.ASMwasBonded = true; } if (tracker.lastUsedAltar.SacrificeData.Executioner.relations.DirectRelationExists( PawnRelationDefOf.Bond, sacrifice)) { result += sacrifice.MarketValue * 2; //Even more sacrifice value for sacrificing one's own pet s.AppendLine(); s.Append("Subtotal: " + result + " Applied Master As Executioner Modifier"); tracker.ASMwasExcMaster = true; } } } //Human sacrifice bonuses if (tracker.lastSacrificeType == CultUtility.SacrificeType.human) { //Default human sacrifice bonus result += sacrifice.MarketValue * MODIFIER_HUMAN; // 50% bonus for human sacrifice //Family bonus handling code var ex = tracker.lastUsedAltar.SacrificeData.Executioner; if (ex.relations.FamilyByBlood.Contains(sacrifice)) { result += sacrifice.MarketValue * 3; //Three times the value for family members ex.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOf.WitnessedDeathFamily); s.AppendLine(); var importantRelation = ex.GetMostImportantRelation(sacrifice); s.Append("Subtotal: " + result + " Applied Family Member, " + importantRelation.label + " as Executioner Modifier"); tracker.HSMwasFamily = true; tracker.lastRelation = importantRelation; } //Favor Only Bonus if (favorSpell) { result += result * 0.2f; // 20% bonus } } //Stars are right if (starsAreRight) { result += result * 0.5f; //50% bonus } //Stars are wrong if (starsAreWrong) { result *= 0.5f; //Lose 50% of value } Utility.DebugReport(s.ToString()); return result; } public void ReceiveSacrifice(Pawn sacrifice, Map map, bool favorSpell = false, bool starsAreRight = false, bool starsAreWrong = false) { var tracker = map.GetComponent<MapComponent_SacrificeTracker>(); var value = (sacrifice.MarketValue + SacrificeBonus(sacrifice, map, favorSpell, starsAreRight, starsAreWrong)) / DIVIDER_HUMAN; value += CultUtility.CongregationBonus(tracker.lastUsedAltar.SacrificeData.Congregation, this, out _, out _); Utility.DebugReport("Sacrifice Value: " + value); AffectFavor(value); } public void ReceiveWorship(Pawn preacher) { var preacherSoc = preacher.skills.GetSkill(SkillDefOf.Social).Level; var congregation = CultTracker.Get.PlayerCult .members; //preacher.Map.GetComponent<MapComponent_LocalCultTracker>().LocalCultMembers; if (congregation == null) { Log.Error("Congregation is null"); } var value = (float) Math.Max(1, preacherSoc); if (value != 0) { value /= 20 * (float) ((int) PlayerTier + 1); } value += CultUtility.CongregationBonus(congregation, this, out _, out _); Utility.DebugReport("Worship Value: " + value); AffectFavor(value); } public void ResetFavor() { favor = 0f; } public void AffectFavor(float favorChange) { var newFavor = (float) Math.Round(favorChange, 2); var value = favor + newFavor; Utility.DebugReport(Label + "'s favor affected: " + newFavor + " Total: " + value); favor = value; } public string Info() { var s = new StringBuilder(); s.AppendLine("Box_Titles".Translate() + ": " + Def.titles); s.AppendLine(); s.AppendLine("Box_Domains".Translate() + ": " + Def.domains); s.AppendLine(); s.AppendLine("Box_Description".Translate() + ": "); s.AppendLine(Def.descriptionLong); return s.ToString(); } public string GetInfoText() { string text = def.LabelCap; var text2 = text; text = string.Concat(text2, "\n", "ColonyGoodwill".Translate(), ": ", PlayerFavor.ToString("###0")); if (hostileToPlayer) { text = text + "\n" + "Hostile".Translate(); } else { text = text + "\n" + "Neutral".Translate(); } return text; } public string DebugString() { var stringBuilder = new StringBuilder(); return stringBuilder.ToString(); } public void DebugDraw() { } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Worship/JobDriver_AttendWorship.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using Cthulhu; using RimWorld; using Verse; using Verse.AI; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class JobDriver_AttendWorship : JobDriver { private readonly TargetIndex Build = TargetIndex.A; private readonly TargetIndex Facing = TargetIndex.B; private readonly TargetIndex Spot = TargetIndex.C; private Pawn setPreacher; protected Building_SacrificialAltar Altar => (Building_SacrificialAltar) job.GetTarget(TargetIndex.A).Thing; protected Pawn PreacherPawn { get { if (setPreacher != null) { return setPreacher; } if (Altar.preacher != null) { setPreacher = Altar.preacher; return Altar.preacher; } foreach (var preacherPawn in pawn.Map.mapPawns.FreeColonistsSpawned) { if (preacherPawn.CurJob.def != CultsDefOf.Cults_HoldWorship) { continue; } setPreacher = preacherPawn; return preacherPawn; } return null; } } public override bool TryMakePreToilReservations(bool errorOnFailed) { return true; } public override void ExposeData() { Scribe_References.Look(ref setPreacher, "setPreacher"); base.ExposeData(); } protected override IEnumerable<Toil> MakeNewToils() { rotateToFace = Facing; AddEndCondition(delegate { if (PreacherPawn.CurJob.def == CultsDefOf.Cults_ReflectOnWorship) { return JobCondition.Succeeded; } if (PreacherPawn.CurJob.def != CultsDefOf.Cults_HoldWorship) { return JobCondition.Incompletable; } return JobCondition.Ongoing; }); this.EndOnDespawnedOrNull(Spot); this.EndOnDespawnedOrNull(Build); yield return Toils_Reserve.Reserve(Spot); var gotoPreacher = TargetC.HasThing ? Toils_Goto.GotoThing(Spot, PathEndMode.OnCell) : Toils_Goto.GotoCell(Spot, PathEndMode.OnCell); yield return gotoPreacher; var altarToil = new Toil { defaultCompleteMode = ToilCompleteMode.Delay, defaultDuration = CultUtility.ritualDuration }; altarToil.AddPreTickAction(() => { pawn.GainComfortFromCellIfPossible(); pawn.rotationTracker.FaceCell(TargetB.Cell); if (PreacherPawn.CurJob.def != CultsDefOf.Cults_HoldWorship) { ReadyForNextToil(); } }); yield return altarToil; yield return Toils_Jump.JumpIf(altarToil, () => PreacherPawn.CurJob.def == CultsDefOf.Cults_HoldWorship); yield return Toils_Reserve.Release(Spot); AddFinishAction(() => { //When the ritual is finished -- then let's give the thoughts if (Altar.currentWorshipState == Building_SacrificialAltar.WorshipState.finishing || Altar.currentWorshipState == Building_SacrificialAltar.WorshipState.finished) { CultUtility.AttendWorshipTickCheckEnd(PreacherPawn, pawn); Utility.DebugReport("Called end tick check"); } pawn.ClearAllReservations(); //if (this.TargetC.HasThing && TargetC.Thing is Thing t) //{ // if (pawn.Res Map.reservationManager.IsReserved(this.job.targetC.Thing, Faction.OfPlayer)) // Map.reservationManager.Release(this.job.targetC.Thing, pawn); //} //else //{ // if (Map.reservationManager.IsReserved(this.job.targetC.Cell, Faction.OfPlayer)) // Map.reservationManager.Release(this.job.targetC.Cell, this.pawn); //} }); } } }<file_sep>/Source/CultOfCthulhu/UI/ITab_AltarSacrifice.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- using RimWorld; using UnityEngine; using Verse; // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class ITab_Sacrifice : ITab { public ITab_Sacrifice() { size = ITab_AltarSacrificesCardUtility.SacrificeCardSize; labelKey = "TabSacrifice"; } protected Building_SacrificialAltar SelAltar => (Building_SacrificialAltar) SelThing; protected override void FillTab() { var rect = new Rect(0f, 0f, size.x, size.y).ContractedBy(5f); ITab_AltarSacrificesCardUtility.DrawSacrificeCard(rect, SelAltar); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Cult.cs using System.Collections.Generic; using System.Linq; using RimWorld; using RimWorld.Planet; using Verse; namespace CultOfCthulhu { public class Cult : IExposable { public bool active; public Pawn founder; public Settlement foundingCity; public Faction foundingFaction; public List<CultInfluence> influences = new List<CultInfluence>(); public Pawn leader; public List<Pawn> members = new List<Pawn>(); public string name = "Unnamed Cult"; public int numHumanSacrifices; public Cult() { } public Cult(Pawn newFounder) { InitializeCult(newFounder); } public void ExposeData() { Scribe_Values.Look(ref name, "name", "Unnamed Cult"); Scribe_Values.Look(ref active, "active"); Scribe_References.Look(ref founder, "founder"); Scribe_References.Look(ref leader, "leader"); Scribe_Collections.Look(ref members, "members", LookMode.Reference); Scribe_References.Look(ref foundingFaction, "foundingFaction"); Scribe_References.Look(ref foundingCity, "foundingCity"); Scribe_Collections.Look(ref influences, "influences", LookMode.Deep); Scribe_Values.Look(ref numHumanSacrifices, "numHumanSacrifices"); } public List<Pawn> MembersAt(Map map) { if (!active) { return null; } var result = map.mapPawns.AllPawnsSpawned .Where(x => x.RaceProps != null && x.RaceProps.Humanlike && IsMember(x)).ToList(); return result; } private bool IsMember(Pawn pawn) { if (!active || members == null || members.Count <= 0) { return false; } if (members.Contains(pawn)) { return true; } return false; } private void SendCultLetterDismantled() { Find.LetterStack.ReceiveLetter("Cults_DismantledACultLabel".Translate(), "Cults_DismantledACultDesc".Translate( name ), CultsDefOf.Cults_StandardMessage); } private void SendCultLetterFounded(Pawn newFounder) { Find.LetterStack.ReceiveLetter("Cults_FoundedACultLabel".Translate(), "Cults_FoundedACultDesc".Translate( newFounder.LabelShort ), CultsDefOf.Cults_StandardMessage); if (foundingCity != null) { Find.WindowStack.Add(new Dialog_NameCult(foundingCity.Map)); } } private void InitializeCult(Pawn newFounder) { var map = newFounder.Map; founder = newFounder; leader = newFounder; foundingFaction = newFounder.Faction; foundingCity = Find.WorldObjects.SettlementAt(newFounder.Map.Tile); influences = new List<CultInfluence>(); foreach (var set in Find.WorldObjects.Settlements) { influences.Add(set == foundingCity ? new CultInfluence(set, 1.0f) : new CultInfluence(set, 0.0f)); } active = true; Find.World.GetComponent<WorldComponent_GlobalCultTracker>().worldCults.Add(this); if (foundingFaction != Faction.OfPlayerSilentFail) { return; } SendCultLetterFounded(newFounder); //It's a day to remember var taleToAdd = TaleDef.Named("FoundedCult"); if ((newFounder.IsColonist || newFounder.HostFaction == Faction.OfPlayer) && taleToAdd != null) { TaleRecorder.RecordTale(taleToAdd, newFounder); } //The founder will remember that, too. newFounder.needs.mood.thoughts.memories.TryGainMemory(CultsDefOf.Cults_FoundedCult); map.GetComponent<MapComponent_LocalCultTracker>().ResolveTerribleCultFounder(newFounder); } private void DismantleCult() { SendCultLetterDismantled(); if (influences != null && influences.Count > 0) { influences.Clear(); influences = null; } active = false; } public void SetMember(Pawn cultMember) { // Is the list missing? Let's fix that. if (members == null) { members = new List<Pawn>(); } //Does this member already exist as part of the cult? //If so, don't add them. if (members?.Count > 0) { foreach (var current in members) { if (current == cultMember) { return; } } } //Add the cultist to the list. members.Add(cultMember); //If the cult already exists, show a message to initiate the pawn into the cult. if (active) { Messages.Message(cultMember.LabelShort + " has been initiated into the cult, " + name, MessageTypeDefOf.PositiveEvent); } //If it doesn't already exist, then let's make it so! else { InitializeCult(cultMember); } } public void RemoveMember(Pawn cultMember) { if (members == null) { return; } if (members.Count == 0) { return; } var tempList = new List<Pawn>(members); foreach (var current in tempList) { if (current != cultMember) { continue; } members.Remove(cultMember); if (members.Count == 0) { DismantleCult(); } } } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/SpellWorker_GameEndingEffect.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Text; using RimWorld; using UnityEngine; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public abstract class SpellWorker_GameEndingEffect : SpellWorker { public static Map map; public static string message; public static float delay; protected override bool CanFireNowSub(IncidentParms parms) { return true; } public override bool CanSummonNow(Map map) { return true; } public abstract string GetEndScreenText(); public abstract float GetDelay(); public string MakeEndScreenText() { var stringBuilder = new StringBuilder(); foreach (var current2 in map.mapPawns.FreeColonists) { if (!current2.Spawned) { continue; } stringBuilder.AppendLine(" " + current2.LabelCap); current2.DeSpawn(); } if (stringBuilder.Length == 0) { stringBuilder.AppendLine("Nobody".Translate().ToLower()); } string preCreditsMessage = GetEndScreenText().Translate( stringBuilder.ToString() ); return preCreditsMessage; } protected override bool TryExecuteWorker(IncidentParms parms) { map = parms.target as Map; message = MakeEndScreenText(); delay = GetDelay(); LongEventHandler.QueueLongEvent(delegate { var screen_Credits = new Cults_Screen_Credits(message, 10) { wonGame = true }; Find.WindowStack.Add(screen_Credits); Find.MusicManagerPlay.ForceSilenceFor(999f); ScreenFader.StartFade(Color.clear, 3f); }, "Cults_SpellGameEndingEffect", false, null); return true; } } }<file_sep>/Source/CultOfCthulhu/CultsFloatMenuPatch.cs using System; using System.Collections.Generic; using System.Linq; using Cthulhu; using JecsTools; using RimWorld; using UnityEngine; using Verse; namespace CultOfCthulhu { public class CultsFloatMenuPatch : FloatMenuPatch { public override IEnumerable<KeyValuePair<_Condition, Func<Vector3, Pawn, Thing, List<FloatMenuOption>>>> GetFloatMenus() { var floatMenus = new List<KeyValuePair<_Condition, Func<Vector3, Pawn, Thing, List<FloatMenuOption>>>>(); var madnessCondition = new _Condition(_ConditionType.IsType, typeof(Pawn)); List<FloatMenuOption> madnessFunc(Vector3 clickPos, Pawn pawn, Thing curThing) { var target = curThing as Pawn; if (pawn != target) { return null; } if (!Utility.HasSanityLoss(pawn)) { return null; } var opts = new List<FloatMenuOption>(); void action() { var newMentalState = Rand.Value > 0.05 ? DefDatabase<MentalStateDef>.AllDefs.InRandomOrder() .FirstOrDefault(x => x.IsAggro == false) : MentalStateDefOf.Berserk; Utility.DebugReport("Selected mental state: " + newMentalState?.label); if (pawn != null && pawn.Drafted) { pawn.drafter.Drafted = false; } pawn?.ClearMind(); pawn?.pather.StopDead(); if (pawn != null && !pawn.mindState.mentalStateHandler.TryStartMentalState(newMentalState)) { Messages.Message("ROM_TradedSanityLossForMadnessFailed".Translate(pawn.LabelShort), pawn, MessageTypeDefOf.RejectInput); return; } Messages.Message("ROM_TradedSanityLossForMadness".Translate(pawn?.LabelShort), pawn, MessageTypeDefOf.ThreatSmall); Utility.RemoveSanityLoss(pawn); } opts.Add(new FloatMenuOption("ROM_TradeSanityForMadness".Translate(), action, MenuOptionPriority.High, null, target)); return opts; } var curSec = new KeyValuePair<_Condition, Func<Vector3, Pawn, Thing, List<FloatMenuOption>>>(madnessCondition, madnessFunc); floatMenus.Add(curSec); return floatMenus; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/CosmicEntities/WorldComponent_CosmicDeities.cs using System.Collections.Generic; using System.Linq; using System.Text; using Cthulhu; using RimWorld; using RimWorld.Planet; using Verse; namespace CultOfCthulhu { public class WorldComponent_CosmicDeities : WorldComponent { private bool AreDeitiesSpawned; public Dictionary<CosmicEntity, int> DeityCache = new Dictionary<CosmicEntity, int>(); public bool WasCultMindednessInitialized = false; public WorldComponent_CosmicDeities(World world) : base(world) { } public CosmicEntity GetCache(CosmicEntity deity) { CosmicEntity result; var flag1 = DeityCache == null; if (flag1) { DeityCache = new Dictionary<CosmicEntity, int>(); } foreach (var current in DeityCache.Keys) { if (current != deity) { continue; } result = current; return result; } DeityCache.Add(deity, deity.Version); result = deity; return result; } public void orGenerate() { if (AreDeitiesSpawned) { return; } foreach (var current in DefDatabase<ThingDef>.AllDefs) { if (current.thingClass != typeof(CosmicEntity)) { continue; } var x = new CosmicEntity(current); //x.Position = new IntVec3(); //x.SpawnSetup(); GetCache(x); } AreDeitiesSpawned = true; //Cthulhu.Utility.DebugReport("Cosmic Deities Spawned"); } public override void WorldComponentTick() { orGenerate(); RevealDeityCheck(); base.WorldComponentTick(); } private List<CosmicEntity> undiscoveredEntities() { var result = new List<CosmicEntity>(); foreach (var entity in DeityCache.Keys.InRandomOrder()) { if (entity.discovered == false) { result.Add(entity); //Cthulhu.Utility.DebugReport(entity.Label); } } return result; } private void RevealDeityCheck() { //Cthulhu.Utility.DebugReport("Reveal Deity Check"); if (Utility.deityResearchDone || !Utility.deityResearch.IsFinished) { return; } if (DeityCache.Any(pair => !pair.Key.discovered)) { foreach (var entity in undiscoveredEntities()) { entity.discovered = true; Utility.DebugReport("Change research should be called."); Utility.ChangeResearchProgress(Utility.deityResearch, 0f, true); var message = "Cults_DiscoveredDeityMessage".Translate(entity.Label); Messages.Message(message, MessageTypeDefOf.PositiveEvent); var s = new StringBuilder(); s.AppendLine(message); s.AppendLine(); s.AppendLine(entity.Info()); Find.LetterStack.ReceiveLetter("Cults_Discovered".Translate(), s.ToString(), LetterDefOf.NeutralEvent); break; } } else { Utility.ChangeResearchProgress(Utility.deityResearch, Utility.deityResearch.baseCost); Utility.deityResearchDone = true; } } private void ReloadCosmicEntity(CosmicEntity entity) { var currentFavor = entity.PlayerFavor; var currentDiscovery = entity.discovered; //Remove entity DeityCache.Remove(entity); //New deity var x = new CosmicEntity(entity.def); x.AffectFavor(currentFavor); x.discovered = currentDiscovery; DeityCache.Add(x, x.Version); //Destroy deity entity.Destroy(); //Cthulhu.Utility.DebugReport("Reloaded " + entity.Label); } private void CheckForUpdates() { //Create a temporary dictionary. //Load all the current deities into it. var tempDic = new Dictionary<CosmicEntity, int>(); foreach (var pair in DeityCache) { tempDic.Add(pair.Key, pair.Value); } //Now, check to see if the saved "version" matches the new "version" we loaded. var entitiesToUpdate = new List<CosmicEntity>(); foreach (var pair in tempDic) { //Version mismatch, let's update! if (pair.Key.Version != pair.Value) { entitiesToUpdate.Add(pair.Key); //Cthulhu.Utility.DebugReport("To be updated +1"); } //Cthulhu.Utility.DebugReport("Cycled"); } foreach (var entity in entitiesToUpdate) { ReloadCosmicEntity(entity); } //Deities are updated, but let's check if there are new deities. foreach (var current in DefDatabase<ThingDef>.AllDefs) { if (current.thingClass != typeof(CosmicEntity)) { continue; } var newDeity = new CosmicEntity(current); if (tempDic.Keys.FirstOrDefault(oldDeity => oldDeity.def.defName == newDeity.def.defName) != null) { continue; } newDeity.discovered = false; GetCache(newDeity); //RevealDeityCheck(); } //Clear that dictionary } public override void ExposeData() { Scribe_Collections.Look(ref DeityCache, "Deities", LookMode.Deep, LookMode.Value); //Scribe_Collections.Look<CosmicEntity>(ref this.DeityCache, "Deities", LookMode.Deep, new object[0]); Scribe_Values.Look(ref AreDeitiesSpawned, "AreDeitiesSpawned"); base.ExposeData(); if (DeityCache == null) { DeityCache = new Dictionary<CosmicEntity, int>(); } if (Scribe.mode != LoadSaveMode.PostLoadInit) { return; } orGenerate(); CheckForUpdates(); } } }<file_sep>/Source/CultOfCthulhu/ThingWithComps_CultGrimoire.cs using System.Collections.Generic; using RimWorld; using UnityEngine; using Verse; using Verse.Sound; namespace CultOfCthulhu { internal class ThingWithComps_CultGrimoire : ThingWithComps { public override IEnumerable<Gizmo> GetGizmos() { foreach (var g in base.GetGizmos()) { yield return g; } var buildable = CultsDefOf.Cults_ForbiddenKnowledgeCenter; //ThingDef.Named("ForbiddenKnowledgeCenter"); var des = FindDesignator(buildable); var stuff = ThingDefOf.WoodLog; if (des == null) { yield break; } if (!des.Visible) { yield break; } var command_Action = new Command_Action { action = delegate { SoundDefOf.ThingSelected.PlayOneShotOnCamera(); //des.SetStuffDef(stuff); des.ProcessInput(new Event()); Find.DesignatorManager.Select(des); }, defaultLabel = "CommandBuildFKC".Translate(), defaultDesc = "CommandBuildFKCDesc".Translate(), icon = des.icon, iconProportions = des.iconProportions, iconDrawScale = des.iconDrawScale, iconTexCoords = des.iconTexCoords, defaultIconColor = stuff?.stuffProps.color ?? buildable.uiIconColor, hotKey = KeyBindingDefOf.Misc11 }; yield return command_Action; } private static Designator_Build FindDesignator(BuildableDef buildable) { var allDefsListForReading = DefDatabase<DesignationCategoryDef>.AllDefsListForReading; foreach (var designationCategoryDef in allDefsListForReading) { foreach (var current in designationCategoryDef.ResolvedAllowedDesignators) { if (current is Designator_Build designator_Build && designator_Build.PlacingDef == buildable) { return designator_Build; } } } return null; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Tsathoggua/SpellWorker_SleeperOfNKai.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_SleeperOfNKai : SpellWorker { public override bool CanSummonNow(Map map) { return true; } protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; //Spawn some goats //Cthulhu.Utility.SpawnPawnsOfCountAt(CultDefOfs.BlackIbex, altar.Position, Rand.Range(2, 5), Faction.OfPlayer); //Spawn a fertility idol. Utility.SpawnThingDefOfCountAt(CultsDefOf.Cults_SleepTotem, 1, new TargetInfo(altar(map).RandomAdjacentCell8Way(), map)); //Spawn a Messages.Message("Cults_SleepTotem_Spawns".Translate(), MessageTypeDefOf.PositiveEvent); Utility.ApplyTaleDef("Cults_SpellSleeperOfNKai", map); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Cult/Seed/WorkGiver_InvestigateTree.cs using Verse; namespace CultOfCthulhu { public class WorkGiver_InvestigateTree : WorkGiver_Investigate { public override ThingRequest PotentialWorkThingRequest => ThingRequest.ForDef(CultsDefOf.Cults_PlantTreeNightmare); } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/TableOfFun/SpellWorker_StarVampireVisit.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using Cthulhu; using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_StarVampireVisit : SpellWorker { public override bool CanSummonNow(Map map) { if (!Utility.IsCosmicHorrorsLoaded()) { Messages.Message("Note: Cosmic Horrors mod isn't loaded. Megaspiders will be summoned instead.", MessageTypeDefOf.NeutralEvent); } //Cthulhu.Utility.DebugReport("CanFire: " + this.def.defName); return true; } protected override bool TryExecuteWorker(IncidentParms parms) { var map = parms.target as Map; //Spawn a Dark Young if (Utility.IsCosmicHorrorsLoaded()) { Utility.SpawnPawnsOfCountAt(DefDatabase<PawnKindDef>.GetNamed("ROM_StarVampire"), altar(map).Position, map, 1, Find.World.factionManager.FirstFactionOfDef(FactionDefOf.AncientsHostile)); } else { Utility.SpawnPawnsOfCountAt(PawnKindDefOf.Megaspider, altar(map).Position, map, Rand.Range(1, 2), Find.FactionManager.FirstFactionOfDef(FactionDefOf.AncientsHostile), true); } Messages.Message("A star vampire is unleashed.", MessageTypeDefOf.ThreatBig); Utility.ApplyTaleDef("Cults_SpellStarVampireVisit", map); return true; } } }<file_sep>/Source/CultOfCthulhu/UI/ITab_AltarFoodSacrificeCardUtility.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Text; using UnityEngine; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { [StaticConstructorOnStartup] public class ITab_AltarFoodSacrificeCardUtility { public static Vector2 TempleCardSize = new Vector2(500f, 320f); public static void DrawTempleCard(Rect rect, Building_SacrificialAltar altar) { GUI.BeginGroup(rect); var rect3 = new Rect(2f, 0f, ITab_AltarSacrificesCardUtility.ColumnSize, ITab_AltarSacrificesCardUtility.ButtonSize); Widgets.Label(rect3, "Deity".Translate() + ": "); rect3.xMin = rect3.center.x - 15f; var label2 = DeityLabel(altar); if (Widgets.ButtonText(rect3, label2, true, false)) { ITab_AltarCardUtility.OpenDeitySelectMenu(altar, ITab_AltarCardUtility.DeityType.OfferingDeity); } TooltipHandler.TipRegion(rect3, "DeityDesc".Translate()); ITab_AltarCardUtility.DrawDeity(altar.tempCurrentOfferingDeity, rect3); var rect4 = rect3; rect4.y += ITab_AltarSacrificesCardUtility.ButtonSize + 15f; rect4.width = ITab_AltarSacrificesCardUtility.ColumnSize; rect4.x -= rect3.x - 2; Widgets.Label(rect4, "Offerer".Translate() + ": "); rect4.xMin = rect4.center.x - 15f; var label3 = OffererLabel(altar); if (Widgets.ButtonText(rect4, label3, true, false)) { ITab_AltarCardUtility.OpenActorSelectMenu(altar, ITab_AltarCardUtility.ActorType.offerer); } TooltipHandler.TipRegion(rect4, "OffererDesc".Translate()); var rect5 = rect4; rect5.y += ITab_AltarSacrificesCardUtility.ButtonSize + 15f; rect5.x -= rect4.x - 2; //rect5.x += 2f; rect5.width = ITab_AltarSacrificesCardUtility.ColumnSize; Widgets.Label(rect5, "Offering".Translate() + ": "); rect5.xMin = rect5.center.x - 15f; var label4 = OfferingLabel(altar); if (Widgets.ButtonText(rect5, label4, true, false)) { OpenOfferingSelectMenu(altar); } TooltipHandler.TipRegion(rect5, "OfferingDesc".Translate()); var rect6 = rect5; rect6.y += ITab_AltarSacrificesCardUtility.ButtonSize + 15f; rect6.x -= rect5.x - 2; //rect5.x += 2f; rect6.width = ITab_AltarSacrificesCardUtility.ColumnSize; Widgets.Label(rect6, "Amount".Translate() + ": "); rect6.xMin = rect6.center.x - 15f; var label5 = AmountLabel(altar); if (Widgets.ButtonText(rect6, label5, true, false)) { OpenAmountSelectMenu(altar); } TooltipHandler.TipRegion(rect6, "AmountDesc".Translate()); //Rect rect3 = new Rect(2f, 0, 210f, 25f); //Widgets.Label(rect3, "Deity".Translate() + ": "); //rect3.xMin = rect3.center.x - 15f; //string label2 = DeityLabel(altar); //if (Widgets.ButtonText(rect3, label2, true, false, true)) //{ // ITab_AltarHumanSacrificeCardUtility.OpenDeitySelectMenu(altar); //} //Rect secondBox = rect3; //secondBox.x += rect3.x + 10f + 30f; //secondBox.xMax += 125f; //secondBox.height = 35f; //Text.Font = GameFont.Medium; //Widgets.Label(secondBox, DeityLabel(altar)); //Text.Font = GameFont.Small; //ITab_CardUtility.DrawTier(altar.tempCurrentSacrificeDeity, new Vector2(secondBox.x, secondBox.y + 30f)); //Rect secondBoxUnder = secondBox; //secondBoxUnder.y += 40f; //secondBoxUnder.width -= 15f; //secondBoxUnder.height = 70f; //Widgets.Label(secondBoxUnder, DeityDescription(altar)); //Rect secondBoxUnder2 = secondBoxUnder; //secondBoxUnder2.y += 70; //secondBoxUnder2.height = 250f; //Widgets.Label(secondBoxUnder2, SpellDescription(altar)); //Rect rect5 = rect3; //rect5.y += 35f; ////rect5.x -= (rect3.x - 5); //rect5.x -= 2f; //rect5.width = 210f; //Widgets.Label(rect5, "Offering".Translate() + ": "); //rect5.xMin = rect5.center.x - 15f; //string label4 = SacrificeLabel(altar); //if (Widgets.ButtonText(rect5, label4, true, false, true)) //{ // ITab_AltarHumanSacrificeCardUtility.OpenSacrificeSelectMenu(altar); //} GUI.EndGroup(); } private static string OfferingLabel(Building_SacrificialAltar altar) { return altar.tempOfferingType == CultUtility.SacrificeType.none ? "None" : altar.tempOfferingType.ToString().CapitalizeFirst(); } private static string OffererLabel(Building_SacrificialAltar altar) { return altar.tempOfferer == null ? "None" : altar.tempOfferer.Name.ToStringShort; } private static string DeityLabel(Building_SacrificialAltar altar) { return altar.tempCurrentOfferingDeity == null ? "None" : altar.tempCurrentOfferingDeity.LabelCap; } private static string AmountLabel(Building_SacrificialAltar altar) { return altar.tempOfferingSize == CultUtility.OfferingSize.none ? "None" : altar.tempOfferingSize.ToString().CapitalizeFirst(); } private static string DeityDescription(Building_SacrificialAltar altar) { if (altar.tempCurrentOfferingDeity == null) { return "None"; } var stringBuilder = new StringBuilder(); //stringBuilder.Append(altar.tempCurrentSacrificeDeity.LabelCap); stringBuilder.AppendLine(); stringBuilder.Append(altar.tempCurrentOfferingDeity.def.description); //stringBuilder.AppendLine(); //stringBuilder.Append("Standing: " + altar.tempCurrentSacrificeDeity.PlayerFavor.ToString()); //stringBuilder.AppendLine(); //stringBuilder.Append("Tier: " + altar.tempCurrentSacrificeDeity.PlayerTier.ToString()); return stringBuilder.ToString(); } /* private static void ForceListenersTest(Building_SacrificialAltar altar) { IntVec3 result; Building chair; foreach (Pawn p in Find.MapPawns.AllPawnsSpawned.FindAll(x => x.RaceProps.intelligence == Intelligence.Humanlike)) { if (!SermonUtility.IsPreacher(p)) { if (!WatchBuildingUtility.TryFindBestWatchCell(altar, p, true, out result, out chair)) { if (!WatchBuildingUtility.TryFindBestWatchCell(altar as Thing, p, false, out result, out chair)) { return; } } if (chair != null) { Job J = new Job(CorruptionDefOfs.AttendSermon, altar.preacher, altar, chair); p.QueueJob(J); p.CurJob.EndCurrentJob(JobCondition.InterruptForced); } else { Job J = new Job(CorruptionDefOfs.AttendSermon, altar.preacher, altar, result); p.QueueJob(J); p.CurJob.EndCurrentJob(JobCondition.InterruptForced); } } } } */ public static void OpenAmountSelectMenu(Building_SacrificialAltar altar) { var list = new List<FloatMenuOption> { new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate { altar.tempOfferingSize = CultUtility.OfferingSize.none; }) }; void action() { altar.tempOfferingSize = CultUtility.OfferingSize.meagre; } list.Add(new FloatMenuOption("Meagre".Translate(), action)); void action2() { altar.tempOfferingSize = CultUtility.OfferingSize.decent; } list.Add(new FloatMenuOption("Decent".Translate(), action2)); void action3() { altar.tempOfferingSize = CultUtility.OfferingSize.sizable; } list.Add(new FloatMenuOption("Sizable".Translate(), action3)); void action4() { altar.tempOfferingSize = CultUtility.OfferingSize.worthy; } list.Add(new FloatMenuOption("Worthy".Translate(), action4)); void action5() { altar.tempOfferingSize = CultUtility.OfferingSize.impressive; } list.Add(new FloatMenuOption("Impressive".Translate(), action5)); Find.WindowStack.Add(new FloatMenu(list)); } public static void OpenOfferingSelectMenu(Building_SacrificialAltar altar) { var list = new List<FloatMenuOption> { new FloatMenuOption("(" + "NoneLower".Translate() + ")", delegate { altar.tempOfferingType = CultUtility.SacrificeType.none; }) }; void action() { altar.tempOfferingType = CultUtility.SacrificeType.plants; } list.Add(new FloatMenuOption("Plants".Translate(), action)); void action2() { altar.tempOfferingType = CultUtility.SacrificeType.meat; } list.Add(new FloatMenuOption("Meat".Translate(), action2)); void action3() { altar.tempOfferingType = CultUtility.SacrificeType.meals; } list.Add(new FloatMenuOption("Meals".Translate(), action3)); Find.WindowStack.Add(new FloatMenu(list)); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Dagon/SpellWorker_TreasuresOfTheDeep.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using RimWorld; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class SpellWorker_TreasuresOfTheDeep : SpellWorker { protected override bool CanFireNowSub(IncidentParms parms) { //Cthulhu.Utility.DebugReport(" //: " + this.def.defName); return true; } protected override bool TryExecuteWorker(IncidentParms parms) { if (!(parms.target is Map map)) { return false; } if (!CultUtility.TryFindDropCell(map.Center, map, 999999, out var intVec)) { return false; } //this.EndOnDespawnedOrNull(this.pawn, JobCondition.Incompletable); for (var i = 0; i < Rand.Range(1, 3); i++) { var thing = (Building_TreasureChest) ThingMaker.MakeThing(CultsDefOf.Cults_TreasureChest); GenPlace.TryPlaceThing(thing, intVec.RandomAdjacentCell8Way(), map, ThingPlaceMode.Near); } map.GetComponent<MapComponent_SacrificeTracker>().lastLocation = intVec; Messages.Message("Treasures from the deep mysteriously appear.", new TargetInfo(intVec, map), MessageTypeDefOf.PositiveEvent); return true; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Worship/JobDriver_HoldWorship.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using System.Diagnostics; using Cthulhu; using RimWorld; using Verse; using Verse.AI; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { public class JobDriver_HoldWorship : JobDriver { private const TargetIndex AltarIndex = TargetIndex.A; private string report = ""; public int TicksLeftInService = int.MaxValue; private Thing WorshipCaller; public bool Forced => job.playerForced; protected Building_SacrificialAltar DropAltar => (Building_SacrificialAltar) job.GetTarget(TargetIndex.A).Thing; public override bool TryMakePreToilReservations(bool errorOnFailed) { return true; } public override string GetReport() { return report != "" ? ReportStringProcessed(report) : base.GetReport(); } [DebuggerHidden] protected override IEnumerable<Toil> MakeNewToils() { //Commence fail checks! this.FailOnDestroyedOrNull(TargetIndex.A); yield return Toils_Reserve.Reserve(AltarIndex, Building_SacrificialAltar.LyingSlotsCount); yield return new Toil { initAction = delegate { DropAltar.ChangeState(Building_SacrificialAltar.State.worshipping, Building_SacrificialAltar.WorshipState.gathering); } }; //Who are we worshipping today? var deitySymbol = ((CosmicEntityDef) DropAltar.currentWorshipDeity.def).Symbol; var deityLabel = DropAltar.currentWorshipDeity.Label; var goToAltar = Toils_Goto.GotoThing(TargetIndex.A, PathEndMode.InteractionCell); //Toil 0: Activate any nearby Worship Callers. yield return new Toil { initAction = delegate { bool validator(Thing x) { return x.TryGetComp<CompWorshipCaller>() != null; } var worshipCaller = GenClosest.ClosestThingReachable(DropAltar.Position, DropAltar.Map, ThingRequest.ForGroup(ThingRequestGroup.BuildingArtificial), PathEndMode.ClosestTouch, TraverseParms.For(pawn, Danger.None), 9999, validator); if (worshipCaller != null) { WorshipCaller = worshipCaller; job.SetTarget(TargetIndex.B, worshipCaller); } else { JumpToToil(goToAltar); } } }; yield return Toils_Goto.GotoThing(TargetIndex.B, PathEndMode.ClosestTouch) .JumpIfDespawnedOrNullOrForbidden(TargetIndex.B, goToAltar); yield return new Toil { initAction = delegate { WorshipCaller.TryGetComp<CompWorshipCaller>().Use(Forced); } }.JumpIfDespawnedOrNullOrForbidden(TargetIndex.B, goToAltar); //Toil 1: Go to the altar. yield return goToAltar; //Toil 2: Wait a bit for stragglers. var waitingTime = new Toil { defaultCompleteMode = ToilCompleteMode.Delay, defaultDuration = CultUtility.ritualDuration, initAction = delegate { report = "Cults_WaitingToStartSermon".Translate(); DropAltar.ChangeState(Building_SacrificialAltar.State.worshipping, Building_SacrificialAltar.WorshipState.worshipping); } }; yield return waitingTime; //Toil 3: Preach the sermon. var preachingTime = new Toil { defaultCompleteMode = ToilCompleteMode.Delay, defaultDuration = CultUtility.ritualDuration, initAction = delegate { report = "Cults_PreachingAbout".Translate( deityLabel ); if (deitySymbol != null) { MoteMaker.MakeInteractionBubble(pawn, null, ThingDefOf.Mote_Speech, deitySymbol); } }, tickAction = delegate { var actor = pawn; actor.skills.Learn(SkillDefOf.Social, 0.25f); actor.GainComfortFromCellIfPossible(); } }; yield return preachingTime; //Toil 4: Time to pray var chantingTime = new Toil { defaultCompleteMode = ToilCompleteMode.Delay, defaultDuration = CultUtility.ritualDuration }; chantingTime.WithProgressBarToilDelay(TargetIndex.A); chantingTime.PlaySustainerOrSound(CultsDefOf.RitualChanting); chantingTime.initAction = delegate { report = "Cults_PrayingTo".Translate( deityLabel ); if (deitySymbol != null) { MoteMaker.MakeInteractionBubble(pawn, null, ThingDefOf.Mote_Speech, deitySymbol); } }; chantingTime.tickAction = delegate { var actor = pawn; actor.skills.Learn(SkillDefOf.Social, 0.25f); actor.GainComfortFromCellIfPossible(); }; yield return chantingTime; //Toil 8: Execution of Prisoner yield return new Toil { initAction = delegate { //TaleRecorder.RecordTale( // Of.ExecutedPrisoner, new object[] //{ // this.pawn, // this.Takee //}); CultUtility.WorshipComplete(pawn, DropAltar, DropAltar.currentWorshipDeity); }, defaultCompleteMode = ToilCompleteMode.Instant }; yield return new Toil { initAction = delegate { if (DropAltar == null) { return; } if (DropAltar.currentWorshipState != Building_SacrificialAltar.WorshipState.finished) { DropAltar.ChangeState(Building_SacrificialAltar.State.worshipping, Building_SacrificialAltar.WorshipState.finished); //Map.GetComponent<MapComponent_SacrificeTracker>().ClearVariables(); } }, defaultCompleteMode = ToilCompleteMode.Instant }; AddFinishAction(() => { //When the ritual is finished -- then let's give the thoughts if (DropAltar.currentWorshipState != Building_SacrificialAltar.WorshipState.finishing && DropAltar.currentWorshipState != Building_SacrificialAltar.WorshipState.finished) { return; } Utility.DebugReport("Called end tick check"); CultUtility.HoldWorshipTickCheckEnd(pawn); }); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Hastur/JobGiver_DeepSleepCarcosa.cs using RimWorld; using Verse; using Verse.AI; namespace CultOfCthulhu { public class JobGiver_DeepSleepCarcosa : ThinkNode_JobGiver { private Building_Bed ownedBed; protected IntVec3 GetBedRoot(Pawn pawn) { ownedBed = pawn.ownership.OwnedBed; return ownedBed != null ? RestUtility.GetBedSleepingSlotPosFor(pawn, ownedBed) : pawn.Position; } protected override Job TryGiveJob(Pawn pawn) { var forcedGotoPosition = GetBedRoot(pawn); if (!forcedGotoPosition.IsValid) { return null; } if (pawn.CanReach(forcedGotoPosition, PathEndMode.ClosestTouch, Danger.Deadly)) { return new Job(JobDefOf.LayDown, forcedGotoPosition) { locomotionUrgency = LocomotionUrgency.Walk }; } pawn.mindState.forcedGotoPosition = IntVec3.Invalid; return null; } } }<file_sep>/Source/CultOfCthulhu/UI/ITab_AltarSacrificesCardUtility.cs // ---------------------------------------------------------------------- // These are basic usings. Always let them be here. // ---------------------------------------------------------------------- using System.Collections.Generic; using UnityEngine; using Verse; // ---------------------------------------------------------------------- // These are RimWorld-specific usings. Activate/Deactivate what you need: // ---------------------------------------------------------------------- // Always needed //using VerseBase; // Material/Graphics handling functions are found here // RimWorld universal objects are here (like 'Building') // Needed when you do something with the AI // Needed when you do something with Sound // Needed when you do something with Noises // RimWorld specific functions are found here (like 'Building_Battery') // RimWorld specific functions for world creation //using RimWorld.SquadAI; // RimWorld specific functions for squad brains namespace CultOfCthulhu { [StaticConstructorOnStartup] public class ITab_AltarSacrificesCardUtility { public enum SacrificeCardTab : byte { Offering, Animal, Human } public static Vector2 SacrificeCardSize = new Vector2(550f, 415f); public static float ButtonSize = 40f; public static float SpacingOffset = 15f; public static float ColumnSize = 245f; public static SacrificeCardTab tab = SacrificeCardTab.Offering; public static SacrificeCardTab Tab { get => tab; set => tab = value; } public static void DrawRename(Building_SacrificialAltar altar) { var rectRename = new Rect(SacrificeCardSize.x - 85f, 0f, 30f, 30f); TooltipHandler.TipRegion(rectRename, "RenameTemple".Translate()); if (Widgets.ButtonImage(rectRename, Buttons.RenameTex)) { Find.WindowStack.Add(new Dialog_RenameTemple(altar)); } } public static void DrawSacrificeCard(Rect inRect, Building_SacrificialAltar altar) { GUI.BeginGroup(inRect); if (CultTracker.Get.PlayerCult != null) { var cultLabelWidth = Text.CalcSize(CultTracker.Get.PlayerCult.name).x; var rect = new Rect(inRect); rect = rect.ContractedBy(14f); rect.height = 30f; Text.Font = GameFont.Medium; Widgets.Label(rect, altar.RoomName); Text.Font = GameFont.Small; DrawRename(altar); var rect2 = new Rect(inRect) { yMin = rect.yMax + 10, height = 22f }; rect2.xMin += 15f; rect2.width = cultLabelWidth + 5; //rect2.yMax -= 38f; Widgets.Label(rect2, CultTracker.Get.PlayerCult.name); if (Mouse.IsOver(rect2)) { Widgets.DrawHighlight(rect2); } if (Mouse.IsOver(rect2) && Event.current.type == EventType.MouseDown) { Find.WindowStack.Add(new Dialog_RenameCult(altar.Map)); } var rect3 = new Rect(inRect) { //rect3.height -= 45f; //rect3.yMin += 45f; yMin = rect2.yMax + 45f, height = 550f }; var list = new List<TabRecord>(); var item = new TabRecord("Offering".Translate(), delegate { tab = SacrificeCardTab.Offering; }, tab == SacrificeCardTab.Offering); list.Add(item); if (altar.currentFunction >= Building_SacrificialAltar.Function.Level2) { var item2 = new TabRecord("Animal".Translate(), delegate { tab = SacrificeCardTab.Animal; }, tab == SacrificeCardTab.Animal); list.Add(item2); } if (altar.currentFunction >= Building_SacrificialAltar.Function.Level3) { var item3 = new TabRecord("Human".Translate(), delegate { tab = SacrificeCardTab.Human; }, tab == SacrificeCardTab.Human); list.Add(item3); } TabDrawer.DrawTabs(rect3, list); FillCard(rect3.ContractedBy(10f), altar); } else { var rect = new Rect(inRect); rect = rect.ContractedBy(14f); rect.height = 30f; Text.Font = GameFont.Medium; Widgets.Label(rect, "Cults_NoPlayerCultAvailable".Translate()); Text.Font = GameFont.Small; } GUI.EndGroup(); } protected static void FillCard(Rect cardRect, Building_SacrificialAltar altar) { if (tab == SacrificeCardTab.Offering) { ITab_AltarFoodSacrificeCardUtility.DrawTempleCard(cardRect, altar); } else if (tab == SacrificeCardTab.Animal) { ITab_AltarAnimalSacrificeCardUtility.DrawTempleCard(cardRect, altar); } else if (tab == SacrificeCardTab.Human) { ITab_AltarHumanSacrificeCardUtility.DrawTempleCard(cardRect, altar); } else { ITab_AltarFoodSacrificeCardUtility.DrawTempleCard(cardRect, altar); } } } }<file_sep>/Source/CultOfCthulhu/HarmonyPatches.cs using System; using System.Collections.Generic; using HarmonyLib; using RimWorld; using UnityEngine; using Verse; namespace CultOfCthulhu { [StaticConstructorOnStartup] internal static class HarmonyPatches { private static readonly bool DebugMode = false; static HarmonyPatches() { var harmony = new Harmony("rimworld.jecrell.cthulhu.cults"); harmony.Patch(AccessTools.Method(typeof(ThingWithComps), nameof(ThingWithComps.InitializeComps)), null, new HarmonyMethod(typeof(HarmonyPatches), nameof(InitializeComps_PostFix))); DebugMessage("ThingWithComps.InitializeComps_PostFix Passed"); harmony.Patch(AccessTools.Property(typeof(Pawn), nameof(Pawn.BodySize)).GetGetMethod(), null, new HarmonyMethod(typeof(HarmonyPatches), nameof(get_BodySize_PostFix))); DebugMessage("Pawn.BodySize.get_BodySize_PostFix Passed"); harmony.Patch(AccessTools.Property(typeof(Pawn), nameof(Pawn.HealthScale)).GetGetMethod(), null, new HarmonyMethod(typeof(HarmonyPatches), nameof(get_HealthScale_PostFix))); DebugMessage("Pawn.HealthScale.get_HealthScale_PostFix Passed"); harmony.Patch( AccessTools.Method(typeof(GenLabel), "BestKindLabel", new[] {typeof(Pawn), typeof(bool), typeof(bool), typeof(bool), typeof(int)}), null, new HarmonyMethod(typeof(HarmonyPatches), nameof(BestKindLabel_PostFix))); DebugMessage("GenLabel.BestKindLabel_PostFix Passed"); harmony.Patch(AccessTools.Method(typeof(Pawn_DrawTracker), nameof(Pawn_DrawTracker.DrawAt)), null, new HarmonyMethod(typeof(HarmonyPatches), nameof(DrawAt_PostFix))); DebugMessage("Pawn_DrawTracker.DrawAt_PostFix Passed"); harmony.Patch( AccessTools.Method(typeof(PawnUtility), nameof(PawnUtility.IsTravelingInTransportPodWorldObject)), null, new HarmonyMethod(typeof(HarmonyPatches), nameof(IsTravelingInTransportPodWorldObject_PostFix))); DebugMessage( "PawnUtility.IsTravelingInTransportPodWorldObject.IsTravelingInTransportPodWorldObject_PostFix Passed"); harmony.Patch(AccessTools.Method(typeof(FertilityGrid), "CalculateFertilityAt"), null, new HarmonyMethod( typeof(HarmonyPatches), nameof(CalculateFertilityAt))); DebugMessage("FertilityGrid.CalculateFertilityAt Passed"); harmony.Patch(AccessTools.Method(typeof(MouseoverReadout), "MouseoverReadoutOnGUI"), new HarmonyMethod( typeof(HarmonyPatches), nameof(MouseoverReadoutOnGUI))); DebugMessage("MouseoverReadout.MouseoverReadoutOnGUI Passed"); } public static void DebugMessage(string s) { if (DebugMode) { Log.Message(s); } } private static string SpeedPercentString(float extraPathTicks) { var f = 13f / (extraPathTicks + 13f); return f.ToStringPercent(); } public static bool MouseoverReadoutOnGUI(MouseoverReadout __instance) { var c = UI.MouseCell(); if (!c.InBounds(Find.CurrentMap) || Event.current.type != EventType.Repaint || Find.MainTabsRoot.OpenTab != null) { return false; } if (!(Find.CurrentMap.GetComponent<MapComponent_FertilityMods>().Get is MapComponent_FertilityMods fert) || !fert.ActiveCells.Contains(c)) { return true; } //Original Variables var BotLeft = new Vector2(15f, 65f); GenUI.DrawTextWinterShadow(new Rect(256f, UI.screenHeight - 256, -256f, 256f)); Text.Font = GameFont.Small; GUI.color = new Color(1f, 1f, 1f, 0.8f); var num = 0f; Rect rect; if (c.Fogged(Find.CurrentMap)) { rect = new Rect(BotLeft.x, UI.screenHeight - BotLeft.y - num, 999f, 999f); Widgets.Label(rect, "Undiscovered".Translate()); GUI.color = Color.white; return false; } rect = new Rect(BotLeft.x, UI.screenHeight - BotLeft.y - num, 999f, 999f); var num2 = Mathf.RoundToInt(Find.CurrentMap.glowGrid.GameGlowAt(c) * 100f); var glowStrings = Traverse.Create(__instance).Field("glowStrings").GetValue<string[]>(); Widgets.Label(rect, glowStrings[num2]); num += 19f; rect = new Rect(BotLeft.x, UI.screenHeight - BotLeft.y - num, 999f, 999f); var terrain = c.GetTerrain(Find.CurrentMap); //string SpeedPercentString = Traverse.Create(__instance).Method("SpeedPercentString", (float)terrain.pathCost).GetValue<string>(); //TerrainDef cachedTerrain = Traverse.Create(__instance).Field("cachedTerrain").GetValue<TerrainDef>(); _ = Traverse.Create(__instance).Field("cachedTerrainString").GetValue<string>(); //if (terrain != cachedTerrain) //{ var fertNum = Find.CurrentMap.fertilityGrid.FertilityAt(c); string str = fertNum <= 0.0001 ? TaggedString.Empty : " " + "FertShort".Translate() + " " + fertNum.ToStringPercent(); string cachedTerrainString = terrain.LabelCap + (terrain.passability == Traversability.Impassable ? null : " (" + "WalkSpeed".Translate(SpeedPercentString(terrain.pathCost) + str + ")")); //cachedTerrain = terrain; //} Widgets.Label(rect, cachedTerrainString); num += 19f; var zone = c.GetZone(Find.CurrentMap); if (zone != null) { rect = new Rect(BotLeft.x, UI.screenHeight - BotLeft.y - num, 999f, 999f); var label = zone.label; Widgets.Label(rect, label); num += 19f; } var depth = Find.CurrentMap.snowGrid.GetDepth(c); if (depth > 0.03f) { rect = new Rect(BotLeft.x, UI.screenHeight - BotLeft.y - num, 999f, 999f); var snowCategory = SnowUtility.GetSnowCategory(depth); string label2 = SnowUtility.GetDescription(snowCategory) + " (" + "WalkSpeed".Translate( SpeedPercentString(SnowUtility.MovementTicksAddOn(snowCategory))) + ")"; Widgets.Label(rect, label2); num += 19f; } var thingList = c.GetThingList(Find.CurrentMap); foreach (var thing in thingList) { if (thing.def.category == ThingCategory.Mote) { continue; } rect = new Rect(BotLeft.x, UI.screenHeight - BotLeft.y - num, 999f, 999f); var labelMouseover = thing.LabelMouseover; Widgets.Label(rect, labelMouseover); num += 19f; } var roof = c.GetRoof(Find.CurrentMap); if (roof != null) { rect = new Rect(BotLeft.x, UI.screenHeight - BotLeft.y - num, 999f, 999f); Widgets.Label(rect, roof.LabelCap); } GUI.color = Color.white; return false; } // RimWorld.FertilityGrid public static void CalculateFertilityAt(FertilityGrid __instance, IntVec3 loc, ref float __result) { var map = Traverse.Create(__instance).Field("map").GetValue<Map>(); if (!(map.GetComponent<MapComponent_FertilityMods>().Get is MapComponent_FertilityMods comp)) { return; } if (comp.ActiveCells.Contains(loc)) { __result *= 2; } } // RimWorld.PawnUtility public static void IsTravelingInTransportPodWorldObject_PostFix(Pawn pawn, ref bool __result) { __result = __result || ThingOwnerUtility.AnyParentIs<ActiveDropPodInfo>(pawn); } //RenderPawnAt_PostFix // Verse.PawnRenderer public static void DrawAt_PostFix(Pawn_DrawTracker __instance, Vector3 loc) { var pawn = (Pawn) AccessTools.Field(typeof(Pawn_DrawTracker), "pawn").GetValue(__instance); if (!(pawn?.GetComp<CompTransmogrified>() is CompTransmogrified {IsTransmogrified: true} compTrans) || !pawn.Spawned) { return; } var matSingle = CultsDefOf.Cults_TransmogAura.graphicData.Graphic.MatSingle; var angle = pawn.Rotation.AsAngle + (compTrans.Hediff.UndulationTicks * 100); var xCap = pawn.kindDef.lifeStages[0].bodyGraphicData.drawSize.x + 0.5f; var zCap = pawn.kindDef.lifeStages[0].bodyGraphicData.drawSize.y + 0.5f; var x = pawn.kindDef.lifeStages[0].bodyGraphicData.drawSize.x; var z = pawn.kindDef.lifeStages[0].bodyGraphicData.drawSize.y; var drawX = Mathf.Clamp((x + compTrans.Hediff.UndulationTicks) * compTrans.Hediff.graphicDiv, 0.01f, xCap); var drawY = AltitudeLayer.Terrain.AltitudeFor(); var drawZ = Mathf.Clamp((z + compTrans.Hediff.UndulationTicks) * compTrans.Hediff.graphicDiv, 0.01f, zCap); var s = new Vector3(drawX, drawY, drawZ); Matrix4x4 matrix = default; matrix.SetTRS(loc, Quaternion.AngleAxis(angle, Vector3.up), s); Graphics.DrawMesh(MeshPool.plane10Back, matrix, matSingle, 0); } // RimWorld.GenLabel public static void BestKindLabel_PostFix(Pawn pawn, bool mustNoteGender, bool mustNoteLifeStage, bool plural, int pluralCount, ref string __result) { if (pawn?.GetComp<CompTransmogrified>() is CompTransmogrified {IsTransmogrified: true}) { __result = "Cults_Monstrous".Translate(__result); } } public static void get_BodySize_PostFix(Pawn __instance, ref float __result) { if (__instance?.GetComp<CompTransmogrified>() is CompTransmogrified {IsTransmogrified: true}) { __result *= 3; } } public static void get_HealthScale_PostFix(Pawn __instance, ref float __result) { if (__instance?.GetComp<CompTransmogrified>() is CompTransmogrified {IsTransmogrified: true}) { __result *= 3; } } public static void InitializeComps_PostFix(ThingWithComps __instance) { if (!(__instance is Pawn p)) { return; } if (p.RaceProps == null || !p.RaceProps.Animal) { return; } var thingComp = (ThingComp) Activator.CreateInstance(typeof(CompTransmogrified)); thingComp.parent = __instance; var comps = AccessTools.Field(typeof(ThingWithComps), "comps").GetValue(__instance); ((List<ThingComp>) comps)?.Add(thingComp); thingComp.Initialize(null); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/ShubNiggurath/Hediff_Transmogrified.cs using System.Linq; using System.Text; using UnityEngine; using Verse; namespace CultOfCthulhu { public class Hediff_Transmogrified : Hediff_Implant { public static float tickMax = 2f; public static bool tickUp = true; public static int tickRate = 8; public float graphicDiv = 0.75f; public float UndulationTicks { get; set; } = 0.01f; public override string TipStringExtra { get { var s = new StringBuilder(); s.Append(base.TipStringExtra); s.AppendLine("Cults_Trans_HI_Body".Translate("300%")); s.AppendLine("Cults_Trans_HI_Health".Translate("300%")); return s.ToString(); } } public override bool ShouldRemove => !pawn.TryGetComp<CompTransmogrified>().IsTransmogrified; public override void Tick() { if (Part == null) { Part = pawn.health.hediffSet.GetNotMissingParts() .FirstOrDefault(x => x.def == pawn.RaceProps.body.corePart.def); } if (Find.TickManager.TicksGame % tickRate != 0) { return; } if (tickUp) { UndulationTicks += 0.01f; } else { UndulationTicks -= 0.01f; } if (UndulationTicks > tickMax) { tickUp = false; } else if (UndulationTicks <= 0.01f) { tickUp = true; } UndulationTicks = Mathf.Clamp(UndulationTicks, 0.01f, tickMax); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Spells/Dagon/Building_LandedShip.cs using System.Collections.Generic; using System.Linq; using System.Text; using Cthulhu; using RimWorld; using Verse; using Verse.AI.Group; using Verse.Sound; namespace CultOfCthulhu { internal class Building_LandedShip : Building { private static readonly HashSet<IntVec3> reachableCells = new HashSet<IntVec3>(); protected int age; private Lord lord; public float pointsLeft = 300f; public override void SpawnSetup(Map map, bool bla) { base.SpawnSetup(map, bla); TrySpawnMadSailors(); } public override void ExposeData() { base.ExposeData(); Scribe_Values.Look(ref pointsLeft, "pointsLeft"); Scribe_Values.Look(ref age, "age"); Scribe_References.Look(ref lord, "defenseLord"); } public override string GetInspectString() { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine(base.GetInspectString()); stringBuilder.AppendLine("AwokeDaysAgo".Translate( age.TicksToDays().ToString("F1") )); return stringBuilder.ToString(); } public override void Tick() { base.Tick(); age++; } private void TrySpawnMadSailors() { var lordList = new List<Pawn>(); var faction = Find.FactionManager.FirstFactionOfDef(CultsDefOf.Cults_Sailors); Utility.DebugReport(faction.ToString()); //Log.Message("Building_LandedShip LordJob_DefendPoint"); var lordJob = new LordJob_DefendPoint(Position); if (pointsLeft <= 0f) { return; } if (lord == null) { lord = LordMaker.MakeNewLord(faction, lordJob, Map, lordList); } while (pointsLeft > 0f) { if (!(from cell in GenAdj.CellsAdjacent8Way(this) where cell.Walkable(Map) select cell).TryRandomElement(out var center)) { continue; } var request = new PawnGenerationRequest(CultsDefOf.Cults_Sailor, faction, PawnGenerationContext.NonPlayer, Map.Tile, false, false, false, false, true, true, 20f, false, true, true, false, false, false, false, false, 0, null, 0); var pawn = PawnGenerator.GeneratePawn(request); if (!GenPlace.TryPlaceThing(pawn, center, Map, ThingPlaceMode.Near)) { continue; } if (pawn.GetLord() != null) { pawn.GetLord().Cleanup(); pawn.GetLord().CurLordToil.Cleanup(); pawn.GetLord().LordJob.Cleanup(); } lord.AddPawn(pawn); pointsLeft -= pawn.kindDef.combatPower; Utility.ApplySanityLoss(pawn, 1f); //Find.WorldPawns.PassToWorld(pawn, PawnDiscardDecideMode.Discard); } pointsLeft = 0f; SoundDefOf.PsychicPulseGlobal.PlayOneShotOnCamera(); } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Interactions/InteractionWorker_SpreadInsanityFailure.cs using RimWorld; using UnityEngine; using Verse; namespace CultOfCthulhu { // <summary> // Hawtcrab insanity spread social interaction mechanic // Pawn encounters Strange Thing ==> Aquires insanity ==> Talks to other Pawn // // Then either: // Reacts positively ===> Pawn loses insanity ==> other Pawn gains smaller amount of insanity // Reacts negatively ===> Pawn gains insanity ==> other Pawn does not gain insanity // </summary> public class InteractionWorker_SpreadInsanityFailure : InteractionWorker { //Almost three times the chance private const float BaseSelectionWeight = 0.8f; //How great the effect is on the sanity values. public static readonly FloatRange SANITY_IMPACT = new FloatRange(0.15f, 0.2f); public override float RandomSelectionWeight(Pawn initiator, Pawn recipient) { //We need two individuals that are part of the colony if (!initiator.IsColonist || !initiator.IsPrisoner) { return 0f; } if (!recipient.IsColonist || !recipient.IsPrisoner) { return 0f; } //If they are sleeping, don't do this. if (initiator.jobs.curDriver.asleep) { return 0f; } if (recipient.jobs.curDriver.asleep) { return 0f; } //We need them to have different mindsets. //Normally, it's double chance of happening. var math = 2f; //Subtract the social skill of the initiator by 10. //A social skill of 20 will return a 0 chance of this happening. math -= (float) initiator.skills.GetSkill(SkillDefOf.Social).Level / 10; //Throw in random chance. math += Rand.Range(-0.5f, 0.5f); //Especially if they don't like the other guy. return initiator.relations.OpinionOf(recipient) < 15 ? Mathf.Clamp(math, 0f, 2f) : 0f; } } }<file_sep>/Source/CultOfCthulhu/NewSystems/Worship/CompWorshipCaller.cs using System.Collections.Generic; using Verse; using Verse.AI; using Verse.Sound; namespace CultOfCthulhu { public class CompWorshipCaller : ThingComp { public CompProperties_WorshipCaller Props => props as CompProperties_WorshipCaller; public Building_SacrificialAltar Altar => (Building_SacrificialAltar) GenClosest.ClosestThingReachable( parent.PositionHeld, parent.Map, ThingRequest.ForGroup(ThingRequestGroup.BuildingArtificial), PathEndMode.ClosestTouch, TraverseMode.ByPawn, 9999, x => x is Building_SacrificialAltar); public IEnumerable<IntVec3> CellsInRange => GenRadial.RadialCellsAround(parent.Position, Props.rangeRadius, true); public virtual void Use(bool forced) { Props.hitSound.PlayOneShot(new TargetInfo(parent.Position, parent.Map)); Building_SacrificialAltar.GetWorshipGroup(Altar, CellsInRange, forced); } public override void PostDrawExtraSelectionOverlays() { base.PostDrawExtraSelectionOverlays(); GenDraw.DrawRadiusRing(parent.Position, Props.rangeRadius); } public override IEnumerable<Gizmo> CompGetGizmosExtra() { foreach (var g in base.CompGetGizmosExtra()) { yield return g; } } } }
f6bc8440ed0be7b960761a681daff1823aa82b06
[ "Markdown", "C#", "Text" ]
139
C#
emipa606/CallofCthulhuCults
1d5f2824fd8bee700430695c08f326d2bfb386ec
a881b96077de87ebd4236402ba59e7cc2157e5f0
refs/heads/main
<repo_name>chaturdev/hotloading<file_sep>/index.js const fs=require('fs'); const path = require('path'); const async=require('async'); //joining path of directory const directoryPath = path.join(__dirname, 'plugin'); //to keep existing file in json var __existingFiles=[]; let i=0; setInterval(async()=>{ ifFirstTime=false; console.log(ifFirstTime); await checkIfFileInPath(); try{ doSomething(); async.eachSeries(__existingFiles,(fileName,cb)=>{ var cls=require(`./plugin/${fileName}`); var output=cls.callFunction(); console.log(output); return cb(); }) }catch(ex){ console.log(ex); } },20*1000) function doSomething () { console.log("here i m doing something"); } /** * check if new file exist in path */ function checkIfFileInPath(){ return new Promise((resolve,reject)=>{ try{ fs.readdir(directoryPath, function (err, files) { //handling error if (err) { return console.log('Unable to scan directory: ' + err); } //listing all files using forEach files.forEach(function (file) { // Do whatever you want to do with the file __existingFiles.push(file); }); resolve(); }); }catch(ex){ console.log(ex); reject(); } }) } //passsing directoryPath and callback function <file_sep>/README.md # hotloading Reload code in existing running system at run time What ever file you will put in plugin folder that will be attached to your project at run time. This can help specific use cases where faster deployment is needed.
b670da551c7fbe41a6e2f530e60770c6a7201740
[ "JavaScript", "Markdown" ]
2
JavaScript
chaturdev/hotloading
6e4de7a6bc2705886c62493f622318f31bc77be1
6e4bb330520d77b8fc2e81d4ba1b39186a8d67d0
refs/heads/main
<file_sep>from china_ui import * from country_ui import * from main_ui import * import sys #render_dayly_chart('05-01-2020','05-01-2021','India') #print(list(flat_country_data('01-01-2021','China'))) if __name__ == '__main__': app = QApplication(sys.argv) MainWindow = QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())<file_sep>import pandas as pd import datetime # 日期字符串拼接 def date_stitch(t_date): root_directory = 'DOVID-19_main_data/COVID-19-master/csse_covid_19_data/csse_covid_19_daily_reports/' date = str(t_date) suffix = '.csv' file_directory = root_directory + date + suffix return file_directory # 日期分割 def split_date(t_date): date = str(t_date).split('-') return date # 读取指定日期的csv数据文件 def get_date_data(t_date): data = pd.read_csv(date_stitch(t_date)) return data # 读取日期段的csv数据文件并处理 def get_date_period_data(begin_date, end_date, t_country): begin = datetime.date(int(split_date(begin_date)[2]), int(split_date(begin_date)[0]), int(split_date(begin_date)[1])) end = datetime.date(int(split_date(end_date)[2]), int(split_date(end_date)[0]), int(split_date(end_date)[1])) d = begin delta = datetime.timedelta(days=1) total_data = [] country = t_country while d <= end: date = str(d.strftime("%m-%d-%Y")) total_data.append(flat_country_data(date,country)) d += delta return total_data # 读取制定日期的某国家的疫情数据 def flat_country_data(t_date, t_country): total = get_date_data(t_date) country = [] provence = [] confirmed = [] deaths = [] recovered = [] active = [] all_confirmed = 0 all_deaths = 0 all_recovered = 0 all_active = 0 for i in total['Country_Region']: country.append(i) for i in total['Province_State']: provence.append(i) for i in total['Confirmed']: confirmed.append(i) for i in total['Deaths']: deaths.append(i) for i in total['Recovered']: recovered.append(i) for i in total['Active']: active.append((i)) t_ls = zip(country, provence, confirmed, deaths, recovered, active) tt_ls = get_country_data(t_ls, t_country) temp = tt_ls[0] all_country = temp[0] for i in tt_ls: all_confirmed = all_confirmed + float(i[2]) all_deaths = all_deaths + float(i[3]) all_recovered = all_recovered + float(i[4]) all_active = all_active + float(i[5]) ls = [all_country, t_date, all_confirmed, all_deaths, all_recovered, all_active] return ls # 读取某国家的疫情数据 def get_country_data(t_list, t_country): t_ls = t_list ls = [] for i in t_ls: if str(i[0]) == str(t_country): ls.append(i) return ls # 将数据扁平化为列表 def flat_total_data(t_date): total = get_date_data(t_date) country = [] provence = [] confirmed = [] for i in total['Country_Region']: country.append(i) for i in total['Province_State']: provence.append(i) for i in total['Confirmed']: confirmed.append(i) ls = zip(country, provence, confirmed) return ls # 读取中国各省份疫情数据 def deal_china_data(t_date): ls = flat_total_data(t_date) t_ls = [] c_ls = [] pinyin = {'Anhui': '安徽', 'Beijing': '北京', 'Chongqing': '重庆', 'Fujian': '福建', 'Gansu': '甘肃', 'Guangdong': '广东', 'Guangxi': '广西', 'Guizhou': '贵州', 'Hainan': '海南', 'Hebei': '河北', 'Heilongjiang': '黑龙江', 'Henan': '河南', 'Hong Kong': '香港', 'Hubei': '湖北', 'Hunan': '湖南', 'Inner Mongolia': '内蒙古', 'Jiangsu': '江苏', 'Jiangxi': '江西', 'Jilin': '吉林', 'Liaoning': '辽宁', 'Macau': '澳门', 'Ningxia': '宁夏', 'Qinghai': '青海', 'Shaanxi': '陕西', 'Shandong': '山东', 'Shanghai': '上海', 'Shanxi': '山西', 'Sichuan': '四川', 'Tianjin': '天津', 'Tibet': '西藏', 'Xinjiang': '新疆', 'Yunnan': '云南', 'Zhejiang': '浙江', 'Unknown': '曾母暗沙'} for i in ls: if 'China' in i: t_ls.append(list(i)) for i in t_ls: temp = i[1] temp = pinyin.get(temp) i[1] = temp c_ls.append(i[1:3]) return c_ls <file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'china_ui.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWebEngineWidgets import * from PyQt5.QtCore import * from graphics_drawing import * class Ui_china_ui(object): def setupUi(self, china_ui): china_ui.setObjectName("china_ui") china_ui.resize(1000, 600) self.centralwidget = QtWidgets.QWidget(china_ui) self.centralwidget.setObjectName("centralwidget") self.dateEdit = QtWidgets.QDateEdit(self.centralwidget) self.dateEdit.setGeometry(QtCore.QRect(40, 10, 110, 22)) self.dateEdit.setObjectName("dateEdit") self.pushButton1 = QtWidgets.QPushButton(self.centralwidget) self.pushButton1.setGeometry(QtCore.QRect(160, 10, 75, 23)) self.pushButton1.setObjectName("get_time") self.pushButton2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton2.setGeometry(QtCore.QRect(245, 10, 75, 23)) self.pushButton2.setObjectName("refresh") self.refreshlebal = QtWidgets.QLabel(self.centralwidget) self.refreshlebal.setGeometry((QtCore.QRect(350,10,300,23))) self.refreshlebal.setObjectName("refreshlabal") self.browser = QWebEngineView(self.centralwidget) self.browser.setGeometry(QtCore.QRect(40, 40, 900, 500)) self.browser.load(QUrl('file:///H:/PYTHON/PythonWork/country.html')) self.browser.setObjectName("htmlwindow") china_ui.setCentralWidget(self.centralwidget) self.pushButton1.clicked.connect(lambda:self.get_time()) self.pushButton2.clicked.connect(lambda:self.refresh_map()) self.retranslateUi(china_ui) QtCore.QMetaObject.connectSlotsByName(china_ui) def retranslateUi(self, china_ui): _translate = QtCore.QCoreApplication.translate china_ui.setWindowTitle(_translate("china_ui", "中国疫情数据可视化地图")) self.pushButton1.setText(_translate("china_ui", "修改时间")) self.pushButton2.setText(_translate("china_ui", "刷新")) self.refreshlebal.setText(_translate("china_ui","请等候地图加载")) def get_time(self): datetime = self.dateEdit.dateTime() time = datetime.toString("MM-dd-yyyy") render_china_map_chart(str(time)) self.refreshlebal.setText("加载完毕,请刷新") def refresh_map(self): self.browser.load(QUrl('file:///H:/PYTHON/PythonWork/country.html')) self.refreshlebal.setText("请等候地图加载") <file_sep># PythonWork-COVID-19 Python大作业 1、数据暂时缺失南海诸岛与台湾省数据 2、当输入的时间越界时,程序崩溃闪退 <file_sep>from pyecharts.charts import Map from pyecharts.charts import Line from pyecharts import options from data_process import * import math # 绘制中国疫情数据图 def render_china_map_chart(t_date): province_data = deal_china_data(t_date) map_country = Map() map_country.set_global_opts(title_opts=options.TitleOpts(title="中国疫情图-确诊人数"), visualmap_opts=options.VisualMapOpts(is_piecewise=True, pieces=[ {"min": 1000, "label": '>1000人', "color": "#6F171F"}, # 不指定 max,表示 max 为无限大(Infinity)。 {"min": 500, "max": 1000, "label": '500-1000人', "color": "#C92C34"}, {"min": 100, "max": 499, "label": '100-499人', "color": "#E35B52"}, {"min": 10, "max": 99, "label": '10-99人', "color": "#F39E86"}, {"min": 1, "max": 9, "label": '1-9人', "color": "#FDEBD0"}])) # 将数据导入地图内,地图模式选择china map_country.add("确诊", list(province_data), maptype="china") # 生成html文件 map_country.render("country.html") def render_dayly_chart(begin_date, end_date, t_country, methods): date = [] t_confirmed = [] t_deaths = [] t_recovered = [] confirmed = [] deaths = [] recovered = [] data = get_date_period_data(begin_date, end_date, t_country) for i in data: date.append(i[1]) t_confirmed.append(i[2]) t_deaths.append(i[3]) t_recovered.append(i[4]) if methods == "普通坐标": confirmed = t_confirmed deaths = t_deaths recovered = t_recovered else: for i in t_confirmed: confirmed.append(math.log(i)) for i in t_deaths: deaths.append(math.log(i)) for i in t_recovered: recovered.append(math.log(i)) line = Line() line.add_xaxis(date) line.add_yaxis("确诊人数", confirmed, is_smooth = True) line.add_yaxis("死亡人数", deaths, is_smooth = True) line.add_yaxis("恢复人数", recovered, is_smooth = True) line.set_global_opts(title_opts=options.TitleOpts(title = "{}疫情数据统计图".format(t_country))) line.set_series_opts(label_opts=options.LabelOpts(is_show=False)) line.render("line.html") <file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'country_ui.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWebEngineWidgets import * from PyQt5.QtCore import * from graphics_drawing import * class Ui_country_ui(object): def setupUi(self, country_ui): country_ui.setObjectName("country_ui") country_ui.resize(1000, 600) self.centralwidget = QtWidgets.QWidget(country_ui) self.centralwidget.setObjectName("centralwidget") self.dateEdit = QtWidgets.QDateEdit(self.centralwidget) self.dateEdit.setGeometry(QtCore.QRect(20, 10, 110, 22)) self.dateEdit.setObjectName("dateEdit") self.dateEdit_2 = QtWidgets.QDateEdit(self.centralwidget) self.dateEdit_2.setGeometry(QtCore.QRect(160, 10, 110, 22)) self.dateEdit_2.setObjectName("dateEdit_2") self.comboBox = QtWidgets.QComboBox(self.centralwidget) self.comboBox.setGeometry(QtCore.QRect(290, 10, 69, 22)) self.comboBox.setObjectName("comboBox") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.statistical_methods = QtWidgets.QComboBox(self.centralwidget) self.statistical_methods.setGeometry(QtCore.QRect(380, 10, 75, 22)) self.statistical_methods.setObjectName("statistical_methods") self.statistical_methods.addItem("") self.statistical_methods.addItem("") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(470, 10, 75, 23)) self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(560, 10, 75, 23)) self.pushButton_2.setObjectName("pushButton_2") self.refreshlebal = QtWidgets.QLabel(self.centralwidget) self.refreshlebal.setGeometry((QtCore.QRect(690,10,300,23))) self.browser = QWebEngineView(self.centralwidget) self.browser.setGeometry(QtCore.QRect(40, 40, 900, 500)) self.browser.load(QUrl('http://localhost:63342/main.py/line.html?_ijt=6rfathn5e84vqqcf2r8etbp83q')) self.browser.setObjectName("htmlwindow") country_ui.setCentralWidget(self.centralwidget) self.pushButton.clicked.connect(lambda :self.get_time()) self.pushButton_2.clicked.connect(lambda:self.refresh_map()) self.retranslateUi(country_ui) QtCore.QMetaObject.connectSlotsByName(country_ui) def retranslateUi(self, country_ui): _translate = QtCore.QCoreApplication.translate country_ui.setWindowTitle(_translate("country_ui", "国家疫情数据统计折线图")) self.comboBox.setItemText(0, _translate("country_ui", "China")) self.comboBox.setItemText(1, _translate("country_ui", "US")) self.comboBox.setItemText(2, _translate("country_ui", "India")) self.comboBox.setItemText(3, _translate("country_ui", "France")) self.comboBox.setItemText(4, _translate("country_ui", "Russia")) self.comboBox.setItemText(5, _translate("country_ui", "Brazil")) self.statistical_methods.setItemText(0, _translate("country_ui", "普通坐标")) self.statistical_methods.setItemText(1, _translate("country_ui", "对数坐标")) self.pushButton.setText(_translate("country_ui", "修改数据")) self.pushButton_2.setText(_translate("country_ui", "刷新")) self.refreshlebal.setText(_translate("china_ui", "请等候地图加载")) def get_time(self): first_time = self.dateEdit.dateTime() end_time = self.dateEdit_2.dateTime() country = self.comboBox.currentText() methods = self.statistical_methods.currentText() f_time = first_time.toString("MM-dd-yyyy") e_time = end_time.toString("MM-dd-yyyy") render_dayly_chart(str(f_time), str(e_time), str(country), str(methods)) self.refreshlebal.setText("加载完毕,请刷新") def refresh_map(self): self.browser.load(QUrl('http://localhost:63342/main.py/line.html?_ijt=6rfathn5e84vqqcf2r8etbp83q')) self.refreshlebal.setText("请等候地图加载") <file_sep>''' Created on 13-May-2018 @author: dgraja ''' from PyQt5 import QtWidgets class ToggleButton(QtWidgets.QPushButton): ''' A Simple On / Off button which separate text and icon values for on and off states. This class extends QPushButton. So use it like a pushbutton, with a simple enhancement of two sets of text and icon values. checked = True means On state checked = False means Off state usage: self.btn_play = ToggleButton(text_on="Play", icon_on="play.png", text_off="Pause", icon_off="pause.png", checked=False, parent=self) ''' def __init__(self, text_on="", icon_on=None, text_off="", icon_off=None, checked=False, parent=None): QtWidgets.QPushButton.__init__(self, parent) self.setCheckable(True) self.toggle_on = True self.icon_off = icon_off self.text_off = text_off self.icon_on = icon_on self.text_on = text_on self.setChecked(checked) self.update_ui(checked) self.clicked.connect(self.on_click) def configure(self, text_on, icon_on, text_off, icon_off, checked=False): self.text_on = text_on self.text_off = text_off self.icon_on = icon_on self.icon_off = icon_off self.setChecked(checked) self.update_ui(checked) def update_ui(self, checked=False): if checked: self.setText(self.text_on) if self.icon_on: self.setIcon(self.icon_on) else: self.setText(self.text_off) if self.icon_off: self.setIcon(self.icon_off) def on_click(self, checked): try: self.update_ui(checked) except Exception as e: print (e) if __name__ == '__main__': pass<file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'main_ui.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets import sys from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.QtCore import * from PyQt5.QtWidgets import * from country_ui import * from china_ui import * import time class Ui_window(object): app1 = QApplication(sys.argv) window1 = QMainWindow() ui1 = Ui_china_ui() ui1.setupUi(window1) app2 = QApplication(sys.argv) window2 = QMainWindow() ui2 = Ui_country_ui() ui2.setupUi(window2) def setupUi(self, window): window.setObjectName("window") window.resize(323, 229) self.label = QtWidgets.QLabel(window) self.label.setGeometry(QtCore.QRect(10, 30, 301, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(16) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.china_button = QtWidgets.QPushButton(window) self.china_button.setGeometry(QtCore.QRect(30, 150, 111, 51)) self.china_button.setObjectName("china_button") self.country_button = QtWidgets.QPushButton(window) self.country_button.setGeometry(QtCore.QRect(180, 150, 111, 51)) self.country_button.setObjectName("country_button") self.label_2 = QtWidgets.QLabel(window) self.label_2.setGeometry(QtCore.QRect(30, 100, 111, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) self.label_2.setFont(font) self.label_2.setAlignment(QtCore.Qt.AlignCenter) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(window) self.label_3.setGeometry(QtCore.QRect(180, 100, 111, 31)) font = QtGui.QFont() font.setFamily("微软雅黑") font.setPointSize(10) self.label_3.setFont(font) self.label_3.setAlignment(QtCore.Qt.AlignCenter) self.label_3.setObjectName("label_3") self.china_button.clicked.connect(lambda :self.show_china_ui()) self.country_button.clicked.connect(lambda :self.show_country_ui()) self.retranslateUi(window) QtCore.QMetaObject.connectSlotsByName(window) def show_china_ui(self): self.window1.show() self.app1.exec() def show_country_ui(self): self.window2.show() self.app2.exec() def retranslateUi(self, window): _translate = QtCore.QCoreApplication.translate window.setWindowTitle(_translate("window", "window")) self.label.setText(_translate("window", "疫情数据可视化分析软件")) self.china_button.setText(_translate("window", "点击查看")) self.country_button.setText(_translate("window", "点击查看")) self.label_2.setText(_translate("window", "中国疫情地图")) self.label_3.setText(_translate("window", "疫情数据折线图")) if __name__ == '__main__': app0 = QApplication(sys.argv) Window0 = QMainWindow() ui0 = Ui_window() ui0.setupUi(Window0) Window0.show() sys.exit(app0.exec_())
92ab61674153ab01b8aa01caac952511ca95392d
[ "Markdown", "Python" ]
8
Python
MuQingWen/PythonWork-COVID-19
aee3f3dc364dd66326bf32c27159dd1ac021fa4b
9dca424d8f606a0f2dc4c409d2f8937eff6009e5
refs/heads/master
<file_sep># U10316040_1032JavaProject 1032JavaProject = 撲克牌遊戲 <file_sep> import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.Timer; public class DecideKing extends JDialog { private JLabel king; private JTextArea message; private String[] suitKing = {"梅花 ", "方塊 ","愛心 ", "黑桃 "}; public static boolean isPass[] = new boolean[4]; public static int currentKing = -1; private boolean isChoose = false; private Timer[] ComDeKing = new Timer[3]; private static Timer wait; private static int whoRound = 0; private int whoWin; public static int DunNum[] = new int[2]; private JPanel panel = new JPanel(); JButton[] King = new JButton[4]; public DecideKing(JFrame frame){ super(frame, "叫牌", true); setBounds(350,100,500,400); //setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); /* for(int i=0; i<13; i++){ System.out.println(PlayGame.getComHandcard(3)[i]); }*/ panel.setBounds(0, 0, 500, 400); panel.setLayout(null); add(panel); king = new JLabel("123"); king.setBounds(340,10,200,100); panel.add(king); message = new JTextArea(); message.setBounds(10,10,300,200); panel.add(message); for(int com = 1;com <=3; com++){ comDeking(com); } wait = new Timer(700,new ActionListener(){ public void actionPerformed(ActionEvent e){ if(isThreePass(isPass)){ for(int i=0; i<4; i++) PlayGame.Order[i] = (whoRound + i) % 4; whoWin = whoRound; PlayGame.WhoFirstPlay((whoRound + 1) % 4); PlayGame.king = currentKing % 4; int level = currentKing/4+1; JOptionPane.showMessageDialog(null, "王: " + level + " " + suitKing[currentKing % 4] + "\n勝利條件:玩家 電腦2 " + (DunNum[0] = whoWin == 0 || whoWin == 3? (7 + level - 1) : (7 - level + 1)) + "敦" + "\n 電腦1 電腦3 " + (DunNum[1] = whoWin == 1 || whoWin == 4? (7 + level - 1) : (7 - level + 1)) + "敦" ); dispose(); PlayGame.ComplayCard.start(); wait.stop(); } if(isChoose){ whoRound = (whoRound + 1) % 4; king.setText("目前的王:" + (currentKing/4+1) + suitKing[currentKing % 4]); isChoose = false; if(whoRound != 0){ if(!isPass[whoRound]){ wait.stop(); ComDeKing[whoRound-1].start(); } else{ isChoose = true; } } else{ if(!isPass[whoRound]){ removeButton(); panel.repaint(); decideKing(); } else{ isChoose = true; } } } } }); wait.start(); decideKing(); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setVisible(true); } private void decideKing(){ wait.stop(); for(int i=0; i<4 && !isPass[0] ; i++){ King[i] = new JButton(currentKing > 0 && i == 3? "Pass" : (currentKing+i+1) /4 + 1 + " " + suitKing[(currentKing + i + 1)%4]); King[i].setBounds(350,200+40*i,100,30); King[i].setFont(new Font("Microsoft YaHei",Font.BOLD,17)); kingListener(King[i], currentKing > 0 && i == 3? currentKing : currentKing + i + 1); panel.add(King[i]); } } private void kingListener(JButton choice, int newKing){ choice.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ removeButton(); if(currentKing != newKing){ currentKing = newKing; isChoose = true; //whoRound = (whoRound + 1) % 4; king.setText("目前的王:" + (currentKing/4+1) + suitKing[currentKing % 4]); // System.out.print(currentKing); wait.start(); //decideKing(); } else{ isPass[0] = true; JLabel pass = new JLabel("Pass"); pass.setFont(new Font("Microsoft YaHei",Font.BOLD,25)); pass.setBounds(340,200,200,100); panel.add(pass); isChoose = true; removeButton(); repaint(); wait.start(); } } }); } private boolean isThreePass(boolean[] isDe){ int count = 0; for(int i =0;i<4; i++){ if(isDe[i]) count++; } return (count == 3); } private void comDeking(int com){ ComDeKing[com-1] = new Timer(1500,new ActionListener(){ public void actionPerformed(ActionEvent e){ currentKing = ComAI.ComDeKing(com, PlayGame.getComHandcard(com), currentKing); //whoRound = (whoRound + 1) % 4; // System.out.print(currentKing); // System.out.println("\ncom " + com + " "); isChoose = true; // System.out.println("Pass:" + isPass[com]); // System.out.println("com " + com+ " King:"+ComAI.kingColor); message.setFont(new Font("Microsoft YaHei",Font.BOLD,30)); message.setText("\n\n" + (isPass[com] ? "電腦" + com +" Pass" : "電腦" + com + " " + (currentKing/4+1) + suitKing[currentKing % 4])); ComDeKing[com-1].stop(); wait.start(); } }); } private void removeButton(){ for(int i=0; i<King.length; i++){ panel.remove(King[i]); } } private class KingPanel{ } } <file_sep>import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.Timer; public class GameFrame extends JFrame { private static ReadyPlay readyPlay = new ReadyPlay(); public static PlayGame playGame = new PlayGame(); private static GameFrame frame; GameFrame(){ setBounds(140,0,800,730); setTitle("Bridge game"); getContentPane().setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(readyPlay); checkBegin(); // setBackground(); } public static void main(String[] args) { frame = new GameFrame(); frame.setVisible(true); } public static GameFrame getFrame(){ return frame; } public static PlayGame getplayGame(){ return playGame; } private void checkBegin(){ Timer timer = new Timer(1000,new ActionListener(){ public void actionPerformed(ActionEvent e){ if(ReadyPlay.isBegin()){ remove(readyPlay); } } }); timer.start(); } private void setBackground(){ Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("card/blue.png")); image = image.getScaledInstance(800, 730, Image.SCALE_DEFAULT); JLabel background = new JLabel(new ImageIcon(image)); background.setBounds(0, 0, 800, 730); add(background); } } <file_sep>import java.awt.Image; import java.awt.Toolkit; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JLabel; public class ComAI { public static int[][] ColorNum = new int[4][4]; public static int[] ColorPoint = new int[4]; //ArrayList<Integer[]> SuitCards = new ArrayList<Integer[]>(); public static int kingColor; public static int PlayCard[] = new int[4]; private static int[] playcard; public static int ComDeKing(int com, int comhandcard[], int currentKing){ int point = 0; for(int i=0; i<13; i++){ ColorNum[com][comhandcard[i]/13]++; switch(comhandcard[i] % 13){ case 0: ColorPoint[comhandcard[i]/13]+= 4;break; case 10: ColorPoint[comhandcard[i]/13]+= 1;break; case 11: ColorPoint[comhandcard[i]/13]+= 2;break; case 12: ColorPoint[comhandcard[i]/13]+= 3;break; } } if(MaxColor(ColorNum[com]) <=4){ if(MaxColor(ColorPoint) <=4){ DecideKing.isPass[com] = true; // System.out.println("kingColor: "+ kingColor); return currentKing;//pass } else if(MaxColor(ColorPoint) >4 && MaxColor(ColorPoint)<=10){ if(currentKing < 8){ if(kingColor == currentKing % 4){ DecideKing.isPass[com] = true; } currentKing += (kingColor != currentKing % 4?(kingColor < currentKing % 4? 4-(currentKing % 4-kingColor) : kingColor - currentKing % 4):0); System.out.println("kingColor: "+ kingColor); return currentKing; } else{ DecideKing.isPass[com] = true; // System.out.println("kingColor: "+ kingColor); return currentKing;//pass } } } else if(MaxColor(ColorNum[com]) > 4 && MaxColor(ColorNum[com])<=7){ if(MaxColor(ColorPoint) <=2){ DecideKing.isPass[com] = true; // System.out.println("kingColor: "+ kingColor); return currentKing;//pass } else if(MaxColor(ColorPoint) >2 && MaxColor(ColorPoint) <=6 ){ if(currentKing < 8){ if(kingColor == currentKing % 4){ DecideKing.isPass[com] = true; } currentKing += (kingColor != currentKing % 4?(kingColor < currentKing % 4? 4-(currentKing % 4-kingColor) : kingColor - currentKing % 4):0); System.out.println("kingColor: "+ kingColor); return currentKing; } else{ DecideKing.isPass[com] = true; return currentKing;//pass } } else{ if(kingColor == currentKing % 4){ DecideKing.isPass[com] = true; } if(currentKing < 8) currentKing += (kingColor != currentKing % 4?(kingColor < currentKing % 4? 4-(currentKing % 4-kingColor) : kingColor - currentKing % 4):0); else DecideKing.isPass[com] = true; System.out.println("kingColor: "+ kingColor); return currentKing; } } else { if(kingColor == currentKing % 4){ DecideKing.isPass[com] = true; } if(currentKing < 8) currentKing += (kingColor != currentKing % 4?(kingColor < currentKing % 4? 4-(currentKing % 4-kingColor) : kingColor - currentKing % 4):0); else DecideKing.isPass[com] = true; return currentKing; } /*for(int i=0; i<4; i++){ point += ColorPoint[i]; }*/ /* for(int i=0 ;i<13; i++){ NumOfSuits[comhandcard[i]/4] ++; if(comhandcard[i]%13 > 10){ point += (comhandcard[i]%13-3); } if(comhandcard[i]%13 == 10) point += 4; } for(int i =0; i<4; i++){ if(NumOfSuits[i]>4) break; if(point >=15 && point <=18){ currentKing = 16; return currentKing; } }*/ return currentKing; } //public static void ComPlayCard(int order, int comhandcard[]){ //} public static void Comthink(int order, int suit){ int card; int com = PlayGame.Order[order]; /* int playcard[] = new int[ColorNum[com][suit]]; for(card=0; card<13; card++){ if(PlayGame.getComHandcard(PlayGame.Order[order])[card]/13 == suit){ for(int i=card; i < card + ColorNum[PlayGame.Order[order]][suit]; i++){ playcard[i] = PlayGame.getComHandcard(com)[i]; } break; } } switch(suit){ case 0: PlayMethod(com,SuitableCard(PlayGame.getComHandcard(com),order), kingColor ); case 1: case 2: case 3: }*/ if(PlayGame.currentcard == -1){ PlayMethod(com,SuitableCard(PlayGame.getComHandcard(com),order), kingColor ); return; } if(!PlayGame.isLack(PlayGame.getComHandcard(com), PlayGame.currentcard)){ if(ColorNum[com][suit] != 0) playcard = new int[ColorNum[com][suit]]; for(card = 0; card < 13; card++){ //int playcard = (PlayGame.getComHandcard(PlayGame.Order[order]))[card]; if( PlayGame.getComHandcard(com)[card]/13 == suit){ for(int i=card; i < card + ColorNum[PlayGame.Order[order]][suit]; i++){ playcard[i] = PlayGame.getComHandcard(com)[i]; } break; } } if(order == 0){ if(playcard[ColorNum[com][suit]-1] == 0){ PlayMethod(com,playcard[ColorNum[com][suit]-1], card + ColorNum[com][suit]-1); } else{ PlayMethod(com,MaxColor(playcard), card + kingColor -1); } } else if(order == 2 || order == 3){ if(playcard[ColorNum[com][suit]-1] == 0){ PlayMethod(com,playcard[ColorNum[com][suit]-1], card + ColorNum[com][suit]-1); } else{ PlayMethod(com,SuitableCard(playcard,order), card + kingColor -1); } } else { PlayMethod(com,SuitableCard(playcard,order), card + kingColor -1); } } else{ PlayMethod(com,SuitableCard(PlayGame.getComHandcard(com),order), kingColor); } } private static void PlayMethod(int com,int card,int position){ PlayCard[com] = card; PlayGame.checkWinDun(com, card); PlayGame.currentcard = card; PlayGame.whoRound = (PlayGame.whoRound + 1) % 4; Image image = Toolkit.getDefaultToolkit().getImage(ComAI.class.getResource("card/"+ card +".png")); image = image.getScaledInstance(85, 130, Image.SCALE_DEFAULT); JLabel Card = new JLabel(new ImageIcon(image)); Card.setBounds(350,200,85,130); GameFrame.getplayGame().add(Card); GameFrame.getplayGame().repaint(); PlayGame.getComHandcard(com)[position] = -4; } private static int MaxColor(int... numbers){ int MaxValue = -2; int color = 0; for (color = 0 ; color < numbers.length ; color++) { if (numbers[color] > MaxValue) { MaxValue = numbers[color]; kingColor = color; } } return MaxValue; } private static int SuitableCard(int[] numbers, int order){ int Value = -2; int card = 0; for (card = 0 ; card < numbers.length ; card++) { if (numbers[card] > PlayGame.currentMaxCard(order)) { Value = numbers[card]; kingColor = card; return Value; } } return Value; } }
20ae0064bf179b87d8240f2e71305f2eb7b2a7e6
[ "Markdown", "Java" ]
4
Markdown
U10316040/U10316040_1032JavaProject
32d2a09e3a62e33c186952d0cabc8518dfe3f08c
c3b7aee3992eb44897b47b6f248ee4aead4583f6
refs/heads/master
<file_sep>import React from 'react'; const CryptoList = (props) => { const currencyList = props.cryptoArray.map((currency, index) => { let arrow = ''; if(currency.class === 'green') { arrow = String.fromCharCode(8593); } else if(currency.class === 'red') { arrow = String.fromCharCode(8595); } else { arrow = String.fromCharCode(8596); } return (<li className="lists" key={index}>Country: {currency.currency} <span className="symbol-icon">{currency.symbol} {arrow}</span> || Last Rate: <span className={currency.class}>{currency.last}</span></li>) }); return( <ul className="ul-list">{currencyList}</ul> ) } export default CryptoList;<file_sep>import React, {Component} from 'react'; import CryptoList from './Cryptolist'; import axios from 'axios'; class Crypto extends Component { constructor() { super(); this.state = { currencyList: [], filteredCountries: [] } }; getCurrencyData = () => { console.log('pobieram'); axios.get(`https://blockchain.info/pl/ticker`) .then(res => { const currencyList = res.data; let currentArray = []; let i = 0; for( let key in currencyList) { let newCurrency = currencyList[key]; let prevCurrency = this.state.currencyList[i]; if(prevCurrency !== undefined) { if(prevCurrency.last>newCurrency.last) { newCurrency.class = 'red'; } else if(prevCurrency.last<newCurrency.last) { newCurrency.class = 'green'; } else { newCurrency.class = 'blue'; } } else { newCurrency.class = 'blue'; } newCurrency.currency = key; currentArray.push(currencyList[key]); i++; } this.setState({currencyList: currentArray, filteredCountries: currentArray}); }) } componentDidMount() { this.getCurrencyData(); this.timer = setInterval(this.getCurrencyData, 1000); }; inputChange = () => { let trimValue = this.inputFilter.value.trim().toUpperCase(); console.log(trimValue) let currentCountry = this.state.currencyList; let filteredList = currentCountry.filter(currentPost => { return currentPost.currency.includes(trimValue) }); this.setState({filteredCountries: filteredList}) } render() { return( <div> <div className="input"> <input className="input-element" type="text" placeholder="Wpisz kraj" onChange={this.inputChange} ref={input=>this.inputFilter = input}/> </div> <CryptoList cryptoArray={this.state.filteredCountries}/> </div> )} } export default Crypto;
cdd7276dffffbd0fa5dbeb33fcf7922a7f84606a
[ "JavaScript" ]
2
JavaScript
pawelSowinskiPortfolio/react-kurs_gitcoin
dd549287703ddc8534ce9c745039d3aafdf09314
a804f2e3c2d2306a0844d6ac33a67cc4a563afeb
refs/heads/master
<repo_name>xRouty/Custom_SQL<file_sep>/customvendors.sql /* -- ################################################################################### -- -- ____ __ ____ -- /\ _`\ /\ \__ __ /\ _`\ -- \ \,\L\_\ \ ,_\ __ __ __ /\_\ __ ___\ \ \/\_\ ___ _ __ __ -- \/_\__ \\ \ \/ /\ \/\ \ /'_ `\/\ \ /'__`\ /' _ `\ \ \/_/_ / __`\/\`'__\/'__`\ -- /\ \L\ \ \ \_\ \ \_\ \/\ \L\ \ \ \/\ \L\.\_/\ \/\ \ \ \L\ \/\ \L\ \ \ \//\ __/ -- \ `\____\ \__\\/`____ \ \____ \ \_\ \__/.\_\ \_\ \_\ \____/\ \____/\ \_\\ \____\ -- \/_____/\/__/ `/___/> \/___L\ \/_/\/__/\/_/\/_/\/_/\/___/ \/___/ \/_/ \/____/ -- /\___/ /\____/ -- \/__/ \_/__/ http://stygianthebest.github.io -- -- ################################################################################### -- -- -- WORLD: STYGIANCORE CUSTOM VENDORS -- -- Adds multiple new vendors with custom inventory for use with StygianCore. -- -- Note: These vendors are placed by importing world_npc_spawn.sql. -- -- ################################################################################### -- -- -------------------------------------------------------------------------------------- -- Deck the halls with boughs of holly.. fa la la la la, la la la la! -- -------------------------------------------------------------------------------------- -- -------------------------------------------------------------------------------------- -- ID RANGE TYPE -- -------------------------------------------------------------------------------------- -- 6010XX - 6019XX - NPC -- 7010XX - 7019XX - ITEM -- 8010XX - 8019XX - QUEST -- 9010XX - 9019XX - LOOT/INFO -- 6015XX - 6019XX - GOSSIP MENU -- 60113X - 60114X - TRINITY STRING, NPC TEXT -- 605XX - 609XX - NPC TEXT -- -------------------------------------------------------------------------------------- -- NPC INDEX -- See the world_npc_spawn.sql for predefined spawn points) -- -------------------------------------------------------------------------------------- -- ID Type LOCATION -- -------------------------------------------------------------------------------------- -- 601000 - Exotic Pets -- 601001 - Pets -- 601002 - Food -- 601003 - Armor -- 601004 - Potions -- 601005 - Fisherman -- 601006 - Artifacts -- 601007 - Books -- 601008 - Holiday -- 601009 - Tools -- 601010 - Clothing -- 601011 - Bags -- 601012 - Fireworks -- 601013 - Transmogrifier -- 601014 - All Mounts -- 601015 - Enchanter -- 601016 - Buffer -- 601017 - Trollop -- 601018 - Gift Box Sender -- 601019 - Portal Master -- 601020 - Gambler -- 601021 - Codebox -- 601022 - Locksmith -- 601023 - Engineer -- 601024 - Specialty -- 601025 - Tabards -- 601026 - Beastmaster -- 601028 - Legendary -- 601029 - Elixer/Flask -- 601030 - Cow -- 601031 - Pig -- 601032 - Exotic Mounts -- 601033 - Mounts -- 601034 - Banker -- 601035 - GM Island Decorator -- 601036 - Bengal Tiger Handler -- 601038 - Horse (Black) -- 601039 - Horse (Caravan) -- 601040 - Horse (Patched) -- 601041 - Horse (White) -- 601042 - Horse (Brown) -- 601043 - Dog -- 601044 - Heirloom Vendor -- 601045 - Global Vendor (Gems) -- 601046 - Global Vendor (Glyphs) -- 601047 - Tauren Female Warrior -- 601048 - Koiter (Male Orc Warrior) -- 601049 - Koiter's Ghost -- 601050 - Carrion Grub Critter -- 601051 - Currency Exchange -- 601052 - Imperial Eagle Critter -- 601045 - Aurora Skyfall Multi-Vendor (Gems) -- 601046 - Grant Higginbothom Multi-Vendor (Glyphs) -- 601047 - Moofoku -- 601048 - Koiter -- 601049 - Koiter (Ghost) -- 601050 - Mr. Grubbs -- 601051 - Trump -- 601052 - MAGA -- 601053 - Retdream -- 601054 - Pamooya -- 601055 - Girlys -- 601056 - Ragathar -- 601057 - Mobbius -- 601058 - Zagmund -- 601059 - Jadenelle -- 601060 - Gatog -- 601061 - Katojune -- 601062 - Bras -- 601063 - Speedy (Turtle) -- 601064 - Shelly (Turtle) -- 601075 - Loremaster -- 70105 - Global Trainer */ USE rocket_world; -- -------------------------------------------------------------------------------------- -- EXOTIC PET VENDOR - 601000 -- -------------------------------------------------------------------------------------- SET @Entry := 601000, @Model := 23812, -- Male Lumberjack @Name := "<NAME>", @Title := "Exotic Pets", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Come browse my selection of the purest exotic pet breeds.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Come browse my selection of the purest exotic pet breeds.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Come browse my selection of the purest exotic pet breeds.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 2714, 0, 0, 18019); -- Lantern, None -- NPC Items DELETE FROM `npc_vendor` WHERE `entry` = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,8494), -- Parrot Cage Hyacinth Macaw (@Entry,10822), -- Dark Whelpling (@Entry,8498), -- Tiny Emerald Whelpling (@Entry,8499), -- Tiny Crimson Whelpling (@Entry,34535), -- Azure Whelpling (@Entry,49362), -- Onyxian Whelpling (@Entry,10398), -- Mechanical Chicken (@Entry,11023), -- Ancona Chicken (@Entry,11110), -- Chicken Egg (@Entry,11474), -- Sprite Darter Egg (@Entry,11825), -- Pet Bombling (@Entry,11826), -- Lil' Smoky (@Entry,11903), -- Cat Carrier Corrupted Kitten (@Entry,12264), -- Worg Carrier (@Entry,12529), -- Smolderweb Carrier (@Entry,13582), -- Zergling Leash (@Entry,13583), -- Panda Collar (@Entry,13584), -- Diablo Stone (@Entry,15996), -- Lifelike Mechanical Toad (@Entry,18964), -- Turtle Egg Loggerhead (@Entry,19054), -- Red Dragon Orb (@Entry,19055), -- Green Dragon Orb -- (@Entry,19450), -- A Jubling's Tiny Home (@Entry,19462), -- Unhatched Jubling Egg (@Entry,20371), -- Blue Murloc Egg (@Entry,20651), -- Orange Murloc Egg (@Entry,20769), -- Disgusting Oozeling (@Entry,21168), -- Baby Shark (@Entry,21277), -- Tranquil Mechanical Yeti (@Entry,21301), -- Green Helper Box (@Entry,21305), -- Red Helper Box (@Entry,21308), -- Jingling Bell (@Entry,21309), -- Snowman Kit (@Entry,22114), -- Pink Murloc Egg -- (@Entry,22200), -- Silver Shafted Arrow (@Entry,22235), -- Truesilver Shafted Arrow (@Entry,22780), -- White Murloc Egg (@Entry,22781), -- Polar Bear Collar (@Entry,23002), -- Turtle Box (@Entry,23007), -- Piglet's Collar (@Entry,23015), -- Rat Cage (@Entry,23083), -- Captured Flame (@Entry,23712), -- White Tiger Cub (@Entry,23713), -- Hippogryph Hatchling (@Entry,25535), -- Netherwhelp's Collar (@Entry,27445), -- Magical Crawdad Box (@Entry,29363), -- <NAME> (@Entry,29953), -- Golden Dragonhawk Hatchling (@Entry,29956), -- Red Dragonhawk Hatchling (@Entry,29957), -- Silver Dragonhawk Hatchling (@Entry,29958), -- Blue Dragonhawk Hatchling (@Entry,29960), -- Captured Firefly (@Entry,30360), -- Lurky's Egg (@Entry,31760), -- Miniwing (@Entry,32233), -- Wolpertinger's Tankard -- (@Entry,32465), -- Fortune Coin (@Entry,32498), -- Fortune Coin (@Entry,32588), -- Banana Charm (@Entry,32616), -- Egbert's Egg (@Entry,32617), -- Sleepy Willy (@Entry,32622), -- Elekk Training Collar (@Entry,33154), -- Sinister Squashling (@Entry,33816), -- Toothy's Bucket (@Entry,33818), -- Muckbreath's Bucket (@Entry,33993), -- Mojo (@Entry,34425), -- Clockwork Rocket Bot (@Entry,34478), -- Tiny Sporebat (@Entry,34492), -- Rocket Chicken (@Entry,34493), -- Dragon Kite (@Entry,34518), -- Golden Pig Coin (@Entry,34519), -- Silver Pig Coin (@Entry,34955), -- Scorched Stone (@Entry,46396), -- Wolvar Orphan Whistle (@Entry,46397), -- Oracle Orphan Whistle (@Entry,35349), -- Snarly's Bucket (@Entry,35350), -- Chuck's Bucket (@Entry,35504), -- Phoenix Hatchling (@Entry,37297), -- Gold Medallion (@Entry,37298), -- Competitor's Souvenir (@Entry,38050), -- Soul-Trader Beacon (@Entry,38628), -- Nether Ray Fry (@Entry,38658), -- Vampiric Batling (@Entry,39148), -- Baby Coralshell Turtle (@Entry,39286), -- Frosty's Collar (@Entry,39656), -- Tyrael's Hilt (@Entry,39973), -- Ghostly Skull (@Entry,40653), -- Reeking Pet Carrier (@Entry,41133), -- Unhatched Mr. Chilly (@Entry,43517), -- Penguin Egg (@Entry,43698), -- Giant Sewer Rat (@Entry,44721), -- Proto-Drake Whelp (@Entry,44723), -- Nurtured Penguin Egg (@Entry,44738), -- Kirin Tor Familiar (@Entry,44794), -- Spring Rabbit's Foot (@Entry,44810), -- Turkey Cage (@Entry,44819), -- Baby Blizzard Bear (@Entry,44822), -- Albino Snake (@Entry,44841), -- Little Fawn's Salt Lick (@Entry,44965), -- Teldrassil Sproutling (@Entry,44970), -- Dun Morogh Cub (@Entry,44971), -- Tirisfal Batling (@Entry,44972), -- Alarming Clockbot NOT IN USE (@Entry,44973), -- Durotar Scorpion (@Entry,44974), -- Elwynn Lamb (@Entry,44980), -- Mulgore Hatchling (@Entry,44982), -- Enchanted Broom (@Entry,44983), -- Strand Crawler (@Entry,44984), -- Ammen Vale Lashling (@Entry,44998), -- Argent Squire (@Entry,45002), -- Mechanopeep (@Entry,45022), -- Argent Gruntling -- (@Entry,45180), -- Murkimus' Little Spear (@Entry,45606), -- Sen'jin Fetish (@Entry,45942), -- XS-001 Constructor Bot (@Entry,46544), -- Curious Wolvar Pup (@Entry,46545), -- Curious Oracle Hatchling (@Entry,46707), -- Pint-Sized Pink Pachyderm (@Entry,46767), -- Warbot Ignition Key (@Entry,46802), -- Heavy Murloc Egg (@Entry,46820), -- Shimmering Wyrmling -- (@Entry,46821), -- Shimmering Wyrmling -- (@Entry,46831), -- <NAME> (@Entry,48112), -- Darting Hatchling (@Entry,48114), -- Deviate Hatchling (@Entry,48116), -- Gundrak Hatchling (@Entry,48118), -- Leaping Hatchling (@Entry,48120), -- Obsidian Hatchling (@Entry,48122), -- Ravasaur Hatchling (@Entry,48124), -- Razormaw Hatchling (@Entry,48126), -- Razzashi Hatchling (@Entry,48527), -- Enchanted Onyx (@Entry,49287), -- Tuskarr Kite (@Entry,46892), -- Murkimus' Tiny Spear (@Entry,49343), -- Spectral Tiger Cub (@Entry,49646), -- Core Hound Pup (@Entry,49662), -- <NAME> (@Entry,49663), -- Wind Rider Cub (@Entry,49665), -- <NAME> (@Entry,49693), -- Lil' Phylactery (@Entry,49912), -- Perky Pug (@Entry,50446), -- Toxic Wasteling (@Entry,53641), -- Ice Chip (@Entry,54436), -- Blue Clockwork Rocket Bot (@Entry,54810), -- Celestial Dragon (@Entry,54847), -- Lil' XT -- (@Entry,54857), -- Murkimus' Little Spear (@Entry,56806); -- Mini Thor -- -------------------------------------------------------------------------------------- -- PET VENDOR - 601001 -- -------------------------------------------------------------------------------------- SET @Entry := 601001, @Model := 23814, -- Female Lumberjack @Name := "<NAME>", @Title := "Pets & Supplies", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Are you interested in a companion.. pet?'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Are you interested in a companion.. pet?', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Are you interested in a companion.. pet?', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 2714, 0, 0, 18019); -- Lantern, None -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,8485), -- Cat Carrier Bombay (@Entry,8486), -- Cat Carrier Cornish Rex (@Entry,8487), -- Cat Carrier Orange Tabby (@Entry,8488), -- Cat Carrier Silver Tabby (@Entry,8489), -- Cat Carrier White Kitten (@Entry,8490), -- Cat Carrier Siamese (@Entry,8491), -- Cat Carrier Black Tabby (@Entry,46398), -- Calico Cat (@Entry,8492), -- Parrot Cage Green Wing Macaw (@Entry,8495), -- Parrot Cage Senegal (@Entry,8496), -- Parrot Cage Cockatiel (@Entry,8497), -- Rabbit Crate Snowshoe (@Entry,8500), -- Great Horned Owl (@Entry,8501), -- Hawk Owl (@Entry,10360), -- Black Kingsnake (@Entry,10361), -- Brown Snake (@Entry,10392), -- Crimson Snake (@Entry,39898), -- Cobra Hatchling (@Entry,10393), -- Cockroach (@Entry,10394), -- Prairie Dog Whistle (@Entry,11026), -- Tree Frog Box (@Entry,11027), -- Wood Frog Box (@Entry,29364), -- Brown Rabbit Crate (@Entry,29901), -- Blue Moth Egg (@Entry,29902), -- Red Moth Egg (@Entry,29903), -- Yellow Moth Egg (@Entry,29904), -- White Moth Egg (@Entry,39896), -- Tickbird Hatchling (@Entry,39899), -- White Tickbird Hatchling (@Entry,4401), -- Mechanical Squirrel Box (@Entry,44820), -- Red Ribbon Pet Leash (@Entry,37460), -- Rope Pet Leash (@Entry,43626), -- Happy Pet Snack (@Entry,35223), -- Papa Hummel's Old Fashioned Pet Buscuit (@Entry,47541), -- Argent Pony Bridle (@Entry,37431), -- Fetch Ball (@Entry,43004), -- Critter Bites (@Entry,43352); -- Pet Grooming Kit -- -------------------------------------------------------------------------------------- -- FOOD VENDOR - 601002 -- -------------------------------------------------------------------------------------- SET @Entry := 601002, @Model := 16302, -- Orc Cook @Name := "<NAME>", @Title := "Exotic Foods", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'You got the dub? I got the grub.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'You got the dub? I got the grub.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'You got the dub? I got the grub.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 2827, 3351, 0, 18019); -- Meat Cleaver, Rolling Pin -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry, 21023), -- Dirge's Kickin' Chimaerok Chops (@Entry, 21024), -- Chimaerok Tenderloin (@Entry, 34753), -- Great Feast (@Entry, 6358), -- Oily Blackmouth (@Entry, 6522), -- Deviate Fish (@Entry, 43015), -- Fish Feast (@Entry, 43478), -- Giant Feast (@Entry, 46887), -- Bountiful Feast (@Entry, 43086), (@Entry, 45932), (@Entry, 45279), (@Entry, 44049), (@Entry, 44071), (@Entry, 44072), (@Entry, 44607), (@Entry, 44722), (@Entry, 44940), (@Entry, 33444), (@Entry, 34769), (@Entry, 34768), (@Entry, 35950), (@Entry, 34764), (@Entry, 34767), (@Entry, 34765), (@Entry, 35948), (@Entry, 34766), (@Entry, 35951), (@Entry, 35947), (@Entry, 35952), (@Entry, 38706), (@Entry, 38698), (@Entry, 43490), (@Entry, 41729), (@Entry, 39520), (@Entry, 40202), (@Entry, 43491), (@Entry, 43492), (@Entry, 41731), (@Entry, 42429), (@Entry, 42778), (@Entry, 42431), (@Entry, 42779), (@Entry, 42777), (@Entry, 42942), (@Entry, 42993), (@Entry, 42994), (@Entry, 42995), (@Entry, 42998), (@Entry, 42996), (@Entry, 42997), (@Entry, 43480), (@Entry, 43488), (@Entry, 43268), (@Entry, 43236), (@Entry, 42999), (@Entry, 43000), (@Entry, 43001), (@Entry, 43005), (@Entry, 43004), (@Entry, 34748), (@Entry, 33445), (@Entry, 34749), (@Entry, 34747), (@Entry, 34751), (@Entry, 34752), (@Entry, 34750), (@Entry, 34754), (@Entry, 34755), (@Entry, 34757), (@Entry, 34756), (@Entry, 34758), (@Entry, 34762), (@Entry, 34759), (@Entry, 34760), (@Entry, 44941), (@Entry, 44953), (@Entry, 34761), (@Entry, 34763); -- -------------------------------------------------------------------------------------- -- ARMOR VENDOR - 601003 -- -------------------------------------------------------------------------------------- SET @Entry := 601003, @Model := 15845, -- Armored Dwarf @Name := "<NAME>", @Title := "Rare Armor", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 14824, 0, 0, 18019); -- War Axe, None -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,4726), -- Chief Brigadier Cloak (@Entry,16803), -- Felheart Slippers (@Entry,16804), -- Felheart Bracers (@Entry,16805), -- Felheart Gloves (@Entry,16806), -- Felheart Belt (@Entry,16807), -- Felheart Shoulder Pads (@Entry,16808), -- Felheart Horns (@Entry,16809), -- Felheart Robes (@Entry,16810), -- Felheart Pants (@Entry,13077), -- Girdle of Uther (@Entry,13130), -- Windrunner Legguards (@Entry,13399), -- Gargoyle Shredder Talons (@Entry,14116), -- Aboriginal Cape (@Entry,16836), -- Cenarion Spaulders (@Entry,16937), -- Dragonstalker's Spaulders (@Entry,17110), -- Seal of the Archmagus (@Entry,17909), -- Frostwolf Insignia Rank 6 (@Entry,17082), -- Shard of the Flame (@Entry,18168), -- Force Reactive Disk (@Entry,18811), -- Fireproof Cloak (@Entry,18814), -- Choker of the Fire Lord (@Entry,18817), -- Crown of Destruction (@Entry,18835), -- High Warlord's Recurve (@Entry,18870), -- Helm of the Lifegiver (@Entry,19138), -- Band of Sulfuras (@Entry,19348), -- Red Dragonscale Protector (@Entry,19384), -- Master Dragonslayer's Ring (@Entry,19396), -- Taut Dragonhide Belt (@Entry,24259), -- Vengeance Wrap (@Entry,28529), -- Royal Cloak of Arathi Kings (@Entry,29776), -- Core of Ar'kelos (@Entry,35584), -- Embroidered Gown of Zul'Drak (@Entry,35591), -- Shoulderguards of the Ice Troll (@Entry,38287), -- Empty Mug of Direbrew (@Entry,41611), -- Eternal Belt Buckle (@Entry,44323), -- Indestructible Alchemist Stone (@Entry,46323), -- Starshine Signet (@Entry,49121), -- Ring of Ghoulish Glee (@Entry,50352), -- Corpse Tongue Coin (@Entry,47216), -- The Black Heart (@Entry,50356), -- Corroded Skeleton Key (@Entry,50363); -- Deathbringer's Will -- -------------------------------------------------------------------------------------- -- POTION VENDOR - 601004 -- -------------------------------------------------------------------------------------- SET @Entry := 601004, @Model := 16182, -- Elven Wine Seller @Name := "<NAME>", @Title := "Potions", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'My spirits are aged to perfection.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'My spirits are aged to perfection.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'My spirits are aged to perfection.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 13612, 0, 0, 18019); -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,8529), -- NoggenFogger Elixer (@Entry, 44958), -- Ethereal Oil (@Entry, 43572), -- Magic Eater (@Entry, 40195), -- Pygmy Oil (@Entry, 35720), -- Lord of Frost's Private Label (@Entry,21721), -- Moonglow (@Entry,12820), -- Winterfall Firewater (@Entry,'118'), (@Entry,'858'), (@Entry,'929'), (@Entry,'1710'), (@Entry,'2455'), (@Entry,'2456'), (@Entry,'2459'), (@Entry,'2633'), (@Entry,'3087'), (@Entry,'3384'), (@Entry,'3385'), (@Entry,'3386'), (@Entry,'3387'), (@Entry,'3823'), (@Entry,'3827'), (@Entry,'3928'), (@Entry,'4596'), (@Entry,'4623'), (@Entry,'5631'), (@Entry,'5632'), (@Entry,'5633'), (@Entry,'5634'), (@Entry,'5816'), (@Entry,'6048'), (@Entry,'6049'), (@Entry,'6050'), (@Entry,'6051'), (@Entry,'6052'), (@Entry,'6149'), (@Entry,'6372'), (@Entry,'9030'), (@Entry,'9036'), (@Entry,'9144'), (@Entry,'9172'), (@Entry,'12190'), (@Entry,'13442'), (@Entry,'13443'), (@Entry,'13444'), (@Entry,'13446'), (@Entry,'13455'), (@Entry,'13456'), (@Entry,'13457'), (@Entry,'13458'), (@Entry,'13459'), (@Entry,'13460'), (@Entry,'13461'), (@Entry,'13462'), (@Entry,'17348'), (@Entry,'17349'), (@Entry,'17351'), (@Entry,'17352'), (@Entry,'18253'), (@Entry,'18839'), (@Entry,'18841'), (@Entry,'20002'), (@Entry,'20008'), (@Entry,'22826'), (@Entry,'22828'), (@Entry,'22829'), (@Entry,'22832'), (@Entry,'22836'), (@Entry,'22837'), (@Entry,'22838'), (@Entry,'22839'), (@Entry,'22841'), (@Entry,'22842'), (@Entry,'22844'), (@Entry,'22845'), (@Entry,'22846'), (@Entry,'22847'), (@Entry,'22849'), (@Entry,'22850'), (@Entry,'22871'), (@Entry,'23578'), (@Entry,'23579'), (@Entry,'23822'), (@Entry,'23823'), (@Entry,'28100'), (@Entry,'28101'), (@Entry,'31676'), (@Entry,'31677'), (@Entry,'31838'), -- (@Entry,'31839'), -- (@Entry,'31840'), -- (@Entry,'31841'), -- (@Entry,'31852'), -- (@Entry,'31853'), -- (@Entry,'31854'), -- (@Entry,'31855'), (@Entry,'32762'), (@Entry,'32763'), -- (@Entry,'32783'), -- (@Entry,'32784'), (@Entry,'32840'), (@Entry,'32844'), (@Entry,'32845'), (@Entry,'32846'), (@Entry,'32847'), -- (@Entry,'32902'), -- (@Entry,'32903'), -- (@Entry,'32904'), -- (@Entry,'32905'), -- (@Entry,'32909'), -- (@Entry,'32910'), (@Entry,'32947'), (@Entry,'32948'), (@Entry,'33092'), (@Entry,'33093'), (@Entry,'33447'), (@Entry,'33448'), (@Entry,'33934'), (@Entry,'33935'), (@Entry,'34440'), -- (@Entry,'36770'), (@Entry,'38351'), (@Entry,'39327'), (@Entry,'39671'), (@Entry,'40067'), (@Entry,'40077'), (@Entry,'40081'), (@Entry,'40087'), (@Entry,'40093'), (@Entry,'40211'), (@Entry,'40212'), (@Entry,'40213'), (@Entry,'40214'), (@Entry,'40215'), (@Entry,'40216'), (@Entry,'40217'), (@Entry,'41166'), (@Entry,'42545'), -- (@Entry,'43530'), -- (@Entry,'43531'), (@Entry,'43569'), (@Entry,'43570'), (@Entry,'44728'), (@Entry,'45276'), (@Entry,'45277'); -- -------------------------------------------------------------------------------------- -- FISHING VENDOR - 601005 -- -------------------------------------------------------------------------------------- SET @Entry := 601005, @Model := 3285, -- Fishing Trainer @Name := "<NAME>", @Title := "<NAME>", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 45991, 34484, 0, 18019); -- Fishing Pole, Old Ironjaw -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES -- BOOKS (@Entry,27532), -- Book: Master Fishing (@Entry,16082), -- Book: Artisan Fishing (@Entry,16083), -- Book: Expert Fishing -- ENCHANTS (@Entry,50816), -- Scroll Enchant Gloves: Angler (@Entry,50406), -- Formula Enchant Gloves: Angler (@Entry,38802), -- Enchant Gloves Fishing -- POTIONS (@Entry,6372), -- Swim Speed Potion (@Entry,5996), -- Elixer of Water Breathing (@Entry,18294), -- Elixer of Greater Water Breathing (@Entry,8827), -- Elixer of Water Walking -- SPECIAL (@Entry,19979), -- Hook of the Master Angler (@Entry,33223), -- Fishing Chair -- VANITY (@Entry,1827), -- Meat Cleaver (@Entry,2763), -- Fisherman's Knife -- CLOTHING (@Entry,7996), -- Worn Fishing Hat (@Entry,19972), -- Lucky Fishing Hat (@Entry,3563), -- Seafarer's Pantaloons (@Entry,7052), -- Azure Silk Belt (@Entry, 50287),-- Boots of the Bay (@Entry,19969), -- Nat Pagle's Extreme Anglin' Boots (@Entry,6263), -- Blue Overalls (@Entry,3342), -- Captain Sander's Shirt (@Entry,4509), -- Seawolf Gloves (@Entry,792), -- Knitted Sandals (@Entry,33820), -- Weather Beaten Fishing Hat (@Entry, 7348), -- Fletcher's Gloves (@Entry, 36019), -- Aerie Belt of Nature Protection -- POLES (@Entry,19970), -- Arcanite Fishing Pole (@Entry,44050), -- Mastercraft Kaluak Fishing Pole (@Entry,45992), -- Jeweled Fishing Pole (@Entry,25978), -- Seth's Graphite Fishing Pole (@Entry,19022), -- Nat Pagle's Extreme Angler FC-5000 (@Entry,45991), -- Bone Fishing Pole (@Entry,45858), -- Nat's Lucky Fishing Pole (@Entry,12225), -- Blump Family Fishing Pole (@Entry,6367), -- Big Iron Fishing Pole (@Entry,6365), -- Strong Fishing Pole (@Entry,6366), -- Darkwood Fishing Pole (@Entry,6256), -- Fishing Pole -- LINE (@Entry,34836), -- Trusilver Spun Fishing Line (@Entry,19971), -- High Test Eternium Fishing Line -- LURES (@Entry,34861), -- Sharpened Fishing Hook (@Entry,46006), -- Glow Worm (@Entry,6811), -- Aquadynamic Fish Lens (@Entry,7307), -- Flesh Eating Worm (@Entry,6533), -- Aquadynamic Fish Attractor (@Entry,6532), -- Bright Baubles (@Entry,6530), -- Nightcrawlers (@Entry,6529), -- Shiny Bauble -- ANGLIN' (@Entry,34832), -- Captain Rumsey's Lager (@Entry,18229); -- Nat Pagle's Guide to Extreme Anglin' -- -------------------------------------------------------------------------------------- -- CLEAN UP FISHERMAN WAYPOINTS - SET CREATURE MOVEMENTTYPE = '2' FOR ANIMATION TO START -- -------------------------------------------------------------------------------------- DELETE FROM `creature_addon` WHERE `guid`=1993577; DELETE FROM `broadcast_text` WHERE ID >= 77500 AND ID <= 77502; DELETE FROM `waypoint_scripts` WHERE guid >= 938 AND guid <= 941; DELETE FROM `waypoint_data` WHERE id = 1993577 AND point <= 13; -- -------------------------------------------------------------------------------------- -- FISHERMAN CREATURE ADDON -- -------------------------------------------------------------------------------------- INSERT INTO `creature_addon` (`guid`, `path_id`, `mount`, `bytes1`, `bytes2`, `emote`, `auras`) VALUES (1993577, 1993577, 0, 0, 0, 0, NULL); -- -------------------------------------------------------------------------------------- -- FISHERMAN WAYPOINT STRINGS -- -------------------------------------------------------------------------------------- INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`) VALUES (77500, 0, 'Ahh.. the sea. Once it casts its spell, it holds one in its net of wonder forever.'), (77501, 0, 'Many men go fishing all of their lives without knowing that it is not fish they are after.'), (77502, 0, 'I wonder if they ever found that hidden treasure buried on the Isle of Dread?'); -- -------------------------------------------------------------------------------------- -- FISHERMAN WAYPOINT SCRIPTS -- -------------------------------------------------------------------------------------- INSERT INTO `waypoint_scripts` (`id`, `delay`, `command`, `datalong`, `datalong2`, `dataint`, `x`, `y`, `z`, `o`, `guid`) VALUES (938, 0, 0, 0, 0, 77500, 0, 0, 0, 0, 938), -- Say (939, 0, 0, 0, 0, 77501, 0, 0, 0, 0, 939), -- Say (940, 0, 0, 0, 0, 77502, 0, 0, 0, 0, 940), -- Say (941, 0, 31, 601005, 0, 0, 0, 0, 0, 0, 941); -- Equip -- -------------------------------------------------------------------------------------- -- FISHERMAN WAYPOINT DATA -- -------------------------------------------------------------------------------------- INSERT INTO `waypoint_data` (`id`, `point`, `position_x`, `position_y`, `position_z`, `orientation`, `delay`, `move_type`, `action`, `action_chance`, `wpguid`) VALUES -- Start (1993577, 1, -10749.4, 2519.6, 0.203893, 0, 30000, 0, 939, 33, 1995303), (1993577, 2, -10776.3, 2503.56, 1.20431, 0, 0, 0, 0, 100, 1995304), (1993577, 3, -10777.2, 2504.67, 0.528472, 0, 30000, 0, 0, 100, 1995305), -- Headed to boats (1993577, 4, -10791.4, 2490.54, 1.74961, 0, 0, 0, 940, 10, 1995306), (1993577, 5, -10805.9, 2460.9, 2.03948, 0, 0, 0, 0, 100, 1995307), -- At the boats, TODO: equip fishing pole (EVENT 941) (1993577, 6, -10807.8, 2461.83, 1.04805, 0, 60000, 0, 941, 100, 1995308), (1993577, 7, -10791.1, 2489.84, 1.98191, 0, 0, 0, 0, 100, 1995309), (1993577, 8, -10760.3, 2513.04, 1.92615, 0, 0, 0, 0, 100, 1995310), (1993577, 9, -10745.8, 2511.96, 3.60894, 0, 0, 0, 0, 100, 1995311), (1993577, 10, -10732.6, 2518.96, 1.79036, 0, 0, 0, 0, 100, 1995312), (1993577, 11, -10702.7, 2521.03, 2.26718, 0, 0, 0, 0, 100, 1995313), -- Looking at sunset (1993577, 12, -10700.2, 2523.61, 0.792882, 0, 60000, 0, 938, 33, 1995314), (1993577, 13, -10749, 2517.63, 1.60554, 0, 0, 0, 0, 25, 1995315); -- -------------------------------------------------------------------------------------- -- ARTIFACT VENDOR - 601006 -- -------------------------------------------------------------------------------------- SET @Entry := 601006, @Model := 22340, -- <NAME> @Name := "<NAME>", @Title := "Artifacts", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'My selection of antiquities is unique.. and expensive.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'My selection of antiquities is unique.. and expensive.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'My selection of antiquities is unique.. and expensive.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 1906, 0, 0, 18019); -- Torch, None -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,1973), -- Orb of Deception (@Entry,2608), -- <NAME> (@Entry,4471), -- Flint and Tinder (@Entry,4696), -- Lapidis Tankard of Tidesippe (@Entry,5060), -- Thieves' Tools (@Entry,5373), -- Lucky Charm (@Entry,5429), -- A Pretty Rock (@Entry,5433), -- Rag Doll (@Entry,5530), -- Blinding Powder (@Entry,6297), -- Old Skull (@Entry,8350), -- The 1 Ring (@Entry,34837), -- The 2 Ring (@Entry,45859), -- The 5 Ring (@Entry,9327), -- Security DELTA Data Access Card (@Entry,11382), -- Blood of the Mountain (@Entry,11420), -- Elegant Writing Tool (@Entry,13047), -- Twig of the World Tree (@Entry,9242), -- Ancient Tablet (@Entry,18335), -- Pristine Black Diamond (@Entry,18665), -- The Eye of Shadow (@Entry,24231), -- Coarse Snuff (@Entry,29570), -- A Gnome Effigy (@Entry,29572), -- Aboriginal Carvings (@Entry,31945), -- Shadow Circuit (@Entry,39355), -- Haute Club Membership Card (@Entry,39356), -- Mind-Soothing Bauble (@Entry,40393), -- Green Sparkly (@Entry,39351), -- Richly Appointed Pipe (@Entry,44464), -- Crude Eating Utensils (@Entry,44678), -- Wine Glass (@Entry,34826), -- Gold Wedding Band (@Entry,45994), -- Lost Ring (@Entry,45995), -- Lost Necklace (@Entry,9360), -- Cuergo's Gold (@Entry,11840), -- Master Builder's Shirt (@Entry,44430), -- Titanium Seal of Dalaran (@Entry,18401), -- Foror's Compendium of Dragonslaying (@Entry,9423), -- The Jackhammer (@Entry,9429), -- Miner's Hat of the Deep (@Entry,9424), -- Ginn-su sword (@Entry,9465), -- Digmaster 5000 (@Entry,9427), -- Stonevault Bonebreaker (@Entry,19865), -- Warblade of Hakkari (@Entry,19866), -- Warblade of Hakkari (@Entry,38802), -- Enchant Gloves Fishing (@Entry,1168), -- Skullflame Shield (@Entry,19854), -- Zin'rokh, Destroyer of Worlds (@Entry,4446), -- Blackvenom Blade (@Entry,35664), -- Unknown Archeologist's Hammer (@Entry,8226), -- The Butcher (@Entry,12608), -- Butcher's Apron (@Entry,23540), -- Felsteel Longblade (@Entry,1728), -- Teebu's Blazing Longsword (@Entry,17782), -- Talisman of Binding Shard (@Entry,14551), -- Edgemaster Handguards (@Entry,1604), -- Chromatic Sword (@Entry,18755), -- Xorthian Firestick (@Entry,9491), -- Hotshot Pilot Gloves (@Entry,9425), -- Pendulum of Doom (@Entry,8029), -- Plans: Wicked Mithril Blade (@Entry,4354), -- Plans: Rich Purple Silk Shirt -- (@Entry,45087), -- Runed Orb -- (@Entry,45506), -- Archivum Data Disc -- (@Entry,43321), -- Crystallized Tear -- (@Entry,43329), -- Pigtail Holder -- (@Entry,34057), -- Abyss Crystal -- (@Entry,37604), -- Tooth Pick -- (@Entry,27978), -- Soap on a Rope -- (@Entry,27979), -- Stone of Stupendous Springing Strides -- (@Entry,19974), -- Mudskunk Lure -- (@Entry,21536), -- Elune Stone -- (@Entry,21829), -- Perfume Bottle -- (@Entry,21833), -- Cologne Bottle -- (@Entry,11325), -- Dark Iron Ale Mug (@Entry,46359); -- Velociraptor Skull -- -------------------------------------------------------------------------------------- -- BOOK VENDOR - 601007 -- -------------------------------------------------------------------------------------- SET @Entry := 601007, @Model := 3071, -- Dwarf Female @Name := "<NAME>", @Title := "Books", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Books are a uniquely portable magic. A reader lives a thousand lives before he dies.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Books are a uniquely portable magic. A reader lives a thousand lives before he dies.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Books are a uniquely portable magic. A reader lives a thousand lives before he dies.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,11108), -- Faded Photograph (@Entry,701003), -- Azerothian Humor Vol. 1 (@Entry,701013), -- Azerothian Humor Vol. 2 (@Entry,11482), -- Crystal Pylon User's Manual (@Entry,18228), -- Autographed Picture of Foror & Tigule (@Entry,18229), -- Nat Pagle's Guide to Extreme Anglin' (@Entry,18364), -- The Emerald Dream (@Entry,18365), -- A Thoroughly Read Copy of \"Nat Pagle's Guide to Extreme Anglin'.\" (@Entry,19483), -- Peeling the Onion (@Entry,19484), -- The Frostwolf Artichoke (@Entry,19851), -- Grom's Tribute (@Entry,20010), -- The Horde's Hellscream (@Entry,20677), -- Decoded Twilight Text (@Entry,29571), -- A Steamy Romance Novel (@Entry,37467), -- A Steamy Romance Novel, Forbidden Love (@Entry,46023), -- A Steamy Romance Novel, Northern Exposure (@Entry,54291), -- A Steamy Romance Novel, Blue Moon (@Entry,39358), -- Give to the Church and the Light Will Provide (@Entry,39317), -- News From The North -- (@Entry,32620), -- Time-Lost Scroll -- (@Entry,36877), -- Folded Letter (@Entry,39361); -- Turning the Other Cheek -- -------------------------------------------------------------------------------------- -- HOLIDAY VENDOR - 601008 -- -------------------------------------------------------------------------------------- SET @Entry := 601008, @Model := 10815, -- Red Imp @Name := "<NAME>", @Title := "Holiday Supplies", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Type := 7, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Want a balloon?'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Want a balloon?', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Want a balloon?', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,20397), -- Hallowed Wand: Pirate (@Entry,20398), -- Hallowed Wand: Ninja (@Entry,20399), -- Hallowed Wand: Leper Gnome (@Entry,20409), -- Hallowed Wand: Ghost (@Entry,20410), -- Hallowed Wand: Bat (@Entry,20411), -- Hallowed Wand: Skeleton (@Entry,20413), -- Hallowed Wand: Random (@Entry,20414), -- Hallowed Wand: Wisp (@Entry,29575), -- A Jack-o'-Lantern (@Entry,34068), -- Weighted Jack-o'-Lantern (@Entry,37895), -- Filled Green Brewfest Stein (@Entry,33019), -- Filled Blue Brewfest Stein (@Entry,44803), -- Spring Circlet (@Entry,3419), -- Red Rose (@Entry,34480), -- Romantic Picnic Basket (@Entry,21154), -- Festival Dress (@Entry,17712), -- Winter Veil Disguise Kit (@Entry,21213), -- Preserved Holly (@Entry,35557), -- Huge Snowball (@Entry,17202), -- Snowball (@Entry,21524), -- Red Winter Hat (@Entry,21542), -- Festival Suit (@Entry,34085), -- Red Winter Clothes (@Entry,34086), -- Winter Boots (@Entry,34087), -- Green Winter Clothes (@Entry,34850), -- Midsummer Ground Flower (@Entry,23323), -- Crown of the Fire Festival (@Entry,23324), -- Mantle of the Fire Festival (@Entry,34683), -- Sandals of Summer (@Entry,34685), -- Vestment of Summer (@Entry,35280), -- Tabard of Summer Flames (@Entry,35279), -- Tabard of Summer Skies (@Entry,34686), -- Brazier of Dancing Flames (@Entry,42438), -- Lovely Cake (@Entry,42436); -- Chocolate Celebration Cake -- -------------------------------------------------------------------------------------- -- TOOL VENDOR - 601009 -- -------------------------------------------------------------------------------------- SET @Entry := 601009, @Model := 22270, -- Human Merchant @Name := "<NAME>", @Title := "Tools", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,5507), -- Ornate Spyglass (@Entry,40772), -- Gnomish Army Knife (@Entry,45631), -- High-Powered Flashlight -- (@Entry,46709); -- MiniZep Controller -- (@Entry,34498), -- Paper Zeppelin Kit (@Entry,38089), -- Ruby Shades (@Entry,4384), -- Explosive Sheep (@Entry,35227); -- Goblin Weather Machine Prototype 01-B -- -------------------------------------------------------------------------------------- -- CLOTHING VENDOR - 601010 -- -------------------------------------------------------------------------------------- SET @Entry := 601010, @Model := 18763, -- Elf in Black @Name := "<NAME>", @Title := "Clothing", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'My elegant silken thread is soft to the touch.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'My elegant silken thread is soft to the touch.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'My elegant silken thread is soft to the touch.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,154), -- Primitive Mantle (@Entry,2955), -- First Mate Hat (@Entry,3322), -- Wispy Cloak (@Entry,3342), -- Captain Sanders' Shirt (@Entry,4334), -- Formal White Shirt (@Entry,6125), -- Brawler's Harness (@Entry,6139), -- Novice's Robe (@Entry,6263), -- Blue Overalls (@Entry,6555), -- Bard's Cloak (@Entry,3427), -- Stylish Black Shirt (@Entry,7348), -- Fletcher's Gloves (@Entry,6796), -- Red Swashbuckler's Shirt (@Entry,6833), -- White Tuxedo Shirt (@Entry,6835), -- Black Tuxedo Pants (@Entry,10034), -- Tuxedo Shirt (@Entry,10035), -- Tuxedo Pants (@Entry,10036), -- Tuxedo Jacket (@Entry,18231), -- Sleeveless T-Shirt (@Entry,19028), -- Elegant Dress (@Entry,22276), -- Lovely Red Dress (@Entry,22278), -- Lovely Blue Dress (@Entry,22279), -- Lovely Black Dress (@Entry,22280), -- Lovely Purple Dress (@Entry,10053), -- Simple Black Dress (@Entry,22282), -- Purple Dinner Suit (@Entry,33820), -- Weather-Beaten Fishing Hat (@Entry,38277), -- Haliscan Jacket (@Entry,41250), -- Green Lumberjack Shirt (@Entry,38), (@Entry,45), (@Entry,49), (@Entry,53), (@Entry,127), (@Entry,148), (@Entry,859), (@Entry,20901), (@Entry,2105), (@Entry,2575), (@Entry,2576), (@Entry,2577), (@Entry,2579), (@Entry,2587), (@Entry,3426), (@Entry,3428), (@Entry,4330), (@Entry,4332), (@Entry,4333), (@Entry,4335), (@Entry,4336), (@Entry,4344), (@Entry,5107), (@Entry,6096), (@Entry,6097), (@Entry,6117), (@Entry,6120), (@Entry,6134), (@Entry,6136), (@Entry,6384), (@Entry,6385), (@Entry,6795), (@Entry,10052), (@Entry,10054), (@Entry,10055), (@Entry,10056), (@Entry,11840), (@Entry,14617), (@Entry,16059), (@Entry,16060), (@Entry,17723), (@Entry,20897), (@Entry,23345), (@Entry,23473), (@Entry,23476), (@Entry,24143), (@Entry,41248), (@Entry,41249), (@Entry,41251), (@Entry,41252), (@Entry,41253), (@Entry,41254), (@Entry,41255), (@Entry,42360), (@Entry,42361), (@Entry,42363), (@Entry,42365), (@Entry,42368), (@Entry,42369), (@Entry,42370), (@Entry,42371), (@Entry,42372), (@Entry,42373), (@Entry,42374), (@Entry,42375), (@Entry,42376), (@Entry,42377), (@Entry,42378), (@Entry,44693), (@Entry,44694), (@Entry,45280), (@Entry,45664), (@Entry,45666), (@Entry,45667), (@Entry,45668), (@Entry,45669), (@Entry,45670), (@Entry,45671), (@Entry,45672), (@Entry,45673), (@Entry,45674), (@Entry,46104), (@Entry,52019); -- -------------------------------------------------------------------------------------- -- BAG VENDOR - 601011 -- -------------------------------------------------------------------------------------- SET @Entry := 601011, @Model := 19156, -- <NAME> @Name := "<NAME>", @Title := "Bags", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Hey, back here, in the dark alley.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Hey, back here, in the dark alley.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Hey, back here, in the dark alley.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,23162), -- Foror's Crate of Endless Resist Gear Storage (36-Slot Bag) (@Entry,51809), -- Portable Hole (24-Slot Bag) (@Entry,14156), -- Bottomless Bag (@Entry,41600), -- Glacial Bag (@Entry,37606); -- Penny Pouch -- -------------------------------------------------------------------------------------- -- FIREWORKS VENDOR - 601012 -- -------------------------------------------------------------------------------------- SET @Entry := 601012, @Model := 7181, -- Goblin @Name := "<NAME>", @Title := "Fireworks", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, -- 118(Undercity) @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Wanna go out with a BANG! Come talk to Sparky!'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Wanna go out with a BANG! Come talk to Sparky!', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Wanna go out with a BANG! Come talk to Sparky!', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC EQUIP DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 2884, 0, 0, 18019); -- Dynamite Stick, None -- NPC VENDOR ITEMS DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,41427), -- Dalaran Firework (@Entry,34599), -- Juggling Torch (@Entry,23771), -- Green Smoke Flare (@Entry,23768), -- White Smoke Flare (@Entry,21747), -- Festival Firecracker (@Entry,21745), -- Elder's Moonstone (@Entry,21744), -- Lucky Rocket Cluster (@Entry,21713), -- Elune's Candle (@Entry,34850), -- Midsummer Ground Flower (@Entry,21576), -- Red Rocket Cluster (@Entry,21574), -- Green Rocket Cluster (@Entry,21571), -- Blue Rocket Cluster (@Entry,21570), -- Cluster Launcher (@Entry,19026), -- Snake Burst Firework (@Entry, 9318), -- Red Firework (@Entry, 9315), -- Yellow Rose Firework (@Entry, 9314), -- Red Streaks Firework (@Entry, 9313), -- Green Firework (@Entry, 9312), -- Blue Firework (@Entry, 8626); -- Blue Sparkler -- -------------------------------------------------------------------------------------- -- TRANSMOGRIFIER - 601013 -- -------------------------------------------------------------------------------------- SET @Entry := 601013, @Model := 19772, -- Soul Trader @Name := "<NAME>", @Title := "Illusionist", @Icon := "Interact", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 1, @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 138936390, @FlagsExtra := 2, @AIName := "SmartAI", -- @Script := "npc_transmogrifier"; -- Now Handled with Eluna @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Appearances are my specialty!'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Appearances are my specialty!', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Appearances are my specialty!', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- -------------------------------------------------------------------------------------- -- ALL MOUNTS VENDOR - 601014 -- -------------------------------------------------------------------------------------- SET @Entry := 601014, @Model := 26571, -- The Black Knight -- @Model := 21249, -- Armored Orc @Name := "<NAME>", @Title := "Mount Trainer", @Icon := "Speak", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 1, @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := "All_Mounts_NPC"; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Hail $N. I can teach you to ride.. anything!'); -- -------------------------------------------------------------------------------------- -- ENCHANTER - 601015 -- -------------------------------------------------------------------------------------- SET @Entry := 601015, @Model := 9353, -- Undead Necromancer @Name := "<NAME>", @Title := "Enchantments", @Icon := "Speak", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 1, @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := "npc_enchantment"; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 11343, 0, 0, 18019); -- Black/Purple Staff, None -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Good day $N. Beauregard Boneglitter at your service. I offer a vast array of gear enchantments for the aspiring adventurer.'); -- -------------------------------------------------------------------------------------- -- BUFFER - 601016 -- -------------------------------------------------------------------------------------- SET @Entry := 601016, -- Alliance Version -- @Model := 4309, -- Human Male Tuxedo -- @Name := "<NAME>", -- @Title := "Ph.D.", -- Horde Version @Model := 14612, -- Tauren Warmaster @Name := "<NAME>", @Title := "", @Icon := "Speak", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 81, @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := "buff_npc"; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 1906, 0, 0, 18019); -- War Axe(14824), Torch -- -------------------------------------------------------------------------------------- -- TROLLOP - 601017 -- -------------------------------------------------------------------------------------- SET @Entry := 601017, @Model := 10927, -- <NAME> @Name := "Amouranth", @Title := "Your New Best Friend", @Icon := "Speak", @GossipMenu := 60117, @MinLevel := 80, @MaxLevel := 80, @Faction := 7, -- Neutral, Attackable @NPCFlag := 81, @Scale := 1.0, @Rank := 2, -- Rare Elite @Type := 3, -- Demon @DynamicFlags:= 1, -- Lootable @TypeFlags := 0, @FlagsExtra := 0, @LootID := 60117, @AIName := "ReactorAI", @Script := "Trollop_NPC"; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, dynamicflags, type_flags, InhabitType, RegenHealth, flags_extra, lootid, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 1, @Type, DynamicFlags, @TypeFlags, 3, 1, @FlagsExtra, @LootID, @AIName, @Script); -- NPC Text DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Hey there $N. Lookin\' for a good time?'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Loot DELETE FROM `rocket_world`.`creature_loot_template` WHERE `entry` = @LootID; INSERT INTO `rocket_world`.`creature_loot_template` (`entry`, `item`, `Chance`, `lootmode`, `groupid`, `MinCount`, `maxcount`) VALUES ('60117', '29571', '100', '1', '0', '1', '1'), ('60117', '37467', '75', '1', '0', '1', '1'), ('60117', '46023', '50', '1', '0', '1', '1'), ('60117', '54291', '25', '1', '0', '1', '1'); -- -------------------------------------------------------------------------------------- -- GAMBLER - 601020 -- -------------------------------------------------------------------------------------- SET @Entry := 601020, @Model := 7337, -- Goblin Banker @Name := "Skinny", @Title := "Gambler", @Icon := "LootAll", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 1, @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := "gamble_npc"; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Hey there, the name\'s Skinny. You feelin\' lucky?'); -- -------------------------------------------------------------------------------------- -- LOCKSMITH - 601022 -- -------------------------------------------------------------------------------------- SET @Entry := 601022, @Model := 6837, -- Fancy Undead Male @Name := "<NAME>", @Title := "Locksmith", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, -- 118(Undercity) @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'I am the keymaster, the lock picker, and the door opener.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'I am the keymaster, the lock picker, and the door opener.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'I am the keymaster, the lock picker, and the door opener.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC EQUIP DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 2714, 0, 0, 18019); -- Lantern, None -- NPC VENDOR ITEMS DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,5060), -- Thieves Tools (@Entry,'5396'), (@Entry,'6893'), (@Entry,'7146'), (@Entry,'11000'), (@Entry,'11078'), (@Entry,'12382'), (@Entry,'15869'), (@Entry,'15870'), (@Entry,'15871'), (@Entry,'15872'), (@Entry,'18249'), (@Entry,'18250'), (@Entry,'18266'), (@Entry,'18268'), (@Entry,'21761'), (@Entry,'21762'), (@Entry,'24490'), (@Entry,'27991'), (@Entry,'28395'), (@Entry,'30622'), (@Entry,'30623'), (@Entry,'30633'), (@Entry,'30634'), (@Entry,'30635'), (@Entry,'30637'), (@Entry,'31084'), (@Entry,'31704'), (@Entry,'32449'), (@Entry,'42482'), (@Entry,'43853'), (@Entry,'43854'), (@Entry,'44581'), (@Entry,'44582'), (@Entry,'45796'), (@Entry,'45798'); -- -------------------------------------------------------------------------------------- -- ENGINEER VENDOR - 601023 -- -------------------------------------------------------------------------------------- SET @Entry := 601023, @Model := 11690, -- <NAME> (Everlook Goblin) @Name := "<NAME>", @Title := "Contraptions", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC VENDOR ITEMS DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,4394), -- Big Iron Bomb (@Entry,10506), -- Deepdive Helmet (@Entry,18984), -- Dimensional Ripper Everlook (@Entry,30542), -- Dimensional Ripper Area 52 (@Entry,37863), -- Direbrew's Remote (@Entry,40768), -- MOLL-E (@Entry,48933), -- Wormhole Generator: Northrend -- (@Entry,49278), -- Goblin Rocket Pack (@Entry,5507), -- Ornate Spyglass (@Entry,40772), -- Gnomish Army Knife (@Entry,45631), -- High-Powered Flashlight (@Entry,4384), -- Explosive Sheep (@Entry,35227), -- Goblin Weather Machine Prototype 01-B (@Entry,9492), -- Electromagnetic Gigaflux Reactivator (@Entry,40727), -- Gnomish Gravity Well (@Entry,49040); -- Jeeves -- -------------------------------------------------------------------------------------- -- SPECIALTY ITEMS - 601024 -- -------------------------------------------------------------------------------------- SET @Entry := 601024, @Model := 26365, -- Elegant Blood Elf Female | 18148, -- <NAME> @Name := "<NAME>", @Title := "Specialty Gifts", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'I have what you want. Come see.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'I have what you want. Come see.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'I have what you want. Come see.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC EQUIP DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 45861, 0, 0, 18019); -- Diamond-Tipped Cane, None -- NPC VENDOR ITEMS DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,7340), -- Flawless Diamond Solitaire (@Entry,38089), -- Ruby Shades (@Entry,7337), -- The Rock (@Entry,34827), -- Noble's Monocle (@Entry,34828), -- Antique Silver Cufflinks (@Entry, 37934), -- Noble' Elementium Signet (@Entry,4368), -- Flying Tiger Goggles (@Entry,32566), -- Picnic Basket (@Entry,41367), -- Dark Jade Focusing Lens (@Entry,42420), -- Shadow Crystal Focusing Lens (@Entry,42421), -- Shadow Jade Focusing Lens -- (@Entry,39351), -- Richly Appointed Pipe (@Entry,45861), -- Diamond-Tipped Cane (@Entry, 18258), -- Gordok Ogre Suit (@Entry, 44228), -- Baby Spice -- (@Entry, 44958), -- Ethereal Oil -- (@Entry, 13506), -- Potion of Petrification -- (@Entry, 43572), -- Magic Eater -- (@Entry, 40195), -- Pygmy Oil (@Entry, 31337), -- Orb of the Blackwhelp (@Entry, 35275), -- Orb of the Sindorei (@Entry, 45853), -- Rituals of the New Moon (@Entry, 32782), -- Time-Lost Figurine (@Entry, 19979), -- Hook of the Master Angler (@Entry, 5462), -- Dartol's Rod of Transformation (@Entry, 4388), -- Discombobulator Ray (@Entry, 52201), -- Muradin's Favor (@Entry, 37254), -- Super Simian Sphere (@Entry, 49704), -- Carved Ogre Idol (@Entry, 23835), -- Gnomish Poultryizer (@Entry, 10716), -- Gnomish Shrink Ray (@Entry, 44818), -- Noblegarden Egg (@Entry, 5332), -- Glowing Cat Figurine (@Entry, 10725), -- Gnomish Battle Chicken (@Entry, 40110), -- Haunted Momento (@Entry, 12185), -- Bloodsail Admiral's Hat (@Entry, 40492), -- Argent War Horn (@Entry, 14022), -- Barov Peasent Caller (H) (@Entry, 14023), -- Barov Peasent Called (A) (@Entry, 32864), -- Commander's Badge (@Entry, 32695), -- Captain's Badge (@Entry, 32694), -- Overseer's Badge (@Entry, 3456), -- Dog Whistle (@Entry, 38506), -- <NAME>'s Favorite Hat (@Entry, 16022), -- Arcanite Dragonling (@Entry, 4396), -- Mechanical Dragonling (@Entry, 35694), -- Khorium Boar (@Entry, 42418), -- Emerald Boar (@Entry, 24124), -- Felsteel Boar (@Entry, 50471), -- The Heartbreaker (@Entry, 54212), -- Instant Statue Pedestal (@Entry, 50966), -- Abracadaver (@Entry, 5218), -- Cleansed Timberling Heart (@Entry, 49490), -- Antilinuvian Cornerstone Grimiore (@Entry, 49308), -- Ancient Cornerstone Grimiore (@Entry, 34029), -- Tiny Voodoo Mask (@Entry, 13353), -- Book of the Dead (@Entry, 54438), -- Tiny Blue Ragdoll (@Entry, 44849), -- Tiny Green Ragdoll (@Entry, 34686), -- Brazier of Dancing Flames (@Entry, 33927), -- Brewfest Pony Keg (@Entry, 38578), -- Flag of Ownership (@Entry, 44606), -- Tiny Train Set (@Entry, 34480), -- Romantic Picnic Basket (@Entry, 44481), -- Grindgear Toy Gorilla (@Entry, 45047), -- Sandbox Tiger (@Entry, 46780), -- Ogre Pinata (@Entry, 45063), -- Foam Sword Rack (@Entry, 38301), -- D.I.S.C.O. (@Entry, 33223), -- Fishing Chair (@Entry, 33219), -- Goblin Gumbo Kettle (@Entry, 32542), -- Imp in a Ball (@Entry, 21326), -- Defender of the Timbermaw (@Entry, 38518), -- Cro's Apple -- (@Entry, 43491), -- Bad Clams (@Entry, 25679), -- Comfortable Insoles -- (@Entry, 43004), -- Critter Bites (@Entry, 36863), -- Decahedral Dwarven Dice (@Entry, 12217), -- Dragonbreath Chili (@Entry, 43492), -- Haunted Herring (@Entry, 44601), -- Heavy Copper Racer (@Entry, 18662), -- Heavy Leather Ball -- (@Entry, 43488), -- Last Week's Mammoth (@Entry, 44792), -- Blossoming Branch (@Entry, 38266), -- Rotund Relic (@Entry, 17202), -- Snowball (@Entry, 43490), -- Tasty Cupcake (@Entry, 33081), -- Voodoo Skull (@Entry, 36862), -- Worn Troll Dice -- (@Entry, 52490), -- Stardust (@Entry, 37604), -- Toothpick (@Entry, 44731), -- Bouquet of Ebon Roses (@Entry, 22206), -- Bouquet of Red Roses (@Entry, 18660), -- World Enlarger (@Entry, 18951), -- Evonice's Landin' Pilla (@Entry, 37313), -- Riding Crop (@Entry, 11122), -- Carrot on a Stick (@Entry, 43660), -- Fire Eater's Guide (@Entry, 13379), -- Piccolo of the Flaming Fire (@Entry, 44482), -- Trusty Copper Racer (@Entry, 50741), -- Vile Fumigator's Mask (@Entry, 44599), -- Zippy Copper Racer (@Entry, 54452), -- Etheral Portal (@Entry, 46349), -- Chef's Hat (@Entry, 38577), -- Party Grenade (@Entry, 54455), -- Paint Bomb (@Entry, 46779), -- Path of Cenarius (@Entry, 38233), -- Path of Illidan (@Entry, 34499), -- Paper Flying Machine (@Entry, 54806), -- Frostscyth of Lord Ahune -- (@Entry, 64482), -- Puzzle Box of Yogg Saron (@Entry,18640), -- Happy Fun Rock (@Entry, 52252), -- Tabard of the Lightbringer (@Entry,46709), -- MiniZep Controller (@Entry,34498); -- Paper Zeppelin Kit -- -------------------------------------------------------------------------------------- -- TABARDS - 601025 -- -------------------------------------------------------------------------------------- SET @Entry := 601025, @Model := 12675, -- Tauren Female with Tabard @Name := "<NAME>", @Title := "Tabards", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC VENDOR ITEMS DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,'5976'), (@Entry,'11364'), (@Entry,'15196'), (@Entry,'15197'), (@Entry,'15198'), (@Entry,'15199'), (@Entry,'19031'), (@Entry,'19032'), (@Entry,'19160'), (@Entry,'19505'), (@Entry,'19506'), (@Entry,'20131'), (@Entry,'20132'), (@Entry,'22999'), (@Entry,'23192'), (@Entry,'23999'), (@Entry,'24004'), (@Entry,'24344'), (@Entry,'25549'), (@Entry,'28788'), (@Entry,'31279'), (@Entry,'31404'), (@Entry,'31405'), (@Entry,'31773'), (@Entry,'31774'), (@Entry,'31775'), (@Entry,'31776'), (@Entry,'31777'), (@Entry,'31778'), (@Entry,'31779'), (@Entry,'31780'), (@Entry,'31781'), (@Entry,'31804'), (@Entry,'32445'), (@Entry,'32828'), (@Entry,'35221'), (@Entry,'35279'), (@Entry,'35280'), (@Entry,'36941'), (@Entry,'40643'), (@Entry,'43154'), (@Entry,'43155'), (@Entry,'43156'), (@Entry,'43157'), -- (@Entry,'43300'), -- (@Entry,'43348'), (@Entry,'43349'), (@Entry,'45574'), (@Entry,'45577'), (@Entry,'45578'), (@Entry,'45579'), (@Entry,'45580'), (@Entry,'45581'), (@Entry,'45582'), (@Entry,'45583'), (@Entry,'45584'), (@Entry,'45585'), (@Entry,'45983'), (@Entry,'46817'), (@Entry,'46818'), (@Entry,'46874'), (@Entry,'49052'), (@Entry,'49054'), (@Entry,'49086'), (@Entry,'51534'), (@Entry,'52252'); -- -------------------------------------------------------------------------------------- -- BEASTMASTER - 601026 -- -------------------------------------------------------------------------------------- SET @Entry := 601026, @Model := 729, -- Shadowfang Moonwalker (White Worgen) @Name := "<NAME>", @Title := "BeastMaster", @Icon := "Speak", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 4194433, @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := "BeastMaster"; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 2196, 1906, 0, 18019); -- Haunch of Meat, Torch -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Greetings $N. And when, on the still cold nights, he pointed his nose at a star and howled long and wolflike, it was his ancestors, dead and dust, pointing nose at star and howling down through the centuries and through him.'); -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES -- MEAT (@Entry,35953), -- (75) -- Mead Blasted Caribou (@Entry,33454), -- (65) -- Salted Venison (@Entry,27854), -- (55) -- Smoked Talbuk Venison (@Entry,8952), -- (45) -- Roasted Quail (@Entry,4599), -- (35) -- Cured Ham Steak (@Entry,3771), -- (25) -- Wild Hog Shank (@Entry,3770), -- (15) -- Mutton Chop (@Entry,2287), -- (5) -- Haunch of Meat (@Entry,117), -- (1) -- Tough Jerky -- FUNGUS (@Entry,35947), -- (75) -- Sparkling Frostcap (@Entry,33452), -- (65) -- Honey-Spiced Lichen (@Entry,27859), -- (55) -- Zangar Caps (@Entry,8948), -- (45) -- Dried King Bolete (@Entry,4608), -- (35) -- Raw Black Truffle (@Entry,4607), -- (25) -- Delicious Cave Mold (@Entry,4606), -- (15) -- Spongy Morel (@Entry,4605), -- (5) -- Red-Speckled Mushroom (@Entry,4604), -- (1) -- Forest Mushroom Cap -- BREAD (@Entry,35950), -- (75) -- Sweet Potato Bread (@Entry,33449), -- (65) -- Crusty Flatbread (@Entry,27855), -- (55) -- Mag'har Grainbread (@Entry,8950), -- (45) -- Homemade Cherry Pie (@Entry,4601), -- (35) -- Soft Banana Bread (@Entry,4544), -- (25) -- Mulgore Spice Bread (@Entry,4542), -- (15) -- Moist Cornbread (@Entry,4541), -- (5) -- Freshly Baked Bread (@Entry,4540), -- (1) -- Tough Hunk of Bread -- FRUIT (@Entry,35948), -- (75) -- Savory Snowplum (@Entry,35949), -- (65) -- Tundra Berries (@Entry,27856), -- (55) -- Sklethyl Berries (@Entry,8953), -- (45) -- Deep Fried Plantains (@Entry,4602), -- (35) -- Moon Harvest Pumpkin (@Entry,4539), -- (25) -- Goldenbark Apple (@Entry,4538), -- (15) -- Snapvine Watermelon (@Entry,4537), -- (5) -- Tel'Abim Banana (@Entry,4536), -- (1) -- Shiny Red Apple -- FISH (@Entry,35951), -- (75) -- Poached Emperor Salmon (@Entry,33451), -- (65) -- Filet of Icefin (@Entry,27858), -- (55) -- Sunspring Carp (@Entry,8957), -- (45) -- Spinefin Halibut (@Entry,21552), -- (35) -- Striped Yellowtail (@Entry,4594), -- (25) -- Rockscale Cod (@Entry,4593), -- (15) -- Bristle Whisker Catfish (@Entry,4592), -- (5) -- Longjaw Mud Snapper (@Entry,787), -- (1) -- Slitherskin Mackeral -- CHEESE (@Entry,35952), -- (75) -- Briny Hardcheese (@Entry,33443), -- (65) -- Sour Goat Cheese (@Entry,27857), -- (55) -- Gradar Sharp (@Entry,8932), -- (45) -- Alterac Swiss (@Entry,3927), -- (35) -- Fine Aged Chedder (@Entry,1707), -- (25) -- Stormwind Brie (@Entry,422), -- (15) -- Dwarven Mild (@Entry,414), -- (5) -- Dalaran Sharp (@Entry,2070), -- (1) -- Darnassian Bleu -- BUFF (@Entry,33875), -- Kibler's Bits -- RARE (@Entry,21024); -- Chimaerok Tenderloin -- -------------------------------------------------------------------------------------- -- LEGENDARY VENDOR - 601028 -- -------------------------------------------------------------------------------------- SET @Entry := 601028, @Model := 27760, -- Ghostly Tauren Shaman @Name := "<NAME>", @Title := "Legendary Artifacts", @Icon := "Buy", @GossipMenu := 60128, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 129, -- Gossip+QuestGiver @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 138412032, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry, 3419); -- Red Rose -- NPC Text DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'My child, no matter how many years go by, no matter how far you\'re away from me, nothing can change the bond between us, my baby you\'ll always be.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Gossip Menu Option DELETE FROM `gossip_menu_option` WHERE `MenuID` = @GossipMenu; INSERT INTO gossip_menu_option (`MenuID`, `OptionID`, `OptionIcon`, `OptionText`, `OptionType`, `OptionNPCFlag`, `ActionMenuID`, `ActionPoiID`, `BoxCoded`, `BoxMoney`, `BoxText`) VALUES (@GossipMenu, 0, 3, 'I want to see your wares', 3, 128, @Entry, 0, 0, 0, ''); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'My child, no matter how many years go by, no matter how far you\'re away from me, nothing can change the bond between us, my baby you\'ll always be.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'My child, no matter how many years go by, no matter how far you\'re away from me, nothing can change the bond between us, my baby you\'ll always be.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts (Speak) DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- -------------------------------------------------------------------------------------- -- ELIXER/FLASK VENDOR - 601029 -- -------------------------------------------------------------------------------------- SET @Entry := 601029, @Model := 16801, -- Elven Reagent Seller @Name := "<NAME>", @Title := "Elixers & Flasks", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC TEXT DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Need a boost? Try one of these.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Need a boost? Try one of these.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Need a boost? Try one of these.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 13612, 0, 0, 18019); -- Wine Glass -- NPC Items DELETE FROM npc_vendor WHERE entry = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,'2454'), (@Entry,'2457'), (@Entry,'2458'), (@Entry,'3382'), (@Entry,'3383'), (@Entry,'3388'), (@Entry,'3389'), (@Entry,'3390'), (@Entry,'3391'), (@Entry,'3825'), (@Entry,'3826'), (@Entry,'3828'), (@Entry,'5996'), (@Entry,'5997'), (@Entry,'6373'), (@Entry,'6662'), (@Entry,'8410'), (@Entry,'8411'), (@Entry,'8412'), (@Entry,'8423'), (@Entry,'8424'), (@Entry,'8529'), (@Entry,'8827'), (@Entry,'8949'), (@Entry,'8951'), (@Entry,'9088'), (@Entry,'9154'), (@Entry,'9155'), (@Entry,'9179'), (@Entry,'9187'), (@Entry,'9197'), (@Entry,'9206'), (@Entry,'9224'), (@Entry,'9233'), (@Entry,'9264'), (@Entry,'10592'), (@Entry,'12820'), (@Entry,'13445'), (@Entry,'13447'), (@Entry,'13452'), (@Entry,'13453'), (@Entry,'13454'), (@Entry,'17708'), (@Entry,'18294'), (@Entry,'20004'), (@Entry,'20007'), (@Entry,'20079'), (@Entry,'20080'), (@Entry,'20081'), (@Entry,'21546'), (@Entry,'22823'), (@Entry,'22824'), (@Entry,'22825'), (@Entry,'22827'), (@Entry,'22830'), (@Entry,'22831'), (@Entry,'22833'), (@Entry,'22834'), (@Entry,'22835'), (@Entry,'22840'), (@Entry,'22848'), (@Entry,'23444'), (@Entry,'23871'), (@Entry,'25539'), (@Entry,'28102'), (@Entry,'28103'), (@Entry,'28104'), (@Entry,'31679'), (@Entry,'32062'), (@Entry,'32063'), (@Entry,'32067'), (@Entry,'32068'), (@Entry,'34130'), (@Entry,'34537'), (@Entry,'37449'), (@Entry,'39666'), (@Entry,'40068'), (@Entry,'40070'), (@Entry,'40072'), (@Entry,'40073'), (@Entry,'40076'), (@Entry,'40078'), (@Entry,'40097'), (@Entry,'40109'), (@Entry,'44012'), (@Entry,'44325'), (@Entry,'44327'), (@Entry,'44328'), (@Entry,'44329'), (@Entry,'44330'), (@Entry,'44331'), (@Entry,'44332'), (@Entry,'45621'), (@Entry,'13510'), (@Entry,'13511'), (@Entry,'13512'), (@Entry,'13513'), (@Entry,'22851'), (@Entry,'22853'), (@Entry,'22854'), (@Entry,'22861'), (@Entry,'22866'), -- (@Entry,'32596'), -- unstable flasks -- (@Entry,'32597'), -- (@Entry,'32598'), -- (@Entry,'32599'), -- (@Entry,'32600'), -- (@Entry,'32601'), (@Entry,'32764'), (@Entry,'32766'), (@Entry,'32767'), -- (@Entry,'32898'), -- shattrath -- (@Entry,'32899'), -- shattrath -- (@Entry,'32900'), -- (@Entry,'32901'), (@Entry,'33208'), -- (@Entry,'35716'), -- shattrath -- (@Entry,'35717'), -- shattrath (@Entry,'40079'), -- (@Entry,'40082'), -- mixture -- (@Entry,'40083'), -- mixture -- (@Entry,'40084'), -- mixture -- (@Entry,'40404'), -- mixture (@Entry,'44939'), (@Entry,'45006'), (@Entry,'45007'), (@Entry,'45008'), (@Entry,'45009'), (@Entry,'46376'), (@Entry,'46377'), (@Entry,'46378'), (@Entry,'46379'), (@Entry,'47499'); -- -------------------------------------------------------------------------------------- -- COW - 601030 -- -------------------------------------------------------------------------------------- SET @Entry := 601030, @Model := 1060, -- Cow @Name := "Cowlie", @Title := "The Milker", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 190, @NPCFlag := 0, @Scale := 1.0, @Rank := 0, @Type := 8, -- Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- -------------------------------------------------------------------------------------- -- PIG - 601031 -- -------------------------------------------------------------------------------------- SET @Entry := 601031, @Model := 16257, -- Pig @Name := "<NAME>", @Title := "For Elise", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 190, @NPCFlag := 0, @Scale := 1.0, @Rank := 0, @Type := 8, -- Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- -------------------------------------------------------------------------------------- -- EXOTIC MOUNT VENDOR - 601032 -- -------------------------------------------------------------------------------------- SET @Entry := 601032, @Model := 14233, -- <NAME>, <NAME> @Name := "<NAME>", @Title := "Exotic Mounts", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @UnitClass := 1, @UnitFlags := 37376, @UnitFlags2 := 2048, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, unit_flags2, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, @UnitClass, @UnitFlags, @UnitFlags2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 1909, 0, 0, 18019); -- Silver Hatchet, None -- NPC ADDON DELETE FROM `creature_template_addon` WHERE `entry`=@Entry; INSERT INTO `creature_template_addon` (`entry`, `path_id`, `mount`, `bytes1`, `bytes2`, `emote`, `auras`) VALUES (@Entry, 0, 24757, 0, 0, 0, NULL); -- Great Brewfest Kodo -- NPC Items DELETE FROM `npc_vendor` WHERE `entry` = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,'33976'), (@Entry,'33999'), (@Entry,'34060'), (@Entry,'34061'), (@Entry,'34092'), (@Entry,'34129'), (@Entry,'35906'), (@Entry,'37011'), (@Entry,'37012'), (@Entry,'37676'), (@Entry,'37719'), (@Entry,'40775'), (@Entry,'43516'), (@Entry,'43951'), (@Entry,'43952'), (@Entry,'43953'), (@Entry,'43954'), (@Entry,'43955'), (@Entry,'43956'), (@Entry,'43958'), (@Entry,'43959'), (@Entry,'43961'), (@Entry,'43962'), (@Entry,'43986'), (@Entry,'44077'), (@Entry,'44080'), (@Entry,'44083'), (@Entry,'44086'), (@Entry,'44151'), (@Entry,'44160'), (@Entry,'44164'), (@Entry,'44175'), (@Entry,'44178'), (@Entry,'44223'), (@Entry,'44224'), (@Entry,'44225'), (@Entry,'44226'), (@Entry,'44230'), (@Entry,'44231'), (@Entry,'44234'), (@Entry,'44235'), (@Entry,'44413'), (@Entry,'44554'), (@Entry,'44558'), (@Entry,'44689'), (@Entry,'44690'), (@Entry,'44707'), (@Entry,'44842'), (@Entry,'44843'), (@Entry,'45801'), (@Entry,'45802'), (@Entry,'46099'), (@Entry,'46100'), (@Entry,'46101'), (@Entry,'46109'), (@Entry,'46171'), (@Entry,'46308'), (@Entry,'46708'), (@Entry,'46743'), (@Entry,'46744'), (@Entry,'46745'), (@Entry,'46746'), (@Entry,'46747'), (@Entry,'46748'), (@Entry,'46749'), (@Entry,'46750'), (@Entry,'46751'), (@Entry,'46752'), (@Entry,'46813'), (@Entry,'46814'), (@Entry,'46815'), (@Entry,'46816'), (@Entry,'47100'), (@Entry,'47101'), (@Entry,'47179'), (@Entry,'47180'), (@Entry,'47840'), (@Entry,'49044'), (@Entry,'49046'), (@Entry,'49096'), (@Entry,'50250'), (@Entry,'51954'), (@Entry,'51955'), (@Entry,'54068'), (@Entry,'54797'), (@Entry,'54860'), -- Factions (@Entry,'45125'), (@Entry,'45586'), (@Entry,'45589'), (@Entry,'45590'), (@Entry,'45591'), (@Entry,'45592'), (@Entry,'45593'), (@Entry,'45595'), (@Entry,'45596'), (@Entry,'45597'), -- Exotics (@Entry,'19902'), -- Swift Zulian Tiger (@Entry,'37828'), -- Great Brewfest Kodo (@Entry,'33977'), -- Swift Brewfest Ram (@Entry,'35513'), -- Swift White Hawkstrider (@Entry,'30480'), -- Fiery Warhorse's Riens (@Entry,'32768'), -- Reins of the Eaven Lord (@Entry,'32458'), -- Ashes of Alar (@Entry,'33809'),-- Amani War Bear (@Entry,'41508'), -- Mechano-Hog (@Entry,'44168'), -- Time-Lost Proto Drake (@Entry,'44177'), -- Reins of the Violet Proto Drake (@Entry,'45693'), -- Mimiron's Head (@Entry,'45725'), -- Argent Hippogryph (@Entry,'46102'), -- Venomhide Ravasaur (@Entry,'49636'), -- Reins of the Onyxian Drake (@Entry,'49098'), -- Crusader's Black Warhorse (@Entry,'52200'), -- Reins of the Crimson Deasthcharger (@Entry,'50818'); -- Invincible's Reins -- -------------------------------------------------------------------------------------- -- MOUNT VENDOR - 601033 -- -------------------------------------------------------------------------------------- SET @Entry := 601033, @Model := 27163, -- Warmaster Molog @Name := "<NAME>", @Title := "Mounts", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 128, -- Vendor @Scale := 1.0, @Rank := 0, @UnitClass := 1, @UnitFlags := 37376, @UnitFlags2 := 2048, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, unit_flags2, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, @UnitClass, @UnitFlags, @UnitFlags2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 21580, 0, 23889, 18019); -- Silver Hatchet, None -- NPC ADDON DELETE FROM `creature_template_addon` WHERE `entry`=@Entry; INSERT INTO `creature_template_addon` (`entry`, `path_id`, `mount`, `bytes1`, `bytes2`, `emote`, `auras`) VALUES (@Entry, 0, 14334, 0, 0, 0, NULL); -- Black Undead Horse -- NPC Items DELETE FROM `npc_vendor` WHERE `entry` = @Entry; INSERT INTO npc_vendor (entry, item) VALUES (@Entry,'1132'), (@Entry,'2411'), (@Entry,'2414'), (@Entry,'5655'), (@Entry,'5656'), (@Entry,'5665'), (@Entry,'5668'), (@Entry,'5864'), (@Entry,'5872'), (@Entry,'5873'), (@Entry,'8563'), (@Entry,'8586'), (@Entry,'8588'), (@Entry,'8591'), (@Entry,'8592'), (@Entry,'8595'), (@Entry,'8629'), (@Entry,'8631'), (@Entry,'8632'), (@Entry,'12302'), (@Entry,'12303'), (@Entry,'12330'), (@Entry,'12351'), (@Entry,'12353'), (@Entry,'12354'), (@Entry,'13086'), (@Entry,'13317'), (@Entry,'13321'), (@Entry,'13322'), (@Entry,'13326'), (@Entry,'13327'), (@Entry,'13328'), (@Entry,'13329'), (@Entry,'13331'), (@Entry,'13332'), (@Entry,'13333'), (@Entry,'13334'), (@Entry,'13335'), (@Entry,'15277'), (@Entry,'15290'), (@Entry,'15292'), (@Entry,'15293'), (@Entry,'18766'), (@Entry,'18767'), (@Entry,'18772'), (@Entry,'18773'), (@Entry,'18774'), (@Entry,'18776'), (@Entry,'18777'), (@Entry,'18778'), (@Entry,'18785'), (@Entry,'18786'), (@Entry,'18787'), (@Entry,'18788'), (@Entry,'18789'), (@Entry,'18790'), (@Entry,'18791'), (@Entry,'18793'), (@Entry,'18794'), (@Entry,'18795'), (@Entry,'18796'), (@Entry,'18797'), (@Entry,'18798'), (@Entry,'18902'), (@Entry,'19029'), (@Entry,'19030'), (@Entry,'19872'), (@Entry,'21176'), (@Entry,'21218'), (@Entry,'21321'), (@Entry,'21323'), (@Entry,'21324'), (@Entry,'25470'), (@Entry,'25471'), (@Entry,'25472'), (@Entry,'25473'), (@Entry,'25474'), (@Entry,'25475'), (@Entry,'25476'), (@Entry,'25477'), (@Entry,'25527'), (@Entry,'25528'), (@Entry,'25529'), (@Entry,'25531'), (@Entry,'25532'), (@Entry,'25533'), (@Entry,'28481'), (@Entry,'28915'), (@Entry,'28927'), (@Entry,'28936'), (@Entry,'29102'), (@Entry,'29103'), (@Entry,'29104'), (@Entry,'29105'), (@Entry,'29220'), (@Entry,'29221'), (@Entry,'29222'), (@Entry,'29223'), (@Entry,'29224'), (@Entry,'29227'), (@Entry,'29228'), (@Entry,'29229'), (@Entry,'29230'), (@Entry,'29231'), (@Entry,'29465'), (@Entry,'29466'), (@Entry,'29467'), (@Entry,'29468'), (@Entry,'29469'), (@Entry,'29470'), (@Entry,'29471'), (@Entry,'29472'), (@Entry,'29743'), (@Entry,'29744'), (@Entry,'29745'), (@Entry,'29746'), (@Entry,'29747'), (@Entry,'30609'), (@Entry,'31829'), (@Entry,'31830'), (@Entry,'31831'), (@Entry,'31832'), (@Entry,'31833'), (@Entry,'31834'), (@Entry,'31835'), (@Entry,'31836'), (@Entry,'32314'), (@Entry,'32316'), (@Entry,'32317'), (@Entry,'32318'), (@Entry,'32319'), (@Entry,'32857'), (@Entry,'32858'), (@Entry,'32859'), (@Entry,'32860'), (@Entry,'32861'), (@Entry,'32862'), (@Entry,'33176'), (@Entry,'33182'), (@Entry,'33183'), (@Entry,'33184'), (@Entry,'33189'); -- -------------------------------------------------------------------------------------- -- BANKER - 601034 -- -------------------------------------------------------------------------------------- SET @Entry := 601034, @Model := 7621, -- Female Tauren @Name := "Marny", @Title := "Banker", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 131072, -- Banker @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC EQUIPPED DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 2714, 0, 0, 18019); -- Lantern, None -- -------------------------------------------------------------------------------------- -- GM Island Decorator - 601035 -- -------------------------------------------------------------------------------------- SET @Entry := 601035, @Model := 12162, -- Molten Giant @Name := "Balrog", @Title := "|cff00ccffIsland Decorator|r", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 1, -- @Scale := 0.25, @Rank := 1, @Type := 0, @TypeFlags := 4, @FlagsExtra := 2, @AIName := "SmartAI", @Script := "GMIsland_Theme_Generator"; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- -------------------------------------------------------------------------------------- -- BENGAL TIGER VENDOR - 601036 - Smart Script Trainer -- -------------------------------------------------------------------------------------- SET @Entry := 601036, @Model := 2575, -- Night Elf Female (Classic) @Name := "<NAME>", @Title := "Bengal Tiger Handler", @Icon := "Trainer", @GossipMenu := 60136, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 3, -- Gossip+QuestGiver @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 138936390, @FlagsExtra := 2, @AIName := "SmartAI", @Spell1 := 828, -- Tiger Riding (828, 6745 passive) @Spell2 := 10790, -- Reins of the Bengal Tiger @Spell3 := 16609, -- Pray to Elune @Item1 := 8630, -- Reins of the Bengal Tiger @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- Text DELETE FROM `npc_text` WHERE `ID` = @Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Greetings $N. Lucky you.. You\'ve arrived at just the right time.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Gossip Menu Option DELETE FROM `gossip_menu_option` WHERE `MenuID` = @GossipMenu; INSERT INTO `gossip_menu_option` (`MenuID`, `OptionID`, `OptionIcon`, `OptionText`, `OptionType`, `OptionNPCFlag`, `ActionMenuID`, `ActionPoiID`, `BoxCoded`, `BoxMoney`, `BoxText`) VALUES (@GossipMenu, 0, 3, 'Train Tiger Riding', 1, 1, @GossipMenu, 0, 0, 0, ''); INSERT INTO `gossip_menu_option` (`MenuID`, `OptionID`, `OptionIcon`, `OptionText`, `OptionType`, `OptionNPCFlag`, `ActionMenuID`, `ActionPoiID`, `BoxCoded`, `BoxMoney`, `BoxText`) VALUES (@GossipMenu, 1, 2, 'Adopt a Bengal Tiger', 1, 1, @GossipMenu, 0, 0, 0, ''); INSERT INTO `gossip_menu_option` (`MenuID`, `OptionID`, `OptionIcon`, `OptionText`, `OptionType`, `OptionNPCFlag`, `ActionMenuID`, `ActionPoiID`, `BoxCoded`, `BoxMoney`, `BoxText`) VALUES (@GossipMenu, 2, 9, 'Pray to Elune', 1, 1, @GossipMenu, 0, 0, 0, ''); -- Smart Scripts DELETE FROM `smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO smart_scripts (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, 0, 0, 0, 62, 0, 100, 0, @GossipMenu, 0, 0, 0, 85, @Spell1, 2, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, ''); INSERT INTO smart_scripts (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, 0, 1, 0, 62, 0, 100, 0, @GossipMenu, 1, 0, 0, 56, @Item1, 1, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, ''); INSERT INTO smart_scripts (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, 0, 2, 0, 62, 0, 100, 0, @GossipMenu, 2, 0, 0, 11, @Spell3, 2, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, ''); -- Update Reins of the Bengal Tiger requirements UPDATE `rocket_world`.`item_template` SET `RequiredLevel`='1', `RequiredSkill`='150', `RequiredSkillRank`='1', `maxcount`='1' WHERE (`entry`='8630'); -- -------------------------------------------------------------------------------------- -- BLACK HORSE - 601038 -- This demonstrates a full Creature Template. A PITA to create! -- -------------------------------------------------------------------------------------- DELETE FROM `rocket_world`.`creature_template` WHERE `entry` = 601038; SET @Entry := 601038, @Model := 239, -- Black Horse @Name := "<NAME>", @Title := "", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 35, @NPCFlag := 0, @Scale := 1.0, @Rank := 0, @Type := 8, -- Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- -------------------------------------------------------------------------------------- -- <NAME>ORSE - 601039 -- -------------------------------------------------------------------------------------- SET @Entry := 601039, @Model := 14551, -- Caravan Horse @Name := "Ginger", @Title := "", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 35, @NPCFlag := 131072, -- Banker @Scale := 1.0, @Rank := 0, @Type := 8, -- Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- -------------------------------------------------------------------------------------- -- BROWN/WHITE HORSE - 601040 -- -------------------------------------------------------------------------------------- SET @Entry := 601040, @Model := 238, -- Brown/White Horse @Name := "Hidalgo", @Title := "", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 35, @NPCFlag := 0, @Scale := 1.0, @Rank := 0, @Type := 8, -- Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- -------------------------------------------------------------------------------------- -- WHITE HORSE - 601041 -- -------------------------------------------------------------------------------------- SET @Entry := 601041, @Model := 236, -- @Name := "Merrylegs", @Title := "", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 35, @NPCFlag := 0, @Scale := 1.0, @Rank := 0, @Type := 8, -- Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- -------------------------------------------------------------------------------------- -- LIGHT BROWN HORSE - 601042 -- -------------------------------------------------------------------------------------- SET @Entry := 601042, @Model := 237, -- @Name := "Spirit", @Title := "Stallion of the Cimarron", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 35, @NPCFlag := 0, @Scale := 1.0, @Rank := 0, @Type := 8, -- Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- -------------------------------------------------------------------------------------- -- DOG (SAI Barking - 601043) -- -------------------------------------------------------------------------------------- SET @Entry := 601043, @Model := 9563, -- Dog @Name := "Wolfy", @Title := "", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 35, @NPCFlag := 0, @Scale := 1.0, @Rank := 0, @Type := 8, -- 8 = Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Ruff! Ruff! Ruff!', '14', '0', '100', '0', '0', '10827', @Entry, '0', 'Random Bark'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Ruff! Ruff! Ruff!', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '5000', '20000', '30000', '120000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Dog Bark'); -- -------------------------------------------------------------------------------------- -- HEIRLOOM VENDOR - 601044 -- -------------------------------------------------------------------------------------- SET @Entry := 601044, @Model := 25900, -- Small Tyrion @Name := "<NAME>", @Title := "Heirloom Merchant", @Icon := "Buy", @GossipMenu := 0, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 130, -- @Scale := 1.0, @Rank := 0, @Type := 7, @TypeFlags := 0, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- Items DELETE FROM `npc_vendor` WHERE `entry`=@Entry; INSERT INTO `npc_vendor` (`entry`,`slot`,`item`,`maxcount`,`incrtime`,`ExtendedCost`) VALUES (@Entry,0,42943,0,0,0), -- Bloodied Arcanite Reaper (@Entry,0,42944,0,0,0), -- Balanced Heartseeker (@Entry,0,42945,0,0,0), -- Venerable Dal'Rend's Sacred Charge (@Entry,0,42946,0,0,0), -- Charmed Ancient Bone Bow (@Entry,0,42947,0,0,0), -- Dignified Headmaster's Charge (@Entry,0,42948,0,0,0), -- Devout Aurastone Hammer (@Entry,0,42949,0,0,0), -- Polished Spaulders of Valor (@Entry,0,42950,0,0,0), -- Champion Herod's Shoulder (@Entry,0,42951,0,0,0), -- Mystical Pauldrons of Elements (@Entry,0,42952,0,0,0), -- Stained Shadowcraft Spaulders (@Entry,0,42984,0,0,0), -- Preened Ironfeather Shoulders (@Entry,0,42985,0,0,0), -- Tattered Dreadmist Mantle (@Entry,0,42991,0,0,0), -- Swift Hand of Justice (@Entry,0,42992,0,0,0), -- Discerning Eye of the Beast (@Entry,0,44091,0,0,0), -- Sharpened Scarlet Kris (@Entry,0,44092,0,0,0), -- Reforged Truesilver Champion (@Entry,0,44093,0,0,0), -- Upgraded Dwarven Hand Cannon (@Entry,0,44094,0,0,0), -- The Blessed Hammer of Grace (@Entry,0,44095,0,0,0), -- Grand Staff of Jordan (@Entry,0,44096,0,0,0), -- Battleworn Thrash Blade (@Entry,0,44097,0,0,0), -- Inherited Insignia of the Horde (@Entry,0,44098,0,0,0), -- Inherited Insignia of the Alliance (@Entry,0,44099,0,0,0), -- Strengthened Stockade Pauldrons (@Entry,0,44100,0,0,0), -- Pristine Lightforge Spaulders (@Entry,0,44101,0,0,0), -- Prized Beastmaster's Mantle (@Entry,0,44102,0,0,0), -- Aged Pauldrons of The Five Thunders (@Entry,0,44103,0,0,0), -- Exceptional Stormshroud Shoulders (@Entry,0,44105,0,0,0), -- Lasting Feralheart Spaulders (@Entry,0,44107,0,0,0), -- Exquisite Sunderseer Mantle (@Entry,0,48677,0,0,0), -- Champion's Deathdealer Breastplate (@Entry,0,48685,0,0,0), -- Polished Breastplate of Valor (@Entry,0,48687,0,0,0), -- Preened Ironfeather Breastplate (@Entry,0,48689,0,0,0), -- Stained Shadowcraft Tunic (@Entry,0,48683,0,0,0), -- Mystical Vest of Elements (@Entry,0,48691,0,0,0), -- Tattered Dreadmist Robe (@Entry,0,48716,0,0,0), -- Venerable Mass of McGowan (@Entry,0,48718,0,0,0), -- Repurposed Lava Dredger (@Entry,0,50255,0,0,0); -- Dread Pirate Ring -- -------------------------------------------------------------------------------------- -- GEM MULTI-VENDOR -- -------------------------------------------------------------------------------------- SET @Entry := 601045, @Model := 26414, @Name := "<NAME>", @Title := "Gems", @Icon := "Buy", @GossipMenu := 60145, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 129, -- Vendor @Scale := 1.0, @Rank := 0, @UnitFlags := 512, @UnitFlags2 := 2048, @DynamicFlags:= 8, @Type := 7, @TypeFlags := 138412032, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, unit_flags2, dynamicflags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, @UnitFlags, @UnitFlags2, @DynamicFlags, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); DELETE FROM `rocket_world`.`gossip_menu_option` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu_option` (`MenuID`, `OptionID`, `OptionIcon`, `OptionText`, `OptionType`, `OptionNPCFlag`, `ActionMenuID`, `ActionPoiID`, `BoxCoded`, `BoxMoney`, `BoxText`) VALUES (@GossipMenu, 0, 3, 'Blue', 3, 128, 601099, 0, 0, 0, ''), (@GossipMenu, 1, 3, 'Green', 3, 128, 601100, 0, 0, 0, ''), (@GossipMenu, 2, 3, 'Orange', 3, 128, 601101, 0, 0, 0, ''), (@GossipMenu, 3, 3, 'Meta', 3, 128, 601106, 0, 0, 0, ''), (@GossipMenu, 4, 3, 'Prismatic', 3, 128, 601105, 0, 0, 0, ''), (@GossipMenu, 5, 3, 'Purple', 3, 128, 601102, 0, 0, 0, ''), (@GossipMenu, 6, 3, 'Red', 3, 128, 601103, 0, 0, 0, ''), (@GossipMenu, 7, 3, 'Yellow', 3, 128, 601104, 0, 0, 0, ''); -- (@GossipMenu, 10, 6, 'Special', 3, 128, 601003, 0, 0, 100, 'These goods are special, so pay up!'); -- NPC Text DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Hello $N. My gems sparkle unlike any other.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Have you seen my selection of precious gemstones?', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Have you seen my selection of precious gemstones?', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- -------------------------------------------------------------------------------------- -- GLYPH MULTI-VENDOR -- -------------------------------------------------------------------------------------- SET @Entry := 601046, @Model := 28119, -- Bald Butler @Name := "<NAME>", @Title := "Glyphs", @Icon := "Buy", @GossipMenu := 60146, @MinLevel := 80, @MaxLevel := 80, @Faction := 35, @NPCFlag := 129, -- Vendor @Scale := 1.0, @Rank := 0, @UnitFlags := 512, @UnitFlags2 := 2048, @DynamicFlags:= 8, @Type := 7, @TypeFlags := 138412032, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, unit_flags2, dynamicflags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, @UnitFlags, @UnitFlags2, @DynamicFlags, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); DELETE FROM `rocket_world`.`gossip_menu_option` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu_option` (`MenuID`, `OptionID`, `OptionIcon`, `OptionText`, `OptionType`, `OptionNPCFlag`, `ActionMenuID`, `ActionPoiID`, `BoxCoded`, `BoxMoney`, `BoxText`) VALUES (@GossipMenu, 0, 3, '<NAME>', 3, 128, 601107, 0, 0, 0, ''), (@GossipMenu, 1, 3, 'Druid', 3, 128, 601108, 0, 0, 0, ''), (@GossipMenu, 2, 3, 'Hunter', 3, 128, 601109, 0, 0, 0, ''), (@GossipMenu, 3, 3, 'Mage', 3, 128, 601110, 0, 0, 0, ''), (@GossipMenu, 4, 3, 'Paladin', 3, 128, 601111, 0, 0, 0, ''), (@GossipMenu, 5, 3, 'Priest', 3, 128, 601116, 0, 0, 0, ''), (@GossipMenu, 6, 3, 'Rogue', 3, 128, 601112, 0, 0, 0, ''), (@GossipMenu, 7, 3, 'Shaman', 3, 128, 601113, 0, 0, 0, ''), (@GossipMenu, 8, 3, 'Warlock', 3, 128, 601114, 0, 0, 0, ''), (@GossipMenu, 9, 3, 'Warrior', 3, 128, 601115, 0, 0, 0, ''); -- (@GossipMenu, 10, 6, 'Special', 3, 128, 601003, 0, 0, 100, 'These goods are special, so pay up!'); -- NPC Text DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Greetings $N. I have the best selection of glyphs for all classes.'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Have you seen my selection of glyphs?', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Have you seen my selection of glyphs?', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- -------------------------------------------------------------------------------------- -- Moofoku - Tauren Female Warrior -- -------------------------------------------------------------------------------------- SET @Entry := 601047, @Model := 601047, -- Custom DBC @Name := "Moofoku", @Title := "Loremaster", @Icon := "Speak", @GossipMenu := 60147, @MinLevel := 85, @MaxLevel := 85, @Faction := 35, @NPCFlag := 129, -- Vendor @Scale := 1.0, @Rank := 3, @UnitFlags := 1, -- 512, @UnitFlags2 := 2048, @DynamicFlags:= 8, @Type := 7, @TypeFlags := 138412032, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, unit_flags2, dynamicflags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, @UnitFlags, @UnitFlags2, @DynamicFlags, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC Text DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`, `em0_1`) VALUES (@Entry, 'Greetings $N. I have what you seek.', '2'); -- Equipped DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 17182, 0, 0, 18019); -- Sulfuras, Hand of Ragnaros, None -- Gossip Menu Option DELETE FROM `rocket_world`.`gossip_menu_option` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu_option` (`MenuID`, `OptionID`, `OptionIcon`, `OptionText`, `OptionType`, `OptionNPCFlag`, `ActionMenuID`, `ActionPoiID`, `BoxCoded`, `BoxMoney`, `BoxText`) VALUES (@GossipMenu, 0, 6, 'The Gift', 3, 128, @Entry, 0, 0, 250000, 'Do you have the gold?'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Aye Mr. Grubbs, May the Warsong never fade.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Aye Mr. Grubbs, May the Warsong never fade.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '30000', '60000', '120000', '300000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- Creature Model Info (Custom DBC/BLP) DELETE FROM `rocket_world`.`creature_model_info` WHERE DisplayID = @Entry; INSERT INTO `rocket_world`.`creature_model_info` (`DisplayID`, `BoundingRadius`, `CombatReach`, `Gender`, `DisplayID_Other_Gender`) VALUES (@Entry, '0', '0', '1', '0'); -- -------------------------------------------------------------------------------------- -- Koiter - Male Orc Warrior - Vendor -- -------------------------------------------------------------------------------------- SET @Entry := 601048, @Model := 601048, -- Custom DBC @Name := "Koiter", @Title := "Sons of the Storm", @Icon := "Speak", @GossipMenu := 60148, @MinLevel := 85, @MaxLevel := 85, @Faction := 35, @NPCFlag := 129, -- @Scale := 1.0, @Rank := 3, @BaseAttack := 0.5, @MinDmg := 75, @MaxDmg := 150, @UnitFlags := 1, -- 512, @UnitFlags2 := 2048, @DynamicFlags:= 8, @Type := 7, @TypeFlags := 138412032, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, mindmg, maxdmg, baseattacktime, unit_class, unit_flags, unit_flags2, dynamicflags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, @MinDmg, @MaxDmg, @BaseAttack,'1', @UnitFlags, @UnitFlags2, @DynamicFlags, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); DELETE FROM `rocket_world`.`gossip_menu_option` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu_option` (`MenuID`, `OptionID`, `OptionIcon`, `OptionText`, `OptionType`, `OptionNPCFlag`, `ActionMenuID`, `ActionPoiID`, `BoxCoded`, `BoxMoney`, `BoxText`) VALUES (@GossipMenu, 0, 6, 'Special', 3, 128, @Entry, 0, 0, 100, 'These goods are special, so pay up!'); -- NPC Text DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`, `em0_1`) VALUES (@Entry, 'Blood and Thunder! I feel the call of battle even in death.', '15'); -- Equipped DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 701012, 0, 0, 18019); -- Koiter's Claymore, None -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Blood and Thunder! I feel the call of battle even in death.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Blood and Thunder! I feel the call of battle even in death.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- Creature Model Info DELETE FROM `rocket_world`.`creature_model_info` WHERE DisplayID = @Entry; INSERT INTO `rocket_world`.`creature_model_info` (`DisplayID`, `BoundingRadius`, `CombatReach`, `Gender`, `DisplayID_Other_Gender`) VALUES (@Entry, '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Koiter's Ghost - Male Orc Warrior - Transparent -- -------------------------------------------------------------------------------------- SET @Entry := 601049, @Model := 601049, -- Custom DBC @Name := "Koiter", @Title := "Sons of the Storm", @Icon := "Speak", @GossipMenu := 60149, @Spell1 := 12024, @MinLevel := 85, @MaxLevel := 85, @Faction := 121, @NPCFlag := 1, -- Vendor @Scale := 1.0, @Rank := 3, @BaseAttack := 0.5, @MinDmg := 75, @MaxDmg := 150, @UnitFlags := 32768, -- 512, @UnitFlags2 := 2048, @DynamicFlags:= 8, @Type := 7, @TypeFlags := 138412032, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, spell1, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, mindmg, maxdmg, baseattacktime, unit_class, unit_flags, unit_flags2, dynamicflags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @Spell1, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, @MinDmg, @MaxDmg, @BaseAttack,'1', @UnitFlags, @UnitFlags2, @DynamicFlags, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- GOSSIP MENU OPTION DELETE FROM `rocket_world`.`gossip_menu_option` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu_option` (`MenuID`, `OptionID`, `OptionIcon`, `OptionText`, `OptionType`, `OptionNPCFlag`, `ActionMenuID`, `ActionPoiID`, `BoxCoded`, `BoxMoney`, `BoxText`) VALUES (@GossipMenu, 0, 6, 'Special', 3, 128, @Entry, 0, 0, 100, 'These goods are special, so pay up!'); -- NPC Text DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`, `em0_1`) VALUES (@Entry, 'Blood and Thunder! I feel the call of battle even in death.', '15'); -- Equipped DELETE FROM `creature_equip_template` WHERE `CreatureID`=@Entry AND `ID`=1; INSERT INTO `creature_equip_template` VALUES (@Entry, 1, 701012, 0, 0, 18019); -- Koiter's Claymore, None -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Blood and Thunder! I feel the call of battle even in death.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Blood and Thunder! I feel the call of battle even in death!', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- Creature Model Info DELETE FROM `rocket_world`.`creature_model_info` WHERE DisplayID = @Entry; INSERT INTO `rocket_world`.`creature_model_info` (`DisplayID`, `BoundingRadius`, `CombatReach`, `Gender`, `DisplayID_Other_Gender`) VALUES (@Entry, '0', '0', '0', '0'); -- Creature Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '25', '0', '100', '0', '0', '0', '0', '0', '11', '18950', '2', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'On Reset - Cast Invisibility and Stealth Detection'); INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '1', '0', '0', '0', '100', '0', '0', '3000', '15000', '20000', '11', '12024', '32', '0', '0', '0', '0', '2', '0', '0', '0', '0', '0', '0', '0', 'In Combat - Cast Net'); INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '2', '0', '6', '0', '100', '0', '0', '0', '0', '0', '214', '0', '0', '0', '0', '0', '0', '7', '0', '0', '0', '0', '0', '0', '0', 'On Death - Send Zone Under Attack'); -- -------------------------------------------------------------------------------------- -- Mr. Grubbs, Moofoku's Pet -- -------------------------------------------------------------------------------------- SET @Entry := 601050, @Model := 7898, -- Carrion Grub @Name := "<NAME>", @Title := "Moo\'s Pet", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 190, @NPCFlag := 0, @Scale := 0.13, @Rank := 0, @Type := 8, -- 8 = Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- -------------------------------------------------------------------------------------- -- Trump (Currency Exchange) -- -------------------------------------------------------------------------------------- SET @Entry := 601051, @Model := 19707, -- Blood Elf Merchant @Name := "Trump", @Title := "Currency Exchange", @Icon := "Speak", @GossipMenu := 60151, @MinLevel := 85, @MaxLevel := 85, @Faction := 35, @NPCFlag := 129, -- Vendor @Scale := 1.0, @Rank := 3, @UnitFlags := 1, -- 512, @UnitFlags2 := 2048, -- @DynamicFlags:= 8, -- @Type := 7, -- @TypeFlags := 138412032, @FlagsExtra := 2, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, unit_flags2, dynamicflags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, @UnitFlags, @UnitFlags2, @DynamicFlags, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- NPC Text DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`, `em1_0`) VALUES (@Entry, 'So to all Americans, in every city near and far, small and large, from mountain to mountain, and from ocean to ocean, hear these words: You will never be ignored again. Your voice, your hopes, and your dreams will define our American destiny. And your courage and goodness and love will forever guide us along the way.', '11'); -- Gossip Menu DELETE FROM `rocket_world`.`gossip_menu` WHERE `MenuID` = @GossipMenu; INSERT INTO `rocket_world`.`gossip_menu` (`MenuID`, `TextID`) VALUES (@GossipMenu, @Entry); -- Gossip Menu Option DELETE FROM `gossip_menu_option` WHERE `MenuID` = @GossipMenu; INSERT INTO gossip_menu_option (`MenuID`, `OptionID`, `OptionIcon`, `OptionText`, `OptionType`, `OptionNPCFlag`, `ActionMenuID`, `ActionPoiID`, `BoxCoded`, `BoxMoney`, `BoxText`) VALUES (@GossipMenu, 0, 3, 'God Bless America! Show me your wares.', 3, 128, 601524, 0, 0, 0, ''); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'So to all Americans, in every city near and far, small and large, from mountain to mountain, and from ocean to ocean, hear these words: You will never be ignored again. Your voice, your hopes, and your dreams will define our American destiny. And your courage and goodness and love will forever guide us along the way.', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'So to all Americans, in every city near and far, small and large, from mountain to mountain, and from ocean to ocean, hear these words: You will never be ignored again. Your voice, your hopes, and your dreams will define our American destiny. And your courage and goodness and love will forever guide us along the way.', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts (Speak) DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '60000', '120000', '180000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- -------------------------------------------------------------------------------------- -- MAGA (Trump's Pet) -- -------------------------------------------------------------------------------------- SET @Entry := 601052, @Model := 25008, -- Imperial Eagle @Name := "MAGA", @Title := "America First!", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 190, @NPCFlag := 0, @Scale := 0.25, @Rank := 0, @Type := 8, -- 8 = Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- Creature Text DELETE FROM `rocket_world`.`creature_text` WHERE `CreatureID` = @Entry; INSERT INTO `rocket_world`.`creature_text` (`CreatureID`, `groupid`, `id`, `text`, `type`, `language`, `probability`, `emote`, `duration`, `sound`, `BroadcastTextID`, `TextRange`, `comment`) VALUES (@Entry, '0', '0', 'Build The Wall!', '12', '0', '100', '0', '0', '0', @Entry, '0', 'Speak'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '0', 'Build The Wall!', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- Smart Scripts DELETE FROM `rocket_world`.`smart_scripts` WHERE `entryorguid` = @Entry; INSERT INTO `rocket_world`.`smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES (@Entry, '0', '0', '0', '1', '0', '100', '0', '45000', '90000', '120000', '600000', '1', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0', '0', '0', 'Speak'); -- -------------------------------------------------------------------------------------- -- Small Turtle - 601063 -- -------------------------------------------------------------------------------------- SET @Entry := 601063, @Model := 16259, -- @Name := "Speedy", @Title := "", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 35, @NPCFlag := 0, @Scale := 1.0, @Rank := 0, @Type := 8, -- Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- -------------------------------------------------------------------------------------- -- Medium Turtle - 601064 -- -------------------------------------------------------------------------------------- SET @Entry := 601064, @Model := 16359, -- @Name := "Shelly", @Title := "", @Icon := NULL, @GossipMenu := 0, @MinLevel := 1, @MaxLevel := 1, @Faction := 35, @NPCFlag := 0, @Scale := 1.0, @Rank := 0, @Type := 8, -- Critter @TypeFlags := 0, @FlagsExtra := 0, @AIName := "SmartAI", @Script := ""; -- NPC DELETE FROM creature_template WHERE entry = @Entry; INSERT INTO creature_template (entry, modelid1, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, faction, npcflag, speed_walk, speed_run, scale, rank, unit_class, unit_flags, type, type_flags, InhabitType, RegenHealth, flags_extra, AiName, ScriptName) VALUES (@Entry, @Model, @Name, @Title, @Icon, @GossipMenu, @MinLevel, @MaxLevel, @Faction, @NPCFlag, 1, 1.14286, @Scale, @Rank, 1, 2, @Type, @TypeFlags, 3, 1, @FlagsExtra, @AIName, @Script); -- ###################################################################################### -- GAME OBJECT CONTENT ADDITIONS -- ###################################################################################### -- -------------------------------------------------------------------------------------- -- Lou the Cabin Boy (Silithus Camp - Tauren in Canoo) -- -------------------------------------------------------------------------------------- SET @Entry := 27923, @GossipMenu := 27923, @GUID := 1993567; -- -------------------------------------------------------------------------------------- -- CLEAN UP CANOE WAYPOINTS -- SET CREATURE MOVEMENTTYPE = '2' FOR ANIMATION TO START -- -------------------------------------------------------------------------------------- DELETE FROM `creature_addon` WHERE `guid`=@GUID; DELETE FROM `db_script_string` WHERE entry >= 2000006053 AND entry <= 2000006055; DELETE FROM `broadcast_text` WHERE ID >= 77503 AND ID <= 77505; DELETE FROM `waypoint_scripts` WHERE guid >= 950 AND guid <= 952; DELETE FROM `waypoint_data` WHERE id = @GUID; -- -------------------------------------------------------------------------------------- -- CANOE CREATURE ADDON (creature_addon) -- -------------------------------------------------------------------------------------- INSERT INTO `creature_addon` (`guid`, `path_id`, `mount`, `bytes1`, `bytes2`, `emote`, `auras`) VALUES (@GUID, @GUID, 0, 0, 0, 0, NULL); -- -------------------------------------------------------------------------------------- -- CANOE WAYPOINT STRINGS (db_script_string) -- -------------------------------------------------------------------------------------- INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`) VALUES (77503, 0, 'Ahh.. the sea. Once it casts its spell, it holds one in its net of wonder forever.'), (77504, 0, 'It\'s not the years in your life, it\'s the life in your years.'), (77505, 0, 'Hey! You over there! Tell Marny I\'ll be there soon!'); -- -------------------------------------------------------------------------------------- -- CANOE WAYPOINT SCRIPTS (waypoint_scripts) -- -------------------------------------------------------------------------------------- INSERT INTO `waypoint_scripts` (`id`, `delay`, `command`, `datalong`, `datalong2`, `dataint`, `x`, `y`, `z`, `o`, `guid`) VALUES (950, 0, 0, 2, 0, 77503, 0, 0, 0, 0, 950), -- Yell (951, 0, 0, 0, 0, 77504, 0, 0, 0, 0, 951), -- Say (952, 0, 0, 0, 0, 77505, 0, 0, 0, 0, 952); -- Say -- -------------------------------------------------------------------------------------- -- CANOE WAYPOINT DATA (waypoint_data) -- -------------------------------------------------------------------------------------- INSERT INTO `rocket_world`.`waypoint_data` (`id`, `point`, `position_x`, `position_y`, `position_z`, `orientation`, `delay`, `move_type`, `action`, `action_chance`, `wpguid`) VALUES (@GUID, '1', '-10806.5', '2381.02', '0.00353344', '0', '0', '0', '950', '100', 0), (@GUID, '2', '-10812.3', '2432', '0.0015548', '0', '3500','0', '952', '100', 0), (@GUID, '3', '-10826.5', '2437.39', '0.00298545', '0', '0', '0', '0', '100', 0), (@GUID, '4', '-10834.1', '2412.9', '0.00169087', '0', '0', '0', '0', '100', 0), (@GUID, '5', '-10819.4', '2186.75', '0.00169087', '0', '0', '0', '0', '100', 0), (@GUID, '6', '-10813.6', '2195.18', '0.00161761', '0', '3500','0', '951', '100', 0), (@GUID, '7', '-10780.9', '2268', '0.00161761', '0', '0', '0', '0', '100', 0), (@GUID, '8', '-10785.2', '2330.89', '0.00161761', '0', '0', '0', '0', '100', 0); -- -------------------------------------------------------------------------------------- -- Barbarian King's Sword (Badlands Crypt) -- -------------------------------------------------------------------------------------- SET @Entry := 144181, @GossipMenu := 12276; -- TODO: Add npc text to object gossip dialog -- GameObject Template UPDATE `rocket_world`.`gameobject_template` SET `type` = '2', `Data6` = @Entry WHERE (`entry` = @Entry); -- NPC Text DELETE FROM `npc_text` WHERE `ID`=@Entry; INSERT INTO `npc_text` (`ID`, `text0_0`) VALUES (@Entry, 'Do you seek the Riddle of Steel $N?'); -- Broadcast Text DELETE FROM `rocket_world`.`broadcast_text` WHERE `ID` = @Entry; INSERT INTO `rocket_world`.`broadcast_text` (`ID`, `Language`, `MaleText`, `FemaleText`, `EmoteID0`, `EmoteID1`, `EmoteID2`, `EmoteDelay0`, `EmoteDelay1`, `EmoteDelay2`, `SoundId`, `Unk1`, `Unk2`, `VerifiedBuild`) VALUES (@Entry, '1', 'Do you seek the Riddle of Steel $N?', '', '0', '0', '0', '0', '0', '0', '0', '0', '1', '12034'); -- -------------------------------------------------------------------------------------- -- Large Backpacks (Hinterlands) -- -------------------------------------------------------------------------------------- SET @Entry := 128100, @BroadcastTextID := 12810, @GossipMenu := 12275; DELETE FROM `rocket_world`.`gameobject_template` WHERE `entry`=@Entry; INSERT INTO `rocket_world`.`gameobject_template` (`entry`, `type`, `displayId`, `name`, `IconName`, `castBarCaption`, `unk1`, `size`, `Data0`, `Data1`, `Data2`, `Data3`, `Data4`, `Data5`, `Data6`, `Data7`, `Data8`, `Data9`, `Data10`, `Data11`, `Data12`, `Data13`, `Data14`, `Data15`, `Data16`, `Data17`, `Data18`, `Data19`, `Data20`, `Data21`, `Data22`, `Data23`, `AIName`, `ScriptName`, `VerifiedBuild`) VALUES (@Entry, '2', '3079', 'Moofoku\'s Backpacks', '', '', '', '1', '0', '3365', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '', '', '12340'); -- TODO: Add npc text to object gossip dialog /* -- ################################################################################### -- -- ____ __ ____ -- /\ _`\ /\ \__ __ /\ _`\ -- \ \,\L\_\ \ ,_\ __ __ __ /\_\ __ ___\ \ \/\_\ ___ _ __ __ -- \/_\__ \\ \ \/ /\ \/\ \ /'_ `\/\ \ /'__`\ /' _ `\ \ \/_/_ / __`\/\`'__\/'__`\ -- /\ \L\ \ \ \_\ \ \_\ \/\ \L\ \ \ \/\ \L\.\_/\ \/\ \ \ \L\ \/\ \L\ \ \ \//\ __/ -- \ `\____\ \__\\/`____ \ \____ \ \_\ \__/.\_\ \_\ \_\ \____/\ \____/\ \_\\ \____\ -- \/_____/\/__/ `/___/> \/___L\ \/_/\/__/\/_/\/_/\/_/\/___/ \/___/ \/_/ \/____/ -- /\___/ /\____/ -- \/__/ \_/__/ http://stygianthebest.github.io -- -- ################################################################################### -- -- -- WORLD: WORLD NPC SPAWN -- -- Places custom NPCs at specific locations in the world. -- -- ################################################################################### -- */ USE stygian_world; -- -------------------------------------------------------------------------------------- -- INITIALIZE -- -------------------------------------------------------------------------------------- SET @GUID := 1993500; DELETE FROM `creature` WHERE `guid` >= @GUID AND `guid` <= @GUID+157; -- -------------------------------------------------------------------------------------- -- NPC SPAWN INDEX -- -------------------------------------------------------------------------------------- -- -- WILDERNESS -- DALARAN -- HINTERLANDS -- UNDERCITY -- SILVERMOON -- SUNROCK RETREAT -- WINTERSPRING -- THUNDER BLUFF -- RATCHET -- BOOTY BAY -- STARTING ZONES -- SILITHUS CAMP -- GM ISLAND -- DUNGEONS/RAIDS -- PORTAL MASTERS -- -- -------------------------------------------------------------------------------------- -- ################################################################################### -- -- WILDERNESS -- ################################################################################### -- -- { -- Koiter's Ghost - The Barrens INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+1, '601049', '1', '1', '1', '0', '1', '47.1423', '-2713.23', '91.6672', '4.76103', '300', '0', '0', '6141', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- <NAME> (Nat Pagle's Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+2, '601005', '1', '1', '1', '0', '1', '-4134.68', '-4046.79', '2.69624', '3.21008', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Bengal Tiger Handler (Stranglethorn Cave) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+10, '601036', '0', '1', '1', '0', '0', '-12832.8', '-1376.24', '113.165', '3.74355', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Trollop (Hmmm.. Ahh!) -- -------------------------------------------------------------------------------------- -- Crypt INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+26, '601017', '1', '1', '1', '0', '0', '4563.85', '-3930.89', '942.178', '4.14652', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Hyjal INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+143, '601017', '0', '1', '1', '0', '0', '-11223.2', '-1406.62', '-15.3612', '4.70242', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Tools - (Ashenvale TalonDeep Path Cave Entrance) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+13, '601009', '1', '1', '1', '0', '0', '1936.73', '-743.61', '114.073', '1.68764', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Black Rats (Barbarian King's Crypt) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+3, '2110', '0', '1', '1', '0', '0', '-6554.18', '-3485.95', '292.678', '4.68442', '300', '6', '0', '1', '0', '1', '0', '0', '0'); INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+4, '2110', '0', '1', '1', '0', '0', '-6541.85', '-3489.82', '292.867', '6.27878', '300', '6', '0', '1', '0', '1', '0', '0', '0'); INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+5, '2110', '0', '1', '1', '0', '0', '-6567.08', '-3489.61', '292.867', '2.68951', '300', '6', '0', '1', '0', '1', '0', '0', '0'); INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+6, '2110', '0', '1', '1', '0', '0', '-6554.48', '-3494.7', '292.867', '4.73547', '300', '6', '0', '1', '0', '1', '0', '0', '0'); INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+7, '2110', '0', '1', '1', '0', '0', '-6554.6', '-3475.9', '295.694', '4.74726', '300', '6', '0', '1', '0', '1', '0', '0', '0'); INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+8, '2110', '0', '1', '1', '0', '0', '-6554.31', '-3467.46', '299.08', '0.00344742', '300', '6', '0', '1', '0', '1', '0', '0', '0'); INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+9, '2110', '0', '1', '1', '0', '0', '-6562.23', '-3467.49', '302.042', '0.00344742', '300', '6', '0', '1', '0', '1', '0', '0', '0'); -- } -- ################################################################################### -- -- DALARAN -- ################################################################################### -- -- { -- Hellscream's Chosen Guild Members INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+148, '601059', '571', '1', '1', '0', '1', '5914.61', '632.007', '645.651', '4.89152', '300', '0', '0', '5342', '0', '0', '0', '0', '0'), (@GUID+149, '601062', '571', '1', '1', '0', '1', '5912.03', '631.569', '645.789', '5.33527', '300', '0', '0', '5342', '0', '0', '0', '0', '0'), (@GUID+150, '601055', '571', '1', '1', '0', '1', '5910.89', '625.229', '646.865', '0.402967', '300', '0', '0', '5342', '0', '0', '0', '0', '0'), (@GUID+151, '601061', '571', '1', '1', '15244', '1', '5920.1', '627.974', '645.728', '3.29325', '300', '0', '0', '5342', '0', '0', '0', '0', '0'), (@GUID+152, '601057', '571', '1', '1', '0', '1', '5918.63', '629.96', '645.64', '3.90979', '300', '0', '0', '5342', '0', '0', '0', '0', '0'), (@GUID+153, '601058', '571', '1', '1', '0', '1', '5916.4', '631.898', '645.586', '4.38103', '300', '0', '0', '5342', '0', '0', '0', '0', '0'), (@GUID+154, '601060', '571', '1', '1', '31840', '1', '5909.38', '627.466', '646.368', '6.24242', '300', '0', '0', '5342', '0', '0', '0', '0', '0'), (@GUID+155, '601056', '571', '1', '1', '0', '1', '5917.83', '623.077', '646.28', '1.85991', '300', '0', '0', '5342', '0', '0', '0', '0', '0'), (@GUID+156, '601053', '571', '1', '1', '0', '1', '5915.28', '622.709', '646.389', '1.45151', '300', '0', '0', '5342', '0', '0', '0', '0', '0'), (@GUID+157, '601054', '571', '1', '1', '0', '1', '5912.25', '623.091', '646.707', '1.12949', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- } -- ################################################################################### -- -- HINTERLANDS -- ################################################################################### -- -- { -- <NAME> INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+122, '601050', '0', '1', '1', '0', '0', '620.007', '-3417.75', '105.754', '4.8514', '300', '0', '0', '42', '0', '0', '0', '0', '0'); -- Moofoku - Shoreline Waterfall INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID, '601047', '0', '1', '1', '0', '0', '621.625', '-3418.64', '105.942', '3.46392', '300', '0', '0', '6141', '0', '0', '0', '0', '0'); -- Seradane INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+120, '601028', '0', '1', '1', '0', '0', '664.312', '-4091.05', '100.713', '0.1141', '300', '0', '0', '5343', '0', '0', '0', '0', '0'); -- } -- ################################################################################### -- -- UNDERCITY -- ################################################################################### -- -- { -- -------------------------------------------------------------------------------------- -- Enchanter (Undercity) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+27, 601015, 0, 1, 1, 0, 1, 1688.05, 45.6258, -62.2919, 6.16394, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Locksmith (Undercity) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+28, 601022, 0, 1, 1, 0, 1, 1534, 329.138, -62.1633, 2.37831, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- } -- ################################################################################### -- -- SILVERMOON -- ################################################################################### -- -- { -- -------------------------------------------------------------------------------------- -- Specialty Gifts (Silvermoon) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+30, 601024, 530, 1, 1, 0, 1, 9542.79, -7448.55, 15.4654, 6.09409, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Clothing (Silvermoon) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+32, 601010, 530, 1, 1, 0, 0, 9638.45, -7384.21, 15.7281, 4.75106, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Currency + MAGA (Silvermoon) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+141, '601052', '530', '1', '1', '0', '0', '9509.95', '-7098.41', '16.3828', '5.53352', '300', '0', '0', '42', '0', '0', '0', '0', '0'); INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+142, '601051', '530', '1', '1', '0', '0', '9511.28', '-7097.95', '16.3859', '5.52468', '300', '0', '0', '6141', '0', '0', '0', '0', '0'); -- } -- ################################################################################### -- -- SUNROCK RETREAT -- ################################################################################### -- -- { -- -------------------------------------------------------------------------------------- -- Beastmaster (Sunrock Retreat) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+33, 601026, 1, 1, 1, 0, 1, 950.892, 899.442, 107.14, 3.81309, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Pet Vendor Exotic (Sunrock Retreat) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+11, 601000, 1, 1, 1, 0, 1, 928.782, 970.332, 103.215, 5.25035, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Fireworks (Sunrock Retreat) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+15, 601012, 1, 1, 1, 0, 1, 870.865, 932.492, 115.501, 1.00529, 300, 0, 0, 2399, 0, 0, 0, 0, 0); -- } -- ################################################################################### -- -- WINTERSPRING -- ################################################################################### -- -- { -- -------------------------------------------------------------------------------------- -- Holiday (WinterSpring) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+12, '601008', '1', '1', '1', '0', '0', '6857.82', '-4676.65', '701.147', '1.5397', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Engineer Contraptions (Everlook) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+29, 601023, 1, 1, 1, 0, 0, 6692.52, -4660.54, 721.695, 5.06463, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Bags (Everlook) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+14, 601011, 1, 1, 1, 0, 0, 6778.46, -4673.04, 723.84, 2.51994, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- } -- ################################################################################### -- -- THUNDER BLUFF -- ################################################################################### -- -- { -- -------------------------------------------------------------------------------------- -- Tabards (Thunder Bluff) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+16, 601025, 1, 1, 1, 0, 0, -1288.81, 129.386, 131.546, 5.26199, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Jukebox NPC (Thunder Bluff) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+17, 601027, 1, 1, 1, 0, 0, -1196.29, 142.095, 142.931, 0.655656, 300, 0, 0, 4163, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Elixers/Flasks (Thunder Bluff) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+18, 601029, 1, 1, 1, 0, 1, -1222.69, 149.248, 133.246, 4.53159, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Pet Vendor (Thunder Bluff) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+19, 601001, 1, 1, 1, 0, 0, -1104.24, 31.6478, 140.599, 3.52235, 300, 0, 0, 4572, 2705, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Cook (Thunder Bluff) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+20, 601002, 1, 1, 1, 0, 1, -1221.31, -20.9276, 165.672, 0.259021, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Potions (Thunder Bluff) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+21, 601004, 1, 1, 1, 0, 1, -1225.41, 149.28, 133.218, 4.9125, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Enchanter (Thunder Bluff) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+22, 601015, 1, 1, 1, 0, 1, -1220.8, 73.2407, 130.162, 4.03285, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Buffer (Thunder Bluff) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+23, 601016, 1, 1, 1, 0, 1, -1206.83, 58.0772, 131.178, 2.9215, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Gambler (Thunder Bluff) -- -------------------------------------------------------------------------------------- DELETE FROM `creature` WHERE `guid`=@GUID+24; INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+24, 601020, 1, 1, 1, 0, 0, -1013, 195.904, 136.64, 2.48562, 300, 0, 0, 4163, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Codebox (Thunder Bluff) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+25, 601021, 1, 1, 1, 0, 0, -1208.77, -87.7774, 161.45, 1.53137, 300, 0, 0, 4163, 0, 0, 0, 0, 0); -- } -- ################################################################################### -- -- RATCHET -- ################################################################################### -- -- { -- Specialty Gifts INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+34, '601024', '1', '1', '1', '0', '1', '-1004.97', '-3702.77', '4.56055', '5.332', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Exotic Pets INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+35, '601000', '1', '1', '1', '0', '1', '-911.296', '-3743.6', '9.65829', '3.88687', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Pets INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+36, '601001', '1', '1', '1', '0', '1', '-909.45', '-3747.25', '9.7803', '3.42348', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- } -- ################################################################################### -- -- BOOTY BAY -- ################################################################################### -- -- { -- Books INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+37, 601007, 0, 1, 1, 0, 0, -14456.7, 446.481, 4.04955, 0.744934, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- Gems INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+38, '601045', '0', '1', '1', '0', '0', '-14399.3', '407.889', '27.7873', '1.18457', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Glyphs INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+39, '601046', '0', '1', '1', '0', '0', '-14447.7', '453.173', '4.04195', '3.68814', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Fisherman INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+40, '601005', '0', '1', '1', '0', '1', '-14430.8', '455.345', '3.69096', '1.06099', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Fireworks INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+41, '601012', '0', '1', '1', '0', '1', '-14431.2', '413.895', '15.2834', '3.74312', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Tools INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+42, '601009', '0', '1', '1', '0', '0', '-14381.3', '375.396', '28.5105', '0.811505', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Bags INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+43, '601011', '0', '1', '1', '0', '0', '-14466.9', '407.893', '25.0617', '2.07416', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Potions INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+44, '601004', '0', '1', '1', '0', '1', '-14493.8', '428.583', '34.5824', '6.18691', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Elixer/Flash INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+45, '601029', '0', '1', '1', '0', '1', '-14487.1', '423.513', '34.5871', '0.98365', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Food INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+46, '601002', '0', '1', '1', '0', '1', '-14430.5', '423.593', '4.16017', '2.11092', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Locksmith INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+47, '601022', '0', '1', '1', '0', '1', '-14450.7', '447.056', '15.6355', '1.29018', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Gambler INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+48, '601020', '0', '1', '1', '0', '0', '-14457.8', '500.532', '15.1142', '3.9204', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Artifacts INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+49, '601006', '0', '1', '1', '0', '1', '-14445.4', '503.154', '21.7678', '4.21636', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Clothing INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+50, '601010', '0', '1', '1', '0', '0', '-14436.2', '381.668', '32.3115', '1.51851', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Tabards INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+51, '601025', '0', '1', '1', '0', '0', '-14432.9', '388.867', '32.326', '2.6652', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Codebox INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+52, '601021', '0', '1', '1', '0', '0', '-14397.3', '427.485', '7.90583', '5.3552', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Enchanter INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+53, '601015', '0', '1', '1', '0', '1', '-14375.4', '400.745', '6.62739', '1.80913', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- Global Trainer INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+54, '70105', '0', '1', '1', '0', '1', '-14352.3', '409.032', '6.63629', '1.95051', '300', '0', '0', '4274', '3994', '0', '0', '0', '0'); -- Buffer INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+55, '601016', '0', '1', '1', '0', '1', '-14289.3', '531.267', '8.93445', '2.70057', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- } -- ################################################################################### -- -- STARTING ZONES -- ################################################################################### -- -- { -- -------------------------------------------------------------------------------------- -- Heirloom Vendor -- -------------------------------------------------------------------------------------- SET @BOA := 601044; INSERT INTO `creature` (`guid`,`id`,`map`,`spawnMask`,`phaseMask`,`modelid`,`equipment_id`,`position_x`,`position_y`,`position_z`,`orientation`,`spawntimesecs`,`spawndist`,`currentwaypoint`,`curhealth`,`curmana`,`MovementType`,`npcflag`,`unit_flags`,`dynamicflags`) VALUES (@GUID+56,@BOA,0,1,1,0,0,-9022.275391,-76.134964,88.489632,5.9219,100,0,0,4274,3994,0,0,0,0), -- Human (Northshire Valley) (@GUID+57,@BOA,0,1,1,0,0,-6170.66,350.627,400.116,1.93837,100,0,0,4274,3994,0,0,0,0), -- Dwarf and Gnome (Coldridge Valley) (@GUID+58,@BOA,1,1,1,0,0,10411.7,781.667,1322.71,5.26217,100,0,0,4274,3994,0,0,0,0), -- NightElf (Shadowglen) (@GUID+59,@BOA,530,1,1,0,0,-4112.79,-13749,73.5646,4.35504,100,0,0,4274,3994,0,0,0,0), -- Draenei (Crash Site) (@GUID+60,@BOA,1,1,1,0,0,-597.151,-4210.22,38.4318,4.08879,100,0,0,4274,3994,0,0,0,0), -- Orc and Troll (Valley of Trial) (@GUID+61,@BOA,0,1,1,0,0,1883.85,1614.12,93.4042,4.55138,100,0,0,4274,3994,0,0,0,0), -- Undead (Deathknell) (@GUID+62,@BOA,1,1,1,0,0,-2899.01,-231.723,53.8403,4.66684,100,0,0,4274,3994,0,0,0,0), -- Tauren (Camp Narache) (@GUID+63,@BOA,530,1,1,0,0,10359.4,-6408.47,38.5311,1.88496,100,0,0,4274,3994,0,0,0,0), -- BloodElf (The Sunspire) (@GUID+64,@BOA,609,1,1,0,0,2435.74,-5610.41,420.092,3.71887,100,0,0,4274,3994,0,0,0,0), -- DeathKnight (The Heart of Acherus) #1 (@GUID+65,@BOA,0,1,1,0,0,2435.74,-5610.41,420.092,3.71887,100,0,0,4274,3994,0,0,0,0); -- DeathKnight (The Heart of Acherus) #2 -- } -- ################################################################################### -- -- SILITHUS CAMP -- ################################################################################### -- -- { -- -------------------------------------------------------------------------------------- -- Artifacts (Silithis Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+31, 601006, 1, 1, 1, 0, 1, -10710.8, 2489.71, 7.92193, 4.76729, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Global Trainer (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+66, '70105', '1', '1', '1', '0', '1', '-10727.8', '2488.44', '7.30801', '4.0446', '300', '0', '0', '4274', '3994', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Lou the Cabin Boy (Silithus Camp - Tauren in Canoe) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+67, '27923', '1', '1', '1', '0', '0', '-10806.6', '2380.73', '0.214895', '1.65698', '300', '0', '0', '8982', '0', '2', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Wolfie the Dog (Silithus Camp - Random Movement) -- -------------------------------------------------------------------------------------- SET @Entry := 601043, @SpawnDist := 0, @MovementType := 0; INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+68, @Entry, '1', '1', '1', '0', '0', '-10721.8', '2410.1', '7.60599', '2.16358', '300', '0', '0', '42', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Speedy (Turtle, Silithus Camp - Random Movement) -- -------------------------------------------------------------------------------------- SET @Entry := 601063, @SpawnDist := 20, @MovementType := 1; INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+146, @Entry, '1', '1', '1', '0', '0', -10740.6, 2430.06, 6.73322, 6.2533, '300', @SpawnDist,'0', '0', '0', @MovementType, '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Shelly (Turtle, Silithus Camp - By Sea) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+147, '601064', '1', '1', '1', '0', '0', '-10670.8', '2523', '0.330614', '1.92402', '300', '0', '0', '71', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Spirit (Horse, Silithus Camp - Random Movement) -- -------------------------------------------------------------------------------------- SET @Entry := 601042, @SpawnDist := 20, @MovementType := 1; INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+69, @Entry, '1', '1', '1', '0', '0', -10740.6, 2430.06, 6.73322, 6.2533, '300', @SpawnDist,'0', '0', '0', @MovementType, '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- MerryLegs (Horse, Silithus Camp - Random Movement) -- -------------------------------------------------------------------------------------- SET @Entry := 601041, @SpawnDist := 20, @MovementType := 1; INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+70, @Entry, '1', '1', '1', '0', '0', -10740.6, 2430.06, 6.73322, 6.2533, '300', @SpawnDist,'0', '0', '0', @MovementType, '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Hidalgo (Horse, Silithus Camp - Random Movement) -- -------------------------------------------------------------------------------------- SET @Entry := 601040, @SpawnDist := 20, @MovementType := 1; INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+71, @Entry, '1', '1', '1', '0', '0', -10740.6, 2430.06, 6.73322, 6.2533, '300', @SpawnDist,'0', '0', '0', @MovementType, '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- <NAME> (Silithus Camp) -- -------------------------------------------------------------------------------------- SET @Entry := 601039, @SpawnDist := 0, @MovementType := 0; INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+72, @Entry, '1', '1', '1', '0', '0', '-10714.3', '2420.37', '7.60684', '4.60612', '300', @SpawnDist,'0', '0', '0', @MovementType, '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Black Beauty (Horse, Silithus Camp - Random Movement) -- -------------------------------------------------------------------------------------- SET @Entry := 601038, @SpawnDist := 20, @MovementType := 1; INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+73, @Entry, 1, 1, 1, 0, 0, -10740.6, 2430.06, 6.73322, 6.2533, 300, @SpawnDist,'0', 0, 0, @MovementType, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Beastmaster (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+74, 601026, 1, 1, 1, 0, 1, -10724.7, 2443.98, 7.60624, 4.33535, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Buffer (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+75, 601016, 1, 1, 1, 0, 1, -10704.4, 2484.29, 7.92193, 3.42427, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Enchanter (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+76, 601015, 1, 1, 1, 0, 1, -10713.3, 2475.62, 7.92193, 1.08771, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Fisherman (Silithus Camp - Waypoint Animated) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+77, 601005, 1, 1, 1, 0, 1, -10749.5, 2517.59, 1.57246, 1.84172, 300, 0, 0, 5342, 0, 2, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- <NAME> (Silithus Camp - Random Movement) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+78, 601030, 1, 1, 1, 0, 0, -10740.6, 2430.06, 6.73322, 6.2533, 300, 25, 0, 42, 0, 1, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- <NAME> (Silithus Camp - Random Movement) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+79, 601031, 1, 1, 1, 0, 0, -10740.6, 2430.06, 6.73322, 6.2533, 300, 25, 0, 42, 0, 1, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Transmogrifier (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+80, 601013, 1, 1, 1, 0, 0, -10717.2, 2486.49, 7.92193, 5.72547, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Banker (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+81, '601034', '1', '1', '1', '0', '1', '-10716', '2468.83', '7.6044', '3.81682', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Currency (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+82, '601051', '1', '1', '1', '0', '0', '-10706.1', '2476.37', '7.92189', '2.26568', '300', '0', '0', '6141', '0', '0', '0', '0', '0'); -- Eagle (#MAGA) INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+140, '601052', '1', '1', '1', '0', '0', '-10705', '2477.45', '9.38379', '2.35598', '300', '0', '0', '42', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Cloth Goods (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+83, 601518, 1, 1, 1, 0, 1, -10709.1, 2413.96, 7.60836, 4.24502, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Metal/Stone Goods (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+84, 601560, 1, 1, 1, 0, 1, -10711.5, 2409.03, 7.60599, 1.24087, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Elemental Goods (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+85, 601528, 1, 1, 1, 0, 1, -10708.1, 2410.3, 7.60954, 2.62319, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Legendary Item Vendor (Silithus Cave) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+86, 601028, 1, 1, 1, 0, 0, -10666.5, 2086.56, -47.4262, 0.321985, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Mounts (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+87, 601033, 1, 1, 1, 0, 1, -10800, 2180.89, 2.02087, 2.63022, 300, 0, 0, 5342, 0, 0, 0, 134255104, 0); -- -------------------------------------------------------------------------------------- -- Exotic Mounts (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+88, 601032, 1, 1, 1, 0, 1, -10796.9, 2195.95, 2.16213, 3.27425, 300, 0, 0, 5342, 0, 0, 0, 134255104, 0); -- -------------------------------------------------------------------------------------- -- Spirit Healer (Silithus Camp) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+119, '6491', '1', '1', '1', '0', '0', '-10715.8', '2350.14', '8.88242', '3.14925', '300', '0', '0', '4121', '0', '0', '0', '0', '0'); -- } -- ################################################################################### -- -- GM ISLAND -- ################################################################################### -- -- { -- -------------------------------------------------------------------------------------- -- Global Vendor Glyphs (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+144, '601045', '1', '1', '1', '0', '0', '16240.5', '16292', '22.9317', '1.48513', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Global Vendor Gems (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+145, '601046', '1', '1', '1', '0', '0', '16241.7', '16306.8', '20.9005', '2.45117', '300', '0', '0', '5342', '0', '0', '0', '0', '0'); -- -------------------------------------------------------------------------------------- -- Global Trainer (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `stygian_world`.`creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+90, '70105', '1', '1', '1', '0', '0', '16254.7', '16304.6', '20.8447', '3.03001', '300', '0', '0', '4274', '3994', '0', '0', '134217728', '0'); -- -------------------------------------------------------------------------------------- -- All Mounts Vendor (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+91, 601014, 1, 1, 1, 0, 0, 16228.8, 16259.4, 13.4481, 3.11482, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Beastmaster (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+92, 601026, 1, 1, 1, 0, 1, 16207.8, 16236.9, 7.48562, 5.98155, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Buffer (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+93, 601016, 1, 1, 1, 0, 0, 16217.2, 16262.5, 13.5767, 6.22107, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Codebox (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+94, 601021, 1, 1, 1, 0, 0, 16228.4, 16262.8, 13.3786, 3.29546, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Enchanter (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+95, 601015, 1, 1, 1, 0, 1, 16217, 16259.7, 13.5628, 6.22107, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- GM Island Decorator (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+96, 601035, 1, 1, 1, 0, 0, 16253.8, 16234.9, 33.5163, 2.3098, 300, 0, 0, 53420, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Transmogrifier (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+97, 601013, 1, 1, 1, 0, 0, 16228.7, 16255.8, 13.3435, 3.11482, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Mounts (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+98, 601033, 1, 1, 1, 0, 1, 16216.3, 16225.2, 4.94466, 2.66716, 300, 0, 0, 5342, 0, 0, 0, 134255104, 0); -- -------------------------------------------------------------------------------------- -- Exotic Mounts (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+99, 601032, 1, 1, 1, 0, 1, 16219.2, 16230.7, 7.52852, 2.66716, 300, 0, 0, 5342, 0, 0, 0, 134255104, 0); -- -------------------------------------------------------------------------------------- -- Rare Pets (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+100, 601000, 1, 1, 1, 0, 1, 16211.2, 16242.9, 10.7703, 5.6713, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Pets (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+101, 601001, 1, 1, 1, 0, 1, 16222.3, 16235.7, 9.54736, 2.62788, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Food (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+102, 601002, 1, 1, 1, 0, 1, 16224.2, 16238.8, 10.5448, 2.69856, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Armor (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+103, 601003, 1, 1, 1, 0, 1, 16225.7, 16241.9, 11.4356, 2.70249, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Potions (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+104, 601004, 1, 1, 1, 0, 1, 16226.7, 16244.9, 12.0007, 2.91062, 300, 0, 0, 5342, 0, 0, 0, 0, 0); DELETE FROM `creature` WHERE `guid`=1980706; -- -------------------------------------------------------------------------------------- -- Fishing (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+105, 601005, 1, 1, 1, 0, 1, 16227.3, 16247.6, 12.3907, 2.80068, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Artifacts (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+106, 601006, 1, 1, 1, 0, 1, 16228, 16250.6, 12.8686, 2.91062, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Books (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+107, 601007, 1, 1, 1, 0, 0, 16228.1, 16253.2, 13.1069, 3.15802, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Holiday (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+108, 601008, 1, 1, 1, 0, 0, 16213.7, 16245.9, 12.0913, 5.93833, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Tools (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+109, 601009, 1, 1, 1, 0, 0, 16214.8, 16248.2, 12.4535, 5.93833, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Clothing (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+110, 601010, 1, 1, 1, 0, 0, 16216.2, 16250.8, 12.7625, 5.93833, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Bags (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+111, 601011, 1, 1, 1, 0, 0, 16217.1, 16253.4, 13.042, 5.93833, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Fireworks (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+112, 601012, 1, 1, 1, 0, 1, 16217.2, 16256.1, 13.3398, 0.138163, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Locksmith (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+113, 601022, 1, 1, 1, 0, 1, 16227.6, 16265.9, 13.2387, 3.13053, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Engineer (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+114, 601023, 1, 1, 1, 0, 0, 16227, 16269.1, 13.1011, 3.13053, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Specialty (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+115, 601024, 1, 1, 1, 0, 1, 16216.9, 16266.1, 13.3949, 0.149947, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Tabards (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+116, 601025, 1, 1, 1, 0, 0, 16217.1, 16269.5, 13.1584, 6.08756, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Legendary (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+117, 601028, 1, 1, 1, 0, 0, 16209.6, 16240.2, 9.14474, 5.67523, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- -------------------------------------------------------------------------------------- -- Elixer/Flasks (GM Island) -- -------------------------------------------------------------------------------------- INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES (@GUID+118, 601029, 1, 1, 1, 0, 1, 16221.4, 16233.2, 8.7621, 2.66323, 300, 0, 0, 5342, 0, 0, 0, 0, 0); -- } -- ################################################################################### -- -- DUNGEONS, RAIDS -- ################################################################################### -- -- { -- NO DATA -- } -- ################################################################################### -- -- PORTAL MASTER -- ################################################################################### -- -- { INSERT INTO creature (guid, id, map, spawnMask, phaseMask, modelid, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, curhealth, curmana) VALUES (@GUID+123, '601019', 1, 1, 1, 0, 16207.2, 16212.8, 1.01735, 1.73647, 25, 0, 13700, 6540), -- GM Island (@GUID+124, '601019', 0, 1, 1, 0, -13180.5, 342.503, 43.1936, 4.32977, 25, 0, 13700, 6540), (@GUID+125, '601019', 530, 1, 1, 0, -3862.69, -11645.8, -137.629, 2.38273, 25, 0, 13700, 6540), (@GUID+126, '601019', 0, 1, 1, 0, -4898.37, -965.118, 501.447, 2.25986, 25, 0, 13700, 6540), (@GUID+127, '601019', 0, 1, 1, 0, -8845.09, 624.828, 94.2999, 0.44062, 25, 0, 13700, 6540), (@GUID+128, '601019', 1, 1, 1, 0, 1599.25, -4375.85, 10.0872, 5.23641, 25, 0, 13700, 6540), (@GUID+129, '601019', 1, 1, 1, 0, -1277.65, 72.9751, 128.742, 5.95567, 25, 0, 13700, 6540), (@GUID+130, '601019', 0, 1, 1, 0, 1637.21, 240.132, -43.1034, 3.13147, 25, 0, 13700, 6540), (@GUID+131, '601019', 530, 1, 1, 0, 9741.67, -7454.19, 13.5572, 3.14231, 25, 0, 13700, 6540), (@GUID+132, '601019', 571, 1, 1, 0, 5807.06, 506.244, 657.576, 5.54461, 25, 0, 13700, 6540), (@GUID+133, '601019', 1, 1, 1, 0, 9866.83, 2494.66, 1315.88, 5.9462, 25, 0, 13700, 6540), (@GUID+134, '601019', 0, 1, 1, 0, -14279.8, 555.014, 8.90011, 3.97606, 25, 0, 13700, 6540), (@GUID+135, '601019', 1, 1, 1, 0, -10750.6, 2470.34, 5.34563, 5.86648, 25, 0, 13700, 6540), -- Silithus Camp (@GUID+136, '601019', 1, 1, 1, 0, 6766.89, -4638.56, 722.002, 0.649926, 25, 0, 13700, 6540), -- Winterspring (@GUID+137, '601019', 1, 1, 1, 0, 1009.35, 1031.26, 104.883, 1.52364, 25, 0, 13700, 6540), -- Sunrock Retreat (@GUID+138, '601019', 451, 1, 1, 0, 16349.1, -16164.1, 39.9247, 4.99547, 25, 0, 13700, 6540), -- Designer Isle (@GUID+139, '601019', 451, 1, 1, 0, 16189.9, 16139.3, 71.3156, 5.48912, 25, 0, 13700, 6540); -- Programmer Isle -- } <file_sep>/README.md # Custom_SQL Custom sql's , e.g disable flying in arena and battleground and azeroth flying
99ae1b8ea25829730c06ad71f75c073e0cd0777a
[ "Markdown", "SQL" ]
2
SQL
xRouty/Custom_SQL
4424e4edba38f3f7704650314058dd2c11dc71c9
c6040ab7536ce77b95affd0a1662cc312283db2f
refs/heads/main
<file_sep>module github.com/reymandhan/treasure go 1.16 <file_sep>package main import "fmt" // initial map var treasureMap = [6][8]string{ {"#", "#", "#", "#", "#", "#", "#", "#"}, {"#", ".", ".", ".", ".", ".", ".", "#"}, {"#", ".", "#", "#", "#", ".", ".", "#"}, {"#", ".", ".", ".", "#", ".", "#", "#"}, {"#", "X", "#", ".", ".", ".", ".", "#"}, {"#", "#", "#", "#", "#", "#", "#", "#"}, } // start position const x, y int = 1, 4 func init() { fmt.Println("Initial Map") printMap(0, 0) } func main() { fmt.Println("\nSearching for Treasure...") total := 0 for i := 1; i <= y; i++ { for j := 1; j < len(treasureMap[0])-x; j++ { for k := 1; k < len(treasureMap); k++ { if y-i+k >= len(treasureMap) { break } newX, newY, status := move(i, j, k) if status { fmt.Printf("\nPossible treasure location found in (%v,%v) by move north %v step(s), east %v step(s), south %v step(s)\n", newX, newY, i, j, k) printMap(newX, newY) total++ } } } } fmt.Printf("\nThere are total %v possible treasure location\n", total) fmt.Println("Press any key to exit") fmt.Scanf("h") } // if found clear path, return true and posible treasure position func move(north, east, south int) (int, int, bool) { currPosX, currPosY := x, y //moving north for i := 1; i <= north; i++ { if treasureMap[currPosY-i][currPosX] == "#" { //blocked by obstacle return -1, -1, false } } currPosY -= north //moving east for i := 1; i <= east; i++ { if treasureMap[currPosY][currPosX+i] == "#" { //blocked by obstacle return -1, -1, false } } currPosX += east //moving south for i := 1; i <= south; i++ { if treasureMap[currPosY+i][currPosX] == "#" { //blocked by obstacle return -1, -1, false } } currPosY += south return currPosX, currPosY, true } func printMap(x, y int) { newMap := treasureMap if x != 0 && y != 0 { newMap[y][x] = "$" } for _, row := range newMap { for _, val := range row { fmt.Printf(" %v ", val) } fmt.Println("") } } <file_sep># Task 2 : Treasure hunt <br/> Run the app : - Go to project root folder - run `go run .` It will show all possible location of the treasure
f8e5ff19b28ca5b7b6b578ee35756e14bf548ab9
[ "Go", "Go Module", "Markdown" ]
3
Go Module
reymandhan/treasure
c17f179c418f9eb4d501bf66a7610498b467b1f3
3921594e0808c7e3c946e246e8fbf6f445211a55
refs/heads/master
<file_sep># Http Client Factory This library is aimed at improving the development experience for REST-like calls in NodeJS. It builds off the Node `http` library. It's inspired by the System.Net.Http.HttpClientFactory library in .NET. ##Basic Usage ```javascript var HttpClientFactory = require("http-client-factory") //Issues a GET request to http://www.tempuri.org/my/endpoint?some=value&search=text var promise = HttpClientFactory.getClient() .get("http://www.tempuri.org/my/endpoint", { some: "value", search: "text"}) promise.then(function (response) { //Do something with the response }) .catch(function (error) { //Do something with the error }) ``` ## API `HttpClientFactory` - `.getClient(AgentOptions)` - Returns `HttpClient` - `AgentOptions` is from `http` library - If `AgentOptions` is null, default settings are used (recommended) HttpClient - `.addHeader(headerKey, headerValue)` - Adds a header to the request with the given key and value - `.setAuthorization(scheme, parameter)` - Sets the Authorization header to `scheme parameter` - Returns `HttpClient` - `.setBasicAuth(username, password)` - Sets the Authorization header to use basic authentication with the given credentials - Returns `HttpClient` - `.addHandler(HttpClientHandler)` - Adds an HttpClientHandler to run on requests and responses - Request handlers are run in the order they're added. The first handler added will run first - Response handlers are run in the reverse order. The _last_ handler added will run first - Returns `HttpClient` - `.get(url, RequestBody)` - Returns `Promise` - `.post(url, RequestBody)` - Returns `Promise` - `.put(url, RequestBody)` - Returns `Promise` - `.delete(url, RequestBody)` - Returns `Promise` - `.send(HttpRequest, RequestBody)` - Sends a [raw request](https://nodejs.org/api/http.html#http_http_request_options_callback) - Returns `Promise` HttpClientHandler - `onRequest: function (HttpRequest, body)` - Reads or modifies request and/or body as needed - Leave undefined if not needed - `onResponse: function (HttpResponse)` - Reads or modifies response if needed - Leave undefined if not needed RequestBody - Normal JSON object - For `.get()`, `.delete()`, `.head()`, and `.options()` requests, this will be converted into query string parameters - For `.put()`, `.post()`, and `.patch()` requests, this will be sent as JSON content ##Reading the Response The response is a typical HTTP response as defined by the `http` library, with the addition of a `body` property which contains the response content (in string form). ##Handlers ### Setting authorization headers ```javascript var handler = { onRequest: function (req) { req.headers.authorization = "sampleAuthScheme authValue"; } } //Issues a POST request to the URL //with the authorization header set to "sampleAuthScheme authValue" //and a JSON payload of { "postdata": "goes here" } HttpClientFactory.getClient() .addHandler(handler) .post("http://www.tempuri.org/my/endpoint", { postdata: "goes here" }) ``` As of v0.2.0, this can be accomplished by calling `client.setAuthorization("sampleAuthScheme", "authValue")` ### Logging request/response data ```javascript var traceLogHandler = { onRequest: function (req, body) { var logger = require("myTraceLogger") logger.logRequest(req.href, req.headers, body) }, onResponse: function (response) { var logger = require("myTraceLogger") logger.logResponse(response.headers, response.body) } } //Logs both request and response data to myTraceLogger HttpClientFactory.getClient() .addHandler(traceLogHandler) .post("http://www.tempuri.org/my/endpoint", { postdata: "goes here" }) ``` ##Promises `httpClientFactory` uses the [bluebird](http://www.npmjs.org/package/bluebird) library for promises<file_sep> function getClient(agentOptions) { var _url = require("url"); var _qs = require("querystring"); var Promise = require("bluebird"); var _handlers = []; function addHandler(handler) { _handlers.push(handler); return this; } function addHeader(key, value) { addHandler({ onRequest: function (req) { if (!key || key.length === 0) throw new Error("Header key is required") req.headers[key] = value } }) return this } function setAuthorization(scheme, value) { addHandler({ onRequest : function(req) { req.headers.authorization = scheme + " " + value } }) return this; } function setBasicAuth(username, password) { var param = username + ":" + password; setAuthorization("Basic", new Buffer(param).toString("base64")) return this; } function get(url, data) { return queryStringInternal(url, data, "get"); } function del(url, data) { return queryStringInternal(url, data, "delete"); } function head(url, data) { return queryStringInternal(url, data, "head"); } function options(url, data) { return queryStringInternal(url, data, "options"); } function put(url, data) { var request = getRequest(url); request.method = "put"; return sendRequest(request, data); } function post(url, data) { var request = getRequest(url); request.method = "post"; return sendRequest(request, data); } function patch(url, data) { var request = getRequest(url); request.method = "patch"; return sendRequest(request, data); } function sendRaw(request, data) { return sendRequest(request, data); } function queryStringInternal(url, data, method) { if (data) { var query = _qs.stringify(data); url += "?" + query; } var request = getRequest(url); request.method = method; return sendRequest(request); } function getRequest(url) { var request = _url.parse(url); request.headers = { "Content-Type": "application/json" } if (agentOptions) { var agent = getProtocol(request).Agent; request.agent = new agent(agentOptions); } return request; } function getProtocol(request) { return request.protocol == "https:" ? require("https") : require("http"); } function sendRequest(request, body) { var promise = new Promise(function (resolve, reject) { _handlers.forEach(function (h) { if (h.onRequest) { h.onRequest(request, body); } }); if (body) { if (body.constructor !== String) { body = JSON.stringify(body); } if (!request.headers) { request.headers = {} } request.headers['Content-Length'] = body.length; } var req = getProtocol(request).request(request, function (response) { var body = ""; response.on("data", function (chunk) { body += chunk; }); response.on("end", function () { response.body = body; for (var i = _handlers.length - 1; i >= 0; i--) { var h = _handlers[i]; if (h.onResponse) { h.onResponse(response); } } resolve(response); }); }); if (body) { req.write(body); } req.on("error", (err) => { reject(err) }) req.end(); }); return promise; } return { get: get, delete: del, head: head, options: options, put: put, post: post, patch: patch, send: sendRaw, addHeader: addHeader, setAuthorization: setAuthorization, setBasicAuth: setBasicAuth, addHandler: addHandler }; } module.exports = { getClient: getClient };<file_sep>var _ = require("underscore"); var _proxyquire = require("proxyquire"); var _httpMock = { request: function () {} }; var _httpsMock = { request: function () {} }; _proxyquire("../lib/httpClientFactory", { "http": _httpMock, "https": _httpsMock, "@noCallThru": true }); var _httpClientFactory; beforeEach(function () { _httpClientFactory = require("../lib/httpClientFactory"); }); describe("Basic HTTP calls", function () { it("sends delete method for delete", function() { //Arrange setHttpResult({ statusCode: 404 }); //Act var result = _httpClientFactory.getClient().delete("http://www.tempuri.org/some/path", { query: "param1", q2: "p2" }).value(); //Assert expect(result.statusCode).toBe(404); expectRequestCalled({ protocol: "http:", host: "www.tempuri.org", pathname: "/some/path", query: "query=param1&q2=p2", method: "delete" }); }); it("sends get method for get", function() { //Arrange setHttpResult({ statusCode: 200 }); //Act var result = _httpClientFactory.getClient().get("http://www.tempuri.org/some/path", { query: "param1", q2: "p2" }).value(); //Assert expect(result.statusCode).toBe(200); expectRequestCalled({ protocol: "http:", host: "www.tempuri.org", pathname: "/some/path", query: "query=param1&q2=p2", method: "get" }); }); it("sends get method for head", function() { //Arrange setHttpResult({ statusCode: 200 }); //Act var result = _httpClientFactory.getClient().head("http://www.tempuri.org/some/path", { query: "param1", q2: "p2" }).value(); //Assert expect(result.statusCode).toBe(200); expectRequestCalled({ protocol: "http:", host: "www.tempuri.org", pathname: "/some/path", query: "query=param1&q2=p2", method: "head" }); }); it("sends get method for options", function() { //Arrange setHttpResult({ statusCode: 200 }); //Act var result = _httpClientFactory.getClient().options("http://www.tempuri.org/some/path", { query: "param1", q2: "p2" }).value(); //Assert expect(result.statusCode).toBe(200); expectRequestCalled({ protocol: "http:", host: "www.tempuri.org", pathname: "/some/path", query: "query=param1&q2=p2", method: "options" }); }); it("sends put method and body for put", function () { //Arrange var response = { some: "content" }; setHttpResult({ statusCode: 200, }, response); var request = { req: "something", obj: { deep: "request" } }; //Act var result = _httpClientFactory.getClient().put( "http://www.tempuri.org/some/path", request).value(); //Assert expect(result.statusCode).toBe(200); expect(_.isEqual(JSON.parse(result.body), response)).toBe(true); expectRequestCalled({ protocol: "http:", host: "www.tempuri.org", pathname: "/some/path", method: "put", headers: { 'Content-Type': 'application/json', 'Content-Length': 44 } }, request); }); it("sends post method and body for post", function () { //Arrange var response = { some: "content" }; setHttpResult({ statusCode: 200, }, response); var request = { req: "something", obj: { deep: "request" } }; //Act var result = _httpClientFactory.getClient().post( "http://www.tempuri.org/some/path", request).value(); //Assert expect(result.statusCode).toBe(200); expect(_.isEqual(JSON.parse(result.body), response)).toBe(true); expectRequestCalled({ protocol: "http:", host: "www.tempuri.org", pathname: "/some/path", method: "post", headers: { 'Content-Type': 'application/json', 'Content-Length': 44 } }, request); }); it("sends patch method and body for patch", function () { //Arrange var response = { some: "content" }; setHttpResult({ statusCode: 200, }, response); var request = { req: "something", obj: { deep: "request" } }; //Act var result = _httpClientFactory.getClient().patch( "http://www.tempuri.org/some/path", request).value(); //Assert expect(result.statusCode).toBe(200); expect(_.isEqual(JSON.parse(result.body), response)).toBe(true); expectRequestCalled({ protocol: "http:", host: "www.tempuri.org", pathname: "/some/path", method: "patch", headers: { 'Content-Type': 'application/json', 'Content-Length': 44 } }, request); }); it("allows sending of any content", function () { //Arrange var response = { some: "content" }; setHttpResult({ statusCode: 200, }, response); var request = { method: "post" } //Act var result = _httpClientFactory.getClient().send(request, "this is not json").value(); //Assert expect(result.statusCode).toBe(200); expect(_.isEqual(JSON.parse(result.body), response)).toBe(true); expectRequestCalled(request, "this is not json"); }); it("allows sending requests over HTTPS", function () { var response = { some: "content" }; setHttpResult({ statusCode: 200, }, response, true); var request = { method: "post" } //Act var result = _httpClientFactory.getClient().post( "https://www.tempuri.org/some/path", request).value(); //Assert expect(result.statusCode).toBe(200); expectRequestCalled({ protocol: "https:", host: "www.tempuri.org", pathname: "/some/path", method: "post" }, request, true) }) }); describe("HTTP agent", function () { it("allows passing agent information", function () { //Arrange setHttpResult({ statusCode: 200 }, null, true); var agentConfig = { keepAlive: true } //Act _httpClientFactory.getClient(agentConfig).post( "https://www.tempuri.org/some/path").value(); //Assert expectRequestCalled({ agent: jasmine.objectContaining({ keepAlive: true }) }, null, true) }) }) describe("Headers", function () { it("throws an exception if the header key is null", function () { //Arrange //Act var result = _httpClientFactory.getClient() .addHeader(null, "headerValue") .get("testuri").reason(); //Assert expect(result.message).toBe("Header key is required") }); it("throws an exception if the header key is empty", function () { //Arrange //Act var result = _httpClientFactory.getClient() .addHeader("", "headerValue") .get("testuri").reason(); //Assert expect(result.message).toBe("Header key is required") }); it("adds the provided header to the request", function () { //Arrange setHttpResult({ statusCode: 200}) //Act _httpClientFactory.getClient() .addHeader("headerKey", "headerValue") .get("testuri"); //Assert expectRequestCalled({ headers: { headerKey: "headerValue", "Content-Type": "application/json" } }) }); }) describe("Authorization", function () { it("allows for setting any authorization", function () { //Arrange setHttpResult({ statusCode: 200}) //Act _httpClientFactory.getClient() .setAuthorization("authScheme", "authValue") .get("testuri") //Assert expectRequestCalled({ headers: { authorization: "authScheme authValue", "Content-Type": "application/json" } }) }) it("allows for setting basicAuth", function () { //Arrange setHttpResult({ statusCode: 200}) //Act _httpClientFactory.getClient() .setBasicAuth("<PASSWORD>", "open sesame") .get("testuri") //Assert expectRequestCalled({ headers: { authorization: "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Content-Type": "application/json" } }) }) }) describe("handlers", function () { it("allows handlers to modify the request header", function () { //Arrange setHttpResult({ statusCode: 200}) var handler = { onRequest: function (req, body) { req.headers.authorization = "someAuth authValue" } }; //Act _httpClientFactory.getClient() .addHandler(handler) .get("testuri"); //Assert expectRequestCalled({ headers: { authorization: "someAuth authValue", "Content-Type": "application/json" } }) }); it("allows handlers to modify the request body", function () { //Arrange setHttpResult({ statusCode: 200}) var handler = { onRequest: function (req, body) { body.test = "extra value" } }; //Act _httpClientFactory.getClient() .addHandler(handler) .post("testuri", { data: 5 }); //Assert expectRequestCalled({}, { data: 5, test: "extra value" }) }); it("allows handlers to modify the response header", function () { //Arrange setHttpResult({ statusCode: 200, headers: {}}) var handler = { onResponse: function (req, body) { req.headers.testVal = "updated header" } }; //Act var result = _httpClientFactory.getClient() .addHandler(handler) .get("testuri").value(); //Assert expect(result.headers.testVal).toBe("updated header") }); it("allows handlers to modify the response body", function () { //Arrange setHttpResult({ statusCode: 200}, "return value") var handler = { onResponse: function (req) { req.body += "-extra value" } }; //Act var result = _httpClientFactory.getClient() .addHandler(handler) .post("testuri", { data: 5 }).value(); //Assert expect(result.body).toBe("return value-extra value") }) }) var _requestMock; function setHttpResult(response, body, isHttps) { var mock = isHttps ? _httpsMock : _httpMock; var responseBody; if (body) { responseBody = body.constructor === String ? body : JSON.stringify(body) } spyOn(mock, "request").and.callFake(function (req, cb) { _requestMock = _.extend({ write: function() {}}, req); spyOn(_requestMock, "write"); response.on = function(eventName, func) { if (eventName == "data") { func(responseBody); return; } if (eventName == "end") { func(); } }; cb(response); _requestMock.end = function() {}; return _requestMock; }); } function expectRequestCalled(request, body, isHttps) { var mock = isHttps ? _httpsMock : _httpMock; expect(mock.request) .toHaveBeenCalledWith(jasmine.objectContaining(request), jasmine.any(Function)); if (body) { var bodyAsString; if (body.constructor === String) { bodyAsString = body; } else { bodyAsString = JSON.stringify(body); } expect(_requestMock.write).toHaveBeenCalledWith(bodyAsString); } }
ce27ec68216a6ea2317a1427afe2c127d82c314d
[ "Markdown", "JavaScript" ]
3
Markdown
mdickin/httpClientFactory
cd1f3ee170bca83b72fced6b01efa6e2a223fc0a
ea8779fd434f5021fce5494e7ac96cbbbadad47a
refs/heads/main
<file_sep> #class person #include.edades #end #puts person module edades edad = 17 def menor_edad print "INgresa tu edad " user = user.chomp.to_s if user <= edad puts " Eres menor de edad" end end def mayor_edad end class edad_clase end class llama_modulo include edades end end puts edades::edad <file_sep>print "ingrese su nombre :" name = gets.chomp puts "HOLA #{name}"<file_sep>puts "hello word" print "hello word 2 " #este es un comentario en ruby o rails #!/usr/bin/env ruby -wKUhello word <file_sep>#array = [1,"pedro",true,false,"juan"] #array.each do |element| # puts element #end array =[1,"pedro",true,false,"juan"] array.each_with_index do |element,index| puts "#{index}:#{element}" end <file_sep>persona = {"nombre" => "oscar" , "edad" => 34} persona.each do |llave, valor| puts "#{llave}: #{valor}" end <file_sep> print "ingersa tu edad ==> " name = gets.chomp.to_i if name <=17 && name >= 1 puts " Tu Estas en etapa adolecente" else puts "ya no eres adolecente " end #class llamametodo #include modulo.rb #def inicio # puts modulo.edades::edad #include modulo.edades #end #end <file_sep> module nuevo edad =5 def metodo_uno end def metodo_dos end class nueva_clase end end puts nuevo::edad<file_sep>puts "El perimetro de un cuadrado del lado 5 es #{5 * 4}" puts "El area de un cuadrado del lado 5 es #{5 * 5}" side = 5 puts "el perimetro de un cuadrado del lado 5 es #{side * 4 }" puts " el area de un cuadrado del lado 5 es #{side * side }" print "ingrese el valor del lado del cuadrado" side = gets.chomp.to_i puts "el perimetro de un cuadrado del lado #{side} es #{side * 4 }" puts " el area de un cuadrado del lado #{side} es #{side * side}"<file_sep>#5.times { |i| puts " hola #{i} "} #puts "hola" #puts "como " #puts "estas" #end (10..15).each do |i| puts "#{i} hola mundo" puts " #{i} hola" end <file_sep>products = [ { id:1, name: "leche", precio: 120,categories: [ "familiar", "comida" ] }, { id:2, name: "Arroz", precio: 1400, categories: [ "familiar", "comida" ] }, { id:3, name: "lavadora", precio: 5000, categories:["electrodomesticos"]} ] products.each do |product| puts product[:name ] puts " id: #{product[:id]}" puts " precio: #{product[:precio]}" puts " categorias: #{product[:categories].join(",")}" puts "-" * 40 end <file_sep>print "ingrese el numero de participantes " num = gets.chomp.to_i people =[] num.times do print " ingrese el nombre del participante " people << gets.chomp end puts "la persona seleccionada es #{people.sample}"<file_sep>#name = "<NAME>" #puts "Hola #{name}" print " ingresa tu edad ==> " user = gets.chomp.to_s if user <= "17" puts "ERES MENOR DE EDAD" else puts "ERES MAYOR DE EDAD" end
da5328e461e17de493a3eaa3fe7cb99011386e47
[ "Ruby" ]
12
Ruby
oscarandres31/reposcar
d85d993e50b4ade57f845e137f893ddc04feff45
8106cfe39eb0ec579dacded322af870b94fb1032
refs/heads/master
<repo_name>fdl-jgo/show-interface1<file_sep>/README.md rostiti ======= A Symfony project created on August 24, 2016, 8:51 pm. <file_sep>/src/AppBundle/Controller/DefaultController.php <?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RedirectResponse; class DefaultController extends Controller { public function indexAction() { // $request = $this->getRequest(); // $local1 = $request->getLocale(); // $local2 = $request; $message = \Swift_Message::newInstance() ->setSubject('Hello Email') ->setFrom('<EMAIL>') ->setTo('<EMAIL>') ->setCharset('utf-8') ->setContentType('text/html') ->setBody( $this->renderView( // app/Resources/views/Emails/registration.html.twig 'AppBundle:Default:index.html.twig', array('mlocal1' => "local1", 'mlocal2' => "locacl2") // 'WebseiteHomeBundle:Default:apropos.html.twig' ) ); $this->get('mailer')->send($message); return $this->render('AppBundle:Default:index.html.twig', array('mlocal1' => "local1", 'mlocal2' => "locacl2")); } public function setLocaleAction(Request $request) { $locale = $request->getLocale(); $url = $this->container->get('request')->headers->get('referer'); if(empty($url)) { $url = $this->container->get('router')->headers->get('index'); } else { $str1 = array("/fr/", "/en/", "/nl/", "/de/"); $str2 = array("/".$locale."/", "/".$locale."/", "/".$locale."/", "/".$locale."/"); $url = str_replace($str1, $str2, $url); } return $this->Redirect($url); } } <file_sep>/src/Webseite/HomeBundle/Resources/public/js/app.js (function () { //outils function myRandom() { var s; var num; s = ((Math.random() * 2) < 1) ? -1 : 1; num = (Math.random() * 0.5) * s; return num; } function myRandom1(min, max) { return (Math.random() * max) + min; } function Vector(_x, _y) { this.x = _x || 0; this.y = _y || 0; if(typeof this.x != 'number' ) PrintErr("Parameter x in Vector constructor"); if(typeof this.y != 'number') PrintErr("Parameter y in Vector constructor"); this.Add = function(_vector) { if (_vector instanceof Vector) { this.x += _vector.x; this.y += _vector.y; return this; } else { PrintErr("Invalid Parameter(s) in Vector.Add"); } } this.EuclidianDistance = function (_vector) { return Math.sqrt((this.x - _vector.x) * (this.x - _vector.x) + (this.y - _vector.y) * (this.y - _vector.y)); } } function drawRect(argCtx, argV1, argV2, argColorS) { argCtx.fillStyle = argColorS; argCtx.fillRect(argV1.x,argV1.y,argV2.x,argV2.y); } function drawLine(argCtx, argFromV, argToV, argLineWidth, argLineColor) { argCtx.moveTo(argFromV.x,argFromV.y); argCtx.lineTo(argToV.x,argToV.y); argCtx.lineWidth = argLineWidth; argCtx.strokeStyle = argLineColor; argCtx.stroke(); } function drawCircle(argCtx, argCenterV, argRayonN, argColorS) { argCtx.beginPath(); argCtx.arc(argCenterV.x, argCenterV.y, argRayonN, 0, 2 * Math.PI, true); argCtx.fillStyle = "#E2FFC6"; argCtx.fill(); } function particle(argCtx, argPosV) { this.position = argPosV; this.radius = 4; this.zone = 50; this.color = '#5cbdaa'; /*this.velocity = new Vector((Math.random() * 0.5), (Math.random() * 0.5))*/ this.velocity = new Vector(myRandom(), myRandom()); this.border = { x1: 0, x2: 0, y1: 0, y2: 0 } this.collideArea = function (argPart) { var dist = this.position.EuclidianDistance(argPart.position); return dist < this.zone + argPart.zone ; } this.hasFriend = function (argPart) { if(this.collideArea(argPart)){ drawLine(argCtx, this.position, argPart.position, 1, this.color); } } this.init = function () { this.border.x2 = assetsResize.w; this.border.y2 = assetsResize.h; drawCircle(argCtx, this.position, this.radius, this.color); } /*this.updat*/ this.update = function () { if(this.position.x <= this.border.x1) { this.velocity.x= -this.velocity.x; this.velocity.y= this.velocity.y; } if(this.position.x >= this.border.x2) { this.velocity.x= -this.velocity.x; this.velocity.y= this.velocity.y; } if(this.position.y <= this.border.y1) { this.velocity.x= this.velocity.x; this.velocity.y= -this.velocity.y; } if(this.position.y >= this.border.y2) { this.velocity.x= this.velocity.x; this.velocity.y= -this.velocity.y; } this.position.x = this.position.x + this.velocity.x; this.position.y = this.position.y + this.velocity.y; this.init(); } this.init(); } /// var canvas = document.createElement('canvas'); var mainDiv = document.getElementById("mainContain"); var ctx = canvas.getContext("2d"); var assetsResize = { w: window.innerWidth - 17, h: window.innerHeight -17 }; var siz = 'theSize'; // acces with (window.theSize) /*document.getElementById("mainContain").style.height = "800px";*/ var particles = []; function Run() { ctx.clearRect(0, 0, canvas.width, canvas.height); if(particles.length > 0 ) { //draw particle and apply actions for (var i = 0; i < particles.length; i++) { for (var j = i+1; j < particles.length; j++) { particles[i].hasFriend(particles[j]); } particles[i].update(); } } RequestAnimationFrame(Run); } window.RequestAnimationFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(_callback, _element) { window.setTimeout(_callback, 1000 / 60); }; })(); //// document.addEventListener('DOMContentLoaded', function () { $(".myCanvas").remove(); canvas.className = 'myCanvas'; canvas.width = assetsResize.w; canvas.height = assetsResize.h; // creation particules : 36 au totla for (var i = 0; i < 36; i++) { var v = new Vector(myRandom1(10, assetsResize.w), myRandom1(10, assetsResize.h)); var p = new particle(ctx, v); particles.push(p) } mainDiv.insertBefore(canvas, mainDiv.firstChild); window[siz] = assetsResize; // acces with (window.theSize) Run(); $(window).resize(function(){ assetsResize = { w: window.innerWidth -17, h: window.innerHeight -17 }; if(particles.length > 0 ) { for (var i = 0; i < particles.length; i++) { particles[i].border.x2 = assetsResize.w; particles[i].border.y2 = assetsResize.h; } } $(".myCanvas").remove(); canvas.className = 'myCanvas'; canvas.width = assetsResize.w; canvas.height = assetsResize.h; mainDiv.insertBefore(canvas, mainDiv.firstChild); window[siz] = assetsResize; // acces with (window.theSize) this is for absolute main div size }); fireDom() }, false); })();<file_sep>/src/Webseite/HomeBundle/Entity/Notification.php <?php namespace Webseite\HomeBundle\Entity; use Symfony\Component\Validator\Constraints as Assert; class Notification { /** * @Assert\NotBlank() * @Assert\Length(max=100) */ private $nom; /** * @Assert\NotBlank() * @Assert\Email() * @Assert\Length(max=100) */ private $email; /** * @Assert\NotBlank() * @Assert\Length(max=255) */ private $objet; /** * @Assert\NotBlank() */ private $contenu; /** * @Assert\DateTime() * @Assert\Type("\DateTime") */ private $datedenvoi; public function setNom($nom) { $this->nom = $nom; return $this; } public function getNom() { return $this->nom; } public function setEmail($email) { $this->email = $email; return $this; } public function getEmail() { return $this->email; } public function setObjet($objet) { $this->objet = $objet; return $this; } public function getObjet() { return $this->objet; } public function setContenu($contenu) { $this->contenu = $contenu; return $this; } public function getContenu() { return $this->contenu; } public function setDatedenvoi($datedenvoi) { $this->datedenvoi = $datedenvoi; return $this; } public function getDatedenvoi() { return $this->datedenvoi; } } <file_sep>/src/Webseite/HomeBundle/Controller/DefaultController.php <?php namespace Webseite\HomeBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Webseite\HomeBundle\Entity\Notification; use Webseite\HomeBundle\Form\NotificationType; class DefaultController extends Controller { public function indexAction() { return $this->render('WebseiteHomeBundle:Default:index.html.twig'); } public function aproposAction() { return $this->render('WebseiteHomeBundle:Default:apropos.html.twig'); } public function notificationAction(Request $request) { $notification = new Notification(); $form = $this->createForm(NotificationType::class, $notification); $form->handleRequest($request); if ($form->isValid()){ // $form->getData() holds the submitted values // but, the original `$task` variable has also been updated $notification = $form->getData(); $message = \Swift_Message::newInstance() ->setSubject( $notification->getObjet() ) ->setFrom("<EMAIL>") ->setTo('<EMAIL>') ->setCharset('utf-8') ->setContentType('text/html') ->setBody( $this->renderView( // app/Resources/views/Emails/registration.html.twig 'AppBundle:Default:index.html.twig', array('mlocal1' => $notification->getContenu()) // 'WebseiteHomeBundle:Default:apropos.html.twig' ) ); $this->get('mailer')->send($message); return $this->redirectToRoute('webseite_home_homepage'); } return $this->render('WebseiteHomeBundle:Default:notify.html.twig', array( 'form' => $form->createView())); } } <file_sep>/src/Webseite/HomeBundle/Form/NotificationType.php <?php namespace Webseite\HomeBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Ivory\CKEditorBundle\Form\Type\CKEditorType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; class NotificationType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('nom') ->add('email') ->add('objet') ->add('contenu', CKEditorType::class ,array('config_name' => 'notify_config') ) ->add('save', SubmitType::class) ; } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'Webseite\HomeBundle\Entity\Notification' )); } /** * @return string */ public function getBlockPrefix() { return 'webseite_home_notifypage'; } }
85f1e9756303c497114bf506f900b197e6be7618
[ "Markdown", "JavaScript", "PHP" ]
6
Markdown
fdl-jgo/show-interface1
89b657e548b573c25e1439f136116099be178ff7
3b10385b9be1092ef09ed157f7c059d08bb41da9
refs/heads/master
<file_sep>package com.zcx; import io.netty.buffer.ByteBuf; /** * Package: pack.data * * @author loafer * Description: * Bcd 码的字节码实现 * Date: 2021/4/13 13:11 * Version: 1.0 */ public abstract class Bcd extends BaseInformationElement { protected byte[] value; protected String strValue; public byte[] getValue() { return value; } public Bcd(ByteBuf byteBuffer) { super(byteBuffer); value = new byte[charSize()]; byteBuffer.readBytes(value); this.strValue = bcd2Str(value); } public Bcd() { super(null); } public Bcd(String strValue) { super(null); this.strValue = String.format("%0" + charSize() * 2 + "d", Long.valueOf(strValue)); if (strValue.length() > charSize()*2) { this.strValue = strValue.substring(0, charSize()*2); } this.value = str2Bcd(this.strValue); } public abstract int charSize(); @Override public void encode(ByteBuf byteBuf) { byteBuf.writeBytes(value); } public String getStrValue() { return strValue; } @Override public int getLen() { return charSize(); } private String bcd2Str(byte[] bytes) { StringBuilder temp = new StringBuilder(bytes.length * 2); for (byte aByte : bytes) { temp.append((byte) ((aByte & 0xf0) >>> 4)); temp.append((byte) (aByte & 0x0f)); } return "0".equalsIgnoreCase(temp.toString().substring(0, 1)) ? temp .toString().substring(1) : temp.toString(); } protected byte[] str2Bcd(String asc) { int len = asc.length(); int mod = len % 2; if (mod != 0) { asc = "0" + asc; len = asc.length(); } byte[] abt; if (len >= 2) { len = len / 2; } byte[] bbt = new byte[len]; abt = asc.getBytes(); int j, k; for (int p = 0; p < asc.length() / 2; p++) { if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) { j = abt[2 * p] - '0'; } else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) { j = abt[2 * p] - 'a' + 0x0a; } else { j = abt[2 * p] - 'A' + 0x0a; } if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) { k = abt[2 * p + 1] - '0'; } else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) { k = abt[2 * p + 1] - 'a' + 0x0a; } else { k = abt[2 * p + 1] - 'A' + 0x0a; } int a = (j << 4) + k; byte b = (byte) a; bbt[p] = b; } return bbt; } @Override public String toString() { return strValue; } } <file_sep>package com.zcx; import io.netty.buffer.ByteBuf; /** * Package: protocol * * @author loafer * Description: * Date: 2021/4/13 10:59 * Version: 1.0 */ public abstract class BaseInformationElement { public BaseInformationElement(ByteBuf byteBuffer) { // sub class must overwrite this constructor // to decode // so noting in here } /** * encode * * @param byteBuf byteBuf */ public abstract void encode(ByteBuf byteBuf); /** * len of bytes * =================== important ==================== * 加法常量会被 jvm 优化 用加法是便于阅读 * 建议按这 1+ 2 +3 +4 +5的形式实现 * * @return bytes len */ public abstract int getLen(); } <file_sep>package com.zcx; import io.netty.buffer.ByteBuf; import io.netty.util.CharsetUtil; import java.nio.charset.Charset; /** * ASCIIString string 封装校验长度 * 如果长度不足用空格补全 * 如果长度过长自动截取 * @author loafer */ public abstract class ASCIIString extends BaseInformationElement { private final CharSequence charSequence; private Charset charset = CharsetUtil.US_ASCII; public ASCIIString(ByteBuf byteBuf) { super(byteBuf); this.charSequence = byteBuf.readCharSequence(getLen(), charset); } public ASCIIString(String s) { super(null); this. charSequence = String.format("%-"+getLen()+"s", s); } @Override public String toString() { return charSequence.toString(); } @Override public void encode(ByteBuf byteBuf) { byteBuf.writeCharSequence(charSequence, charset); } public void setCharset(Charset charset) { this.charset = charset; } public Charset getCharset() { return charset; } }
63531b24f64361490d51d3a7234f2a8b3beda015
[ "Java" ]
3
Java
zcx1218029121/zoom
3722239f5210ae588f6220d98cd23dcbe6ae67b3
05975480d250056c8ae26d04e055dea395c73b90
refs/heads/main
<repo_name>georgmao/serverless-starter-templates<file_sep>/README.md # serverless-starter-templates A collection of starter examples for common serverless use cases * [Queue Processing](queue-processing-sqs-lambda) This template deploys a SQS resource and a Lambda function to process the records in SQS. It enables the event source for SQS --> Lambda and enables polling on your behalf. * [Stream Processing](stream-processing-kinesis-lambda) This template deploys a Kinesis stream and a Lambda function to process the records in Kinesis. It enables the event source for Kinesis --> Lambda and enables polling on your behalf. * [Microservice](microservice-api-lambda) This template deploys a HTTP API endpoint and 2 Lambda functions to process API requests forwarded from API Gateway. It uses two functions to demostrate seperation of logic and security. ## Serverless Application Model All projects include a SAM template you can use to deploy the application. The AWS SAM CLI is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API. To use the AWS SAM CLI, you need the following tools: * AWS SAM CLI - [Install the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html). * Node.js - [Install Node.js 14](https://nodejs.org/en/), including the npm package management tool. * Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community). <file_sep>/microservice-api-lambda/src/handlers/secondFunction.js /** * A Lambda function that parses a payload from the an API Gateway request * All log statements are written to CloudWatch */ exports.handler = async (event, context) => { // Log the event payload console.info(JSON.stringify(event)); // Get the requestContext. It has a http field with request details // requestContext: { http: {} } var requestContext = event.requestContext; var userAgent = requestContext.http.userAgent; var clientIp = requestContext.http.sourceIp; var httpMethod = requestContext.http.method; if(httpMethod == "GET") return (`SECURE: Hello you are using: ${userAgent} from IP ${clientIp}`); else if(httpMethod == "POST"){ return (`You POSTED this: ${event.body}`); } else{ return "Unsupported request" } } <file_sep>/microservice-api-lambda/README.md # microservice-api-lambda This project contains source code and supporting files for a serverless application that you can deploy with the AWS Serverless Application Model (AWS SAM) command line interface (CLI). It includes the following files and folders: - `src` - Code for the application's Lambda function. - `template.yml` - A template that defines the application's AWS resources. ## Test the application Use the provided sample API Gateway payload in `event.json` or generate a sample payload: * sam local generate-event apigateway aws-proxy You can Invoke the function locally, passing it the sample payload: * sam local invoke apiFunction -e event.json * sam local invoke secondFunction -e event.json Or to deploy the API and host it locally for integration testing: * sam local start-api There are 3 paths defined: `*/hello*` , `*/post*` , and `/secure/hello`. `/hello` expects a HTTP GET and `/post` expects a HTTP POST with body. These routes are implemented by the same Lambda function. The function checks the request payload for the `httpMethod` and responds accordingly. `/secure/hello` expects a HTTP GET. This route is implemented by a second Lambda function. You should use this design pattern when you have different security permissions that require you implement seperate functions. - To hit the predefined `/hello` path, submit a GET request to: http://127.0.0.1/hello - To hit the predefined `/post` path, submit a POST request to: http://127.0.0.1/post - To hit the predefined `/secure/hello` path, submit a POST request to: http://127.0.0.1/secure/hello You may need to use a development port such as 3000. ie http://127.0.0.1:3000/ ## Deploy the application * sam local deploy -g This uses the guided feature to deploy your application.<file_sep>/stream-processing-kinesis-lambda/src/handlers/index.js /** * A Lambda function that parses a payload from the SQS ReceieveMessage call * All log statements are written to CloudWatch */ exports.handler = async (event, context) => { // Log the event payload console.info(JSON.stringify(event)); // Get the incoming records var records = event.Records; // Process each record records.forEach(e => { console.info (JSON.stringify(e)) }) return (`Number of Records Processed: ${records.length}`); } <file_sep>/stream-processing-kinesis-lambda/README.md # queue-processing-sqs-lambda This project contains source code and supporting files for a serverless application that you can deploy with the AWS Serverless Application Model (AWS SAM) command line interface (CLI). It includes the following files and folders: - `src` - Code for the application's Lambda function. - `template.yml` - A template that defines the application's AWS resources. ## Test the application Use the provided sample Kinesis payload in `event.json` or generate a sample payload: * sam local generate-event kinesis get-records Invoke the function locally, passing it the sample payload * sam local invoke -e event.json ## Deploy the application * sam local deploy -g This uses the guided feature to deploy your application.
057bd7f55f317e814206d9ad4dd6a3ba1f942882
[ "Markdown", "JavaScript" ]
5
Markdown
georgmao/serverless-starter-templates
179d13b64a65e9485fd8ade04574192c85b675bf
74cf78cca21cc2183418190c619f309b7591b223
refs/heads/master
<repo_name>crisgol/svelte-form<file_sep>/packages/lib/src/types.ts import { JSONSchema7, JSONSchema7Type, JSONSchema7Array } from 'json-schema' import { ErrorObject } from 'ajv' export interface JSONSchema extends JSONSchema7 {} export interface JSONSchemaArray extends JSONSchema7Array {} export type JSONSchemaType = JSONSchema7Type export type JSONObject = Record<string, JSONSchemaType> export interface SvelteComponent {} export interface FieldComponents { wrapper: SvelteComponent boolean: SvelteComponent null: SvelteComponent integer: SvelteComponent number: SvelteComponent string: SvelteComponent array: SvelteComponent object: SvelteComponent } export interface FieldProps<T extends JSONSchemaType, E extends Errors = ErrorObject[]> { value: T | null errors: E | null schema?: JSONSchema components?: FieldComponents } export interface FormComponents extends FieldComponents { layout: SvelteComponent } export interface FormProps<T extends JSONSchemaType> { data: T schema: JSONSchema components: FormComponents } export interface ErrorRecord { [k: string]: ErrorObject[] | ErrorRecord } export type Errors = ErrorRecord | ErrorObject[] <file_sep>/packages/lib/src/svelte-form.ts export { default as GenericField } from './fields/GenericField.svelte' <file_sep>/packages/lib/src/components/index.ts import { FieldComponents, FormComponents } from '../types' import BooleanField from './BooleanField.svelte' import NullField from './NullField.svelte' import NumberField from './NumberField.svelte' import StringField from './StringField.svelte' import ObjectField from './ObjectField.svelte' import ArrayField from './ArrayField.svelte' import Wrapper from './Wrapper.svelte' import Layout from './Layout.svelte' export const defaultFieldComponents: FieldComponents = { boolean: BooleanField, null: NullField, number: NumberField, integer: NumberField, string: StringField, object: ObjectField, array: ArrayField, wrapper: Wrapper } export const defaultFormComponents: FormComponents = { ...defaultFieldComponents, layout: Layout } <file_sep>/packages/lib/src/helpers.ts import typeDetect from 'type-detect' import Ajv, { ErrorObject } from 'ajv' import { FieldProps, JSONObject, JSONSchema, JSONSchemaType, ErrorRecord, Errors } from './types' export function createProps< T extends JSONSchemaType, E extends Errors = ErrorObject[] >(): FieldProps<T, E> { const props: FieldProps<T, E> = { value: null, errors: null } return props } export function objectDefaultValue(schema: JSONSchema, value: JSONObject | null): JSONObject { const v: JSONObject = {} const { properties } = schema if (properties) { for (let k in properties) { const propSchema = properties[k] if (typeof propSchema !== 'boolean') { const item = value && value[k] v[k] = defaultValue(propSchema, item) } } } return v } export function defaultValue(schema: JSONSchema, value: JSONSchemaType): JSONSchemaType { if (value === null && schema.default !== undefined) { value = schema.default } if (schema.type === 'object') { return objectDefaultValue(schema, <JSONObject>value) } return value } export function normalizeObject(value: JSONObject, isRoot = true): JSONObject | null { const obj: JSONObject = {} for (const k in value) { let v = value[k] v = typeDetect(v) === 'Object' ? normalizeObject(v as JSONObject, false) : v if (v !== null) { obj[k] = v } } return Object.keys(obj).length ? obj : isRoot ? {} : null } export function normalizeValue(value: JSONSchemaType): JSONSchemaType { return typeDetect(value) === 'Object' ? normalizeObject(value as JSONObject) : value } const ajv = new Ajv({ allErrors: true }) export function validate(schema: JSONSchema, data: JSONSchemaType) { const valid = ajv.validate(schema, data) as boolean if (!valid) { return ajv.errors as Ajv.ErrorObject[] } return null } export function errorsToMap(errors: ErrorObject[]): ErrorRecord { const errorMap: ErrorRecord = {} return errors .map( (error): [string[], ErrorObject] => { const pathSuffix = error.keyword === 'required' ? `.${(<Ajv.RequiredParams>error.params).missingProperty}` : '' const path = `${error.dataPath}${pathSuffix}`.split('.').slice(1) return [path, error] } ) .reduce((acc, [path, error]) => { path.reduce((obj, key, i, arr) => { // build tree if (i !== arr.length - 1) { return (obj[key] ? obj[key] : (obj[key] = obj[key] || {})) as ErrorRecord } // add error if (obj[key]) { ;(obj[key] as ErrorObject[]).push(error) } else { obj[key] = [error] } return obj }, acc) return acc }, errorMap) }
827979e5777ecef718ee59f323f8f20a9fae7a11
[ "TypeScript" ]
4
TypeScript
crisgol/svelte-form
9b5e5521e0c15a3e90eee92c7a2929314fac5449
d864e79651dfbc272e063061b5cab6ddd849cae9
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 王卓诚 # Create_date : 2018-05-15 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json import time class FuTengInvestSpider(GGFundNavSpider): name = 'FundNav_FuTengInvest' sitename = '富腾资产' channel = '投资顾问' allowed_domains = ['www.futeng.com'] username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'http://www.futeng.com/futeng/front/jjcp' }] def parse_fund(self, response): urls = response.xpath('//table[@class="tabstyle"]/tr') for uu in urls: url1 = uu.xpath("td[2]/a/@href").extract_first() cpid = url1.replace('/futeng/front/toValueInfo?cpId=', '') pg = 0 formdata = { 'rowPerPage': '100', 'pageNo': str(pg), 'cpId': cpid } self.ips.append({ 'url': 'http://www.futeng.com/futeng/front/loadValueInfo', 'form': formdata, 'ext': cpid, 'pg': 1 }) def parse_item(self, response): cpId = response.meta['ext'] pg = response.meta['pg'] fund_info = json.loads(response.text) if len(fund_info['data']) > 0: for k, v in enumerate(fund_info['data']): productname_bf1 = v['cpName'] productname_bf1 = productname_bf1.strip() nav = v['cpjz'] added_nav = v['cpljjz'] statistic_date1 = (v['createTime']['time']) / 1000 timearray = time.localtime(statistic_date1) statistic_date = time.strftime("%Y-%m-%d", timearray) nav = nav.strip() added_nav = added_nav.strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = productname_bf1 item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) item['added_nav'] = float(added_nav) yield item if fund_info['totalCount'] > 0: next_pg = pg + 1 formdata = { 'rowPerPage': '100', 'pageNo': str(next_pg), 'cpId': cpId } self.ips.append({ 'url': "http://www.futeng.com/futeng/front/loadValueInfo", 'ext': cpId, 'form': formdata, 'pg': next_pg }) <file_sep># -*- coding: utf-8 -*- import json from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class ChangChengGuoRuiSpider(GGFundNoticeSpider): name = 'FundNotice_ChangChengGuoRui' sitename = '长城国瑞证券' entry = 'https://www.gwgsc.com/main/zcgl/zxxx/index.shtml' lps = [ { 'url': 'https://www.gwgsc.com/servlet/json', 'form': { 'funcNo': '820001', 'curPage': '1', 'numPerPage': '10', 'catalogId': '37' }, 'pg': 1 } ] def parse_list(self, response): json_data = json.loads(response.text) results = json_data['results'][0] rows = results['data'] for row in rows: url = row['url'] url = urljoin(get_base_url(response), url) title = row['title'] publish_time = row['c_data'] # 公告名称不完整,进入详情获取 if '...' in title: self.ips.append({ 'url': url, 'ext': {'publish_time': publish_time} }) else: item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = url item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item tp = int(results['totalPages']) pg = response.meta['pg'] + 1 if pg <= tp: self.lps.append({ 'url': 'https://www.gwgsc.com/servlet/json', 'form': { 'funcNo': '820001', 'curPage': str(pg), 'numPerPage': '10', 'catalogId': '37' }, 'pg': pg }) def parse_item(self, response): ext = response.meta['ext'] publish_time = ext['publish_time'] title = response.xpath('//div[@class="top"]/h4/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = response.url item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-21 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class WuKuangSecuritiesSpider(GGFundNavSpider): name = 'FundNav_WuKuangSecurities' sitename = '五矿证券' channel = '券商资管净值' trs_keycode = ['<KEY>', '<KEY>', '<KEY>', '8051637b-a7<KEY>-<KEY>', '9443378e-c0a2-4b10-bc76-d150fac6a514', 'a15c45e6-059e-4cbd-a664-bb3e8320a5a6', 'a4a2a8a6-8743-4188-9e5b-1599e4c55743', 'a5905a55-18b9-4676-8e47-c399e357ef45', 'bff21410-16bc-427e-8594-e9a2a8ade197', 'd3b226bd-2e18-4f55-b20d-0a48dc4a2298'] ips = [] main_href = 'http://www.wkzq.com.cn/wkzq/news/NewsDetail.aspx?sysClassID=9ae8360a-2ef7-4d30-9c12-cc5b50b0b8d5&id=' for k in trs_keycode: ips.append({ 'url': main_href + k, }) def parse_item(self, response): rows = response.css('div.detail_cn tr')[1:] for r in rows: row_str = ''.join(r.css('td ::text').re('\S+')) if '产品' in row_str or '净值' in row_str: continue if 'a5905a55-18b9-4676-8e47-c399e357ef45' in response.url: fund_name = response.css('span#msgTitle::text').re_first('(.*)产品净值') date = ''.join(r.css('td:nth-child(1) ::text').re('\S+')) nav_a = ''.join(r.css('td:nth-child(2) ::text').re('\S+')) add_nav_a = ''.join(r.css('td:nth-child(4) ::text').re('\S+')) item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav_a.replace('.', '.')) if nav_a else None item['added_nav'] = float(add_nav_a.replace(' ', '')) if add_nav_a else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item nav_b = ''.join(r.css('td:nth-child(3) ::text').re('\S+')) add_nav_b = ''.join(r.css('td:nth-child(5) ::text').re('\S+')) item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name + '次级' item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav_b.replace('.', '.')) if nav_b else None item['added_nav'] = float(add_nav_b.replace(' ', '')) if add_nav_b else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item else: date = ''.join(r.css('td:nth-child(1) ::text').re('\S+')) fund_name = ''.join(r.css('td:nth-child(3) ::text').re('\S+')) nav = ''.join(r.css('td:nth-child(4) ::text').re('\S+')) add_nav = ''.join(r.css('td:nth-child(5) ::text').re('\S+')) if '和而泰员工持股计划' == fund_name: fund_code = ''.join(r.css('td:nth-child(2) ::text').re('\S+')) fund_name = fund_name + fund_code item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav.replace('.', '.')) if nav else None item['added_nav'] = float(add_nav.replace(' ', '')) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-07 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import Request class NingBoPanShiTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_NingBoPanShiTouZiInvest' sitename = '宁波磐石投资' channel = '投顾净值' allowed_domains = ['www.nbpstz.com/'] def start_requests(self): yield Request(url='http://www.nbpstz.com/web/index.php?s=/Fund/index.html', callback=self.parse_pre_fund) def parse_pre_fund(self, response): fund_urls = response.xpath("//div[@class='bg']") for url in fund_urls: fund_url = url.xpath('.//@href').extract_first() fund_name = url.xpath('.//text()').extract_first() self.fps.append({ 'url': 'http://www.panshifund.com' + fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_fund(self, response): fund_url = response.xpath("//a[contains(., '点击详情了解')]//@href").extract_first() fund_name = response.meta['ext']['fund_name'] if fund_url: self.ips.append({ 'url': fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath("//div[@id='jj']//tr") fund_name = response.meta['ext']['fund_name'] for row in rows[1:]: statistic_date = row.xpath("./td[4]//text()").extract_first().strip() added_nav = row.xpath("./td[3]//text()").extract_first().strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest, Request from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class YunChengTaiInvestSpider(GGFundNavSpider): name = 'FundNav_YunChengTaiInvest' sitename = '云程泰投资' channel = '投顾净值' username = '本易123456' password = '<PASSWORD>' def start_requests(self): yield Request(url='http://www.yctchina.com.cn/index.html', callback=self.parse_pre_login) def parse_pre_login(self, response): yield FormRequest(url='http://www.yctchina.com.cn/member/index_do.php', formdata={ 'userid': self.username, 'pwd': <PASSWORD>, 'fmdo': 'login', 'dopost': 'login', 'gourl': '' }, headers={ 'Content-Type': 'application/x-www-form-urlencoded' }, callback=self.parse_login) def parse_login(self, response): self.fps = [{ 'url': 'http://www.yctchina.com.cn/a/yincang/index.html', 'ref': response.url }] yield self.request_next() def parse_fund(self, response): funds = response.xpath('//table[@id="cp_table"]/tr/td[last()]/a/@href').extract() for url in funds: url = urljoin(get_base_url(response), url) self.ips.append({ 'url': url, 'ref': response.url }) def parse_item(self, response): datas = response.xpath('//*[@id="pd_table"]//tr') next_url = response.xpath('/html/body/div[4]//ul[@class="pagelist"]/li/a[text()="下一页"]/@href').extract_first() for row in datas[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = row.xpath('./td[1]/text()').extract_first() item['channel'] = self.channel item['url'] = response.url nav = row.xpath('./td[2]/text()').extract_first() item['nav'] = float(nav) statistic_date = row.xpath('./td[5]/text()').extract_first() item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item if next_url is not None and next_url != 'javascript:void(0);': url = urljoin(get_base_url(response), next_url) self.ips.append({'url': url, 'ref': response.url}) <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-21 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class WuYuanAssetSpider(GGFundNavSpider): name = 'FundNav_WuYuanAsset' sitename = '悟源资产' channel = '投资顾问' fps = [{'url': 'http://www.wyamc.cn/index.php?g=&m=list&a=index&id=24'}] def parse_fund(self, response): href_list = response.xpath('//div[@class="ny_zblb1"]//ul[@style=" display:block"]//@href').extract() name_list = response.xpath('//div[@class="ny_zblb1"]//ul[@style=" display:block"]//a/text()').extract() for href, fname in zip(href_list, name_list): self.ips.append({ 'url': 'http://www.wyamc.cn%s' % href, 'ref': response.url, 'ext': fname }) def parse_item(self, response): rows = response.css('div.product_con:nth-child(2) tr')[1:] for r in rows: dt = r.css('td:nth-child(1) ::text').extract() nav = r.css('td:nth-child(2) ::text').extract_first() add_nav = r.css('td:nth-child(3) ::text').extract_first() date = ''.join(dt) item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = response.meta['ext'] item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav) if nav else None item['added_nav'] = float(add_nav) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y%m%d') if date else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import json class XiYuInvestSpider(GGFundNoticeSpider): name = 'FundNotice_XiYuInvest' sitename = '西域投资' entry = 'http://www.xiyu88.com/' # 固定Cookie cookies = 'isagree=agree' ips = [{ 'url': 'http://www.xiyu88.com/notices/json/listNotices', 'ref': 'http://www.xiyu88.com/notices/json/listNotices', 'form': {'currentPage': '1', 'everyPage': '10'}, 'ext': {'page': '1'} }] def parse_item(self, response): rows = json.loads(response.text) ext = response.meta['ext'] for row in rows[1]: url = urljoin(get_base_url(response), '/notices/view?id=' + str(row[0])) item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = row[1] item['url'] = url item['publish_time'] = datetime.strptime(row[2], '%Y-%m-%d %H:%M') yield item tp = int(rows[0]) tp = tp / 10 if tp % 10 == 0 else tp // 10 + 1 pg = int(ext['page']) + 1 if pg <= tp: self.ips.append({ 'url': 'http://www.xiyu88.com/notices/json/listNotices', 'ref': 'http://www.xiyu88.com/notices/json/listNotices', 'form': {'currentPage': str(pg), 'everyPage': '10'}, 'ext': {'page': str(pg)} }) <file_sep># coding:utf-8 import re from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavSpider from FundNavSpiders import GGFundNavItem class ChangjiangQiHuoSpider(GGFundNavSpider): name = 'FundNav_ChangjiangQiHuo' sitename = '长江期货' channel = '发行机构' fps = [ {'url': 'http://www.cjfco.com.cn/main/info/zcglgg/index.html'} ] def parse_fund(self, response): ext = response.meta['ext'] if 'type' not in ext: urls = response.xpath('//div[@class = "listcontent"]/*/li/a[contains(text(),"产品净值公告")]') else: urls = response.xpath('//*/li/a[contains(text(),"产品净值公告")]') for url in urls: href = url.xpath('./@href').extract_first() ips_url = urljoin(get_base_url(response), href) self.ips.append({ 'url': ips_url, 'ref': response.url }) page_count_info = re.findall(r'pagecount:(\d+)', response.text) curpage_info = re.findall(r'curpage:(\d+)', response.text) if page_count_info and curpage_info: page_count = page_count_info[0] curpage = curpage_info[0] if int(curpage) < int(page_count): self.fps.append({ 'url': 'http://www.cjfco.com.cn/servlet/Article?catalogId=3055&_=1524619825165&pageNumber='+str(int(curpage)+1)+'&rowOfPage=25&reqUrl=%2Fservlet%2FArticle%3FcatalogId%3D3055', 'ref': response.url, 'ext': {'type': '1'} }) yield self.request_next() def parse_item(self, response): title = response.xpath('//h1[@class="title"]/text()').extract_first() if '('in title: statistic_date = title.split('(', 1)[1].replace(')', '').strip() elif '(' in title: statistic_date = title.split('(', 1)[1].replace(')', '').strip() funds = response.css('table tbody tr') if funds: title_name = funds[0].xpath('./td[1]/p/strong/text()').extract_first() if title_name is not None: for fund in funds[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url fund_name = fund.xpath('./td[1]/p/text()').extract_first().strip().replace('(', '').replace(')', '').replace('\t', '').replace('\r', '').replace('\n', '') item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y年%m月%d日') nav = fund.xpath('./td[3]/p/text()').extract_first().strip().replace('(', '').replace(')', '').replace('\t', '').replace('\r', '').replace('\n', '') if nav is None or nav == '': return item['nav'] = float(nav) yield item else: title_name = funds[0].xpath('./td[1]/text()').extract_first() if title_name is None: title_name = funds[0].xpath('./td[1]/font/text()').extract_first() if '产品净值公告'in title_name: funds.pop(0) title_four_name = funds[0].xpath('./td[4]/text()').extract_first() if '产品净值' == title_four_name: for fund in funds[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url fund_name = fund.xpath('./td[1]/text()').extract_first() item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y年%m月%d日') nav = fund.xpath('./td[4]/text()').extract_first() item['nav'] = float(nav) yield item else: if '基金全称' != title_name: title_name = funds[0].xpath('./td[1]/text()').extract_first() nav_name = funds[0].xpath('./td[3]/text()').extract_first() for fund in funds[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url fund_name = fund.xpath('./td[1]/text()').extract_first() if fund_name is None: fonts = fund.xpath('./td[1]/font') font_name = '' for font in fonts: text = font.xpath('./text()').extract_first() font_name += text fund_name = font_name item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y年%m月%d日') if '单位净值' == nav_name or '净值' == nav_name: nav = fund.xpath('./td[3]/text()').extract_first() if '无' != nav: item['nav'] = float(nav) yield item youxian_nav = fund.xpath('./td[4]/text()').extract_first() if '无' != youxian_nav: item['fund_name'] = fund_name+'_优先级' item['nav'] = float(youxian_nav) yield item jinqu_nav = fund.xpath('./td[5]/text()').extract_first() if '无' != jinqu_nav: item['fund_name'] = fund_name+'_进取级' item['nav'] = float(jinqu_nav) yield item elif '累计净值' == nav_name: added_nav = fund.xpath('./td[3]/text()').extract_first() item['added_nav'] = float(added_nav) yield item youxian_nav = fund.xpath('./td[4]/text()').extract_first() if '无' != youxian_nav: item['fund_name'] = fund_name + '_优先级' item['nav'] = float(youxian_nav) yield item jinqu_nav = fund.xpath('./td[5]/text()').extract_first() if '无' != jinqu_nav: item['fund_name'] = fund_name + '_进取级' item['nav'] = float(jinqu_nav) yield item else: for fund in funds[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url fund_name = fund.xpath('./td[2]/text()').extract_first() item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y年%m月%d日') nav = fund.xpath('./td[5]/text()').extract_first() item['nav'] = float(nav) yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-04 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import Request import re class MaiDaoZiChanInvestSpider(GGFundNavSpider): name = 'FundNav_MaiDaoZiChanInvest' sitename = '麦岛资产' channel = '投资顾问' allowed_domains = ['www.maidaoziguan.com'] username = '13916427906' password = '<PASSWORD>' cookies = 'PHPSESSID=40scgb8hn8cdrkpfak9ar93276; 0203_110_179_245=0203.110.179.245; 0203_110_179_245time=1526533306; Hm_lvt_c9477ef9d8ebaa27c94f86cc3f505fa5=1526533309; Hm_lpvt_c9477ef9d8ebaa27c94f86cc3f505fa5=1526533309; quote.color=2; SSID=0203.110.179.2451526533306' def start_requests(self): yield Request(url='http://www.maidaoziguan.com/index.php/category/index/id/111.html', callback=self.parse_pre_fund) def parse_pre_fund(self, response): fund_urls = response.xpath("//div[@class='m_con_in']/ul[@id='dom_set']//li") for url in fund_urls: fund_url = url.xpath('.//@href').extract_first() self.fps.append({ 'url': 'http://www.maidaoziguan.com' + fund_url.replace('.html#dom_set', '/p/1.html#dom_set'), 'ref': response.url, }) def parse_fund(self, response): rows_urls = response.xpath("//ul[@class='cplb_ul2']/li/a[@class='fr']//@href").extract() if rows_urls: for url in rows_urls: self.ips.append({ 'url': 'http://www.maidaoziguan.com' + url, 'ref': response.url, }) pg = re.findall(r'/p/(\d+).html', response.url)[0] next_pg = str(int(pg) + 1) self.fps.append({ 'url': response.url.replace('/p/' + pg + '.html', '/p/' + next_pg + '.html'), 'ref': response.url, }) def parse_item(self, response): fund_info = re.findall(r'摘要:([\s\S]*?)</p>', response.text)[0] fund_info = fund_info.replace('累计参考净值:', ',').replace('参考净值:', '').replace(',', ',').replace(' ', '') fund_infos = fund_info.split(',') fund_name = fund_infos[0] statistic_date = fund_infos[1].strip().replace('年', '-').replace('月', '-').replace('日', '') nav = fund_infos[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if '累计参考净值' in response.text: added_nav = fund_infos[3] item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep>from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest class FujianxuchengFutureSpider(GGFundNavSpider): name = 'FundNav_FujianxuchengFuture' sitename = '旭诚资产' channel = '投顾净值' username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'http://www.xuchengfund.com/cpjzs.asp' }] def start_requests(self): yield FormRequest(url='http://www.xuchengfund.com/logins.asp', formdata={'mob': '13916427906', 'pass': '<PASSWORD>', 'submit2': '(unable to decode value)'}, meta={ 'handle_httpstatus_list': [302] }) def parse_fund(self, response): urls = response.xpath('/html/body/table[5]/tr/td/table[2]/tr[position()>1]') for url in urls: href = url.xpath('./td/a/@href').extract_first() code = href.rsplit('=', 1)[1] fund_name = url.xpath('./td/a/text()').extract_first() self.ips.append({ 'url': 'http://www.xuchengfund.com/cpjzs.asp?pid=' + str(code) + '&page=1', 'ref': response.url, 'ext': {'code': code, 'fund_name': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] code = ext['code'] fund_names = ext['fund_name'] rows = response.xpath('/html/body/table[5]/tr/td[3]/table[5]/tr') rows = rows[1:-1] for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_names statistic_date = row.xpath("./td[6]/text()").re_first('\d+-\d+-\d+') item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None nav = row.xpath('./td[2]/text()').extract_first() item['nav'] = float(nav) if nav else None added_nav = row.xpath("./td[3]/text()").extract_first() item['added_nav'] = float(added_nav) if added_nav else None yield item next_url = response.xpath( '/html/body/table[5]/tr/td[3]/table[5]/tr[24]/td/table/tr/td[2]/a[text()="下页"]/@href').extract_first() if next_url: url = urljoin(get_base_url(response), next_url) self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'code': code, 'fund_name': fund_names} }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class WuXiZhiXinInvestSPider(GGFundNoticeSpider): name = 'FundNotice_WuXiZhiXinInvest' sitename = '无锡智信投资' entry = 'http://www.zxwealth.com.cn/gsdt' ips = [ { 'url': 'http://www.zxwealth.com.cn/gsdt', 'pg': 1 } ] def parse_item(self, response): rows = response.xpath('//div[@class="newslist"]/ul/li') for row in rows: url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./a/text()').extract_first() publish_time = row.xpath('./span/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item tp = int(response.xpath('//div[@class="pagenavi"]/a[contains(text(),"尾页")]/@href').re_first('page/(\d+)')) pg = response.meta['pg'] + 1 if pg <= tp: self.ips.append({ 'url': 'http://www.zxwealth.com.cn/gsdt/page/{0}'.format(pg), 'ref': response.url, 'pg': pg }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url import re class ZhongHangStockNoticeSpider(GGFundNoticeSpider): name = 'FundNotice_ZhongHangStockNotice' sitename = '中航证券' entry = 'http://www.avicsec.com/' lps = [{'url': 'http://www.avicsec.com/main/invest/stockDividend/C00001/collectiveInvestment.shtml', 'ref': 'http://www.avicsec.com/main/invest/stockDividend/index.shtml'}] def parse_list(self, response): funds = response.xpath('//*[@id="showLeft3418"]/dd/a/@href').extract() for fund in funds: url1 = 'http://www.avicsec.com/servlet/ArticlePageAction?catalogId=3445&state=3&titleLength=50&gpdm=' url2 = 'http://www.avicsec.com/servlet/ArticlePageAction?catalogId=3444&state=3&titleLength=50&gpdm=' gpdm = re.search(r'stockDividend\/(\S+)\/collectiveInvestment', fund).group(1) url1 = url1 + gpdm url2 = url2 + gpdm form = {'curPage': '1', 'numPerPage': '10', 'type': '1'} self.ips.append({'url': url1, 'form': form, 'ext': {'page': '1'}}) self.ips.append({'url': url2, 'form': form, 'ext': {'page': '1'}}) def parse_item(self, response): ext = response.meta['ext'] page = int(ext['page']) total_page = re.search(r'pagecount\:(\d+),', response.text) if total_page: total_page = int(total_page.group(1)) else: total_page = 0 rows = response.xpath('//ul/li/a') for row in rows: title = row.xpath('./strong/text()').extract_first() url = row.xpath('./@href').extract_first() publish_time = row.xpath('./span/text()').extract_first() publish_time = datetime.strptime(publish_time, '%Y.%m.%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = urljoin(get_base_url(response), url) item['title'] = title item['publish_time'] = publish_time yield item if page < total_page: form = {'curPage': str(page+1), 'numPerPage': '10', 'type': '1'} self.ips.append({ 'url': response.url, 'form': form, 'ext': {'page': str(page+1)}, 'ref': response.url }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class YingDaSecuritySpider(GGFundNavSpider): name = 'FundNav_YingDaSecurity' sitename = '英大证券' channel = '券商资管净值' fps = [ { 'url': 'http://www.ydsc.com.cn/ydzq/zcgl/content.jsp?classid=0002000100130006' } ] def parse_fund(self, response): rows = response.xpath('//ul[@id="side-menu"]/li[5]/ul/li/a') for row in rows: class_id = row.xpath('./@href').re_first('classid=([^/]+)&num=1') self.ips.append({ 'url': 'http://www.ydsc.com.cn/ydzq/zcgl/cpjhjzList.jsp', 'form': { 'classid': class_id, 'pageIndex': '1', 'pageSize': '10', 'hrefURL': '', 'filter': '' }, 'pg': 1 }) def parse_item(self, response): rows = response.xpath('//table[@class="tab_01"]/tr')[1:] for row in rows: fund_name = row.xpath('./td[2]/text()').extract_first() statistic_date = row.xpath('./td[3]/text()').re_first('\d+-\d+-\d+') nav = row.xpath('./td[4]/text()').re_first('[0-9.]+') added_nav = row.xpath('./td[5]/text()').re_first('[0-9.]+') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item t_count = response.xpath('//div[@class="pages_ul_page33"]/ul/li[1]/text()').re_first('共有([\d]+)条记录') tp = int(t_count) / 10 if int(t_count) % 10 == 0 else int(t_count) // 10 + 1 pg = response.meta['pg'] + 1 if pg <= tp: class_id = response.meta['form']['classid'] self.ips.append({ 'url': 'http://www.ydsc.com.cn/ydzq/zcgl/cpjhjzList.jsp', 'form': { 'classid': class_id, 'pageIndex': str(pg), 'pageSize': '10', 'hrefURL': '', 'filter': '' }, 'pg': pg }) <file_sep>from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class TaoXuanYouShengAssetSpider(GGFundNoticeSpider): name = 'FundNotice_TaoXuanYouShengAsset' sitename = '深圳前海韬选优胜资产' entry = 'http://www.txysa.com/' lps = [ { 'url': 'http://www.txysa.com/news.php?cid=146', 'ref': None } ] def parse_list(self, response): noticeList = response.xpath('//div[@class="r_news"]/ul/li') for notice in noticeList: noticeLink = notice.xpath('./a/@href').extract_first().strip() noticeLink = urljoin(get_base_url(response), noticeLink) title = notice.xpath('./a/text()').extract_first() publish_time = notice.xpath('./em/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = noticeLink item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item next_url = response.xpath('//div[@class="quotes"]/a[contains(text(), "下一页")]/@href').extract_first() if next_url is not None: self.lps.append({'url': urljoin(get_base_url(response), next_url), 'ref': response.url}) <file_sep>from datetime import datetime from scrapy import Request,FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re import json import hashlib class XiaMenBoFuLiAssetSpider(GGFundNavSpider): name = 'FundNav_XiaMenBoFuLiAsset' sitename = '厦门博孚利资产' channel = '投资顾问' username = '15618207420' password = '<PASSWORD>' cookies = 'isAgreen=1' def start_requests(self): yield Request(url='http://www.xmpfl.com', callback=self.parse_pre_login) def parse_pre_login(self, response): url = 'http://www.xmpfl.com/api/login' yield FormRequest(url=url, formdata={'username': self.username, 'password': hashlib.md5(self.password.encode(encoding='UTF-8')).hexdigest()}, callback=self.parse_login) def parse_login(self, response): self.fps = [{ 'url': 'http://www.xmpfl.com/products/', 'ref': response.url }] def parse_fund(self, response): funds = response.xpath('/html/body/div[3]//div[@class="bd"]/ul/li/a') for fund in funds: url = fund.xpath('./@href').extract_first() fund_name = fund.xpath('./text()').extract_first() fund_id = re.search(r'products\/(\d+)\.html', url).group(1) url = 'http://www.xmpfl.com/api/worth?id=' + fund_id self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): if response.status == 500: return ext = response.meta['ext'] fund_name = ext['fund_name'] rows = json.loads(response.text) if rows: acc_values = rows['acc_values'] dates = rows['date'] values = rows['values'] for date in dates: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url statistic_date = date nav = values.pop(0) added_nav = acc_values.pop(0) item['nav'] = float(nav) if nav is not None and nav != '' else None item['added_nav'] = float(added_nav) if added_nav is not None and added_nav != '' else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 柳美云 # Create_date : 2018-05-22 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class ShengYangAssetSpider(GGFundNavSpider): name = 'FundNav_ShengYangAsset' sitename = '升阳资产' channel = '投顾净值' allowed_domains = ['www.syzc.com.cn'] username = '郑益明' password = '<PASSWORD>' fps = [{'url': 'http://www.syzc.com.cn/products.asp'}] cookies = 'ASPSESSIONIDSABCQABQ=KOAJNELCCKPJCKHKDADEHKNC; _D_SID=19D6E7D9CAEAC334EC653F3BCC544ECE; UserName=13916427906' def parse_fund(self, response): link = response.xpath('//div[@id="inner_left"]//ul//li//a//@href').extract() for href in link: # 对异常的未披露净值的三只产品,在此处先做剔除 if href not in ('products.asp?id=2', 'products.asp?id=8', 'products.asp?id=9'): ips_url = urljoin('http://www.syzc.com.cn/', href) self.ips.append({ 'url': ips_url, 'ref': response.url, }) def parse_item(self, response): fund_name = response.xpath( '//div[@id="tagContent2"]/table/tbody//tr[2]//p//font//text()').extract_first().strip() rows = response.xpath('//div[@class="tagContent"]//table//tbody//tr') for row in rows[6:]: i = row.xpath("td//font//text()").extract() i2 = [_ for _ in i if _.strip()] if len(i2) > 3: nav = i2[0].replace(',', '').replace(' ', '') statistic_date = i2[3].replace(',', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name.replace('净值披露表', '') item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url import json class XinHuFuturesSpider(GGFundNavSpider): name = 'FundNav_XinHuFutures' sitename = '新湖期货' channel = '期货净值' fps = [{ 'url': 'http://www.xinhu.cn/cfzx.html?action=list-more&page=1', 'ref': 'http://www.xinhu.cn/' }] def parse_fund(self, response): funds = response.xpath('//table[@class="tb-cfzx mgt10"]/tbody/tr/td[1]/a') for fund in funds: url = fund.xpath("./@href").extract_first() fund_name = fund.xpath("./text()").extract_first() self.ips.append({ 'url': url, 'ref': response.url, 'form': { 'curpage': '0', 'flag': '' }, 'ext': {'fund_name': fund_name} }) next_url = response.xpath('//div[@class="pages"]/a[@class="next"]/@href').extract_first() if next_url is not None and next_url != '': self.fps.append({ 'url': urljoin(get_base_url(response), next_url), 'ref': response.url }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] cur = response.meta['form']['curpage'] if cur == '0': rows = response.xpath('//table[@id="trade_detail_table"]/tr') for row in rows[1:(len(rows)-1)]: statistic_date = row.xpath('normalize-space(./td[1]/text())').extract_first() if statistic_date is None or statistic_date == '': continue statistic_date = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row.xpath('normalize-space(./td[2]/text())').extract_first(default='') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = statistic_date item['nav'] = float(nav) if nav is not None else None yield item # 总页数 tp = response.xpath('//span[@class="qp_totalnumber"]/text()').extract()[0] # 当前页 cp = response.xpath('//span[@class="qp_pagenumber"]/text()').extract()[0] if int(cp) < int(tp): next_url = response.url + '&dosubmit=1' self.ips.append({ 'url': next_url, 'ref': response.url, 'form': { 'curpage': cp, 'flag': 'next' }, 'ext': {'fund_name': fund_name} }) else: info_json = json.loads(response.text) rows = info_json['data']['list'] for row in rows: if row is None: break statistic_date = row['dateline'] statistic_date = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row['total_nav'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = statistic_date item['nav'] = float(nav) if nav is not None else None yield item # 总页数 tp = info_json['data']['cpage'] # 当前页 cp = info_json['data']['page'] if int(cp) < int(tp): next_url = response.url self.ips.append({ 'url': next_url, 'ref': response.url, 'form': { 'curpage': str(cp), 'flag': 'next' }, 'ext': {'fund_name': fund_name} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class PingAnXinTuoTrustSpider(GGFundNavSpider): name = 'FundNav_PingAnXinTuoTrust' sitename = '平安信托' channel = '信托净值' allowed_domains = ['trust.pingan.com'] fps = [{'url': 'http://trust.pingan.com/products/1'}] def parse_fund(self, response): fund_urls = response.xpath("//tr//@href").extract() if fund_urls: for fund_url in fund_urls: self.ips.append({ 'url': urljoin('http://trust.pingan.com', fund_url), 'ref': response.url, }) next_url = response.xpath('//a[contains(text(), "下一页")]/@href').extract_first() if next_url: self.fps.append({ 'url': urljoin('http://trust.pingan.com', str(next_url)), 'ref': response.url, }) def parse_item(self, response): rows = response.xpath("//div[@class='table-body']/table/tbody//tr") fund_name = response.xpath("//h2[@class='product-name']//text()").extract_first() for row in rows: statistic_date = row.xpath("./td[1]//text()").extract_first().strip() if '2' in statistic_date: nav = row.xpath("./td[2]//text()").extract_first().strip() added_nav = row.xpath("./td[3]//text()").extract_first().strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime import time from urllib.parse import urljoin from scrapy import FormRequest, Request from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import re class DeYaInvestNoticeSpider(GGFundNoticeSpider): name = 'FundNotice_DeYaInvestNotice' sitename = '德亚投资' entry = 'http://www.deyainvest.com/' username = '13916427906' password = '<PASSWORD>' #cookies = 'disclaimer=viewed; user_id=MTA3Ng%3D%3D--f21972507c46323f16bc9c323d4d978c043fcfc0; remember_token=<PASSWORD>; _deya_web_session=OF<KEY>2hudnAwWXNzVkFGSUlaOSt3czZVUT09--6509c8d1304bd44b327f0b31aec010ab38bd244d' lps = [ { 'url': 'http://www.deyainvest.com/my/products', 'ref': None, 'ext': {'page': '1'} } ] def start_requests(self): yield Request(url='http://www.deyainvest.com/', callback=self.parse_login_pre) def parse_login_pre(self, response): csrf_token = response.xpath('/html/head/meta[@name="csrf-token"]/@content').extract_first() url = 'http://www.deyainvest.com/disclaimer' yield Request(url= url, method='PUT', headers={'X-CSRF-Token': csrf_token, 'Accept':'*/*;q=0.5, text/javascript, application/javascript, application/ecmascript, application/x-ecmascript'}, callback=self.parse_login_next) def parse_login_next(self, response): yield Request(url='http://www.deyainvest.com/login', callback=self.parse_login) def parse_login(self, response): csrf_token = response.xpath('/html/body//input[@name="authenticity_token"]/@value').extract_first() form = {'utf8': '✓', 'authenticity_token': csrf_token, 'session[mobile]': self.username, 'session[password]': <PASSWORD>, 'session[remember_me]': '0', 'session[remember_me]': '1', 'commit': '登录'} yield FormRequest(url='http://www.deyainvest.com/login', method='POST', formdata=form, headers={ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' }, ) def parse_list(self, response): csrf_token = response.xpath('/html/head/meta[@name="csrf-token"]/@content').extract_first() self.ips.append({ 'url': 'http://www.deyainvest.com/announcements?page=1&to=products', 'ref': response.url, 'X-Requested-With': 'XMLHttpRequest', 'headers': { 'X-CSRF-Token': csrf_token, 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01' }}) def parse_item(self, response): line = response.text titles = re.findall(r'\\"\\">(\S+\s?\S+)\s*<\\/span>', line) dates = re.findall(r' text-right\\">\\n\s+(\d+年\d+月\d+日)\\n\s+<', line) urls = re.findall(r'data-remote=\\"true\\" href=\\"(\S+)\\">', line) next_url = re.search(r'href=\\"(/announcements\?\S+)\\">下一页', line) if next_url: next_url = next_url.group(1) for title in titles: url = urls.pop(0) url = urljoin(get_base_url(response), url) publish_time = dates.pop(0) publish_time = datetime.strptime(publish_time, '%Y年%m月%d日') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title # item['publish_time'] = publish_time yield item #self.log(item) if next_url: next_url = urljoin(get_base_url(response), next_url) csrf_token = response.xpath('/html/head/meta[@name="csrf-token"]/@content').extract_first() self.ips.append({ 'url': next_url, 'ref': response.url, 'X-Requested-With': 'XMLHttpRequest', 'headers': { 'X-CSRF-Token': csrf_token, 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01' }})<file_sep>from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class AbmFundSpider(GGFundNavSpider): name = 'FundNav_AbmFund' sitename = '珠海阿巴马资产' channel = '投顾净值' username = '350982198506242251' password = '<PASSWORD>' fps = [{'url': 'http://www.abmfund.com/index.php?c=product&a=index&pid=1'}] def start_requests(self): yield FormRequest(url='http://www.abmfund.com/index.php?c=member&a=login', formdata={'username': '350982198506242251', 'pwd': '<PASSWORD>', }) def parse_fund(self, response): funds = response.xpath("//ul[@class='menubox']/li/div/a") for fund in funds: url = fund.xpath("./@href").extract_first() fund_url = urljoin(get_base_url(response), url) fund_name = fund.xpath("./text()").extract_first() self.ips.append({ 'url': fund_url, 'ref': response.url, 'pg': 1, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name1 = response.meta['ext']['fund_name'] date = re.search('categories:\s*\[(.*?)\]', response.text, re.S) date = date.group(1)if date else None dates = re.findall('\d+-\d+-\d+', date.replace('/', '-'))if date else [] navs1 = re.search("name:\s*'整体净值',\s*data:\s*\[(.*?)\]", response.text, re.S) navs1 = navs1.group(1)if navs1 else None navs1 = re.findall('[0-9.]+', navs1)if navs1 else [] navs2 = re.search("name:\s*'进取[级]*净值',\s*marker:\s*\{\s*symbol:\s*'diamond'\s*\},\s*data:\s*\[(.*?)\]", response.text, re.S) navs2 = navs2.group(1)if navs2 else None navs2 = re.findall('[0-9.]+', navs2)if navs2 else [] navs3 = re.search("name:\s*'费前净值|单位净值',\s*marker:\s*\{\s*symbol:\s*'diamond'\s*\},\s*data:\s*\[(.*?)\]", response.text, re.S) navs3 = navs3.group(1) if navs3 else None navs3 = re.findall('[0-9.]+', navs3) if navs3 else [] if navs1 and navs2: for fund_name in [fund_name1, fund_name1+'进取级']: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url if '进取级' in fund_name: for date, nav in zip(dates, navs2): item['fund_name'] = fund_name item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') yield item else: for date, nav in zip(dates, navs1): item['fund_name'] = fund_name item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') yield item elif len(navs2) == 0 and navs1: for date, nav in zip(dates, navs1): item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name1 item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') yield item elif len(navs1) + len(navs2) == 0 and navs3: for date, nav in zip(dates, navs3): item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name1 item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class GuanHeAssetSpider(GGFundNoticeSpider): name = 'FundNotice_GuanHeAsset' sitename = '浙江观合资产' entry = 'http://www.guanheasset.com/website/w/h?mt=2&mc=2799282&cc=2776206' lps = [ { 'url': 'http://www.guanheasset.com/website/w/h?mt=2&mc=2799282&cc=2776206' } ] def parse_list(self, response): rows = response.xpath('//div[@class="simu-site-subnav"]')[1].xpath('./ul/li/a') for row in rows: url = row.xpath('./@href').extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url }) def parse_item(self, response): rows = response.xpath('//div[@class="simu-site-list"]/ul/a') for row in rows: url = row.xpath('./@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./li/div[1]/text()').extract_first().strip() publish_time = row.xpath('./li/div[2]/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from scrapy import Request from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class YouYiFengAssetSpider(GGFundNavSpider): name = 'FundNav_YouYiFengAsset' sitename = '厦门祐益峰资产' channel = '投资顾问' cookies = 'PHPSESSID=acsfonglk7pmhbb71aldb283e0' # cookie固定 username = '<EMAIL>' password = '<PASSWORD>' def start_requests(self): yield Request(url='http://www.youhillstock.com/index.php?m=Product&a=index', callback=self.parse_fund) def parse_fund(self, response): funds = response.xpath('//div[@class="subNav"]/ul/li/a') for fund in funds: url = fund.xpath('./@href').extract_first() fund_name = fund.xpath('./text()').extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//table[@id="dateTR"]/tbody/tr') for row in rows: nav = row.xpath('./td[2]/text()').extract_first() added_nav = row.xpath('./td[3]/text()').extract_first() statistic_date = row.xpath('./td[1]/text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_Date : 2018-05-18 # Alter_Date : 2018-05-24 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import calendar class HaiZhengTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_HaiZhengTouZiInvest' sitename = '海证投资' channel = '投资顾问' allowed_domains = ['www.zgqhtzw.com'] username = '13916427906' password = '<PASSWORD>' cookies = 'safedog-flow-item=; kerenLogin=userid=13916427906; popped=yes; productpopped=yes' fps = [ {'url': 'http://www.zgqhtzw.com/fund.aspx?sClass=1&sType=3'}, ] def parse_fund(self, response): fund_urls = response.xpath("//div[@id='mainInLeft']/ul//li") for url in fund_urls: fund_name = url.xpath('./a/@title').extract_first().strip() fund_url = url.xpath('./a/@href').extract_first() self.ips.append({ 'url': 'http://www.zgqhtzw.com/'+fund_url, 'ref': response.url, 'ext':{'fund_name':fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'].replace('(已终结)', '') nav = response.xpath("//div[@class='text_jz']/table[@class='d_t']/tbody/tr[2]/td[2]//text()").extract_first() added_nav = response.xpath("//div[@class='text_jz']/table[@class='d_t']/tbody/tr[2]/td[2]//text()").extract_first() date = response.xpath("//div[@class='text_jz']/table[@class='d_t']/tbody/tr[4]/td[2]//text()").extract_first() if len(date) < 10: date_info = date.replace('年', '-').replace('月', '') year = date_info[0:4] if date_info[-2] == '1': month = '1' + date_info[-1] else: month = date_info[-1] wday, monthrange = calendar.monthrange(int(year), int(month)) weekday = calendar.weekday(int(year), int(month), monthrange) if weekday == 5: monthrange = monthrange - 1 elif weekday == 6: monthrange = monthrange - 2 statistic_date = date_info + '-' + str(monthrange) else: statistic_date=date item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy import Request from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class YingXueInvestSpider(GGFundNoticeSpider): name = 'FundNotice_YingXueInvest' sitename = '映雪投资' entry = 'http://www.snowlightcapital.cn/' username = '13916427906' password = '<PASSWORD>' ips = [ { 'url': 'http://www.snowlightcapital.cn/moreNews', 'ref': 'http://www.snowlightcapital.cn/', 'pg': 1 } ] def start_requests(self): yield Request(url='http://www.snowlightcapital.cn/getUserLogin?cellphone=13916427906&pwd=<PASSWORD>&saveRank=Y&randnum=0.8588240370783373', ) def parse_item(self, response): rows = response.xpath('//div[@class="snowview_bot"]/ul/li') for row in rows: title = row.xpath('./a/text()').extract_first() url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) publish_time = row.xpath('./span/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = url item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item tp = response.xpath('//div[@class="left tx_fye"]/a[contains(text(),"末页")]').re_first('\d+') pg = response.meta['pg'] if pg < int(tp): pg = pg+1 next_url = 'http://www.snowlightcapital.cn/moreNews?pageNum=' + tp + '&pageNo=' + str(pg) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': pg }) <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-04 from urllib.parse import urljoin from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class YongYuanFundSpider(GGFundNavSpider): name = 'FundNav_YongYuanFund' sitename = '嘉兴永源投资' channel = '投资顾问' fps = [{'url': 'http://www.yongyuanfund.com/Index.aspx'}] def parse_fund(self, response): funds = response.xpath('//div[@class="netWorth"]/table/tr')[1:] for fund in funds: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund.xpath('./td[1]/a/text()').extract_first() statistic_date = fund.xpath('./td[5]/text()').extract_first() item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') nav = fund.xpath('./td[2]/text()').extract_first() item['nav'] = float(nav) if nav is not None else None yield item url = fund.xpath('./td[1]/a/@href').extract_first() url = urljoin('http://www.yongyuanfund.com/', url) self.ips.append({ 'url': url, 'ref': response.url }) def parse_item(self, response): nav_rows = response.xpath('//div[@class="content"]/table//tr') for row in nav_rows[1:]: nav_info = row.xpath('td/text()').extract() fund_name = nav_info[0] statistic_date = nav_info[4] nav = nav_info[1] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-04 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class LingZhenZiChanInvestSpider(GGFundNavSpider): name = 'FundNav_LingZhenZiChanInvest' sitename = '领真资产' channel = '投资顾问' allowed_domains = ['www.lzasset.com'] fps = [{'url': 'http://www.lzasset.com/funds.php?ntc=1'}] def parse_fund(self, response): fund_urls = response.xpath("//div[@class='fund_list']//a") for url in fund_urls: fund_url = url.xpath(".//@href").extract_first() fund_name = url.xpath(".//text()").extract_first() if fund_url: self.ips.append({ 'url': 'http://www.lzasset.com' + fund_url + '&page=1&ntc=1', 'ref': response.url, 'ext': {'fund_name': fund_name,'last_one_date':""}, 'pg': 1 }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath("//div[@class='right_colume']//ul") if len(rows) > 1: for row in rows[1:]: statistic_date = row.xpath("./li[1]//text()").extract_first() nav = row.xpath("./li[2]//text()").extract_first() added_nav = row.xpath("./li[3]//text()").extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item pg = response.meta['pg'] last_two_date = response.meta['ext']['last_one_date'] last_one_date = statistic_date if last_one_date != last_two_date: next_pg = pg + 1 next_url = response.url.replace('page=' + str(pg), 'page=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name,'last_one_date':last_one_date} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-21 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin import re class WesternTrustSpider(GGFundNavSpider): name = 'FundNav_WesternTrust' sitename = '西部信托' channel = '信托净值' allowed_domains = ['www.wti-xa.com'] fps = [{'url': 'http://www.wti-xa.com/gongsixinwen_single_jingzhi.jsp?pageIndex=1&pageSize=10&pageFlag=3'}] def parse_fund(self, response): names_list = response.xpath('//div[@class="content"]/div[2]//tr//@title').extract() href_list = response.xpath('//div[@class="content"]/div[2]//tr//@href').extract() for name, fund_href in zip(names_list, href_list): if ('特定产品' not in name) and ('jm_login.jsp' not in fund_href): fund_name = name href = fund_href ips_url = (urljoin('http://www.wti-xa.com/', href)) self.ips.append({ 'url': ips_url, 'ref': response.url, 'pg': 1, 'ext': {'fund_name': fund_name}, }) end_page = re.findall('<DIV class=pageinfo>共 (.*?)页,跳转到', response.text)[0] pg = response.url.replace('http://www.wti-xa.com/gongsixinwen_single_jingzhi.jsp?pageIndex=', '').replace( '&pageSize=10&pageFlag=3', '') next_pg = int(pg) + 1 if next_pg <= int(end_page): self.fps.append({ 'url': 'http://www.wti-xa.com/gongsixinwen_single_jingzhi.jsp?pageIndex=' + str( next_pg) + '&pageSize=10&pageFlag=3', 'ref': response.url, }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//div[@class="box"]/div/div//tr') for row in rows[1:]: statistic_date = row.xpath('.//td[1]//text()').extract_first() if '分红' not in statistic_date: nav = row.xpath('.//td[2]//text()').extract_first() added_nav = row.xpath('.//td[3]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if ('-' not in nav) else None item['added_nav'] = float(added_nav) if ('-' not in added_nav) else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department:保障部 # Author:宋孝虎 # Create_Date:2018-05-30 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class HuiShengTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_HuiShengTouZiInvest' sitename = '汇升投资' channel = '投顾净值' allowed_domains = ['www.hhhstz.com'] def start_requests(self): urls = ['http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/5.html&name=汇升睿进二号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/7.html&name=大朴汇升定增一号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/17.html&name=汇升融创一号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/15.html&name=大朴汇升定增二号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/28.html&name=汇升稳进多策略四号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/1.html&name=睿进一号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/24.html&name=稳进七号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/10.html&name=汇升多策略', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/25.html&name=创盈一号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/3.html&name=富安达汇升稳进一号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/16.html&name=汇升稳进二号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/21.html&name=稳进五号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/30.html&name=汇升稳进多策略三号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/6.html&name=千石华宝汇升优选一号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/20.html&name=大有期货-华量汇鸿汇升一号资产管理计划', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/22.html&name=汇升共盈尊享', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/29.html&name=汇升智选二号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/2.html&name=汇升稳进一号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/23.html&name=汇升多策略二号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/8.html&name=平安信托金蕴九期', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/11.html&name=汇升稳进价值增长', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/18.html&name=汇升融创二号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/19.html&name=汇升稳进三号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/26.html&name=汇升稳进融享', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/4.html&name=广发汇盛MOM2号', 'http://www.hhhstz.com/Home/Index/productDetail/action_name/product/id/9.html&name=汇升智选一号'] for url in urls: self.ips.append({ 'url': url, 'ref': 'http://www.hhhstz.com', }) yield self.request_next() def parse_item(self, response): fund_name = response.xpath('//h2//text()').extract_first() navs = re.findall('var data1= \[(.*?)\];', response.text)[0].replace('"', '').split(',') added_navs = re.findall(r'var data2= \[(.*?)\];', response.text)[0].replace('"', '').split(',') statistic_dates = re.findall(r'var data3= \[(.*?)\];', response.text)[0].replace('"', '').split(',') for nav, added_nav, statistic_date in zip(navs, added_navs, statistic_dates): item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest, Request from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class YongWangAssetsSpider(GGFundNavSpider): name = 'FundNav_YongWangAssets' sitename = '永望资产' channel = '投资顾问' username = '123' password = '<PASSWORD>' fps = [{ 'url': 'http://www.ywasset.com/product/index.php?c=show&id=1' }] def start_requests(self): yield FormRequest(url='http://www.ywasset.com/member/index.php?c=login&m=index', formdata={ 'back': '', 'data[username]': self.username, 'data[password]': <PASSWORD> }, callback=self.parse_login) def parse_login(self, response): url = response.xpath('//div[@id="messagetext"]/p/script/@src').extract_first() yield Request(url=urljoin(get_base_url(response), url), ) def parse_fund(self, response): funds = response.xpath("//div[@class='fl pagleft']/ul/li/a") for fund in funds: url = fund.xpath('./@href').extract_first() fund_name = fund.xpath('./text()').extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//table/tbody/tr')[1:] for row in rows: statistic_date = row.xpath('./td[1]//text()').re_first('\d+/\d+/\d+') nav = row.xpath('./td[2]//text()').re_first('[0-9.]+') added_nav = row.xpath('./td[3]//text()').re_first('[0-9.]+') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest from scrapy import Request import re class LongYuanTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_LongYuanTouZiInvest' sitename = '隆源投资' channel = '投资顾问' allowed_domains = ['www.longwininvestment.com'] username = '13916427906' password = '<PASSWORD>.' def start_requests(self): yield FormRequest( url='http://www.longwininvestment.com/Execution.aspx?type=login&t=user&tipurl=http://www.longwininvestment.com/default.aspx&tip_string=%E4%BC%9A%E5%91%98%E7%99%BB%E5%BD%95%E6%88%90%E5%8A%9F%EF%BC%81', formdata={'yonghuming': '13916427906', 'mima': 'ZYYXSM123.'}, meta={'handle_httpstatus_list': [302]}, callback=self.parse_home) def parse_home(self, response): yield Request(url='http://www.longwininvestment.com/page.aspx?id=1&classid=39', callback=self.parse_home_url) def parse_home_url(self, response): fund_urls = response.xpath("//div[@class='cp_list']//a") for url in fund_urls: fund_name = url.xpath('.//text()').extract_first().strip() fund_url = url.xpath('.//@href').extract_first() self.fps.append({ 'url': 'http://www.longwininvestment.com' + fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_fund(self, response): if 'iframe src=' in response.text: fund_url = re.findall(r'<iframe src="(.*?)" allowtransparency=', response.text)[0] fund_name = response.meta['ext']['fund_name'] self.ips.append({ 'url': 'http://www.longwininvestment.com' + fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name, 'url': fund_url}, 'pg': 1 }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath("//tr") if len(rows) > 1: for row in rows[1:]: nav = row.xpath('./td[2]//text()').extract_first().replace('( ', '(').replace('(', '(') if '(' in nav: nav = nav.split('(')[0] statistic_date = row.xpath('./td[1]//text()').extract_first().replace('年', '-').replace('月', '-').replace( '日', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item pg = response.meta['pg'] next_pg = int(pg) + 1 url = response.meta['ext']['url'] next_url = 'http://www.longwininvestment.com' + url + '&page=' + str(next_pg) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name, 'url': url}, }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy import FormRequest import json class BaochengqihuoSpider(GGFundNoticeSpider): name = 'FundNotice_Baochengqihuo' sitename = '宝城期货' entry = 'http://www.bcqhgs.com/' def start_requests(self): yield FormRequest( url='http://www.bcqhgs.com/handle/zcgl.ashx?action=getzcglcount', formdata={'fs': 'ZGGG'}, callback=self.parse_list ) def parse_list(self, response): count = int(response.text) self.ips.append({ 'url': 'http://www.bcqhgs.com/handle/zcgl.ashx?action=getzcgl', 'form': { 'fs': 'ZGGG', 'pagecount': str(count), 'pagesize': '15', 'pageindex': '0' }, 'pg': 0 }) def parse_item(self, response): form = response.meta['form'] pagecount = form['pagecount'] pagesize = form['pagesize'] rows = json.loads(response.text) for row in rows: item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry url = 'http://www.bcqhgs.com/zcgldetail.shtml#ZGGG_' + str(row['infor_id']) title = row['infor_title'] publish_time = row['infor_addtime'] publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item pg = response.meta['pg'] + 1 if (int(pagecount) / int(pagesize)) > int(pg): self.ips.append({ 'url': 'http://www.bcqhgs.com/handle/zcgl.ashx?action=getzcgl', 'form': { 'fs': 'ZGGG', 'pagecount': pagecount, 'pagesize': '15', 'pageindex': str(pg) }, 'pg': pg }) yield self.request_next() <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class DongFangZhengQuanChuangXinTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_DongFangZhengQuanChuangXinTouZiInvest' sitename = '上海东方证券创新投资' channel = '投资顾问' allowed_domains = ['dzcx.dfzq.com.cn'] ips = [ {'url': 'http://dzcx.dfzq.com.cn/js/product.js'}, ] def parse_item(self, response): fund_names = re.findall('"name" : "(.*?)",', response.text) navs = re.findall('"unit" : "(.*?)",', response.text) added_navs = re.findall('"accumulation" : "(.*?)",', response.text) statistic_dates = re.findall('"date" : "(.*?)"', response.text) for row in zip(fund_names, statistic_dates, navs, added_navs): fund_name = row[0] statistic_date = row[1] nav = row[2] added_nav = row[3] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-02 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest import re class HongYiTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_HongYiTouZiInvest' sitename = '鸿逸投资' channel = '投顾净值' allowed_domains = ['www.hongyish.com.cn'] username = '15838569960' password = '<PASSWORD>' fps = [{'url': 'http://www.hongyish.com.cn/proindex.asp'}] def start_requests(self): yield FormRequest(url='http://www.hongyish.com.cn/MemberLogin.asp', formdata={'LoginName': '15838569960', 'LoginPass': '<PASSWORD>', 'x': '41', 'y': '17', } ) def parse_fund(self, response): fund_urls = response.xpath("//td[@id='submenu1']//tr") for url in fund_urls: fund_url = url.xpath(".//@href").extract_first() fund_name = url.xpath("./td//text()").extract()[1] self.ips.append({ 'url': fund_url.replace('pro.asp?', 'http://www.hongyish.com.cn/equity.asp?page=1&'), 'ref': response.url, 'ext': {'fund_name': fund_name}, 'pg': 1 }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath("//div[@class='bottombox fl']/table[@class='equityTable']//tr") end_pg = re.findall('当前为<font color="#FF0000">(.*?)</font>/(\d+)页 ', response.text)[0][1] if len(rows) > 1: for row in rows[1:]: statistic_date = row.xpath("./td[1]//text()").extract_first() nav = row.xpath("./td[2]//text()").extract_first() added_nav = row.xpath("./td[3]//text()").extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') yield item pg = response.meta['pg'] if pg < int(end_pg): next_pg = pg + 1 next_url = response.url.replace('?page=' + str(pg), '?page=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 柳美云 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class DuanMuTouZiSpider(GGFundNavSpider): name = 'FundNav_DuanMuTouZi' sitename = '四川端木投资' channel = '投资顾问' allowed_domains = ['www.duanmutouzi.com'] ips = [ {'url': 'http://www.duanmutouzi.com/home.html'} ] def parse_item(self, response): rows = response.xpath("//div[@class='hca_pro fl']//tr") for row in rows[1:]: i = row.xpath("./td//text()").extract() if i[2] not in '已结束': fund_name = i[0] statistic_date = i[3] nav = i[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None yield item <file_sep>from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime import re class XingYeTrustSpider(GGFundNavSpider): name = 'FundNav_XingYeTrust' channel = '信托净值' fps = [ { 'url': 'http://www.ciit.com.cn/xingyetrust-web/netvalues/netvalues!getValue?type=1&currentpage=1', 'ref': 'http://www.ciit.com.cn/', 'ext': {'sitename': '兴业信托1'}, 'pg': 1 }, { 'url': 'http://www.ciit.com.cn/xingyetrust-web/netvalues/netvalues!getValue?type=0&currentpage=1', 'ref': 'http://www.ciit.com.cn/', 'ext': {'sitename': '兴业信托2'}, 'pg': 1 } ] def parse_fund(self, response): sitename = response.meta['ext']['sitename'] funds = response.xpath('//table[@class="pro_table"]/tr/td[2]/a') for fund in funds: fund_code = fund.xpath('./@href').re_first('fundCode=(\S+)\&') fund_name = fund.xpath('./text()').extract_first() self.ips.append({ 'url': 'http://www.ciit.com.cn/funds-struts/fund-net-chart-table/{}?page=1-200'.format(fund_code), 'ref': response.url, 'ext': {'fund_name': fund_name, 'sitename': sitename} }) pg = response.meta['pg'] tp = response.xpath('//a[contains(text(), "尾页")]/@href').re_first('\d+') if tp is not None: if pg < int(tp): pg += 1 url = re.sub('currentpage=\d+', 'currentpage=' + str(pg), response.url) self.fps.append({ 'url': url, 'ref': response.url, 'ext': {'sitename': sitename}, 'pg': pg }) def parse_item(self, response): sitename = response.meta['ext']['sitename'] fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//table[@class="table2"]/tr')[1:] for row in rows: item = GGFundNavItem() item['sitename'] = sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = row.xpath('./td[1]').re_first('\d+-\d+-\d+') if statistic_date is None: continue item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row.xpath('./td[2]').re_first('>\s*([0-9.]+)\s*<') item['nav'] = float(nav) if nav is not None else None yield item <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-08 from datetime import datetime from scrapy import FormRequest, Request from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class GoldenQuantSpider(GGFundNavSpider): name = 'FundNav_GoldenQuant' sitename = '灰金量投' channel = '投资顾问' username = '13916427906' password = '<PASSWORD>' fps = [{'url': 'https://goldenquant.com'}] def start_requests(self): yield Request(url='https://goldenquant.com/login', callback=self.parse_login) def parse_login(self, response): token = response.xpath('//input[@name="_token"]/@value').extract_first() yield FormRequest(url='https://goldenquant.com/login', method='POST', formdata={'_token': token, 'email': self.username, 'password': <PASSWORD>, 'remember': '1' }, ) def parse_fund(self, response): name_info = response.xpath( '//div[@class="col-sm-6 col-md-4 col-lg-3 text-center m-top-24"]/div[@class="investments-top"]/p[@class="title-lg opacity-1"]/text()').extract() code_info = response.xpath( '//div[@class="col-sm-6 col-md-4 col-lg-3 text-center m-top-24"]/div[@class="investments-bottom"]/a[@class="btn btn-orange btn-width-200"]/@onclick').re( '\d+') for name, code in zip(name_info, code_info): nav_link = 'https://goldenquant.com/api/product/' + code + '/nav' self.ips.append({ 'url': nav_link, 'ref': response.url, 'ext': name }) def parse_item(self, response): nav_json = json.loads(response.text) for nav_info, added_nav_info in zip(nav_json['nav'], nav_json['auv']): nav = nav_info[1] added_nav = added_nav_info[1] statistic_date = datetime.fromtimestamp((nav_info[0] / 1000)) fund_name = response.meta['ext'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if added_nav else None item['statistic_date'] = statistic_date if statistic_date else None yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-21 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class WuKongAssetSpider(GGFundNavSpider): name = 'FundNav_WuKongAsset' sitename = '悟空投资' channel = '投顾净值' fps = [{'url': 'http://www.wukongtz.com/list/?6_1.html'}] def parse_fund(self, response): href_list = response.css('ul.f12 a::attr(href)').extract() for href in href_list: self.ips.append({ 'url': 'http://www.wukongtz.com%s' % href, 'ref': response.url }) def parse_item(self, response): rows = response.css('tbody#result tr') for r in rows: fund_name = r.css('td:nth-child(1)::text').extract_first() date = r.css('td:nth-child(2)::text').extract_first() add_nav = r.css('td:nth-child(3) ::text').re_first("(.*)") item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['added_nav'] = float(add_nav) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item next_href = response.xpath('//div[@class="pages"]//a[contains(text(),"下一页")]/@href').extract_first() if next_href: self.ips.append({ 'url': 'http://www.wukongtz.com/list/%s' % next_href, 'ref': response.url }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from scrapy import Request from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class NewValueSpider(GGFundNavSpider): name = 'FundNav_NewValue' sitename = '新价值' channel = '投顾净值' cookies = 'UM_distinctid=161bcc83bc04aa-0250cf6ddd829f-393d5f0e-15f900-161bcc83bc1195; ASPSESSIONIDACCBSQBT=BHFBIAACFCNNGACDAGNPFCLH; ASPSESSIONIDCCDASQAS=DJJNOOADOPEBOIJDEADGMGJO; ASPSESSIONIDAABATRBT=MHFDDFIAFIGLIPFLJCMOCEFJ; ASPSESSIONIDCACATRAS=LMDNABLAOJNLHAABDPHGLNEJ; ASPSESSIONIDCCCCRQBS=PBNLOIGAECEMJFHCPNFJLBNF; ASPSESSIONIDACDATRBT=EPODFEGAJNOEFPNPHNAHELDI; ASPSESSIONIDCASAQRTS=EJBPKBOCDFHKIDKLAFHMIKGJ; CNZZDATA2966838=cnzz_eid%3D535109687-1502961414-http%253A%252F%252Fwww.newvalue.com.cn%252F%26ntime%3D1527123493' username = '123456' password = '<PASSWORD>' def start_requests(self): yield Request(url='http://www.newvalue.com.cn/products.asp?pid=1', callback=self.parse_login) def parse_login(self, response): urls = response.xpath('//ul[@class="yiji"]/li/a/@href').extract() for url in urls: self.fps.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url }) def parse_fund(self, response): funds = response.xpath('//table[@class="pr_view"]/tr/td[1]/a') for fund in funds: url = fund.xpath('./@href').extract_first() fund_name = fund.xpath('./text()').extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//*[@id="group_one"]/tr') for row in rows: nav = row.xpath('./td[3]/text()').extract_first() statistic_date = row.xpath('./td[2]/text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep> from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class PingAnHeDingInvestSpider(GGFundNavSpider): name = 'FundNav_PingAnHeDingInvest' sitename = '平安阖鼎投资' channel = '投顾净值' fps = [ { 'url': 'http://trust.pingan.com/hedingchanpinjingzhi/index.shtml', 'form': {'currentPageNo': '1'}, 'pg': 1 } ] def parse_fund(self, response): funds = response.xpath('//table[@id="hdTable"]/tr')[1:] for fund in funds: fund_code = fund.xpath('./td[last()]/a/@href').re_first('index_(\S+)_1\.shtml') fund_name = fund.xpath('./td[2]/text()').extract_first() self.ips.append({ 'url': 'http://trust.pingan.com/hedingchanpinjingzhi/index_' + fund_code + '_2.shtml', 'form': {'trustNo': fund_code, 'pageNo': '1', 'allPage': '2'}, 'ref': response.url, 'ext': {'fund_name': fund_name}, }) pg = response.meta['pg'] if len(funds) > 1: pg += 1 self.fps.append({ 'url': 'http://trust.pingan.com/hedingchanpinjingzhi/index.shtml', 'form': {'currentPageNo': str(pg)}, 'ref': response.url, 'pg': pg }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//table[@class="hwp_table m_a"]/tbody/tr')[2:] for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name fund_date = row.xpath('./td[2]/text()').extract_first() if fund_date is None: continue item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') nav = row.xpath('./td[4]/text()').re_first('[0-9.]+') item['nav'] = float(nav) if nav is not None and nav != '' else None added_nav = row.xpath('./td[5]/text()').re_first('[0-9.]+') item['added_nav'] = float(added_nav) if added_nav is not None and added_nav != '' else None yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-06-04 from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime import re class BoHaiTrustSpider(GGFundNavSpider): name = 'FundNav_BoHaiTrust' sitename = '渤海信托' channel = '信托净值' allowed_domains = ['www.xingrunfund.com'] start_urls = ['http://www.xingrunfund.com/product.asp'] fps = [{'url': 'https://www.bohaitrust.com/Other/netvalue/cid/46/lid/47/p/1.html', 'pg': 1}] def parse_fund(self, response): href_list = response.css('div.jzlist a::attr(href)').extract() for href in href_list: self.ips.append({ 'url': 'https://www.bohaitrust.com' + href, 'ref': response.url, }) if href_list: next_pg = response.meta['pg'] + 1 next_url = re.sub('p/\d+\.', r'p/%s.' % next_pg, response.url) self.fps.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg }) def parse_item(self, response): p_name = response.xpath('//input[@name="productname"]/@value').extract_first() date_list = response.xpath('//input[@name="xx"]/@value').extract_first().split(',') nav_list = response.xpath('//input[@name="yy"]/@value').extract_first().split(',') for d, n in zip(date_list, nav_list): item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = p_name.strip() item['statistic_date'] = datetime.strptime(d.strip(), '%Y-%m-%d') if d else None item['nav'] = float(n.strip()) if n else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class ShunShiGuoJiSpider(GGFundNoticeSpider): name = 'FundNotice_ShunShiGuoJi' sitename = '顺时国际' entry = 'http://www.timewise.com.cn/website/w/h?mt=2&mc=3665612&cc=1519602' ips = [ { 'url': 'http://www.timewise.com.cn/website/w/h?mt=2&mc=3665612&cc=1519602', 'pg': 0 } ] def parse_item(self, response): rows = response.xpath('//div[@class="simu-site-list"]/ul/a') for row in rows: click_url = row.xpath('./@clickurl').extract_first() href = urljoin(get_base_url(response), row.xpath('./@href').extract_first()) url = click_url if click_url is not '' else href title = row.xpath('./li/div[@class="simu-site-right"]/div[1]/text()').extract_first().strip() publish_time = row.xpath('./li/div[@class="simu-site-right"]/div[3]/div[2]/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item tp = int(response.xpath('//div[@class="simu-site-pagination"]/ul/li[last()]/a[contains(text(),"末页")]/@href').re_first('paging&c=(\d+)')) pg = response.meta['pg'] + 1 if pg <= tp: self.ips.append({ 'url': 'http://www.timewise.com.cn/website/w/h?mt=2&mc=3665612&cc=1519602&fp=paging&c={0}'.format(pg), 'ref': response.url, 'pg': pg }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-04-27 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class HongTaZhengQuanSecutiesSpider(GGFundNavSpider): name = 'FundNav_HongTaZhengQuanSecuties' sitename = '红塔证券' channel = '券商资管净值' allowed_domains = ['www.hongtastock.com'] proxy = 2 fps = [{'url': 'http://www.hongtastock.com/funddaily/funddaily.aspx?id=C58888'}] def parse_fund(self, response): fund_ids = re.findall('<option(.*?)value="(.*?)">(.*?)</option>', response.text) zz1 = '<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="(.*?)" />' zz2 = '<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="(.*?)" />' __VIEWSTATE = re.findall(zz1, response.text)[0] __EVENTVALIDATION = re.findall(zz2, response.text)[0] for id in fund_ids: fund_id = id[1] fund_name = id[2] self.ips.append({ 'url': 'http://www.hongtastock.com/funddaily/funddaily.aspx?id=' + fund_id, 'ref': response.url, 'form': {'__VIEWSTATE': __VIEWSTATE, '__VIEWSTATEGENERATOR': '5ED276C6', '__EVENTTARGET': 'pager1', '__EVENTARGUMENT': "1", '__EVENTVALIDATION': __EVENTVALIDATION, 'ProductName': fund_id, }, 'ext': {'fund_name': fund_name, 'fund_id': fund_id}, 'pg': 1 }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath("//table[@class='listtable']//tr") for row in rows[4:]: statistic_date = row.xpath("./td[1]//text()").extract_first().strip() nav = row.xpath("./td[2]//text()").extract_first().strip() added_nav = row.xpath("./td[3]//text()").extract_first().strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime( statistic_date.replace('年', '-').replace('月', '-').replace('日', ''), '%Y-%m-%d') yield item if '</span><a disabled' not in response.text: pg = response.meta['pg'] fund_id = response.meta['ext']['fund_id'] next_pg = str(int(pg) + 1) zz1 = '<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="(.*?)" />' zz2 = '<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="(.*?)" />' __VIEWSTATE = re.findall(zz1, response.text)[0] __EVENTVALIDATION = re.findall(zz2, response.text)[0] self.ips.append({ 'url': 'http://www.hongtastock.com/funddaily/funddaily.aspx?id=' + fund_id, 'ref': response.url, 'form': {'__VIEWSTATE': __VIEWSTATE, '__VIEWSTATEGENERATOR': '5ED276C6', '__EVENTTARGET': 'pager1', '__EVENTARGUMENT': str(next_pg), '__EVENTVALIDATION': __EVENTVALIDATION, 'ProductName': fund_id, }, 'ext': {'fund_name': fund_name, 'fund_id': fund_id}, 'pg': next_pg }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest, Request from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class BeiJingFuRuiDeInvestSpider(GGFundNoticeSpider): name = 'FundNotice_BeiJingFuRuiDeInvest' sitename = '北京福睿德投资' entry = 'http://www.freedchina.com/news/notice' username = '13916427906' password = '<PASSWORD>' ips = [ { 'url': 'http://www.freedchina.com/news/notice', 'pg': 1 } ] def start_requests(self): yield Request(url='http://www.freedchina.com/ti/agree/status/agree', meta={'handle_httpstatus_list': [302]}, callback=self.parse_login) def parse_login(self, response): yield FormRequest(url='http://www.freedchina.com/Login/login', formdata={ 'username': self.username, 'password': self.<PASSWORD> }, meta={'handle_httpstatus_list': [302]}) def parse_item(self, response): rows = response.xpath('//div[@class="new_box clearbox"]/ul/li/a') for row in rows: url = row.xpath('./@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./h6/text()').extract_first() publish_time = row.xpath('./time/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item tp = response.xpath('//div[@class="page ha-waypoint"]/a[text() = "最后一页"]/@href').re_first('page=([\d]+)') pg = response.meta['pg'] + 1 if tp and pg <= int(tp): self.ips.append({ 'url': 'http://www.freedchina.com/news/notice?page={0}'.format(pg), 'ref': response.url, 'pg': pg }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin class ZhongOuRuiBoInvestSpider(GGFundNoticeSpider): name = 'FundNotice_ZhongOuRuiBoInvest' sitename = '中欧瑞博' entry = 'http://www.rabbitfund.com.cn' ips = [ { 'url': 'http://www.rabbitfund.com.cn/cn/news/notice.html?cateid=14034', 'ref': 'http://www.rabbitfund.com.cn', } ] def parse_item(self, response): datas = response.xpath('//ul[@class="announ-ul"]/li/a') for notice in datas: href = notice.xpath('./@href').extract_first() title = notice.xpath('normalize-space(./div[@class="announ-cont"]/h3/text())').extract_first() year = notice.xpath('./div[@class="announ-time"]/p/text()').extract_first() publish_time = year + '-' + notice.xpath('./div[@class="announ-time"]/h3/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = href item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item next_url = response.xpath('//a[contains(text(),"下一页")]/@href').extract_first() if next_url is not None and next_url != '': url = self.entry + next_url self.ips.append({'url': url, 'ref': response.url}) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class HuiYuInvestSpider(GGFundNavSpider): name = 'FundNav_HuiYuInvest' sitename = '云南汇誉投资' channel = '投资顾问' fps = [ { 'url': 'http://www.huiyutouzi.cn/list.asp?id=6' } ] def parse_fund(self, response): rows = response.xpath('//div[@class="mm box1"]')[0].xpath('./ul/li/a[contains(text(),"产品历史净值")]') for row in rows: url = row.xpath('./@href').extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url }) def parse_item(self, response): fund_name = response.xpath('//h1[@class="aTitle"]/text()').re_first('([^/]+)产品历史净值') rows = response.xpath('//table/tbody/tr')[1:] for row in rows: statistic_date = row.xpath('./td[1]//text()').re_first('\d+-\d+-\d+') nav = row.xpath('./td[2]//text()').re_first('[0-9.]+') added_nav = row.xpath('./td[3]//text()').re_first('[0-9.]+') if statistic_date is not None: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep>SPIDER_MODULES = [ 'spiders', 'FundNavSpiders', 'FundNoticeSpiders', ] DEFAULT_REQUEST_HEADERS = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Language': 'zh-CN,zh;q=0.9', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)' ' Chrome/66.0.3359.139 Safari/537.36', } proxies = [ None, # http://user:pass@addr:port None, None, None, None, None, ] fund_nav = { 'db': { 'host': '192.168.0.53', 'name': 'scrapy_debug_db', 'port': 1433, 'user': 'sql_scrapy', 'pswd': '<PASSWORD>', 'table': 't_nav_general', 'timeout': 60, }, } fund_notice = { 'db': { 'host': '192.168.0.53', 'name': 'scrapy_debug_db', 'port': 1433, 'user': 'sql_scrapy', 'pswd': '<PASSWORD>', 'table': 't_fund_announcement', 'timeout': 60, }, } <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-04-27 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re import json class HongYeQiHuoFuturesSpider(GGFundNavSpider): name = 'FundNav_HongYeQiHuoFutures' sitename = '弘业期货' channel = '期货净值' fps = [{'url': 'http://www.ftol.com.cn/main/lczx/zcgl/cpjzpl/detail.shtml'}] def parse_fund(self, response): fund_ids = re.findall(r'product_code="(.*?)"', response.text) for fund_id in fund_ids: self.ips.append({ 'url': 'http://www.ftol.com.cn/servlet/json?funcNo=906329&product_code=' + fund_id + '&year=0&month=3&day=0&_catalogId=&rightId=', 'ref': response.url, }) def parse_item(self, response): nav_intos = json.loads(response.text) nav_into = nav_intos['results'][0] fund_name = nav_into['product_shortname'] nav_datas = nav_into['nav_date'] navs = nav_into['product_nav_arr'] for row in zip(nav_datas, navs): statistic_date = row[0] nav = row[1] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class JunZeLiCapitalSpider(GGFundNoticeSpider): name = 'FundNotice_JunZeLiCapital' sitename = '深圳君泽利投资发展企业' entry = 'http://www.jzlfund.com/News.asp' lps = [ { 'url': 'http://www.jzlfund.com/News.asp' } ] def parse_list(self, response): rows = response.xpath('//div[@class="left_menu"]/a[contains(text(),"企业动态") or contains(text(),"企业公告")]') for row in rows: url = row.xpath('./@href').extract_first() class_id = row.xpath('./@href').re_first('ClassID=(\d+)') self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url, 'pg': 1, 'ext': {'class_id': class_id} }) def parse_item(self, response): ext = response.meta['ext'] rows = response.xpath('//ul[@id="news"]/li') for row in rows: url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./a/text()').extract_first() publish_time = row.xpath('./span/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = url item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item class_id = ext['class_id'] tp = int(response.xpath('//div[@id="showpage"]/div/a/@href')[-1].re_first('Page=(\d+)')) pg = response.meta['pg'] + 1 if pg <= tp: self.ips.append({ 'url': 'http://www.jzlfund.com/News.asp?ClassID={0}&Page={1}'.format(class_id, pg), 'ref': response.url, 'pg': pg, 'ext': {'class_id': class_id} }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url import json import re class ZhongXinJianSheSpider(GGFundNoticeSpider): name = 'FundNotice_ZhongXinJianShe' sitename = '中信建投' entry = 'https://www.csc108.com/' proxy = 2 cookies = '__jsluid=9f8ce8eb51aab6705d8a908f91634fbd; SERVERID=b6f09cec80b80dc50f5a41b77b6cee7e|1526537676|1526537676; JSESSIONID=_jxs151mash1VkzEvfwO5IcLu4wIAMlVbco_eWGTJ37UvuP8yBtC!-1252920085' username = '15138719815' password = '<PASSWORD>' lps = [{'url': 'https://www.csc108.com/zgcp/assetManageIndex.jspx'}] def parse_list(self, response): base_url = 'https://www.csc108.com/zgcp/getAttachUploadList.jspx' funds = response.xpath( '/html/body/div[5]/div//div[@class="zuocefudhul"]/ul/ul[position()>1]/li/a/@href').extract() for url in funds: fund_id = re.search(r'productCode=(\S+)', url).group(1) self.ips.append({'url': base_url, 'ref': response.url, 'form': {'curPage': '1', 'file_type': '1', 'productCode': str(fund_id)}, 'ext': {'report_type': '1', 'file_type': '1', 'page': '1', 'fund_id': str(fund_id)}}) self.ips.append({'url': base_url, 'ref': response.url, 'form': {'curPage': '1', 'file_type': '2', 'productCode': str(fund_id)}, 'ext': {'report_type': '1', 'file_type': '2', 'page': '1', 'fund_id': str(fund_id)}}) self.ips.append({'url': base_url, 'ref': response.url, 'form': {'curPage': '1', 'file_type': '3', 'productCode': str(fund_id)}, 'ext': {'report_type': '1', 'file_type': '3', 'page': '1', 'fund_id': str(fund_id)}}) def parse_item(self, response): ext = response.meta['ext'] report_type = int(ext['report_type']) page = int(ext['page']) fund_id = ext['fund_id'] file_type = ext['file_type'] if report_type == 1: rows = response.xpath('//li') if len(rows) > 0: for row in rows: url = row.xpath('.//a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('.//a/text()').extract_first() publish_time = row.xpath('./span/text()').extract_first() if publish_time: publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item base_url = 'https://www.csc108.com/zgcp/getAttachUploadList.jspx' url = base_url + '?curPage=' + str(page+1) url = url + '&file_type=' + str(file_type) url = url + '&productCode=' + str(fund_id) self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'report_type': str(report_type), 'file_type': str(file_type), 'page': str(page+1), 'fund_id': str(fund_id)} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-18 # Alter_date : 2018-05-23 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest import re class SHZQFuturesSpider(GGFundNavSpider): name = 'FundNav_SHZQFutures' sitename = '上海中期期货' channel = '期货净值' allowed_domains = ['www.shcifco.com'] username = 'ZYYXSM' password = '<PASSWORD>' fps = [{ 'url': 'http://www.shcifco.com/plus/list.php?tid=168&TotalResult=25&nativeplace=0&infotype=0&keyword=&fxlx=&cplx=&cpjs=&tzcl=&PageNo=1'}, ] def start_requests(self): yield FormRequest(url='http://www.shcifco.com/relo/shangxian_ac.php', formdata={'username': 'ZYYXSM', 'password': '<PASSWORD>', 'submit': '', }) def parse_fund(self, response): fund_hrefs = response.xpath("//div[@class='cfzx_main3_main']/div[4]//ul//li[2]//@href").extract() fund_names = response.xpath("//div[@class='cfzx_main3_main']/div[4]//ul//li[2]//a//text()").extract() for (fund_href, name) in zip(fund_hrefs, fund_names): urls = re.findall('.*/(.*?).html', fund_href)[0] fund_url = 'http://www.shcifco.com/plus/show_jz.php?wdid=' + urls fund_name = name.strip() self.ips.append({ 'url': fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name}}) pg = response.url.replace( 'http://www.shcifco.com/plus/list.php?tid=168&TotalResult=25&nativeplace=0&infotype=0&keyword=&fxlx=&cplx=&cpjs=&tzcl=&PageNo=', '') next_pg = int(pg) + 1 if next_pg <= 2: self.fps.append({ 'url': 'http://www.shcifco.com/plus/list.php?tid=168&TotalResult=25&nativeplace=0&infotype=0&keyword=&fxlx=&cplx=&cpjs=&tzcl=&PageNo=' + str( next_pg), 'ref': response.url}) def parse_item(self, response): rows = response.xpath('//div[@class="cfzx_tjtg"]/div[2]//ul') fund_name = response.meta['ext']['fund_name'] for row in rows[2:]: statistic_date = row.xpath('.//li[1]//text()').extract_first() navs = row.xpath('.//li[2]//text()').extract_first() added_navs = row.xpath('.//li[3]//text()').extract_first() if (statistic_date is not None and navs is not None and added_navs is not None) and ('/' not in navs) and ( '.' not in statistic_date): date = statistic_date.strip() nav = navs.strip() added_nav = added_navs.strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) if '-' not in added_nav else None item['statistic_date'] = datetime.strptime(date, '%Y/%m/%d') yield item <file_sep># -*- coding: utf-8 -*- import json from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class ZhaoShangSecuritySpider(GGFundNoticeSpider): name = 'FundNotice_ZhaoShangSecurity' sitename = '招商证券' entry = 'https://amc.cmschina.com/news/gonggao' lps = [ { 'url': 'https://amc.cmschina.com/news/gonggao' } ] def parse_list(self, response): rows = response.xpath('//div[@class="left_nav left"]/ul/li/a') for row in rows: url = row.xpath('./@href').extract_first() name = row.xpath('./text()').extract_first() if name == '最新公告': url_param = 'https://amc.cmschina.com/news/detail?type=gonggao&id=' url_type = 'gonggao' elif name == '定期报告': url_param = 'https://amc.cmschina.com/news/detail?type=dqbg&id=' url_type = 'dqbg' self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url, 'form': { 'type': url_type, 'page': '1' }, 'headers': { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept': 'application/json, text/javascript, */*; q=0.01' }, 'pg': 1, 'ext': {'url_param': url_param, 'url_type': url_type} }) def parse_item(self, response): url_type = response.meta['ext']['url_type'] url_param = response.meta['ext']['url_param'] data = json.loads(response.text)['data'] rows = data['rows'] for row in rows: url_id = row[0] title = row[1] publish_time = row[2] url = url_param + url_id item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') if '-' in publish_time else datetime.strptime(publish_time, '%Y%m%d') yield item total = int(data['total']) page_size = int(data['pagesize']) tp = int(total / page_size if total % page_size == 0 else total // page_size + 1) pg = response.meta['pg'] + 1 if pg <= tp: self.ips.append({ 'url': 'https://amc.cmschina.com/news/{0}'.format(url_type), 'ref': response.url, 'form': { 'type': url_type, 'page': str(pg) }, 'headers': { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept': 'application/json, text/javascript, */*; q=0.01' }, 'pg': pg, 'ext': {'url_param': url_param, 'url_type': url_type} }) <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-21 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class WenShaCapitalSpider(GGFundNavSpider): name = 'FundNav_WenShaCapital' sitename = '温莎资本' channel = '投资顾问' fps = [{'url': 'http://www.windsorfund.cn/jingxuan9.html'}] def parse_fund(self, response): href_list = response.css('div.span4.menu-side a::attr(href)').extract() fname_list = response.css('div.span4.menu-side a::text').extract() for h, fname in zip(href_list, fname_list): if 'announcement' not in h: href = h.replace('./', '') self.ips.append({ 'url': 'http://www.windsorfund.cn/' + href, 'ref': response.url, 'ext': fname, 'dont_retry': True, 'dont_redirect': True, 'handle_httpstatus_list': [301, 302] }) def parse_item(self, response): if response.status == 200: rows = response.xpath('//div[contains(@class,"product_tab_sub")][3]//tr') fund_name = response.meta['ext'].replace(':', '') for r in rows[1:]: date = r.css('td:nth-child(1)::text').re_first('\S+') add_nav = r.css('td:nth-child(2)::text').re_first('\S+') item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['added_nav'] = float(add_nav.replace(' ', '')) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y/%m/%d') if date else None yield item <file_sep>from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json from datetime import date, datetime class LeiGenFundSpider(GGFundNavSpider): name = 'FundNav_LeiGenFund' sitename = '上海雷根资产' channel = '投顾净值' fps = [ { 'url': 'http://m.reganfund.com/weChat/fundQueryNew', 'body': "{'fundInfo': '', 'top100': '1', 'tagIds': ''}", 'headers': { 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Content-Type': 'application/json; charset=UTF-8' } } ] def parse_fund(self, response): funds = json.loads(response.text)['resultList'] for fund in funds: if fund['fundName'] == '雷根9号基金': fund_code = 'S33704' else: fund_code = fund['fundCode'] body = json.dumps( {"fundCode": fund_code, "startDate": "2001-01-01", "endDate": date.isoformat(datetime.now())}) self.ips.append({ 'url': 'http://m.reganfund.com/weChat/dataOverview', 'body': body, 'headers': {'Content-Type': 'application/json; charset=UTF-8'} }) def parse_item(self, response): rows = json.loads(response.text)['result']['value'] fund_name = json.loads(response.text)['fundName'] for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = 'http://www.reganfund.com/product.html' item['fund_name'] = fund_name statistic_date = row['tradingDate'] item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row['nav'] item['nav'] = float(nav) if nav is not None else None added_nav = row['nav'] item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department:保障部 # Author:王卓诚 # Create_Date:2018-05-28 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class JinYuanSecuritySpider(GGFundNavSpider): name = 'FundNav_JinYuanSecurity' sitename = '金元证券' channel = '券商资管净值' allowed_domains = ['www.jyzq.cn'] cookies = 'JSESSIONID=abcZWIrFf_HAH5unRYfow; loginumber=0.91299219250646320180522132951; _isLoginIn=83@%7C@%7C@1526967043614; user_id=83; nick_name=%E6%9C%9D%E6%9C%9D; userid=0b36ba4b8309331b123cc76bcf2915bc; ismechanism=0; isAccordWith=; url=' username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'http://www.jyzq.cn/servlet/json', 'ref': 'http://www.jyzq.cn', 'form': {'funcNo': '502001', 'pageNum': '1', 'pageSize': '100', 'i_product_small_type': '1', 'i_product_stat': '0' } }] def parse_fund(self, response): fundnames = json.loads(response.text) fundnames1 = fundnames['results'][0]['data'] for v1 in fundnames1: self.ips.append({ 'url': 'http://www.jyzq.cn/servlet/json', 'ref': response.url, 'pg': 1, 'ext': v1['i_product_id'], 'form': { 'funcNo': '501020', 'pageNum': '1', 'pageSize': '200', 'product_id': v1['i_product_id'] } }) def parse_item(self, response): pid = response.meta['ext'] fund_info1 = json.loads(response.text) fund_into = fund_info1['results'][0]['data'] for v in fund_into: pnamef = v['i_product_name'] statistic_date = v['n_product_nav_day'] nav = v['n_product_nav'] added_nav = v['n_product_total_nav'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = pnamef item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if added_nav else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item if len(fund_into) > 2: next_pg = response.meta['pg'] + 1 self.ips.append({ 'url': 'http://www.jyzq.cn/servlet/json', 'ref': response.url, 'pg': next_pg, 'ext': pid, 'form': { 'funcNo': '501020', 'pageNum': str(next_pg), 'pageSize': '200', 'product_id': pid } }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-28 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest class XiangLiangDuoWeiCapitalSpider(GGFundNavSpider): name = 'FundNav_XiangLiangDuoWeiCapital' sitename = '北京向量多维资本' channel = '投顾净值' allowed_domains = ['www.xiangliangfund.com'] username = '薛熙茂' password = '<PASSWORD>' fps = [{ 'url': 'http://www.xiangliangfund.com/?a=cp&id=1' }] def start_requests(self): yield FormRequest(url='http://www.xiangliangfund.com/?a=dodl', formdata={ 'name': self.username, 'pwd': self.password }) def parse_fund(self, response): funds = response.xpath('//ul[@class = "menu"]//li//@href').extract() for f_url in funds: self.ips.append({ 'url': 'http://www.xiangliangfund.com' + f_url, 'ref': response.url }) def parse_item(self, response): f_list = response.xpath('//div[@class = "xian xian1"]/table[2]//tr') for i in f_list[1:]: t = i.xpath('td//text()').extract() fund_name = t[0] statistic_date = t[1] nav = t[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None yield item <file_sep># coding:utf-8 from datetime import datetime from urllib.parse import urljoin from FundNavSpiders import GGFundNavSpider from FundNavSpiders import GGFundNavItem from scrapy.utils.response import get_base_url class ZheShiShiYeSpider(GGFundNavSpider): name = 'FundNav_ZheShiShiYe' sitename = '哲实实业' channel = '投资顾问' fps = [ {'url': 'http://www.zs9188.com/Value.aspx'} ] def parse_fund(self, response): funds = response.xpath('//ul[@class="left_nav"]/li/a') for fund in funds: url = fund.xpath("./@href").extract_first() ips_url = urljoin(get_base_url(response), url) fund_name = fund.xpath("./text()").extract_first() self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] funds = response.xpath('//tr')[1:] for fund in funds: nav = fund.xpath('./td[5]//span/text()').extract_first() added_nav = fund.xpath('./td[6]//span/text()').extract_first() statistic_date = fund.xpath('./td[3]//span/text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) item['added_nav'] = float(added_nav) yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-02 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import Request class HouEnTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_HouEnTouZiInvest' sitename = '厚恩投资' channel = '投资顾问' allowed_domains = ['www.hone2015.com'] userName = '<EMAIL>' password = '<PASSWORD>' fps = [{'url': 'http://www.hone2015.com/index.php/Product_index_navid_2_all_1.html'}] def start_requests(self): yield Request( url='http://www.hone2015.com/index.php/Home/Members_ajaxLogin.html?userName=2<PASSWORD>1%40qq.com&password=<PASSWORD>&autoLogin=1', callback=self.parse_fund) def parse_fund(self, response): fund_urls = response.xpath("//div[@class='col-lg-12 col-md-12 col-sm-12']") for url in fund_urls: fund_url = url.xpath('.//@href').extract_first() fund_name = url.xpath(".//h4[@class='colo_main col-lg-10 col-md-10 col-sm-10']//text()").extract_first() self.ips.append({ 'url': 'http://www.hone2015.com' + fund_url.replace('.html', '_type_unit_p_1.html'), 'ref': response.url, 'ext': {'fund_name': fund_name}, 'pg': 1 }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath( "//div[@class='col-lg-12 col-md-12 col-sm-12']/table[@class='table table-striped']/tbody/tr") if '暂无信息' not in response.text: for row in rows: statistic_date = row.xpath("./td[1]//text()").extract_first().strip() nav = row.xpath("./td[2]//text()").extract_first().strip() added_nav = row.xpath("./td[3]//text()").extract_first().strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item pg = response.meta['pg'] next_pg = pg + 1 next_url = response.url.replace('type_unit_p_' + str(pg), 'type_unit_p_' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name} }) yield self.request_next() <file_sep>from datetime import datetime import json from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class DatongZhengQuanSpider(GGFundNavSpider): name = 'FundNav_DatongZhengQuan' sitename = '大同证券' channel = '券商资管净值' username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'https://sc.dtsbc.com.cn:8908/servlet/json', 'form': {'funcNo': '1001997', 'page': '1', 'numPerPage': '10'}, 'headers': {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }] def parse_fund(self, response): results = json.loads(response.text)['results'] if results: result = results[0] totalPages = result['totalPages'] currentPage = result['currentPage'] funds = result['data'] if funds: for fund in funds: product_code = fund['product_code'] fund_name = fund['product_name'] self.ips.append({ 'url': 'https://sc.dtsbc.com.cn:8908/servlet/json', 'ref': response.url, 'form': {'funcNo': '1001998', 'product_code': product_code, 'page': '1', 'numPerPage': '20'}, 'headers': {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, 'ext': {'fund_name': fund_name, 'product_code': product_code} }) if int(currentPage) < int(totalPages): self.fps.append({ 'url': 'https://sc.dtsbc.com.cn:8908/servlet/json', 'form': {'funcNo': '1001997', 'page': str(int(currentPage) + 1), 'numPerPage': '10'}, 'headers': {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }) def parse_item(self, response): meta = response.meta['ext'] fund_name = meta['fund_name'] product_code = meta['product_code'] results = json.loads(response.text)['results'] if results: result = results[0] totalPages = result['totalPages'] currentPage = result['currentPage'] rows = result['data'] if rows: for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = row['nav_date'] item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') income_value_per_ten_thousand = row['profit_per_million'] if income_value_per_ten_thousand: income_value_per_ten_thousand = income_value_per_ten_thousand.replace('-', '') if income_value_per_ten_thousand != ''and ','not in income_value_per_ten_thousand: item['income_value_per_ten_thousand'] = float( income_value_per_ten_thousand) if income_value_per_ten_thousand is not None else None d7_annualized_return = row['seven_days_annual_profit'] if d7_annualized_return: d7_annualized_return = d7_annualized_return.replace('-', '') if d7_annualized_return != '': item['d7_annualized_return'] = float( d7_annualized_return) if d7_annualized_return is not None else None nav = row['nav'] if nav: nav = nav.replace('-', '') if nav != '': item['nav'] = float(nav) if nav is not None else None added_nav = row['total_nav'] if added_nav: added_nav = added_nav.replace('-', '') if added_nav != '': item['added_nav'] = float(added_nav) if added_nav is not None else None yield item if int(currentPage) < int(totalPages): self.ips.append({ 'url': 'https://sc.dtsbc.com.cn:8908/servlet/json', 'ref': response.url, 'form': {'funcNo': '1001998', 'product_code': product_code, 'page': str(int(currentPage) + 1), 'numPerPage': '20'}, 'headers': {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, 'ext': {'fund_name': fund_name, 'product_code': product_code} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-24 # Alter_date : 2018-05-30 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json import time class LianXunZhengQuanSecuritySpider(GGFundNavSpider): name = 'FundNav_LianXunZhengQuanSecurity' sitename = '联讯证券' channel = '券商PB净值列表' allowed_domains = ['192.168.3.11:8716'] def start_requests(self): ids = [('12&pageSize=100&orderCond=netValueDate+desc&name=盘通1号投资基金', '盘通1号投资基金'), ('13&pageSize=100&orderCond=netValueDate+desc&name=富锦-领航增利1期私募证券投资基金', '富锦-领航增利1期私募证券投资基金'), ('14&pageSize=100&orderCond=netValueDate+desc&name=富锦-领航增利2期私募证券投资基金', '富锦-领航增利2期私募证券投资基金'), ('15&pageSize=100&orderCond=netValueDate+desc&name=聚力财富稳健1号证券投资基金', '聚力财富稳健1号证券投资基金'), ('16&pageSize=100&orderCond=netValueDate+desc&name=明星9号私募投资基金', '明星9号私募投资基金'), ('17&pageSize=100&orderCond=netValueDate+desc&name=弘达资本盈东一号基金', '弘达资本盈东一号基金'), ('18&pageSize=100&orderCond=netValueDate+desc&name=恒大普惠证券投资基金二号', '恒大普惠证券投资基金二号'), ('19&pageSize=100&orderCond=netValueDate+desc&name=(已清盘)大兆新价值发现1号私募证券投资基金', '(已清盘)大兆新价值发现1号私募证券投资基金'), ('19&pageSize=100&orderCond=netValueDate+desc&name=大兆新价值发现1号私募证券投资基金', '大兆新价值发现1号私募证券投资基金'), ('20&pageSize=100&orderCond=netValueDate+desc&name=万喜稳盈一号', '万喜稳盈一号'), ('20&pageSize=100&orderCond=netValueDate+desc&name=万喜稳赢一号', '万喜稳赢一号'), ('21&pageSize=100&orderCond=netValueDate+desc&name=数金赤壁量化对冲私募证券投资基金', '数金赤壁量化对冲私募证券投资基金'), ('22&pageSize=100&orderCond=netValueDate+desc&name=天信俊霖1期基金', '天信俊霖1期基金'), ('23&pageSize=100&orderCond=netValueDate+desc&name=丹阳资本新三板2号定增基金', '丹阳资本新三板2号定增基金'), ('24&pageSize=100&orderCond=netValueDate+desc&name=钡镭永进私募证券投资基金', '钡镭永进私募证券投资基金'), ('25&pageSize=100&orderCond=netValueDate+desc&name=盛为联赢1号私募证券投资基金', '盛为联赢1号私募证券投资基金'), ('26&pageSize=100&orderCond=netValueDate+desc&name=真鑫如意二期证券投资基金', '真鑫如意二期证券投资基金'), ('27&pageSize=100&orderCond=netValueDate+desc&name=天运证券投资一号基金', '天运证券投资一号基金'), ('28&pageSize=100&orderCond=netValueDate+desc&name=明星11号私募投资基金', '明星11号私募投资基金'), ('29&pageSize=100&orderCond=netValueDate+desc&name=明星10号私募投资基金', '明星10号私募投资基金'), ('30&pageSize=100&orderCond=netValueDate+desc&name=恒裕满堂一号私募基金', '恒裕满堂一号私募基金'), ('31&pageSize=100&orderCond=netValueDate+desc&name=吉石创盈私募证券投资基金', '吉石创盈私募证券投资基金'), ('32&pageSize=100&orderCond=netValueDate+desc&name=华诺2号私募股权投资基金', '华诺2号私募股权投资基金'), ('33&pageSize=100&orderCond=netValueDate+desc&name=翊善致远一号私募基金', '翊善致远一号私募基金'), ('34&pageSize=100&orderCond=netValueDate+desc&name=千安二号平衡型证券投资私募基金', '千安二号平衡型证券投资私募基金'), ('35&pageSize=100&orderCond=netValueDate+desc&name=汉唐1号私募基金', '汉唐1号私募基金'), ('36&pageSize=100&orderCond=netValueDate+desc&name=深圳众享财富1号私募基金', '深圳众享财富1号私募基金')] for id in ids: self.ips.append({ 'url': 'http://192.168.3.11:8716/lxzq-info/api/data/list.action?requestId=o17miub1ej2nlhBjTskhLaMkhNgy8XV9&clientId=100001&table=trusteeship_netValue&mainId=' + id[0], 'ref': 'https://mall.lczq.com/servlet/', 'ext': {'fund_name': id[1]} }) urls = [( '43&starttime=&endtime=&page=0&size=20&name=%C3%96%C3%8A%C3%91%C2%BA%C2%B1%C2%A61%C2%BA%C3%85%C3%93%C3%85%C3%8F%C3%88%C2%BC%C2%B6A1', '质押宝1号优先级A1'), ( '29&starttime=&endtime=&page=0&size=20&name=%C3%8C%C3%AC%C3%90%C3%87%C3%97%C3%8A%C2%B1%C2%BE1%C2%BA%C3%85', '天星资本1号'), ('58&starttime=&endtime=&page=0&size=20&name=%C3%81%C2%AA%C2%B0%C2%B28%C2%BA%C3%85', '联安8号'), ('27&starttime=&endtime=&page=0&size=20&name=%C2%BC%C3%9B%C3%96%C2%B57%C2%BA%C3%85', '价值7号'), ('63&starttime=&endtime=&page=0&size=20&name=%C3%97%C3%B0%C2%BB%C2%AA5%C2%BA%C3%85', '尊华5号'), ('38&starttime=&endtime=&page=0&size=20&name=%C2%BB%C3%9D%C2%B8%C2%BB1%C2%BA%C3%85', '惠富1号'), ( '46&starttime=&endtime=&page=0&size=20&name=%C3%96%C3%8A%C3%91%C2%BA%C2%B1%C2%A61%C2%BA%C3%85%C2%B4%C3%8E%C2%BC%C2%B6B', '质押宝1号次级B'), ('28&starttime=&endtime=&page=0&size=20&name=%C2%BC%C3%9B%C3%96%C2%B59%C2%BA%C3%85', '价值9号'), ( '45&starttime=&endtime=&page=0&size=20&name=%C3%96%C3%8A%C3%91%C2%BA%C2%B1%C2%A61%C2%BA%C3%85%C3%93%C3%85%C3%8F%C3%88%C2%BC%C2%B6A2', '质押宝1号优先级A2'), ( '30&starttime=&endtime=&page=0&size=20&name=%C3%8C%C3%AC%C3%90%C3%87%C3%97%C3%8A%C2%B1%C2%BE2%C2%BA%C3%85', '天星资本2号'), ('57&starttime=&endtime=&page=0&size=20&name=%C3%97%C3%B0%C3%8F%C3%AD7%C2%BA%C3%85', '尊享7号'), ('39&starttime=&endtime=&page=0&size=20&name=%C3%94%C3%82%C3%94%C3%82%C3%93%C2%AF1%C2%BA%C3%85', '月月盈1号'), ('55&starttime=&endtime=&page=0&size=20&name=%C3%81%C2%AA%C3%93%C2%AE2%C2%BA%C3%85', '联赢2号'), ('25&starttime=&endtime=&page=0&size=20&name=%C3%88%C3%BD%C2%B0%C3%A5%C2%BB%C3%A31%C2%BA%C3%85', '三板汇1号'), ('54&starttime=&endtime=&page=0&size=20&name=%C3%97%C3%B0%C3%8F%C3%AD5%C2%BA%C3%85', '尊享5号'), ('56&starttime=&endtime=&page=0&size=20&name=%C3%81%C2%AA%C2%B0%C2%B27%C2%BA%C3%85', '联安7号'), ( '15&starttime=&endtime=&page=0&size=20&name=%C2%BB%C3%9D%C2%B0%C2%B21%C2%BA%C3%85%C3%93%C3%85%C3%8F%C3%88%C2%BC%C2%B6', '惠安1号优先级'), ('42&starttime=&endtime=&page=0&size=20&name=%C3%81%C2%AA%C2%B0%C2%B26%C2%BA%C3%85', '联安6号'), ( '33&starttime=&endtime=&page=0&size=20&name=%C3%8C%C3%AC%C3%90%C3%87%C3%97%C3%8A%C2%B1%C2%BE3%C2%BA%C3%85', '天星资本3号'), ( '41&starttime=&endtime=&page=0&size=20&name=%C3%81%C2%AA%C3%93%C2%AE1%C2%BA%C3%85%C2%B4%C3%8E%C2%BC%C2%B6', '联赢1号次级'), ('59&starttime=&endtime=&page=0&size=20&name=%C3%97%C3%B0%C2%BB%C2%AA1%C2%BA%C3%85', '尊华1号'), ( '16&starttime=&endtime=&page=0&size=20&name=%C2%BB%C3%9D%C2%B0%C2%B21%C2%BA%C3%85%C2%B4%C3%8E%C2%BC%C2%B6', '惠安1号次级'), ( '40&starttime=&endtime=&page=0&size=20&name=%C3%81%C2%AA%C3%93%C2%AE1%C2%BA%C3%85%C3%93%C3%85%C3%8F%C3%88%C2%BC%C2%B6', '联赢1号优先级'), ( '47&starttime=&endtime=&page=0&size=20&name=%C3%96%C3%8A%C3%91%C2%BA%C2%B1%C2%A61%C2%BA%C3%85%C3%93%C3%85%C3%8F%C3%88%C2%BC%C2%B6A3', '质押宝1号优先级A3'), ( '19&starttime=&endtime=&page=0&size=20&name=%C3%8C%C3%AC%C3%8C%C3%AC%C3%80%C3%BB1%C2%BA%C3%85', '天天利1号'), ('52&starttime=&endtime=&page=0&size=20&name=%C3%97%C3%B0%C3%8F%C3%AD1%C2%BA%C3%85', '尊享1号'), ('62&starttime=&endtime=&page=0&size=20&name=%C3%97%C3%B0%C3%8F%C3%AD9%C2%BA%C3%85', '尊享9号'), ('1&starttime=&endtime=&page=0&size=20&name=%C3%8F%C3%96%C2%BD%C3%B0%C2%BB%C3%9D', '现金惠'), ('53&starttime=&endtime=&page=0&size=20&name=%C3%97%C3%B0%C3%8F%C3%AD3%C2%BA%C3%85', '尊享3号')] for url in urls: self.ips.append({ 'url': 'http://www.lxzq.com.cn/api/financials/netannouncement/page?detailid=' + url[0], 'ref': 'https://mall.lczq.com/servlet/', 'ext': {'fund_name': url[1]} }) yield self.request_next() def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] row_info = json.loads(response.text) if '192.168.127.12' in response.url: rows = row_info['result'] else: rows = row_info['get_response']['netAnnouncements']['items'] for row in rows: statistic_date = row['netValueDate'] nav = row['netValue'] added_nav = row['totalNetValue'] item = GGFundNavItem() item['sitename'] = self.sitename item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None if '192.168.127.12' in response.url: item['channel'] = self.channel item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') else: item['channel'] = '券商资管净值' item['statistic_date'] = datetime.strptime( time.strftime("%Y-%m-%d", time.localtime(int(statistic_date) / 1000)), '%Y-%m-%d') yield item <file_sep>from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ShenzhenyouliSpider(GGFundNavSpider): name = 'FundNav_Shenzhenyouli' sitename = '深圳友利基金' channel = '投资顾问' username = 'ZYYXSM' password = '<PASSWORD>' cookies = 'ASP.NET_SessionId=40voc455ixlpweinl4r1y445; WHIR_USERINFOR=whir_mem_member_pid=189&membertype=&loginname=ZYYXSM&password=<PASSWORD>&realname=&sex=&mobile=13916427906&email=yuangh%40go-goal.com&address=&integral=100&accountstate=&typeid=1&subjectid=0&state=-1&sort=&isdel=False&createdate=2018-5-14+11%3a37%3a33&createuser=&updateuser=&updatedate=2018-5-14+11%3a37%3a33&nickname=&brithdate=&takename=&takeaddress=&takeregion=&taketel=&takepostcode=&takeemail=&randomnum=&codes=&activatecode=xkfy&typeofcertificate=1417&purchasestatus=1&customertype=1&clientsname=%e9%83%91%e7%9b%8a%e6%98%8e&idnumber=350402197902120017' fps = [{ 'url': 'http://www.youlifund.com/cpjz/list_57.aspx?itemid=207' }] def parse_fund(self, response): urls = response.xpath('//ul[@class="ul"]/li') for url in urls: href = url.xpath('./a/@href').extract_first() myurl = urljoin(get_base_url(response), href) fund_name = url.xpath('./a/text()').extract_first() self.ips.append({ 'url': myurl, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] fund_names = ext['fund_name'] rows = response.xpath('//table[@id="txt"]/tr') for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_names statistic_date = row.xpath("./td[3]/text()").re_first('\d+-\d+-\d+') item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None nav = row.xpath("./td[4]/text()").extract_first() item['nav'] = float(nav) if nav else None added_nav = row.xpath("./td[5]/text()").extract_first() item['added_nav'] = float(added_nav) if added_nav else None yield item <file_sep> from scrapy import cmdline # cmdline.execute(['scrapy', 'crawl', 'FundNav_JinguTrust', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_GuangdaBank', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_WuhanWeixinFund', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_TianhesichuangInvset', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_XrzFund', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_BaoyinCyInvset', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_XZeastmoney', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_XinPuAsset', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_BotongInvset', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_HongdaoInvset', '-a', 'jobId=0L']) cmdline.execute(['scrapy', 'crawl', 'FundNav_BoHaiTrust', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_MingxiZichan', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_SdictkTrust', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_Fotic', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_ZhenxinZichan', '-a', 'jobId=0L']) # cmdline.execute(['scrapy', 'crawl', 'FundNav_ZhejiangBkxtz', '-a', 'jobId=0L']) <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-17 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class ZFundsInvestSpider(GGFundNavSpider): name = 'FundNav_ZFundsInvest' sitename = '深圳知方石投资' channel = '投顾净值' allowed_domains = ['www.zfunds.com.cn'] start_urls = ['http://www.zfunds.com.cn/plus/list.php?tid=82'] username = '18601692933' password = '<PASSWORD>' cookies = 'PHPSESSID=d9l1n7atcdqncabgjl5oj65sh1; DedeUserID=31; DedeUserID__ckMd5=882ba998b483692b; DedeLoginTime=1526520012; DedeLoginTime__ckMd5=d90bf43eb449b42d; layerPopup2=hide' fps = [{'url': 'http://www.zfunds.com.cn/plus/list.php?tid=82'}] def parse_fund(self, response): fund_list = response.xpath('//div[@class="bggg"]/li/a/@href').extract() for key in fund_list: fund_url = urljoin('http://www.zfunds.com.cn', key) self.ips.append({ 'url': fund_url, 'ref': response.url }) def parse_item(self, response): fund_info = response.xpath('//div[@class="gundong2"]/ul/div[@class="bb"]/div') for row in fund_info: row_info = row.xpath('div/text()').extract() statistic_date = row_info[1].strip() nav = row_info[2] added_nav = row_info[3] if response.url == 'http://www.zfunds.com.cn/plus/list.php?tid=88': fund_name = '前海开源知方石1号' else: fund_name = row_info[0] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if added_nav else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class AnHuiXiangHaiAssetNoticeSpider(GGFundNoticeSpider): name = 'FundNotice_AnHuiXiangHaiAssetNotice' sitename = '安徽翔海资产' entry = 'http://www.xianghaizg.com/' ips = [{ 'url': 'http://www.xianghaizg.com/a/chanpinjingzhi/shouyigonggao/', }] def parse_item(self, response): title = response.xpath('//div[@class="picnews"]/div[1]/span/strong/span/text()').extract_first() url = response.url item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title publish_time = datetime.strptime('2017-01-26', '%Y-%m-%d') item['publish_time'] = publish_time yield item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class YiHuInvestSpider(GGFundNavSpider): name = 'FundNav_YiHuInvest' sitename = '翼虎投资' channel = '投顾净值' username = '15538536932' password = '<PASSWORD>' cookies = 'PHPSESSID=0j0t74bfgft5vlg2pvam4bos14; username=25e9Bug0%2B4rNbzBCso4RWn3Z0EOi%2Fpo41884IVmms%2B0XvwQWvecC0Q; lastlogintime=6992h88Sqso4AzzBqaQpTpWrQBSOqT8DKcjvllCD084ZCQDsRpXO; lastloginip=3e3aTmXzbSxDfFmlwW54AGgXag4YyGlnQZzu8cmSk8aZcKAG8VTyZEAT' fps = [ {'url': 'http://www.szyihu.com/product.php?cid=51', 'ext': {'type': '1'}} ] def parse_fund(self, response): funds = response.xpath( '/html/body/div[4]/div[2]//div[@class="tab_main"]//div/table[1]//tr[position()>1]/td[1]/a') for fund in funds: url = fund.xpath('./@href').extract_first() fund_name = fund.xpath('./text()').extract_first() fund_name = fund_name.strip() id = re.search(r'id=(\d+)', url).group(1) url = 'http://www.szyihu.com/show.php?c=show&id=' + id self.ips.append({ 'url': url + '&page=1', 'ref': response.url, 'ext': {'fund_name': fund_name, 'page': '1', 'url': url} }) def parse_item(self, response): rows = response.xpath('//tr') ext = response.meta['ext'] fund_name = ext['fund_name'] url = ext['url'] next_page = response.xpath('/html/body/div/a[text()="下一页"]/@href').re_first(r'&page=(\d+)') for row in rows[1:]: fund_date = row.xpath('./td[4]/text()').extract_first() nav = row.xpath('./td[1]/text()').extract_first() added_nav = row.xpath('./td[2]/text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name try: item['statistic_date'] = datetime.strptime(fund_date, '%Y/%m/%d') except ValueError: continue item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None yield item if next_page: self.ips.append({ 'url': url + '&page=' + str(next_page), 'ref': response.url, 'ext': {'fund_name': fund_name, 'url': url} }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class YuanShiAssetSpider(GGFundNoticeSpider): name = 'FundNotice_YuanShiAsset' sitename = '源实资产' entry = 'http://www.jvam.com.cn' ips = [ { 'url': 'http://www.jvam.com.cn/news/notice?pageCurrent=1', 'ref': 'http://www.jvam.com.cn', 'ext': {'page': '1'} } ] def parse_item(self, response): ext = response.meta['ext'] page = int(ext['page']) rows = response.xpath('//*[@id="body_content"]//div[@class="about_div cls"]/div[2]/div/div') if len(rows) >= 5: self.ips.append({'url': 'http://www.jvam.com.cn/news/notice?pageCurrent='+str(page+1), 'ref': response.url, 'ext': {'page': str(page+1)}}) for notice in rows: href = notice.xpath('./a/@href').extract_first().strip() title = notice.xpath('./a/text()').extract_first().strip() publish_time = notice.xpath('./span/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = self.entry + href item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class PuYuanZiChanInvestSpider(GGFundNavSpider): name = 'FundNav_PuYuanZiChanInvest' sitename = '璞远资产' channel = '投顾净值' allowed_domains = ['www.capnext.cn'] fps = [{'url': 'http://www.capnext.cn/product'}] def parse_fund(self, response): fund_urls = response.xpath("//div[2]//tr//@href").extract() for fund_url in fund_urls: self.ips.append({ 'url': 'http://www.capnext.cn' + fund_url, 'ref': response.url, }) def parse_item(self, response): categories = re.findall('categories: \[(.*?)\]', response.text)[0] nav_info = re.findall('data:\[(.*?)\]', response.text)[0] statistic_dates = categories.split(',') navs = nav_info.split(',') fund_name = response.xpath("//h1[@class='articleh1']//text()").extract_first() for row in zip(statistic_dates, navs): statistic_date = row[0].replace("'", "") nav = row[1] added_nav = row[1] if statistic_date: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-14 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class TianFengSecuritySpider(GGFundNavSpider): name = 'FundNav_TianFengSecurity' sitename = '天风证券' channel = '券商资管净值' fps = [{ 'url': 'http://www.tfzq.com/business/fund.html?sale=0&page=1', }] def parse_fund(self, response): # self.ips.append({'url': 'http://www.tfzq.com/product/jingzhi.html?p_id=18'}) href_list = response.css('ul.search_result_ul a::attr(href)').extract() title_list = response.css('ul.search_result_ul li:first-child::attr(title)').extract() next_href = response.css('li.next a::attr(href)').extract_first() if next_href not in response.url: # 下一页链接最大289页始终能取到,所以做个判断 self.fps.append({ 'url': 'http://www.tfzq.com' + next_href, 'ref': response.url, }) for h, t in zip(href_list, title_list): self.ips.append({ 'url': 'http://www.tfzq.com' + h, 'ref': response.url, 'ext': {'fund_name': t} }) def parse_item(self, response): if 'fundDetail' in response.url: dt_list = re.findall('x_data.*\[(.*)\];.*var series_data', response.text, re.DOTALL)[0].split(',') nav_list = re.findall('var series_data.*"data":\[(.*)\]\},\{', response.text, re.DOTALL)[0].split(',') add_nav_list = re.findall('var series_data.*\},\{.*"data":\[(.*)\]\}\];', response.text, re.DOTALL)[ 0].split(',') for date, nav, add_nav in zip(dt_list, nav_list, add_nav_list): item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = response.meta['ext']['fund_name'] item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav.replace('"', '')) if nav else None item['added_nav'] = float(add_nav.replace('"', '')) if add_nav else None item['statistic_date'] = datetime.strptime(date.replace('"', ''), '%Y-%m-%d') if date else None yield item if '?p_id=18' in response.url: table = response.css('table.table_worth tr')[1:] # date = table.xpath('//tr/td[1]/text()').extract()[1:] for r in table: date = r.xpath('td[1]/text()').extract_first() # 点金1期 fund_name = '点金1期' nav = r.xpath('td[2]/text()').extract_first() add_nav = r.xpath('td[3]/text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav) if nav else None item['added_nav'] = float(add_nav) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item # 点金1期A级 fund_name = '点金1期A级' nav_a = r.xpath('td[4]/text()').extract_first() add_nav_a = r.xpath('td[5]/text()').extract_first() if nav_a is not None or add_nav_a is not None: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav_a) if nav else None item['added_nav'] = float(add_nav_a) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item # 点金1期B级 fund_name = '点金1期B级' nav_b = r.xpath('td[6]/text()').extract_first() add_nav_b = r.xpath('td[7]/text()').extract_first() nav2_b = r.xpath('td[8]/text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav_b) if nav_b else None item['added_nav'] = float(add_nav_b) if add_nav_b else None item['nav_2'] = float(nav2_b) if nav2_b else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url import re class ZhongLueInvestSpider(GGFundNavSpider): name = 'FundNav_ZhongLueInvest' sitename = '厦门中略投资管理有限公司' channel = '投顾净值' fps = [{ 'url': 'http://www.zhongluefund.com/products.aspx?productsCateID=78&products_Id=78&CateId=78&ViewCateID=78', 'ref': 'http://www.zhongluefund.com/' }] def parse_fund(self, response): funds = response.xpath('//div[@class="menu_1"]/a') for fund in funds: id = fund.xpath("./@href").extract_first() fund_name = fund.xpath("./text()").extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), id), 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath('//div[@class="w100"]/table/tbody/tr') fund_name = response.meta['ext']['fund_name'] for row in rows[1:]: statistic_date = row.xpath('normalize-space(./td[1]/text())').extract_first() statistic_date = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row.xpath('normalize-space(./td[2]/text())').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = statistic_date item['nav'] = float(nav) if nav is not None else None yield item dates = re.search('categories:\s*\[([^\]]+)\]\s*\},', response.text).group(1) dates = re.findall('\d+-\d+-\d+', dates) added_navs = re.search("name:\s*'累计净值',\s*data:\s*\[([^\]]+)\]", response.text).group(1) added_navs = re.findall('[0-9.]+', added_navs) for date, added_nav in zip(dates, added_navs): item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = date item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') added_nav = added_nav item['added_nav'] = float(added_nav) if added_nav is not None else None yield item<file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import json class ZhongXinStockSpider(GGFundNoticeSpider): name = 'FundNotice_ZhongXinStock' sitename = '中信证券' entry = 'http://www.cs.ecitic.com/' allowed_domains = ['www.eagle-fund.com/'] ips = [{'url': 'http://www.cs.ecitic.com/finance/dynamicInfor.jsp?notifyType=_product_report&type=4', 'ext': {'report_type': '1'}}] lps = [{'url': 'http://www.cs.ecitic.com/productInfo.do?method=getProduct', 'form': {'type': '1'}}] def parse_list(self, response): funds = json.loads(response.text) if funds: funds = funds['list'] base_url1 = 'http://www.cs.ecitic.com/finance/prodListIframe.jsp?whichCat=_product_report&pageno=1&product_id=' base_url2 = 'http://www.cs.ecitic.com/finance/prodListIframe.jsp?whichCat=_periodical_report&product_id=' for fund in funds: fund_id = fund['productCode'] url1 = base_url1 + str(fund_id) url2 = base_url2 + str(fund_id) self.ips.append({'url': url1, 'ref':response.url, 'ext': {'report_type': '2'}}) self.ips.append({'url': url2, 'ref': response.url, 'ext': {'report_type': '2'}}) def parse_item(self, response): ext = response.meta['ext'] report_type = int(ext['report_type']) if report_type == 1: rows = response.xpath('/html/body/div[2]/div[2]//div[@class="rightdiv_n"]/ul/li') next_url = response.xpath('//*[@id="page"]/div[2]/ul/a[last()]/@href').extract_first() else: rows = response.xpath('//li') next_url = response.xpath('//*[@id="page"]//a[text()="下一页"]/@href').extract_first() for row in rows: url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./a//text()').extract_first().strip() publish_time = row.xpath('./span/text()').extract_first() publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item if next_url and next_url != 'javascript:void(0);': next_url = urljoin(get_base_url(response), next_url) self.ips.append({ 'url': next_url, 'ref': response.url, 'ext': {'report_type': str(report_type)} }) <file_sep>from scrapy import cmdline #cmdline.execute(['scrapy', 'crawl', 'FundNav_AnXinStock', '-a', 'jobId=0L']) # 安信证券 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_DiyichuangyeQiHuo', '-a', 'jobId=0L']) # 第一创业期货 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ZhongLiangTrust', '-a', 'jobId=0L']) # 中粮信托 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ZunDaoAsset', '-a', 'jobId=0L']) #尊道资产 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YuanCeAsset', '-a', 'jobId=0L']) #远策投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_XiNanFuture', '-a', 'jobId=0L']) #西南期货 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_XiYuInvest', '-a', 'jobId=0L']) #西域投资 cmdline.execute(['scrapy', 'crawl', 'FundNav_YuanXinYongFengFund', '-a', 'jobId=0L']) #圆信永丰基金 <file_sep># -*- coding: utf-8 -*- from urllib.parse import urljoin from datetime import datetime from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class ZhongYinGuoJiSpider(GGFundNoticeSpider): name = 'FundNotice_ZhongYinGuoJi' sitename = '中银国际' entry = 'http://www.bocichina.com/boci/asset/mfinancing/productIntro.jsp?productCode=A80001&forthMenu=qtcd_asset_jhlc_one_cpjj&secondMenu=qtcd_asset_jhlc' lps = [ { 'url': 'http://www.bocichina.com/boci/asset/mfinancing/productIntro.jsp?productCode=A80001&forthMenu=qtcd_asset_jhlc_one_cpjj&secondMenu=qtcd_asset_jhlc' } ] ips = [ { 'url': 'http://www.bocichina.com/boci/asset/cms/commonNewsList.jsp?productCode=A80001&whichCat=zcgl_jhlc_cpgg&state=1&showSize=20&catName=产品公告', 'pg': 1, 'ext': {'product_code': 'A80001'} } ] def parse_list(self, response): rows = response.xpath('//table[@class="border1"]/tr/td/a')[1:] for row in rows: product_code = row.xpath('./@onclick').re_first('productCode=([^/]+)\', \'q') self.ips.append({ 'url': 'http://www.bocichina.com/boci/asset/cms/commonNewsList.jsp?productCode={0}&whichCat=zcgl_jhlc_cpgg&state=1&showSize=20&catName=产品公告'.format(product_code), 'ref': response.url, 'pg': 1, 'ext': {'product_code': product_code} }) def parse_item(self, response): ext = response.meta['ext'] product_code = ext['product_code'] rows = response.xpath('//body/table[1]/tr') if rows: for row in rows: title = row.xpath('./td[1]/a/text()').re_first('・([^/]+)') url = row.xpath('./td[1]/a/@href').extract_first() url = urljoin(get_base_url(response), url) publish_time = row.xpath('./td[2]/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = url item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item count = response.xpath('//td[@class="float_left"]/a')[-1].xpath('./@href').re_first('totalCount=([\d]+)') if count is not None: pg = response.meta['pg'] + 1 tp = int(response.xpath('//td[@class="float_left"]/a')[-1].xpath('./@href').re_first('pageno=([\d]+)')) if pg <= tp: self.ips.append({ 'url': 'http://www.bocichina.com/boci/asset/cms/commonNewsList.jsp?state=1&whichCat=zcgl_jhlc_cpgg&productCode={0}&totalCount={1}&pageShowSize=20&pageno={2}'.format(product_code, count, pg), 'ref': response.url, 'pg': pg, 'ext': {'product_code': product_code, 'count': count} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 王卓诚 # Create_date : 2018-05-15 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin class JinBaiRongInvestSpider(GGFundNavSpider): name = 'FundNav_JinBaiRongInvest' sitename = '金百镕投资' channel = '投顾净值' allowed_domains = ['www.gblcapital.com'] username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'http://www.gblcapital.com/index.php/product' }] def parse_fund(self, response): arul = response.xpath('//div[@class="left_side"]/ul/li') for uu in arul: pname = uu.xpath('a/text()').extract_first() pname = pname.replace('- ', '') url = uu.xpath('a/@href').extract_first() url = urljoin(get_base_url(response), url) self.ips.append({ 'url': url, 'ref': response.url, 'ext': pname }) def parse_item(self, response): fund_name = response.meta['ext'] rows = response.xpath('//div[@id="fadecon"]/div[2]/table//table/tr')[1:] for k, row in enumerate(rows): statistic_date = row.xpath("./td[2]/text()").extract_first() nav = row.xpath("./td[3]/text()").extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep>import json from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import time import re class ZhongXinStockNavSpider(GGFundNavSpider): name = 'FundNav_ZhongXinStockNav' sitename = '中信证券' channel = '券商资管净值' username = '13916427906' cookies = '__jsluid=1613b909ac9687f95a1714f00e7deaa7; bdshare_firstime=1526364502593; JSESSIONID=<KEY>; token=<KEY>%<KEY>%253D%253D; code=900022; type=1; Hm_lvt_e64c4cc8f0e3ee65907bf65d0eff8496=1526364472,1526520132; Hm_lpvt_e64c4cc8f0e3ee65907bf65d0eff8496=1526539642; cursel=1' fps = [{'url': 'http://www.cs.ecitic.com/productInfo.do?method=getProduct', 'form': {'type': '1'}}, {'url': 'http://www.cs.ecitic.com/productInfo.do?method=getProduct', 'form': {'type': '2'}}, {'url': 'http://www.cs.ecitic.com/productWorth.do?method=getProLimitMinList', 'form': {'keyCode': 'pro_limit_min'}}, {'url': 'http://www.cs.ecitic.com/productInfo.do?method=getProduct', 'form': {'type': '4'}}, {'url': 'http://www.cs.ecitic.com/productInfo.do?method=getProduct', 'form': {'type': '5'}}, {'url': 'http://www.cs.ecitic.com/productInfo.do?method=getProduct', 'form': {'type': '6'}}] def parse_fund(self, response): cur_url = response.url funds = json.loads(response.text) if funds: if cur_url.count('getProLimitMinList') > 0: funds = funds['data'] for fund in funds: key_code = fund['keyCode'] url = 'http://www.cs.ecitic.com/productWorth.do?method=getQxMinByProductTypePage' form = {'keyCode:pro': 'limit_min_qtxl', 'currPageNum': '1', 'pageRowSize': '50', 'firstResult': '0', 'maxResult': '50'} self.fps.append({'url': url, 'form': form, 'ref': response.url, 'ext': {'form': form}}) else: funds = funds['list'] if cur_url.count('getQxMinByProductTypePage') > 0 and len(funds) < 50: url = 'http://www.cs.ecitic.com/productWorth.do?method=getQxMinByProductTypePage' form = response.meta['ext']['form'] cur_page = int(form['currPageNum']) form['currPageNum'] = str(cur_page + 1) form['firstResult'] = str(cur_page * 50) form['maxResult'] = str((cur_page + 1) * 50) self.fps.append({'url': url, 'form': form, 'ref': response.url, 'ext': {'form': form}}) base_url = 'http://www.cs.ecitic.com/proValue.do?method=pagePValue' for fund in funds: form = {'startTime': '', 'pCode': '', 'currPageNum': '1', 'pageRowSize': '100', 'firstResult': '0', 'maxResult': '100'} fund_name = fund['productName'] fund_id = fund['productCode'] form['pCode'] = str(fund_id) self.ips.append({'url': base_url, 'form': form, 'ref': response.url, 'ext': {'fund_name': fund_name, 'form': form}}) def parse_item(self, response): ext = response.meta['ext'] form = ext['form'] page = int(form['currPageNum']) rows = json.loads(response.text) rows = rows['list'] fund_name = ext['fund_name'] if len(rows) > 0: base_url = 'http://www.cs.ecitic.com/proValue.do?method=pagePValue' form['currPageNum'] = str(page + 1) form['firstResult'] = str(page * 100) form['maxResult'] = str((page + 1) * 100) self.ips.append( {'url': base_url, 'form': form, 'ref': response.url, 'ext': {'fund_name': fund_name, 'form': form}}) for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = row['submitDate']['time'] statistic_date = time.localtime(int(statistic_date) / 1000) statistic_date = time.strftime('%Y-%m-%d', statistic_date) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if row['mwfRate'] and row['qrnhRate']: income_value_per_ten_thousand = row['mwfRate'] income_value_per_ten_thousand = re.search('[0-9.]+', income_value_per_ten_thousand) income_value_per_ten_thousand = income_value_per_ten_thousand.group(0) if income_value_per_ten_thousand else None item['income_value_per_ten_thousand'] = float( income_value_per_ten_thousand) if income_value_per_ten_thousand else None d7_annualized_return = row['qrnhRate'] d7_annualized_return = re.search('[0-9.]+', d7_annualized_return) d7_annualized_return = d7_annualized_return.group(0)if d7_annualized_return else None item['d7_annualized_return'] = float(d7_annualized_return) if d7_annualized_return else None elif row['yearRate']: annualized_return = row['yearRate'] annualized_return = re.search('[0-9.]+', annualized_return) annualized_return = annualized_return.group(0) if annualized_return else None item['annualized_return'] = float(annualized_return) if annualized_return else None else: nav = row['dateValue'] item['nav'] = float(nav) if nav is not None else None added_nav = row['totalValue'] item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-17 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json from scrapy import Request, FormRequest class QiHuoZiGuanSpider(GGFundNavSpider): name = 'FundNav_QiHuoZiGuan' sitename = '期货资管网' channel = '期货资管净值' def start_requests(self): yield Request(url='http://www.ziguan123.com/site/login?1=1', callback=self.parse_pre_login) def parse_pre_login(self, response): csrf_token = response.xpath('//meta[@name="csrf-token"]/@content').extract_first() yield FormRequest(url='http://www.ziguan123.com/site/login', formdata={'_csrf': csrf_token, 'LoginForm[username]': '13916427906', 'LoginForm[password]': '<PASSWORD>', 'signup-button': '', 'LoginForm[rememberMe]': '1'}, meta={'handle_httpstatus_list': [302], 'Content-Type': 'application/x-www-form-urlencoded'}, callback=self.parse_pre2_login) def parse_pre2_login(self, response): yield Request(url='http://www.ziguan123.com/product/ziguan', callback=self.parse_login) def parse_login(self, response): csrf_token = response.xpath('//meta[@name="csrf-token"]/@content').extract_first() self.fps.append( {'url': 'http://www.ziguan123.com/ajax/zgdatalist', 'form': {'fundtype': '62', 'sort_name': 'Month1', 'sort_type': 'desc', 'page_index': '1', 'page_size': '100', 'companyid': ''}, 'headers': {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': csrf_token, 'Referer': 'http://www.ziguan123.com/product/ziguan'} }, ) def parse_fund(self, response): funds = json.loads(response.text)['rawdata']['data'] for fund in funds: fund_name = fund['productname'] fund_id = fund['id'] url = 'http://www.ziguan123.com/product/detail/{}'.format(fund_id) self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'fund_name': fund_name}, }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//div[@class="w300 f14"]/table/tbody/tr') for row in rows: statistic_date = row.xpath('./td[1]').re_first('\d+-\d+-\d+') nav = row.xpath('./td[2]').re_first('>\s*([0-9.]+)\s*<') added_nav = row.xpath('./td[3]').re_first('>\s*([0-9.]+)\s*<') if statistic_date is None: continue item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav)if nav is not None else None item['added_nav'] = float(added_nav)if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import json class FengLingCapitalSpider(GGFundNoticeSpider): name = 'FundNotice_FengLingCapital' sitename = '丰岭资本' entry = 'http://www.szhvc.com/' ips = [{ 'url': 'http://www.szhvc.com/api/pc/message/news/paging?tagl2=REPORTS&pageSize=3&pageNum=1&_=1527477855432', 'ref': 'http://www.szhvc.com/news/report', 'pg': 1 }] def parse_item(self, response): datas = json.loads(response.text) rows = datas['collection'] for row in rows: title = row['title'] url = '/news/detail/' + str(row['articleId']) url = urljoin(get_base_url(response), url) publish_time = row['publishTime'] publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item tp = datas['property']['pages'] cp = response.meta['pg'] if cp < tp: cp = cp+1 self.ips.append({ 'url': 'http://www.szhvc.com/api/pc/message/news/paging?tagl2=REPORTS&pageSize=3&pageNum='+str(cp)+'&_=1527477855432', 'ref': response.url, 'pg': cp }) <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class XinshidaizhengquanSecuritySpider(GGFundNavSpider): name = 'FundNav_XinshidaizhengquanSecurity' sitename = '新时代证券' channel = '券商资管净值' fps = [{ 'url': 'http://www.xsdzq.cn/cmsproduct/D23001/brief.shtml?procode=D23001&fundtype=xjgl', }] def parse_fund(self, response): urls = response.xpath( '//div[@class = "fgsgk_main"]/ul/li[@style="background:#FFFFFF;padding-left:5px;width:90%;display:none"]') for url in urls: code = url.xpath('./a/@id').extract_first() fund_name = url.xpath('./a/text()').extract_first() self.ips.append({ 'url': 'http://www.xsdzq.cn/xsdweb/xsdweb/netvalue/getNetValueListByCode.do?pageSize=1000&gotoPage=1', 'form': {'netValue.product_code': code}, 'ref': response.url, 'ext': {'fundname': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] fundname = ext['fundname'] rows = response.xpath('//table[@class="zcgl_cpjj"]//tr') rows = rows[1:-2] for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fundname statistic_date = row.xpath('./td[1]/text()').re_first('\d+-\d+-\d+') statistic_date = '20' + str(statistic_date) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None if '7日年化收益率(%)' in response.xpath('//table/tr[1]/th[2]/text()').extract_first(): d7_annualized_return = row.xpath('./td[2]').re_first('>\s*([0-9.]+)\s*<') item['d7_annualized_return'] = float( d7_annualized_return) if d7_annualized_return else None yield item else: nav = row.xpath('./td[2]/text()').extract_first() item['nav'] = float(nav) if nav else None added_nav = row.xpath('./td[3]/text()').extract_first() item['added_nav'] = float(added_nav) if added_nav else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-07 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re import json class HuaJingSecuritiesSpider(GGFundNavSpider): name = 'FundNav_HuaJingSecurities' sitename = '华菁证券资管' channel = '发行机构' fps = [{'url': 'https://am.huajingsec.com/netvalue/index.html', 'ref': 'https://am.huajingsec.com/index.html'}] def parse_fund(self, response): name = response.xpath('//div[@class="selbody1 lmenu"]/ul/li/ul//li/a//text()').extract() product_id = re.findall('<li pcode="(.*?)" pname', response.text) for name, p_id in zip(name, product_id): fund_name = name fund_id = p_id ips_url = 'https://am.huajingsec.com/common-web/chart/fundnetchart!getFundNetChartJson?fundcode=' + fund_id + '&charttype=2' self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] data = json.loads(response.text) nav = data['seriesData0'] added_nav = data['seriesData1'] statistic_date = data['xAxisData'] for nav, added_nav, statistic_date in zip(nav, added_nav, statistic_date): added_nav = float(added_nav) statistic_date = statistic_date item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin import re import json class ZhongTouStockSpider(GGFundNoticeSpider): name = 'FundNotice_ZhongTouStock' sitename = '中投证券' entry = 'http://www.china-invs.cn/d01/zcgl/index.html' cookies = 'BotMitigationCookie_1969904701684545095="548876001526977326ReMV07wqIjlG7bSU7Vrw9m2cwKM="; JSESSIONID=<KEY>' lps = [ { 'url': 'http://www.china-invs.cn/d01/zcgl/index.html#A60042_7', 'ref': 'http://www.china-invs.cn/d01/zcgl/index.html', 'ext': {'flag': 0} } ] def parse_list(self, response): flag = response.meta['ext']['flag'] if flag == 0: ids = response.xpath('//ul[@id="menu"]/li[2]/ul/li/a/@href').extract() for id in ids: id = re.findall('(A\d+|S\d+)', id)[0] self.lps.append({ 'url': 'http://www.china-invs.cn/d01/zcgl/product.jsp?id=' + id + '&li=7&textid=&tmp=0.8856078093043638', 'ref': response.url, 'ext': {'flag': 1} }) else: code = response.xpath('//script').extract_first() code = re.findall('list_report\(\\\'(\d+)', code)[0] self.ips.append({ 'url': 'http://www.china-invs.cn/supermarket/A6_Report_JSON.jsp?code=' + code + '&page=1&0.5678455961605193', 'ref': response.url, 'pg': 1, 'ext': {'code': code} }) def parse_item(self, response): datas = json.loads(response.text) for data in datas: id = data['id'] href = '/article5.html?id=' + str(id) url = urljoin(get_base_url(response), href) title = data['title'] publish_time = data['date'] item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item if len(datas) > 0: pg = response.meta['pg'] code = response.meta['ext']['code'] np = pg+1 self.ips.append({ 'url': 'http://www.china-invs.cn/supermarket/A6_Report_JSON.jsp?code=' + code + '&page=' + str(np) + '&0.5678455961605193', 'ref': response.url, 'pg': np, 'ext': {'code': code} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class PuDaoTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_PuDaoTouZiInvest' sitename = '朴道投资' channel = '投顾净值' allowed_domains = ['www.pudaofund.com'] fps = [ {'url': 'http://www.pudaofund.com/product.do'}, ] def parse_fund(self, response): fund_urls = response.xpath("//div[@class='side sidePic_pro']/ul/li[@class='unselect']") for url in fund_urls: fund_name = url.xpath('.//text()').extract_first() fund_url = url.xpath('.//@href').extract_first() self.ips.append({ 'url': 'http://www.pudaofund.com' + fund_url.replace('.do', '_netvalue.do'), 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath("//div[@class='sub2Table']//tr") fund_name = response.meta['ext']['fund_name'] for row in rows[1:]: statistic_date = row.xpath("./td[2]//text()").extract_first() nav = row.xpath("./td[3]//text()").extract_first() if nav: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class FengYiTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_FengYiTouZiInvest' sitename = '上海沣谊投资' channel = '投资顾问' allowed_domains = ['www.blossomfund.cn'] fps = [ {'url': 'http://www.blossomfund.cn/product/index'}, ] def parse_fund(self, response): fund_urls = response.xpath("//div[@class='left']//@href").extract() for fund_url in fund_urls: self.ips.append({ 'url': 'http://www.blossomfund.cn' + fund_url + '&page=1', 'ref': response.url, 'pg': 1 }) def parse_item(self, response): rows = response.xpath("//div[@class='right']//tr") for row in rows[1:]: fund_name = row.xpath("./td[1]//text()").extract_first() statistic_date = row.xpath("./td[4]//text()").extract_first() nav = row.xpath("./td[2]//text()").extract_first().replace('(', '(').split('(')[0] added_nav = row.xpath("./td[3]//text()").extract_first().replace('(', '(').split('(')[0] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name if fund_name == '沣谊一号': item['nav'] = float(nav) if nav is not None else None item['added_nav_2'] = float(added_nav) if added_nav is not None else None else: item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-02 from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class HuaAoTrustSpider(GGFundNavSpider): name = 'FundNav_HuaAoTrust' sitename = '华澳信托' channel = '信托净值' fps = [{ 'url': 'http://www.huaao-trust.com/list/705/1.shtml', 'pg': 1 }] def parse_fund(self, response): href_list = response.css('div.news_list a::attr(href)').extract() if href_list: for href in href_list: self.ips.append({ 'url': urljoin(get_base_url(response), href), 'ref': response.url }) next_pg = response.meta['pg'] + 1 self.fps.append({ 'url': 'http://www.huaao-trust.com/list/705/%s.shtml' % next_pg, 'ref': response.url, 'pg': next_pg }) def parse_item(self, response): rows = response.css('div.news_details tr') for r in rows[1:]: row = r.xpath('td//text()').extract() fund_name = row[0] fund_date = row[2] fund_nav = row[3] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y/%m/%d') item['nav'] = float(fund_nav) if fund_nav else None yield item <file_sep># coding:utf-8 # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-02 from datetime import datetime from FundNavSpiders import GGFundNavSpider from FundNavSpiders import GGFundNavItem from scrapy import Request import re class GuoXinZhengQuanNavSpider(GGFundNavSpider): name = 'FundNav_GuoXinZhengQuanNav' sitename = '国信证券' channel = '券商资管净值' allowed_domains = ['www.guosen.com.cn'] def start_requests(self): yield Request(url='http://www.guosen.com.cn/gxzq/gxyw/jhlc_xx.jsp?fundcode=931204', callback=self.parse_pre_fund) def parse_pre_fund(self, response): urls = response.xpath('//ul[@id = "navLeft_jhlcjh"]//script').extract() for url in urls: pattern = re.compile(r'<li><a id=\\"(.*?)\\" href=\\"/gxzq/gxyw(.*?)">(.*?)</a></li>') fund_code = pattern.findall(url)[0][0] self.fps.append({ 'url': 'http://www.guosen.com.cn/gxzq/gxyw/jhlc_xx.jsp?fundcode=' + fund_code, 'ext': fund_code, 'ref': response.url }) def parse_fund(self, response): pg = 1 fund_code = response.meta['ext'] fund_text = ''.join(response.xpath('//script[@type]').extract()) pattern = re.compile(r'(\d+,\d+,.*?,\d+)') fund_type = pattern.findall(fund_text)[0][-1] self.ips.append({ 'url': 'http://www.guosen.com.cn/gxzq/gxyw/content_jzList.jsp', 'form': { 'funcNo': '2000053', 'type': str(fund_type), 'fundcode': str(fund_code), 'pageIndex': str(pg), 'pageSize': '20', }, 'pg': 1, 'ext': [fund_type, fund_code] }) def parse_item(self, response): fund_code = response.meta['ext'][1] fund_type = response.meta['ext'][0] pg = response.meta['pg'] fund = response.xpath('//table//tr') # 普通净值 if fund_type == '1': for i in fund[1:]: t = i.xpath('td//text()').extract() fundname = t[1] statistic_date = t[2].replace('(分红权益登记日)', '') # 含有"美元"字样,且有'null' nav = re.findall(r'\S*', t[3])[0].replace('null', '') added_nav = re.findall(r'\S*', t[4])[0].replace('null', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fundname item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav != '' else None item['added_nav'] = float(added_nav) if added_nav != '' else None yield item # 货币净值 elif fund_type == '2': for i in fund[1:]: t = i.xpath('td//text()').extract() fundname = t[1] statistic_date = t[2] annualized_return = t[3].strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fundname item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['annualized_return'] = float(annualized_return) if annualized_return != '' else None yield item # 国信8号等..带A份额 elif fund_type == '3': for i in fund[1:]: t = i.xpath('td//text()').extract() fundname = t[0] statistic_date = t[1] nav = t[2].replace('null', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fundname item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav != '' else None yield item for i in fund[1:]: t = i.xpath('td//text()').extract() fundname = t[0] + '份额B' statistic_date = t[1] nav = t[3].replace('null', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fundname item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav != '' else None yield item # 国信久立成长1号等..带A,B份额 elif fund_type == '4': for i in fund[1:]: t = i.xpath('td//text()').extract() fundname = t[1] statistic_date = t[2] nav = t[3].replace('null', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fundname item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav != '' else None yield item for i in fund[1:]: t = i.xpath('td//text()').extract() fundname = t[1] + '份额A' statistic_date = t[2] nav = t[4].replace('null', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fundname item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav != '' else None yield item for i in fund[1:]: t = i.xpath('td//text()').extract() fundname = t[1] + '份额B' statistic_date = t[2] nav = t[5].replace('null', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fundname item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav != '' else None yield item if response.xpath('//table/tr[2]'): next_pg = int(pg) + 1 self.ips.append({ 'url': 'http://www.guosen.com.cn/gxzq/gxyw/content_jzList.jsp', 'form': { 'funcNo': '2000053', 'type': str(fund_type), 'fundcode': str(fund_code), 'pageIndex': str(next_pg), 'pageSize': '20', }, 'pg': next_pg, 'ext': [fund_type, fund_code] }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class YinLiAssetSpider(GGFundNoticeSpider): name = 'FundNotice_YinLiAsset' sitename = '银莅资产' entry = 'http://www.ylzcgl.com' cookies = 'cookie_authState=1' ips = [{'url': 'http://www.ylzcgl.com/news1.asp'}] def parse_item(self, response): next_url = response.xpath('/html/body/table[2]//div[@class="xianshi"]//a[text()="下一页"]/@href').extract_first() rows = response.xpath('/html/body/table[2]//div[@class="xianshi"]/table//tr') for row in rows: item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry title = row.xpath('./td[2]/a/text()').extract_first() url = row.xpath('./td[2]/a/@href').extract_first() url = urljoin(get_base_url(response), url) publish_time = row.xpath('./td[3]/text()').extract_first() publish_time = datetime.strptime(publish_time, '%Y/%m/%d') item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item if next_url: next_url = urljoin(get_base_url(response), next_url) self.ips.append({'url': next_url, 'ref': response.url}) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class ZhuoYeInvestSpider(GGFundNavSpider): name = 'FundNav_ZhuoYeInvest' sitename = '卓晔投资' channel = '投资顾问' fps = [{ 'url': 'http://www.zhuoyetz.com/pr.jsp', 'ref': 'http://www.zhuoyetz.com/' }] def parse_fund(self, response): funds = response.xpath('//a[@class="fk-productName"]') for fund in funds: id = fund.xpath("./@href").extract_first() fund_name = fund.xpath("./text()").extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), id), 'ref': response.url, 'ext': {'fund_name': fund_name} }) # next_url = response.xpath("//a[contains(text(), '下一页')]/@href").extract_first() # if next_url is not None and next_url != response.url: # self.ips.append({ # 'url': next_url, # 'ref': response.url, # 'ext': {'fund_name': fund_name} # }) def parse_item(self, response): # 历史净值 rows = response.xpath('//*[@id="detailedDesc"]/div/table[2]/tbody/tr') if len(rows) == 0: # 最新净值 item = GGFundNavItem() fund_name = response.meta['ext']['fund_name'] datas = response.xpath('//td[@class="propValue g_minor"]/span/text()').extract() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(datas[3], '%Y-%m-%d') item['nav'] = float(datas[2]) if datas[2] is not None else None item['added_nav'] = float(datas[1]) if datas[1] is not None else None yield item else: fund_name = response.xpath('//*[@id="detailedDesc"]/div/table[1]/tbody/tr[1]/td[2]/text()').extract_first() for row in rows[1:]: statistic_date = row.xpath('normalize-space(./td[1]/text())').extract_first() sign = statistic_date[4] statistic_date = datetime.strptime(statistic_date, '%Y' + sign + '%m' + sign + '%d') nav = row.xpath('normalize-space(./td[2]/text())').extract_first() added_nav = row.xpath('normalize-space(./td[3]/text())').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = statistic_date item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-22 # 参考配置文档分类 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class ShangHaiTrust2Spider(GGFundNavSpider): name = 'FundNav_ShangHaiTrust2' sitename = '上海信托2' channel = '信托净值' allowed_domains = ['www.shanghaitrust.com'] fps = [{ 'url': 'http://www.shanghaitrust.com/products/red/index.html' }] def parse_fund(self, response): pg = 1 nowtime = datetime.now().strftime('%Y-%m-%d') funds = response.xpath('//div[@class ="information_news_list"]//@href').extract() fund_names = response.xpath('//div[@class ="information_news_list"]//@title').extract() for fund_name, fund in zip(fund_names, funds): fund_code = fund.split('/')[3] self.ips.append({ 'url': 'http://www.shanghaitrust.com/chart-web/chart/fundnettable?pages=1-15&fundcode=%s&from=2000-01-01&to=%s' % ( fund_code, nowtime), 'ref': response.url, 'ext': [fund_name, fund_code], 'pg': '1' }) def parse_item(self, response): fund_name = response.meta['ext'][0] fund_code = response.meta['ext'][1] pg = response.meta['pg'] f_list = response.xpath('//table[@id="dataTable"]//tr') for i in f_list[1:]: t = i.xpath('td//text()').extract() statistic_date = t[0] nav = ''.join(t[1].split()) added_nav = ''.join(t[2].split()) item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None yield item max_pg = re.findall('\d+', response.xpath('//td//a[contains(@href,"topage")]//@href').extract_first())[0] nowtime = datetime.now().strftime('%Y-%m-%d') if int(pg) < int(max_pg): next_pg = int(pg) + 1 self.ips.append({ 'url': 'http://www.shanghaitrust.com/chart-web/chart/fundnettable?fundcode=%s&from=2000-01-01&to=%s&pages=%d-15' % ( fund_code, nowtime, next_pg), 'ref': response.url, 'ext': [fund_name, fund_code], 'pg': next_pg }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-10 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class GuangZhouQiHuoFuturesSpider(GGFundNavSpider): name = 'FundNav_GuangZhouQiHuoFutures' sitename = '广州期货' channel = '期货净值' allowed_domains = ['www.gzf2010.com.cn'] username = 'ZYYXSM' password = '<PASSWORD>' cookies = 'UM_distinctid=162dcfa8c9c10d-0fd046460da28a-3c604504-15f900-162dcfa8c9d40a; yunsuo_session_verify=f5fe86d4185ef28b5bea1a33951efe74; ASP.NET_SessionId=fujnrtj2ec1tdk55iykd2n55; Bs_SessionID=201805100937164687; CNZZDATA1254886268=1712538512-1524123062-%7C1525912206; UserInfo=13352' fps = [ {'url': 'https://www.gzf2010.com.cn/product.aspx?c=01&page=1', 'pg': 1}, {'url': 'https://www.gzf2010.com.cn/product.aspx?c=02&page=1', 'pg': 1}, ] def parse_fund(self, response): fund_urls = response.xpath("//div[@class='r right right_all']/div[@class='box']/p[@class='p1']//a") if fund_urls: for url in fund_urls: fund_url = url.xpath('./@href').extract_first() fund_name = url.xpath('./text()').extract_first() self.ips.append({ 'url': 'https://www.gzf2010.com.cn/table.aspx?' + fund_url.replace('Showpro.aspx?', '') + '&page=1', 'ref': response.url, 'ext': {'fund_name': fund_name}, 'pg': 1 }) pg = response.meta['pg'] next_pg = int(pg) + 1 next_url = response.url.replace('&page=' + str(pg), '&page=' + str(next_pg)) self.fps.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath("//tr") for row in rows[1:]: statistic_date = row.xpath("./td[1]//text()").extract_first() nav = row.xpath("./td[2]//text()").extract_first() added_nav = row.xpath("./td[3]//text()").extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item if len(rows) > 1: pg = response.meta['pg'] next_pg = int(pg) + 1 next_url = response.url.replace('&page=' + str(pg), '&page=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name}, }) <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-04 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class MingZuZhengQuanSecuritiesSpider(GGFundNavSpider): name = 'FundNav_MingZuZhengQuanSecurities' sitename = '民族证券' channel = '券商资管净值' fps = [{ 'url': 'http://www.e5618.com/mzzq/zcgl/public/left.jsp', 'form': {'classid': '0001000100010008000400020001'} }] def parse_fund(self, response): class_id = response.css('div.zcgl_menu02 a::attr(href)').re('classid=(.*)') fund_name = response.css('div.zcgl_menu02 a::text').extract() for f_name, c_id in zip(fund_name, class_id): self.ips.append({ 'url': 'http://www.e5618.com/mzzq/zcgl/public/cpNavContent.jsp', 'form': { 'classid': c_id + '0003', 'type': '2', 'pageIndex': '1' }, 'pg': 1, 'ext': f_name }) def parse_item(self, response): fund_name = response.meta['ext'] rows = response.css('tr')[2:] col_type = response.css('tr th::text').extract() if rows: for r in rows: row = r.css('td::text').extract() date = row[0] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None if '单位净值' in col_type: item['nav'] = float(row[1]) if row[1] else None item['added_nav'] = float(row[2]) if row[2] else None elif '7日年化' in col_type: item['d7_annualized_return'] = float(row[1]) if row[1] else None item['income_value_per_ten_thousand'] = float(row[2]) if row[2] else None yield item next_pg = response.meta['pg'] + 1 meta = response.meta meta['pg'] = next_pg meta['form']['pageIndex'] = str(next_pg) self.ips.append(meta) <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-07 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest class MingShenInvestSpider(GGFundNavSpider): name = 'FundNav_MingShenInvest' sitename = '铭深资产' channel = '投资顾问' username = 'ZYYXSM' password = '<PASSWORD>' ips = [{'url': 'http://www.mindeep.cn/a/chanpinyujishu/dianxingchanpin/21.html'}] def start_requests(self): yield FormRequest(url='http://www.mindeep.cn/member/index_do.php', formdata={'person': '1', 'fmdo': 'login', 'dopost': 'login', 'gourl': '<?php if(!empty($gourl)) echo $gourl;?>', 'username': 'ZYYXSM', 'phone': '13916427906' }) def parse_item(self, response): data1 = response.css('div.ac-mid-p2 tr')[1:-2] f_name = '外贸信托-铭深1号' for td in data1: fund_list = td.xpath('./td//text()').extract() filter_info = [_.strip() for _ in fund_list if _.strip()] fund_date = filter_info[0] fund_nav = filter_info[2] fund_added_nav = filter_info[1] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = f_name item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(fund_nav) if fund_nav else None item['added_nav'] = float(fund_added_nav) if fund_added_nav else None yield item data2 = response.css('div.ac-mid-p2 tr')[-2] column1 = data2.xpath('./td[1]//text()').extract() date_col = [_.strip() for _ in column1 if _.strip()] column2 = data2.xpath('./td[2]//text()').extract() add_nav_col = [_.strip() for _ in column2 if _.strip()] column3 = data2.xpath('./td[3]//text()').extract() nav_col = [_.strip() for _ in column3 if _.strip()] for date, nav, add_nav in zip(date_col, nav_col, add_nav_col): item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = f_name item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') item['nav'] = float(nav) if nav else None item['added_nav'] = float(add_nav) if add_nav else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-17 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ShangHaiYingZhiAssetSpider(GGFundNavSpider): name = 'FundNav_ShangHaiYingZhiAsset' sitename = '上海应治资产' channel = '投资顾问' allowed_domains = ['www.zenithmacer.com'] fps = [ {'url': 'http://www.zenithmacer.com/c/l-143-0.html'}, {'url': 'http://www.zenithmacer.com/c/l-141-0.html'}, {'url': 'http://www.zenithmacer.com/c/l-138-0.html'}, ] def parse_fund(self, response): funds = response.xpath('//h2//a//@href').extract() for f_url in funds: fund_url = 'http://www.zenithmacer.com' + f_url self.ips.append({ 'url': fund_url, 'ref': response.url, }) def parse_item(self, response): funds_list = response.xpath('//table//tr') for i in funds_list[1:]: t = i.xpath('td//text()').extract() fund_name = ''.join(t[0].split()) statistic_date = ''.join(t[1].split()) nav = ''.join(t[2].split()) item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') item['nav'] = float(nav) if nav is not None else None yield item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import Request, FormRequest import json class ShiYuFundSpider(GGFundNavSpider): name = 'FundNav_ShiYuFund' sitename = '世域投资' channel = '投资顾问' username = '13916427906' verifycode = '167528' Authorization = '<KEY>' def start_requests(self): yield FormRequest( url='http://www.jdoor.cn/api/customerlogin/', method='POST', body=json.dumps({"phone": "13916427906", "verifycode": self.verifycode}), headers={ 'org': '1819b573-3e70-4adc-95f1-d8a2b8a09787', 'Content-Type': 'application/json', 'Pragma': 'no-cache', 'Accept': '*/*'}, callback=self.parse_login) def parse_login(self, response): yield Request( url='http://www.jdoor.cn/api/products/', method='GET', headers={ 'Authorization': self.Authorization, 'org': '1819b573-3e70-4adc-95f1-d8a2b8a09787', 'Content-Type': 'application/json', 'Accept': '*/*', }, callback=self.parse_fund) def parse_fund(self, response): funds = json.loads(response.text)['results'] for fund in funds: self.ips.append({ 'url': 'http://www.jdoor.cn/api/products/' + str( fund['id']) + '/comparenetvalue/all/', 'method': 'GET', 'headers': { 'Authorization': self.Authorization, 'org': '1819b573-3e70-4adc-95f1-d8a2b8a09787', 'Content-Type': 'application/json', 'Accept': '*/*', }, 'ext': {'fund_name': fund['short_name']} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] datas = json.loads(response.text)['netvalues'] for data in datas: fund_date = data['value_date'] nav = data['unit_value'] added_nav = data['total_value'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 柳美云 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class HaoEnTouZiSpider(GGFundNavSpider): name = 'FundNav_HaoEnTouZi' sitename = '昊恩投资' channel = '投资顾问' allowed_domains = ['www.hetz.com.cn'] ips = [ {'url': 'http://www.hetz.com.cn/index.asp', }, ] def parse_item(self, response): fund_names = re.findall('<OPTION VALUE="(\d+)(.*?)>(.*?)</OPTION>', response.text) for name in fund_names: fund_id = name[0] fund_name = name[2] zz = "//div[@id='d%s']//tr" % (fund_id) rows = response.xpath(zz) for row in rows[1:]: nav = row.xpath('./td[2]//text()').extract_first() statistic_date = row.xpath('./td[3]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y.%m.%d') item['nav'] = float(nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-28 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import Request, FormRequest class GuangDaFuZunSpider(GGFundNavSpider): name = 'FundNav_GuangDaFuZun' sitename = '光大富尊' channel = '投资顾问' username = '15838569960' password = '<PASSWORD>' ips = [ {'url': 'http://www.ebfortune.com/product/navlist/SE9010?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/2?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/3?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/S29403?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/SE4114?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/SE5274?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/SE5276?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/SE5749?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/SE9027?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/SK2137?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/SK2138?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/SK2139?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/TG0004?p=1', 'pg': '1'}, {'url': 'http://www.ebfortune.com/product/navlist/1?p=1', 'pg': '1'}, ] def start_requests(self): yield Request(url='http://www.ebfortune.com/login?goto=http%3A%2F%2Fwww.ebfortune.com%2Fproduct%2Fnavlist%2FSE9010%3Fp%3D1', callback=self.parse_login) def parse_login(self, response): token = response.xpath('//input[@name="puff_beetl_client_token"]/@value').extract_first() yield FormRequest(url='http://www.ebfortune.com/user/login', formdata={'certificationtype': 'A', 'certificationnum': '15838569960', 'password': '<PASSWORD>'}, headers={'Puff-ClientToken': token, 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}) def parse_item(self, response): pg = response.meta['pg'] f_list = response.xpath('//tr') for i in f_list[1:]: t = i.xpath('td//text()').extract() fund_name = t[0] statistic_date = t[1] nav = t[2] added_nav = t[3] item = GGFundNavItem() item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item if len(f_list) > 1: next_pg = int(pg) + 1 self.ips.append({ 'url': response.url.split('=')[0] + '=' + str(next_pg), 'ref': response.url, 'pg': next_pg }) <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-21 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class RongShengFundSpider(GGFundNavSpider): name = 'FundNav_RongShengFund' sitename = '融升基金' channel = '投资顾问' # 页面无法正常访问,取TRS历史链接 ips = [{'url': 'http://www.rongshengjijin.com/teamview_1433024.html?name=融升凤舞私募投资基金', 'ext': '融升凤舞私募投资基金'}, {'url': 'http://www.rongshengjijin.com/teamview_1778216.html?name=融升多策略私募投资基金', 'ext': '融升多策略私募投资基金'}, {'url': 'http://www.rongshengjijin.com/teamview_473621.html?name=融升稳健投资基金', 'ext': '融升稳健投资基金'}, {'url': 'http://www.rongshengjijin.com/teamview_713077.html?name=申万汇富威海融升一号集合资产管理计划', 'ext': '申万汇富威海融升一号集合资产管理计划'}] def parse_item(self, response): fund_name = response.meta['ext'] rows = response.xpath('//table[last()]//tr') for r in rows[1:]: dt = r.xpath('td[1]/text()').re_first('\S+') nav = r.xpath('td[2]/text()').re_first('\S+') added_nav = r.xpath('td[3]/text()').re_first('\S+') item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if added_nav else None item['statistic_date'] = datetime.strptime(dt, '%Y年%m月%d日') if dt else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-16 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ShangHaiShunYanInvestSpider(GGFundNavSpider): name = 'FundNav_ShangHaiShunYanInvest' sitename = '上海顺彦投资' channel = '投资顾问' allowed_domains = ['www.shunyanjijin.com'] ips = [{ 'url': 'http://www.shunyanjijin.com/nianshouyilv/', }] def parse_item(self, response): f_list = response.xpath('//table//tbody[@bgcolor ="#ffffff"]//tr') for i in f_list: item = GGFundNavItem() t = i.xpath('td//text()').extract() fund_name = t[0] nav = t[4] statistic_date = t[6] item['nav'] = float(nav) if nav is not None else None item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date,'%Y/%m/%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import Request class ShangHaiShiHuiAssetSpider(GGFundNavSpider): name = 'FundNav_ShangHaiShiHuiAsset' sitename = '上海拾晖资产' channel = '投资顾问' allowed_domains = ['www.shihuizc.com'] def start_requests(self): yield Request(url='http://www.shihuizc.com/index.php?ac=article&at=list&tid=8', callback=self.parse_pre_fund) def parse_pre_fund(self, response): funds_urls = response.xpath('//div[@class = "prod_divs"]//@onclick').extract() for funds_url in funds_urls: self.fps.append({ 'url': 'http://www.shihuizc.com/index.php?' + funds_url.split('?')[1], }) def parse_fund(self, response): funds = response.xpath('//ul[@class ="menu"]//li//a//@href').extract() fund_names = response.xpath('//ul[@class ="menu"]//li//a//text()').extract() for fund_name, f_url in zip(fund_names, funds): self.ips.append({ 'url': f_url, 'ref': response.url, 'ext': fund_name if '产品' not in fund_name else None }) def parse_item(self, response): fund_name = response.meta['ext'] f_list = response.xpath('//table//tr') for i in f_list[1:]: t = i.xpath('td//text()').extract() statistic_date = t[1] nav = t[2] added_nav = t[3] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None yield item <file_sep>from scrapy import cmdline #第一创业证券资管 #cmdline.execute(['scrapy', 'crawl', 'FundNav_DiyichuangyeSecuritiesManagement', '-a', 'jobId=0L']) #中粮期货 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_Zlqh', '-a', 'jobId=0L']) #盈峰资本 #cmdline.execute(['scrapy', 'crawl', 'FundNav_InforeCapital', '-a', 'jobId=0L']) #岱熹投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ShanghaidaixiInvest', '-a', 'jobId=0L']) #北京久银投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_BeijingjiuyinInvest', '-a', 'jobId=0L']) #北京朴禾投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_BeijingpuheInvest', '-a', 'jobId=0L']) #深圳盛冠达资产投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ShenzhenshengguandaInvest', '-a', 'jobId=0L']) #佑瑞持 #cmdline.execute(['scrapy', 'crawl', 'FundNav_UrichInvest', '-a', 'jobId=0L']) #国融证券 #cmdline.execute(['scrapy', 'crawl', 'FundNav_GuorongzhengquanInvest', '-a', 'jobId=0L']) #茂典资产 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_Maodian', '-a', 'jobId=0L']) #好买私募基金网 #cmdline.execute(['scrapy', 'crawl', 'FundNav_Howbuysimu', '-a', 'jobId=0L']) #中国国际金融股份有限公司 #cmdline.execute(['scrapy', 'crawl', 'FundNav_Zhongjin', '-a', 'jobId=0L']) #恒如投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HengruInvest', '-a', 'jobId=0L']) #白石资产 #cmdline.execute(['scrapy', 'crawl', 'FundNav_WhiterockAssert', '-a', 'jobId=0L']) #朱雀股权投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhuqueInvest', '-a', 'jobId=0L']) #勤远投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_QinyuanInvest', '-a', 'jobId=0L']) #深圳国投汇金资产 #cmdline.execute(['scrapy', 'crawl', 'FundNav_Guotouhuijin', '-a', 'jobId=0L']) #深圳博闻投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ShenzhenbowenInvest', '-a', 'jobId=0L']) #彩石资产 #cmdline.execute(['scrapy', 'crawl', 'FundNav_CaiShiAsset', '-a', 'jobId=0L']) #英大信托 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YingDaTrust', '-a', 'jobId=0L']) #冰剑投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_BingJianFund', '-a', 'jobId=0L']) #浙江巴克夏投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_XiaBaKeInvest', '-a', 'jobId=0L']) #华融期货 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HuaRongQiHuo', '-a', 'jobId=0L']) #宏亮投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HongLiangInvest', '-a', 'jobId=0L']) #上海乾璟投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_QianJingInvest', '-a', 'jobId=0L']) #上海平安阖鼎投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_PingAnKeDingInvest', '-a', 'jobId=0L']) #广州正闻投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_GuangzhouzhengwenInvest', '-a', 'jobId=0L']) #上海岳海资产 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ShanghaiyuehaiAsset', '-a', 'jobId=0L']) #广西北部湾资产 #cmdline.execute(['scrapy', 'crawl', 'FundNav_GuangxibeibuwangAsset', '-a', 'jobId=0L']) #翠丰基金 #cmdline.execute(['scrapy', 'crawl', 'FundNav_CuifengFund', '-a', 'jobId=0L']) #创元期货 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_Chuangyuanqihuo', '-a', 'jobId=0L']) #福能期货 #cmdline.execute(['scrapy', 'crawl', 'FundNav_Funengqihuo', '-a', 'jobId=0L']) #扬州亿鑫投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YangzhouyixinInvest', '-a', 'jobId=0L']) #冠通北纬资产 #cmdline.execute(['scrapy', 'crawl', 'FundNav_GuantongbeiweiAsset', '-a', 'jobId=0L']) #般若投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_BanruoInvest', '-a', 'jobId=0L']) #广州玄元投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_GuangzhouxuanyuanInvest', '-a', 'jobId=0L']) #齐鲁证券 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_Qiluzhengquan', '-a', 'jobId=0L']) #宏锡基金 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HongxiFund', '-a', 'jobId=0L']) #华西证券 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HuaxiZhengQuan', '-a', 'jobId=0L']) #银河证券 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YinheZhengquan', '-a', 'jobId=0L']) #华鑫证券 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HuaxinZhengQuan', '-a', 'jobId=0L']) #辰月投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ChenyueInvest', '-a', 'jobId=0L']) #宏锡基金 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_HongxiFund', '-a', 'jobId=0L']) #格林大华期货 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_GelindahuaQihuo', '-a', 'jobId=0L']) #东方财富证券资管 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_DongfangcaifuZhengquan', '-a', 'jobId=0L']) #大同证券 #cmdline.execute(['scrapy', 'crawl', 'FundNav_DatongZhengQuan', '-a', 'jobId=0L']) #光大兴陇信托 #cmdline.execute(['scrapy', 'crawl', 'FundNav_GuangdaxinglongTrust', '-a', 'jobId=0L']) #华鑫信托 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HuaxinTrust', '-a', 'jobId=0L']) #北京澎泰资本 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_BeijingpengtaiCapital', '-a', 'jobId=0L']) #玖歌投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_JiugeInvest', '-a', 'jobId=0L']) #珺容投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_JunrongInvest', '-a', 'jobId=0L']) #北京恒宇天泽投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_BeijinghengyutaizeInvest', '-a', 'jobId=0L']) #深圳三和创赢资产 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ShenzhensanhechuangyingAsset', '-a', 'jobId=0L']) #北京久银投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_BeijingjiuyinInvest', '-a', 'jobId=0L']) #长江期货 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ChangjiangQiHuo', '-a', 'jobId=0L']) #世域投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ShiYuFund', '-a', 'jobId=0L']) #上海益菁汇资产 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ShanghaiyijinghuiFuture', '-a', 'jobId=0L']) #深圳华银精治资产 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_HuayinjingzhiInvest', '-a', 'jobId=0L']) #融通资本 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_RongtongFuture','-a', 'jobId=0L']) #宝城期货 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_Baochengqihuo','-a', 'jobId=0L']) #乐瑞资产 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_LeruiTrust','-a', 'jobId=0L']) #引领投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YinlingInvest','-a', 'jobId=0L']) #深圳前海唐氏投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ShenzhenqianhaitangshiInvest','-a', 'jobId=0L']) #兴证期货 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_XingzhengFuture','-a', 'jobId=0L']) #凡贝资产 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_FanbeiFutrue','-a', 'jobId=0L']) #星石投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_BeijingxingshiInvest','-a', 'jobId=0L']) #旭诚资产 #cmdline.execute(['scrapy', 'crawl', 'FundNav_FujianxuchengFuture','-a', 'jobId=0L']) #耀之资产 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YaozhiFuture','-a', 'jobId=0L']) #睿亿投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_RuiyiInvest','-a', 'jobId=0L']) #兴业证券 #cmdline.execute(['scrapy', 'crawl', 'FundNav_XingyeFuture','-a', 'jobId=0L']) #新时代证券 #cmdline.execute(['scrapy', 'crawl', 'FundNav_XinshidaizhengquanSecurity','-a', 'jobId=0L']) #洼盈投资 #cmdline.execute(['scrapy', 'crawl', 'FundNav_WayingInvest','-a', 'jobId=0L']) #天鑫财富 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_TianxinFuture','-a', 'jobId=0L']) #泊通投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_BotongInvest','-a', 'jobId=0L']) #中原信托 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongyuanxintuoInvest','-a', 'jobId=0L']) #中信建投 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongxinjiantouAsset','-a', 'jobId=0L']) #深圳友利基金 #cmdline.execute(['scrapy', 'crawl', 'FundNav_Shenzhenyouli','-a', 'jobId=0L']) #江苏金百灵资产 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_JinbailingFuture','-a', 'jobId=0L']) #北京诚盛投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_BeijingchengshengInvest','-a', 'jobId=0L']) #德亚投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_DeYaInvestNotice','-a', 'jobId=0L']) #广州凯纳投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_KainaiInvest','-a', 'jobId=0L']) #中泰信托 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongtaixintuoInvest','-a', 'jobId=0L']) #中金 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongjinInvest','-a', 'jobId=0L']) #北京云程泰 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_YunchengtaiInvest','-a', 'jobId=0L']) #红岸资本 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_HonganInvest','-a', 'jobId=0L']) #光大金控投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_GuangdajinkongInvest','-a', 'jobId=0L']) #天勤资产 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_TianqinFuture','-a', 'jobId=0L']) #西藏中睿合银投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongruiheyinInvest','-a', 'jobId=0L']) #安州投资 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_AnzhouInvest','-a', 'jobId=0L']) #长安信托 cmdline.execute(['scrapy', 'crawl', 'FundNotice_Changanxintuo','-a', 'jobId=0L'])<file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-10 from urllib.parse import urljoin from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class WanQuanYiDeSpider(GGFundNavSpider): name = 'FundNav_WanQuanYiDe' sitename = '深圳万泉易德资产' channel = '投顾净值' allowed_domains = ['www.wqydzc.com'] start_urls = ['http://www.wqydzc.com/qxcp/'] fps = [{'url': 'http://www.wqydzc.com/qxcp/'}] def parse_fund(self, response): link_key = response.xpath('//div[@class="con"]/dl[@class="sort_brand"]/dt/a/@href').extract() for key in link_key: fund_link = urljoin('http://www.wqydzc.com', key) self.ips.append({ 'url': fund_link, 'ref': response.url }) def parse_item(self, response): fund_name = response.xpath('//tr[@class="tr01"][1]/td[2]/text()').extract_first() nav_rows = response.xpath('//table[@class="table01"]//tr') for row in nav_rows[1:]: nav_info = row.xpath('td/text()').extract() statistic_date = nav_info[0].strip() nav = nav_info[1] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d %H:%M:%S') item['nav'] = float(nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-04 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class TianBeiHeZiChanInvestSpider(GGFundNavSpider): name = 'FundNav_TianBeiHeZiChanInvest' sitename = '广东天贝合资产' channel = '投资顾问' allowed_domains = ['www.ten-bagger.com'] username = '13916427906' password = '<PASSWORD>' fps = [{'url': 'http://www.ten-bagger.com/zh-CN/products.php?page=1'}] def parse_fund(self, response): fund_urls = response.xpath("//table[2]//table//table//table[1]//tr") for url in fund_urls: fund_url = url.xpath("./td//@href").extract_first() fund_name = url.xpath("./td//text()").extract_first() if fund_url and 'displayproduct' in fund_url: self.ips.append({ 'url': 'http://www.ten-bagger.com/zh-CN/' + fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name}, }) if len(fund_urls) > 5: pg = response.url.replace('http://www.ten-bagger.com/zh-CN/products.php?page=', '') next_pg = str(int(pg) + 1) self.fps.append({ 'url': response.url.replace('?page=' + pg, '?page=' + next_pg), 'ref': response.url, }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath("//div[@class='c02_content']/table[@class='product']/tbody//tr") for row in rows[1:]: statistic_date = row.xpath("./td[2]//text()").extract_first() nav = row.xpath('./td[3]//text()').extract_first() added_nav = row.xpath('./td[4]//text()').extract_first() if '2' in statistic_date: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class YiCunInvestSpider(GGFundNoticeSpider): name = 'FundNotice_YiCunInvest' sitename = '一村投资' entry = 'http://www.v-investment.com/news/public' lps = [ { 'url': 'http://www.v-investment.com/news/public' } ] def parse_list(self, response): rows = response.xpath('//div[@class="news-title"]/a') for row in rows: url = row.xpath('./@href').extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url }) def parse_item(self, response): url = response.url title = response.xpath('//div[@class="news-title"]/text()').extract_first() publish_time = response.xpath('//span[@class="date"]/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = url item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class ShanGuoTouTrustSpider(GGFundNavSpider): name = 'FundNav_ShanGuoTouTrust' sitename = '陕国投' channel = '信托净值' allowed_domains = ['www.siti.com.cn'] fps = [ {'url': 'http://www.siti.com.cn/product.php?fid=23&fup=3&pageid=1', 'pg': 1}, ] def parse_fund(self, response): fund_urls = response.xpath("//div[@class='proDl']//tr//@href").extract() for fund_url in fund_urls: fund_pg = re.findall('pageid=(\d+)', fund_url)[0] self.ips.append({ 'url': 'http://www.siti.com.cn/' + fund_url.replace('pageid=' + fund_pg, 'pageid=1'), 'ref': response.url, 'pg': 1 }) if fund_urls: pg = response.meta['pg'] next_pg = pg + 1 self.fps.append({ 'url': 'http://www.siti.com.cn/product.php?fid=23&fup=3&pageid=' + str(next_pg), 'ref': response.url, 'pg': next_pg }) def parse_item(self, response): fund_name = response.xpath("//div[@class='proTitle'][1]/h1//text()").extract_first() rows = response.xpath("//div[@class='proDl']//tr") if len(rows) > 1: for row in rows[1:]: statistic_date = row.xpath("./td[1]//text()").extract_first().replace('年', '-').replace('月', '-').replace( '日', '') nav = row.xpath("./td[3]").re_first('>\s*([0-9.]+)\s*<') added_nav = row.xpath("./td[4]").re_first('>\s*([0-9.]+)\s*<') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item pg = response.meta['pg'] next_pg = pg + 1 self.ips.append({ 'url': response.url.replace('pageid=' + str(pg), 'pageid=' + str(next_pg)), 'ref': response.url, 'pg': next_pg, }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin import re class DaYeTrustSpider(GGFundNoticeSpider): name = 'FundNotice_DaYeTrust' sitename = '大业信托' entry = 'http://www.dytrustee.com/' lps = [ { 'url': 'http://www.dytrustee.com/Information.aspx', 'ref': 'http://www.dytrustee.com/', 'ext': {'flag': 0} } ] def parse_list(self, response): if response.meta['ext']['flag'] == 1: pg = response.meta['pg'] self.ips.append({ 'url': response.url + '&page=' + str(pg), 'ref': response.url }) else: urls = response.xpath("//ul[@class='fix']/li/a") for url in urls[2:]: href = url.xpath('./@href').extract_first() type = url.xpath('./text()').extract_first() self.lps.append({ 'url': urljoin(get_base_url(response), href), 'ref': response.url, 'pg': 1, 'ext': {'flag': 1, 'type': type} }) def parse_item(self, response): datas = response.xpath("//div[@class='news_list fix']/ul/li") for notice in datas: href = notice.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), href) title = notice.xpath('./a/text()').extract_first() publish_time = notice.xpath('./small/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item next_url = response.xpath('//div[@id="AspNetPager1"]/div[1]/a[contains(text(),"下一页")]/@href').extract_first() if next_url is not None: self.ips.append({ 'url': urljoin(get_base_url(response), next_url), 'ref': response.url }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-01 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class HwachinInvestSpider(GGFundNavSpider): name = 'FundNav_HwachinInvest' sitename = '华勤投资' channel = '投资顾问' username = 'ZYYXSM' password = '<PASSWORD>' cookies = '__guid=36323750.1600720933798163000.1524909128435.6665; PHPSESSID=b45b6ef70eadce73c1e8273e066566f4; GWFiG_auth=<KEY>; GWFiG__userid=cfc0VHWNOd-HPPs85Gm1BRrtvygPYZh9WehXArSiDs4I; GWFiG__username=09b1apC6kQLaxW_1bgQ9006b6yuYaOfemDm7H42sjMNrzq8; GWFiG__groupid=dbbd9nbPpz7B2H_yhVGKw15BUOeFA1eIpivuFi1W; GWFiG__nickname=a2daQiN0QY8wNu2uI7XoCkA--z1xnq28PYNoTcTTqZ51Zv4; monitor_count=32' fps = [{'url': 'http://www.hwachin.com/index.php?m=content&c=index&a=show&catid=33&id=1'}] def parse_fund(self, response): fund_urls = response.xpath("//div[@id='jquery-accordion-menu'][@class='jquery-accordion-menu red']/ul/li[3]/a") for url in fund_urls: ips_url = url.xpath('.//@href').extract_first() fund_name = url.xpath('.//text()').extract_first() self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath("//div[@id='tab2'][@class='tab_content']/table/tbody//tr") for row in rows[1:]: fund_date = row.xpath('.//td[2]//text()').extract_first() nav = row.xpath('.//td[3]//text()').extract_first() added_nav = row.xpath('.//td[4]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date.replace('/', '-'), '%Y-%m-%d') item['nav'] = float(nav) item['added_nav'] = float(added_nav) yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-02 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import Request from urllib.parse import urljoin from scrapy.utils.response import get_base_url class GuoLianZhengQuanSecutiesSpider(GGFundNavSpider): name = 'FundNav_GuoLianZhengQuanSecuties' sitename = '国联证券' channel = '券商资管净值' username = '13228803' cookies = 'JSESSIONID=F27241BAFE251EC87E7FE95412FCE0EA; UM_distinctid=162f6c25511322-0c2a257239f065-3c604504-15f900-162f6c25512358; CNZZDATA5813404=cnzz_eid%3D488101347-1524553576-%26ntime%3D1524701933; lcLastUrl="http://www.glsc.com.cn/glzq/financing/management/gf_4.jsp"' def start_requests(self): yield Request( url='http://www.glsc.com.cn/glzq/financing/management/management_business.html?sub_top=FinancingIndex&child_top=management_business', callback=self.parse_pre_fund) def parse_pre_fund(self, response): fund_urls = response.xpath("//div[@id='menu_zzjsnet' or @id='menu_yzz' or @id='menu_abc']/ul//a") for url in fund_urls: fund_url = url.xpath("./@href").extract_first() fund_url = urljoin(get_base_url(response), fund_url) self.fps.append({ 'url': fund_url, 'ref': response.url, }) def parse_fund(self, response): fund_into = response.xpath("//table[@id='News4']") fund_urls = fund_into.xpath('.//tr') urls = fund_urls.xpath('.//@src').extract() name = fund_urls.xpath('./td//text()').extract() names = [i for i in name if ' ' not in i] for i in zip(urls, names): fund_url = i[0] fund_name = i[1].replace('集合净值', '').replace('收益', '').replace('预估年化收益率', '') self.ips.append({ 'url': 'http://www.glsc.com.cn' + fund_url + '&current_page=1', 'pg': 1, 'ref': response.url, 'ext': {'fund_name': fund_name}, }) def parse_item(self, response): rows = response.xpath("//tr[@class='table-td2']") fund_name = response.meta['ext']['fund_name'] if len(rows) > 0: for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name if '预估年化收益率' in response.xpath('//tr[@class="table-title1"]/td[1]/text()').extract_first(): statistic_date = row.xpath("./td[2]//text()").extract_first() item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') annualized_return = row.xpath('./td[1]//text()').extract_first() item['annualized_return'] = float(annualized_return) if annualized_return else None elif '七日年化收益率' in response.xpath('//tr[@class="table-title1"]/td[3]/text()').extract_first(): statistic_date = row.xpath("./td[1]//text()").extract_first() item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') d7_annualized_return = row.xpath('./td[2]//text()').extract_first() income_value_per_ten_thousand = row.xpath('./td[3]//text()').re_first('[0-9.]+') item['d7_annualized_return'] = float(d7_annualized_return) item['income_value_per_ten_thousand'] = float(income_value_per_ten_thousand) else: nav = row.xpath('./td[1]//text()').extract_first() add_nav = row.xpath('./td[2]//text()').extract_first() item['nav'] = float(nav)if nav else None item['added_nav'] = float(add_nav)if add_nav else None statistic_date = row.xpath("./td[3]//text()").extract_first() item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') yield item pg = response.meta['pg'] next_pg = int(pg) + 1 next_url = response.url.replace('current_page=' + str(pg), 'current_page=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name.replace('净值', '')}, }) <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-16 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class HuoLiAssetSpider(GGFundNavSpider): name = 'FundNav_HuoLiAsset' sitename = '货力资产' channel = '投资顾问' username = '18883929277' password = '<PASSWORD>' cookies = r'PHPSESSID=2pq7d4oro2fv7uifbbiqjgdm44; DedeUserID__ckMd5=386c326b098c13bf; DedeUserID=12; DedeLoginTime__ckMd5=aaddc98eab3669bf; DedeLoginTime=1526436874' fps = [ {'url': 'http://www.huoliasset.com/plus/list.php?tid=4', 'ref': 'http://www.huoliasset.com/index.html'} ] def parse_fund(self, response): link_key = response.xpath('//div[@class="brc_man"]/div[@class="bod"]/div[@class="in"]/div[@class="lst"]/div[@class="l"]/a/@href').extract() fund_name = response.xpath('//div[@class="brc_man"]/div[@class="bod"]/div[@class="in"]/div[@class="lst"]/div[@class="l"]/a/@title').extract() for name, key in zip(fund_name, link_key): nav_link = urljoin('http://www.huoliasset.com', key) self.ips.append({ 'url': nav_link, 'ref': response.url, 'ext': {'fund_name': name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] nav_rows = response.xpath('//div[@id="coc"]/table/tbody/tr[2]/td[1]/div[@class="pro_box"]/div[@class="pro_con"]//tr') for row in nav_rows[1:]: nav_info = row.xpath('td/text()').extract() if nav_info[0].strip(): statistic_date = nav_info[0].strip() nav = nav_info[1].strip() added_nav = nav_info[2].strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if added_nav else None yield item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class YuanCeAssetSpider(GGFundNavSpider): name = 'FundNav_YuanCeAsset' sitename = '远策投资' channel = '投顾净值' fps = [{ 'url': 'http://www.yuancefund.com/newslist.php?cid=7', 'ext': {'type': '1'} }] username = 'ZYYXSM' password = '<PASSWORD>.' cookies = 'PHPSESSID=iddm66nipb4jh4fs477up8k2n1; yunsuo_session_verify=0ae6a7abca5f16cc0006651628c8893d' def parse_fund(self, response): link_list = response.xpath('//div[@class = "pro_class"]/a/@href').extract() type = response.meta['ext']['type'] if type == '1': for link in link_list: cid = re.search(r'newslist\.php\?cid=(\d+)', link).group(1) self.fps.append({ 'url': 'http://www.yuancefund.com/newslist.php?cid=' + cid, 'ref': response.url, 'ext': {'type': '2'} }) if type == '2': rows = response.xpath('//ul[@id = "mycarousel"]/li/a') for row in rows: cid = re.search(r'newslist\.php\?cid=(\d+)', row.xpath('./@href').extract_first()).group(1) fund_name = row.xpath('./@title').extract_first() self.ips.append({ 'url': 'http://www.yuancefund.com/newslist.php?cid=' + cid + '&t=1', 'ref': response.url, 'ext': {'fund_name': fund_name} }) yield self.request_next() def parse_item(self, response): datas = response.xpath('//div[@class="li"]/table//tr') for row in datas[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = row.xpath('./td[1]/text()').extract_first().strip() statistic_date = row.xpath('./td[2]/text()').extract_first().strip() item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row.xpath('./td[3]/text()').extract_first().strip() item['nav'] = float(nav) if nav is not None else None yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-30 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from FundNavSpiders import Request from urllib import parse import re class JinZhongHeSecuritySpider(GGFundNavSpider): name = 'FundNav_JinZhongHeSecurity' sitename = '金中和' channel = '投顾净值' username = '朝阳永续' password = '<PASSWORD>' fps = [{'url': 'http://www.golden18.com/pzbz.asp?Title=%D0%C5%CD%D0%B2%FA%C6%B7'}] def start_requests(self): href = '?UserName=%B3%AF%D1%F4%D3%C0%D0%F8&Password=<PASSWORD>&Login=+%B5%C7%C2%BC+' yield Request( url='http://www.golden18.com/UserLogin.asp' + href, meta={ 'dont_redirect': True, 'handle_httpstatus_list': [302, 301] }) def parse_fund(self, response): title_list = response.css('a.left::attr(href)').re('Title=(.*)') for title in title_list: href = parse.urlencode({'Title': title}, encoding='gb2312') self.ips.append({ 'url': 'http://www.golden18.com/product.asp?' + href, 'ref': response.url, 'ext': title }) def parse_item(self, response): res_text = re.sub('[\s,]', '', response.text) target_str = re.findall('单位净值报告(.*)深圳市金中和投资管理有限公司', res_text, re.DOTALL) if target_str: rows = target_str[0].split('</TR>') for tr in rows: date = re.findall('\d{4}\.\d{2}\.\d{2}', tr, re.DOTALL) nav = re.findall('[^\d\.](\d{2,3}\.\d{2})[^%]', tr, re.DOTALL) if date: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = response.meta['ext'] item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav[0].strip()) if nav else None item['statistic_date'] = datetime.strptime(date[0].strip(), '%Y.%m.%d') if date else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-28 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class HuaTaiSecuritySpider(GGFundNavSpider): name = 'FundNav_HuaTaiSecurity' sitename = '华泰证券' channel = '券商资管净值' allowed_domains = ['htamc.htsc.com.cn'] ips = [ { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941239&t=5&start=0&limits=1000&name=.C2.B6.C2.A8.C3.94.C3.B66.C2.BA.C3.85.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '定增6号(风险级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941183&t=5&start=0&limits=1000&name=.C2.BB.C3.95.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE1.C3.86.C3.9A', 'ext': '徽华1号A份额1期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941199&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B02.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园2号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940025&t=3&start=0&limits=1000&name=.C2.BD.C3.9A.C2.BC.C3.99.C3.88.C3.95.C3.80.C3.AD.C2.B2.C3.86', 'ext': '节假日理财'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941160&t=5&start=0&limits=1000&name=.C2.BE.C2.A9.C2.BB.C2.AA1.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '京华1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941434&t=4&start=0&limits=1000&name=.C3.84.C3.8F.C2.B3.C3.A41.C2.BA.C3.85A2', 'ext': '南充1号A2'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941109&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE3.C3.86.C3.9A', 'ext': '浦华1号A份额3期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941412&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA3.C2.BA.C3.85.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6A1', 'ext': '浦华3号优先级A1'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF8156&t=5&start=0&limits=1000&name=.C3.88.C3.BC.C3.81.C3.AC.C3.81.C3.AC.C2.BA.C2.BD1.C2.BA.C3.85', 'ext': '赛领领航1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940008&t=5&start=0&limits=1000&name=.C3.8F.C3.96.C2.BD.C3.B0.C2.B9.C3.9C.C2.BC.C3.92', 'ext': '现金管家'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941163&t=5&start=0&limits=1000&name=.C3.93.C2.AF.C3.8C.C2.A91.C2.BA.C3.85', 'ext': '盈泰1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941219&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB4.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见4号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941251&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB5.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见5号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940344&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X16', 'ext': '月月优先6月X16'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940321&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.97.C2.A8.C3.8F.C3.ADX1', 'ext': '月月优先专享X1'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940083&t=4&start=0&limits=1000&name=.C3.96.C3.8A.C3.91.C2.BA.C2.B1.C2.A61.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '质押宝1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940042&t=5&start=0&limits=1000&name=.C2.B8.C3.9F.C3.8A.C3.95.C3.92.C3.A6.C3.95.C2.AE', 'ext': '高收益债'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940210&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X10', 'ext': '季季优先X10'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940213&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X13', 'ext': '季季优先X13'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941430&t=5&start=0&limits=1000&name=.C2.BD.C2.A1.C3.90.C3.901.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '健行1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941113&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE7.C3.86.C3.9A', 'ext': '浦华1号A份额7期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941107&t=5&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85B.C2.B7.C3.9D.C2.B6.C3.AE', 'ext': '浦华1号B份额'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940085&t=5&start=0&limits=1000&name=.C3.8E.C3.88.C3.80.C3.BB1.C2.BA.C3.85', 'ext': '稳利1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940013&t=5&start=0&limits=1000&name=.C3.90.C3.82.C3.90.C3.8B.C2.B2.C3.BA.C3.92.C2.B5', 'ext': '新兴产业'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941220&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB4.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见4号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941254&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB6.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见6号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940332&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.881.C3.94.C3.82X3', 'ext': '月月优先1月X3'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940312&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX12', 'ext': '月月优先半年X12'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940319&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX19', 'ext': '月月优先半年X19'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941156&t=5&start=0&limits=1000&name=.C3.96.C3.8A.C3.91.C2.BA.C3.92.C3.971.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE1.C3.86.C3.9A', 'ext': '质押易1号A份额1期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941158&t=5&start=0&limits=1000&name=.C3.96.C3.8A.C3.91.C2.BA.C3.92.C3.971.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE3.C3.86.C3.9A', 'ext': '质押易1号A份额3期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940053&t=5&start=0&limits=1000&name=.C2.B0.C3.AB.C3.84.C3.AA.C2.B7.C2.A2.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '半年发(风险级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941152&t=5&start=0&limits=1000&name=.C2.B9.C2.B2.C3.93.C2.AE1.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '共赢1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF0585&t=5&start=0&limits=1000&name=.C2.B9.C2.B2.C3.93.C2.AE2.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '共赢2号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941235&t=5&start=0&limits=1000&name=.C2.BB.C3.9B.C3.94.C3.B31.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '慧泽1号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941234&t=5&start=0&limits=1000&name=.C2.BB.C3.9B.C3.94.C3.B31.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '慧泽1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940030&t=5&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C2.B7.C2.A2.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '季季发(风险级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941232&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B010.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园10号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941190&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B01.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941199&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B02.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园2号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=S75566&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B03.C2.BA.C3.85', 'ext': '家园3号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940004&t=5&start=0&limits=1000&name=.C2.B2.C2.BD.C2.B2.C2.BD.C3.8E.C2.AA.C3.93.C2.AF', 'ext': '步步为盈'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941184&t=5&start=0&limits=1000&name=.C2.BB.C3.95.C2.BB.C2.AA1.C2.BA.C3.85.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6A2', 'ext': '徽华1号优先级A2'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940029&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C2.B7.C2.A2.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '季季发(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941211&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A67.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力7号(中间级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941115&t=5&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE9.C3.86.C3.9A', 'ext': '浦华1号A份额9期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941280&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A91.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941256&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB7.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见7号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940181&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.881.C3.94.C3.82X8', 'ext': '月月优先1月X8'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940341&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X13', 'ext': '月月优先6月X13'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940252&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX7', 'ext': '月月优先新享X7'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940305&t=2&start=0&limits=1000&name=.C3.94.C3.B6.C3.87.C2.BF.C3.95.C2.AE.C3.88.C2.AF.C3.93.C3.85.C3.8F.C3.885.C2.BA.C3.85', 'ext': '增强债券优先5号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940048&t=5&start=0&limits=1000&name=.C2.B2.C3.86.C2.B8.C2.BB2.C2.BA.C3.85.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '财富2号(风险级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940209&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X9', 'ext': '季季优先X9'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941206&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A62.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力2号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941411&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA3.C2.BA.C3.85.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6B', 'ext': '浦华3号风险级B'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941162&t=5&start=0&limits=1000&name=.C3.88.C3.99.C3.8C.C2.A91.C2.BA.C3.85', 'ext': '荣泰1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941219&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB4.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见4号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941253&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB6.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见6号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940281&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.883.C3.94.C3.82X1', 'ext': '月月优先3月X1'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940263&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.884.C3.94.C3.82X3', 'ext': '月月优先4月X3'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940311&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX11', 'ext': '月月优先半年X11'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940255&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX10', 'ext': '月月优先新享X10'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941258&t=5&start=0&limits=1000&name=.C3.96.C3.90.C2.BF.C3.86.C2.BD.C3.B0.C2.B2.C3.861.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '中科金财1号(中间级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941173&t=5&start=0&limits=1000&name=.C3.96.C3.90.C3.92.C3.B81.C2.BA.C3.856.C2.B8.C3.B6.C3.94.C3.821.C3.86.C3.9A', 'ext': '中银1号6个月1期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941152&t=5&start=0&limits=1000&name=.C2.B9.C2.B2.C3.93.C2.AE1.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '共赢1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941182&t=5&start=0&limits=1000&name=.C2.BB.C3.95.C2.BB.C2.AA1.C2.BA.C3.85B.C2.B7.C3.9D.C2.B6.C3.AE', 'ext': '徽华1号B份额'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940201&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X1', 'ext': '季季优先X1'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941431&t=5&start=0&limits=1000&name=.C2.BD.C2.A1.C3.90.C3.901.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '健行1号(次级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941241&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A614.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力14号(中间级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941205&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A62.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力2号(中间级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941205&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A62.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力2号(中间级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941111&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE5.C3.86.C3.9A', 'ext': '浦华1号A份额5期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940028&t=1&start=0&limits=1000&name=.C3.8C.C3.AC.C3.8C.C3.AC.C2.B7.C2.A2B', 'ext': '天天发B'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940038&t=1&start=0&limits=1000&name=.C3.8C.C3.AC.C3.8C.C3.AC.C2.B7.C2.A2C', 'ext': '天天发C'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940087&t=5&start=0&limits=1000&name=.C3.8D.C2.B6.C3.88.C3.9A.C2.B1.C2.A6C.C2.BC.C2.B6', 'ext': '投融宝C级'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940253&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX8', 'ext': '月月优先新享X8'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941226&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B08.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园8号(次级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941161&t=5&start=0&limits=1000&name=.C2.BE.C2.A9.C2.BB.C2.AA1.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '京华1号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941241&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A614.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力14号(中间级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941203&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A63.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力3号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941432&t=5&start=0&limits=1000&name=.C3.84.C3.8F.C2.B3.C3.A41.C2.BA.C3.85B', 'ext': '南充1号B'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941413&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA3.C2.BA.C3.85.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6A2', 'ext': '浦华3号优先级A2'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941281&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A91.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰1号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941506&t=5&start=0&limits=1000&name=.C3.88.C3.B0.C3.93.C2.AF1.C2.BA.C3.85A', 'ext': '瑞盈1号A'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940007&t=5&start=0&limits=1000&name=.C3.93.C3.85.C3.95.C2.AE.C2.BE.C2.AB.C3.91.C2.A1', 'ext': '优债精选'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940180&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.881.C3.94.C3.82X7', 'ext': '月月优先1月X7'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940282&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.883.C3.94.C3.82X2', 'ext': '月月优先3月X2'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940310&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX10', 'ext': '月月优先半年X10'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940318&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX18', 'ext': '月月优先半年X18'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940306&t=2&start=0&limits=1000&name=.C3.94.C3.B6.C3.87.C2.BF.C3.95.C2.AE.C3.88.C2.AF.C3.93.C3.85.C3.8F.C3.886.C2.BA.C3.85', 'ext': '增强债券优先6号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941179&t=5&start=0&limits=1000&name=.C3.96.C3.87.C2.B7.C3.89.C3.89.C3.BA.C3.8E.C3.AF1.C2.BA.C3.85.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '智飞生物1号(风险级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940054&t=5&start=0&limits=1000&name=.C3.92.C3.97.C3.88.C3.9A.C2.B1.C2.A61.C2.BA.C3.85', 'ext': '易融宝1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940033&t=5&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C2.B7.C2.A2.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '月月发(风险级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940246&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX1', 'ext': '月月优先新享X1'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940256&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX11', 'ext': '月月优先新享X11'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940248&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX3', 'ext': '月月优先新享X3'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940249&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX4', 'ext': '月月优先新享X4'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941259&t=5&start=0&limits=1000&name=.C3.96.C3.90.C2.BF.C3.86.C2.BD.C3.B0.C2.B2.C3.861.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '中科金财1号(次级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941239&t=5&start=0&limits=1000&name=.C2.B6.C2.A8.C3.94.C3.B66.C2.BA.C3.85.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '定增6号(风险级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940099&t=4&start=0&limits=1000&name=.C2.B7.C3.A1.C3.8C.C2.A9.C2.B4.C3.B3.C2.B7.C3.A1A1', 'ext': '丰泰大丰A1'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940210&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X10', 'ext': '季季优先X10'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941191&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B01.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园1号(次级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941161&t=5&start=0&limits=1000&name=.C2.BE.C2.A9.C2.BB.C2.AA1.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '京华1号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941204&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A62.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力2号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941164&t=5&start=0&limits=1000&name=.C3.8A.C2.A2.C3.8C.C2.A91.C2.BA.C3.85', 'ext': '盛泰1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF5284&t=5&start=0&limits=1000&name=.C3.8D.C2.B6.C3.94.C3.B61.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '投增1号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940013&t=5&start=0&limits=1000&name=.C3.90.C3.82.C3.90.C3.8B.C2.B2.C3.BA.C3.92.C2.B5', 'ext': '新兴产业'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941251&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB5.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见5号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940341&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X13', 'ext': '月月优先6月X13'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940315&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX15', 'ext': '月月优先半年X15'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940256&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX11', 'ext': '月月优先新享X11'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941325&t=4&start=0&limits=1000&name=.C3.97.C3.B0.C3.8F.C3.AD1.C2.BA.C3.85X21', 'ext': '尊享1号X21'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941326&t=4&start=0&limits=1000&name=.C3.97.C3.B0.C3.8F.C3.AD1.C2.BA.C3.85X22', 'ext': '尊享1号X22'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940053&t=5&start=0&limits=1000&name=.C2.B0.C3.AB.C3.84.C3.AA.C2.B7.C2.A2.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '半年发(风险级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941224&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B07.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园7号(次级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941215&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A68.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力8号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941110&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE4.C3.86.C3.9A', 'ext': '浦华1号A份额4期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941283&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A92.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰2号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940087&t=5&start=0&limits=1000&name=.C3.8D.C2.B6.C3.88.C3.9A.C2.B1.C2.A6C.C2.BC.C2.B6', 'ext': '投融宝C级'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941248&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB15.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见15号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941178&t=5&start=0&limits=1000&name=.C3.96.C3.87.C2.B7.C3.89.C3.89.C3.BA.C3.8E.C3.AF1.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '智飞生物1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941172&t=5&start=0&limits=1000&name=.C3.96.C3.90.C3.92.C3.B81.C2.BA.C3.85.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '中银1号(风险级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940057&t=5&start=0&limits=1000&name=.C3.97.C3.B0.C3.8F.C3.AD.C2.BC.C2.BE.C2.BC.C2.BE.C2.B7.C2.A2.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '尊享季季发(风险级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=S78688&t=5&start=0&limits=1000&name=.C2.B2.C2.A2.C2.B9.C2.BA.C2.BB.C3.B9.C2.BD.C3.B01.C2.BA.C3.85', 'ext': '并购基金1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940048&t=5&start=0&limits=1000&name=.C2.B2.C3.86.C2.B8.C2.BB2.C2.BA.C3.85.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '财富2号(风险级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941245&t=5&start=0&limits=1000&name=.C2.B6.C2.A8.C3.94.C3.B6.C2.B9.C2.B2.C2.BD.C3.B81.C2.BA.C3.85', 'ext': '定增共进1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941153&t=5&start=0&limits=1000&name=.C2.B9.C2.B2.C3.93.C2.AE1.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '共赢1号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941200&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B02.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园2号(次级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941223&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B07.C2.BA.C3.85.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6', 'ext': '家园7号优先级'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941160&t=5&start=0&limits=1000&name=.C2.BE.C2.A9.C2.BB.C2.AA1.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '京华1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941246&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A616.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力16号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941212&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A67.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力7号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941213&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A68.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力8号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941433&t=4&start=0&limits=1000&name=.C3.84.C3.8F.C2.B3.C3.A41.C2.BA.C3.85A1', 'ext': '南充1号A1'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=S78988&t=5&start=0&limits=1000&name=.C2.B2.C2.A2.C2.B9.C2.BA.C2.BB.C3.B9.C2.BD.C3.B02.C2.BA.C3.85', 'ext': '并购基金2号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF0585&t=5&start=0&limits=1000&name=.C2.B9.C2.B2.C3.93.C2.AE2.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '共赢2号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940213&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X13', 'ext': '季季优先X13'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940207&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X7', 'ext': '季季优先X7'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=S75566&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B03.C2.BA.C3.85', 'ext': '家园3号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941203&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A63.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力3号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941411&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA3.C2.BA.C3.85.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6B', 'ext': '浦华3号风险级B'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941283&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A92.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰2号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941164&t=5&start=0&limits=1000&name=.C3.8A.C2.A2.C3.8C.C2.A91.C2.BA.C3.85', 'ext': '盛泰1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940041&t=5&start=0&limits=1000&name=.C3.8D.C2.B6.C3.88.C3.9A.C2.B1.C2.A6B.C2.BC.C2.B6', 'ext': '投融宝B级'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941400&t=5&start=0&limits=1000&name=.C3.8D.C2.B6.C3.88.C3.9A.C3.94.C3.B6.C3.80.C3.BB1.C2.BA.C3.85', 'ext': '投融增利1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF5284&t=5&start=0&limits=1000&name=.C3.8D.C2.B6.C3.94.C3.B61.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '投增1号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940056&t=4&start=0&limits=1000&name=.C3.97.C3.B0.C3.8F.C3.AD.C2.BC.C2.BE.C2.BC.C2.BE.C2.B7.C2.A2.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '尊享季季发(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940052&t=4&start=0&limits=1000&name=.C2.B0.C3.AB.C3.84.C3.AA.C2.B7.C2.A2.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '半年发(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940027&t=5&start=0&limits=1000&name=.C2.B1.C3.9C.C3.8F.C3.95', 'ext': '避险'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940019&t=2&start=0&limits=1000&name=.C2.B6.C2.A8.C2.B4.C3.A6.C2.B1.C2.A6', 'ext': '定存宝'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=S76682&t=5&start=0&limits=1000&name=.C2.BB.C2.AA.C3.93.C2.AF1.C2.BA.C3.85', 'ext': '华盈1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940211&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X11', 'ext': '季季优先X11'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940208&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X8', 'ext': '季季优先X8'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SG1665&t=5&start=0&limits=1000&name=.C2.BE.C2.AD.C3.8E.C2.B34.C3.86.C3.9A', 'ext': '经纬4期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941211&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A67.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力7号(中间级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941213&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A68.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力8号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940085&t=5&start=0&limits=1000&name=.C3.8E.C3.88.C3.80.C3.BB1.C2.BA.C3.85', 'ext': '稳利1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941194&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB1.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941220&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB4.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见4号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941198&t=5&start=0&limits=1000&name=.C2.B6.C2.A8.C3.94.C3.B63.C2.BA.C3.85', 'ext': '定增3号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940212&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X12', 'ext': '季季优先X12'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940205&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X5', 'ext': '季季优先X5'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940205&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X5', 'ext': '季季优先X5'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941224&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B07.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园7号(次级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940025&t=3&start=0&limits=1000&name=.C2.BD.C3.9A.C2.BC.C3.99.C3.88.C3.95.C3.80.C3.AD.C2.B2.C3.86', 'ext': '节假日理财'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941204&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A62.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力2号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941201&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A63.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力3号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941201&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A63.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力3号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941214&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A68.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力8号(中间级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941111&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE5.C3.86.C3.9A', 'ext': '浦华1号A份额5期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940052&t=4&start=0&limits=1000&name=.C2.B0.C3.AB.C3.84.C3.AA.C2.B7.C2.A2.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '半年发(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940047&t=4&start=0&limits=1000&name=.C2.B2.C3.86.C2.B8.C2.BB2.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '财富2号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940101&t=5&start=0&limits=1000&name=.C2.B7.C3.A1.C3.8C.C2.A9.C2.B4.C3.B3.C2.B7.C3.A1B', 'ext': '丰泰大丰B'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940067&t=5&start=0&limits=1000&name=.C2.BA.C3.AA.C2.B9.C3.9B.C2.BB.C3.98.C2.B1.C2.A81.C2.BA.C3.85.C2.A3.C2.A8.C3.86.C3.95.C3.8D.C2.A8.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '宏观回报1号(普通级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940214&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X14', 'ext': '季季优先X14'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941225&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B08.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园8号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940126&t=5&start=0&limits=1000&name=.C2.BD.C2.A1.C2.BF.C2.B5.C3.96.C3.90.C2.B9.C3.BA', 'ext': '健康中国'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941212&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A67.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力7号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941210&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A67.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力7号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941434&t=4&start=0&limits=1000&name=.C3.84.C3.8F.C2.B3.C3.A41.C2.BA.C3.85A2', 'ext': '南充1号A2'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941285&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A93.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰3号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941412&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA3.C2.BA.C3.85.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6A1', 'ext': '浦华3号优先级A1'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941282&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A92.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰2号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940018&t=1&start=0&limits=1000&name=.C3.8C.C3.AC.C3.8C.C3.AC.C2.B7.C2.A2A', 'ext': '天天发A'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940232&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.881.C3.94.C3.82X2', 'ext': '月月优先1月X2'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940181&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.881.C3.94.C3.82X8', 'ext': '月月优先1月X8'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940314&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX14', 'ext': '月月优先半年X14'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940246&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX1', 'ext': '月月优先新享X1'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940251&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX6', 'ext': '月月优先新享X6'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940300&t=2&start=0&limits=1000&name=.C3.94.C3.B6.C3.87.C2.BF.C3.95.C2.AE.C3.88.C2.AFC.C2.BC.C2.B6', 'ext': '增强债券C级'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941257&t=5&start=0&limits=1000&name=.C3.96.C3.90.C2.BF.C3.86.C2.BD.C3.B0.C2.B2.C3.861.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '中科金财1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941258&t=5&start=0&limits=1000&name=.C3.96.C3.90.C2.BF.C3.86.C2.BD.C3.B0.C2.B2.C3.861.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '中科金财1号(中间级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940097&t=4&start=0&limits=1000&name=.C3.92.C3.97.C3.88.C3.9A.C2.B1.C2.A62.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '易融宝2号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941243&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB2.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见2号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940342&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X14', 'ext': '月月优先6月X14'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940316&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX16', 'ext': '月月优先半年X16'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941500&t=5&start=0&limits=1000&name=.C3.96.C3.90.C2.B5.C3.8D.C3.86.C3.80.C2.BC.C2.B6.C3.95.C2.AE1.C2.BA.C3.85', 'ext': '中低评级债1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941171&t=5&start=0&limits=1000&name=.C3.96.C3.90.C3.92.C3.B81.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '中银1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940039&t=5&start=0&limits=1000&name=.C3.96.C3.90.C3.96.C2.A4800.C3.94.C3.B6.C3.87.C2.BF', 'ext': '中证800增强'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941300&t=2&start=0&limits=1000&name=.C3.97.C3.B0.C3.8F.C3.AD1.C2.BA.C3.85Z', 'ext': '尊享1号Z'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941255&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB7.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见7号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940261&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.884.C3.94.C3.82X1', 'ext': '月月优先4月X1'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940310&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX10', 'ext': '月月优先半年X10'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940247&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX2', 'ext': '月月优先新享X2'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940249&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX4', 'ext': '月月优先新享X4'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940325&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.97.C2.A8.C3.8F.C3.ADX5', 'ext': '月月优先专享X5'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941169&t=5&start=0&limits=1000&name=.C3.AE.C2.A3.C3.8C.C2.A9.C2.A1.C2.A4.C2.B2.C3.86.C2.B8.C2.BBFOF2.C2.BA.C3.85', 'ext': '睿泰·财富FOF2号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941248&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB15.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见15号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941243&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB2.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见2号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941195&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB3.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见3号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941196&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB3.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见3号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940261&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.884.C3.94.C3.82X1', 'ext': '月月优先4月X1'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940343&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X15', 'ext': '月月优先6月X15'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940311&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX11', 'ext': '月月优先半年X11'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940321&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.97.C2.A8.C3.8F.C3.ADX1', 'ext': '月月优先专享X1'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941156&t=5&start=0&limits=1000&name=.C3.96.C3.8A.C3.91.C2.BA.C3.92.C3.971.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE1.C3.86.C3.9A', 'ext': '质押易1号A份额1期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941172&t=5&start=0&limits=1000&name=.C3.96.C3.90.C3.92.C3.B81.C2.BA.C3.85.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '中银1号(风险级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941165&t=5&start=0&limits=1000&name=.C3.88.C2.AB.C3.87.C3.B2.C3.95.C2.AE.C3.88.C2.A8.C2.BB.C3.BA.C2.BB.C3.A11.C2.BA.C3.85', 'ext': '全球债权机会1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940041&t=5&start=0&limits=1000&name=.C3.8D.C2.B6.C3.88.C3.9A.C2.B1.C2.A6B.C2.BC.C2.B6', 'ext': '投融宝B级'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940032&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C2.B7.C2.A2.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '月月发(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940132&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.881.C3.94.C3.82X1', 'ext': '月月优先1月X1'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940232&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.881.C3.94.C3.82X2', 'ext': '月月优先1月X2'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940344&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X16', 'ext': '月月优先6月X16'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940315&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX15', 'ext': '月月优先半年X15'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941174&t=5&start=0&limits=1000&name=.C3.96.C3.90.C3.92.C3.B81.C2.BA.C3.8512.C2.B8.C3.B6.C3.94.C3.822.C3.86.C3.9A', 'ext': '中银1号12个月2期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940012&t=5&start=0&limits=1000&name=.C3.97.C3.8F.C2.BD.C3.B0.C3.81.C3.BA.C2.A3.C2.A8QDII.C2.A3.C2.A9', 'ext': '紫金龙(QDII)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941326&t=4&start=0&limits=1000&name=.C3.97.C3.B0.C3.8F.C3.AD1.C2.BA.C3.85X22', 'ext': '尊享1号X22'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940003&t=5&start=0&limits=1000&name=.C3.97.C3.8F.C2.BD.C3.B03.C2.BA.C3.85', 'ext': '紫金3号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940002&t=5&start=0&limits=1000&name=.C3.97.C3.8F.C2.BD.C3.B02.C2.BA.C3.85', 'ext': '紫金2号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940057&t=5&start=0&limits=1000&name=.C3.97.C3.B0.C3.8F.C3.AD.C2.BC.C2.BE.C2.BC.C2.BE.C2.B7.C2.A2.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '尊享季季发(风险级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941245&t=5&start=0&limits=1000&name=.C2.B6.C2.A8.C3.94.C3.B6.C2.B9.C2.B2.C2.BD.C3.B81.C2.BA.C3.85', 'ext': '定增共进1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940208&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X8', 'ext': '季季优先X8'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941226&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B08.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园8号(次级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SG1665&t=5&start=0&limits=1000&name=.C2.BE.C2.AD.C3.8E.C2.B34.C3.86.C3.9A', 'ext': '经纬4期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941432&t=5&start=0&limits=1000&name=.C3.84.C3.8F.C2.B3.C3.A41.C2.BA.C3.85B', 'ext': '南充1号B'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941108&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE2.C3.86.C3.9A', 'ext': '浦华1号A份额2期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941110&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE4.C3.86.C3.9A', 'ext': '浦华1号A份额4期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941115&t=5&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE9.C3.86.C3.9A', 'ext': '浦华1号A份额9期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941282&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A92.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰2号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941507&t=5&start=0&limits=1000&name=.C3.88.C3.B0.C3.93.C2.AF1.C2.BA.C3.85B', 'ext': '瑞盈1号B'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940018&t=1&start=0&limits=1000&name=.C3.8C.C3.AC.C3.8C.C3.AC.C2.B7.C2.A2A', 'ext': '天天发A'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940038&t=1&start=0&limits=1000&name=.C3.8C.C3.AC.C3.8C.C3.AC.C2.B7.C2.A2C', 'ext': '天天发C'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940066&t=4&start=0&limits=1000&name=.C2.BA.C3.AA.C2.B9.C3.9B.C2.BB.C3.98.C2.B1.C2.A81.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '宏观回报1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940202&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X2', 'ext': '季季优先X2'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941225&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B08.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园8号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941240&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A614.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力14号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941106&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE1.C3.86.C3.9A', 'ext': '浦华1号A份额1期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941113&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE7.C3.86.C3.9A', 'ext': '浦华1号A份额7期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF5283&t=5&start=0&limits=1000&name=.C3.8D.C2.B6.C3.94.C3.B61.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '投增1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940098&t=5&start=0&limits=1000&name=.C3.92.C3.97.C3.88.C3.9A.C2.B1.C2.A62.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '易融宝2号(次级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940098&t=5&start=0&limits=1000&name=.C3.92.C3.97.C3.88.C3.9A.C2.B1.C2.A62.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '易融宝2号(次级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941163&t=5&start=0&limits=1000&name=.C3.93.C2.AF.C3.8C.C2.A91.C2.BA.C3.85', 'ext': '盈泰1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940132&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.881.C3.94.C3.82X1', 'ext': '月月优先1月X1'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941195&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB3.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见3号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941252&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB5.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见5号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940032&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C2.B7.C2.A2.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '月月发(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940335&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.883.C3.94.C3.82X10', 'ext': '月月优先3月X10'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940255&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX10', 'ext': '月月优先新享X10'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940248&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX3', 'ext': '月月优先新享X3'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940301&t=2&start=0&limits=1000&name=.C3.94.C3.B6.C3.87.C2.BF.C3.95.C2.AE.C3.88.C2.AF.C3.93.C3.85.C3.8F.C3.881.C2.BA.C3.85', 'ext': '增强债券优先1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940058&t=6&start=0&limits=1000&name=.C3.97.C3.8A.C3.88.C2.AF.C3.8D.C2.A8.C2.B7.C3.96.C2.BC.C2.B6A', 'ext': '资券通分级A'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941019&t=2&start=0&limits=1000&name=.C3.97.C3.8F.C2.BD.C3.B01.C2.BA.C3.85B.C2.BC.C2.B6', 'ext': '紫金1号B级'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940250&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX5', 'ext': '月月优先新享X5'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940006&t=5&start=0&limits=1000&name=.C3.94.C3.AC.C2.B8.C2.A3.C3.89.C2.A3.C3.A8.C3.B7', 'ext': '造福桑梓'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941157&t=5&start=0&limits=1000&name=.C3.96.C3.8A.C3.91.C2.BA.C3.92.C3.971.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE2.C3.86.C3.9A', 'ext': '质押易1号A份额2期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941158&t=5&start=0&limits=1000&name=.C3.96.C3.8A.C3.91.C2.BA.C3.92.C3.971.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE3.C3.86.C3.9A', 'ext': '质押易1号A份额3期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941155&t=5&start=0&limits=1000&name=.C3.96.C3.8A.C3.91.C2.BA.C3.92.C3.971.C2.BA.C3.85B.C2.B7.C3.9D.C2.B6.C3.AE', 'ext': '质押易1号B份额'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941259&t=5&start=0&limits=1000&name=.C3.96.C3.90.C2.BF.C3.86.C2.BD.C3.B0.C2.B2.C3.861.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '中科金财1号(次级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940039&t=5&start=0&limits=1000&name=.C3.96.C3.90.C3.96.C2.A4800.C3.94.C3.B6.C3.87.C2.BF', 'ext': '中证800增强'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF0581&t=5&start=0&limits=1000&name=.C2.B9.C2.B2.C3.93.C2.AE2.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '共赢2号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941182&t=5&start=0&limits=1000&name=.C2.BB.C3.95.C2.BB.C2.AA1.C2.BA.C3.85B.C2.B7.C3.9D.C2.B6.C3.AE', 'ext': '徽华1号B份额'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940207&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X7', 'ext': '季季优先X7'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941200&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B02.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园2号(次级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940005&t=5&start=0&limits=1000&name=.C2.BD.C3.B5.C3.89.C3.8F.C3.8C.C3.AD.C2.BB.C2.A8', 'ext': '锦上添花'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941114&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE8.C3.86.C3.9A', 'ext': '浦华1号A份额8期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941244&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB2.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见2号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940335&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.883.C3.94.C3.82X10', 'ext': '月月优先3月X10'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940262&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.884.C3.94.C3.82X2', 'ext': '月月优先4月X2'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940345&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X17', 'ext': '月月优先6月X17'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940312&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX12', 'ext': '月月优先半年X12'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940251&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX6', 'ext': '月月优先新享X6'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940308&t=2&start=0&limits=1000&name=.C3.94.C3.B6.C3.87.C2.BF.C3.95.C2.AE.C3.88.C2.AF.C3.93.C3.85.C3.8F.C3.888.C2.BA.C3.85', 'ext': '增强债券优先8号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941179&t=5&start=0&limits=1000&name=.C3.96.C3.87.C2.B7.C3.89.C3.89.C3.BA.C3.8E.C3.AF1.C2.BA.C3.85.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '智飞生物1号(风险级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940011&t=5&start=0&limits=1000&name=.C3.96.C3.9C.C3.86.C3.9A.C3.82.C3.96.C2.B6.C2.AF', 'ext': '周期轮动'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF5968&t=5&start=0&limits=1000&name=.C2.BB.C2.AA.C3.94.C3.B61.C2.BA.C3.85', 'ext': '华增1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941183&t=5&start=0&limits=1000&name=.C2.BB.C3.95.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE1.C3.86.C3.9A', 'ext': '徽华1号A份额1期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941235&t=5&start=0&limits=1000&name=.C2.BB.C3.9B.C3.94.C3.B31.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '慧泽1号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940201&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X1', 'ext': '季季优先X1'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941233&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B010.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园10号(次级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941114&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE8.C3.86.C3.9A', 'ext': '浦华1号A份额8期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941284&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A93.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰3号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941169&t=5&start=0&limits=1000&name=.C3.AE.C2.A3.C3.8C.C2.A9.C2.A1.C2.A4.C2.B2.C3.86.C2.B8.C2.BBFOF2.C2.BA.C3.85', 'ext': '睿泰·财富FOF2号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940008&t=5&start=0&limits=1000&name=.C3.8F.C3.96.C2.BD.C3.B0.C2.B9.C3.9C.C2.BC.C3.92', 'ext': '现金管家'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941194&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB1.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941254&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB6.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见6号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=S78688&t=5&start=0&limits=1000&name=.C2.B2.C2.A2.C2.B9.C2.BA.C2.BB.C3.B9.C2.BD.C3.B01.C2.BA.C3.85', 'ext': '并购基金1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940047&t=4&start=0&limits=1000&name=.C2.B2.C3.86.C2.B8.C2.BB2.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '财富2号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=S76682&t=5&start=0&limits=1000&name=.C2.BB.C2.AA.C3.93.C2.AF1.C2.BA.C3.85', 'ext': '华盈1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF5968&t=5&start=0&limits=1000&name=.C2.BB.C2.AA.C3.94.C3.B61.C2.BA.C3.85', 'ext': '华增1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940209&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X9', 'ext': '季季优先X9'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941112&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE6.C3.86.C3.9A', 'ext': '浦华1号A份额6期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941107&t=5&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85B.C2.B7.C3.9D.C2.B6.C3.AE', 'ext': '浦华1号B份额'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941413&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA3.C2.BA.C3.85.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6A2', 'ext': '浦华3号优先级A2'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941284&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A93.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰3号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941162&t=5&start=0&limits=1000&name=.C3.88.C3.99.C3.8C.C2.A91.C2.BA.C3.85', 'ext': '荣泰1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941506&t=5&start=0&limits=1000&name=.C3.88.C3.B0.C3.93.C2.AF1.C2.BA.C3.85A', 'ext': '瑞盈1号A'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941507&t=5&start=0&limits=1000&name=.C3.88.C3.B0.C3.93.C2.AF1.C2.BA.C3.85B', 'ext': '瑞盈1号B'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940247&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX2', 'ext': '月月优先新享X2'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941171&t=5&start=0&limits=1000&name=.C3.96.C3.90.C3.92.C3.B81.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '中银1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940058&t=6&start=0&limits=1000&name=.C3.97.C3.8A.C3.88.C2.AF.C3.8D.C2.A8.C2.B7.C3.96.C2.BC.C2.B6A', 'ext': '资券通分级A'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940002&t=5&start=0&limits=1000&name=.C3.97.C3.8F.C2.BD.C3.B02.C2.BA.C3.85', 'ext': '紫金2号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940037&t=2&start=0&limits=1000&name=.C3.97.C3.8F.C2.BD.C3.B0.C2.BB.C3.B5.C2.B1.C3.92.C3.94.C3.B6.C3.87.C2.BF', 'ext': '紫金货币增强'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940056&t=4&start=0&limits=1000&name=.C3.97.C3.B0.C3.8F.C3.AD.C2.BC.C2.BE.C2.BC.C2.BE.C2.B7.C2.A2.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '尊享季季发(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=S78988&t=5&start=0&limits=1000&name=.C2.B2.C2.A2.C2.B9.C2.BA.C2.BB.C3.B9.C2.BD.C3.B02.C2.BA.C3.85', 'ext': '并购基金2号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941238&t=5&start=0&limits=1000&name=.C2.B6.C2.A8.C3.94.C3.B66.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '定增6号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940214&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X14', 'ext': '季季优先X14'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941206&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A62.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力2号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941215&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A68.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力8号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941280&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A91.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940097&t=4&start=0&limits=1000&name=.C3.92.C3.97.C3.88.C3.9A.C2.B1.C2.A62.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '易融宝2号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940007&t=5&start=0&limits=1000&name=.C3.93.C3.85.C3.95.C2.AE.C2.BE.C2.AB.C3.91.C2.A1', 'ext': '优债精选'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940318&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX18', 'ext': '月月优先半年X18'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940325&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.97.C2.A8.C3.8F.C3.ADX5', 'ext': '月月优先专享X5'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940302&t=2&start=0&limits=1000&name=.C3.94.C3.B6.C3.87.C2.BF.C3.95.C2.AE.C3.88.C2.AF.C3.93.C3.85.C3.8F.C3.882.C2.BA.C3.85', 'ext': '增强债券优先2号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF8156&t=5&start=0&limits=1000&name=.C3.88.C3.BC.C3.81.C3.AC.C3.81.C3.AC.C2.BA.C2.BD1.C2.BA.C3.85', 'ext': '赛领领航1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941176&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB11.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见11号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941253&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB6.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见6号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940281&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.883.C3.94.C3.82X1', 'ext': '月月优先3月X1'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940282&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.883.C3.94.C3.82X2', 'ext': '月月优先3月X2'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940346&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X18', 'ext': '月月优先6月X18'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940254&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX9', 'ext': '月月优先新享X9'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940254&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX9', 'ext': '月月优先新享X9'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940300&t=2&start=0&limits=1000&name=.C3.94.C3.B6.C3.87.C2.BF.C3.95.C2.AE.C3.88.C2.AFC.C2.BC.C2.B6', 'ext': '增强债券C级'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940084&t=5&start=0&limits=1000&name=.C3.96.C3.8A.C3.91.C2.BA.C2.B1.C2.A61.C2.BA.C3.85.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '质押宝1号(风险级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941178&t=5&start=0&limits=1000&name=.C3.96.C3.87.C2.B7.C3.89.C3.89.C3.BA.C3.8E.C3.AF1.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '智飞生物1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940304&t=2&start=0&limits=1000&name=.C3.94.C3.B6.C3.87.C2.BF.C3.95.C2.AE.C3.88.C2.AF.C3.93.C3.85.C3.8F.C3.884.C2.BA.C3.85', 'ext': '增强债券优先4号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941257&t=5&start=0&limits=1000&name=.C3.96.C3.90.C2.BF.C3.86.C2.BD.C3.B0.C2.B2.C3.861.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '中科金财1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940011&t=5&start=0&limits=1000&name=.C3.96.C3.9C.C3.86.C3.9A.C3.82.C3.96.C2.B6.C2.AF', 'ext': '周期轮动'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940059&t=7&start=0&limits=1000&name=.C3.97.C3.8A.C3.88.C2.AF.C3.8D.C2.A8.C2.B7.C3.96.C2.BC.C2.B6B', 'ext': '资券通分级B'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940037&t=2&start=0&limits=1000&name=.C3.97.C3.8F.C2.BD.C3.B0.C2.BB.C3.B5.C2.B1.C3.92.C3.94.C3.B6.C3.87.C2.BFA', 'ext': '紫金货币增强A'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940003&t=5&start=0&limits=1000&name=.C3.97.C3.8F.C2.BD.C3.B03.C2.BA.C3.85', 'ext': '紫金3号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941300&t=2&start=0&limits=1000&name=.C3.97.C3.B0.C3.8F.C3.AD1.C2.BA.C3.85Z', 'ext': '尊享1号Z'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940019&t=2&start=0&limits=1000&name=.C2.B6.C2.A8.C2.B4.C3.A6.C2.B1.C2.A6', 'ext': '定存宝'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940067&t=5&start=0&limits=1000&name=.C2.BA.C3.AA.C2.B9.C3.9B.C2.BB.C3.98.C2.B1.C2.A81.C2.BA.C3.85.C2.A3.C2.A8.C3.86.C3.95.C3.8D.C2.A8.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '宏观回报1号(普通级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941184&t=5&start=0&limits=1000&name=.C2.BB.C3.95.C2.BB.C2.AA1.C2.BA.C3.85.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6A2', 'ext': '徽华1号优先级A2'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941191&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B01.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园1号(次级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941190&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B01.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941430&t=5&start=0&limits=1000&name=.C2.BD.C2.A1.C3.90.C3.901.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '健行1号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940005&t=5&start=0&limits=1000&name=.C2.BD.C3.B5.C3.89.C3.8F.C3.8C.C3.AD.C2.BB.C2.A8', 'ext': '锦上添花'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941246&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A616.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力16号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941285&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A93.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰3号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941400&t=5&start=0&limits=1000&name=.C3.8D.C2.B6.C3.88.C3.9A.C3.94.C3.B6.C3.80.C3.BB1.C2.BA.C3.85', 'ext': '投融增利1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941197&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB1.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见1号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940027&t=5&start=0&limits=1000&name=.C2.B1.C3.9C.C3.8F.C3.95', 'ext': '避险'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941238&t=5&start=0&limits=1000&name=.C2.B6.C2.A8.C3.94.C3.B66.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '定增6号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940100&t=4&start=0&limits=1000&name=.C2.B7.C3.A1.C3.8C.C2.A9.C2.B4.C3.B3.C2.B7.C3.A1A2', 'ext': '丰泰大丰A2'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=S76681&t=5&start=0&limits=1000&name=.C2.BB.C2.AA.C3.8E.C3.881.C2.BA.C3.85', 'ext': '华稳1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941234&t=5&start=0&limits=1000&name=.C2.BB.C3.9B.C3.94.C3.B31.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '慧泽1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940030&t=5&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C2.B7.C2.A2.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '季季发(风险级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940206&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X6', 'ext': '季季优先X6'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941202&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A63.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力3号(中间级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941108&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE2.C3.86.C3.9A', 'ext': '浦华1号A份额2期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941281&t=5&start=0&limits=1000&name=.C3.86.C3.96.C3.8C.C2.A91.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '浦泰1号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941165&t=5&start=0&limits=1000&name=.C3.88.C2.AB.C3.87.C3.B2.C3.95.C2.AE.C3.88.C2.A8.C2.BB.C3.BA.C2.BB.C3.A11.C2.BA.C3.85', 'ext': '全球债权机会1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940004&t=5&start=0&limits=1000&name=.C2.B2.C2.BD.C2.B2.C2.BD.C3.8E.C2.AA.C3.93.C2.AF', 'ext': '步步为盈'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941198&t=5&start=0&limits=1000&name=.C2.B6.C2.A8.C3.94.C3.B63.C2.BA.C3.85', 'ext': '定增3号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941153&t=5&start=0&limits=1000&name=.C2.B9.C2.B2.C3.93.C2.AE1.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '共赢1号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940029&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C2.B7.C2.A2.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '季季发(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940211&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X11', 'ext': '季季优先X11'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940202&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X2', 'ext': '季季优先X2'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941233&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B010.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园10号(次级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941242&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A614.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力14号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941242&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A614.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力14号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941247&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A616.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力16号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941214&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A68.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力8号(中间级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940042&t=5&start=0&limits=1000&name=.C2.B8.C3.9F.C3.8A.C3.95.C3.92.C3.A6.C3.95.C2.AE', 'ext': '高收益债'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF0581&t=5&start=0&limits=1000&name=.C2.B9.C2.B2.C3.93.C2.AE2.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '共赢2号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941262&t=5&start=0&limits=1000&name=.C2.B9.C3.89.C3.88.C2.A8.C3.97.C3.B0.C3.8F.C3.AD1.C2.BA.C3.85', 'ext': '股权尊享1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940066&t=4&start=0&limits=1000&name=.C2.BA.C3.AA.C2.B9.C3.9B.C2.BB.C3.98.C2.B1.C2.A81.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '宏观回报1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=S76681&t=5&start=0&limits=1000&name=.C2.BB.C2.AA.C3.8E.C3.881.C2.BA.C3.85', 'ext': '华稳1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941223&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B07.C2.BA.C3.85.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6', 'ext': '家园7号优先级'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941247&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A616.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力16号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941210&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A67.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力7号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941112&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE6.C3.86.C3.9A', 'ext': '浦华1号A份额6期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=SF5283&t=5&start=0&limits=1000&name=.C3.8D.C2.B6.C3.94.C3.B61.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '投增1号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941244&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB2.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见2号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940212&t=4&start=0&limits=1000&name=.C2.BC.C2.BE.C2.BC.C2.BE.C3.93.C3.85.C3.8F.C3.88X12', 'ext': '季季优先X12'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941232&t=5&start=0&limits=1000&name=.C2.BC.C3.92.C3.94.C2.B010.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '家园10号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940126&t=5&start=0&limits=1000&name=.C2.BD.C2.A1.C2.BF.C2.B5.C3.96.C3.90.C2.B9.C3.BA', 'ext': '健康中国'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941431&t=5&start=0&limits=1000&name=.C2.BD.C2.A1.C3.90.C3.901.C2.BA.C3.85.C2.A3.C2.A8.C2.B4.C3.8E.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '健行1号(次级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941240&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A614.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力14号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941202&t=5&start=0&limits=1000&name=.C2.BE.C3.9B.C3.81.C2.A63.C2.BA.C3.85.C2.A3.C2.A8.C3.96.C3.90.C2.BC.C3.A4.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '聚力3号(中间级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941106&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE1.C3.86.C3.9A', 'ext': '浦华1号A份额1期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940054&t=5&start=0&limits=1000&name=.C3.92.C3.97.C3.88.C3.9A.C2.B1.C2.A61.C2.BA.C3.85', 'ext': '易融宝1号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941177&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB11.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见11号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941176&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB11.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见11号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941249&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB15.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见15号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941196&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB3.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见3号(优先级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940262&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.884.C3.94.C3.82X2', 'ext': '月月优先4月X2'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940317&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX17', 'ext': '月月优先半年X17'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940253&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX8', 'ext': '月月优先新享X8'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940012&t=5&start=0&limits=1000&name=.C3.97.C3.8F.C2.BD.C3.B0.C3.81.C3.BA.C2.A3.C2.A8QDII.C2.A3.C2.A9', 'ext': '紫金龙(QDII)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940028&t=1&start=0&limits=1000&name=.C3.8C.C3.AC.C3.8C.C3.AC.C2.B7.C2.A2B', 'ext': '天天发B'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941177&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB11.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见11号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941197&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB1.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见1号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941252&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB5.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见5号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940332&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.881.C3.94.C3.82X3', 'ext': '月月优先1月X3'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940343&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X15', 'ext': '月月优先6月X15'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940345&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X17', 'ext': '月月优先6月X17'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940314&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX14', 'ext': '月月优先半年X14'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940316&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX16', 'ext': '月月优先半年X16'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940319&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX19', 'ext': '月月优先半年X19'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940006&t=5&start=0&limits=1000&name=.C3.94.C3.AC.C2.B8.C2.A3.C3.89.C2.A3.C3.A8.C3.B7', 'ext': '造福桑梓'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941249&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB15.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见15号(进取级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940180&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.881.C3.94.C3.82X7', 'ext': '月月优先1月X7'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941500&t=5&start=0&limits=1000&name=.C3.96.C3.90.C2.B5.C3.8D.C3.86.C3.80.C2.BC.C2.B6.C3.95.C2.AE1.C2.BA.C3.85', 'ext': '中低评级债1号'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941174&t=5&start=0&limits=1000&name=.C3.96.C3.90.C3.92.C3.B81.C2.BA.C3.8512.C2.B8.C3.B6.C3.94.C3.822.C3.86.C3.9A', 'ext': '中银1号12个月2期'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941325&t=4&start=0&limits=1000&name=.C3.97.C3.B0.C3.8F.C3.AD1.C2.BA.C3.85X21', 'ext': '尊享1号X21'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941256&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB7.C2.BA.C3.85.C2.A3.C2.A8.C2.BD.C3.B8.C3.88.C2.A1.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见7号(进取级)'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941255&t=5&start=0&limits=1000&name=.C3.94.C2.B6.C2.BC.C3.BB7.C2.BA.C3.85.C2.A3.C2.A8.C3.93.C3.85.C3.8F.C3.88.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '远见7号(优先级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940033&t=5&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C2.B7.C2.A2.C2.A3.C2.A8.C2.B7.C3.A7.C3.8F.C3.95.C2.BC.C2.B6.C2.A3.C2.A9', 'ext': '月月发(风险级)'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940263&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.884.C3.94.C3.82X3', 'ext': '月月优先4月X3'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940346&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X18', 'ext': '月月优先6月X18'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940313&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX13', 'ext': '月月优先半年X13'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940317&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX17', 'ext': '月月优先半年X17'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940303&t=2&start=0&limits=1000&name=.C3.94.C3.B6.C3.87.C2.BF.C3.95.C2.AE.C3.88.C2.AF.C3.93.C3.85.C3.8F.C3.883.C2.BA.C3.85', 'ext': '增强债券优先3号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940307&t=2&start=0&limits=1000&name=.C3.94.C3.B6.C3.87.C2.BF.C3.95.C2.AE.C3.88.C2.AF.C3.93.C3.85.C3.8F.C3.887.C2.BA.C3.85', 'ext': '增强债券优先7号'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941157&t=5&start=0&limits=1000&name=.C3.96.C3.8A.C3.91.C2.BA.C3.92.C3.971.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE2.C3.86.C3.9A', 'ext': '质押易1号A份额2期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941173&t=5&start=0&limits=1000&name=.C3.96.C3.90.C3.92.C3.B81.C2.BA.C3.856.C2.B8.C3.B6.C3.94.C3.821.C3.86.C3.9A', 'ext': '中银1号6个月1期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941109&t=4&start=0&limits=1000&name=.C3.86.C3.96.C2.BB.C2.AA1.C2.BA.C3.85A.C2.B7.C3.9D.C2.B6.C3.AE3.C3.86.C3.9A', 'ext': '浦华1号A份额3期'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940342&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.886.C3.94.C3.82X14', 'ext': '月月优先6月X14'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940313&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C2.B0.C3.AB.C3.84.C3.AAX13', 'ext': '月月优先半年X13'}, { 'url': 'http://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940250&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX5', 'ext': '月月优先新享X5'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940252&t=4&start=0&limits=1000&name=.C3.94.C3.82.C3.94.C3.82.C3.93.C3.85.C3.8F.C3.88.C3.90.C3.82.C3.8F.C3.ADX7', 'ext': '月月优先新享X7'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940037&t=2&start=0&limits=1000&name=.C3.97.C3.8F.C2.BD.C3.B0.C2.BB.C3.B5.C2.B1.C3.92.C3.94.C3.B6.C3.87.C2.BFA', 'ext': '紫金货币增强A'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941155&t=5&start=0&limits=1000&name=.C3.96.C3.8A.C3.91.C2.BA.C3.92.C3.971.C2.BA.C3.85B.C2.B7.C3.9D.C2.B6.C3.AE', 'ext': '质押易1号B份额'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=941019&t=2&start=0&limits=1000&name=.C3.97.C3.8F.C2.BD.C3.B01.C2.BA.C3.85B.C2.BC.C2.B6', 'ext': '紫金1号B级'}, { 'url': 'https://htamc.htsc.com.cn/jhcp/JhcpJzgx/jhjzList.do?productCode=940059&t=7&start=0&limits=1000&name=.C3.97.C3.8A.C3.88.C2.AF.C3.8D.C2.A8.C2.B7.C3.96.C2.BC.C2.B6B', 'ext': '资券通分级B'}, ] def parse_item(self, response): fund_name = response.meta['ext'] f_list = json.loads(response.text)["items"] for i in f_list: item = GGFundNavItem() statistic_date = i['JZRQ'] if 'VAL3' in response.text: d7_annualized = i['VAL1'].replace('--', '') income_value_per_ten_thousand = i['VAL3'].replace('--', '') item['d7_annualized_return'] = float( d7_annualized) if d7_annualized is not None and d7_annualized != '' else None item['income_value_per_ten_thousand'] = float( income_value_per_ten_thousand) if income_value_per_ten_thousand is not None and income_value_per_ten_thousand != '' else None elif 'VAL4' in response.text: annualized_return = i['VAL4'].replace('--', '').replace('%', '') item['annualized_return'] = float( annualized_return) if annualized_return is not None and annualized_return != '' else None else: if 'VAL1' in i and 'VAL2' in i: nav = i['VAL1'].replace('--', '') added_nav = i['VAL2'].replace('--', '') item['nav'] = float(nav) if nav is not None and nav != '' else None item['added_nav'] = float(added_nav) if added_nav is not None and added_nav != '' else None item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class ChanganxintuoSpider(GGFundNoticeSpider): name = 'FundNotice_Changanxintuo' sitename = '长安信托' entry = 'https://www.xitic.cn/' cookies = '_shcdcms=74336f879f3549a1864085b13391c5ee; TS01caa770=01b2148ee2c8064dbe39ba558349546fcfc101cf6d2138303b2327f84fa853465da02a171063542a4ec4934600b0850314cf494048e99feab8fc2b49400325a6f8919a9cddaa8ea76cfd778773e46e7d8bde15a255; JSESSIONID=74336f879f3549a1864085b13391c5ee; __guid=177915299.1109513210227355400.1527492594004.2322; BIGipServerEweb_nginx_pool=1731428362.20480.0000; UM_distinctid=163a5a75e404a0-000d76d879ca2a-6b1b1279-1fa400-163a5a75e413f7; monitor_count=11; CNZZDATA1000026426=270451545-1527487437-https%253A%252F%252Fwww.caitc.cn%252F%7C1527492871; TS01afccea=01b2148ee2d3913314353e011913e4461f938511fba1e0726af63cea930dd444eda69574ad78de3e2b703004d60907d2f5f0beae6f9cc201be90962888337773d6fd27084f' ips = [ { 'url': 'https://www.caitc.cn/home/productReportSearch.jspx?reportType=0&title=&page=1', }, { 'url': 'https://www.caitc.cn/home/productReportSearch.jspx?reportType=3&title=&page=1', }, ] def parse_item(self, response): rows = response.xpath('//ul[@class="cmnList"]/li') for row in rows: url = row.xpath('./a/@href').extract_first() if url == 'javascript:void(0)': # <a href="javascript:void(0)" onclick="getPdf('/home','/projectText/201510201386/1010/101002/144643001676888.pdf')"> # r",\'(\S+)\'" 意思是: 以逗号开始的截取后面的单引号里面的多个非空字符,单引号里面的东西用()定位 on_click = row.xpath('./a/@onclick').re_first(r",\'(\S+)\'") on_click = str('/uploads/fore') + on_click url = on_click url = urljoin(get_base_url(response), url) title = row.xpath('./a/text()').extract_first().replace('\t', '').replace('\r', '').replace('\n', '') publish_time = row.xpath('./span/text()').extract_first() publish_time = datetime.strptime(publish_time, '%Y/%m/%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item next_url = response.xpath('//div[@class="pdtPaging"]/a[text()="下一页"]/@href').extract_first() if next_url: next_url = urljoin(get_base_url(response), next_url) self.ips.append({ 'url': next_url, 'ref': response.url }) <file_sep># coding:utf-8 import json from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from FundNavSpiders import FormRequest class GeShangLiCaiSpider(GGFundNavSpider): name = 'FundNav_GeShangLiCai' sitename = '格上理财' channel = '第三方净值' username = '13916427906' password = '<PASSWORD>' def start_requests(self): payload = '{"password":"<PASSWORD>","username":"13916427906"}' yield FormRequest( url='https://www.licai.com/api/v1/auth/login/pass', method='PUT', body=payload, headers={ 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json, text/plain, */*' }, callback=self.parse_pre_fund ) def parse_pre_fund(self, response): payload = {"offset": '0', "sortName": "rr_since_this_year", "sortType": "-", "investment_strategy_1": "-1", "investment_strategy_2": "0", "annualized_rr_since_start": "-1", "investment_risk": "-1", "achievement_since_this_year": "0", "achievement_in_1_year": "0", "achievement_in_3_year": "0", "achievement_in_5_year": "0", "manager_type": "0", "amac_private_aum": "0", "establishment_date": "0", "product_status": "-1", "keyname": ""} self.fps.append({ 'url': "https://www.licai.com/api/v1/private/productlist", 'headers': { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', 'Referer': 'https://www.licai.com/simu/product/', 'Content-Type': 'application/json; charset=utf-8', }, 'body': json.dumps(payload), 'ext': 0 }) def parse_fund(self, response): next_offset = response.meta['ext'] + 50 fund_urls = json.loads(response.text)['result'] if fund_urls: for url in fund_urls: fundname = url['product_full_name'] fund_id = url['product_id'] self.ips.append({ 'url': "https://www.licai.com/simu/product/" + fund_id + '.html', 'ref': response.url, 'ext': fundname }) self.fps.append({ 'url': "https://www.licai.com/api/v1/private/productlist", 'ref': response.url, 'headers': { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', 'Referer': 'https://www.licai.com/simu/product/', 'Content-Type': 'application/json; charset=utf-8', }, 'body': json.dumps({"offset": str(next_offset), "sortName": "rr_since_this_year", "sortType": "-", "investment_strategy_1": "-1", "investment_strategy_2": "0", "annualized_rr_since_start": "-1", "investment_risk": "-1", "achievement_since_this_year": "0", "achievement_in_1_year": "0", "achievement_in_3_year": "0", "achievement_in_5_year": "0", "manager_type": "0", "amac_private_aum": "0", "establishment_date": "0", "product_status": "-1", "keyname": ""}), 'ext': next_offset }) def parse_item(self, response): fund_name = response.meta['ext'] fund_list = response.xpath('//div[@name ="data"]/div[@class = "nr_con"][1]//table[@class = "tab tab_01"]//tr') for i in fund_list: t = i.xpath('td//text()').extract() statistic_date = ''.join(t[0].split()) nav = ''.join(t[1].split()) # 网站复权累计净值不抓取 item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) yield item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class HuaLinSecuritySpider(GGFundNavSpider): name = 'FundNav_HuaLinSecurity' sitename = '华林证券' channel = '券商资管净值' ips = [] fund_dict = {'富贵竹9号': '8', '富贵竹12号': '8', '富贵竹13号': '136', '富贵竹2号': '0', '富贵竹5号': '3', '富贵竹3号': '1', '富贵竹11号': '7', '富贵竹17号': '137', '满天星1号': '140', } for (fund_name, fund_code) in fund_dict.items(): ips.append({ 'url': 'https://mall.chinalions.cn/servlet/financial/IndexAction?function=AjaxPricePage&product_egroup={}'.format( fund_code), 'ext': {'pg': 1, 'fund_code': fund_code, 'fund_name': fund_name}, 'form': {'curPage': '1', 'numPerPage': '17'} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath("//tr")[1:] for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = row.xpath("./td[1]").re_first('\d+-\d+-\d+') item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row.xpath("./td[2]").re_first('>\s*([0-9.]+)\s*<') item['nav'] = float(nav) if nav is not None else None added_nav = row.xpath("./td[5]").re_first('>\s*([0-9.]+)\s*<') item['added_nav'] = float(added_nav) if added_nav is not None else None yield item # ext = response.meta['ext'] # pg = ext['pg'] # fund_code = ext['fund_code'] # if pg < 10: # pg += 1 # self.ips.append({ # 'url': 'https://mall.chinalions.cn/servlet/financial/IndexAction?function=AjaxPricePage&product_egroup={0}'.format( # fund_code), # 'ext': {'pg': pg, 'fund_code': fund_code, 'fund_name': fund_name}, # 'from': {'curPage': str(pg), 'numPerPage': '17'}, # 'headers': {'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded'} # }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-19 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import Request class TuoPuTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_TuoPuTouZiInvest' sitename = '拓璞投资' channel = '投顾净值' allowed_domains = ['www.top-investment.cn'] ips = [ { 'url': 'http://www.top-investment.cn/product1.php?infoid=9&sid=12', 'ext': {'fund_name': '万联拓璞1号'} }, ] def start_requests(self): yield Request( url='http://www.top-investment.cn/product.php', callback=self.fund_list_name) def fund_list_name(self, response): fund_urls = response.xpath("//div[@class='container'][1]/table//tr/td[1]/table[2]//tr") for url in fund_urls: fund_name = url.xpath(".//text()").extract()[1] fund_url = url.xpath(".//@href").extract_first() if fund_url: self.fps.append({ 'url': 'http://www.top-investment.cn/' + fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_fund(self, response): fund_url = response.xpath("//a[contains(., '产品净值')]//@href").extract_first() fund_name = response.meta['ext']['fund_name'] if fund_url: self.ips.append({ 'url': 'http://www.top-investment.cn/' + fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) else: self.ips.append({ 'url': response.url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath("//div[@class='ff']//tr") fund_name = response.meta['ext']['fund_name'] for row in rows: statistic_dates = row.xpath("./td[1]//text()").extract() statistic_date = ''.join(statistic_dates).replace('/', '-') nav = row.xpath("./td[2]//text()").extract_first() added_nav = row.xpath("./td[3]//text()").extract_first() if '20' in statistic_date: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department:保障部 # Author:王卓诚 # Create_Date:2018-05-28 from datetime import datetime from scrapy import Request from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class WeiLuInvestSpider(GGFundNavSpider): name = 'FundNav_WeiLuInvest' sitename = '围炉投资' channel = '投顾净值' allowed_domains = ['www.valuefund.cnm'] cookies = 'PHPSESSID=r8d5eaibe3dnsca0lrn3phdvn6; 480cc6234107423cdd913fecaebc469a=86; think_template=default' username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'http://www.valuefund.cn/index.php/Product_index_navid_24.html', 'ref': 'http://www.valuefund.cn' }] def start_requests(self): href = 'userName=%s&password=%s&autoLogin=1' % (self.username, self.password) yield Request( url='http://www.valuefund.cn/index.php/Home/Members_ajaxLogin.html?' + href) def parse_fund(self, response): arul = response.xpath('//div[@class="row pro_list"]/div[@class="col-lg-12 col-md-12 col-sm-12"]') for uu in arul: url = uu.xpath('a/@href').extract_first() url = url.replace('/index.php/Product_details_navid_24_goodsid_', '').replace('.html', '') url2 = 'http://www.valuefund.cn/index.php/Product_details_navid_24_goodsid_' + url + '_type_unit_p_1.html' pname = uu.xpath('a/div[1]/h4/text()').extract_first() self.ips.append({ 'url': url2, 'ref': response.url, 'pg': 1, 'ext': {'pname': pname, 'pid': url} }) def parse_item(self, response): rows = response.xpath("//table[@class='table table-striped table-hover text-center']/tbody/tr") fund_name = response.meta['ext']['pname'] pid = response.meta['ext']['pid'] for row in rows: statistic_date = row.xpath("./td[1]//text()").extract_first() nav = row.xpath("./td[2]//text()").extract_first() added_nav = row.xpath("./td[3]//text()").extract_first() if len(statistic_date) == 10: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if added_nav else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item if len(rows) > 2: next_pg = response.meta['pg'] + 1 self.ips.append({ 'url': 'http://www.valuefund.cn/index.php/Product_details_navid_24_goodsid_' + pid + '_type_unit_p_' + str( next_pg) + '.html', 'pg': next_pg, 'ext': {'pname': fund_name, 'pid': pid} }) <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-06 from datetime import datetime from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class MingHeInvestSpider(GGFundNavSpider): name = 'FundNav_MingHeInvest' sitename = '明河投资' channel = '投顾净值' username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'http://www.river-fund.com/index.php?m=product&c=index&a=net&catid=1', }] def start_requests(self): yield FormRequest(url='http://www.river-fund.com/index.php?m=users&c=index&a=login', formdata={'id_number': self.username, 'password': self.password, 'type': 'browse'}, meta={ 'dont_redirect': True, 'handle_httpstatus_list': [302, 301] }) def parse_fund(self, response): ips_list = response.css('div.aboutWarpShow div.warpLfMune a::attr(href)').extract() name_list = response.css('div.aboutWarpShow div.warpLfMune a::text').extract() for ips_url, f_name in zip(ips_list, name_list): self.ips.append({ 'url': ips_url + '&page=1', 'ref': response.url, 'pg': 1, 'ext': f_name }) def parse_item(self, response): rows = response.css('table.tableStyle.overvieTOP tr')[1:] if rows: for r in rows: row = r.xpath('td//text()').extract() date = row[1] nav = row[2] add_nav = row[3] fund_name = response.meta['ext'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(add_nav) if add_nav is not None else None yield item next_pg = response.meta['pg'] + 1 self.ips.append({ 'url': re.sub('\d+$', str(next_pg), response.url), 'ref': response.url, 'pg': next_pg, 'ext': response.meta['ext'] }) <file_sep>from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class YiFanAssetSpider(GGFundNavSpider): name = 'FundNav_YiFanAsset' sitename = '易凡资产' channel = '投顾净值' username = '13916427906' password = '<PASSWORD>' cookies = "CODEIMG=e2a7555f7cabd6e31aef45cb8cda4999; MUSER=13916427906; MENAME=%E9%83%91%E7%9B%8A%E6%98%8E; MEMBERID=248; MEMBERTYPE=%E4%B8%AA%E4%BA%BA%E5%90%88%E6%A0%BC%E6%8A%95%E8%B5%84%E8%80%85; MEMBERTYPEID=35; ZC=d54dc3f140e0b9cf94769bf2fe887796" fps = [{'url': 'http://www.zj-yifan.com/product/class/', 'ref': None}] def parse_fund(self, response): funds = response.xpath( '//*[@id="content"]/div[2]//div[@class="pdv_border"]/div[2]//div[@class="picFit"]/a/@href').extract() for url in funds: url = urljoin(get_base_url(response), url) self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'page': '1','url': url} }) def parse_item(self, response): ext = response.meta['ext'] url = ext['url'] page = int(ext['page']) next_page = response.xpath('//*[@id="productcontent"]/div[3]/div[2]/select[@name="page"]/option[last()]/text()').re_first(r'(\d+)') fund_name = response.xpath('//*[@id="prodtitle"]/text()').extract_first() rows = response.xpath('//*[@id="productcontent"]/div[3]/table//tr') for row in rows[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url nav = row.xpath('./td[1]/text()').extract_first() item['nav'] = float(nav) added_nav = row.xpath('./td[2]/text()').extract_first() item['added_nav'] = float(added_nav) statistic_date = row.xpath('./td[3]/text()').extract_first() item['statistic_date'] = datetime.strptime(statistic_date, '%Y%m%d') yield item if page < int(next_page): self.ips.append({ 'url': url+'&page='+str(page+1), 'ref': response.url, 'ext': {'page': str(page+1), 'url': url} }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class YingDunAssetNoticeSpider(GGFundNoticeSpider): name = 'FundNotice_YingDunAssetNotice' sitename = '盈盾资本' entry = 'http://www.profitshields.cn/' ips = [{'url': 'http://www.profitshields.com/html/news/gongsi/list_1.html', 'ref': 'http://www.profitshields.com/index.html', 'ext': {'page': '1'}}] def parse_item(self, response): next_url = response.xpath('/html/body/div[3]//ul[@class="pagelist"]/li/a[text()="下一页"]/@href').extract_first() rows = response.xpath('/html/body/div[3]//div[@class="xinwen"]/dl/dt') for row in rows: title = row.xpath('./a/text()').extract_first() url = row.xpath('./a/@href').extract_first() publish_time = row.xpath('./span/text()').extract_first() publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = urljoin(get_base_url(response), url) item['title'] = title item['publish_time'] = publish_time yield item if next_url: next_url = urljoin(get_base_url(response), next_url) self.ips.append({ 'url': next_url, 'ref': response.url }) <file_sep>import hashlib import traceback from decimal import Decimal from datetime import datetime from urllib.parse import quote from scrapy import Item, Field from scrapy import Request, FormRequest from ggmssql.pool import Pool from GGScrapy import GGSpider from GGScrapy import MultiPartFormRequest import config # 基金净值Spider基类 class GGFundNavSpider(GGSpider): custom_settings = { 'ITEM_PIPELINES': {'FundNavSpiders.GGFundNavPipeline': 300} } dbPool = Pool(config.fund_nav['db']['host'], config.fund_nav['db']['port'], config.fund_nav['db']['user'], config.fund_nav['db']['pswd'], config.fund_nav['db']['name'], timeout=config.fund_nav['db']['timeout']) dbTable = config.fund_nav['db']['table'] fps = [] # fund (list) pages ips = [] # item (list) pages def request_next(self): if not (self.ips or self.fps): if hasattr(self, 'gen_request') and callable(self.gen_request): request = self.gen_request() if isinstance(request, Request): return request ps = self.ips or self.fps # pages pf = self.parse_item if self.ips else self.parse_fund # parse function if ps: pi = ps.pop(0) # page info pg = pi['pg'] if 'pg' in pi else None ext = pi['ext'] if 'ext' in pi else {} url = pi['url'] if 'url' in pi else None req_url = url(pg) if callable(url) else url ref = pi['ref'] if 'ref' in pi else None req_ref = ref(pg) if callable(ref) else ref self.logger.info('Preparing Request <%s> %s', req_url, {'pg': pg, 'ext': ext}) headers = pi['headers'] if 'headers' in pi else {} headers = headers if isinstance(headers, dict) else {} headers['Referer'] = req_ref meta = { 'pi': pi, 'pg': pg, 'url': url, 'ref': ref, 'ext': ext, 'headers': headers, } gg_reset_cookies = pi.get('gg_reset_cookies', None) if gg_reset_cookies is not None: meta['gg_reset_cookies'] = gg_reset_cookies dont_redirect = pi.get('dont_redirect', None) if dont_redirect is not None: meta['dont_redirect'] = dont_redirect dont_retry = pi.get('dont_retry', None) if dont_retry is not None: meta['dont_retry'] = dont_retry max_retry_times = pi.get('max_retry_times', None) if max_retry_times is not None: meta['max_retry_times'] = max_retry_times gg_retry_wait = pi.get('gg_retry_wait', None) if gg_retry_wait is not None: meta['gg_retry_wait'] = gg_retry_wait retry_http_codes = pi.get('retry_http_codes', None) if retry_http_codes is not None: meta['retry_http_codes'] = retry_http_codes handle_httpstatus_list = pi.get('handle_httpstatus_list', None) if handle_httpstatus_list is not None: meta['handle_httpstatus_list'] = handle_httpstatus_list handle_httpstatus_all = pi.get('handle_httpstatus_all', None) if handle_httpstatus_all is not None: meta['handle_httpstatus_all'] = handle_httpstatus_all mform = pi['mform'] if 'mform' in pi else None if mform is not None: formdata = {} for (k, v) in mform.items(): v = v(pg) if callable(v) else v formdata[k] = v meta['mform'] = mform return MultiPartFormRequest(url=req_url, dont_filter=True, callback=pf, method='POST', headers=headers, formdata=formdata, meta=meta) form = pi['form'] if 'form' in pi else None if form is not None: formdata = {} for (k, v) in form.items(): v = v(pg) if callable(v) else v formdata[k] = v meta['form'] = form return FormRequest(url=req_url, dont_filter=True, callback=pf, method='POST', headers=headers, formdata=formdata, meta=meta) body = pi['body'] if 'body' in pi else None body = body(pg) if callable(body) else body method = 'POST' if body else 'GET' meta['body'] = body return Request(req_url, dont_filter=True, callback=pf, method=method, headers=headers, body=body, meta=meta) def get_last_statistic_date(self, fund_name): last_statistic_date = datetime.min conn = self.dbPool.acquire() cursor = conn.cursor() try: table = self.dbTable cursor.execute( 'SELECT TOP 1 statistic_date FROM ' + table + ' WHERE sitename=%s AND channel=%s AND fund_name=%s ORDER BY statistic_date DESC', (self.sitename, self.channel, fund_name)) row = cursor.fetchone() last_statistic_date = row['statistic_date'] if row else last_statistic_date finally: cursor.close() self.dbPool.release(conn) return last_statistic_date def parse_fund(self, response): pass def parse_item(self, response): pass # 基金净值Item class GGFundNavItem(Item): hkey = Field() # 哈希唯一 groupname = Field() # 分组名称 sitename = Field() # 站点名称 channel = Field() # 频道名称 url = Field() # 链接地址 fund_name = Field() # 基金名称 statistic_date = Field() # 统计日期 fund_code = Field() # 基金代码 nav = Field() # 单位净值(单位: 元) added_nav = Field() # 累计净值(单位: 元) nav_2 = Field() # 含业绩报酬的单位净值(单位: 元) added_nav_2 = Field() # 含业绩报酬的累计单位净值(单位: 元) total_nav = Field() # 总资产净值(单位: 元) share = Field() # 资产份额(单位: 份) income_value_per_ten_thousand = Field() # 每万份计划收益(单位: 元) d7_annualized_return = Field() # 7日年化收益率(单位: %) d30_annualized_return = Field() # 30日年化收益率(单位: %) annualized_return = Field() # 预估收益率(单位: %) d7_floating_return = Field() # 浮动七日收益率(单位: %) # 基金净值Pipeline class GGFundNavPipeline(object): def process_item(self, item, spider): try: sitename = item.get('sitename', getattr(spider, 'sitename', None)) sitename = sitename.strip() if isinstance(sitename, str) else None sitename = None if sitename == '' else sitename assert sitename is not None channel = item.get('channel', getattr(spider, 'channel', None)) channel = channel.strip() if isinstance(channel, str) else None channel = None if channel == '' else channel assert channel is not None statistic_date = item.get('statistic_date', None) assert isinstance(statistic_date, datetime) statistic_date = statistic_date.strftime('%Y-%m-%d') fund_name = item.get('fund_name', None) fund_name = fund_name.strip() if isinstance(fund_name, str) else None fund_name = None if fund_name == '' else fund_name assert fund_name is not None conn = spider.dbPool.acquire() cursor = conn.cursor() try: cursor.execute( 'SELECT TOP 1 hkey,fund_code,url,nav,added_nav,nav_2,added_nav_2,total_nav,share' ',income_value_per_ten_thousand,d7_annualized_return,d30_annualized_return,annualized_return' + ' FROM ' + spider.dbTable + ' WHERE sitename=%s AND channel=%s AND statistic_date=%s AND fund_name=%s ORDER BY tmstamp', (sitename, channel, statistic_date, fund_name,)) row = cursor.fetchone() or {} groupname = item.get('groupname', getattr(spider, 'groupname', row.get('groupname', None))) groupname = groupname.strip() if isinstance(groupname, str) else None groupname = None if groupname == '' else groupname fund_code = item.get('fund_code', row.get('fund_code', None)) fund_code = fund_code.strip() if isinstance(fund_code, str) else None fund_code = None if fund_code == '' else fund_code url = item.get('url', row.get('url', None)) url = url.decode() if isinstance(url, bytes) else url url = url.strip() if isinstance(url, str) else None url = None if url == '' else url nav = item.get('nav', row.get('nav', None)) nav = Decimal(nav) if isinstance(nav, int) else nav nav = Decimal(str(nav)) if isinstance(nav, float) else nav nav = nav.normalize() if isinstance(nav, Decimal) else nav assert nav is None or isinstance(nav, Decimal) added_nav = item.get('added_nav', row.get('added_nav', None)) added_nav = Decimal(added_nav) if isinstance(added_nav, int) else added_nav added_nav = Decimal(str(added_nav)) if isinstance(added_nav, float) else added_nav added_nav = added_nav.normalize() if isinstance(added_nav, Decimal) else added_nav assert added_nav is None or isinstance(added_nav, Decimal) nav_2 = item.get('nav_2', row.get('nav_2', None)) nav_2 = Decimal(nav_2) if isinstance(nav_2, int) else nav_2 nav_2 = Decimal(str(nav_2)) if isinstance(nav_2, float) else nav_2 nav_2 = nav_2.normalize() if isinstance(nav_2, Decimal) else nav_2 assert nav_2 is None or isinstance(nav_2, Decimal) added_nav_2 = item.get('added_nav_2', row.get('added_nav_2', None)) added_nav_2 = Decimal(added_nav_2) if isinstance(added_nav_2, int) else added_nav_2 added_nav_2 = Decimal(str(added_nav_2)) if isinstance(added_nav_2, float) else added_nav_2 added_nav_2 = added_nav_2.normalize() if isinstance(added_nav_2, Decimal) else added_nav_2 assert added_nav_2 is None or isinstance(added_nav_2, Decimal) total_nav = item.get('total_nav', row.get('total_nav', None)) total_nav = Decimal(total_nav) if isinstance(total_nav, int) else total_nav total_nav = Decimal(str(total_nav)) if isinstance(total_nav, float) else total_nav total_nav = total_nav.normalize() if isinstance(total_nav, Decimal) else total_nav assert total_nav is None or isinstance(total_nav, Decimal) share = item.get('share', row.get('share', None)) share = Decimal(share) if isinstance(share, int) else share share = Decimal(str(share)) if isinstance(share, float) else share share = share.normalize() if isinstance(share, Decimal) else share assert share is None or isinstance(share, Decimal) income_value_per_ten_thousand = item.get('income_value_per_ten_thousand', row.get('income_value_per_ten_thousand', None)) income_value_per_ten_thousand = Decimal(income_value_per_ten_thousand) if isinstance( income_value_per_ten_thousand, int) else income_value_per_ten_thousand income_value_per_ten_thousand = Decimal(str(income_value_per_ten_thousand)) if isinstance( income_value_per_ten_thousand, float) else income_value_per_ten_thousand income_value_per_ten_thousand = income_value_per_ten_thousand.normalize() if isinstance( income_value_per_ten_thousand, Decimal) else income_value_per_ten_thousand assert income_value_per_ten_thousand is None or isinstance(income_value_per_ten_thousand, Decimal) d7_annualized_return = item.get('d7_annualized_return', row.get('d7_annualized_return', None)) d7_annualized_return = Decimal(d7_annualized_return) if isinstance(d7_annualized_return, int) \ else d7_annualized_return d7_annualized_return = Decimal(str(d7_annualized_return)) if isinstance(d7_annualized_return, float) \ else d7_annualized_return d7_annualized_return = d7_annualized_return.normalize() if isinstance(d7_annualized_return, Decimal) \ else d7_annualized_return assert d7_annualized_return is None or isinstance(d7_annualized_return, Decimal) d30_annualized_return = item.get('d30_annualized_return', row.get('d30_annualized_return', None)) d30_annualized_return = Decimal(d30_annualized_return) if isinstance(d30_annualized_return, int) \ else d30_annualized_return d30_annualized_return = Decimal(str(d30_annualized_return)) if isinstance(d30_annualized_return, float) \ else d30_annualized_return d30_annualized_return = d30_annualized_return.normalize() if isinstance(d30_annualized_return, Decimal) \ else d30_annualized_return assert d30_annualized_return is None or isinstance(d30_annualized_return, Decimal) annualized_return = item.get('annualized_return', row.get('annualized_return', None)) annualized_return = Decimal(annualized_return) if isinstance(annualized_return, int) \ else annualized_return annualized_return = Decimal(str(annualized_return)) if isinstance(annualized_return, float) \ else annualized_return annualized_return = annualized_return.normalize() if isinstance(annualized_return, Decimal) \ else annualized_return assert annualized_return is None or isinstance(annualized_return, Decimal) d7_floating_return = item.get('d7_floating_return', row.get('d7_floating_return', None)) d7_floating_return = Decimal(d7_floating_return) if isinstance(d7_floating_return, int) \ else d7_floating_return d7_floating_return = Decimal(str(d7_floating_return)) if isinstance(d7_floating_return, float) \ else d7_floating_return d7_floating_return = d7_floating_return.normalize() if isinstance(d7_floating_return, Decimal) \ else d7_floating_return assert d7_floating_return is None or isinstance(d7_floating_return, Decimal) finally: cursor.close() spider.dbPool.release(conn) md5 = hashlib.md5() seed = 'sitename=' + quote(sitename) seed += '&channel=' + quote(channel) seed += '&statistic_date=' + quote(statistic_date) seed += '&fund_name=' + quote(fund_name) if fund_code is not None: seed += '&fund_code=' + quote(fund_code) if url is not None: seed += '&url=' + quote(url) if nav is not None: seed += '&nav=' + quote(str(nav)) if added_nav is not None: seed += '&added_nav=' + quote(str(added_nav)) if nav_2 is not None: seed += '&nav_2=' + quote(str(nav_2)) if added_nav_2 is not None: seed += '&added_nav_2=' + quote(str(added_nav_2)) if total_nav is not None: seed += '&total_nav=' + quote(str(total_nav)) if share is not None: seed += '&share=' + quote(str(share)) if income_value_per_ten_thousand is not None: seed += '&income_value_per_ten_thousand=' + quote(str(income_value_per_ten_thousand)) if d7_annualized_return is not None: seed += '&d7_annualized_return=' + quote(str(d7_annualized_return)) if d30_annualized_return is not None: seed += '&d30_annualized_return=' + quote(str(d30_annualized_return)) if annualized_return is not None: seed += '&annualized_return=' + quote(str(annualized_return)) if d7_floating_return is not None: seed += '&d7_floating_return=' + quote(str(d7_floating_return)) md5.update(seed.encode('utf-8')) hkey = md5.hexdigest() item['hkey'] = hkey conn = spider.dbPool.acquire() cursor = conn.cursor() try: if row == {}: cursor.execute( 'INSERT INTO ' + spider.dbTable + ' (hkey,groupname,sitename,channel,statistic_date,fund_name,fund_code,url,nav,added_nav,nav_2' ',added_nav_2,total_nav,share,income_value_per_ten_thousand,d7_annualized_return,d30_annualized_return' ',annualized_return,d7_floating_return)' + ' VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)', (hkey, groupname, sitename, channel, statistic_date, fund_name, fund_code, url, nav, added_nav, nav_2, added_nav_2, total_nav, share, income_value_per_ten_thousand, d7_annualized_return, d30_annualized_return, annualized_return, d7_floating_return)) elif row['hkey'] != hkey: cursor.execute( 'UPDATE ' + spider.dbTable + ' SET hkey=%s,groupname=%s,fund_code=%s,url=%s,nav=%s,added_nav=%s,nav_2=%s,added_nav_2=%s' ',total_nav=%s,share=%s,income_value_per_ten_thousand=%s,d7_annualized_return=%s' ',d30_annualized_return=%s,annualized_return=%s,d7_floating_return=%s,update_time=GETDATE()' + ' WHERE hkey=%s', (hkey, groupname, fund_code, url, nav, added_nav, nav_2, added_nav_2, total_nav, share, income_value_per_ten_thousand, d7_annualized_return, d30_annualized_return, annualized_return, d7_floating_return, row['hkey'],)) finally: cursor.close() spider.dbPool.release(conn) except: spider.crawler.engine.close_spider(spider, 'pipeline error!') spider.crawler.stats.set_value('exit_emsg', traceback.format_exc()) spider.crawler.stats.set_value('exit_emsg_item', item) spider.crawler.stats.set_value('exit_code', 1) finally: return item # 基金(code)净值Pipeline class GGFundCodeNavPipeline(object): def process_item(self, item, spider): try: sitename = item.get('sitename', getattr(spider, 'sitename', None)) sitename = sitename.strip() if isinstance(sitename, str) else None sitename = None if sitename == '' else sitename assert sitename is not None channel = item.get('channel', getattr(spider, 'channel', None)) channel = channel.strip() if isinstance(channel, str) else None channel = None if channel == '' else channel assert channel is not None statistic_date = item.get('statistic_date', None) assert isinstance(statistic_date, datetime) statistic_date = statistic_date.strftime('%Y-%m-%d') fund_code = item.get('fund_code', None) fund_code = fund_code.strip() if isinstance(fund_code, str) else None fund_code = None if fund_code == '' else fund_code assert fund_code is not None conn = spider.dbPool.acquire() cursor = conn.cursor() try: cursor.execute( 'SELECT TOP 1 hkey,fund_name,url,nav,added_nav,nav_2,added_nav_2,total_nav,share' ',income_value_per_ten_thousand,d7_annualized_return,d30_annualized_return, annualized_return' + ' FROM ' + spider.dbTable + ' WHERE sitename=%s AND channel=%s AND statistic_date=%s AND fund_code=%s ORDER BY tmstamp', (sitename, channel, statistic_date, fund_code,)) row = cursor.fetchone() or {} groupname = item.get('groupname', getattr(spider, 'groupname', row.get('groupname', None))) groupname = groupname.strip() if isinstance(groupname, str) else None groupname = None if groupname == '' else groupname fund_name = item.get('fund_name', row.get('fund_name', None)) fund_name = fund_name.strip() if isinstance(fund_name, str) else None fund_name = None if fund_name == '' else fund_name assert fund_name is not None url = item.get('url', row.get('url', None)) url = url.decode() if isinstance(url, bytes) else url url = url.strip() if isinstance(url, str) else None url = None if url == '' else url nav = item.get('nav', row.get('nav', None)) nav = Decimal(nav) if isinstance(nav, int) else nav nav = Decimal(str(nav)) if isinstance(nav, float) else nav nav = nav.normalize() if isinstance(nav, Decimal) else nav assert nav is None or isinstance(nav, Decimal) added_nav = item.get('added_nav', row.get('added_nav', None)) added_nav = Decimal(added_nav) if isinstance(added_nav, int) else added_nav added_nav = Decimal(str(added_nav)) if isinstance(added_nav, float) else added_nav added_nav = added_nav.normalize() if isinstance(added_nav, Decimal) else added_nav assert added_nav is None or isinstance(added_nav, Decimal) nav_2 = item.get('nav_2', row.get('nav_2', None)) nav_2 = Decimal(nav_2) if isinstance(nav_2, int) else nav_2 nav_2 = Decimal(str(nav_2)) if isinstance(nav_2, float) else nav_2 nav_2 = nav_2.normalize() if isinstance(nav_2, Decimal) else nav_2 assert nav_2 is None or isinstance(nav_2, Decimal) added_nav_2 = item.get('added_nav_2', row.get('added_nav_2', None)) added_nav_2 = Decimal(added_nav_2) if isinstance(added_nav_2, int) else added_nav_2 added_nav_2 = Decimal(str(added_nav_2)) if isinstance(added_nav_2, float) else added_nav_2 added_nav_2 = added_nav_2.normalize() if isinstance(added_nav_2, Decimal) else added_nav_2 assert added_nav_2 is None or isinstance(added_nav_2, Decimal) total_nav = item.get('total_nav', row.get('total_nav', None)) total_nav = Decimal(total_nav) if isinstance(total_nav, int) else total_nav total_nav = Decimal(str(total_nav)) if isinstance(total_nav, float) else total_nav total_nav = total_nav.normalize() if isinstance(total_nav, Decimal) else total_nav assert total_nav is None or isinstance(total_nav, Decimal) share = item.get('share', row.get('share', None)) share = Decimal(share) if isinstance(share, int) else share share = Decimal(str(share)) if isinstance(share, float) else share share = share.normalize() if isinstance(share, Decimal) else share assert share is None or isinstance(share, Decimal) income_value_per_ten_thousand = item.get('income_value_per_ten_thousand', row.get('income_value_per_ten_thousand', None)) income_value_per_ten_thousand = Decimal(income_value_per_ten_thousand) if isinstance( income_value_per_ten_thousand, int) else income_value_per_ten_thousand income_value_per_ten_thousand = Decimal(str(income_value_per_ten_thousand)) if isinstance( income_value_per_ten_thousand, float) else income_value_per_ten_thousand income_value_per_ten_thousand = income_value_per_ten_thousand.normalize() if isinstance( income_value_per_ten_thousand, Decimal) else income_value_per_ten_thousand assert income_value_per_ten_thousand is None or isinstance(income_value_per_ten_thousand, Decimal) d7_annualized_return = item.get('d7_annualized_return', row.get('d7_annualized_return', None)) d7_annualized_return = Decimal(d7_annualized_return) if isinstance(d7_annualized_return, int) \ else d7_annualized_return d7_annualized_return = Decimal(str(d7_annualized_return)) if isinstance(d7_annualized_return, float) \ else d7_annualized_return d7_annualized_return = d7_annualized_return.normalize() if isinstance(d7_annualized_return, Decimal) \ else d7_annualized_return assert d7_annualized_return is None or isinstance(d7_annualized_return, Decimal) d30_annualized_return = item.get('d30_annualized_return', row.get('d30_annualized_return', None)) d30_annualized_return = Decimal(d30_annualized_return) if isinstance(d30_annualized_return, int) \ else d30_annualized_return d30_annualized_return = Decimal(str(d30_annualized_return)) if isinstance(d30_annualized_return, float) \ else d30_annualized_return d30_annualized_return = d30_annualized_return.normalize() if isinstance(d30_annualized_return, Decimal) \ else d30_annualized_return assert d30_annualized_return is None or isinstance(d30_annualized_return, Decimal) annualized_return = item.get('annualized_return', row.get('annualized_return', None)) annualized_return = Decimal(annualized_return) if isinstance(annualized_return, int) \ else annualized_return annualized_return = Decimal(str(annualized_return)) if isinstance(annualized_return, float) \ else annualized_return annualized_return = annualized_return.normalize() if isinstance(annualized_return, Decimal) \ else annualized_return assert annualized_return is None or isinstance(annualized_return, Decimal) d7_floating_return = item.get('d7_floating_return', row.get('d7_floating_return', None)) d7_floating_return = Decimal(d7_floating_return) if isinstance(d7_floating_return, int) \ else d7_floating_return d7_floating_return = Decimal(str(d7_floating_return)) if isinstance(d7_floating_return, float) \ else d7_floating_return d7_floating_return = d7_floating_return.normalize() if isinstance(d7_floating_return, Decimal) \ else d7_floating_return assert d7_floating_return is None or isinstance(d7_floating_return, Decimal) finally: cursor.close() spider.dbPool.release(conn) md5 = hashlib.md5() seed = 'sitename=' + quote(sitename) seed += '&channel=' + quote(channel) seed += '&statistic_date=' + quote(statistic_date) seed += '&fund_code=' + quote(fund_code) seed += '&fund_name=' + quote(fund_name) if url is not None: seed += '&url=' + quote(url) if nav is not None: seed += '&nav=' + quote(str(nav)) if added_nav is not None: seed += '&added_nav=' + quote(str(added_nav)) if nav_2 is not None: seed += '&nav_2=' + quote(str(nav_2)) if added_nav_2 is not None: seed += '&added_nav_2=' + quote(str(added_nav_2)) if total_nav is not None: seed += '&total_nav=' + quote(str(total_nav)) if share is not None: seed += '&share=' + quote(str(share)) if income_value_per_ten_thousand is not None: seed += '&income_value_per_ten_thousand=' + quote(str(income_value_per_ten_thousand)) if d7_annualized_return is not None: seed += '&d7_annualized_return=' + quote(str(d7_annualized_return)) if d30_annualized_return is not None: seed += '&d30_annualized_return=' + quote(str(d30_annualized_return)) if annualized_return is not None: seed += '&annualized_return=' + quote(str(annualized_return)) if d7_floating_return is not None: seed += '&d7_floating_return=' + quote(str(d7_floating_return)) md5.update(seed.encode('utf-8')) hkey = md5.hexdigest() item['hkey'] = hkey conn = spider.dbPool.acquire() cursor = conn.cursor() try: if row == {}: cursor.execute( 'INSERT INTO ' + spider.dbTable + ' (hkey,groupname,sitename,channel,statistic_date,fund_code,fund_name,url,nav,added_nav,nav_2' ',added_nav_2,total_nav,share,income_value_per_ten_thousand,d7_annualized_return,d30_annualized_return' ',annualized_return,d7_floating_return)' + ' VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)', (hkey, groupname, sitename, channel, statistic_date, fund_code, fund_name, url, nav, added_nav, nav_2, added_nav_2, total_nav, share, income_value_per_ten_thousand, d7_annualized_return, d30_annualized_return, annualized_return, d7_floating_return)) elif row['hkey'] != hkey: cursor.execute( 'UPDATE ' + spider.dbTable + ' SET hkey=%s,groupname=%s,fund_name=%s,url=%s,nav=%s,added_nav=%s,nav_2=%s,added_nav_2=%s' ',total_nav=%s,share=%s,income_value_per_ten_thousand=%s,d7_annualized_return=%s' ',d30_annualized_return=%s,annualized_return=%s,d7_floating_return=%s,update_time=GETDATE()' + ' WHERE hkey=%s', (hkey, groupname, fund_name, url, nav, added_nav, nav_2, added_nav_2, total_nav, share, income_value_per_ten_thousand, d7_annualized_return, d30_annualized_return, annualized_return, d7_floating_return, row['hkey'],)) finally: cursor.close() spider.dbPool.release(conn) except: spider.crawler.engine.close_spider(spider, 'pipeline error!') spider.crawler.stats.set_value('exit_emsg', traceback.format_exc()) spider.crawler.stats.set_value('exit_emsg_item', item) spider.crawler.stats.set_value('exit_code', 1) finally: return item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class YinTaiSecuritiesSpider(GGFundNavSpider): name = 'FundNav_YinTaiSecurities' sitename = '银泰证券' channel = '券商资管净值' fps = [ { 'url': 'https://biz.ytzq.com/web/bus/json', 'form': {'funcNo': '101108'} } ] def parse_fund(self, response): funds = json.loads(response.text)['results'] for fund in funds: fund_code = fund['fundcode'] fund_name = fund['fundname'] self.ips.append({ 'url': 'https://biz.ytzq.com/web/bus/json?funcNo=101109&pro_code={}&sortType=1'.format(fund_code), 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = json.loads(response.text)['results'] for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = row['create_time'] item['statistic_date'] = datetime.strptime(statistic_date, '%Y%m%d') nav = row['relate_price'] item['nav'] = float(nav) if nav is not None else None added_nav = row['cumulative_net'] item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep># coding:utf-8 # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-02 from datetime import datetime from FundNavSpiders import GGFundNavSpider from FundNavSpiders import GGFundNavItem import json class HangHaiDYQiHuoSpider(GGFundNavSpider): name = 'FundNav_HaiHangDYQiHuo' sitename = '海航东银期货' channel = '期货净值' allowed_domains = ['www.dyqh.com.cn'] username = '13916427906' password = '<PASSWORD>' # 跑数据前请更换最新cookies,不更换会造成漏抓产品 cookies = '__guid=98848536.420203476737738300.1516165948645.9883; ASP.NET_SessionId=5yq3xv5kiz4nz5hd5l511jwh; popped=yes; monitor_count=17' fps = [{ 'url': 'http://www.dyqh.com.cn/wealth-product.aspx?Index=4&Type=1&BItem=1&Item=0', 'form': { '__VIEWSTATE': 'of1ydSBodTI84LFaJVoo2fSQI0Z3x+7rH84tHic+6JAjWf+b6GaS7Cq<KEY>uQauFKPhDK2O7t1Y<KEY>', '__EVENTTARGET': 'pgServer', '__EVENTARGUMENT': '1', }, 'headers': {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}, 'pg': 1, }] def parse_fund(self, response): pg = response.meta['pg'] codes = response.xpath('//div[@class = "notice-content-top"]//li//dt/a//@href').extract() fund_names = response.xpath('//div[@class = "notice-content-top"]//li//dt/a//p//text()').extract() for fund_code, fund_name in zip(codes, fund_names): ips_url = 'http://www.dyqh.com.cn/Handler/GetWealthNet.ashx?Id=' + fund_code.split('=')[1] self.ips.append({ 'url': ips_url, 'ref': response.url, 'headers': { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}, 'ext': fund_name }) max_page = response.xpath('//div[@id = "pgServer"]//text()').extract()[-4] if pg < int(max_page): next_pg = pg + 1 self.fps.append({ 'url': 'http://www.dyqh.com.cn/wealth-product.aspx?Index=4&Type=1&BItem=1&Item=0', 'form': { '__VIEWSTATE': '<KEY>', '__EVENTTARGET': 'pgServer', '__EVENTARGUMENT': str(next_pg), }, 'headers': {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}, 'pg': next_pg, }) def parse_item(self, response): fund_name = response.meta['ext'] fund = json.loads(response.text) for i in fund: item = GGFundNavItem() statistic_date = i['NetDate'].replace('0:00:00', '') nav = i['NetEstimate'] item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') item['nav'] = float(nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy import FormRequest class FanbeiFutrueSpider(GGFundNoticeSpider): name = 'FundNotice_FanbeiFutrue' sitename = '凡贝资产' entry = 'http://www.fbamc.com/index.php' proxy = 2 def start_requests(self): yield FormRequest( url='http://www.fbamc.com/index.php?p=default', # 首页面 callback=self.parse_list # 回调下面方法 ) def parse_list(self, response): self.ips.append({ 'url': 'http://www.fbamc.com/index.php?p=news_list&c_id=17&lanmu=1', # 数据列表页面 }) yield self.request_next() def parse_item(self, response): rows = response.xpath('//div[@class="news_list p2"]/li') for row in rows: url = row.xpath('./a/@href').extract_first()#获取路径 url = urljoin(get_base_url(response), url)#拼接绝对路径 title = row.xpath('./a/@title').extract_first()#标题 publish_time = row.xpath('./a/h1/span/text()').extract_first().strip().replace('\t', '').replace('\r', '').replace('\n', '')#时间格式 publish_time = datetime.strptime(publish_time, '%Y/%m/%d')#转换时间格式 item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item yield self.request_next()<file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin import re class XinShengTrustSpider(GGFundNoticeSpider): name = 'FundNotice_XinShengTrust' sitename = '长城新盛信托' entry = 'http://www.gwxstrust.com/' ips = [ { 'url': 'http://www.gwxstrust.com/cn/page.jsp?id=23&pageIndex=1', 'ref': 'http://www.gwxstrust.com/', 'pg': 1 } ] def parse_item(self, response): datas = response.xpath('//div[@class="lh-160p"]/div[@class="m-b-10"]') for notice in datas[1:]: href = notice.xpath('./div[1]/a/@href').extract_first() url = urljoin(get_base_url(response), href) title = notice.xpath('./div[1]/a/text()').extract_first() publish_time = notice.xpath('./div[2]/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item next_url = response.xpath('//div[@class="pager"]/table/tr/td[3]/image/@onclick').re_first('\d+') if next_url is not None: self.ips.append({ 'url': 'http://www.gwxstrust.com/cn/page.jsp?id=23&pageIndex=' + next_url, 'ref': response.url }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class ShanghaiyijinghuiFutureSpider(GGFundNoticeSpider): name = 'FundNotice_ShanghaiyijinghuiFuture' sitename = '上海益菁汇资产' entry = 'http://www.yjhassets.com' proxy = 2 ips = [{ 'url': 'http://www.yjhassets.com/website/w/h?mt=2&mc=2734076&cc=59931', }] def parse_item(self, response): rows = response.xpath('//div[@class="simu-site-list"]/ul/a') for row in rows: url = row.xpath('./@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./li/div/div[1]/text()').extract_first().strip().replace('\t', '').replace('\r', '').replace('\n', '') publish_time = row.xpath('./li/div/div[3]/div[2]/text()').extract_first().strip().replace('\t', '').replace('\r', '').replace('\n', '') publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item next_url = response.xpath('//div[@class="simu-site-pagination"]/ul/li/a[contains(text(),"下一页")]/@href').extract_first() if next_url and next_url != 'javascript:;': next_url = urljoin(get_base_url(response), next_url) self.ips.append({ 'url': next_url, 'ref': response.url }) <file_sep>from scrapy import cmdline # 免认证 #上海厚崇资产-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_PingAnDaHua', '-a', 'jobId=0L']) #cmdline.execute(['scrapy', 'crawl', 'FundNotice_PingAnDaHua', '-a', 'jobId=0L']) #中邮证券-券商资管净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_zystock', '-a', 'jobId=0L']) #渤海证券-券商资管净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_bhhjamc', '-a', 'jobId=0L']) #九沐资本-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_JiuMuAssets', '-a', 'jobId=0L']) #平安资产-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_PingAnAssets', '-a', 'jobId=0L']) #赋成资产-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_FuChegnAsset', '-a', 'jobId=0L']) #福能期货-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_FuNengFuture', '-a', 'jobId=0L']) #广东天贝合资产-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_GuangDongTianBeiHeAsset', '-a', 'jobId=0L']) #上海老渔民投资-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ShangHaiLaoYuMinInvest', '-a', 'jobId=0L']) #银叶投资-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_YinYeInvest', '-a', 'jobId=0L']) #丰润投资-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_FengRuiInvest', '-a', 'jobId=0L']) #华炎投资-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_HuaYanInvest', '-a', 'jobId=0L']) #骏胜资产-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_JunShengAsset', '-a', 'jobId=0L']) #牟合资产-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_MuHeAsset', '-a', 'jobId=0L']) #南土资产-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_NanTuAsset', '-a', 'jobId=0L']) #上海庐雍资产-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ShangHaiLuYongAsset', '-a', 'jobId=0L']) #中粮信托-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongLiangXinTuo', '-a', 'jobId=0L']) #上海同亿富利投资-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_shtyflInvest', '-a', 'jobId=0L']) #首创期货-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ShouChuangInvest', '-a', 'jobId=0L']) #财富证券资管-券商资管净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_CaiFuStockZiGuan', '-a', 'jobId=0L']) #粤财信托-信托净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YueCaiXinTuo', '-a', 'jobId=0L']) #哲实实业-投顾顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ZheShiShiYe', '-a', 'jobId=0L']) #言起投资-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_YanQiInvest', '-a', 'jobId=0L']) #云国投-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_YanQiInvest', '-a', 'jobId=0L']) #招商证券-券商资管净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ZhaoShangStock', '-a', 'jobId=0L']) #源实资产-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_YuanShiAsset', '-a', 'jobId=0L']) #方正东亚信托-信托净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_FangZhengDongYaTrust', '-a', 'jobId=0L']) #易同投资-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YiTongInvest', '-a', 'jobId=0L']) #杭州德锐资本投资-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_DeRuiAssetInvest', '-a', 'jobId=0L']) #山楂树投资-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ShanZhaShuInvest', '-a', 'jobId=0L']) #银莅资产-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_YinLiAsset', '-a', 'jobId=0L']) #重庆国际信托-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ChongQingGuoJiTrust', '-a', 'jobId=0L']) #中银国际-券商资管净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ZhongYinGuoJiStock', '-a', 'jobId=0L']) #星鸿资产-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_XingHongAsset', '-a', 'jobId=0L']) #盈盾资本-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_YingDunAssetNotice', '-a', 'jobId=0L']) #中航证券-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongHangStockNotice', '-a', 'jobId=0L']) #北京佑瑞持投资-公告 cmdline.execute(['scrapy', 'crawl', 'FundNotice_BieJingYouRuiChiInvest', '-a', 'jobId=0L']) #博洋投资-公告 cmdline.execute(['scrapy', 'crawl', 'FundNotice_BoYangInvestNotice', '-a', 'jobId=0L']) #鼎力投资-公告 cmdline.execute(['scrapy', 'crawl', 'FundNotice_DingLiInvestNotice', '-a', 'jobId=0L']) #大柏地投资-公告 cmdline.execute(['scrapy', 'crawl', 'FundNotice_DaBoDiInvestNotice', '-a', 'jobId=0L']) #百瑞信托公告-公告 cmdline.execute(['scrapy', 'crawl', 'FundNotice_BaiRuiTurstNotice', '-a', 'jobId=0L']) #安徽翔海资产-公告 cmdline.execute(['scrapy', 'crawl', 'FundNotice_AnHuiXiangHaiAssetNotice', '-a', 'jobId=0L']) # 自动登录 #浙江慧安家族财富投资-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ZhejiangHuian', '-a', 'jobId=0L']) #中域投资-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ZhongyuInvset', '-a', 'jobId=0L']) #蓝海韬略-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_LanhaiTaolue', '-a', 'jobId=0L']) #东航金控-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_DongHangJinKong', '-a', 'jobId=0L']) #安徽嘉和投资-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_JiaHeInvest', '-a', 'jobId=0L']) #呈瑞投资-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ChengRuiInvest', '-a', 'jobId=0L']) #徽商期货-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_HuiShangFuture', '-a', 'jobId=0L']) #新里程碑资产-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_XinLiChengBeiAsset', '-a', 'jobId=0L']) #海通期货-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_HaiTongFuture', '-a', 'jobId=0L']) #华菁证券资管-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_HuaJIngStock', '-a', 'jobId=0L']) #上海游马地投资-券商资管公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ShangHaiYouMaDiInvest', '-a', 'jobId=0L']) #永兴投资-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YongXingInvest', '-a', 'jobId=0L']) #深圳老虎汇资产-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ShenZhenLaoHuHuiAsset', '-a', 'jobId=0L']) #大岩资本-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_DaYanAsset', '-a', 'jobId=0L']) #映雪投资-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YingXueInvest', '-a', 'jobId=0L']) #艾方资产-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_AiFangAsset', '-a', 'jobId=0L']) #从容投资-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_CongRongInvest', '-a', 'jobId=0L']) #泓澄投资-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HongChengInvest', '-a', 'jobId=0L']) #慧安投资-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HuiAnInvest', '-a', 'jobId=0L']) #资舟资产-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ZiZhouAsset', '-a', 'jobId=0L']) #山东银企投资-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ShanDongYinQiInvest', '-a', 'jobId=0L']) #合晟资产-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HeShengAsset', '-a', 'jobId=0L']) #云程泰投资-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YunChengTaiInvest', '-a', 'jobId=0L']) #辰阳投资-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_ChengYangInvest', '-a', 'jobId=0L']) #宝蓁投资-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_BaoZhenInvest', '-a', 'jobId=0L']) #杭州明曦资本-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HangZhouMingXiAsset', '-a', 'jobId=0L']) #厦门博孚利资产-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_XiaMenBoFuLiAsset', '-a', 'jobId=0L']) #盈盾资本-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YingDunAssetNav', '-a', 'jobId=0L']) #南华期货-公告 cmdline.execute(['scrapy', 'crawl', 'FundNotice_NanHuaFutureNotice', '-a', 'jobId=0L']) # Cookie认证 #艾叶投资-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_AiYeInvest', '-a', 'jobId=0L']) #东海期货-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_DongHaiFuture', '-a', 'jobId=0L']) #穗富投资-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HuiFuInvest', '-a', 'jobId=0L']) #昶享资产-投资顾问 #cmdline.execute(['scrapy', 'crawl', 'FundNav_HaiShangChangXiangAsset', '-a', 'jobId=0L']) #昭图投资-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_BaoChiInvest', '-a', 'jobId=0L']) #国金证券资管-券商资管净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_GuoJinStockZiGuan', '-a', 'jobId=0L']) #易凡资产-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_YiFanAsset', '-a', 'jobId=0L']) #易凡资产-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YiFanAssetCookie', '-a', 'jobId=0L']) #翼虎投资-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YiHuInvest', '-a', 'jobId=0L']) #银石投资-投顾净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_YinShiInvest', '-a', 'jobId=0L']) #中信证券-券商资管净值 #cmdline.execute(['scrapy', 'crawl', 'FundNav_ZhongXinStockNav', '-a', 'jobId=0L']) #北京中外建投资-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_BeiJingZhongWeiJianInvest', '-a', 'jobId=0L']) #银河证券公告-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_YinHeStockNotice', '-a', 'jobId=0L']) #银石投资-公告 #cmdline.execute(['scrapy', 'crawl', 'FundNotice_YinShiInvestNotice', '-a', 'jobId=0L'])<file_sep># -*- coding: utf-8 -*- import json import re from datetime import datetime import lxml.etree from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ZunJiaAssetSpider(GGFundNavSpider): name = 'FundNav_ZunJiaAsset' sitename = '尊嘉资产' channel = '投顾净值' def start_requests(self): yield FormRequest(url='http://www.juniorchina.com.cn/Index/login_in.html', formdata={ 'name': '18939019964', 'pwd': '<PASSWORD>', 'checkSent': '0', 'value': 'ok' }, callback=self.parse_login) def parse_login(self, response): self.fps.append({ 'url': 'http://www.juniorchina.com.cn/Product/product.html', 'ref': response.url }) def parse_fund(self, response): funds = response.xpath('//ul[@id="xiala"]/li/p') ids = response.xpath('//ul[@id="xiala"]/script') for (fund, id) in zip(funds, ids): fund_name = fund.xpath('normalize-space(./text())').extract_first() fund_id = id.xpath('./text()').extract_first() fund_id = re.findall('\d+', fund_id)[1] self.ips.append({ 'url': 'http://www.juniorchina.com.cn/Product/juniorchina_produt.html?fund_id=' + fund_id, 'ref': response.url, 'pg': 1, 'ext': {'fund_name': fund_name, 'fund_id': fund_id} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] info_json = json.loads(response.text) chart = lxml.etree.HTML(info_json['content']) rows = chart.xpath('//table[@id="juniorchina_table"]/tr') for row in rows[1:]: statistic_date = row.xpath('./td[1]/text()') if len(statistic_date) == 0: continue statistic_date = statistic_date[0] nav = row.xpath('./td[2]/text()')[0] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item #总页数 tp = chart.xpath('//script[contains(text(),"pagenumber")]/text()')[0] tp = re.findall('pagenumber"\)\.val\("(\d+)', tp)[0] pg = response.meta['pg'] fund_id = response.meta['ext']['fund_id'] if pg < int(tp): pg = pg+1 self.ips.append({ 'url': 'http://www.juniorchina.com.cn/Product/juniorchina_produt.html?fund_id=' + fund_id + '&begin=&over=&new_page=' + str(pg), 'ref': response.url, 'pg': pg, 'ext': {'fund_name': fund_name, 'fund_id': fund_id} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-04-26 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest class HaoFengTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_HaoFengTouZiInvest' sitename = '昊沣投资' channel = '投顾净值' fps = [{'url': 'http://www.goodwind.me/index.php'}] def start_requests(self): yield FormRequest(url='http://www.goodwind.me/disclaimer.php?ret=%3F', formdata={'ret': '?'}, callback=self.parse_fund) def parse_fund(self, response): fund_urls = response.xpath("//div[@class='f_l newbg']/table[@class='table pr_view']//tr//@href").extract() for fund_url in fund_urls: self.ips.append({ 'url': 'http://www.goodwind.me/' + fund_url, 'ref': response.url, }) def parse_item(self, response): rows = response.xpath("//tr") for row in rows[1:]: fund_name = row.xpath("./td[1]//text()").extract_first() statistic_date = row.xpath("./td[2]//text()").extract_first() nav = row.xpath("./td[3]//text()").extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># Department : 保障部 # Author : 李婧 # Create_date : 2018-04-26 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class GuoLingAssetSpider(GGFundNavSpider): name = 'FundNav_GuoLingAsset' sitename = '国领资产' channel = '投顾净值' allowed_domains = ['http://guolingzichan.com/'] fps = [ { 'url': 'http://guolingzichan.com/product_93895.html#visualmodule_1' } ] def parse_fund(self, response): fund_infos = response.xpath("//div[@class='m-theme10-title']/a") for fund_info in fund_infos: ips_url = fund_info.xpath('.//@href').extract_first() fund_name = fund_info.xpath('.//text()').extract_first() fund_url = urljoin('http://guolingzichan.com/', ips_url) self.ips.append({ 'url': fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath("//div[@id='out_ph']/table[@class='ke-zeroborder'][2]/tbody/tr") fund_name = response.meta['ext']['fund_name'] if len(rows) == 0: rows = response.xpath("//div[@class='m-view-list']/div[@id='out_ph']//tr") for row in rows[1:]: statistic_date = row.xpath("./td[1]//text()").extract_first().strip() if '2' in statistic_date: nav = row.xpath("./td[3]//text()").extract_first().strip() added_nav = row.xpath("./td[2]//text()").extract_first().strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date.replace('/', '-'), '%Y-%m-%d') yield item else: for row in rows[1:]: statistic_date = row.xpath("./td[1]//text()").extract_first().strip() if '2' in statistic_date: nav = row.xpath("./td[3]//text()").extract_first().strip() added_nav = row.xpath("./td[2]//text()").extract_first().strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date.replace('/', '-'), '%Y-%m-%d') yield item <file_sep>import json from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ZhaoShangStockZiGuanSpider(GGFundNavSpider): name = 'FundNav_ZhaoShangStockZiGuan' sitename = '招商证券资管' channel = '券商资管净值' username = '13916427906' password = '<PASSWORD>' cookies = 'PLAY_SESSION=f308296c260bd1aa0ccbd588f56c76ff5a6dde96-%00___ID%3Aa11e7ff9-716f-4d05-a58d-c723db286382%00; cms_yht="VzDPKfPg4frpftbZoX/06Be9wTToSt5i1R3WGKF32d3FCchL22vYoDj6LaXu7njImZoLpkvzDeM+@doeFsGvgORFP/iiTGwo5ZpGXMhRDdgXplX8gSAqaXiUYanFSvr3QkLhluQMzpyP6fwy7PqfbUWYX@oi7ewNHwRELDj2B9bxw="' fps = [{ 'url': 'https://amc.cmschina.com/p/productlist', 'form': {'limit': '2000'}, 'ref': 'https://amc.cmschina.com/', }] def parse_fund(self, response): funds = json.loads(response.text)['data']['rows'] for fund in funds: fund_name = fund['name_abbrev'] type_code = fund['type_code'] fund_id = fund['fund_id'] url = 'https://amc.cmschina.com/licai/jz' self.ips.append({ 'url': url, 'ref': response.url, 'form': {'fund_id': fund_id, 'page': '1', 'startdate': '', 'enddate': ''}, 'ext': {'fund_name': fund_name, 'page': '1', 'fund_id': str(fund_id), 'type_code': type_code} }) def parse_item(self, response): datas = json.loads(response.text) ext = response.meta['ext'] fund_name = ext['fund_name'] type_code = ext['type_code'] page = int(ext['page']) fund_id = ext['fund_id'] if datas is not None and datas['data']['rows'] is not None: datas = datas['data']['rows'] if len(datas) > 0: url = 'https://amc.cmschina.com/licai/jz' self.ips.append({ 'url': url, 'ref': response.url, 'form': {'fund_id': fund_id, 'page': str(page + 1), 'startdate': '', 'enddate': ''}, 'ext': {'fund_name': fund_name, 'page': str(page + 1), 'fund_id': str(fund_id), 'type_code': type_code} }) for data in datas: statistic_date = data[2] nav = data[3] added_nav = data[4] annualized_return = data[14] d7_annualized_return = data[7] income_value_per_ten_thousand = data[5] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = 'https://amc.cmschina.com/licai/detail?fund_id={}'.format(fund_id) item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y%m%d') if type_code == '1': item['annualized_return'] = float( annualized_return) if annualized_return is not None and annualized_return != '' else None elif type_code == '2': item['d7_annualized_return'] = float( d7_annualized_return) if d7_annualized_return is not None and d7_annualized_return != '' else None item['income_value_per_ten_thousand'] = float( income_value_per_ten_thousand) if income_value_per_ten_thousand is not None and income_value_per_ten_thousand != '' else None else: item['nav'] = float(nav) if nav is not None and nav != '' else None item['added_nav'] = float(added_nav) if added_nav is not None and nav != '' else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-22 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re import json class ShangHaiLiangHuaInvestSpider(GGFundNavSpider): name = 'FundNav_ShangHaiLiangHuaInvest' sitename = '上海量化投资' channel = '投资顾问' allowed_domains = ['www.qfund.com'] cookies = '__guid=46425889.3259545501557033500.1526895215504.0994; JSESSIONID=6A21E1488A7C01F48D0F9F7A582BA246; lianghua=%7B%22userName%22%20%3A%20%22139****7906%22%2C%20%22email%22%20%3A%20%22yuangh%40go-goal.com%22%2C%22aniuUid%22%20%3A%20%22svb3zkjjtmzmowvil3n2zlr4umdaqt09%22%2C%22userNickName%22%20%3A%20%22139****7906%22%7D; monitor_count=10' password = '<PASSWORD>' ips = [{ 'url': 'http://www.qfund.com/productionList.do' }] def parse_item(self, response): js_text = response.xpath('//script//text()').extract()[2].split(';')[0] funds_js = re.findall('\'{.*?}\'', js_text, re.DOTALL)[0].replace('\'{', '{').replace('}\'', '}') funds_name = response.xpath('//ul//li//a/span[1]//text()').extract() funds_code = response.xpath('//ul//li//a/span[2]//text()').extract() for fund_name, fund_code in zip(funds_name, funds_code): fs_list = json.loads(funds_js)[fund_code]['weekNetWorth'] for f in fs_list: statistic_date = f['addTime'] nav = f['netWorth'] added_nav = f['totalWorth'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class KunShengTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_KunShengTouZiInvest' sitename = '坤盛投资' channel = '投资顾问' allowed_domains = ['www.ntkstz.com'] ips = [{'url': 'http://www.ntkstz.com/index.asp'}] def parse_item(self, response): rows = response.xpath("//div/div/table//tr") fund_names = response.xpath("//div/p/b//text()").extract() fund_name = ''.join(fund_names) for row in rows[1:]: nav = row.xpath('./td[1]/p//text()').extract()[1] added_nav = row.xpath('./td[2]/p//text()').extract()[1] statistic_date = row.xpath('./td[3]/p//text()').extract()[1] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name.replace('净值表', '') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y.%m.%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class ShanXiXinTuoTrustSpider(GGFundNavSpider): name = 'FundNav_ShanXiXinTuoTrust' sitename = '山西信托' channel = '信托净值' allowed_domains = ['www.sxxt.net'] fps = [ {'url': 'http://www.sxxt.net/xxpl/cpgg/jzgg/', 'pg': 1}, ] def parse_fund(self, response): fund_urls = response.xpath("//div[@class='in_news']/ul/li//@href").extract() for fund_url in fund_urls: self.ips.append({ 'url': 'http://www.sxxt.net' + fund_url, 'ref': response.url, }) if fund_urls: pg = response.meta['pg'] next_pg = pg + 1 self.fps.append({ 'url': 'http://www.sxxt.net/xxpl/cpgg/jzgg/index' + str(next_pg) + '.html', 'ref': response.url, 'pg': next_pg }) def parse_item(self, response): zz = '<td style="([\s\S]*?)">20([\s\S]*?)<([\s\S]*?)>(\d.\d+)<' if '>净值公告</td>' in response.text: navinfos = response.text.split('>净值公告</td>') else: navinfos = response.text.split('产品名称:') for navinfo in navinfos: if '>净值公告</td>' not in response.text: navinfo = '产品名称:' + navinfo if '产品名称' in navinfo: name = re.findall('产品名称:(.*?)</td>', navinfo) if name: fund_name = name[0].split(' ')[0].replace('</strong>', '').replace('&nbsp;', '') else: fund_name = re.findall('产品名称:(.*?)<', navinfo)[0].split(' ')[0].replace('</strong>', '').replace( '&nbsp;', '') if '累计净值' in navinfo: zz = '<td style="([\s\S]*?)">20([\s\S]*?)<([\s\S]*?)">(\d.\d+)<([\s\S]*?)>(\d.\d+|[\s\S+]|&nbsp;)</' rows = re.findall(zz, navinfo) for row in rows: added_nav = None item = GGFundNavItem() nav = row[3] if '累计净值' in navinfo: added_nav = row[5].replace(' ', '').replace(' ', '').replace('&nbsp;', '') if added_nav: item['added_nav'] = float(added_nav) if added_nav is not None else None statistic_date = '20' + row[1] if '<' in nav: nav = re.findall('>(.*?)<', nav)[0] statistic_date = re.findall('(.*?)<', statistic_date)[0] statistic_date = statistic_date.replace('年', '-').replace('月', '-').replace('日', '') item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name.replace('</span>', '') item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep>import re from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class XiNanZhengQuanPBSpider(GGFundNavSpider): name = 'FundNav_XiNanZhengQuanPB' sitename = '西南证券' channel = '券商PB净值列表' fps = [{ 'url': 'http://jdz.swsc.com.cn:8080/tg102/tgSmjj1_getByfilterC.action', 'ref': 'http://jdz.swsc.com.cn:8080/tg102/tgSmjj1_getByfilterC.action', 'pg': 1, 'ext': {'flag': 0} }] def parse_fund(self, response): ext = response.meta['ext'] flag = ext['flag'] if flag == 1: fund_name = response.meta['ext']['fund_name'] fund_id = re.split('\?', response.url)[1] url = "/tg102/tgProductValue1_getByfilterC.action?pfNa="+fund_name+"&"+fund_id self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url, 'pg': 1, 'ext': {'fund_name': fund_name} }) else: funds = response.xpath('//table[@class="tuoguan_table_porduct"]/tbody/tr/td[2]/a') for fund in funds: url = fund.xpath('./@href').extract_first() fund_name = fund.xpath('normalize-space(./text())').extract_first() self.fps.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url, 'pg': 1, 'ext': {'flag': 1, 'fund_name': fund_name} }) tp = response.xpath('//span[@class="cpb"]/text()').extract_first() tp = re.findall('共(\d+)', tp)[0] cp = response.meta['pg'] if cp < int(tp): cp = cp + 1 self.fps.append({ 'url': response.url, 'ref': response.url, 'form': { 'search.code': '', 'search.productInfo.name': '', 'search.state': '', 'pagination.pageNum': str(cp), 'pagination.pageSize': '10' }, 'pg': cp, 'ext': {'flag': 0} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//table[@class="tuoguan_table_porduct"]/tbody/tr') for row in rows[1:]: statistic_date = row.xpath('normalize-space(./td[2]/span/text())').extract_first() if statistic_date == '': continue nav = row.xpath('normalize-space(./td[3]/span/text())').extract_first() added_nav = row.xpath('normalize-space(./td[4]/span/text())').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None yield item tp = response.xpath('//span[@class="cpb"]/text()').extract_first() tp = re.findall('共(\d+)', tp)[0] cp = response.meta['pg'] if cp < int(tp): cp = cp+1 self.ips.append({ 'url': response.url, 'ref': response.url, 'form': { 'search.code': '', 'search.productInfo.name': '', 'search.state': '', 'pagination.pageNum': str(cp), 'pagination.pageSize': '10' }, 'pg': cp, 'ext': {'fund_name': fund_name} }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class HaiXiShengQianInvestSpider(GGFundNoticeSpider): name = 'FundNotice_HaiXiShengQianInvest' sitename = '福建海西晟乾投资' entry = 'http://www.fjhxsq.com/plus/list.php?tid=3' ips = [ { 'url': 'http://www.fjhxsq.com/plus/list.php?tid=3' } ] def parse_item(self, response): rows = response.xpath('//ul[@class="e2"]/li/table/tbody/tr') for row in rows: url = row.xpath('./td[1]/a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./td[1]/a/text()').extract_first() publish_time = row.xpath('./td[2]/span/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department:保障部 # Author:王卓诚 # Create_Date:2018-05-25 from datetime import datetime from scrapy import Request from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider # from scrapy.utils.response import get_base_url # from urllib.parse import urljoin # from urllib.parse import urljoin from scrapy import FormRequest import json class YingWeiInvestSpider(GGFundNavSpider): name = 'FundNav_YingWeiInvest' sitename = '惟盈投资' channel = '投顾净值' allowed_domains = ['www.winingfund.com'] username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'http://www.winingfund.com/index.php', 'ref': 'http://www.winingfund.com' }] def start_requests(self): yield FormRequest(url='http://www.winingfund.com/portals/login.php?p=wyzx2', formdata={ 'username': self.username, 'password': self.<PASSWORD> }) def parse_fund(self, response): arul = response.xpath('//ul[@class="dropdown-menu"]/li') for uu in arul: url = uu.xpath('a/@href').extract_first() url = url.replace('portals/product.php?p=', '') if (not url.find('portals/') > -1): url2 = 'http://www.winingfund.com/portals/api.php?callback=jQuery2140059739919985194234_1526870154121&command=2001&product=' + url + '&_=1526870154122' self.ips.append({ 'url': url2, 'ref': response.url }) def parse_item(self, response): fund_info = response.text wz1 = fund_info.find('{"result') fund_info1 = fund_info[wz1:len(fund_info) - 1] fund_info2 = json.loads(fund_info1) productname_bf = fund_info2['result']['name'] for k, v in enumerate(fund_info2['result']['date']): statistic_date = v nav = fund_info2['result']['value'][k] statistic_date = statistic_date.replace('/', '-') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = productname_bf item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin class JHLAssetSpider(GGFundNoticeSpider): name = 'FundNotice_JHLAsset' sitename = '深圳前海进化论资产' entry = 'http://www.jhlfund.com/website/w/h' ips = [ { 'url': 'http://www.jhlfund.com/website/w/h?mt=2&mc=2909478&cc=2899337', 'ref': 'http://www.jhlfund.com/website/w/h', 'pg': 0 } ] def parse_item(self, response): datas = response.xpath('//div[@class="simu-site-list"]/ul/a') for notice in datas: href = notice.xpath('./@href').extract_first() url = urljoin(get_base_url(response), href) title = notice.xpath('normalize-space(./li/div/div[1]/text())').extract_first() publish_time = notice.xpath('./li/div/div[3]/div[2]/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item next_url = response.xpath('//a[contains(text(), "下一页")]/@href').extract_first() if next_url is not None and next_url != '': url = self.entry + next_url self.ips.append({'url': url, 'ref': response.url}) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest, Request from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class YuanPuInvestSpider(GGFundNavSpider): name = 'FundNav_YuanPuInvest' sitename = '元普投资' channel = '投顾净值' username = '18625981663' password = '<PASSWORD>' def start_requests(self): yield FormRequest(url='http://www.yuanputouzi.com/index.php?m=member&c=index&a=public_login_ajax', formdata={ 'username': self.username, 'password': <PASSWORD> }, callback=self.start_pre_requests) def start_pre_requests(self, response): yield Request(url='http://www.yuanputouzi.com/products/zdgl/', callback=self.parse_login_fund) def parse_login_fund(self, response): rows = response.xpath('//ul[@class="clearfix"]/li') for row in rows: url = row.xpath('./a/@href').extract_first() self.fps.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url }) def parse_fund(self, response): rows = response.xpath('//ul[@class="fl pro-names"]/li') for row in rows: pro_id = row.xpath('./a/@href').re_first('([\d]+).html') self.ips.append({ 'url': 'http://www.yuanputouzi.com/index.php?m=content&c=index&a=ajax_page_list', 'ref': response.url, 'form': { 'proid': str(pro_id), 'page': '1' }, 'pg': 1 }) def parse_item(self, response): rows = response.xpath('//tr')[1:] for row in rows: fund_name = row.xpath('./td[1]/text()').extract_first() statistic_date = row.xpath('./td[3]/text()').re_first('\d+-\d+-\d+') nav = row.xpath('./td[4]/text()').re_first('[0-9.]+') added_nav = row.xpath('./td[5]/text()').re_first('[0-9.]+') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item if len(rows) == 20: form = response.meta['form'] pg = response.meta['pg'] + 1 pro_id = form['proid'] self.ips.append({ 'url': 'http://www.yuanputouzi.com/index.php?m=content&c=index&a=ajax_page_list', 'ref': response.url, 'form': { 'proid': str(pro_id), 'page': str(pg) }, 'pg': pg }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class GZYinGuoDaCapitalSpider(GGFundNoticeSpider): name = 'FundNotice_GZYinGuoDaCapital' sitename = '广州银国达资产' entry = 'http://www.ingoalamc.com/index.php/Article_index_navid_79_cNavid_102.html' ips = [ { 'url': 'http://www.ingoalamc.com/index.php/Article_index_navid_79_cNavid_102.html', 'ref': None } ] def parse_item(self, response): rows = response.xpath('//ul[@class="new_list"]/li/a') for row in rows: url = row.xpath('./@href').extract_first() url = urljoin(get_base_url(response), url) publish_time = row.xpath('./div/div[1]/time/text()').re_first('\d+.\d+.\d+') title = row.xpath('./div/div[1]/h4/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = url item['publish_time'] = datetime.strptime(publish_time, '%Y.%m.%d') yield item next_url = response.xpath('//a[@class="next"]/@href').extract_first() if next_url: self.ips.append({ 'url': urljoin(get_base_url(response), next_url), 'ref': None }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-14 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ShangHaiLiangHanInvestSpider(GGFundNavSpider): name = 'FundNav_ShangHaiLiangHanInvest' sitename = '上海量函投资' channel = '投资顾问' allowed_domains = ['www.quantfn.com'] username = '13916427906' password = '<PASSWORD>' cookies = '__guid=261440907.29537647574523732.1526266146264.8103; PHPSESSID=lpba7s83ql092em2mh1s3vbio5; DedeUserID=64; DedeUserID__ckMd5=efba1073e76861b3; DedeLoginTime=1526266247; DedeLoginTime__ckMd5=9ee68a34d0e0b1b6; cookie=tongyi; monitor_count=16' fps = [{ 'url': 'http://www.quantfn.com/plus/list.php?tid=7' }] def parse_fund(self, response): funds = response.xpath('//table//td[@rowspan]//a[@class ="yuyue"]//@href').extract() fund_names = response.xpath('//table//td[@rowspan and @class = "pro_name"]//text()').extract() for fund_name, f_url in zip(fund_names, funds): self.ips.append({ 'url': 'http://www.quantfn.com/' + f_url, 'ref': response.url, 'ext': fund_name }) def parse_item(self, response): fund_name = response.meta['ext'] fund = response.xpath('//div[@id ="c1"]//tbody//tr') for i in fund[1:]: t = i.xpath('td//text()').extract() statistic_date = ''.join(t[0].split()) nav = ''.join(t[1].split()) added_nav = ''.join(t[2].split()) item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-23 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class HuaChuangZhengQuanSecutiesSpider(GGFundNavSpider): name = 'FundNav_HuaChuangZhengQuanSecuties' sitename = '华创证券' channel = '券商资管净值' allowed_domains = ['www.hczq.com'] urername = '13916427906' password = '<PASSWORD>' fps = [{'url': 'http://www.hczq.com/hczq/getNavigation.do?type=2'}, ] def parse_fund(self, response): fund_urls = response.xpath("//a[contains(text(), '净值公布')]//@href").extract() for fund_url in fund_urls: self.ips.append({ 'url': 'http://www.hczq.com' + fund_url, 'pg': 1, 'ref': response.url, }) yield self.request_next() def parse_item(self, response): rows = response.xpath("//div[@class='col_fr col_w838']//tr") if len(rows) > 1: for row in rows[1:]: fund_name = row.xpath('./td[2]//text()').extract_first().strip() statistic_date = row.xpath('./td[3]//text()').extract_first().strip() item = GGFundNavItem() if '万份收益' not in response.text: nav = row.xpath('./td[4]//text()').extract_first() add_nav = row.xpath('./td[5]//text()').extract_first() if nav: item['nav'] = float(nav.strip()) if nav else None item['added_nav'] = float(add_nav.strip()) if add_nav else None else: income_value_per_ten_thousand = row.xpath('./td[4]//text()').extract_first().strip() d7_annualized_return = row.xpath('./td[5]//text()').extract_first().strip().replace('%', '') item['d7_annualized_return'] = float(d7_annualized_return) if d7_annualized_return else None item['income_value_per_ten_thousand'] = float( income_value_per_ten_thousand) if income_value_per_ten_thousand else None item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item pg = response.meta['pg'] next_pg = pg + 1 next_url = response.url.replace('currentPage=' + str(pg), 'currentPage=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg }) <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-14 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class XinLongYuanSpider(GGFundNavSpider): name = 'FundNav_XinLongYuan' sitename = '深圳前海新隆源投资' channel = '投资顾问' allowed_domains = ['www.sinlongyoon.com'] start_urls = ['http://www.sinlongyoon.com/prolist.asp'] username = 'ZYYXSM' password = '<PASSWORD>' cookies = 'ASPSESSIONIDCSBTADDB=LFCNCHIACDKHHFCCGPCBOJHP; Users=UserName=ZYYXSM&UserID=13; ASPSESSIONIDCSDQCDDA=ALNLHMJAIAPHCCJDEIKBNPCN; company=wzckeckd=agress' fps = [{'url': 'http://www.sinlongyoon.com/prolist.asp'}] def parse_fund(self, response): fund_list = response.xpath('//div[@class="cplist"]/ul/li/a/@href').extract() for key in fund_list: fund_url = urljoin('http://www.sinlongyoon.com/', key) self.ips.append({ 'url': fund_url, 'ref': response.url }) def parse_item(self, response): fund_info = response.xpath('//div[@class="cpdata"]/table[@class="zsbg"][2]//tr') for row in fund_info: row_info = row.xpath('td/text()').extract() fund_name = row_info[0].strip() statistic_date = row_info[1] nav_info = row_info[2] if nav_info[0: 1] == '.': nav = '0' + nav_info else: nav = nav_info item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None item['nav'] = float(nav) if nav else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest from scrapy import Request import re class NingJuTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_NingJuTouZiInvest' sitename = '宁聚投资' channel = '投顾净值' allowed_domains = ['www.zjfunds.com'] username = '13916427906' password = '<PASSWORD>' ips = [{'url': 'http://www.zjfunds.com/gsearch.aspx?curr_menu=products'}] def start_requests(self): yield Request( url='http://www.zjfunds.com/logon.aspx', callback=self.per_login) def per_login(self, response): __VIEWSTATE = \ re.findall(r'<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="(.*?)" />', response.text)[0] __VIEWSTATEGENERATOR = re.findall(r'__VIEWSTATEGENERATOR" value="(.*?)"', response.text)[0] __EVENTVALIDATION = re.findall(r'__EVENTVALIDATION" value="(.*?)"', response.text)[0] yield FormRequest( url='http://www.zjfunds.com/logon.aspx', formdata={ '__VIEWSTATE': __VIEWSTATE, '__VIEWSTATEGENERATOR': __VIEWSTATEGENERATOR, '__EVENTVALIDATION': __EVENTVALIDATION, 'idcard': '13916427906', 'password': '<PASSWORD>', 'btnSubmit': '立即登录', 'chkAgree': 'on' }) def parse_item(self, response): rows = response.xpath("//div[@class='plist']//div[@class='ptb']") for row in rows: fund_name = row.xpath(".//td[@class='title']//text()").extract_first() nav = row.xpath(".//td[@class='prolist_r']/b//text()").extract_first() statistic_date = row.xpath( ".//td[@class='prolist_r']/p[@class='small-font']//text()").extract_first().replace('截至日期:', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class FangZhengDongYaXinTuoSpider(GGFundNoticeSpider): name = 'FundNotice_FangZhengDongYaXinTuo' sitename = '方正东亚信托' entry = 'http://www.gt-trust.com/' lps = [{ 'url': 'http://www.gt-trust.com/index.php/index-show-tid-16.html', }] def parse_list(self, response): notice_types = response.xpath('//div[@class="ny_tit_box"]/a/@href').extract() for notice_type in notice_types: if 'tid-18' not in notice_type: url = urljoin(get_base_url(response), notice_type) self.ips.append({'url': url, 'ref': response.url}) def parse_item(self, response): rows = response.css('.pro_list ul li') next_url = response.xpath('//a[@class="page_right"]/@href').extract_first() for row in rows: url = row.xpath('./h1/a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./h1/a/text()').extract_first() publish_time = row.xpath('./span/text()').re_first(r'(\d+-\d+-\d+)') publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item if next_url: next_url = urljoin(get_base_url(response), next_url) self.ips.append({ 'url': next_url, 'ref': response.url }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 柳美云 # Create_date : 2018-05-04 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class LiuXingTouZiSpider(GGFundNavSpider): name = 'FundNav_LiuXingTouZi' sitename = '杭州流星投资' channel = '投资顾问' fps = [{ 'url': 'http://www.liuxingtouzi.com/wp/%E6%97%97%E4%B8%8B%E4%BA%A7%E5%93%81/' }] def parse_fund(self, response): link_key = response.xpath( "//div[@class='wf-container-main']/div[@id='content']/table/tbody/tr[2]/td[2]/a//@href").extract() for i in link_key: url = i self.ips.append({ 'url': url, 'ref': response.url }) def parse_item(self, response): nav_list = response.xpath( "//div[@class='wpb_text_column wpb_content_element ']/div[@class='wpb_wrapper']/div[2]/table/tbody/tr") fund_name_list = response.xpath("//div[@class='wf-td hgroup']/h1") fund_name = fund_name_list.xpath('.//text()').extract_first() for row in nav_list: i = row.xpath(".//text()").extract() i2 = [_ for _ in i if _.strip()] statistic_date = i2[0].replace('\xa0', '') nav = i2[1] added_nav = i2[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y.%m.%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-21 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class WuDangAssetSpider(GGFundNavSpider): name = 'FundNav_WuDangAsset' sitename = '武当资产' channel = '投顾净值' fps = [{'url': 'http://www.wudangfund.com/Home/Products/index.html'}] def parse_fund(self, response): fid_list = response.css('div.box1_c div.left li > a::attr(href)').re('id/(\d+)/type') name_list = response.css('div.box1_c div.left li > a::text').extract() for fid, fname in zip(fid_list, name_list): self.ips.append({ 'url': 'http://www.wudangfund.com/Home/Products/clist/id/%s/type/3.html' % fid, 'ref': response.url, 'ext': fname }) def parse_item(self, response): rows = response.css('table.table_3 tr')[1:] for r in rows: dt = r.css('td:nth-child(2)::text').extract_first() add_nav = r.css('td:nth-child(3)::text').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = response.meta['ext'] item['channel'] = self.channel item['url'] = response.url item['added_nav'] = float(add_nav) if add_nav else None item['statistic_date'] = datetime.strptime(dt, '%Y-%m-%d') if dt else None yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-08 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest import json import time class NanHuaFuturesSpider(GGFundNavSpider): name = 'FundNav_NanHuaFutures' sitename = '南华期货' channel = '期货净值' username = '13916427906' password = '<PASSWORD>' stamp_href = 't=%s' % int(time.time() * 1000) fps = [{'url': 'https://www.nanhua.net/assetdata/all.json?' + stamp_href}] def start_requests(self): yield FormRequest(url='https://www.nanhua.net/member/newLogin.shtm?start=0&%s' % self.stamp_href, formdata={'account': self.username, 'password': <PASSWORD>, 'isagree': 'on', 'rememberme': '1' }) def parse_fund(self, response): data = json.loads(response.text) for i in data: code = i[0] self.ips.append({ 'url': 'https://www.nanhua.net/assetdata/%s.json?%s' % (code, self.stamp_href), 'ref': response.url, }) def parse_item(self, response): data = json.loads(response.text) for d in data: stamp = d[0] fund_name = d[1] nav = d[2] date = datetime.fromtimestamp(stamp / 1000) item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = date item['nav'] = float(nav) if nav else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-04-27 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class HangZhouDeRuiZiBenTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_HangZhouDeRuiZiBenTouZiInvest' sitename = '杭州德锐资本投资' channel = '投资顾问' fps = [{'url': 'http://www.winner98.net/yejizhanshi/id-1.html'}] def parse_fund(self, response): fund_urls = response.xpath("///div[@class='acc-box']/a") for url in fund_urls: fund_url = url.xpath("./@href").extract_first() fund_name = url.xpath(".//text()").extract_first() self.ips.append({ 'url': 'http://www.winner98.net/?a=ajax&mod=' + fund_url.replace('/', '').replace('id-', '&id=').replace( '.html', '&page=1'), 'ref': response.url, 'pg': 1, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath("//tr") if len(rows) > 1: for row in rows[1:]: statistic_date = row.xpath("./td[2]//text()").extract_first() nav = row.xpath("./td[3]//text()").extract_first().replace('\\u5143","page":"', '').replace('\\u5143', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item pg = response.meta['pg'] next_pg = int(pg) + 1 next_url = response.url.replace('&page=' + str(pg), '&page=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name} }) <file_sep>from datetime import datetime from urllib.parse import urljoin import html from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class YiFanAssetSpider(GGFundNoticeSpider): name = 'FundNotice_YiFanAsset' sitename = '易凡资产' entry = 'http://www.zj-yifan.com/' proxy = 1 username = '13916427906' password = '<PASSWORD>' cookies = 'CODEIMG=502cc2c94be1a7c4ca7ef25b8b50bc04; MUSER=13916427906; MENAME=%E9%83%91%E7%9B%8A%E6%98%8E; MEMBERID=248; MEMBERTYPE=%E4%B8%AA%E4%BA%BA%E5%90%88%E6%A0%BC%E6%8A%95%E8%B5%84%E8%80%85; MEMBERTYPEID=35; ZC=d54dc3f140e0b9cf94769bf2fe887796' lps = [{ 'url': 'http://www.zj-yifan.com/product/class/', 'ext': {'type': '1'} }] def parse_list(self, response): type = int(response.meta['ext']['type']) if type == 1: funds = response.xpath('//*[@id="spdv_16951"]/div/div[2]/div[@class="productquery_dolphin"]') for fund in funds: url = fund.xpath('.//a/@href').extract_first() url = urljoin(get_base_url(response), url) self.lps.append({'url': url, 'ref': response.url, 'ext': {'type': '2'}}) else: urls = response.xpath('//*[@id="spdv_17288"]/div//ul[@class="newslist"]/li/a/@href').extract() for url in urls: url = urljoin(get_base_url(response), url) self.ips.append({'url': url, 'ref': response.url}) def parse_item(self, response): url = response.url title = response.xpath('//*[@id="newscontent"]/div[1]/text()').extract_first() publish_time = response.xpath('//*[@id="newscontent"]/div[2]/text()[1]').re_first('\d+-\d+-\d+ \d+:\d+:\d+') url = urljoin(get_base_url(response), url) item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = html.unescape(title) item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d %H:%M:%S') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-22 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import Request class PathfinderCapitalSpider(GGFundNavSpider): name = 'FundNav_PathfinderCapital' sitename = '舍得之道资产' channel = '投顾净值' allowed_domains = ['www.msnfund.com'] def start_requests(self): yield Request(url='http://www.msnfund.com/f/html/30/category-catid-30.html', callback=self.parse_pre_fund) def parse_pre_fund(self, response): fund_infos = response.xpath('//table[6]//tr//a') for fund_info in fund_infos: fund_url = fund_info.xpath(".//@href").extract_first() fund_name = fund_info.xpath(".//text()").extract_first() self.fps.append({ 'url': fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_fund(self, response): fund_name = response.meta['ext']['fund_name'] fund_url = response.xpath("//a[contains(text(), '基金价格')]//@href").extract_first() self.ips.append({ 'url': fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath('//table[@border="0"][@width="95%"]//td//p') fund_name = response.meta['ext']['fund_name'] for row in rows[5:]: fund_info = ''.join(row.xpath('.//span//text()').extract()).split() if len(fund_info) > 1: statistic_date = fund_info[0] nav = fund_info[1] added_nav = fund_info[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item rows = response.xpath('//table[@border="0"][@width="95%"]//td//div') fund_name = response.meta['ext']['fund_name'] for row in rows[5:]: fund_info = ''.join(row.xpath('.//span//text()').extract()).split() if len(fund_info) > 1: statistic_date = fund_info[0] nav = fund_info[1] added_nav = fund_info[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-04-27 from urllib.parse import urljoin from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class HuiWeiInvestSpider(GGFundNavSpider): name = 'FundNav_HuiWeiInvest' sitename = '汇蔚资产' channel = '投资顾问' fps = [{'url': 'http://www.huiweijijin.com/qxcp/hwcc/'}] def parse_fund(self, response): link_key = response.xpath('//ul[@class="sub_menu"]/li/a/@href').extract() for key in link_key: fund_link = urljoin('http://www.huiweijijin.com/', key.replace('../', '')) self.ips.append({ 'url': fund_link, 'ref': response.url }) def parse_item(self, response): fund_info = response.xpath('//div[@class="sub"]/table/tbody/tr/td[2]/span/text()').extract() fund_name = fund_info[0] statistic_date = fund_info[4] nav = fund_info[1] added_nav = fund_info[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import time class LiShangTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_LiShangTouZiInvest' sitename = '理尚投资' channel = '投顾净值' allowed_domains = ['www.hzlishang.com'] username = '<EMAIL>' password = '<PASSWORD>' cookies = 'ASP.NET_SessionId=icelrswtv1a5vvrxynnglyur; lishang=userid=116&username=%e9%99%88%e7%84%95%e7%84%95' fps = [{'url': 'http://www.hzlishang.com/product.aspx?id=446'}] def parse_fund(self, response): fund_urls = response.xpath("///div[@class='biao1']//@href").extract() for fund_url in fund_urls: self.ips.append({ 'url': 'http://www.hzlishang.com/' + fund_url, 'ref': response.url, }) def parse_item(self, response): fund_name = response.xpath("//div[@class='content2 fr']/h2//text()").extract_first().strip() rows = response.xpath("//table/tbody//tr") for row1 in rows: row = row1.xpath('./td').extract() if len(row) == 4: navs = row1.xpath('./td[1]//text()').extract() nav = ''.join(navs).strip() added_navs = row1.xpath('./td[2]//text()').extract() added_nav = ''.join(added_navs).strip() statistic_dates = row1.xpath('./td[4]//text()').extract() statistic_date = ''.join(statistic_dates).strip() try: time.strptime(statistic_date, "%Y-%m-%d") a = '正确' except: a = '失败' if a == '正确': item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # -*- coding: utf-8 -*- # Department:保障部 # Author:宋孝虎 # Create_Date:2018-04-24 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class CaiTongZhengQuanSecutiesSpider(GGFundNavSpider): name = 'FundNav_CaiTongZhengQuanSecuties' sitename = '财通证券' channel = '券商资管净值' allowed_domains = ['www.ctzg.com'] fps = [{ 'url': 'http://www.ctzg.com/servlet/json?funcNo=904504&page=1&numPerPage=500&conditionArr=%25E5%2585%25A8%25E9%2583%25A8%252C%25E5%2585%25A8%25E9%2583%25A8%252C%25E5%2585%25A8%25E9%2583%25A8%252C%25E5%2585%25A8%25E9%2583%25A8%252C%25E5%2585%25A8%25E9%2583%25A8&jjjc=&sort=%25E5%258F%2591%25E5%25B8%2583%25E6%2597%25B6%25E9%2597%25B41', 'pg': 1}] def parse_fund(self, response): funds = json.loads(response.text)['results'][0]['data'] for fund in funds: type = fund['name'] fund_code = fund['jjdm'] self.ips.append({ 'url': 'http://www.ctzg.com/servlet/json?funcNo=904505&code=' + fund_code + '&catalogIds=&page=1&numPerPage=500', 'ref': response.url, 'pg': 1, 'ext': {'type': type} }) pg = response.meta['pg'] next_pg = pg + 1 self.fps.append({ 'url': response.url.replace('&page=' + str(pg), '&page=' + str(next_pg)), 'ref': response.url, 'pg': next_pg }) def parse_item(self, response): type = response.meta['ext']['type'] nav_info = json.loads(response.text) rows = nav_info['results'][0]['data'] for row in rows: fund_name = row['fundnameeng'] nav = row['tab_rate_1'] added_nav = row['tab_rate_2'] d7_annualized_return = row['tab_rate_2'] income_value_per_ten_thousand = row['tab_rate_1'] statistic_date = row['tradedate'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name if type == '七日年化收益率': item['income_value_per_ten_thousand'] = float(income_value_per_ten_thousand)if income_value_per_ten_thousand else None item['d7_annualized_return'] = float(d7_annualized_return)if d7_annualized_return else None else: item['nav'] = float(nav) if nav is not None and nav != '' else None item['added_nav'] = float(added_nav) if added_nav is not None and added_nav != '' else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item if len(rows) > 1: pg = response.meta['pg'] next_pg = int(pg) + 1 next_url = response.url.replace('&page=' + str(pg), '&page=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'type': type} }) <file_sep># -*- coding: utf-8 -*- import time from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class GuoTaiJunAnSpider(GGFundNoticeSpider): name = 'FundNotice_GuoTaiJunAn' sitename = '国泰君安' entry = 'https://www.gtjazg.com/disclosure?topicCode=dqbg' username = '13916427906' password = '<PASSWORD>' cookies = 'gjzgs1=93258df25a7846b0f01e47621e0e11b2; Hm_lvt_8f8cb8797fca1e91d224d6a674006462=1524446374,1525238928,1525660102; showthemenr=show; remebermobile=13916427906; login_sign=<PASSWORD>; s201_SESSION=4E21CC50F282EDE32C26AD45813F378C; Hm_lpvt_8f8cb8797fca1e91d224d6a674006462=1526266297' lps = [ { 'url': 'https://www.gtjazg.com/disclosurePage?parent_ids=&topicCode=dqbg&p=1&starDate=&entDate=&name=&_={0}'.format(int(round(time.time() * 1000))), 'ref': None, 'pg': 1 } ] def parse_list(self, response): rows = response.xpath('//ul[@class="list2 con-xxpl"]/li/a') for row in rows: url = row.xpath('./@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./span[@class="title"]//text()').extract_first().strip() publish_time = row.xpath('.//text()').re_first('\d+-\d+-\d+') if '...' in title: self.ips.append({ 'url': url, 'ref': response.url }) else: item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = url item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item pg = response.meta['pg'] + 1 tp = int(response.xpath('//div[@class="yl-page"]/p').xpath('string(.)').re_first(r'共([\d]+)页')) if tp >= pg: self.lps.append({ 'url': 'https://www.gtjazg.com/disclosurePage?parent_ids=&topicCode=dqbg&p={0}&starDate=&entDate=&name=&_={1}'.format(pg, int(round(time.time() * 1000))), 'ref': response.url, 'pg': pg }) def parse_item(self, response): title = response.xpath('//div[@class="contentDetail"]/div/h3//text()').extract_first().strip() publish_time = response.xpath('//div[@class="contentDetail"]/div/div[@class ="dateBox"]/div[@class="date f-12px fl"]/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = response.url item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import json class BieJingYouRuiChiInvestSpider(GGFundNoticeSpider): name = 'FundNotice_BieJingYouRuiChiInvest' sitename = '北京佑瑞持投资' entry = 'http://www.urich.cn/' ips = [{ 'url': 'http://www.urich.cn/news.asp?page=1', 'ref': 'http://www.urich.cn/', 'ext': {'page': '1'} }] def parse_item(self, response): ext = response.meta['ext'] page = int(ext['page']) total_page = int(response.xpath('//div[@class="digg"]/a[text()=">"]/@href').re_first(r'page=(\d+)')) notices = response.xpath('//td[@class="newslist"]') years = response.xpath('//td[@class="newslist2"]/text()').extract() for row in notices: url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./a//text()').extract_first() publish_time = years.pop(0) publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item if page < total_page: self.ips.append({ 'url': 'http://www.urich.cn/news.asp?page='+str(page+1), 'ref': response.url, 'ext': {'page': str(page+1)} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-07 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class XunShiFundSpider(GGFundNavSpider): name = 'FundNav_XunShiFund' sitename = '青岛循实投资' channel = '投资顾问' fps = [{'url': 'http://www.xunshifund.com/zhaoshang.asp?id=63'}] def parse_fund(self, response): fund_urls = response.xpath('//div[@class="mian_nav"]/ul/li[4]/a/@href').extract() fund_name = response.xpath('//div[@class="neiy_main"]//div/div[2]/ul/li[1]//text()').extract() for url, name in zip(fund_urls, fund_name): ips_url = urljoin('http://www.xunshifund.com/default.asp', url) fund_name = name self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//div[@class="form_table"]/table/tbody//tr') for row in rows[1:]: fund_date = row.xpath('.//td[1]//text()').extract_first() added_nav = row.xpath('.//td[2]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y年%m月%d日') item['added_nav'] = float(added_nav) yield item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class YinShiInvestSpider(GGFundNavSpider): name = 'FundNav_YinShiInvest' sitename = '银石投资' channel = '投顾净值' username = '123' password = '<PASSWORD>' cookies = 'ASPSESSIONIDCQCSBRCS=BNIPKAKAGFIPCEGMCILKLKEJ; UM_distinctid=1635dde3124186-01657901838b6-3c3c5f0c-15f900-1635dde312535c; ASPSESSIONIDCCSCRQRS=FMENINKBMOECHMBPPCELELDK; ASPSESSIONIDACRBTRRS=DCELAEFCEHDBBLHMGNBEMAPN; CNZZDATA5752077=cnzz_eid%3D616721198-1526285665-http%253A%252F%252Fwww.silver-stone.com.cn%252F%26ntime%3D1527041074' fps = [ {'url': 'http://www.silver-stone.com.cn/product.asp'} ] def parse_fund(self, response): urls = response.xpath( '//*[@id="Container"]/div[2]//div[@class="prv_con"]/table//tr/td[1]/a/@href').extract() for url in urls: url = urljoin(get_base_url(response), url) self.ips.append({ 'url': url, 'ref': response.url }) def parse_item(self, response): fund_name = response.xpath('//*[@id="show1"]/table//tr[1]/th[2]/text()').extract_first() rows = response.xpath('//*[@id="show2"]/div[2]/table//tr') for row in rows[1:]: fund_date = row.xpath('./td[2]/text()').extract_first().strip() nav = row.xpath('./td[3]/text()').extract_first().strip() added_nav = row.xpath('./td[4]/text()').extract_first().strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y年%m月%d日') item['nav'] = float(nav) if nav is not None else None if added_nav is not None and added_nav.count('%') == 0 and added_nav != '-': item['added_nav'] = float(added_nav) if nav is not None else None yield item <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-21 from datetime import datetime from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class SunnyAssetSpider(GGFundNavSpider): name = 'FundNav_SunnyAsset' sitename = '深圳前海阳光宝资产' channel = '投资顾问' allowed_domains = ['www.ygbqh.com'] start_urls = ['http://www.ygbqh.com/products.php'] username = '13916427906' password = '<PASSWORD>' fps = [{'url': 'http://www.ygbqh.com/products.php'}] def start_requests(self): yield FormRequest(url='http://www.ygbqh.com/check_login.php', headers={'Referer': 'http://www.ygbqh.com/userlogin.php'}, formdata={ 'u_user': self.username, 'u_pass': self.<PASSWORD>, 'button': '登 录', 'act': 'login' }) def parse_fund(self, response): fund_list = response.xpath('//div[@class="left_menu"]/a/@href').extract() fund_name_list = response.xpath('//div[@class="left_menu"]/a/text()').extract() pg = 1 for key, name in zip(fund_list, fund_name_list): fund_url = 'http://www.ygbqh.com/' + key + '&cid=2&page=' + str(pg) self.ips.append({ 'url': fund_url, 'ref': response.url, 'pg': pg, 'ext': {'fund_name': name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] page_number = response.xpath( '//div[@class="fypage_blk"]/div[@class="fypage"]/a[text()="尾页"]/@href').extract_first() end_page = int(page_number[-1]) fund_info = response.xpath('//div[@id="products_jz"]/table').extract_first() fund_nav = re.findall('<td>(.*?)</td>', fund_info) fund_nav_list = [fund_nav[i:i + 5] for i in range(0, len(fund_nav), 5)] for nav_info in fund_nav_list: statistic_date = nav_info[2] nav = nav_info[3] added_nav = nav_info[4] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if nav else None yield item pg = response.meta['pg'] if pg < end_page: next_pg = pg + 1 next_url = response.url.replace('&page=' + str(pg), '&page=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-02 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class HongHuTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_HongHuTouZiInvest' sitename = '泓湖投资' channel = '投顾净值' allowed_domains = ['www.honghuinvest.com'] cookies = 'JSESSIONID=72482488132D214E5B0C823D33FF66B1; cookie_2726861_authState=1; configCode=2728275; isRealHost=1; headImageUrl=; customerCode=2745024; companyName=%E4%B8%8A%E6%B5%B7%E6%B3%93%E6%B9%96%E6%8A%95%E8%B5%84%E7%AE%A1%E7%90%86%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8; companyType=1; companyLogo=2726861/image/12ae4a222ce549e9957f3825a2673462.png; companyCode=2726861; type=3; investType=1; nickName=%E4%B8%8A%E6%B5%B7%E6%9C%9D%E9%98%B3%E6%B0%B8%E7%BB%AD%E5%9F%BA%E9%87%91%E9%94%80%E5%94%AE%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8; customerName=%E4%B8%8A%E6%B5%B7%E6%9C%9D%E9%98%B3%E6%B0%B8%E7%BB%AD%E5%9F%BA%E9%87%91%E9%94%80%E5%94%AE%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8; userCode=2745024; simuSiteToken=<PASSWORD>58ecfd93cd4763840e714de<KEY>b52d4bef707<KEY> <PASSWORD> <KEY>fd3837ecc4aa23ca9811223ab36293b06de91ed5a1a68261ac3904a997b1de5b5a70c7ef87a5f80ff7afc138b587db2c39cf0991fd434e9e9b8e4f01ee33549312e0049e05681920b7dd64; telephone=""' fps = [{'url': 'http://www.honghuinvest.com/website/w/h?mt=8&mc=2730542&cc=2726861&fp=d'}] def parse_fund(self, response): fund_ids = response.xpath("//div[@class='clickproduct']") for url in fund_ids: fund_name = url.xpath(".//@productname").extract_first() fund_id = url.xpath(".//@productcode").extract_first() self.ips.append({ 'url': 'http://www.honghuinvest.com/website/mobile/getChartReferData?parms={companyCode:%s,userType:3,ReferCode:0,ProductCode:%s}&_=1525221380874' % ( fund_id, fund_id), 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): nav_info = json.loads(response.text) navs = nav_info['data'][1] added_navs = nav_info['data'][2] fund_name = response.meta['ext']['fund_name'] for row in zip(navs, added_navs): statistic_date = row[0][0] nav = row[0][1] added_nav = row[1][1] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-17 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ShangHaiTaiRongAssetSpider(GGFundNavSpider): name = 'FundNav_ShangHaiTaiRongAsset' sitename = '上海泰荣资产' channel = '投资顾问' allowed_domains = ['www.tairong-asset.com'] fps = [{ 'url': 'http://www.tairong-asset.com/html/products/' }] def parse_fund(self, response): funds = response.xpath('//div[@class ="cncontent"]//li//@href').extract() fund_names = response.xpath('//div[@class ="cncontent"]//li//span//text()').extract() for fund_name, f_url in zip(fund_names, funds): self.ips.append({ 'url': f_url, 'ref': response.url, 'ext': fund_name }) def parse_item(self, response): fund_name = response.meta['ext'] f_list = response.xpath('//div[@id ="content_jz"]//table//tr') for i in f_list[1:]: t = i.xpath('td//text()').extract() # 判断此行含有数据 if '-' in ''.join(t): statistic_date = t[1] nav = t[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date,'%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-14 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy import FormRequest class DiDaoFundSpider(GGFundNavSpider): name = 'FundNav_DiDaoFund' sitename = '深圳狄道投资' channel = '投资顾问' allowed_domains = ['www.didaofund.com'] username = 'ZYYXSM' password = '<PASSWORD>' fps = [{'url': 'http://www.didaofund.com/product.php'}] def start_requests(self): yield FormRequest(url='http://www.didaofund.com/login.php', formdata={'type': 'pc', 'username': 'ZYYXSM', 'pwd': '<PASSWORD>'}, ) def parse_fund(self, response): href_list = response.xpath('//div[@class="c3_b"]//@href').extract() fund_names = response.xpath('//div[@class="c3_b"]//@title').extract() for url, name in zip(href_list, fund_names): ips_url = urljoin('http://www.didaofund.com/', url) fund_name = name self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath('//div[@class="rightbar_cont_photo2"]/table[2]/tbody//tr') fund_name = response.meta['ext']['fund_name'] for row in rows: fund_date = row.xpath('.//td[2]//text()').extract_first() fund_nav = row.xpath('.//td[3]//text()').extract_first() added_nav = row.xpath('.//td[4]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(fund_nav) item['added_nav'] = float(added_nav) yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class ZTZhengQuanZiGuanSpider(GGFundNavSpider): name = 'FundNav_ZTZhengQuanZiGuan' sitename = '中天证券资管' channel = '券商资管净值' fps = [{ 'url': 'http://www.iztzq.com/servlet/json', 'ref': 'http://www.iztzq.com/', 'form': { 'funcNo': '834005', 'curPage': '1', 'numPerPage': '10', 'proType': '4' } }, { 'url': 'http://www.iztzq.com/servlet/json', 'ref': 'http://www.iztzq.com/', 'form': { 'funcNo': '834005', 'curPage': '1', 'numPerPage': '10', 'proType': '5' } }, { 'url': 'http://www.iztzq.com/servlet/json', 'ref': 'http://www.iztzq.com/', 'form': { 'funcNo': '834005', 'curPage': '1', 'numPerPage': '10', 'proType': '6' } }, { 'url': 'http://www.iztzq.com/servlet/json', 'ref': 'http://www.iztzq.com/', 'form': { 'funcNo': '834005', 'curPage': '1', 'numPerPage': '10', 'proType': '7' } }, { 'url': 'http://www.iztzq.com/servlet/json', 'ref': 'http://www.iztzq.com/', 'form': { 'funcNo': '834005', 'curPage': '1', 'numPerPage': '10', 'proType': '8' } } ] def parse_fund(self, response): info_json = json.loads(response.text) datas = info_json['results'][0]['data'] for data in datas: pro_code = data['pro_code'] self.ips.append({ 'url': 'http://www.iztzq.com/servlet/json', 'ref': response.url, 'form': { 'funcNo': '834013', 'code': pro_code, 'page': '1', 'numPerPage': '10' }, 'ext': {'pro_code': pro_code} }) # 总页数 tp = info_json['results'][0]['totalPages'] # 当前页 cp = info_json['results'][0]['currentPage'] if int(cp) < int(tp): cp = cp + 1 self.fps.append({ 'url': 'http://www.iztzq.com/servlet/json', 'ref': response.url, 'form': { 'funcNo': '834005', 'curPage': str(cp), 'numPerPage': '10', 'proType': response.meta['form']['proType'] } }) def parse_item(self, response): info_json = json.loads(response.text) datas = info_json['results'][0]['data'] for data in datas: fund_name = data['pro_name'] nav = data['nav'] add_nav = data['accumulativenav'] statistic_date = data['tradedate'] statistic_date = datetime.strptime(statistic_date, '%Y-%m-%d') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = statistic_date item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(add_nav) if add_nav is not None else None yield item # 总页数 tp = info_json['results'][0]['totalPages'] # 当前页 cp = info_json['results'][0]['currentPage'] pro_code = response.meta['ext']['pro_code'] if int(cp) < int(tp): cp = cp+1 self.ips.append({ 'url': 'http://www.iztzq.com/servlet/json', 'ref': response.url, 'form': { 'funcNo': '834013', 'code': pro_code, 'page': str(cp), 'numPerPage': '10' }, 'ext': {'pro_code': pro_code} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-11 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ShangHaiLaoYuMinInvestSpider(GGFundNavSpider): name = 'FundNav_ygh_ShangHaiLaoYuMinInvest' sitename = '上海老渔民投资' channel = '投资顾问' allowed_domains = ['www.oldfisherman.cn'] cookies = '__guid=184689711.2923636182507737000.1525937386563.4534; PHPSESSID=g7sv1g2vajam6i5n7tu6ho2j01; monitor_count=7' ips = [{ 'url': 'http://www.oldfisherman.cn/product.php', }] def parse_item(self, response): fund = response.xpath('//tbody//tr') for i in fund: t = i.xpath('td//text()').extract() if '产品名称' not in t[0]: item = GGFundNavItem() fund_name = t[0] statistic_date = t[1] nav = t[2] added_nav = t[3] item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-10 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ShangHaiJingXiangAssetsSpider(GGFundNavSpider): name = 'FundNav_ShangHaiJingXiangAssets' sitename = '上海鲸象资产' channel = '投顾净值' allowed_domains = ['www.jxassets.com'] fps = [{'url': 'http://www.jxassets.com/fund.html'}] def parse_fund(self, response): fund_urls = response.xpath('//ul[@id ="treeNav"]//a//@href').extract() for url in fund_urls: self.ips.append({ 'url': 'http://www.jxassets.com/' + url, 'ref': response.url, }) def parse_item(self, response): fund = response.xpath('//table[@id = "table"]//tr') for i in fund[1:]: t = i.xpath('td//text()').extract() item = GGFundNavItem() fund_name = t[0] statistic_date = t[2] nav = t[4] added_nav = t[5] item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class YuJinFundSpider(GGFundNavSpider): name = 'FundNav_YuJinFund' sitename = '裕晋投资' channel = '投顾净值' username = '<EMAIL>' password = '<PASSWORD>' def start_requests(self): yield FormRequest(url='http://www.yujinfund.com/Yzm_consent.html', formdata={'sdsa': '已了解并接受上述所有条款和条件'}, callback=self.parse_login) def parse_login(self, response): yield FormRequest(url='http://www.yujinfund.com/Index_ajaxLogin.html', formdata={'email': self.username, 'password': self.password}, callback=self.parse_fund) fps = [ { 'url': 'http://www.yujinfund.com/Home/Product_index.html', 'ref': None } ] def parse_fund(self, response): rows = response.xpath('//table[@class="container h_pro pro"]/tr')[1:] for row in rows: product_details_id = row.xpath('./td[@class="proname"]/a/@href').re_first(r'Product_details_id_[\d]+') fund_name = row.xpath('./td[@class="proname"]/a/text()').extract_first() self.ips.append({ 'url': 'http://www.yujinfund.com/{0}_type_unit.html'.format(product_details_id), 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//table[@class="h_pro"]/tr')[1:] for row in rows: statistic_date = row.xpath('./td[1]/text()').re_first('\d+-\d+-\d+') nav = row.xpath('./td[2]/text()').re_first('[0-9.]+') added_nav = row.xpath('./td[3]/text()').re_first('[0-9.]+') if fund_name in ['平安*安蕴10期B类', '建信*3号普通级']: nav = row.xpath('./td[5]/text()').re_first('[0-9.]+') added_nav = row.xpath('./td[6]/text()').re_first('[0-9.]+') if nav is not None: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item next_url = response.xpath('//div[@class="page"]/div/a[contains(text(), "下一页")]/@href').extract_first() if next_url: self.ips.append({ 'url': urljoin(get_base_url(response), next_url), 'ref': response.url, 'ext': {'fund_name': fund_name} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest class HeQiYingTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_HeQiYingTouZiInvest' sitename = '上海鹤骑鹰投资' channel = '投资顾问' allowed_domains = ['www.heqiying.com'] username = '15090191207' password = '<PASSWORD>' fps = [ {'url': 'http://www.heqiying.com/fund_mng/desktop/networths'}, {'url': 'http://www.heqiying.com/fund_mng/desktop/networthsclosed'}, ] def start_requests(self): yield FormRequest( url='http://www.heqiying.com/fund_mng/resources/j_spring_security_check', formdata={ 'username': '15090191207', 'password': '<PASSWORD>', }) def parse_fund(self, response): fund_urls = response.xpath("//@data-href").extract() for fund_url in fund_urls: self.ips.append({ 'url': 'http://www.heqiying.com' + fund_url, 'ref': response.url, }) def parse_item(self, response): fund_name = response.xpath("//div[@class='col-md-9']/h4//text()").extract_first() rows = response.xpath("//div[@id='value']//div") for row in rows: statistic_date = row.xpath("./div[@class='col-lg-4'][1]//text()").extract_first() nav = row.xpath("./div[@class='col-lg-4'][2]//text()").extract_first() added_nav = row.xpath("./div[@class='col-lg-4'][3]//text()").extract_first() if statistic_date: statistic_date = statistic_date.strip() nav = nav.strip() added_nav = added_nav.strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import re class ZhongjinInvestSpider(GGFundNoticeSpider): name = 'FundNotice_ZhongjinInvest' sitename = '中金' entry = 'http://www.cicc.com' lps = [{ 'url': 'http://www.cicc.com/portal/business/am_products_cn.xhtml?productType=0&columniditr=528&columnidano=348&columnidlaw=538&attributevalue=ALL' }] def parse_list(self, response): rows = response.xpath('//tbody[@id="listForm:data:tbody_element"]/tr') for row in rows: href = row.xpath('./td[2]/a/@href').re_first(r'(\?\S+)') self.ips.append({ 'url': 'http://www.cicc.com/portal/business/show_amproduct_cn_body.xhtml'+str(href), 'ref': response.url, 'headers': {'Upgrade-Insecure-Requests': '1'} }) def parse_item(self, response): rows = response.xpath('//*[@id="announcement"]/ul/li') if rows: for row in rows: url = row.xpath('./span[1]/a/@onclick').extract_first() urls1 = re.search(r'\'(\/portal\/business\/am\/\S+/)\',', url).group(1) urls2 = re.search(r'\/\',\'(\S*)\'', url).group(1) if urls2 == '': urls2 = re.search(r"showArticle\(\'(\d+)\'", url).group(1) # 152447 url = 'http://www.cicc.com/portal/business/show_amannouncement_cn.xhtml?articleId='+str(urls2) else: url_all = urls1+str('//')+urls2 url = urljoin(get_base_url(response), url_all) title = row.xpath('./span[1]/a/text()').extract_first().strip().replace('\t', '').replace('\r', '').replace('\n', '') publish_time = row.xpath('./span[2]/text()').re_first('\d+-\d+-\d+') publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item rows_another = response.xpath('//div[@id="lawfiles"]/ul/li') if rows_another: for row in rows_another: url = row.xpath('./span/a/@onclick').extract_first() urls1 = re.search(r'\'(\/portal\/business\/am\/\S+/)\',', url).group(1) urls2 = re.search(r'\/\',\'(\S*)\'', url).group(1) if urls2 == '': urls2 = re.search(r"showArticle\(\'(\d+)\'", url).group(1) url = 'http://www.cicc.com/portal/business/show_amannouncement_cn.xhtml?articleId=' + str(urls2) else: url_all = urls1 + str('//') + urls2 url = urljoin(get_base_url(response), url_all) title = row.xpath('./span/a/text()').extract_first().strip().replace('\t', '').replace('\r', '').replace('\n', '') publish_time = None item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item<file_sep> from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin import re class XiNanStockSpider(GGFundNavSpider): name = 'FundNav_XiNanStock' sitename = '西南证券' channel = '券商资管净值' fps = [{ 'url': 'http://www.swsc.com.cn/xnsecu/cpzx/jhlc.jsp?classid=0001000100120011' }] def parse_fund(self, response): funds = response.xpath('/html/body/div[3]/div[2]/div[@class="cl_cats"]/ul/li/a/@title').extract() base_url = 'http://www.swsc.com.cn/xnsecu/cpzx/jhjzss.jsp?pageno=1&hrefURL=&filter=&channelId=' for channel_id in funds: url = base_url + str(channel_id) self.ips.append({'url': url, 'ref': response.url, 'ext': {'page': '1', 'channel_id': str(channel_id)}}) def parse_item(self, response): ext = response.meta['ext'] page = int(ext['page']) channel_id = ext['channel_id'] rows = response.xpath('//tr') fund_name = response.xpath('//tr[1]/th[2]/text()').extract_first() if len(rows) > 2: head_titles = rows[1].xpath('./th/text()').extract() for row in rows[2:]: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url date = row.xpath('./td[1]/text()').extract_first() item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None if head_titles.count('单位净值') > 0 or head_titles.count('单位净值(参考)') > 0: nav = row.xpath('./td[2]/text()').extract_first() item['nav'] = float(nav) if nav else None if head_titles.count('累计净值') > 0 or head_titles.count('累计净值(参考)') > 0: added_nav = row.xpath('./td[3]/text()').extract_first() item['added_nav'] = float(added_nav) if added_nav else None if head_titles.count('七日年化收益') > 0: d7_annualized_return = row.xpath('./td[2]/text()').extract_first() item['d7_annualized_return'] = float(d7_annualized_return) if d7_annualized_return else None if head_titles.count('每万分收益') > 0: income_value_per_ten_thousand = row.xpath('./td[3]/text()').extract_first() item['income_value_per_ten_thousand'] = float(income_value_per_ten_thousand) if income_value_per_ten_thousand else None yield item base_url = 'http://www.swsc.com.cn/xnsecu/cpzx/jhjzss.jsp?hrefURL=&filter=&channelId=' url = base_url + str(channel_id) url = url + '&pageno=' + str(page+1) self.ips.append({'url': url, 'ref': response.url, 'ext': {'page': str(page+1), 'channel_id': str(channel_id)}}) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-08 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class HengJiangUnionSpider(GGFundNavSpider): name = 'FundNav_HengJiangUnion' sitename = '前海恒江联合' channel = '投顾净值' allowed_domains = ['hjlhtz.com'] fps = [{'url': 'http://hjlhtz.com/notice.htm?id=1'}] def parse_fund(self, response): fund_urls = response.xpath("//div[@id='pro_nav_content']/div/div/div//a") for url in fund_urls: fund_url = url.xpath('.//@href').extract_first() ips_url = urljoin('http://hjlhtz.com/products.htm', fund_url) fund_name = url.xpath('.//text()').extract_first() self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath("//table//tr") for row in rows[1:]: fund_date = row.xpath('.//td[1]//text()').extract_first() nav = row.xpath('.//td[2]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y%m%d') item['nav'] = float(nav) yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class HengQinBoDuAssetSpider(GGFundNavSpider): name = 'FundNav_HengQinBoDuAsset' sitename = '博度资产' channel = '投资顾问' username = '18603799126' password = '<PASSWORD>' def start_requests(self): yield FormRequest(url='http://www.broadmeasure.com/ChkLogin.asp', formdata={'UserName': '18603799126', 'Password': '<PASSWORD>'}, callback=self.parse_login) def parse_login(self, response): urls = response.xpath('//div[@id="panel-element-506907"]/div/a/@href').extract() for url in urls: if url.find('#') != -1: url = 'pro.asp' self.fps.append({ 'url': 'http://www.broadmeasure.com/' + url, 'ref': response.url }) def parse_fund(self, response): fund_name = response.xpath('normalize-space(//div[@id="ys"]/table/tbody/tr[1]/td[2]/text())').extract_first() self.ips = [{ 'url': 'http://www.broadmeasure.com/datetab.php', 'ref': response.url, 'ext': {'fund_name': fund_name} }] def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] info_json = json.loads(response.text) rows = info_json['dataList'] for row in rows: statistic_date = row['datelist'] added_nav = row['val'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from scrapy import Request from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class YuanShiAssetSpider(GGFundNavSpider): name = 'FundNav_YuanShiAsset' sitename = '源实资产' channel = '投顾净值' allowed_domains = ['http://www.jvam.com.cn/index.php'] cookies = 'PHPSESSID=fvvj839qqn7turu71h08rbhmt5' # cookie固定 username = '18602199319' password = '<PASSWORD>' def start_requests(self): yield Request(url='http://www.jvam.com.cn/products', callback=self.parse_login) def parse_login(self, response): urls = response.xpath('//ul[@class="pl-ul"]/li/ul/li/a/@href').extract() for url in urls: self.fps.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url }) def parse_fund(self, response): fund_name = response.xpath('normalize-space(//div[@id="pr-info"]/table/tr[1]/td[2]/text())').extract_first() self.ips = [{ 'url': response.url.replace('info', 'data') + '?p=1', 'ref': response.url, 'pg': 1, 'ext': {'fund_name': fund_name} }] def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//tr') if len(rows) != 0: for row in rows: nav = row.xpath('./td[1]/text()').extract_first() added_nav = row.xpath('./td[2]/text()').extract_first() statistic_date = row.xpath('./td[4]/text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item pg = response.meta['pg'] next_pg = int(pg) + 1 next_url = response.url.replace('?p=' + str(pg), '?p=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 # Alter_Date : 2018-05-24 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re import calendar class ShanDongShiJianTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_ShanDongShiJianTouZiInvest' sitename = '山东时间投资' channel = '投资顾问' allowed_domains = ['www.timefund.cn'] ips = [ {'url': 'http://www.timefund.cn/a/fuwuyuchanpin/guonawuliu/'}, ] def parse_item(self, response): fund_name = re.findall("name:'(.*?)',", response.text)[0] navs = re.findall('var chanpinjingzhi = \[(.*?)\];', response.text)[0].replace(' ', '').split(',') statistic_dates = re.findall("var times = \[(.*?)\];", response.text)[0].replace(' ', '').replace("'", '').split(",") for row in zip(statistic_dates, navs): nav = row[1] date = row[0].replace('.', '-') if len(date) < 8: year = int(date[0:4]) month = int(date[5:]) wday, monthrange = calendar.monthrange(year, month) weekday = calendar.weekday(year, month, monthrange) if weekday == 5: monthrange = monthrange - 1 elif weekday == 6: monthrange = monthrange - 2 statistic_date = date + '-' + str(monthrange) else: statistic_date = date item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item fund_name1 = re.findall("name:'(.*?)',", response.text)[2] navs1 = re.findall('var sachina = \[(.*?)\];', response.text)[0].replace(' ', '').split(',') statistic_dates1 = re.findall("var sachinaTimes = \[(.*?)\];", response.text)[0].replace(' ', '').replace("'", '').split(",") for row1 in zip(statistic_dates1, navs1): nav1 = row1[1] date1 = row1[0].replace('.', '-') if len(date1) < 8: year1 = int(date1[0:4]) month1 = int(date1[5:]) wday1, monthrange1 = calendar.monthrange(year1, month1) weekday1 = calendar.weekday(year1, month1, monthrange1) if weekday1 == 5: monthrange1 = monthrange1 - 1 elif weekday1 == 6: monthrange1 = monthrange1 - 2 statistic_date1 = date1 + '-' + str(monthrange1) else: statistic_date1 = date1 item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name1 item['nav'] = float(nav1) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date1, '%Y-%m-%d') yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class TianQiInvestmentSpider(GGFundNavSpider): name = 'FundNav_TianQiInvestment' sitename = '天琪投资' channel = '投资顾问' cookies = 'judge=tq_cookie' fps = [{'url': 'http://www.tqtz.com.cn/qixiazijin/qixiajijin/'}] def parse_fund(self, response): href_list = response.css('div.qxjj_con_1 a::attr(href)').extract() fname_list = response.css('div.qxjj_con_1 p.qxjj_title::text').extract() for href, fname in zip(href_list, fname_list): self.ips.append({ 'url': 'http://www.tqtz.com.cn' + href, 'ref': response.url, 'ext': fname }) def parse_item(self, response): nav_list = re.findall("asd='(.*)';.*zxc=", response.text, re.DOTALL)[0].split('|') date_list = re.findall("zxc='(.*)';.*cpqy=", response.text, re.DOTALL)[0].split('|') for dt, nav in zip(date_list, nav_list): item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = response.meta['ext'] item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav) if nav else None item['statistic_date'] = datetime.strptime(dt, '%Y/%m/%d') if dt else None yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-08 from datetime import datetime from scrapy import FormRequest, Request from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class NaSiTeInvestSpider(GGFundNavSpider): name = 'FundNav_NaSiTeInvest' sitename = '纳斯特' channel = '投顾净值' username = '13916427906' password = '<PASSWORD>' fps = [{'url': 'http://www.gfnest.com/pm/productinformation_doFindProductins.do?code=product'}] def start_requests(self): yield FormRequest(url='http://www.gfnest.com/customers/cust_doLogin.do', formdata={ 'cust.cusiName': '13916427906', 'cust.cusiPassword': '<PASSWORD>' }) def parse_pre_fund(self, response): yield Request(url='http://www.gfnest.com/index.do') def parse_fund(self, response): id_list = response.css('div.left li::attr(id)').extract() name_list = response.css('div.left li a::text').extract() for i, name in zip(id_list, name_list): self.ips.append({ 'url': 'http://www.gfnest.com/pm/productinformation_doQueryProByPk.do?pid=%s' % i, 'ref': response.url, 'ext': name.replace('【已结束】', '').replace('【到期结束】', '') }) def parse_item(self, response): fund_name = response.meta['ext'] rows = response.css('table#table1 tr')[1:] for r in rows: td = r.css('::text').extract() row = [_.strip() for _ in td if _.strip()] date = row[0] nav = row[1] add_nav = row[2] item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') item['nav'] = float(nav) if nav else None item['added_nav'] = float(add_nav) if add_nav else None yield item <file_sep># -*- coding: utf-8 -*- # Department:保障部 # Author:宋孝虎 # Create_Date:2018-05-30 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class JiaMoZiBenInvestSpider(GGFundNavSpider): name = 'FundNav_JiaMoZiBenInvest' sitename = '嘉谟资本' channel = '投顾净值' allowed_domains = ['www.gammacapital.com.cn'] ips = [{ 'url': 'http://www.gammacapital.com.cn/?page_id=9&sk&order=unit_price&face=cont-products', 'ref': 'http://www.gammacapital.com.cn' }] def parse_item(self, response): rows = response.xpath("//div[@class='con_prd_cate active']//tr") for row in rows[1:]: fund_name = row.xpath('./td[1]//text()').extract_first() nav = row.xpath('./td[3]//text()').extract_first() added_nav = row.xpath('./td[4]//text()').extract_first() statistic_date = row.xpath('./td[5]//text()').extract_first().replace('更新日期', '').replace(':', '').replace( '(届满结束)', '').strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None if fund_name == '嘉谟动量': item['statistic_date'] = datetime.strptime(statistic_date, '%d/%m/%Y') else: item['statistic_date'] = datetime.strptime(statistic_date, '%m/%d/%Y') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import json class BeiJingZhongWeiJianInvestSpider(GGFundNoticeSpider): name = 'FundNotice_BeiJingZhongWeiJianInvest' sitename = '北京中外建投资' entry = 'http://www.cciif.cn/product/JN' proxy = 2 cookies = 'JSESSIONID=52F91E698D2ED23089DEA7854BE09812' username = '13916427906' password = '<PASSWORD>' ips = [{'url': 'http://www.cciif.cn/getProductList?pageIndex=1&siteType=JN&pageSize=5', 'ref': None, 'ext': {'page': '1'}}] def parse_item(self, response): page = int(response.meta['ext']['page']) rows = json.loads(response.text) rows = rows['rows'] if len(rows) > 0: for row in rows: url = 'http://www.cciif.cn/showSiteDetail?id=' title = row['title'] publish_time = row['last_update_time'][0:10] publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url + str(row['id']) item['title'] = title item['publish_time'] = publish_time yield item self.ips.append({ 'url': 'http://www.cciif.cn/getProductList?siteType=JN&pageSize=5&pageIndex='+str(page+1), 'ref': response.url, 'ext': {'page': str(page+1)} }) yield self.request_next() <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 柳美云 # Create_date : 2018-05-04 from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class GuoJinChuangXinInvestSpider(GGFundNavSpider): name = 'FundNav_GuoJinChuangXinInvest' sitename = '国金创新投资' channel = '投顾净值' # username = '13916427906' # password = '<PASSWORD>' fps = [{ 'url': 'http://www.gjll.com.cn/index.php?s=/product/detail/sort_id/40/id/17.html' }] def parse_fund(self, response): # 取各产品对应的链接,当前选中和未选中的大类对应上一级class不同,故不取 link_key = response.xpath( '//div[@class="cmm_pro_content"]/div[@class="cmm_pro_left"]/ul//p//@onclick').extract() for i in link_key: url = i.replace('window.location.href=', '').replace("'", '') self.ips.append({ 'url': url, 'ref': response.url }) def parse_item(self, response): list_info = response.xpath('//div[@class="cmm_pro_right"]/div[@class="cmm_pro_rbox"][2]/ul//li') fund_name = list_info.xpath('.//span[1]//text()').extract() statistic_date = list_info.xpath('.//span[2]//text()').extract() nav = list_info.xpath('.//span[3]//text()').extract() added_nav = list_info.xpath('.//span[4]//text()').extract() for fund_name, statistic_date, nav, added_nav in zip(fund_name, statistic_date, nav, added_nav): item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import Request, FormRequest class DongFangGangWanSpider(GGFundNavSpider): name = 'FundNav_DongFangGangWan' sitename = '东方港湾' channel = '投顾净值' username = 'admin888' password = '<PASSWORD>' fps = [{ 'url': 'http://www.ebay-invest.com/Home/Product_detail.html' }] def start_requests(self): yield Request(url='http://www.ebay-invest.com/index_index.html', callback=self.parse_pre_login) def parse_pre_login(self, response): yield FormRequest(url='http://www.ebay-invest.com/Yzm_consent.html', formdata={'sdsa': '确认'}, callback=self.parse_login) def parse_login(self, response): yield FormRequest(url='http://www.ebay-invest.com/Members_login.html', formdata={'username': 'admin888', 'password': '<PASSWORD>'}) def parse_fund(self, response): codes = response.xpath('//div[@class = "fl w260"]//li//a//@href').extract() fundnames = response.xpath('//div[@class = "fl w260"]//li//a/text()').extract() for code, fundname in zip(codes, fundnames): ips_url = 'http://www.ebay-invest.com' + code.replace('.html', '') + '_catid_1_type_unit.html' self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': fundname }) def parse_item(self, response): fund_name = response.meta['ext'] fund_list = response.xpath('//table//tr') for i in fund_list[1:]: t = i.xpath('td//text()').extract() statistic_date = t[1] nav = t[2] added_nav = t[3] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) item['added_nav'] = float(added_nav) yield item if response.xpath('//div//a[@class = "next"]//@href'): next_href = response.xpath('//div//a[@class = "next"]//@href').extract_first() next_url = 'http://www.ebay-invest.com' + next_href self.ips.append({ 'url': next_url, 'ref': response.url, 'ext': fund_name }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 柳美云 # Create_date : 2018-05-04 from urllib.parse import urljoin from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class JiaoYinTrustSpider(GGFundNavSpider): name = 'FundNav_JiaoYinTrust' sitename = '交银信托' channel = '信托净值' fps = [{ 'url': 'https://www.bocommtrust.com/index.php?id=209' }] def parse_fund(self, response): fund_list = response.xpath('//div[@class="number_tablebox"]//div//li//a//@href').extract() for key_fund in fund_list: link_fund = urljoin('https://www.bocommtrust.com/', key_fund) self.ips.append({ 'url': link_fund, 'ref': response.url }) def parse_item(self, response): rows = response.xpath('//div[@class="number_tablebox"]//tr') fund_name = response.xpath('//div[@class="title"]/text()').extract_first() for row in rows[1:]: row_info = row.xpath('td//text()').extract() statistic_date = row_info[0] nav = row_info[1] if len(row_info) > 2 and row_info[4] == '--': income_value_per_ten_thousand = row_info[2] d7_annualized_return = row_info[3] d30_annualized_return = None elif len(row_info) > 2 and row_info[4] != '--': d7_annualized_return = row_info[3] d30_annualized_return = row_info[4] if '(2017年7月20日向中央结算公司和上海清算所支付了债券账户维护费用。)' in row_info[2]: income_value_per_ten_thousand = row_info[2].replace('(2017年7月20日向中央结算公司和上海清算所支付了债券账户维护费用。)', '') else: income_value_per_ten_thousand = row_info[2] else: income_value_per_ten_thousand = None d7_annualized_return = None d30_annualized_return = None item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['income_value_per_ten_thousand'] = float( income_value_per_ten_thousand) if income_value_per_ten_thousand is not None else None item['d7_annualized_return'] = float(d7_annualized_return) if d7_annualized_return is not None else None item['d30_annualized_return'] = float(d30_annualized_return) if d30_annualized_return is not None else None yield item next_urls = response.xpath('//div/a[contains(., "下一")]//@href').extract_first() if next_urls: self.ips.append({ 'url': 'https://www.bocommtrust.com/' + next_urls, 'ref': response.url }) <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-09 from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class ShiPuInvestSpider(GGFundNavSpider): name = 'FundNav_ShiPuInvest' sitename = '深圳石浦投资' channel = '投资顾问' allowed_domains = ['www.sptz.com'] start_urls = ['http://www.sptz.com/products.html'] ips = [{'url': 'http://www.sptz.com/products.html'}] def parse_item(self, response): fund_name = response.xpath( '//table[@class="product_table ke-zeroborder"]//tr[1]/td[2]/text()').extract_first().strip() nav_rows = response.xpath('//div[@class="shop_div"]/table[@class="ke-zeroborder"]//tr') for nav_row in nav_rows[1:]: nav_td = nav_row.xpath('td//text()').extract() if nav_td: if nav_td[1].strip() != '日期': if nav_td[1].strip() == '2017/12/01': statistic_date = nav_td[1].strip() nav = 1.0544 else: statistic_date = nav_td[1].strip() nav = nav_td[2].strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') item['nav'] = float(nav) if nav else None yield item <file_sep>from datetime import datetime, date from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class TianShengQiaoSpider(GGFundNavSpider): name = 'FundNav_TianShengQiao' sitename = '天生桥' channel = '投资顾问' ips = [] for id in ['1', '4']: ips.append({ 'url': 'https://naturebridge-asset.com/api/public/funds/' + id + '/netvalues/start/2001-01-01/end/' + date.isoformat(datetime.now()), 'headers': {'authorization': 'Basic Z<KEY>bVJjMFg4'} }) def parse_item(self, response): fund_name = json.loads(response.text)['name'] rows = json.loads(response.text)['net_values'] for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = row['date'] item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row['value'] item['nav'] = float(nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-24 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class LianChuZhengQuanSecutiesSpider(GGFundNavSpider): name = 'FundNav_LianChuZhengQuanSecuties' sitename = '联储证券' channel = '券商资管净值' allowed_domains = ['mall.lczq.com'] urername = '<EMAIL>' password = '<PASSWORD>' def start_requests(self): ids = ['257', '258', '259', '260', '262', '263', '264', '265', '266', '267', '268', '269', '276', '277', '278', '279', '280', '282', '283', '284', '285', '286', '287', '288', '289', '324', '326', '327', '328', '331', '334', '335', '336', '337', '338', '341', '342', '343', '344', '345', '346', '347', '348', '349', '350', '351', '352', '353', '354', '355', '356', '359', '360', '361', '363', '366', '369', '370', '372', '374', '375', '377', '378', '379'] for id in ids: self.ips.append({ 'url': 'https://mall.lczq.com/servlet/json?funcNo=1000071&product_id=' + id + '&start_date=&end_date=&curPage=1&numPerPage=1000', 'ref': 'https://mall.lczq.com/servlet/', }) yield self.request_next() def parse_item(self, response): row_info = json.loads(response.text) rows = row_info['results'][0]['data'] for row in rows: fund_name = row['product_name'] statistic_date = row['nav_date'].replace('-', '') nav = row['relate_price'] added_nav = row['cumulative_net'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y%m%d') yield item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class XinDaSecuritiesSpider(GGFundNavSpider): name = 'FundNav_XinDaSecurities' sitename = '信达证券' channel = '券商资管净值' fps = [ { 'url': 'http://www.cindasc.com/servlet/json?funcNo=2000025&currentPage=1&numPerPage=500', } ] def parse_fund(self, response): funds = json.loads(response.text)['DataSet0'] for fund in funds: fund_code = fund['productcode'] fund_name = fund['productname'] self.ips.append({ 'url': 'http://www.cindasc.com/servlet/json?funcNo=2000023&ispage=y&numPerPage=500&productcode={}&currentPage=1'.format(fund_code), 'ref': response.url, 'ext': {'fund_name': fund_name, 'fund_code': fund_code}, 'pg': 1 }) def parse_item(self, response): fund_code = response.meta['ext']['fund_code'] fund_name = response.meta['ext']['fund_name'] rows = json.loads(response.text)['DataSet0'] for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = row['networth_date'] item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if fund_name == '信达现金宝集合资产管理计划': d7_annualized_return = row['newnav'] item['d7_annualized_return'] = float(d7_annualized_return) if d7_annualized_return is not None else None else: nav = row['newnav'] item['nav'] = float(nav) if nav is not None else None added_nav = row['totalnav'] item['added_nav'] = float(added_nav) if added_nav is not None else None yield item tp = json.loads(response.text)['DataSet1'][0]['total_pages'] pg = response.meta['pg'] if pg < int(tp): pg += 1 self.ips.append({ 'url': 'http://www.cindasc.com/servlet/json?funcNo=2000023&ispage=y&numPerPage=500&productcode={0}&currentPage={1}'.format(fund_code, pg), 'ext': response.meta['ext'] }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class GanTanHaoTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_GanTanHaoTouZi' sitename = '上海感叹号投资' channel = '投资顾问' allowed_domains = ['www.gthfund.com'] fps = [{'url': 'http://www.gthfund.com/wp-content/themes/dux/action/proddetailhandler.php'}] def parse_fund(self, response): data = json.loads(response.text) fid_list = data['cps'] for i in fid_list: fund_id = i['id'] fund_name = i['prod'] self.ips.append({ 'url': 'http://www.gthfund.com/wp-content/themes/dux/action/data.php?id=' + fund_id + '&page=1&calc=0', 'ref': response.url, 'pg': 1, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): nav_infos = json.loads(response.text) rows = nav_infos['data'] fund_name = response.meta['ext']['fund_name'] for row in rows: statistic_date = row['modtime'] nav = row['nav'] added_nav = row['netnav'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item if len(rows) > 1: pg = response.meta['pg'] next_pg = int(pg) + 1 next_url = response.url.replace('&page=' + str(pg), '&page=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name}, }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class YiBoInvestSpider(GGFundNoticeSpider): name = 'FundNotice_YiBoInvest' sitename = '绎博投资' entry = 'http://www.everinvestment.cn/' username = '<EMAIL>' password = '<PASSWORD>' ips = [ { 'url': 'http://www.everinvestment.cn/xxplybyq', 'ref': 'http://www.everinvestment.cn/' }, { 'url': 'http://www.everinvestment.cn/xxplybeq', 'ref': 'http://www.everinvestment.cn/' } ] def start_requests(self): yield FormRequest(url='http://www.everinvestment.cn/userlogin?returnurl=', formdata={ 'Username': self.username, 'Password': <PASSWORD> }) def parse_item(self, response): times = response.xpath('//div[@class="yibuSmartViewMargin absPos"]/div/div/div/p/span/text()').extract() rows = response.xpath('//div[@class="yibuSmartViewMargin absPos"]/div/a/span/i') for (row, time) in zip(rows, times[3:]): title = row.xpath('./following-sibling::span/text()').extract_first() url = row.xpath('./../../@href').extract_first() url = urljoin(get_base_url(response), url) publish_time = time item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = url item['publish_time'] = datetime.strptime(publish_time, '%Y年%m月%d日') yield item <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-31 from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class JianXinTrustSpider(GGFundNavSpider): name = 'FundNav_JianXinTrust' sitename = '建信信托' channel = '信托净值' allowed_domains = ['www.xingrunfund.com'] start_urls = ['http://www.xingrunfund.com/product.asp'] trs_keyid = [10812, 14149, 14005, 13979, 13980, 14001, 14002, 14003, 14004, 13798, 10814, 10815, 11670, 11465, 11463, 9896, 9744, 8072, 8758, 8931, 8933, 8935, 8937, 8939, 8920, 8922, 8941, 8943, 8945, 8925, 8927, 8913, 8915, 8917, 8924, 8901, 8902, 8903, 8904, 8905, 8784, 8907, 8786, 8787, 8789, 8912, 8788, 8747, 7911, 7794, 7817, 7224, 7028, 6976, 6912, 6681, 6682, 6683, 6321, 5678, 2733, 2818, 3107, 3118, 1664, 1663] main_url = 'http://www.ccbtrust.com.cn/templates/second/index.aspx?nodeid=16&page=ContentPage&contentid=' ips = [] for key in trs_keyid: ips.append({'url': main_url + str(key)}) def parse_item(self, response): nav_rows = response.xpath('//div[@class="acc_content"]//tbody/tr') for row in nav_rows[1:]: nav = ''.join(row.xpath('td[3]//text()').re('\S+')) if nav: fund_name = ''.join(row.xpath('td[1]//text()').extract()) date = ''.join(row.xpath('td[2]//text()').extract()).replace('(成立日)', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name.strip() item['statistic_date'] = datetime.strptime(date.strip(), '%Y-%m-%d') if date else None item['nav'] = float(nav.strip()) if nav else None yield item <file_sep>from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest, Request from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class YiTongInvestSpider(GGFundNavSpider): name = 'FundNav_YiTongInvest' sitename = '易同投资' channel = '投顾净值' username = '15538536932' password = '<PASSWORD>' def start_requests(self): yield Request(url='http://www.etock.com.cn/member/member.php?c=login', callback=self.parse_pre_login) def parse_pre_login(self, response): yield FormRequest(url='http://www.etock.com.cn/member/member.php?a=login', formdata={ 'username': self.username, 'password': <PASSWORD>, 'btnSubmit': '登 录' }, headers={ 'Content-Type': 'application/x-www-form-urlencoded' }, callback=self.parse_login) def parse_login(self, response): self.fps = [{ 'url': 'http://www.etock.com.cn/member/products.php', 'ref': response.url }] def parse_fund(self, response): funds = response.xpath('/html/body/div[3]/div[@class="pdtlist"]/ul/li/a/@href').extract() for url in funds: url = urljoin(get_base_url(response), url) self.ips.append({ 'url': url, 'ref': response.url }) def parse_item(self, response): fund_name = response.xpath( '/html/body/div[3]/div[1]/div[@class="product"]/h1/text()').extract_first() line = response.text dates = re.search(r"\['(\d+.*)'\]", line) if dates: dates = dates.group(1) dates = dates.split(',') rows = re.search(r"\[(\d+\..*\d+)]", line).group(1) rows = rows.split(',') for date in dates: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url nav = rows.pop(0) item['nav'] = float(nav) date = re.search(r'(\d+-\d+-\d+)', date).group(1) item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') yield item <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-17 from datetime import datetime from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class ZCHaiWeiSpider(GGFundNavSpider): name = 'FundNav_ZCHaiWei' sitename = '深圳智诚海威资产' channel = '投顾净值' allowed_domains = ['www.bspartners.com.cn'] start_urls = ['http://www.bspartners.com.cn/'] username = 'ZYYXSM' password = '<PASSWORD>' fps = [{'url': 'http://www.bspartners.com.cn/'}] def start_requests(self): yield FormRequest(url='http://www.bspartners.com.cn/ajax/Login.aspx', headers={'Referer': 'http://www.bspartners.com.cn/'}, formdata={ 'FAction': 'login', 'Name': self.username, 'Pwd': <PASSWORD> }) def parse_fund(self, response): fund_list = response.xpath('//ul[@class="dropdown-menu-next clearfix"][1]/li/a/@href').extract() for key in fund_list: fund_url = urljoin('http://www.bspartners.com.cn', key) self.ips.append({ 'url': fund_url, 'ref': response.url }) def parse_item(self, response): fund_name = response.xpath( '//div[@class="table-box"][1]/table[@class="table-pro"][1]//tr[1]/td[@class ="table-r"]/text()').extract_first() nav_rows = response.xpath('//div[@class="table-box"][2]/table[@class="table-trust-th"][1]//tr') for row in nav_rows[1:]: nav_info = row.xpath('td/text()').extract() statistic_date = nav_info[0].strip() nav = nav_info[1].strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None item['nav'] = float(nav) if nav else None yield item <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-11 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class LiYingCapitalSpider(GGFundNavSpider): name = 'FundNav_LiYingCapital' sitename = '深圳力盈资本' channel = '投资顾问' allowed_domains = ['www.szlyzb.com'] start_urls = ['http://www.szlyzb.com/index.php/lycp'] username = '13916427906' password = '<PASSWORD>' cookies = 'PHPSESSID=u0s1cs2cn2oupc1i75dftti1r2' ips = [{'url': 'http://www.szlyzb.com/index.php/lycp', 'ref': 'http://www.szlyzb.com/'}] def parse_item(self, response): fund_info = response.xpath('//div[@style="height: 400px !important; overflow-x: hidden;"]//tr') for row in fund_info: nav_info = row.xpath('td/text()').extract() fund_name = nav_info[0].strip() statistic_date = nav_info[1].strip() nav = nav_info[2].strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None item['nav'] = float(nav) if nav else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class PinJinZiChanInvestSpider(GGFundNavSpider): name = 'FundNav_PinJinZiChanInvest' sitename = '品今资产' channel = '投顾净值' allowed_domains = ['www.chinapinjinamc.com'] username = 'ZYYXSM' password = '<PASSWORD>' fps = [ {'url': 'http://www.chinapinjinamc.com/index/project/product/page/1', 'pg': 1} ] def parse_fund(self, response): fund_urls = response.xpath("//ul[@class='product_online_list']/li//@href").extract() if fund_urls: for fund_url in fund_urls: self.ips.append({ 'url': fund_url + '?moretable=1&pagedd=1', 'ref': response.url, 'pg': 1 }) pg = response.meta['pg'] next_url = pg + 1 self.fps.append({ 'url': 'http://www.chinapinjinamc.com/index/project/product/page/' + str(next_url), 'ref': response.url, 'pg': next_url }) def parse_item(self, response): rows = response.xpath("//div[@class='value_list value_list_fw clearfix']//tr") fund_name = response.xpath("//h1[@class='list_title clearfix']/span[@class='t']//text()").extract_first() statistic_title = response.xpath( "//div[@class='value_list value_list_fw clearfix']/table/thead/tr/th[7]//text()").extract_first() if len(rows) > 1: for row in rows[1:]: if statistic_title: statistic_date = row.xpath("./td[7]//text()").extract_first().strip() else: statistic_date = row.xpath("./td[4]//text()").extract_first().strip() nav = row.xpath("./td[2]//text()").extract_first() added_nav = row.xpath("./td[3]//text()").extract_first() if nav is not None: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if added_nav is not None: item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item pg = response.meta['pg'] next_pg = pg + 1 self.ips.append({ 'url': response.url.replace('pagedd=' + str(pg), 'pagedd=' + str(next_pg)), 'ref': response.url, 'pg': next_pg, }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-03 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class JiuXuZiChanSpider(GGFundNavSpider): name = 'FundNav_JiuXuZiChan' sitename = '九旭资产' channel = '投顾净值' fps = [{ 'url': 'http://www.jiuxuzc.com/', 'ref': 'http://www.jiuxuzc.com/qixiachanpin/jiuxu2hao/2016-04-13/86.html' }] def parse_fund(self, response): fund_infos = response.xpath('//div[@class="jiuxu_nav"]/ul/li[3]/ul//li') for url in fund_infos: fund_url = url.xpath('.//@href').extract_first() fund_name = url.xpath('.//text()').extract_first() ips_url = urljoin('http://www.jiuxuzc.com/', fund_url) self.ips.append({ 'url': ips_url, 'ref': response.url, 'pg': 1, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): funds = response.xpath("//div[@id='jx_chart']//tr") if funds: fund_name = funds[1].xpath('./td//text()').extract_first() added_nav = funds[3].xpath('./td//text()').extract() fund_date = funds[5].xpath('./td//text()').extract() nav = funds[2].xpath('./td/text()').extract() for i in zip(added_nav, fund_date, nav): added_nav = i[0] statistic_date = i[1] nav = i[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 柳美云 # Create_date : 2018-05-04 from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class ZiTanAssetSpider(GGFundNavSpider): name = 'FundNav_ZiTanAsset' sitename = '杭州紫潭投资' channel = '投顾净值' fps = [{ 'url': 'http://zt-assets.idc.gszwz.cn/list-90-1.html' }] def parse_fund(self, response): fund_href_list = response.xpath('//div[@class="submenu "]/div[@class="subNavBox"]/ul/li/a//@href').extract() for href in fund_href_list: url = 'http://zt-assets.idc.gszwz.cn/' + href self.ips.append({ 'url': url, 'ref': response.url }) def parse_item(self, response): nav_list = response.xpath("//div[@class='main']//ul[2]//tr") fund_name_list = response.xpath("//div[@class='cont']/h2") fund_name = fund_name_list.xpath('.//text()').extract_first() for row in nav_list[1:]: i = row.xpath(".//text()").extract() i2 = [_ for _ in i if _.strip()] statistic_date = i2[0] nav = i2[1] added_nav = i2[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y.%m.%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department:保障部 # Author:王卓诚 # Create_Date:2018-05-28 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class JinDeZiChanInvestSpider(GGFundNavSpider): name = 'FundNav_JinDeZiChanInvest' sitename = '金锝资产' channel = '投顾净值' allowed_domains = ['www.jindefund.com'] fps = [{'url': 'http://www.jindefund.com/page.aspx?node=12'}] def parse_fund(self, response): fund_urls = response.xpath("//div[@class='pz_SideLayer']/li") for url in fund_urls: fund_url = url.xpath('.//@href').extract_first() fund_name = url.xpath('.//text()').extract_first() self.ips.append({ 'url': 'http://www.jindefund.com' + fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath("//div[@class='t_240']/ul/li") fund_name = response.meta['ext']['fund_name'] for row in rows[1:]: statistic_date = row.xpath("./div[1]//text()").extract_first() nav = row.xpath("./div[2]//text()").extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-08 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from FundNavSpiders import FormRequest class RuiYiInvestSpider(GGFundNavSpider): name = 'FundNav_RuiYiInvest' sitename = '睿亿投资' channel = '投资顾问' username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'http://www.ruiyiinvestment.com/product' }] def start_requests(self): yield FormRequest(url='http://www.ruiyiinvestment.com/user/login', formdata={ 'username': self.username, 'password': self.<PASSWORD> }) def parse_fund(self, response): href_list = response.css('div.left a::attr(href)').extract() for href in href_list: self.ips.append({ 'url': 'http://www.ruiyiinvestment.com%s' % href, 'ref': response.url }) def parse_item(self, response): rows = response.css('div.right tr')[1:] for r in rows: row = r.css('td::text').extract() fund_name = row[0] nav = row[1] added_nav = row[2] date = row[3] item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if added_nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from scrapy import FormRequest from FundNoticeSpiders import GGFundNoticeSpider class ChengYangInvestSpider(GGFundNoticeSpider): name = 'FundNotice_ChengYangInvest' sitename = '辰阳投资' entry = 'http://www.ifc-cherami.com/' username = '13916427906' password = '<PASSWORD>' ips = [ { 'url': 'http://www.ifc-cherami.com/index.php?g=portal&m=prod&a=announce', 'ref': None, } ] def start_requests(self): yield FormRequest(url='http://www.ifc-cherami.com/index.php?g=portal&m=user&a=dologin', method='POST', formdata={'login_phone': self.username, 'login_passwd': <PASSWORD>, 'checkbox': 'on'}, headers={ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, ) def parse_item(self, response): datas = response.xpath('/html/body//div[@class="zxxw_C"]/ul/li') for notice in datas: href = notice.xpath('./div/p/a/@href').extract_first().strip() title = notice.xpath('./div/span/text()').extract_first().strip() publish_time = notice.xpath('./div/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = self.entry + href item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep>import json from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class YueCaiXinTuoSpider(GGFundNavSpider): name = 'FundNav_YueCaiXinTuo' sitename = '粤财信托' channel = '信托净值' entry = 'http://www.utrusts.com' fps = [ { 'url': 'http://www.utrusts.com/product/list_20_page_1.html', 'ext': {'type': '1'} } ] def parse_fund(self, response): ext = response.meta['ext'] type = int(ext['type']) if type == 1: fund_list = response.xpath( '//*[@id="warpper"]/section[2]//div[@class="jingzhi"]//div[@class="div5"]/a/@href').extract() next_url = response.xpath( '//*[@id="warpper"]/section[2]//div[@class="Pages"]//a[@class="a_next"]/@href').extract_first() for fund in fund_list: url = fund.strip() url = self.entry + url self.fps.append({ 'url': url, 'ref': response.url, 'ext': {'type': '2'} }) if next_url is not None and next_url != 'javascript:void(0);': url = self.entry + next_url self.fps.append({'url': url, 'ref': response.url, 'ext': {'type': '1'}}) else: url = 'http://www.utrusts.com/Ajax/GetWorthSingleAllData.aspx' pro_code = re.search(r'proCode = "(\d+)"', response.text).group(1) self.ips.append({ 'url': url, 'form': {'procode': pro_code}, 'ref': response.url }) def parse_item(self, response): datas = json.loads(response.text) for data in datas: fund_date = data['ProNetDate'] nav = data['NetWorth'] nav = re.search('[0-9.]+', nav) nav = nav.group(0) if nav else None added_nav = data['CumulativeNet'] added_nav = re.search('[0-9.]+', added_nav) added_nav = added_nav.group(0) if added_nav else None fund_name = data['ProductCode'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if added_nav else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-14 from datetime import datetime from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class TaiChenInvestSpider(GGFundNavSpider): name = 'FundNav_TaiChenInvest' sitename = '泰诚资本' channel = '投顾净值' username = '350402197902120017' password = '<PASSWORD>' fps = [{'url': 'http://www.taichengziben.com/tczb/index.php?m=product&a=index'}] def start_requests(self): yield FormRequest(url='http://www.taichengziben.com/tczb/index.php?m=login&a=index', formdata={ 'username': self.username, 'password': <PASSWORD> }) def parse_fund(self, response): href_list = response.css('div#val_bottom a::attr(href)').extract() for href in href_list: self.ips.append({ 'url': 'http://www.taichengziben.com' + href, 'ref': response.url }) def parse_item(self, response): fund_name = response.xpath('//dl[@class="weizhi"]/dd/text()').extract_first() date_reg = re.findall('categories: \[(.*)\].*labels', response.text, re.DOTALL)[0] nav_reg = re.findall("基金净值走势.*data\s*:\s*\[(.*)\],.*'沪深300'", response.text, re.DOTALL)[0] date_list = [_.strip().replace('"', '') for _ in date_reg.split(',')] nav_list = [_.strip() for _ in nav_reg.split(',')] for date, nav in zip(date_list, nav_list): item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav else None item['statistic_date'] = datetime.strptime(date, '%Y.%m.%d') yield item <file_sep>from datetime import datetime from urllib.parse import urljoin from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class BeijingxingshiInvestSpider(GGFundNavSpider): name = 'FundNav_BeijingxingshiInvest' sitename = '星石投资' channel = '投顾净值' username = '18625981663' password = '<PASSWORD>' cookies = 'ASP.NET_SessionId=23esbiiusvgdl055nj3yyjrr; Remember=True; Cookie_U_Account=18625981663; Cookie_U_Name=123456; Cookie_U_Password=<PASSWORD>; Cookie_U_Group=1; Cookie_U_Level=1; Cookie_U_Phone=18625981663' fps = [{ 'url': 'http://www.starrockinvest.com/xs/invest/wproductinfo?id=1' }] def parse_fund(self, response): urls = response.xpath('//li[@id="all"]/ul/li') for url in urls: code = url.xpath('./a/@name').extract_first() fund_name = url.xpath('./a/text()').extract_first() self.ips.append({ 'url': 'http://www.starrockinvest.com/xs/invest/wproductinfo?id=' + str(code) + '&page=1', 'ref': response.url, 'ext': {'code': code, 'fund_name': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] code = ext['code'] fund_names = ext['fund_name'] rows = response.xpath('//table[@class="pl2"]//tr[position()>1]') for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_names statistic_date = row.xpath("./td[1]/text()").re_first('\d+-\d+-\d+') item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None nav = row.xpath('./td[2]/text()').extract_first() item['nav'] = float(nav) if nav else None yield item next_url = response.xpath('//span[@class="fr"]/a[text()="下一页"]/@href').extract_first() if next_url != 'javascript:void(0)': url = urljoin('http://www.starrockinvest.com', next_url) self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'code': code, 'fund_name': fund_names} }) <file_sep># -*- coding: utf-8 -*- from FundNavSpiders import GGFundNavSpider from FundNavSpiders import GGFundNavItem from scrapy import FormRequest from urllib.parse import urljoin from scrapy.utils.response import get_base_url from datetime import datetime class XinShiJiFuturesSpider(GGFundNavSpider): name = 'FundNav_XinShiJiFutures' sitename = '新世纪期货' channel = '发行机构' username = '18638357950' password = '<PASSWORD>' password_md5 = '<PASSWORD>' fps = [ { 'url': 'http://www.zjncf.com.cn/asset-management/product-value', 'pg': 0 } ] def start_requests(self): yield FormRequest(url='http://www.zjncf.com.cn/user/login', formdata={ 'accountName': self.username, 'password': <PASSWORD>.<PASSWORD>, }) def parse_fund(self, response): rows = response.xpath('//ul[@class="product-value-list"]/li/a') for row in rows: url = row.xpath('./@href').extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url }) count = int(response.xpath('//div[@id="Pagination"]/@data-pagecount').extract_first()) tp = int(count / 20 if count % 20 == 0 else count // 20 + 1) pg = response.meta['pg'] + 1 if pg < tp: self.fps.append({ 'url': 'http://www.zjncf.com.cn/asset-management/product-value?pageNum={0}'.format(pg), 'ref': response.url, 'pg': pg }) def parse_item(self, response): row = response.xpath('//div[@class="news-content"]/div/div').xpath('string(.)') fund_name = row.re_first(r'([^/]+)截[止|至]').strip() statistic_date = row.re_first(r'(\d+年\d+月\d+日)') nav = row.re_first(r'计划份额净值:([0-9.]+)') added_nav = row.re_first(r'累积净值([0-9.]+)') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) if added_nav is not None else added_nav item['statistic_date'] = datetime.strptime(statistic_date, '%Y年%m月%d日') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-08 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy import FormRequest import re class QianHaiFangYuanInvestSpider(GGFundNavSpider): name = 'FundNav_QiMingLeTou' sitename = '启明乐投' channel = '投资顾问' allowed_domains = ['www.qmletou.com'] username = '13916427906' password = '<PASSWORD>' fps = [{'url': 'http://www.qmletou.com/Products.aspx'}] def start_requests(self): yield FormRequest(url='http://www.qmletou.com/System/Users/AddUser.ashx', formdata={'Command': 'Login', 'UserName': '13916427906', 'Password': '<PASSWORD>'} ) def parse_fund(self, response): href_list = response.xpath('//div[@class="left_nav"]//@href').extract() fund_names = response.xpath('//div[@class="left_nav"]/ul/li//text()').extract() for url, name in zip(href_list, fund_names): ips_url = urljoin('http://www.qmletou.com/Products.aspx', url) fund_name = name self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] date_info = re.findall('categories: \[(.*?)\]', response.text)[0] nav_info = re.findall('data: \[(.*?),\]', response.text)[1] added_nav_info = re.findall('data:\[(.*?),\]', response.text)[0] navs = nav_info.split(',') added_navs = added_nav_info.split(',') dates = date_info.split(',') for i in zip(dates, navs, added_navs): fund_date = i[0].replace("'", '') nav = i[1] added_nav = i[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(nav) item['added_nav'] = float(added_nav) yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class XianTongInvestSpider(GGFundNavSpider): name = 'FundNav_XianTongInvest' sitename = '仙童投资' channel = '投资顾问' username = '15838569960' password = '<PASSWORD>' fps = [ { 'url': 'http://www.fairchildfund.com/goods/info/viewinfo?goodsid=4&id=25' } ] def start_requests(self): yield FormRequest(url='http://www.fairchildfund.com/member/user/login', formdata={ 'account': self.username, 'password': <PASSWORD>, 'returnurl': 'http://www.fairchildfund.com/' }, meta={'handle_httpstatus_list': [302]}) def parse_fund(self, response): rows = response.xpath('//ul[@id="cp"]/li/a[contains(@href,"viewinfo")]') for row in rows: url = row.xpath('./@href').extract_first() url = urljoin(get_base_url(response), url) goods_id = row.xpath('./@href').re_first('goodsid=([\d]+)') fund_id = row.xpath('./@href').re_first('&id=([\d]+)') self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'goods_id': goods_id, 'fund_id': fund_id} }) def parse_item(self, response): rows = response.xpath('//div[@class="product_mon clearfix mmm"]/div/table/tr')[1:] for row in rows: fund_name = row.xpath('./td[1]/text()').extract_first() statistic_date = row.xpath('./td[2]/text()').re_first('\d+-\d+-\d+') nav = row.xpath('./td[3]/text()').re_first('[0-9.]+') added_nav = row.xpath('./td[4]/text()').re_first('[0-9.]+') if nav: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item next_url = response.xpath('//div[@id="pages"]/a[last()]/@href').extract_first() if 'javascript' not in next_url: self.ips.append({ 'url': urljoin(get_base_url(response), next_url), 'ref': response.url }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy import Request class YueHaiAssetSpider(GGFundNoticeSpider): name = 'FundNotice_YueHaiAsset' sitename = '上海岳海资产' entry = 'http://www.yuehaizichan.com' ips = [{ 'url': 'http://www.yuehaizichan.com/News_index_catid_4.html', }] def start_requests(self): yield Request(url='http://www.yuehaizichan.com/', method='POST', headers={ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': 'http://www.yuehaizichan.com/'}, callback=self.parse_login) def parse_login(self, response): yield Request( url='http://www.yuehaizichan.com/Index_index.html', headers={ 'Accept': 'application/json, text/javascript, */*; q=0.01', }) def parse_item(self, response): rows = response.xpath('//ul[@class="container_2 new_list clearbox"]/li/a') for row in rows: url = row.xpath('./@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('normalize-space(./div/h3/text())').extract_first() publish_time = row.xpath('normalize-space(./div/time/text())').extract_first() publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-08 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy import FormRequest class QianHaiFangYuanInvestSpider(GGFundNavSpider): name = 'FundNav_QianHaiFangYuanInvest' sitename = '前海方圆资本' channel = '投顾净值' username = 'ZYYXSM' password = '<PASSWORD>' fps = [{'url': 'http://www.qhfyzb.com/content.asp?pid=3'}] def start_requests(self): yield FormRequest(url='http://www.qhfyzb.com/Plus/CheckLogin.asp', formdata={'UserName': 'ZYYXSM', 'UserPswd': 'ZYYXSM123', 'verifycode': '', 'input': '登录'}, ) def parse_fund(self, response): href_list = response.xpath('//div[@class="pic_list"]/div//ul[@class="pic"]//@href').extract() fund_names = response.xpath('//div[@class="pic_list"]/div//ul[@class="pic"]//@alt').extract() for url, name in zip(href_list, fund_names): ips_url = urljoin('http://www.qhfyzb.com/', url) fund_name = name self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath('//ul[@class="tab_ct jz"]/table//tr') fund_name = response.meta['ext']['fund_name'] for row in rows[1:]: fund_date = row.xpath('.//td[3]//text()').extract_first() nav = row.xpath('.//td[4]//text()').extract_first() added_nav = row.xpath('.//td[6]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(nav) item['added_nav'] = float(added_nav) yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-08 # Alter_date : 2018-05-22 from datetime import datetime from scrapy import Request from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class PingAnZhengQuanSecuritySpider(GGFundNavSpider): name = 'FundNav_PingAnZhengQuanSecurity' sitename = '平安证券' channel = '券商资管净值' allowed_domains = ['stock.pingan.com'] def start_requests(self): payload = {"body": {}, "requestId": "c1f177fa16c13202f9934b71db7fc986"} yield Request(url='https://stock.pingan.com/restapi/contentservice/openWeb/collectFinancialList', body=json.dumps(payload), method='POST', headers={ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', 'Referer': 'https://stock.pingan.com/static/webinfo/assetmanage/index.html', 'Content-Type': 'application/json', }, callback=self.parse_fund) def parse_fund(self, response): fund_infos = json.loads(response.text) fund_ids = fund_infos['results']['productList'] for id in fund_ids: fund_name = id['fundName'].strip() fund_id = id['id'] self.ips.append({ 'url': "https://stock.pingan.com/restapi/contentservice/openWeb/queryCFProductHistory", 'ref': response.url, 'ext': {'fund_name': fund_name, 'fund_id': fund_id, 'isnav': '1'}, 'headers': { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', 'Content-Type': 'application/json;charset=UTF-8', }, 'body': json.dumps( {"body": {"pageSize": 15, "pageNo": 1, "id": fund_id, "proType": 0, "startDate": "", "endDate": "", "pageType": 0}, "requestId": "b9024b74c270802d7086907c911d8aff"}), 'pg': 1 }) fund_idss = fund_infos['results']['cashList'] for ids in fund_idss: fund_name = ids['fundName'].strip() fund_id = ids['id'] self.ips.append({ 'url': "https://stock.pingan.com/restapi/contentservice/openWeb/queryCFProductHistory", 'ref': response.url, 'ext': {'fund_name': fund_name, 'fund_id': fund_id, 'isnav': '0'}, 'headers': { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', 'Content-Type': 'application/json;charset=UTF-8', }, 'body': json.dumps( {"body": {"pageSize": 15, "pageNo": 1, "id": fund_id, "proType": 1, "startDate": "", "endDate": "", "pageType": 0}, "requestId": "202ecace8fe64d995d2f271912f7d7ee"}), }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] is_nav = response.meta['ext']['isnav'] nav_info = json.loads(response.text) rows = nav_info['results']['dataList'] for row in rows: statistic_date = row['tradeDate'] item = GGFundNavItem() if is_nav == '1': nav = row['nav'] added_nav = row['accumulativeNav'] item['nav'] = float(nav) item['added_nav'] = float(added_nav) else: income_value_per_ten_thousand = row['fundIncome'] d7_annualized_return = row['yield'] annualized_return = row['fundDayIncome'] item['income_value_per_ten_thousand'] = float(income_value_per_ten_thousand) item['d7_annualized_return'] = float(d7_annualized_return) item['annualized_return'] = float(annualized_return) item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name.replace(' ', '') item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep>from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class DeRuiAssetInvestSpider(GGFundNoticeSpider): name = 'FundNotice_DeRuiAssetInvest' sitename = '杭州德锐资本投资' entry = 'http://www.winner98.net' lps = [ { 'url': 'http://www.winner98.net/news/typeid-3.html', 'ref': None } ] def parse_list(self, response): noticeList = response.xpath('/html/body/div[@class="xiangqing"]/ul/li') for notice in noticeList: noticeLink = notice.xpath('./a/@href').extract_first().strip() title = notice.xpath('./h2/text()').extract_first() publish_time = notice.xpath('./h3/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = urljoin(get_base_url(response), noticeLink) item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep>from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url import re class ShangHaiAoSuoHaoNaAssetSpider(GGFundNoticeSpider): name = 'FundNotice_ShangHaiAoSuoHaoNaAsset' sitename = '上海奥索灏纳资产' entry = 'http://www.panna-wealth.com/' lps = [ { 'url': 'http://www.ashnasset.com.cn/index.php?m=content&c=index&a=lists&catid=25', 'ref': None } ] def parse_list(self, response): noticeList = response.xpath('/html/body/div/div[2]/div[2]/div[3]//div[@class="zp11_1 mg2 xi14"]') next_page = response.xpath('/html/body/div/div[2]/div[2]/div[3]/div[@class="fy cen xi14"]/a[text()="下一页"]/@href').extract_first() cur_page = int(response.xpath('/html/body/div/div[2]/div[2]/div[3]/div[@class="fy cen xi14"]/span/text()').extract_first()) next_page_index = int(re.search(r'page=(\d+)', next_page).group(1)) for notice in noticeList: noticeLink = notice.xpath('./a/@href').extract_first().strip() title = notice.xpath('./a/text()').extract_first() publish_time = notice.xpath('./span/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = urljoin(get_base_url(response), noticeLink) item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item if next_page and cur_page != next_page_index: next_url = urljoin(get_base_url(response), next_page) self.lps.append({ 'url': next_url, 'ref': response.url, }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class HeJuTouZiiInvestSpider(GGFundNavSpider): name = 'FundNav_HeJuTouZiiInvest' sitename = '和聚投资' channel = '投顾净值' username = '13916427906' password = '<PASSWORD>' cookies = 'JSESSIONID=3E6279CA6E1FFA89E14EA08CD565D6C9; acw_tc=AQAAACBIaQwaqwIA9bNuy6fteinTidPa; JSESSIONID=3E6279CA6E1FFA89E14EA08CD565D6C9; JSESSIONID=3E6279CA6E1FFA89E14EA08CD565D6C9; clientlanguage=zh_CN' fps = [{'url': 'https://www.hejufund.com/member/fundInfo/list.jspx'}] def parse_fund(self, response): fund_urls = response.xpath("//div[@id='fundDayDiv']//tr") for url in fund_urls[1:]: fund_name = url.xpath('./td[2]//text()').extract_first() fund_url = url.xpath('./td[2]//@href').extract_first() self.ips.append({ 'url': 'https://www.hejufund.com/member/fundInfo/ferter_info.jspx?fundCode=' + fund_url.replace( '/member/fundInfo/detail.jspx?fundCode=', '').replace('&q=', '') + '&pageIndex=1', 'ref': response.url, 'ext': {'fund_name': fund_name}, 'pg': 1 }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = json.loads(response.text)['list'] if rows: for row in rows: statistic_date = row['cDate'] nav = row['netValue'] added_nav = row['totalNetValue'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item pg = response.meta['pg'] next_pg = pg + 1 next_url = response.url.replace('pageIndex=' + str(pg), 'pageIndex=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name} }) <file_sep># -*- coding: utf-8 -*- # Department:保障部 # Author:宋孝虎 # Create_Date:2018-05-30 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ChuanCaiZhengQuanSecuritySpider(GGFundNavSpider): name = 'FundNav_ChuanCaiZhengQuanSecurity' sitename = '川财证券' channel = '券商资管净值' allowed_domains = ['www.cczq.com'] ips = [{ 'url': 'http://www.cczq.com/cgi-bin/NVFundAction?function=NVFundInfo&curPage=1&numPerPage=10&totalpage=23', 'ref': 'http://www.cczq.com' }] def parse_item(self, response): rows = response.xpath('//tr') for row in rows[1:]: fund_name = row.xpath('./td[1]//text()').extract_first() statistic_date = row.xpath('./td[4]//text()').extract_first() nav = row.xpath('./td[2]//text()').extract_first() added_nav = row.xpath('./td[3]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin import re class ZiJinTrustSpider(GGFundNoticeSpider): name = 'FundNotice_ZiJinTrust' sitename = '紫金信托' entry = 'http://www.zjtrust.com.cn/' lps = [ { 'url': 'https://www.zjtrust.com.cn/cn/page/33.html', 'ref': 'http://www.zjtrust.com.cn', 'ext': {'flag': 0} } ] def parse_list(self, response): if response.meta['ext']['flag'] == 1: pg = response.meta['pg'] self.ips.append({ 'url': response.url + '?pageIndex=' + str(pg), 'ref': response.url, 'pg': pg, 'ext': {'baseUrl': response.url} }) else: urls = response.xpath("//div[contains(text(),'公告') or contains(text(),'报告')]") for url in urls: href = url.xpath('./@onclick').extract_first() if href is None: continue href = re.findall('=\\\'([^\s]*)\\\'', href)[0] type = url.xpath('./text()').extract_first() self.lps.append({ 'url': urljoin(get_base_url(response),href), 'ref': 'http://www.zjtrust.com.cn', 'pg': 1, 'ext': {'flag': 1, 'type': type} }) def parse_item(self, response): datas = response.xpath('/html/body/div[2]/div[2]/div[3]/div[2]/div/table/tbody/tr') for notice in datas: href = notice.xpath('./td[1]/a/@onclick').extract_first() href = re.findall('\d+', href) url = urljoin(get_base_url(response), href[0] + '/' + href[1] + '.html') title = notice.xpath('./td[1]/a/text()').extract_first() publish_time = notice.xpath('normalize-space(./td[2]/text())').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item np = response.xpath('//li[@class="next"]/a[contains(text(),"下一页")]/@href').re_first('\d+') if np is not None: next_url = response.meta['ext']['baseUrl'] + '?pageIndex=' + np self.ips.append({ 'url': next_url, 'ref': response.url, 'ext': {'baseUrl': response.meta['ext']['baseUrl']} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-07 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class HuaXinSecuritiesSpider(GGFundNavSpider): name = 'FundNav_HuaXinSecurities' sitename = '华信证券' channel = '券商资管净值' # username = '13916427906' # password = '<PASSWORD>' fps = [{ 'url': 'https://trade.shhxzq.com/api/product/queryFinanceSuperMarket', 'headers': { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/x-www-form-urlencoded', 'deviceId': 'Bva7x0Ha9HTon9RiJLhtSk', 'browserName': 'Chrome', 'channel': 'P', 'Referer': 'https://trade.shhxzq.com/financialMarket?productType=3', }, 'form': { 'pageSize': '500', 'pageNo': '1', 'productType': '3', }, }] def parse_fund(self, response): funds_list = json.loads(response.text)['resultData']['result'] for fund in funds_list: code = fund['productid'][-6:] # 七日年化收益率;单位净值,年化业绩比较基准 f_type = fund['yieldType'] self.ips.append({ 'url': 'http://www.shhxzq.com/web/zcgl/jhjzList.jsp?FundCode=' + code + '&pageIndex=1&pageSize=9999', 'ref': response.url, 'ext': f_type }) def parse_item(self, response): fund_type = response.meta['ext'] funds_list = json.loads(response.text)['result'] for i in funds_list: statistic_date = i['pubtime'] fund_name = i['name'] item = GGFundNavItem() if '七日年化收益率' in fund_type: ten_thousand = i['dwjz'] d7_annualized = i['ljjz'] item['income_value_per_ten_thousand'] = float(ten_thousand) if ten_thousand != '' else None item['d7_annualized_return'] = float(d7_annualized) if d7_annualized != '' else None else: nav = i['dwjz'] added_nav = i['ljjz'] item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep>from datetime import datetime from scrapy import FormRequest, Request from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class YingDunAssetNavSpider(GGFundNavSpider): name = 'FundNav_YingDunAssetNav' sitename = '盈盾资本' channel = '投资顾问' username = 'ZYYXSM' password = '<PASSWORD>' fps = [{'url': 'http://www.profitshields.com/plus/list.php?tid=3', 'ref': 'http://www.profitshields.com/index.html'}] def start_requests(self): yield Request(url='http://www.profitshields.com/member/login.php', callback=self.parse_pre_login) def parse_pre_login(self, response): url = 'http://www.profitshields.com/member/index_do.php' form = {'fmdo': 'login', 'dopost': 'login', 'gourl': '', 'userid': self.username, 'pwd': <PASSWORD>, 'keeptime': '2592000'} yield FormRequest(url=url, formdata=form, callback=self.parse_login) def parse_login(self, response): yield Request(url='http://www.profitshields.com/index.html') def parse_fund(self, response): funds = response.xpath('/html/body/div[@class="con"]/div[1]/div[1]/ul/li/a') for fund in funds[0:(len(funds)-2)]: url = fund.xpath('./@href').extract_first() fund_name = fund.xpath('./text()').extract_first() url = urljoin(get_base_url(response), url) self.ips.append({'url': url, 'ext': {'fund_name': fund_name}}) def parse_item(self, response): ext = response.meta['ext'] fund_name = ext['fund_name'] rows = response.xpath('//*[@id="blogs_spacerank_2"]/div/table/tbody/tr') for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url statistic_date = row.xpath('./td[2]//text()').re_first(r'\d+-\d+-\d+') item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row.xpath('./td[1]//text()').extract_first() item['nav'] = float(nav) if nav is not None and nav != '' else None added_nav = row.xpath('./td[3]//text()').extract_first() item['added_nav'] = float(added_nav) if added_nav is not None and added_nav != '' else None yield item <file_sep>from scrapy import cmdline cmdline.execute(['scrapy', 'crawl', 'FundNav_CaiKaFeiFundSales', '-a', 'jobId=0L']) # --192.168.0.139 # --select # --select123 # --已配置python抓取的站点 # select distinct sitename,channel # from funddb.dbo.t_nav_general # where sitename = '德邦证券' # # --192.168.0.141 # --select # --select123 # --核查私募数据库中是否有该产品 # select fund_id, fund_full_name, fund_name # from SUNTIME_DB.dbo.t_pf_info # where entry_class = 1 and entry_status = 3 # and (fund_full_name like '%%' --根据产品全称 # or fund_name like '%%') --根据产品简称 # TRS现有站点 # 192.168.0.139 # 库名:funddb # 表名:urlcontent # select top 100 sitename, channel from urlcontent group by sitename, channel order by sitename # 入库数据 # --192.168.0.139 funddb urlcontent表 # select select123 # Department : 保障部 # Author : 钱斌 # Create_date : 2018-04-26<file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-21 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy import FormRequest class BoYangTongZhouSpider(GGFundNavSpider): name = 'FundNav_BoYangTongZhou' sitename = '深圳伯洋同舟资产' channel = '投顾净值' allowed_domains = ['www.boyangtongzhou.com'] phone = '13916427906' password = '<PASSWORD>' fps = [{'url': 'http://www.boyangtongzhou.com/list.php?id=16'}] def start_requests(self): yield FormRequest(url='http://www.boyangtongzhou.com/register.php?act=login', formdata={'tel': '13916427906', 'pwd': '<PASSWORD>'}, ) def parse_fund(self, response): href_list = response.xpath('//div[@class="ht_special"]/div/ul//li//@href').extract() for url in href_list: ips_url = urljoin('http://www.boyangtongzhou.com/', url) self.ips.append({ 'url': ips_url, 'ref': response.url }) def parse_item(self, response): rows = response.xpath('//table[@class="table ke-zeroborder"]/tbody//tr') fund_name = response.xpath('//div[@class="content_msg"]/h1//text()').extract_first().replace('基金净值', '') for row in rows[1:]: fund_date = row.xpath('.//td[1]//text()').re_first('\d+-\d+-\d+') if fund_date is None: continue fund_nav = row.xpath('.//td[2]//text()').extract_first() added_nav = row.xpath('.//td[3]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date.replace(' ', ''), '%Y-%m-%d') item['nav'] = float(fund_nav) item['added_nav'] = float(added_nav) yield item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class YuanXinYongFengFundSpider(GGFundNavSpider): name = 'FundNav_YuanXinYongFengFund' sitename = '圆信永丰基金' channel = '投资顾问' cookies = 'ant_stream_58f8ded42f583=1525780301/2858073168; bow_stream_58f8ded42f583=13; HttpOnly=true; Secure=true; Hm_lvt_db4388806b6dc4f0176aeb7b266292a8=1524205932,1525676217,1525751781; ant_stream_590a19478316c=1525788896/1910063861; bow_stream_590a19478316c=13; bot_stream_590a19478316c=3; JSESSIONID=JpvKhxBJLxMZy8qbdkln56T6qVvqxLhcPYQPnGTpSts2JvmBF25f!-274733271; Hm_lpvt_db4388806b6dc4f0176aeb7b266292a8=1525760569' fps = [{ 'url': 'http://www.gtsfund.com.cn/', 'ext': {'type': '1'} }] def parse_fund(self, response): print(response.text) type = response.meta['ext']['type'] if type == '1': tables = response.xpath('//div[@id="content"]/div[@class="pagefund"]//table') for table in tables: thCount = len(table.xpath(".//tr[1]/th")) rows = table.xpath(".//tr") for row in rows[1:]: is_currency_type = '0' # 是否为货币型产品 if thCount == 6: is_currency_type = '1' fund_code = row.xpath('./td[1]/a/@title').extract_first().strip() fund_name = row.xpath('./td[1]/a/text()').extract_first().strip() self.fps.append({ 'url': 'http://www.gtsfund.com.cn/products/' + fund_code + '/introduction/index.html', 'ref': response.url, 'ext': {'type': '2', 'fund_code': fund_code, 'is_currency_type': is_currency_type, 'fund_name': fund_name} }) if type == '2': fund_name = response.meta['ext']['fund_name'] fund_code = response.meta['ext']['fund_code'] is_currency_type = response.meta['ext']['is_currency_type'] self.ips.append({ 'url': 'http://www.gtsfund.com.cn/chart-web/chart/fundnettable?pages=1-15&fundcode=' + fund_code + '&from=&to=', 'ref': response.url, 'ext': {'fund_code': fund_code, 'fund_name': fund_name, 'page': '1', 'is_currency_type': is_currency_type} }) yield self.request_next() def parse_item(self, response): fund_code = response.meta['ext']['fund_code'] fund_name = response.meta['ext']['fund_name'] is_currency_type = response.meta['ext']['is_currency_type'] tpg = response.xpath('//*[@class="dtitle_t"]/table/tr/td/text()[1]').re_first('共\s*(\d+)\s*页') page = response.meta['ext']['page'] table = response.xpath('//*[@id="dataTable"]') rows = table.xpath(".//tr") for row in rows[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = row.xpath('./td[2]/text()').extract_first().strip() item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if is_currency_type == '0': # 常规产品 nav = row.xpath('./td[3]/text()').extract_first().strip() added_nav = row.xpath('./td[4]/text()').extract_first().strip() item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None if is_currency_type == '1': # 货币型产品 income_value_per_ten_thousand = row.xpath('./td[3]/text()').extract_first().strip() d7_annualized_return = row.xpath('./td[4]/text()').extract_first().strip().replace('%', '') item['income_value_per_ten_thousand'] = float( income_value_per_ten_thousand) if income_value_per_ten_thousand is not None else None item['d7_annualized_return'] = float(d7_annualized_return) if d7_annualized_return is not None else None # self.log(item) yield item if tpg is not None: page = int(page) if page < int(tpg): self.ips.append({ 'url': 'http://www.gtsfund.com.cn/chart-web/chart/fundnettable?pages=' + str( page + 1) + '-15&fundcode=' + fund_code + '&from=&to=', 'ref': response.url, 'ext': {'fund_code': fund_code, 'fund_name': fund_name, 'page': str(page + 1), 'is_currency_type': is_currency_type} }) <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-10 from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class CqJiHongSpider(GGFundNavSpider): name = 'FundNav_CqJiHong' sitename = '稷宏金融' channel = '投资顾问' allowed_domains = ['financ.cqjihong.com'] start_urls = ['http://financ.cqjihong.com/Financ.aspx?pid=15'] ips = [{'url': 'http://financ.cqjihong.com/Ajax/getprolist.ashx', 'ref': 'http://financ.cqjihong.com/Financ.aspx?pid=15', 'form': { 'a': '0', 'pid': '15', 'T_ProductName': '稷宏1号证券私募基金' }, 'pg': 0 }] def parse_item(self, response): if response.xpath('//tr[@class="old"]'): nav_rows = response.xpath('//tr[@class="old"]') for row in nav_rows: nav_info = row.xpath('td/text()').extract() statistic_date = nav_info[0] nav = nav_info[1] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = '稷宏1号证券私募基金' item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None yield item next_pg = response.meta['pg'] + 20 self.ips.append({ 'url': 'http://financ.cqjihong.com/Ajax/getprolist.ashx', 'ref': 'http://financ.cqjihong.com/Financ.aspx?pid=15', 'form': { 'a': str(next_pg), 'pid': '15', 'T_ProductName': '稷宏1号证券私募基金' }, 'pg': next_pg }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-21 from datetime import datetime from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ZhiXinInvestSpider(GGFundNavSpider): name = 'FundNav_ZhiXinInvest' sitename = '无锡智信投资' channel = '投资顾问' username = '123' password = '<PASSWORD>' fps = [{'url': 'http://www.zxwealth.com.cn/zqjy', 'ext': {'type': 'start_url'}}] def start_requests(self): yield FormRequest(url='http://www.zxwealth.com.cn/login?loggedout=true', formdata={ 'log': self.username, 'pwd': <PASSWORD>, 'rememberme': 'forever', 'wp-submit': '登录', 'redirect_to': 'http://www.zxwealth.com.cn/wp-admin/', 'testcookie': '1' }) def parse_fund(self, response): response_type = response.meta['ext']['type'] if response_type == 'start_url': fps_url_list = response.css('div.left_mian a::attr(href)').extract() name_list = response.css('div.left_mian a::text').extract() for fps_url, fname in zip(fps_url_list, name_list): self.fps.append({ 'url': fps_url, 'ref': response.url, 'ext': {'type': 'fps'} }) if response_type == 'fps': ips_url = response.xpath( '//div[@class="tab fb f14 white"]//a[contains(text(),"历史业绩")]/@href').extract_first() self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'type': 'ips'} }) def parse_item(self, response): rows = response.css('tbody#result tr') fund_name = response.css('div.right_mian h2::text').re_first('\S+') for r in rows: td_dt = r.css('td:nth-child(2)::text').extract_first(default='') td_nav = r.css('td:nth-child(3)::text').extract_first(default='') td_add_nav = r.css('td:nth-child(4)::text').extract_first(default='') if '2017-03-34' in td_dt: td_dt = '2017-03-24' item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(td_nav.strip()) if td_nav.strip() else None item['added_nav'] = float(td_add_nav.strip()) if td_add_nav.strip() else None item['statistic_date'] = datetime.strptime(td_dt.strip(), '%Y-%m-%d') if td_dt.strip() else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-16 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class ShangHaiQianKunAssetSpider(GGFundNavSpider): name = 'FundNav_ShangHaiQianKunAsset' sitename = '上海乾堃资产' channel = '投资顾问' allowed_domains = ['www.qk-capital.com'] ips = [{ 'url': 'http://www.qk-capital.com/lists/30/p/1.html', }] def parse_item(self, response): f_list = response.xpath('//tbody//tr') for i in f_list: item = GGFundNavItem() t = i.xpath('td//text()').extract() fund_name = re.findall('.*净值', t[0])[0].replace('净值', '') if i.xpath('td[3]//text()'): nav = t[1] added_nav = t[2] statistic_date = t[3] item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None else: nav = t[1] statistic_date = t[2] item['nav'] = float(nav) if nav is not None else None item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date,'%Y-%m-%d') yield item next_href = response.xpath('//li[@class ="paging_next"]//a[contains(text(),下一页)]//@href').extract_first() if next_href: ips_url = 'http://www.qk-capital.com' + next_href self.ips.append({ 'url': ips_url, 'ref': response.url }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class DongGuanTrustSPider(GGFundNoticeSpider): name = 'FundNotice_DongGuanTrust' sitename = '东莞信托' entry = 'http://www.dgxt.com/searchContent.jspx' lps = [ { 'url': 'http://www.dgxt.com/searchContent.jspx' } ] def parse_list(self, response): rows = response.xpath('//ul[@class="cunb_list"]/li') for row in rows: url = row.xpath('./a/@href').extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url }) def parse_item(self, response): rows = response.xpath('//ul[@class="xcpl"]/li[not(@class)]') for row in rows: url = row.xpath('./span[@class="xmcn_ry"]/a/@href').extract_first() if 'javascript:void(0);' != url: url = urljoin(get_base_url(response), url) else: # 加密公告取当前所在页面地址 url = response.url title = row.xpath('./span[@class="xmcn_ry"]/a/text()').extract_first() publish_time = row.xpath('./span[@class="xmcn_njy"]/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item next_url = response.xpath('//div[@class="pages"]/a[contains(text(),"下一页")]/@href').extract_first() if 'javascript:void(0);' != next_url: self.ips.append({ 'url': urljoin(get_base_url(response), next_url), 'ref': response.url }) <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class ZhaoTuInvestSpider(GGFundNavSpider): name = 'FundNav_ZhaoTuInvest' sitename = '昭图投资' channel = '投顾净值' phone = '13916427906' cookies = 'PHPSESSID=8p82ofqf3tautuu9bg1gbioci3; UM_distinctid=1633fa484141b9-0b4c3c56fee0bf-3c3c5b05-15f900-1633fa4841525; realname=ZYYXSM; CNZZDATA3077745=cnzz_eid%3D144306366-1525775958-%26ntime%3D1527039952; reports=0' fps = [ {'url': 'http://www.zoomtrend.cn/index.php?controller=products&action=read&id=1', 'ext': {'type': '1'} } ] def parse_fund(self, response): ext = response.meta['ext'] type = int(ext['type']) if type == 1: href_list = response.xpath('/html/body/table[3]//tr/td[1]/table[2]//a') for data in href_list: url = data.xpath('./@href').extract_first() fund_name = data.xpath('./text()').extract_first().strip().replace(' ', '') url = urljoin(get_base_url(response), url) self.fps.append({ 'url': url, 'ref': response.url, 'ext': {'type': '2', 'fund_name': fund_name} }) else: fund_name = ext['fund_name'] url = response.xpath('//*[@id="pr_content"]/table//font[text()="基金净值"]/../../@href').extract_first() url = urljoin(get_base_url(response), url) self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'fund_name': fund_name, 'page': '0', 'url': url} }) yield self.request_next() def parse_item(self, response): last_page = response.xpath('//*[@id="LastPage"]/@onclick').re_first('fnOnPageChanged\((\d+)\)') last_page = int(last_page) ext = response.meta['ext'] datas = response.xpath('//*[@id="pr_content"]//table[@class="nets"]//tr') fund_name = ext['fund_name'] page = int(ext['page']) url = ext['url'] next_url = response.xpath('//*[@id="NextPage"]/a') for data in datas[1:]: fund_date = data.xpath('./td[1]/text()').extract_first() nav = data.xpath('./td[2]/text()').extract_first() added_nav = data.xpath('./td[3]/text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name.strip() item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None yield item if page < last_page: self.ips.append({ 'url': url+'&page='+str(page+1), 'ref': response.url, 'ext': {'fund_name': fund_name, 'page': str(page+1), 'url': url} }) yield self.request_next() <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json import re class ShenHongWanYuanzqSpider(GGFundNavSpider): name = 'FundNav_ShenWanHongYuanzq' sitename = '申万宏源证券(原申万)' channel = '券商资管净值' fps = [ { 'url': 'http://www.sywg.com/sywg/busiProduct.do?method=getProductProList&page=1', 'pg': 1 } ] def parse_fund(self, response): funds = json.loads(response.text.replace("'", "\""))['pros'] for fund in funds: fund_name = fund['fundName'] fund_code = fund['productCode'] type = fund['showType'] self.ips.append({ 'url': 'http://www.sywg.com/sywg/busiProduct.do?method=getProductNetValueList&productCode='+ fund_code + '&showSize=10&pageNo=1&type=' + type, 'ext': {'fund_name': fund_name, 'type': type} }) pg = response.meta['pg'] t_count = json.loads(response.text.replace("'", "\""))['totalCount'] tp = int(t_count)/8 if pg < tp: pg += 1 self.fps.append({ 'url': 'http://www.sywg.com/sywg/busiProduct.do?method=getProductProList&page={}'.format(pg), 'pg': pg }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] type = response.meta['ext']['type'] rows = re.search('netList:\[(.*?)\]', response.text).group(1) rows = rows.replace('\\', '') navs = re.findall('valueStr2:\'([0-9.]+)\'', rows) added_navs = re.findall('valueStr1:\'([0-9.]+)\'', rows) dates = re.findall('\d+-\d+-\d+', rows) for nav, added_nav, date in zip(navs, added_navs, dates): item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = date item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if type == '0': nav = nav item['nav'] = float(nav) if nav is not None else None annualized_return = added_nav item['added_nav'] = float(annualized_return) if annualized_return is not None else None else: nav = nav item['nav'] = float(nav) if nav is not None else None added_nav = added_nav item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-08 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib import parse import re class KindoAssetSpider(GGFundNavSpider): name = 'FundNav_KindoAsset' sitename = '津渡资产' channel = '投资顾问' allowed_domains = ['http://www.kindoasset.com/'] fps = [{'url': 'http://www.kindoasset.com/products.asp', }] def parse_fund(self, response): fund_infos = response.xpath('//div[@id="box_l"]/ul/li/a') for url in fund_infos: fund_name = url.xpath('.//text()').extract_first() conditionarr = parse.quote(fund_name) ips_url = 'http://www.kindoasset.com/products.asp?bclasscode=' + conditionarr + '&sclasscode=' + '&page=1' self.ips.append({ 'url': ips_url, 'ref': response.url, 'pg': 1, 'ext': { 'fund_name': fund_name } }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//div[@class="pro_con_b"][@id="con04"]/table//tr') if rows: for row in rows[2:]: statistic_date = row.xpath('.//td[1]//text()').extract_first() nav = row.xpath('.//td[2]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item tpg = re.findall('<option selected="selected" value="value" >(.*?)/(.*?)</option>', response.text)[0][1] pg = response.meta['pg'] old_str = 'page=' + str(pg) if pg < int(tpg): new_str = 'page=' + str(pg + 1) next_url = response.url.replace(old_str, new_str) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': pg + 1, 'ext': {'fund_name': fund_name} }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class ZhongHaiInvestSpider(GGFundNoticeSpider): name = 'FundNotice_ZhongHaiInvest' sitename = '中海信托' entry = 'http://www.zhtrust.com/product/index.shtml' lps = [ { 'url': 'http://www.zhtrust.com/front/fund/Product/findProductBySearch.do?gotoPage=1', 'pg': 1 } ] def parse_list(self, response): rows = response.xpath('//div[@class="pan"]/h4/a') for row in rows: fund_code = row.xpath('./@href').re_first('fundcode=([^/]+)') self.ips.append({ 'url': 'http://www.zhtrust.com/front/fund/Product/findProductArticle.do?gotoPage=1&fundcode={0}'.format(fund_code), 'ref': response.url, 'pg': 1, 'ext': {'fund_code': fund_code} }) tp = int(response.xpath('//div[@class="page"]/ul/li/text()').re_first('共\d+/(\d+)页')) pg = response.meta['pg'] + 1 if pg <= tp: self.lps.append({ 'url': 'http://www.zhtrust.com/front/fund/Product/findProductBySearch.do?gotoPage={0}'.format(pg), 'ref': response.url, 'pg': pg }) def parse_item(self, response): rows = response.xpath('//li[@class="glist"]') if rows: for row in rows: url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./a/text()').extract_first().strip() publish_time = row.xpath('./span/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item ext = response.meta['ext'] fund_code = ext['fund_code'] tp = int(response.xpath('//div[@class="page"]/ul/li/text()').re_first('共\d+/(\d+)页')) pg = response.meta['pg'] + 1 if pg <= tp: self.ips.append({ 'url': 'http://www.zhtrust.com/front/fund/Product/findProductArticle.do?gotoPage={0}&fundcode={1}'.format(pg, fund_code), 'ref': response.url, 'pg': pg, 'ext': {'fund_code': fund_code} }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from scrapy import FormRequest from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ZhongXingHuiJinInvestSpider(GGFundNavSpider): name = 'FundNav_ZhongXingHuiJinInvest' sitename = '中兴汇金投资' channel = '投顾净值' allowed_domains = ['www.sczxhj.com'] fps = [ { 'url': 'http://www.sczxhj.com/zxhj-1/', 'ref': 'http://www.sczxhj.com/', 'ext': {'a': 0} } ] def start_requests(self): yield FormRequest(url='http://www.sczxhj.com/index.php?m=content&c=member&a=login', formdata={'username': 'ZYYXSM', 'password': '<PASSWORD>'}, ) def parse_fund(self, response): ext = response.meta['ext'] a = ext['a'] if a == 1: fund_name = response.meta['ext']['fund_name'] fund_url = response.meta['ext']['fund_url'] self.ips.append({ 'url': fund_url + '?page=1', 'ref': response.url, 'ext': {'fund_name': fund_name, 'fund_url': fund_url} }) else: fund_urls = response.xpath('//ul[@class="btn"]/li /a') for fund in fund_urls: fund_name = fund.xpath('./text()').extract_first() url = fund.xpath("./@href").extract_first() if url: fund_url = urljoin(get_base_url(response), url) self.fps.append({ 'url': fund_url, 'ref': response.url, 'ext': {'a': 1, 'fund_name': fund_name, 'fund_url': fund_url} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//div[@class="Details"]/ul/li') for row in rows[1:]: nav = row.xpath("./div[4]/text()").extract_first() nav = "".join(nav.split()) add_nav = row.xpath("./div[5]/text()").extract_first() add_nav = "".join(add_nav.split()).replace("..", ".") statistic_date = row.xpath("./div[3]/text()").extract_first() statistic_date = "".join(statistic_date.split()) item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(add_nav) if add_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item fund_url = response.meta['ext']['fund_url'] next_url = response.xpath("//a[contains(@title, '下一页')]/@href").extract_first() next_url = fund_url + next_url if next_url is not None and next_url != response.url: self.ips.append({ 'url': next_url, 'ref': response.url, 'ext': {'fund_name': fund_name, 'fund_url': fund_url} }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class ZhongXinTrustSpider(GGFundNoticeSpider): name = 'FundNotice_ZhongXinTrust' sitename = '中信信托' entry = 'https://trust.ecitic.com/information/index.shtml' ips = [ { 'url': 'https://trust.ecitic.com/information/clgg/index.shtml', 'ext': {'url_type': 'clgg'}, 'pg': 1 }, { 'url': 'https://trust.ecitic.com/information/xtswglbg/index.shtml', 'ext': {'url_type': 'xtswglbg'}, 'pg': 1 }, { 'url': 'https://trust.ecitic.com/information/qsbg/index.shtml', 'ext': {'url_type': 'qsbg'}, 'pg': 1 }, { 'url': 'https://trust.ecitic.com/information/qtbg/index.shtml', 'ext': {'url_type': 'qtbg'}, 'pg': 1 } ] def parse_item(self, response): ext = response.meta['ext'] rows = response.xpath('//div[@class="newsList"]/div') for row in rows: title = row.xpath('./a/@title').extract_first() url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) publish_time = row.xpath('./span/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = url item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item url_type = ext['url_type'] tp = int(response.xpath('//div[@class="pageinfo"]/text()').re_first('\d+')) pg = response.meta['pg'] + 1 if pg <= tp: self.ips.append({ 'url': 'https://trust.ecitic.com/information/{0}/index_{1}.shtml'.format(url_type, pg), 'ref': response.url, 'ext': {'url_type': url_type}, 'pg': pg }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest from scrapy.utils.response import get_base_url from urllib.parse import urljoin class PuShiTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_PuShiTouZiInvest' sitename = '朴石投资' channel = '投资顾问' allowed_domains = ['www.postone.com.cn'] username = '<EMAIL>' password = '<PASSWORD>' fps = [{'url': 'http://www.postone.com.cn/info.asp?base_id=2'}] def start_requests(self): yield FormRequest(url='http://www.postone.com.cn/user_login.asp', formdata={'name': '<EMAIL>', 'pass': '<PASSWORD>'}, callback=self.parse_fund) def parse_fund(self, response): fund_urls = response.xpath("//div[@class='menu']/dl/dt//@href").extract() for fund_url in fund_urls: self.ips.append({ 'url': 'http://www.postone.com.cn/' + fund_url + '&page=1', 'ref': response.url, 'pg': 1 }) def parse_item(self, response): rows = response.xpath("//div[@class='list2']/ul//li") if len(rows) > 1: for row in rows[1:]: fund_name = row.xpath(".//span[@class='title']//text()").extract_first() statistic_date = row.xpath(".//span[@class='title4']//text()").extract_first() nav = row.xpath("./span[@class='title3'][2]//text()").extract_first() added_nav = row.xpath("./span[@class='title2']//text()").extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item next_url = response.xpath('//a[text()="下一页"]/@href').extract_first() if next_url and next_url != 'javascript:void(0);': # pg = response.meta['pg'] # next_pg = pg + 1 # self.ips.append({ # 'url': response.url.replace('page=' + str(pg), 'page=' + str(next_pg)), # 'ref': response.url, # 'pg': next_pg, # }) self.ips.append({ 'url': urljoin(get_base_url(response), next_url), 'ref': response.url }) <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-22 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class LianHeLiYeSpider(GGFundNavSpider): name = 'FundNav_LianHeLiYe' sitename = '深圳前海联合利业投资' channel = '投顾净值' allowed_domains = ['www.qhlhly.com'] start_urls = ['http://www.qhlhly.com/product.aspx?key=1'] username = '350402197902120017' password = '<PASSWORD>' cookies = 'Hm_lvt_32deacaddae51078587f3f5c35c88f1d=1527065297; ASP.NET_SessionId=oauzy12nr3c3rxxmo0mn4lcn; Hm_lpvt_32deacaddae51078587f3f5c35c88f1d=1527065841' ips = [{'url': 'http://www.qhlhly.com/product.aspx?key=1'}] def parse_item(self, response): name_info = response.xpath('//div[@class="wapper clearfix overhide"]/dl[@class="subleft"]/dd/a/text()').extract() nav_area = response.xpath('//div[@id="page01s01"]/div[contains(@class,"box_b")]/div') for name, nav_detail in zip(name_info, nav_area): fund_name = name nav_info = nav_detail.xpath('div[contains(@id,"area")]') for n in nav_info: nav_rows = n.xpath('table/tbody/tr') for row in nav_rows[1:]: nav_info_detail = row.xpath('td/text()').extract() statistic_date = nav_info_detail[1] nav = nav_info_detail[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') if statistic_date else None item['nav'] = float(nav) if nav else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-04 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class CapallAssetSpider(GGFundNavSpider): name = 'FundNav_CapallAsset' sitename = '开宝资产' channel = '投资顾问' fps = [{'url': 'http://www.capall.com.cn/', 'ref': 'http://www.kindoasset.com/'}] def parse_fund(self, response): fund_infos = response.xpath('//div[@class="navbox"]/div/ul/li[5]/ul//li') for url in fund_infos: fund_url = url.xpath('.//@href').extract_first() fund_name = url.xpath('.//text()').extract_first() ips_url = urljoin('http://www.capall.com.cn/', fund_url) self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath("//div[@class='skmain']/div[2]//tr") for row in rows[1:]: fund_name = row.xpath('.//td[1]//text()').extract_first() fund_date = row.xpath('.//td[5]//text()').extract_first() fund_nav = row.xpath('.//td[2]//text()').extract_first() if fund_nav: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date.replace('.', '-'), '%Y-%m-%d') item['nav'] = float(fund_nav) yield item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin import re class ZhongYinGuoJiStockSpider(GGFundNavSpider): name = 'FundNav_ZhongYinGuoJiStock' sitename = '中银国际' channel = '券商资管净值' fps = [{ 'url': 'http://www.bocichina.com/boci/asset/mfinancing/productIntro.jsp?productCode=A80001&forthMenu=qtcd_asset_jhlc_one_cpjj&secondMenu=qtcd_asset_jhlc' }] def parse_fund(self, response): funds = response.xpath('//td[@background="/boci/pic/gk_10.jpg"]/a') for fund in funds[0:1]: code = fund.xpath('./@onclick').re_first(r'productCode=(\S+)\'') if code is None: code = 'A80001' fund_name = fund.xpath('./text()').re_first(r'·(\S+)') url = 'http://www.bocichina.com/boci/colNetValueAction.do?method=list&productCode=' + code url = url + '&forthMenu=qtcd_asset_jhlc_' + code self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'page': '1', 'url': url, 'fund_name': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] fund_name = ext['fund_name'] page = int(ext['page']) base_url = ext['url'] rows = response.xpath('//td[@bgcolor="#ffffff"]') if rows and len(rows) > 1: rows = rows[1] rows = rows.xpath('.//tr') head_row = rows[0].xpath('./td/text()').re('\S+') if rows and len(rows) > 1: for row in rows[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url statistic_date = row.xpath('./td[1]/text()').extract_first() item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None if head_row.count('单位净值') > 0: nav = row.xpath('./td[2]/text()').extract_first() item['nav'] = float(nav) if nav else None if head_row.count('累计净值') > 0: added_nav = row.xpath('./td[3]/text()').extract_first() item['added_nav'] = float(added_nav) if added_nav else None if head_row.count('每万份收益') > 0: income_value_per_ten_thousand = row.xpath('./td[2]/text()').extract_first() item['income_value_per_ten_thousand'] = float( income_value_per_ten_thousand) if income_value_per_ten_thousand else None if head_row.count('七日年化收益率') > 0: d7_annualized_return = row.xpath('./td[3]/text()').re_first('(\d+\.?\d*)') item['d7_annualized_return'] = float(d7_annualized_return) if d7_annualized_return else None yield item url = base_url + '&pagesize=10&currentPage=' + str(page + 1) self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'page': str(page + 1), 'url': base_url, 'fund_name': fund_name} }) <file_sep>import json from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class XiangCaiZhengQuanSpider(GGFundNavSpider): name = 'FundNav_XiangCaiZhengQuan' sitename = '湘财证券' channel = '券商资管净值' fps = [{ 'url': 'https://ziguan.xcsc.com/main/zcgl/qxcp/DA0001/cpgk.shtml' }] def parse_fund(self, response): funds = response.xpath('//ul[@id="qxcpul"]/li/a') for fund in funds: fund_name = fund.xpath('./text()').extract_first() code = fund.xpath('./@href').re_first('[A-Z]+\d+') self.ips.append({ 'url': 'https://ziguan.xcsc.com/servlet/asset/AssetManage', 'ref': response.url, 'form': { 'function': 'loadFundJz', 'fundcode': code, 'curPage': '1', 'numPerPage': '10', 'reqUrl': '/servlet/asset/AssetManage?function=loadFundJz&fundcode=' + code, '_': '1526452208722' }, 'ext': {'fund_name': fund_name, 'fund_code': code} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath('//table/tr') type = response.xpath('//table/tr[1]/th[2]/text()').extract() for row in rows[1:]: statistic_date = row.xpath('./td[1]/text()').extract_first() if statistic_date is None or statistic_date == '': continue nav = row.xpath('./td[2]/text()').extract_first() added_nav = row.xpath('./td[3]/text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y%m%d') if '份额净值' in type: item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None elif '万份收益' in type: item['income_value_per_ten_thousand'] = float(nav) if nav is not None and nav != '--' else None item['annualized_return'] = float(added_nav.strip('%'))/100.0 if added_nav is not None and added_nav != '--' else None yield item if len(rows) > int(response.meta['form']['numPerPage']): code = response.meta['ext']['fund_code'] pg = response.meta['form']['curPage'] pg = int(pg)+1 self.ips.append({ 'url': 'https://ziguan.xcsc.com/servlet/asset/AssetManage', 'ref': response.url, 'form': { 'function': 'loadFundJz', 'fundcode': code, 'curPage': str(pg), 'numPerPage': '10', 'reqUrl': '/servlet/asset/AssetManage?function=loadFundJz&fundcode=' + code, '_': '1526452208722' }, 'ext': {'fund_name': fund_name, 'fund_code': code} }) <file_sep>from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url class ShanZhaShuInvestSpider(GGFundNoticeSpider): name = 'FundNotice_ShanZhaShuInvest' sitename = '山楂树投资' entry = 'http://www.hawthorninvest.com/' lps = [ { 'url': 'http://www.hawthorninvest.com/asset/dynamic', 'ref': None } ] def parse_list(self, response): notices = response.xpath('/html/body/div[4]//div[@class="trends"]/dl') for notice in notices: url = notice.xpath('./dd/a/@href').extract_first().strip() url = urljoin(get_base_url(response), url) title = notice.xpath('./dd/a/h3/text()').extract_first() publish_time_year = notice.xpath('./dt/text()').extract_first() publish_time_day = notice.xpath('./dt/b/text()').extract_first() publish_time = publish_time_year + '-' + publish_time_day item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time.strip(), '%Y-%m-%d') yield item next_page = response.xpath('/html/body/div[4]/div[2]/div[@class="paging"]//a[text()="下一页"]/@href').extract_first() if next_page is not None and next_page != 'javascript:': next_url = urljoin(get_base_url(response), next_page) self.lps.append({ 'url': next_url, 'ref': response.url, }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin class YunGuoInvestSpider(GGFundNoticeSpider): name = 'FundNotice_YunGuoInvest' sitename = '云国投' entry = 'http://www.yntrust.com' ips = [ { 'url': 'http://www.yntrust.com/Disclosure/Notice', 'ref': 'http://www.yntrust.com/Disclosure/Index' } ] def __init__(self, *args, **kwargs): super(YunGuoInvestSpider, self).__init__(*args, **kwargs) def parse_item(self, response): datas = response.xpath('/html/body/section[2]/div//ul[@class="bulletin_main clearfix"]/li') next_url = response.xpath('/html/body/section[2]/div//div[@class="page"]/div/a[last()]/@href').extract_first() for notice in datas: href = notice.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), href) title = notice.xpath('./a/span/text()').extract_first().strip() publish_time = notice.xpath('./a/time/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item if next_url is not None and next_url != '': url = self.entry + next_url self.ips.append({'url': url, 'ref': response.url}) yield self.request_next() <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class GuangdajinkongInvestSpider(GGFundNoticeSpider): name = 'FundNotice_GuangdajinkongInvest' sitename = '上海光大金控投资' entry = 'http://www.ebasset.com/' ips = [{ 'url': 'http://www.ebasset.com/?q=notice-eba', }] def parse_item(self, response): rows = response.xpath('//table[@class="views-view-grid cols-1"]//tr') for row in rows: url = row.xpath('./td/span/span/a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./td/span/span/a/text()').extract_first().replace('\t', '').replace('\r', '').replace('\n', '') publish_time = row.xpath('./td/div/div/span/@content').extract_first() publish_time = publish_time[0:10] publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item next_url = response.xpath('//ul[@class="pager"]/li/a[contains(text(),"下一页")]/@href').extract_first() if next_url: next_url = urljoin(get_base_url(response), next_url) self.ips.append({ 'url': next_url, 'ref': response.url })<file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest from scrapy import Request class LaiYinYingXueTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_LaiYinYingXueTouZiInvest' sitename = '莱茵映雪投资' channel = '投资顾问' allowed_domains = ['www.lsl-invest.com'] username = '18521028957' password = '<PASSWORD>' fps = [{'url': 'http://www.lsl-invest.com/product/qjcp159/'}] def start_requests(self): yield FormRequest(url='http://www.lsl-invest.com//register.php?login=now', formdata={'password': '<PASSWORD>', 'userphone': '18521028957', }, callback=self.parse_fund) def parse_fund(self, response): fund_urls = response.xpath("//div[@class='snow_fdiv']//@href").extract() for fund_url in fund_urls: self.ips.append({ 'url': fund_url + 'p1.html', 'ref': response.url, 'pg': 1 }) def parse_item(self, response): fund_name = response.xpath("//div[@class='sitemp clearfix']/h2//text()").extract_first().strip() rows = response.xpath("//div[@class='snow_value mt10']/div//tr") if rows: for row in rows: nav = row.xpath('./td[3]//text()').extract_first() statistic_date = row.xpath('./td[2]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item pg = response.meta['pg'] next_pg = int(pg) + 1 next_url = response.url.replace('/p' + str(pg) + '.html', '/p' + str(next_pg) + '.html') self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, }) <file_sep># -*- coding: utf-8 -*- from scrapy import cmdline #上海沃胜资产管理有限公司 # cmdline.execute(['scrapy', 'crawl', 'FundNav_ShangHaiWoShengAsset', '-a', 'jobId=0L']) #深圳市长流资本管理有限公司 # cmdline.execute(['scrapy', 'crawl', 'FundNav_ChangLiuInvest', '-a', 'jobId=0L']) #云南卓晔投资管理有限公司 # cmdline.execute(['scrapy', 'crawl', 'FundNav_ZhuoYeInvest', '-a', 'jobId=0L']) #紫金信托有限责任公司 # cmdline.execute(['scrapy', 'crawl', 'FundNav_ZiJinTrust', '-a', 'jobId=0L']) # 厦门中略投资管理有限公司 # cmdline.execute(['scrapy', 'crawl', 'FundNav_ZhongLueInvest', '-a', 'jobId=0L']) # 新湖期货 # cmdline.execute(['scrapy', 'crawl', 'FundNav_XinHuFutures', '-a', 'jobId=0L']) # 中天证券资管 # cmdline.execute(['scrapy', 'crawl', 'FundNav_ZTZhengQuanZiGuan', '-a', 'jobId=0L']) # 湘财证券 # cmdline.execute(['scrapy', 'crawl', 'FundNav_XiangCaiZhengQuan', '-a', 'jobId=0L']) # 西南证券 券商PB净值 # cmdline.execute(['scrapy', 'crawl', 'FundNav_XiNanZhengQuanPB', '-a', 'jobId=0L']) #登录 #珠海横琴博度资产管理有限公司 # cmdline.execute(['scrapy', 'crawl', 'FundNav_HengQinBoDuAsset', '-a', 'jobId=0L']) #四川中兴汇金投资有限公司 # cmdline.execute(['scrapy', 'crawl', 'FundNav_ZhongXingHuiJinInvest', '-a', 'jobId=0L']) #上海源实资产管理有限公司 # cmdline.execute(['scrapy', 'crawl', 'FundNav_YuanShiAsset', '-a', 'jobId=0L']) # 厦门祐益峰资产 # cmdline.execute(['scrapy', 'crawl', 'FundNav_YouYiFengAsset', '-a', 'jobId=0L']) # 新价值 # cmdline.execute(['scrapy', 'crawl', 'FundNav_NewValue', '-a', 'jobId=0L']) # 尊嘉资产 # cmdline.execute(['scrapy', 'crawl', 'FundNav_ZunJiaAsset', '-a', 'jobId=0L']) #公告 #深圳前海韬选优胜资产 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_TaoXuanYouShengAsset', '-a', 'jobId=0L']) # 上海稻沣投资 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_DaoFengInvest', '-a', 'jobId=0L']) # 广发基金 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_GuangFaFund', '-a', 'jobId=0L']) # 昊恩投资 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_HaoenInvest', '-a', 'jobId=0L']) #嘉澳投资 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_JiaAoInvest', '-a', 'jobId=0L']) # 北京华觉资产 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_HuaJueAsset', '-a', 'jobId=0L']) # 映雪投资公告 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_YingXueInvest', '-a', 'jobId=0L']) # 紫金信托公告 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZiJinTrust', '-a', 'jobId=0L']) # 中信建投 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongXinJianTou', '-a', 'jobId=0L']) # 泓澄投资 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_HongChengInvest', '-a', 'jobId=0L']) # 深圳前海进化论资产 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_JHLAsset', '-a', 'jobId=0L']) # 中投期货 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongTouFutures', '-a', 'jobId=0L']) # 中投证券 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongTouStock', '-a', 'jobId=0L']) # 中江信托 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongJiangTrust', '-a', 'jobId=0L']) # 中欧瑞博 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongOuRuiBoInvest', '-a', 'jobId=0L']) # 中融信托 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_ZhongRongTrust', '-a', 'jobId=0L']) # 大业信托 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_DaYeTrust', '-a', 'jobId=0L']) # 上海元葵资产 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_ShangHaiYuanKuiAsset', '-a', 'jobId=0L']) # 古木投资 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_GuMuInvest', '-a', 'jobId=0L']) # 丰岭资本 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_FengLingCapital', '-a', 'jobId=0L']) # 绎博投资 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_YiBoInvest', '-a', 'jobId=0L']) # 上海岳海资产 cmdline.execute(['scrapy', 'crawl', 'FundNotice_YueHaiAsset', '-a', 'jobId=0L']) # 长城新盛信托 # cmdline.execute(['scrapy', 'crawl', 'FundNotice_XinShengTrust', '-a', 'jobId=0L']) <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-24 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class HuNanTrustSpider(GGFundNavSpider): name = 'FundNav_HuNanTrust' sitename = '湖南信托' channel = '信托净值' trs_key_url = 'http://www.huntic.com/channels/71.html' trs_fname = '湖南信托•湘军彭大帅2号证券投资集合资金信托计划' fps = [{'url': trs_key_url}] def parse_fund(self, response): href_list = response.css('div.xxlb a::attr(href)').extract() for href in href_list: self.ips.append({ 'url': 'http://www.huntic.com' + href, 'ref': response.url, 'ext': self.trs_fname }) next_href = response.xpath('//div[@class="pages"]//a[contains(text(),"下一页")]/@href').extract_first() if next_href: self.fps.append({ 'url': 'http://www.huntic.com' + next_href, 'ref': response.url, 'ext': self.trs_fname }) def parse_item(self, response): date = response.css('div.nrmb p ::text').re_first('20\d{2}\.\d{2}\.\d{2}') if date: values = response.css('div.nrmb p ::text').re('\d{1}\.\d{3,}') nav = values[0] add_nav = values[1] item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = response.meta['ext'] item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav) if nav else None item['added_nav'] = float(add_nav) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y.%m.%d') if date else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 袁龚浩 # Create_date : 2018-05-07 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class GuoXinXinTuoSpider(GGFundNavSpider): name = 'FundNav_HuaXinXinTuo' sitename = '华信信托' channel = '信托净值' proxy = 1 # 此站点经常出现连接超时 custom_settings = { 'DOWNLOAD_TIMEOUT': 240, } fps = [{ 'url': 'http://www.huaxintrust.com/news2.asp?nid=36-46', }] def parse_fund(self, response): next_href = response.xpath('//a[contains(text(),"下页")]//@href').extract_first() if next_href: self.fps.append({ 'url': 'http://www.huaxintrust.com/news2.asp' + next_href, 'ref': response.url, }) fund_urls = response.xpath('//ul[@class = "neirong33"]//a//@href').extract() for url in fund_urls: self.ips.append({ 'url': 'http://www.huaxintrust.com/' + url, 'ref': response.url, }) def parse_item(self, response): item = GGFundNavItem() funds = response.xpath('//table//tr[2]') fund_name = ''.join((''.join(funds.xpath('//td[1]//div//text()').extract())).split()) if funds.xpath('td[3]//div//text()'): nav = funds.xpath('td[3]//div//text()').extract_first() added_nav = funds.xpath('td[4]//div//text()').extract_first() item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None else: nav = funds.xpath('td[2]//div//text()').extract_first() item['nav'] = float(nav) if nav is not None else None statistic_date = response.xpath('//div[@class="rer"]').re_first('数据截止到(\d+年\d+月\d+日)') item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y年%m月%d日') yield item <file_sep> from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin class FangZhengDongYaTrustSpider(GGFundNavSpider): name = 'FundNav_FangZhengDongYaTrust' sitename = '方正东亚信托' channel = '信托净值' proxy = 2 fps = [ { 'url': 'http://www.gt-trust.com/index.php/index-show-tid-18.html' } ] def parse_fund(self, response): funds = response.xpath('/html/body/div[3]/div[3]//div[@class="table_wrap_two"]/table//tr/td[1]/a/@href').extract() next_url = response.xpath('/html/body/div[3]//div[@class="ny_page wow zoomIn"]/a[text()="下一页"]/@href').extract_first() for url in funds: url = urljoin(get_base_url(response), url) self.ips.append({ 'url': url, 'ref': response.url }) if next_url is not None and next_url != '': next_url = urljoin(get_base_url(response), next_url) self.fps.append({ 'url': next_url, 'ref': response.url }) def parse_item(self, response): rows = response.xpath('//tr') fund_name = response.xpath('/html/body/div[3]/div[3]//div[@class="art-title"]/h3/text()').extract_first() for row in rows[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name if len(row.xpath('./td')) > 2: fund_date = row.xpath('./td[2]//text()').re_first('\d+-\d+-\d+') fund_nav = row.xpath('./td[3]//text()').re_first('\d+\.?\d*') if fund_date is None or fund_date == '': fund_date = row.xpath('./td[1]//text()').re_first('\d+-\d+-\d+') fund_nav = row.xpath('./td[2]//text()').re_first('\d+\.?\d*') item['nav'] = float(fund_nav) if fund_nav is not None and fund_nav != '' else None item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') yield item else: fund_date = row.xpath('./td[1]//text()').re_first('\d+-+\d+-\d+') fund_date = fund_date.replace('--', '-', 2) fund_nav = row.xpath('./td[2]//text()').re_first('\d+\.?\d*') item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(fund_nav) if fund_nav is not None and fund_nav != '' else None yield item self.request_next() <file_sep>from datetime import datetime from urllib.parse import urljoin import html from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import json class JinYuanSecuritiesSpider(GGFundNoticeSpider): name = 'FundNotice_JinYuanSecurities' sitename = '金元证券' entry = 'http://www.jyzq.cn/osoa/views/main/asset_management/Asset_list/index.shtml' username = '13916427906' password = '<PASSWORD>' cookies = 'loginumber=0.5687556305170236201805299827; JSESSIONID=abc2EkbsvGpPE8UPeCPow; _isLoginIn=83@%7C@%7C@1527556127012; user_id=83; nick_name=%E6%9C%9D%E6%9C%9D; userid=0b36ba4b8309331b123cc76bcf2915bc; ismechanism=0; isAccordWith=; url=' lps = [ { 'url': 'http://www.jyzq.cn/servlet/json', 'form': {'funcNo': '502001', 'pageNum': '1', 'pageSize': '500', 'i_product_small_type': '1', 'i_product_stat': '0'}, }, { 'url': 'http://www.jyzq.cn/servlet/json', 'form': {'funcNo': '502001', 'pageNum': '1', 'pageSize': '500', 'i_product_small_type': '1', 'i_product_stat': '1'}, }, ] def parse_list(self, response): funds = json.loads(response.text)['results'][0]['data'] for fund in funds: fund_id = fund['i_product_id'] i_id = fund['i_id'] self.ips.append({ 'url': 'http://www.jyzq.cn/servlet/json', 'form': {'funcNo': '501019', 'pageNum': '1', 'pageSize': '500', 'product_id': fund_id, 'l_article_type': '1'}, 'ext': {'i_id': i_id} }) self.ips.append({ 'url': 'http://www.jyzq.cn/servlet/json', 'form': {'funcNo': '501019', 'pageNum': '1', 'pageSize': '500', 'product_id': fund_id, 'l_article_type': '2'}, 'ext': {'i_id': i_id} }) def parse_item(self, response): i_id = response.meta['ext']['i_id'] rows = json.loads(response.text)['results'][0]['data'] for row in rows: url = 'http://www.jyzq.cn/osoa/views/main/asset_management/special_assets_list/article_details.shtml?id={0}&i_id={1}&product_id={2}&i_product_small_type=1'.format( row['l_article_id'], i_id, row['l_product_id']) title = row['l_tiltie'] publish_time = row['l_creation_time'] url = urljoin(get_base_url(response), url) item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = html.unescape(title) item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep>from scrapy import cmdline cmdline.execute(['scrapy', 'crawl', 'FundNav_HuoLiAsset', '-a', 'level=0', '-a', 'debug=1', '-a', 'jobId=0L']) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 柳美云 # Create_date : 2018-05-22 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class JieXunFundsSpider(GGFundNavSpider): name = 'FundNav_JieXunFunds' sitename = '杰询投资' channel = '投顾净值' allowed_domains = ['www.jxfunds.com'] username = 'ZYYXSM' password = '<PASSWORD>' cookies = 'UM_distinctid=163053a583d4bc-02fbcaeafa98fa-454c092b-1fa400-163053a583e2c7; CNZZDATA1253653248=2039850130-1524800635-%7C1524904022; PHPSESSID=i0qclqkvlqd7t49l4517smq784; syCkE_auth=89331ws6vgtmgxBkfVx64nZTza5nweX2RCp2UbrbgSkI6YQIbsTgPG2ReBhRZsjxi1sOtYaNKkbYpF-bBBTctEQRI90h7Ja6qzMXwKBDZ2j-O_MyY1dP0RHyPDHnRdqkarFQOgEKTNln44o6SyxNXqAaCFc; syCkE__userid=89331ws6vgtmgxBkfVl84nVYza9ixOmkR3wnBbrd0Sk; syCkE__username=<KEY>; syCkE__groupid=<KEY>tvSUFxqFmlrf2Ryl_Bu3e; syCkE__nickname=89331ws6vgtmgxBkfVp66XFWwK86x7TwEy0gAuK2ukMx3P4' fps = [ {'url': 'http://www.jxfunds.com/index.php?m=content&c=index&a=addpro&page1=0&catid=18&q=', 'pg': 0}, ] def parse_fund(self, response): fund_urls = response.xpath('//div[@class="list_mar2"]//a//@href').extract() for fund_url in fund_urls: self.ips.append({ 'url': fund_url, 'ref': response.url, }) if fund_urls: # 如果抓不到链接,则停止 next_pg = response.meta['pg'] + 1 self.fps.append({ 'url': 'http://www.jxfunds.com/index.php?m=content&c=index&a=addpro&page1=' + str( next_pg) + '&catid=18&q=', 'ref': response.url, 'pg': next_pg }) def parse_item(self, response): fund_name = response.xpath('//div[@class="main"]/div[2]/div[1]/p/text()').extract_first() nav_list = response.xpath('//div[@id="cat_2"]//table//tr') for row in nav_list[2:]: row_info = row.xpath('td//text()').extract() if len(row_info) >= 3: statistic_date = row_info[0] nav = row_info[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name.replace('【期限已到】', '').replace('【分红】', '') item['statistic_date'] = datetime.strptime(statistic_date, '%Y%m%d') item['nav'] = float(nav) if nav is not None else None yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-06-04 from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class JiangSuTrustSpider(GGFundNavSpider): name = 'FundNav_JiangSuTrust' sitename = '江苏信托' channel = '信托净值' fps = [{'url': 'http://www.jsitic.net/418.html'}] def parse_fund(self, response): href_list = response.xpath('//div[@class="float_left hand text-left"][contains(text(), "历史净值")]/@onclick' ).re("window.location.href='(.*)'") for href in href_list: self.ips.append({ 'url': 'http://www.jsitic.net' + href, 'ref': response.url, }) def parse_item(self, response): rows = response.xpath('//div[@style="height:30px;"]') for r in rows: fund_name = r.xpath('div[1]/text()').extract_first() date = r.xpath('div[2]/text()').re_first('\S+') nav = r.xpath('div[3]/text()').re_first('\S+') if date: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name.strip() item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None item['nav'] = float(nav) if nav else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin import re class GuangfaFundSpider(GGFundNoticeSpider): name = 'FundNotice_GuangfaFund' sitename = '广发基金' entry = 'http://www.gffunds.com.cn' lps = [ { 'url': 'http://www.gffunds.com.cn/zhlc/147/xxgg/149/index.htm', 'ref': 'http://www.gffunds.com.cn', 'pg': 0 } ] def parse_list(self, response): funds = response.xpath('//td[@class="TDbgcolor5"]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/a') for fund in funds: url = fund.xpath('./@href').extract_first() title = fund.xpath('./text()').extract_first() publish_time = re.findall('[P0|t]+(\d{8})', url)[0] if 'pdf' not in url: self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url, }) else: item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y%m%d') yield item tp = response.css('script').re_first(r'[1-9]\d+') pg = response.meta['pg'] next_pg = int(pg) + 1 if next_pg < int(tp): next_url = urljoin(get_base_url(response), 'index_' + str(next_pg) + '.htm') self.lps.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, }) def parse_item(self, response): if '.pdf' not in response.url: title = re.search('<h2>(.*?)</h2>', response.text).group(1) publish_time = re.search('\d+-\d+-\d+', response.text).group(0) item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = response.url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-10 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class JunZeLinFundSpider(GGFundNavSpider): name = 'FundNav_JunZeLinFund' sitename = '深圳君泽利投资发展企业' channel = '投资顾问' allowed_domains = ['www.jzlfund.com'] fps = [{'url': 'http://www.jzlfund.com/Products.asp'}] def parse_fund(self, response): self.ips.append({'url': 'http://www.jzlfund.com/'}) href_list = response.xpath('//div[@class="left_menu"]//@href').extract() fund_names = response.xpath('//div[@class="left_menu"]/a//text()').extract() for url, name in zip(href_list, fund_names): ips_url = urljoin('http://www.jzlfund.com/', url) fund_name = name self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): if 'ID' in response.url: rows = response.xpath('//div[@id="faq_content_1"]/div/table//tr') fund_name = response.meta['ext']['fund_name'] for row in rows[1:]: fund_date = row.xpath('.//td[2]//text()').extract_first() fund_nav = row.xpath('.//td[3]//text()').extract_first() added_nav = row.xpath('.//td[4]//text()').extract_first() if '%' not in added_nav: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(fund_nav) item['added_nav'] = float(added_nav) yield item else: rows = response.xpath('//div[@class="iproducts_tbe"][@id="iproducts_0"]//tr') for row in rows[1:]: fund_name = row.xpath('./td[1]//text()').extract_first().strip() fund_nav = row.xpath('./td[2]//text()').extract_first().strip() fund_date = row.xpath('.//td[5]//text()').extract_first().strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(fund_nav) yield item yield self.request_next() <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class SmilefofSpider(GGFundNoticeSpider): name = 'FundNotice_Smilefof' sitename = '上海拾麦资产' entry = 'http://www.smilefof.com' lps = [ { 'url': 'http://www.smilefof.com/news/cpgg/', 'ref': 'http://www.smilefof.com/news/' } ] def parse_list(self, response): datas = response.xpath('/html/body/div//ul[@class="article"]/li') for notice in datas: href = notice.xpath('./span[1]/a/@href').extract_first().strip() title = notice.xpath('./span[1]/a/text()').extract_first().strip() publish_time = notice.xpath('./span[2]/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = self.entry + href item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import json from urllib.parse import urljoin from scrapy.utils.response import get_base_url class YinHeStockNoticeSpider(GGFundNoticeSpider): name = 'FundNotice_YinHeStockNotice' sitename = '银河金汇证券' allowed_domains = ['www.chinastock.com.cn'] entry = 'http://yhjh.chinastock.com.cn' cookies = 'JSESSIONID=qp6VTEKbiG88N-qKGnBRTnKqRaH6l9u_1GlkSWz27ADW9mpBQjJQ!-1352806688; WT_FPC=id=2c910a547c8f47b74fe1522637769135:lv=1527218235556:ss=1527218211544' username = '18625981663' password = '<PASSWORD>' lps = [{'url': 'http://yhjh.chinastock.com.cn/yhwz/managemoney/product.jsp?nav=', 'ref': None, 'ext': {'report_type': '1'}}] def parse_list(self, response): ext = response.meta['ext'] report_type = int(ext['report_type']) if report_type == 1: funds = response.xpath('//*[@id="service"]/div[2]/div[1]/div[1]/div[2]/div[2]//a/@href').extract() for url in funds: url = urljoin(get_base_url(response), url) self.lps.append({'url': url, 'ref': response.url, 'ext': {'report_type': '2'}}) else: url_pro = response.xpath('//*[@id="dne3"]/@href').extract_first() url_pro = urljoin(get_base_url(response), url_pro) url_money = response.xpath('//*[@id="dne5"]/@href').extract_first() url_money = urljoin(get_base_url(response), url_money) url_law = response.xpath('//*[@id="dne8"]/@href').extract_first() url_law = urljoin(get_base_url(response), url_law) self.ips.append({'url': url_pro, 'ref': response.url, 'ext': {'report_type': '1', 'url': url_pro}}) self.ips.append({'url': url_money, 'ref': response.url, 'ext': {'report_type': '1', 'url': url_money}}) self.ips.append({'url': url_law, 'ref': response.url, 'ext': {'report_type': '1', 'url': url_law}}) def parse_item(self, response): ext = response.meta['ext'] report_type = int(ext['report_type']) if report_type == 1: base_url = ext['url'] next_page = response.xpath('//*[@id="pager"]/div/div[@class="pagination_next"]/a/@pagenum').extract_first() if next_page: url = base_url + '&pageNum=' + str(next_page) self.ips.append({'url': url, 'ref': response.url, 'ext': {'report_type': '1', 'url': base_url}}) rows = response.xpath('/html/body/div/div[1]/ul/li/a/@href').extract() for url in rows: url = urljoin(get_base_url(response), url) self.ips.append({'url': url, 'ref': response.url, 'ext': {'report_type': '2'}}) else: url = response.url title = response.xpath('//*[@id="dleft1"]/div[1]/text()').extract_first().strip() publish_time = response.xpath('//*[@id="dleft1"]/div[2]/text()').re_first('\d+-\d+-\d+') publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin import re class ZhongRongTrustSpider(GGFundNoticeSpider): name = 'FundNotice_ZhongRongTrust' sitename = '中融信托' entry = 'http://www.zritc.com' lps = [ { 'url': 'http://www.zritc.com/zrcf_zyyw/gbbg/new/', 'ref': 'http://www.zritc.com', } ] def parse_list(self, response): urls = response.xpath('//div[@class="nav-sub mb20"]/div[4]/a') for url in urls[1:]: href = url.xpath('./@href').extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), href), 'ref': response.url, 'pg': 0 }) def parse_item(self, response): datas = response.xpath('//ul[@id="ggul"]/li') for notice in datas: href = notice.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), href) title = notice.xpath('normalize-space(./a/text())').extract_first() publish_time = notice.xpath('./span/text()').extract_first() item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y/%m/%d') yield item tp = response.xpath('//div[@class="page"]/table/tr/td/script').extract_first() tp = re.findall('var countPage = (\d+)', tp)[0] cp = response.meta['pg'] if (cp+1) < int(tp): cp = cp+1 next_url = urljoin(get_base_url(response), 'index_' + str(cp) + '.html') self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': cp }) <file_sep>from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class YinlingInvestSpider(GGFundNavSpider): name = 'FundNav_YinlingInvest' sitename = '引领投资' channel = '投资顾问' username = '吴迪' password = '<PASSWORD>' cookies = 'shengming=yes' def start_requests(self): yield FormRequest(url='http://www.yinlinggroup.com/ashx/login.ashx', formdata={ 'UserName': self.username, 'UserPwd': <PASSWORD>, 'UserType': '1' }, callback=self.parse_list) def parse_list(self, response): self.fps.append({ 'url': 'http://www.yinlinggroup.com/product/zhengquan/' }) def parse_fund(self, response): urls = response.xpath('//ul[@class="nyLejUL"]/li') for url in urls: href = url.xpath('./a/@href').extract_first() urls = urljoin(get_base_url(response), href) code = urls.rsplit('=', 1)[1] fund_name = url.xpath('./a/text()').extract_first() self.ips.append({ 'url': 'http://www.yinlinggroup.com/product/zhengquan/?ProID=' + str(code), 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] fund_names = ext['fund_name'] rows = response.xpath('//table[@class="cpxxkNR1_bg1"]/tr') for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_names statistic_date = row.xpath("./td[2]/text()").re_first('\d+-\d+-\d+') item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row.xpath('./td[3]/text()').extract_first() item['nav'] = float(nav) if nav else None added_nav = row.xpath("./td[4]/text()").extract_first() item['added_nav'] = float(added_nav) if added_nav else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 柳美云 # Create_date : 2018-05-22 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class YiYuanXinFundSpider(GGFundNavSpider): name = 'FundNav_YiYuanXinFund' sitename = '江苏易元鑫资产' channel = '投顾净值' allowed_domains = ['www.eyxfund.com'] username = '13461073668' password = '<PASSWORD>' fps = [{'url': 'http://www.eyxfund.com/Product'}] cookies = 'ASP.NET_SessionId=ekybn1kobru4x5s0ujugime0; xjly=hayden' def parse_fund(self, response): link = response.xpath('//div[@id="item_content1"]//li//@href').extract() for link_key in link: if link_key not in 'javascript:void(0);': href = link_key ips_url = urljoin('http://www.eyxfund.com', href) self.ips.append({ 'url': ips_url, 'ref': response.url, }) def parse_item(self, response): fund_name_list = response.xpath('//div[@class="item_div1"]/div/h1') fund_name = fund_name_list.xpath('.//text()').extract_first() if fund_name: row = response.xpath('////div[@class="coop_namej"]/table/tbody/tr') for rows in row[1:]: nav_list = rows.xpath('td//text()').extract() statistic_date = nav_list[0] nav = nav_list[1].replace(' ', '') added_nav = nav_list[2].replace(' ', '') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class XiZangTrustSpider(GGFundNavSpider): name = 'FundNav_XiZangTrust' sitename = '西藏信托' channel = '信托净值' fps = [{ 'url': 'http://www.ttco.cn/ttco/page_networth', 'ref': None, 'form': {'st': 'dd', 'netWorthPage.pageSize': '500', 'netWorthPage.pageNum': '1'} }] def parse_fund(self, response): funds = response.xpath('//div[@class="mainDetail"]/table/tr')[1:] for fund in funds: id = fund.xpath('./td[1]/a/@href').re_first('id=(\S+)') fund_name = fund.xpath('./td[1]/a/text()').extract_first() self.ips.append({ 'url': 'http://www.ttco.cn/ttco/networthList?netWorthNetPage.start=0&product.id={}'.format(id), 'ref': response.url, 'ext': {'fund_name': fund_name, 'pg': 0, 'id': id} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] id = response.meta['ext']['id'] rows = response.xpath('//table[@class="valueList"]/tr')[1:] for row in rows: statistic_date = row.xpath('./td[1]/text()').re_first('\d+-\d+-\d+') nav = row.xpath('./td[2]/text()').re_first('([0-9.]+)') added_nav = row.xpath('./td[3]/text()').re_first('([0-9.]+)') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None statistic_date = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date is not None else None item['statistic_date'] = statistic_date yield item ext = response.meta['ext'] pg = ext['pg'] tpg = response.xpath('//a[text()= "尾页"]/@href').re_first('start=(\d+)\&') if tpg and pg * 10 < int(tpg): ext['pg'] += 1 self.ips.append({ 'url': 'http://www.ttco.cn/ttco/networthList?netWorthNetPage.start={}&product.id={}'.format( ext['pg'] * 10, id), 'ref': response.url, 'ext': ext }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-02 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy import FormRequest class JingHengCapitalSpider(GGFundNavSpider): name = 'FundNav_JingHengCapital' sitename = '景恒资本' channel = '投顾净值' username = 'ZYYXSM' password = '<PASSWORD>' fps = [{'url': 'http://www.jhcapital.com.cn/product.asp'}] def start_requests(self): yield FormRequest(url='http://www.jhcapital.com.cn/login_post.asp', formdata={'LoginId': 'ZYYXSM', 'Password': '<PASSWORD>' }, ) def parse_fund(self, response): fund_infos = response.xpath('//div[@class="container cclearfix"]/div/ul/li/ul//li') for url in fund_infos: fund_url = url.xpath('.//@href').extract_first() fund_name = url.xpath('.//text()').extract_first() ips_url = urljoin('http://www.jhcapital.com.cn/product.asp', fund_url) self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath('//div[@class="product_conn"]/div[2]/table//tr') fund_name = response.meta['ext']['fund_name'] for row in rows[1:]: fund_date = row.xpath('.//td[2]//text()').extract_first() fund_nav = row.xpath('.//td[4]//text()').extract_first() added_nav = row.xpath('.//td[5]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y年%m月%d日') item['nav'] = float(fund_nav) item['added_nav'] = float(added_nav) yield item <file_sep># -*- coding: utf-8 -*- from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class UsuFundSpider(GGFundNavSpider): name = 'FundNav_UsuFund' sitename = '优素资产' channel = '投资顾问' # 入口地址 start_urls = ['http://www.usufund.com/'] cookies = 'UM_distinctid=163203b5378301-0f634f77a34da2-3f3c5701-15f900-163203b537917a; JSESSIONID=AF437CE550F5C3531DB357ED714C6FFD; SESSION=93b1d228-f95b-4e2e-9510-46f7758c65b6; CNZZDATA1259878002=1137005077-1525253551-http%253A%252F%252Finfo.hffss.com%252F%7C1527042591' fps = [ { 'url': 'http://info.hffss.com/app/reg/show', 'ref': 'http://info.hffss.com/app/reg/show' } ] def parse_fund(self, response): funds = response.css('.am-accordion-content>div>div:nth-child(2)') for fund in funds: fund_name = fund.xpath('./div[@class="pro-name"]/text()').extract_first() pid = fund.xpath('./input[@class="pidInput"]/@value').extract_first() self.ips.append({ 'url': 'http://info.hffss.com/app/prosummary/' + pid, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] fund_name = ext['fund_name'] rows = response.xpath("//input[@id='nv12m']/@value").extract_first() rows = eval(rows) for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = row[0] item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row[2] item['nav'] = float(nav) if nav is not None else None added_nav = row[3] item['added_nav'] = float(added_nav) if added_nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 王卓诚 # Create_date : 2018-04-27 from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class BoRuiAiJianInvestSpider(GGFundNavSpider): name = 'FundNav_BoRuiAiJianInvest' sitename = '柏瑞爱建资产' channel = '公募专户净值' allowed_domains = ['www.pa-asset.com'] username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'http://www.pa-asset.com/list/6521/1.shtml', 'pg': 1 }] def parse_fund(self, response): urls = response.xpath('//div[@class="right2"]/p') if urls: next_pg = response.meta['pg'] + 1 self.fps = [{ 'url': 'http://www.pa-asset.com/list/6521/' + str(next_pg) + '.shtml', 'ref': response.url, 'pg': next_pg }] for uu in urls: infotext = uu.xpath('a/em/text()').extract_first() url = urljoin(get_base_url(response), uu.xpath('a/@href').extract_first()) if infotext.find('净值公布') > -1: chuanproductname = infotext.replace(' ', '').replace('净值公布', '') self.ips.append({ 'url': url, 'ref': response.url, 'ext': chuanproductname }) def parse_item(self, response): productname = response.meta['ext'] rows = response.xpath('//div[@class="p"]/table/tbody/tr') tmpst_date = '' for k, row in enumerate(rows): tmpfundname = '' statistic_date = '' f0 = row.xpath(r'./td[1]/strong/span/text()').extract_first() f1 = row.xpath(r'./td[1]/span/text()').extract_first() f2 = row.xpath(r'./td[2]/span/text()').extract_first() if f0 is None and f1 is None and f2 is None: continue if (k == 0 or k % 4 == 0) and (not f0 is None or not f1 is None): if f0 is None and not f1 is None: f0 = f1 f0 = f0.strip().replace('/', '-') zhouqi1 = re.compile(r'\d{4}(/|-)\d{1,2}(/|-)\d{1,2}', re.S | re.I | re.M) zhouqi2 = re.findall(zhouqi1, f0) if len(zhouqi2) > 0 and tmpst_date == '' or f0 != tmpst_date: tmpst_date = f0 if k > 0 and k % 4 != 0 and not f2 is None: if f1 == '单位总净值:' or f1.find('总净值') > 0: tmpfundname = productname elif f1 == '单位净值:优先级' or f1.find('优先级') > 0: tmpfundname = productname + '优先级' elif f1 == '单位净值:次级' or f1.find('次级') > 0: tmpfundname = productname + '次级' nav = f2.strip() if tmpst_date != '': statistic_date = tmpst_date item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = tmpfundname item['nav'] = float(nav) if nav else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from urllib.parse import unquote_plus class XingYeGuoJiTrustNoticeSpider(GGFundNoticeSpider): name = 'FundNotice_XingYeGuoJiTrustNotice' sitename = '兴业国际信托' entry = 'http://www.ciit.com.cn/' lps = [{'url': 'http://www.ciit.com.cn/news/p-notice/ext/index.html', 'ext': {'report_type': '1'}}] def parse_list(self, response): ext = response.meta['ext'] report_type = int(ext['report_type']) if report_type == 1: funds = response.xpath('//*[@id="about-list"]/li[3]/dl/dt/a[text()!="净值公告"]/@href').extract() for url in funds: self.lps.append({'url': url, 'ref': response.url, 'ext': {'report_type': '2'}}) else: url = response.xpath('//*[@id="frame1"]/@src').extract_first() url = urljoin(get_base_url(response), url) self.ips.append({'url': url, 'ref': response.url, 'ext': {'base_url': url}}) def parse_item(self, response): ext = response.meta['ext'] base_url = ext['base_url'] next_page = response.xpath('/html/body/div/div/div/li/a[text()="下一页"]/@href').re_first(r'turnto\(\'(\d+)\'\)') if next_page: next_url = base_url + '&currentpage=' + str(next_page) self.ips.append({'url': next_url, 'ref': response.url, 'ext': {'base_url': base_url}}) rows = response.css('.innercont>ul>li') for row in rows: url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./a/@title').extract_first().strip().replace('.pdf', '') publish_time = row.xpath('./span/text()').extract_first().strip() publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = unquote_plus(url) item['title'] = title item['publish_time'] = publish_time yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-04-25 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class GuoMinXinTuoTrustsSpider(GGFundNavSpider): name = 'FundNav_GuoMinXinTuoTrusts' sitename = '国民信托' channel = '信托净值' fps = [ {'url': 'http://www.natrust.cn/fe/equity/catList.gsp'}, ] def parse_fund(self, response): fund_urls = response.xpath( "//div[@class='job_list']/ul[@class='job_list_text job_list_text2']//li[1]//@href").extract() for url in fund_urls: self.ips.append({ 'url': 'http://www.natrust.cn/fe/equity/' + url + '&page=1', 'ref': response.url, 'pg': 1 }) def parse_item(self, response): rows = response.xpath("//div[@class='Details_right']/div[@class='jz_table']//tr") fund_name = response.xpath("//div[@class='left']//text()").extract_first() if len(rows) > 1: for row in rows[1:]: statistic_date = row.xpath("./td[1]//text()").extract_first() if '-' in statistic_date: statistic_date = statistic_date.replace('-', '/') if statistic_date[4] != '/': statistic_date = statistic_date.replace(statistic_date[0:4], statistic_date[0:4] + '/') nav = row.xpath('./td[2]//text()').extract_first() added_nav = row.xpath('./td[3]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') yield item pg = response.meta['pg'] next_pg = int(pg) + 1 next_url = response.url.replace('&page=' + str(pg), '&page=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, }) <file_sep>from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class WayingInvestSpider(GGFundNavSpider): name = 'FundNav_WayingInvest' sitename = '洼盈投资' channel = '投资顾问' username = '13916427906' password = '<PASSWORD>' cookies ='kerenLogin=userid=13916427906' fps = [{ 'url': 'http://www.wytzfund.com/product.aspx?sClass=3&sType=1&oid=18' }] def start_requests(self): yield FormRequest(url='http://www.wytzfund.com/index.aspx') def parse_fund(self, response): urls = response.xpath('//div[@class="quicksub"]/ul/li') for url in urls: href = url.xpath('./a/@href').extract_first() myurl = urljoin(get_base_url(response), href) fund_name = url.xpath('./a/@title').extract_first().replace('(已终结)', '').replace('(已结束)', '').replace('(已终结)', '') self.ips.append({ 'url': myurl, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] fund_names = ext['fund_name'] rows = response.xpath('//div[@class="text_jz"]//table//tr') rows.pop(0) item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_names nav = rows.pop(0).xpath("./td[2]//text()").extract_first() item['nav'] = float(nav) if nav else None added_nav = rows.pop(0).xpath("./td[2]//text()").extract_first() item['added_nav'] = float(added_nav) if added_nav else None statistic_date = rows.pop(0).xpath(".//td[2]//text()").re_first('\d+-\d+-\d+') item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None yield item <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-02 from urllib.parse import urljoin from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class HuiLiFundSpider(GGFundNavSpider): name = 'FundNav_HuiLiFund' sitename = '汇利资产' channel = '投顾净值' fps = [{'url': 'http://www.hlfund.com/detail.asp?id=55&bid=111&name=%BB%E3%C0%FB%BE%C5%C1%FA'}] def parse_fund(self, response): link_key = response.xpath('//td/a[contains(text(), "净值")]/@href').extract() fund_info = response.xpath('//td[@align="left" and @bgcolor="#F2F2F2"]/strong/text()').extract() for key, name in zip(link_key, fund_info): fund_link = urljoin('http://www.hlfund.com/', key) fund_name = name.replace(':', '') self.ips.append({ 'url': fund_link, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): nav_rows = response.xpath('//table[@width="96%"]//table/tbody/tr') for row in nav_rows[1:]: nav_info = row.xpath('td/font/text()').extract() fund_name = response.meta['ext']['fund_name'] statistic_date = nav_info[0].replace(',', '').strip() nav = nav_info[1] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y年%m月%d日') item['nav'] = float(nav) if nav is not None else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import re class EverbrightXinglongTrustSpider(GGFundNoticeSpider): name = 'FundNotice_EverbrightXinglongTrust' sitename = '光大兴陇信托' entry = 'https://www.ebtrust.com/notice.html' ips = [ { 'url': 'https://www.ebtrust.com/notice/tp/221/page/1.html', 'ref': 'https://www.ebtrust.com/notice.html', }, { 'url': 'https://www.ebtrust.com/notice/tp/222/page/1.html', 'ref': 'https://www.ebtrust.com/notice.html', }, ] def parse_item(self, response): rows = response.xpath('//div[@class="noticeList"]/ul/li') for row in rows: title = row.xpath('./a/text()').extract_first().strip() url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) publish_time = row.xpath('./span/text()').extract_first().strip() publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item next_page = response.xpath("//div[@class='ims_pager']/text()").re_first('"next_page":(\d+),\s*"up_page"') last_page = response.xpath("//div[@class='ims_pager']/text()").re_first('"last_page":(\d+),\s*"next_page"') if next_page and int(next_page) < int(last_page): url = re.sub(r'page/\d+', 'page/' + next_page, response.url) self.ips.append({ 'url': url, 'ref': response.url, }) <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-08 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin import re class AlphaInvestSpider(GGFundNavSpider): name = 'FundNav_AlphaInvest' sitename = '宁波阿尔法投资' channel = '投资顾问' fps = [{ 'url': 'http://www.nb-alpha.cn/a/jijinchanpin/jijinjingzhi/list_38_1.html', 'pg': 1 }] def parse_fund(self, response): if response.status != '404': href_list = response.css('div.news a::attr(href)').extract() for href in href_list: self.ips.append({ 'url': urljoin(get_base_url(response), href), 'ref': response.url, }) next_pg = response.meta['pg'] + 1 self.fps.append({ 'url': re.sub('list_38_\d+', 'list_38_' + str(next_pg), response.url), 'ref': response.url, 'pg': next_pg }) def parse_item(self, response): rows = response.css('div.content tr')[1:] fund_name = response.css('div.article_title h2::text').extract_first().replace('净值', '') if '嘉得新三板一号' not in fund_name: for r in rows: row = [_.strip() for _ in r.css('td ::text').extract() if _.strip()] date = row[0].strip().replace('.', '-') nav = row[1].strip() item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav) if nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class ShangHaiYiZhouAssetSpider(GGFundNoticeSpider): name = 'FundNotice_ShangHaiYiZhouAsset' sitename = '上海亿舟资产' entry = 'http://www.yizhouzichan.com/article/cpgg' lps = [ { 'url': 'http://www.yizhouzichan.com/article/cpgg' } ] def parse_list(self, response): rows = response.xpath('//ul[@class="prodectlixl"]/li')[1:] for row in rows: url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) self.ips.append({ 'url': url, 'ref': response.url, 'pg': 1, 'ext': {'entry': url.replace('#introduce', '')} }) def parse_item(self, response): entry = response.meta['ext']['entry'] rows = response.xpath('//div[@class="baogaobox"]') for row in rows: url = row.xpath('./p/a/@href').extract_first() if 'javascript' not in url: url = urljoin(get_base_url(response), url) else: # 加密公告取当前所在页面地址 url = response.url title = row.xpath('./p/a/text()').extract_first() publish_time = row.xpath('./div/text()').re_first('\d+-\d+-\d+') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item tp = response.xpath('//span[@id="totalPage"]/text()').re_first('共(\d+)页') if tp: pg = response.meta['pg'] + 1 if pg <= int(tp): self.ips.append({ 'url': entry + '/' + str(pg), 'ref': response.url, 'pg': pg, 'ext': {'entry': entry} }) <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-08 from datetime import datetime from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class SanXiangInvestSpider(GGFundNavSpider): name = 'FundNav_SanXiangInvest' sitename = '惠州三想投资' channel = '投资顾问' username = '13916427906' password = '<PASSWORD>' fps = [{'url': 'http://www.sanxianginvest.com/index.php?id=product'}] def start_requests(self): yield FormRequest(url='http://www.sanxianginvest.com/api.php?c=login&f=save&_noCache=0.8049219487167945', headers={'Referer': 'http://www.sanxianginvest.com'}, formdata={ 'post_date': '2025-05-08 16:00:43', 'pdip': '172.16.31.10', 'user': self.username, 'pass': self.password }) def parse_fund(self, response): name_list = response.xpath('//div[@class="product-list"]//tr/td[1]/a/text()').extract() fund_list = response.xpath('//div[@class="product-list"]//tr/td[1]/a/@href').extract() for fund_name, link in zip(name_list, fund_list): self.ips.append({ 'url': link, 'ref': response.url, 'ext': fund_name }) def parse_item(self, response): fund_name = response.meta['ext'] nav_rows = response.xpath('//tr[@class="dd"]') for row in nav_rows: nav_info = row.xpath('td/text()').extract() statistic_date = nav_info[1].replace('25016-6-3', '2016-6-3').replace('.', '-').strip() nav = nav_info[2].strip() added_nav = nav_info[3].replace('..', '.').strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if added_nav else None yield item <file_sep># -*- coding: utf-8 -*- import json from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class TianHuaFundSpider(GGFundNavSpider): name = 'FundNav_TianHuaFund' sitename = '杭州添华投资' channel = '投资顾问' fps = [ { 'url': 'http://www.tianhuafund.com/show-67-41-1.html' } ] def parse_fund(self, response): fund_name = response.xpath('//ul[@class="factor"]/li[1]/span/text()').extract_first() pro_id = response.xpath('//div[@class="list_boxL"]/ul/li[1]/a/@href').re_first(r'show-67-([\d]+)-1.html') self.ips.append({ 'url': 'http://www.tianhuafund.com/ajax_do.php?action=pages', 'ref': response.url, 'form': {'pageNum': '0', 'pro_id': pro_id}, 'pg': 0, 'ext': {'fund_name': fund_name, 'pro_id': pro_id} }) def parse_item(self, response): ext = response.meta['ext'] fund_name = ext['fund_name'] pro_id = ext['pro_id'] json_data = json.loads(response.text) rows = json_data['list'] for row in rows: statistic_date = row['date'] nav = row['networth'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') if len(statistic_date.split('/')) == 3 else datetime.strptime(statistic_date, '%Y/%m%d') item['nav'] = float(nav) if nav is not None else None yield item pg = response.meta['pg'] + 1 tp = int(json_data['totalPage']) if pg < tp: self.ips.append({ 'url': 'http://www.tianhuafund.com/ajax_do.php?action=pages', 'ref': response.url, 'form': {'pageNum': str(pg), 'pro_id': pro_id}, 'pg': pg, 'ext': {'fund_name': fund_name, 'pro_id': pro_id} }) <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url import re class ZunDaoAssetSpider(GGFundNavSpider): name = 'FundNav_ZunDaoAsset' sitename = '尊道投资' channel = '投资顾问' fps = [{ 'url': 'http://www.topwayinvest.com/product.aspx?&jsid=3', 'ext': {'type': '1'} }] username = '15838867575' password = '<PASSWORD>' cookies = 'ASP.NET_SessionId=tx24lhz5hqk3ko45jxmna4bp; UserNmae=123; UserId=99' def parse_fund(self, response): link_list = response.xpath('//ul[@class = "lmenu"]//li/a//@href').extract() type = response.meta['ext']['type'] if type == '1': for link in link_list: self.fps.append({ 'url': 'http://www.topwayinvest.com/' + link, 'ref': response.url, 'ext': {'type': '2'} }) if type == '2': rows = response.xpath('//table[@class = "pro_table all productAll"]//tr')[1:] for row in rows: fund_id = re.search(r'cateid=(\d+)', row.xpath('./td[1]/a/@href').extract_first()).group(1) fund_url = row.xpath('./td[1]/a/@href').extract_first() fund_name = row.xpath('./td[1]/a/@title').extract_first() url = urljoin(get_base_url(response), fund_url) self.ips.append({ 'url': url, 'form': {'id': str(fund_id), 'action': '1'}, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] # //*[@id="con_one_4"]/table/tbody/tr[1] datas = response.xpath('//*[@id="con_one_4"]/table//tr') for row in datas[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name statistic_date = row.xpath('./td[1]/text()').extract_first().strip() item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') nav = row.xpath('./td[2]/text()').extract_first().strip() nav = nav.replace('元', '') item['nav'] = float(nav) if nav is not None else None added_nav = row.xpath('./td[4]/text()').extract_first().strip() added_nav = added_nav.replace('元', '') item['added_nav'] = float(added_nav) if added_nav != '' else None yield item <file_sep>import json from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class DongFangZQSpider(GGFundNavSpider): name = 'FundNav_DongFangZhengQuan' sitename = '东方证券' channel = '券商资管净值' username = '18638871675' password = '<PASSWORD>' fps = [ {'url': 'http://www.dfham.com/product/big/piangu/910004/index.html'}, {'url': 'http://www.dfham.com/product/small/piangu/918002/index.html'} ] def parse_fund(self, response): fundnames = response.xpath('//div[@class = "wrap-left"]//div[@class = "type"]//a//text()').extract() nums = response.xpath('//div[@class = "wrap-left"]//div[@class = "type"]//a//@href').extract() for num, fundname in zip(nums, fundnames): # 取链接当中的id,用split拆不出来,所以直接取了 id = num[-17:-11] ips_url = 'http://www.dfham.com/common-web/chart/fundnetchart!getFundNetChartJson?fundcode=' + id self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': fundname }) def parse_item(self, response): fund_name = response.meta['ext'] funds = json.loads(response.text) navs = funds['seriesData0'] add_navs = funds['seriesData1'] dates = funds['xAxisData'] for nav, add_nav, date in zip(navs, add_navs, dates): item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') item['nav'] = float(nav) item['added_nav'] = float(add_nav) yield item <file_sep>from datetime import datetime from urllib.parse import urljoin from urllib import parse from scrapy import FormRequest, Request from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class XingHuiAssetSpider(GGFundNavSpider): name = 'FundNav_XingHuiAsset' sitename = '星惠资产' channel = '投资顾问' username = '13916427906' password = '<PASSWORD>' def start_requests(self): yield Request(url='http://www.starwint.com/tanc.html', callback=self.parse_pre_login) def parse_pre_login(self, response): url = 'http://www.starwint.com//user_reg_check.aspx?callback=jQuery31002569703387914626_1525855147766&type=login&phone='+self.username+'&pass='+self.password+'&reme=1&rn=1&_=1525855147770' yield FormRequest(url=url, callback=self.parse_login) def parse_login(self, response): self.fps = [{ 'url': 'http://www.starwint.com/news/list/24_1.htm', 'ref': response.url, 'ext': {'type': '1'} }] def parse_fund(self, response): ext = response.meta['ext'] type = int(ext['type']) if type == 1: funds = response.xpath('//*[@id="shizhi"]/ul/li/a/@href').extract() for url in funds: url = urljoin(get_base_url(response), url) self.fps.append({ 'url': url, 'ref': response.url, 'ext': {'type': '2'} }) else: url = response.xpath('//*[@id="nav"]//div[@class="bt02"]/iframe/@src').extract_first() url = urljoin(get_base_url(response), url) self.ips.append({ 'url': url, 'ref': response.url }) def parse_item(self, response): line = response.url fund_name = re.search(r'name=(\S+)', line).group(1) fund_name = parse.unquote_plus(fund_name) rows = response.xpath('//*[@id="form1"]/div[2]/table[2]//tr[4]/td/table//tr') for row in rows[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = parse.unquote_plus(response.url) nav = row.xpath('./td[2]//text()').re_first(r'(\d+\.?\d*)') item['nav'] = float(nav) statistic_date = row.xpath('./td[1]//text()').extract_first() item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-03 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy import FormRequest import time class KuanQiAssetSpider(GGFundNavSpider): name = 'FundNav_KuanQiAsset' sitename = '宽奇资产' channel = '投资顾问' fps = [{'url': 'http://www.kuanqifund.com/157'}] username = 'zhangcheng' password = '<PASSWORD>' def start_requests(self): yield FormRequest(url='http://www.kuanqifund.com/apply/member/userLogin.asp', formdata={'userNameLogin': 'zhangcheng', 'passwordLogin': '<PASSWORD>', 'userLoginCheckcode': '7505', 'userLabelId': '529'}, callback=self.parse_fund) def parse_fund(self, response): time.sleep(3) fund_infos = response.xpath('//div[@class="fwmain_nleft edit_putHere"]/div/div//span//h2[2]//a') for url in fund_infos: ips_url = url.xpath('.//@href').extract_first() fund_name = url.xpath('.//text()').extract_first().replace('产品净值(', '').replace(')', '') self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath("//table[@class='MsoNormalTable']/tbody//tr") fund_name = response.meta['ext']['fund_name'] for row in rows[1:]: fund_date = row.xpath('.//td[1]/p//span[1]/text()').extract_first() fund_nav = row.xpath('.//td[2]/p//span[1]/text()').extract_first() if fund_date != '2016-10-': item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(fund_nav) yield item <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-11 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin import re class HuaRongTrustSpider(GGFundNavSpider): name = 'FundNav_HuaRongTrust' sitename = '华融信托' channel = '信托净值' allowed_domains = ['www.huarongtrust.com.cn'] fps = [{'url': 'http://www.huarongtrust.com.cn/?jzgb/page/1.html'}, ] def parse_fund(self, response): fund_infos = response.xpath('//div[@class="jzgb"]/table//tr') for fund_info in fund_infos[1:]: fund_name = fund_info.xpath('.//td[2]//text()').extract_first() fund_href = fund_info.xpath('.//td[9]//@href').extract_first() added_nav = fund_info.xpath('.//td[5]//text()').extract_first() ips_url = (urljoin('http://www.huarongtrust.com.cn/?jzgb.html', fund_href.replace('/./', '')).replace( '.html', '')) + '/page/1' + '.html' self.ips.append({ 'url': ips_url, 'ref': response.url, 'pg': 1, 'ext': {'fund_name': fund_name, 'added_nav': added_nav}, }) end_page = re.findall('"last_page":(.*?),', response.text)[0] pg = response.url.replace('http://www.huarongtrust.com.cn/?jzgb/page/', '').replace('.html', '') next_pg = int(pg) + 1 if next_pg <= int(end_page): self.fps.append({ 'url': 'http://www.huarongtrust.com.cn/?jzgb/page/' + str(next_pg) + '.html', 'ref': response.url }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] added_nav = response.meta['ext']['added_nav'] rows = response.xpath('//div[@class="jzgbShow"]/table//tr') for row in rows[1:]: statistic_date = row.xpath('.//td[1]//text()').extract_first() nav = row.xpath('.//td[2]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) if added_nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y%m%d') added_nav = None yield item end_page = re.findall('"last_page":(.*?),', response.text)[0] pg = response.meta['pg'] old_str = '/page/' + str(pg) if pg < int(end_page): new_str = '/page/' + str(pg + 1) next_url = response.url.replace(old_str, new_str) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': pg + 1, 'ext': {'fund_name': fund_name, 'added_nav': added_nav} }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-18 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class HanXinZiChanInvestSpider(GGFundNavSpider): name = 'FundNav_HanXinZiChanInvest' sitename = '瀚信资产' channel = '投顾净值' allowed_domains = ['www.hanxinchina.com'] username = '朝阳永续' password = '<PASSWORD>' cookies = 'UM_distinctid=1630499fe7e27d-0d959b16ddc151-3c604504-15f900-1630499fe7f40b; ASP.NET_SessionId=i2wz0mve4z1lxbuefagbjc45; CNZZDATA2812330=cnzz_eid%3D1535361529-1524790591-%26ntime%3D1526368672' fps = [ {'url': 'http://www.hanxinchina.com/ProductInfo.aspx'}, ] def parse_fund(self, response): fund_urls = response.xpath("//div[@class='r_product']/dl/dd//li//li") for url in fund_urls: fund_name = url.xpath('./a//text()').extract_first().strip() fund_url = url.xpath('./a/@href').extract_first() self.ips.append({ 'url': 'http://www.hanxinchina.com/cs.aspx?id='+fund_url.replace('ProductInfo.aspx?id=',''), 'ref': response.url, 'ext':{'fund_name':fund_name} }) def parse_item(self, response): statistic_dates = re.findall(r'categories: \[(.*?)\]', response.text)[0].split(",") navs = re.findall(r'data: \[(.*?)\]', response.text)[0].split(",") added_navs = re.findall(r'data: \[(.*?)\]', response.text)[1].split(",") fund_name=response.meta['ext']['fund_name'] if len(statistic_dates)>1: for row in zip(statistic_dates, navs, added_navs): statistic_date = row[0].replace("'", '') nav = row[1] added_nav = row[2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if nav is not None else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class ZhongtaixintuoInvestSpider(GGFundNoticeSpider): name = 'FundNotice_ZhongtaixintuoInvest' sitename = '中泰信托' entry = 'http://www.zhongtaitrust.com/' ips = [{ 'url': 'http://www.zhongtaitrust.com/cn/fortune/products/info.jsp?pageIndex=1' }] def parse_item(self, response): rows = response.xpath('//div[@class="alist2"]/div[not(@class)]') for row in rows: url = row.xpath('./div[1]/a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./div[1]/a/text()').extract_first() publish_time = row.xpath('./div[2]/text()').extract_first() publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item next_page = response.xpath('//table[@class="w-all h-30"]/tr/td[3]/image[@class]/@onclick').re_first('\d+') next_url = 'http://www.zhongtaitrust.com/cn/fortune/products/info.jsp?pageIndex='+str(next_page) if next_page: self.ips.append({ 'url': next_url, }) <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-06 from datetime import datetime from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class MingDaAseetSpider(GGFundNavSpider): name = 'FundNav_MingDaAseet' sitename = '明达资产' channel = '投顾净值' username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'http://www.mingdafund.com/index.php?controller=products&action=read&id=1', }] def start_requests(self): yield FormRequest(url='http://www.mingdafund.com/index.php?controller=clientUsers&action=login', formdata={'username': self.username, 'password': <PASSWORD>, 'Submit': '登 录'}, meta={ 'dont_redirect': True, 'handle_httpstatus_list': [302, 301] }) def parse_fund(self, response): id_list = response.xpath('//table[@width="180"]//td[@class="ldh"]//@href').re('action=read&id=(.*)') name_list = response.xpath('//table[@width="180"]//td[@class="ldh"]//text()').extract() for f_id, f_name in zip(id_list, name_list): self.ips.append({ 'url': 'http://www.mingdafund.com/index.php?controller=products&action=nets&id={}&type=1&page=0'.format( f_id), 'ref': response.url, 'pg': 0, 'ext': f_name }) def parse_item(self, response): next_pg = response.meta['pg'] + 1 total_pg = response.css('div#paper strong::text').extract()[1] if next_pg <= int(total_pg): rows = response.xpath('//td[@align="left"]//tr')[1:] for r in rows: if len(r.xpath('td')) > 1: row = r.xpath('td//text()').extract() date = row[0] nav = row[1] fund_name = response.meta['ext'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None yield item self.ips.append({ 'url': re.sub('\d+$', str(next_pg), response.url), 'ref': response.url, 'pg': next_pg, 'ext': response.meta['ext'] }) <file_sep>from datetime import datetime from urllib.parse import urljoin import html from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class XiNanFutureSpider(GGFundNoticeSpider): name = 'FundNotice_XiNanFuture' sitename = '西南期货' entry = 'http://www.swfutures.com/e/member/login/' username = '13916427906' password = '<PASSWORD>' cookies = 'UM_distinctid=1633d537dff82-098842fdf1ec7-3c3c5b05-15f900-1633d537e0330c; jjqcccheckinfokey=1525742175%2C94a4afec66fb4beb142e0faf560e3159%2<KEY>; CNZZDATA1261917271=1803972790-1525737813-http%253A%252F%252Fwww.swfutures.com%252F%7C1525777209; jjqccmlusername=13916427906; jjqccmluserid=93; jjqccmlgroupid=1; jjqccmlrnd=jGAait1s4nyRKDN1jwX6; jjqccmlauth=8<KEY>' lps = [{ 'url': 'http://www.swfutures.com/e/action/ListInfo/?classid=11' }] def parse_list(self, response): next_url = response.xpath('/html/body/div[4]/div/div[2]/div/a[text()="下一页"]/@href').extract_first() notices = response.xpath('/html/body/div[4]/div/div[2]/ul/li') for notice in notices: url = notice.xpath('./a/@href').extract_first() title = notice.xpath('./a/text()').extract_first() publish_time = notice.xpath('./a/span/text()').extract_first() url = urljoin(get_base_url(response), url) item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = html.unescape(title) item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d %H:%M:%S') yield item if next_url is not None: next_url = urljoin(get_base_url(response), next_url) self.lps.append({ 'url': next_url, 'ref': response.url }) <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url import re class ZhaoShangStockSpider(GGFundNavSpider): name = 'FundNav_ZhaoShangStock' sitename = '招商证券' channel = '券商资管净值' fps = [ { 'url': 'http://www.newone.com.cn/ws/html?arg=4financing/880014/2&', 'ext': {'type': '1'} } ] def parse_fund(self, response): ext = response.meta['ext'] type = int(ext['type']) if type == 1: funds = response.xpath('//*[@id="menu_list"]/li[3]/dl/dd/a') for fund in funds: url = fund.xpath('./@href').extract_first() fund_name = fund.xpath('./text()').extract_first() url = urljoin(get_base_url(response), url) self.fps.append({ 'url': url, 'ref': response.url, 'ext': {'type': '2', 'fund_name': fund_name} }) else: page_url = response.url # fund_name = response.xpath( # '//*[@id="right"]/div[6]//table[@class="cont_table"]//td/*[text()="产品全称"]/../../td[2]/text()').extract_first() # if fund_name is None or fund_name == '': fund_name = ext['fund_name'] jhdm = re.search(r'financing\/(\d+)\/', page_url).group(1) url = 'http://www.newone.com.cn/jzlb' self.ips.append({ 'url': url + '?page=1&jhdm=' + str(jhdm), 'ref': response.url, 'ext': {'fund_name': fund_name, 'page': '1', 'jhdm': str(jhdm)} }) def parse_item(self, response): ext = response.meta['ext'] page = int(ext['page']) jhdm = str(ext['jhdm']) fund_name = ext['fund_name'] line = response.text funds = response.xpath('//table//tr') titles = funds.pop(0).xpath('./td/text()').extract() url = 'http://www.newone.com.cn/jzlb?page=' + str(page + 1) + '&jhdm=' + str(jhdm) i = len(funds) - 1 if i >= 20: self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'fund_name': fund_name, 'page': str(page + 1), 'jhdm': str(jhdm)} }) for fund in funds[0:i]: fund_date = fund.xpath('./td[1]/text()').extract_first() nav = None added_nav = None d7_annualized_return = None income_value_per_ten_thousand = None if titles.count('单位净值(元)') > 0: nav = fund.xpath('./td[2]/text()').extract_first() if titles.count('累计净值(元)') > 0: added_nav = fund.xpath('./td[3]/text()').extract_first() if titles.count('每万份计划净收益(元)') > 0: income_value_per_ten_thousand = fund.xpath('./td[2]/text()').extract_first() if titles.count('七日年化收益率') > 0: d7_annualized_return = fund.xpath('./td[3]/text()').re_first(r'(\d+\.\d+)\%') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y-%m-%d') item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None else None item['d7_annualized_return'] = float(d7_annualized_return) if d7_annualized_return is not None else None item['income_value_per_ten_thousand'] = float( income_value_per_ten_thousand) if income_value_per_ten_thousand is not None else None yield item <file_sep>from datetime import datetime from scrapy import Request from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class BaoZhenInvestSpider(GGFundNavSpider): name = 'FundNav_BaoZhenInvest' sitename = '宝蓁投资' channel = '投资顾问' arc_username = '15538536932' arc_password = '<PASSWORD>' zyyx_username = '13916427906' zyyx_arc_password = '<PASSWORD>' def start_requests(self): yield Request(url='http://www.szbztz.com/Html/login.html', callback=self.parse_pre_login) def parse_pre_login(self, response): url = 'http://www.szbztz.com/handler/bztz.ashx?action=login&name='+self.arc_username+'&pass='+self.arc_password yield Request(url=url, callback=self.parse_login) def parse_login(self, response): self.fps = [{ 'url': 'http://www.szbztz.com/handler/bztz.ashx?action=yjfhload&item=loadnav', 'ref': response.url, 'ext': {'type': '1'} }] def parse_fund(self, response): ext = response.meta['ext'] type = int(ext['type']) if type == 1: fund_names = re.findall(r'>([\u4E00-\u9FA5]+)<\/a>', response.text) parent_ids = re.findall(r'vparentid=\'(\d+)\'', response.text) funds = response.xpath('/html//div[@class="view-content"]//a/@href').extract() for i in parent_ids: url = 'http://www.szbztz.com/handler/bztz.ashx?action=yjfhload&item=parentclick&parentid='+i self.fps.append({ 'url': url, 'ref': response.url, 'ext': {'type': '2', 'fund_name': fund_names.pop(0)} }) else: child_ids = re.search(r'vparentid=\'(\d+)\' vchildid=\'(\d+)\'>投资收益表', response.text) parent_id = child_ids.group(1) child_id = child_ids.group(2) fund_name = ext['fund_name'] url = 'http://www.szbztz.com/handler/bztz.ashx?action=yjfhload&item=chlidclick&parentid='+parent_id+'&childid='+child_id self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] fund_name = ext['fund_name'] datas = response.xpath('//tr') for row in datas[1:]: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url tds = row.xpath('./td') if len(tds) > 4: statistic_date = row.xpath('./td[2]//text()').re_first(r'\d+-\d+-\d+') if statistic_date is None or statistic_date == '': continue nav = row.xpath('./td[3]//text()').re_first(r'(\d+\.?\d*)') item['nav'] = float(nav) if nav is not None and nav != '' else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item elif len(tds) > 2: statistic_date = row.xpath('./td[1]//text()').re_first(r'\d+年\d+月\d+日') if statistic_date is None or statistic_date == '': continue nav = row.xpath('./td[2]//text()').re_first(r'(\d+\.?\d*)') item['nav'] = float(nav) if nav is not None and nav != '' else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y年%m月%d日') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class DaBoDiInvestNoticeSpider(GGFundNoticeSpider): name = 'FundNotice_DaBoDiInvestNotice' sitename = '大柏地投资' entry = 'http://www.bgclfund.com' ips = [{ 'url': 'http://www.bgclfund.com/index.php?c=article&a=type&tid=10&page=1', }] def parse_item(self, response): rows = response.xpath('//ul[@class="hd newslist"]/li') for row in rows: url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./a/text()').extract_first() publish_time = row.xpath('./a/span/text()').re_first(r'(\d+-\d+-\d+)') publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class BeiJingGuoJiTrustNoticeSpider(GGFundNoticeSpider): name = 'FundNotice_BeiJingGuoJiTrustNotice' sitename = '北京国际信托' entry = 'https://www.bjitic.com/' ips = [{ 'url': 'https://www.bjitic.com/news-54.html', }] def parse_item(self, response): rows = response.xpath('//*[@id="discover"]//div[@class="newslist"]/ul/li') next_url = response.xpath('//*[@id="discover"]/div[1]//a[text()="下一页"]/@href').extract_first() last_url = response.xpath('//*[@id="discover"]/div[1]//a[text()="末页"]/@href').extract_first() for row in rows: url = row.xpath('./div[2]/h3/a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./div[2]/h3/a/text()').extract_first() publish_year = row.xpath('./div[1]/span[2]/text()').extract_first() publish_day = row.xpath('./div[1]/span[1]/text()').extract_first() publish_time = str(publish_year) + '-' + str(publish_day) publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item if next_url and next_url != last_url: next_url = urljoin(get_base_url(response), next_url) self.ips.append({ 'url': next_url, 'ref': response.url }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class TianqinFutureSpider(GGFundNoticeSpider): name = 'FundNotice_TianqinFuture' sitename = '天勤资产' entry = 'http://www.tianqinassets.com/' ips = [{ 'url': 'http://www.tianqinassets.com/index.php?catid=2&page=1', }] def parse_item(self, response): rows = response.xpath('//ul[@class="noborder"]/li') for row in rows: url = row.xpath('./a/@href').extract_first() url = urljoin(get_base_url(response), url) title = row.xpath('./a/text()').extract_first().replace('\t', '').replace('\r', '').replace('\n', '') publish_time = row.xpath('./span/text()').extract_first() publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item next_url = response.xpath('//div[@class="xiaocms-page"]/a[contains(text(),"下一页")]/@href').extract_first() if next_url: next_url = urljoin(get_base_url(response), next_url) self.ips.append({ 'url': next_url, 'ref': response.url }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 宋孝虎 # Create_date : 2018-05-04 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class LingRiZiChanInvestSpider(GGFundNavSpider): name = 'FundNav_LingRiZiChanInvest' sitename = '凌日资产' channel = '投资顾问' allowed_domains = ['www.lrfunds.com'] fps = [{'url': 'http://www.lrfunds.com/products/47-7.html'}] def parse_fund(self, response): fund_urls = response.xpath("//div[@id='side_list']/ul/li") for url in fund_urls: fund_url = url.xpath(".//@href").extract_first() fund_name = url.xpath(".//text()").extract_first() if fund_url: self.ips.append({ 'url': 'http://www.lrfunds.com' + fund_url.replace('.html', '_1.html'), 'ref': response.url, 'ext': {'fund_name': fund_name}, 'pg': 1 }) def parse_item(self, response): fund_name = response.meta['ext']['fund_name'] rows = response.xpath("//table[@class='jingzhi']//tr") if rows: for row in rows: statistic_date = row.xpath("./td[1]//text()").extract_first() nav = row.xpath('./td[2]//text()').extract_first() added_nav = row.xpath('./td[3]//text()').extract_first() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if added_nav: item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') yield item pg = response.meta['pg'] next_pg = pg + 1 next_url = response.url.replace('_' + str(pg) + '.html', '_' + str(next_pg) + '.html') self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg, 'ext': {'fund_name': fund_name} }) <file_sep># -*- coding: utf-8 -*- # Department:保障部 # Author:王卓诚 # Create_Date:2018-05-28 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class WanLianSecuritySpider(GGFundNavSpider): name = 'FundNav_WanLianSecurity' sitename = '万联证券' channel = '券商资管净值' allowed_domains = ['www.wlzq.cn'] cookies = 'JSESSIONID=abcym1Z36W1t8-8xGLkow; clientinfo=IWeq75+dwN2F+5fFVp5tNXDv6IF6mTyUTKq21LhU2Ek=&xPBSQiYdRhf0KJ5WvrBMwg==&xPBSQiYdRhf0KJ5WvrBMwg==&qfxYJ8xyR8yxjdhalY9g5tNN3Zd7+5iEeYKWv8xAoAs=&xPBSQiYdRhf0KJ5WvrBMwg==; @user_id=IWeq75+dwN2F+5fFVp5tNXDv6IF6mTyUTKq21LhU2Ek=; @fund_account=xPBSQiYdRhf0KJ5WvrBMwg==; tk_stat_b=2; tk_stat_c=1527041369814; tk_stat_e=44; tk_stat_a=17; tk_stat_id=01FB3ABE714A48C698CB10F47AD5E35; tk_stat_z=none' username = '13916427906' password = '<PASSWORD>' fps = [{ 'url': 'http://www.wlzq.cn/main/zcgl/index.shtml', 'ref': 'http://www.wlzq.cn' }] def parse_fund(self, response): arul = response.xpath('//table[@class="table02"]/tr') for uu in arul[1:]: url = uu.xpath('.//@onclick').extract_first() pname = uu.xpath('./td[1]//text()').extract_first() if (not url is None): pid = url.replace("showUrl('", '').replace("')", '').replace(';', '') self.ips.append({ 'url': 'http://www.wlzq.cn/servlet/FundPageAction?function=AjaxFundNav&fundid=' + pid + '&rand=0.8130904473364353', 'ref': response.url, 'pg': 1, 'ext': {'pname': pname, 'pid': pid} }) def parse_item(self, response): fund_name = response.meta['ext']['pname'] jzinfo = response.text jzinfotype1 = re.compile(r'<title>(.*)</title>', re.S | re.I | re.M) jzinfotype2 = re.findall(jzinfotype1, jzinfo) jzdate1 = re.compile(r'<date>(.*)</date>', re.S | re.I | re.M) jzdate2 = re.findall(jzdate1, jzinfo) jzzhi1 = re.compile(r'<value>(.*)</value>', re.S | re.I | re.M) jzzhi2 = re.findall(jzzhi1, jzinfo) jzdate3 = jzdate2[0].split(',') if (len(jzinfotype2) > 0 and len(jzdate2) > 0 and len(jzzhi2) > 0): # 七日年化 if (jzinfotype2[0].find('七日年化收益率') > -1): jzzhi3 = jzzhi2[0].split(',') for k1, v1 in enumerate(jzdate3): statistic_date = v1 d7_annualized_return = jzzhi3[k1] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['d7_annualized_return'] = float(d7_annualized_return) if d7_annualized_return else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y%m%d') yield item # 净值 elif (jzinfotype2[0].find('单位净值') > -1): jzzhi31 = jzzhi2[0].split('|') jzzhi41 = jzzhi31[0].split(',') jzzhi42 = jzzhi31[1].split(',') for k2, v2 in enumerate(jzdate3): statistic_date = v2 nav = jzzhi41[k2] added_nav = jzzhi42[k2] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if added_nav else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y%m%d') yield item <file_sep>from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class YaozhiFutureSpider(GGFundNavSpider): name = 'FundNav_YaozhiFuture' sitename = '耀之资产' channel = '投顾净值' username = 'ZYYXSM' password = '<PASSWORD>' cookies = 'acceptDisclaimer=1; PHPSESSID=1kqg5hq712ohutl0vcbu5t4qh4' fps = [{ 'url': 'http://www.yzamc.com/index.php/performance' }] def parse_fund(self, response): urls = response.xpath('//table[@class="table table-hover table-striped performance"]//tr') for url in urls[1:]: href = url.xpath('./td[1]/a/@href').extract_first() code = href.rsplit('=', 1)[1] fund_name = url.xpath('./td[1]/a/text()').extract_first() self.ips.append({ 'url': 'http://www.yzamc.com/index.php/ajax/productdatalist?&p=1&id=' + str(code), 'ref': response.url, 'ext': {'code': code, 'fund_name': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] code = ext['code'] fund_names = ext['fund_name'] rows = response.xpath('//tr') rows = rows[0:-1] for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_names statistic_date = row.xpath("./td[1]/text()").re_first('\d+-\d+-\d+') item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None nav = row.xpath('./td[2]/text()').extract_first() item['nav'] = float(nav) if nav else None yield item next_page = response.xpath('//ul[@class="pages"]/li[last()]/@onclick').re_first(r',\'(\d+)\'\)') if next_page: self.ips.append({ 'url': 'http://www.yzamc.com/index.php/ajax/productdatalist?&p=' + next_page + '&id=' + str(code) + '', 'ref': response.url, 'ext': {'code': code, 'fund_name': fund_names} }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin class HaoenInvestSpider(GGFundNoticeSpider): name = 'FundNotice_HongChengInvest' sitename = '泓澄投资' entry = 'http://www.hccapital.com.cn/' lps = [ { 'url': 'http://www.hccapital.com.cn/notice.jsp', 'ref': 'http://www.hccapital.com.cn/notice.jsp', 'form': { 'method': 'checkin' }, 'ext': {'flag': 0} } ] def parse_list(self, response): flag = response.meta['ext']['flag'] if flag == 0: self.lps.append({ 'url': 'http://www.hccapital.com.cn/list/41.html', 'ref': response.url, 'ext': {'flag': 1} }) else: urls = response.xpath('//ul[@class="news-list"]/li/a') for url in urls: href = url.xpath('./@href').extract_first() title = url.xpath('./h5/text()').extract_first() link = urljoin(get_base_url(response), href) self.ips.append({ 'url': link, 'ref': response.url, 'ext': {'title': title, 'url': link} }) next_url = response.xpath('//div[@id="pager"]/ul/li/a[contains(text(), "»")]/@href').extract_first() if next_url is not None and urljoin(get_base_url(response), next_url) != response.url: self.lps.append({ 'url': urljoin(get_base_url(response), next_url), 'ref': response.url, 'ext': {'flag': 1} }) def parse_item(self, response): publish_time = response.xpath('//div[@class="detail_title"]/p').re_first('\d+-\d+-\d+') title = response.meta['ext']['title'] url = response.meta['ext']['url'] item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = datetime.strptime(publish_time, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- import json from datetime import datetime from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class TianTianFundSpider(GGFundNavSpider): name = 'FundNav_TianTianFund' sitename = '天天基金' channel = '天天基金' username = '13636340681' password = '<PASSWORD>' fps = [ { 'url': 'http://fund.eastmoney.com/gaoduan/FundTradeHighEnd.aspx?t=1&var=rankData&ss=all&jz=1&pt=all&nw=all&bm=all&is=all&sc=1y&st=desc&pi=1&pn=20&r=0.047422430673792704', 'pg': 1, }, { 'url': 'http://fund.eastmoney.com/gaoduan/FundTradeHighEnd.aspx?t=1&var=rankData&ss=all&jz=3&pt=4&nw=all&bm=all&is=all&sc=1y&st=desc&pi=1&pn=20&r=0.17771536765939233', 'pg': 1, } ] def start_requests(self): payload = { "loginParam": "<KEY>} yield FormRequest(url='https://login.1234567.com.cn/LoginController.aspx/LoginNew', body=json.dumps(payload), method='POST' ) def parse_fund(self, response): datas = json.loads(response.text[13:-1]) rows = datas['datas'] for row in rows: fund_code = row['FUNDCODE'] fund_name = row['FUNDNAME'] self.ips.append({ 'url': 'http://fund.eastmoney.com/gaoduan/PinzhongF10DataApi.aspx?type=lsjz&fc={0}&pageindex=1&pagesize=10&lsjzSDate=&lsjzEDate=&r=0.94615975431393'.format( fund_code), 'ref': response.url, 'pg': 1, 'ext': {'fund_name': fund_name, 'fund_code': fund_code} }) tp = int(datas['allPages']) pg = response.meta['pg'] + 1 if pg <= tp: self.fps.append({ 'url': 'http://fund.eastmoney.com/gaoduan/FundTradeHighEnd.aspx?t=1&var=rankData&ss=all&jz=1&pt=all&nw=all&bm=all&is=all&sc=1y&st=desc&pi={0}&pn=20&r=0.047422430673792704'.format( pg), 'ref': response.url, 'pg': pg, }) def parse_item(self, response): ext = response.meta['ext'] fund_name = ext['fund_name'] fund_code = ext['fund_code'] datas = json.loads(response.text[11:]) rows = datas['Datas'] for row in rows: statistic_date = row['PDATE'] nav = row['NAV'] added_nav = row['ACCNAV'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name if 'MUI' in row and 'SYI' in row: income_value_per_ten_thousand = row['MUI'] d7_annualized_return = row['SYI'] if income_value_per_ten_thousand and d7_annualized_return: item['d7_annualized_return'] = float( d7_annualized_return) if d7_annualized_return is not None and d7_annualized_return != '' else None item['income_value_per_ten_thousand'] = float( income_value_per_ten_thousand) if income_value_per_ten_thousand is not None and income_value_per_ten_thousand != '' else None else: item['nav'] = float(nav) if nav is not None else None item['added_nav'] = float(added_nav) if added_nav is not None and added_nav != '' else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item tp = int(datas['Pages']) pg = response.meta['pg'] + 1 if pg <= tp: self.ips.append({ 'url': 'http://fund.eastmoney.com/gaoduan/PinzhongF10DataApi.aspx?type=lsjz&fc={0}&pageindex={1}&pagesize=10&lsjzSDate=&lsjzEDate=&r=0.94615975431393'.format( fund_code, pg), 'ref': response.url, 'pg': pg, 'ext': {'fund_name': fund_name, 'fund_code': fund_code}, }) <file_sep># -*- coding: utf-8 -*- # Department:保障部 # Author:王卓诚 # Create_Date:2018-05-28 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class JinShiTouZiInvestSpider(GGFundNavSpider): name = 'FundNav_JinShiTouZiInvest' sitename = '金石投资' channel = '投资顾问' allowed_domains = ['www.gsfund.cn'] username = '点点' password = '<PASSWORD>' cookies = 'PHPSESSID=e1suj9gubpi6e2kfgraf56g474' fps = [{'url': 'http://www.gsfund.cn/Products/index.html'}] def parse_fund(self, response): fund_urls = response.xpath("//li[@class='pw-list-small pw-list-small-on'][3]//@href").extract() fund_names = response.xpath("//a[@id='zhanxian']//text()").extract() for url in zip(fund_urls, fund_names): fund_url = url[0] fund_name = url[1] self.ips.append({ 'url': 'http://www.gsfund.cn' + fund_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath("//div[@class='pw-right-content']//tr") fund_name = response.meta['ext']['fund_name'] for row in rows[1:]: date = row.xpath("./td[2]//text()").extract() statistic_date = ''.join(date) nav = row.xpath("./td[3]//text()").extract_first() if statistic_date: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class YuanFengFundSpider(GGFundNavSpider): name = 'FundNav_YuanFengFund' sitename = '源沣资本' channel = '投顾净值' cookies = 'hlk=checkboxs=1&ty=123' fps = [ { 'url': 'http://www.yffund.com.cn/product.asp', 'ref': None } ] def parse_fund(self, response): rows = response.xpath('//table/tr/td[1]/a') for row in rows: url = row.xpath('./@href').extract_first() self.ips.append({ 'url': urljoin(get_base_url(response), url), 'ref': response.url }) def parse_item(self, response): rows = response.xpath('//div[@id="tabs4_con_2"]/table/tr')[1:] for row in rows: fund_name = row.xpath('./td[1]/text()').extract_first() nav = row.xpath('./td[2]/text()').re_first('[0-9.]+') added_nav = row.xpath('./td[3]/text()').re_first('[0-9.]+') statistic_date = row.xpath('./td[7]/text()').re_first('\d+-\d+-\d+') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy import FormRequest from scrapy.utils.response import get_base_url from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import json class NanHuaFutureNoticeSpider(GGFundNoticeSpider): name = 'FundNotice_NanHuaFutureNotice' sitename = '南华期货' entry = 'https://www.nanhua.net/' username = '13916427906' password = '<PASSWORD>' ips = [ { 'url': 'https://www.nanhua.net/jSearch/queryNewsListByTypeForJson.shtm?site=newnanhua&type=201201&start=1&limit=16', 'ref': 'https://www.nanhua.net/amc/diagnosis/announcements.html', 'ext': {'page': '1'} } ] def start_requests(self): url = 'https://www.nanhua.net/member/newLogin.shtm?start=0' yield FormRequest(url=url, headers={'X-Requested-With': 'XMLHttpRequest', 'Referer': 'https://www.nanhua.net/member/login.html?url=aHR0cHM6Ly93d3cubmFuaHVhLm5ldC8=' }, formdata={ 'account': self.username, 'password': <PASSWORD>, 'isagree': 'on', 'rememberme': '1'}) def parse_item(self, response): ext = response.meta['ext'] page = int(ext['page']) rows = json.loads(response.text) total_pages = int(rows['totalPages']) rows = rows['recordList'] for row in rows: url = row['href'] url = urljoin(get_base_url(response), url) title = row['subject'] publish_time = row['createTime'] publish_time = datetime.strptime(publish_time, '%Y-%m-%d %H:%M:%S') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item if page < total_pages: url = 'http://www.nanhua.net/jSearch/queryNewsListByTypeForJson.shtm?site=newnanhua&type=201201&limit=16&start=' url = url + str(page+1) self.ips.append({ 'url': url, 'ref': response.url, 'ext': {'page': str(page+1)} }) <file_sep>from datetime import datetime from scrapy import Request, FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json class HangZhouMingXiAssetSpider(GGFundNavSpider): name = 'FundNav_HangZhouMingXiAsset' sitename = '杭州明曦资本' channel = '投资顾问' username = 'ZYYXSM' password = '<PASSWORD>' def start_requests(self): url = 'http://www.mingxifund.com/check' yield Request(url=url, callback=self.parse_pre_login) def parse_pre_login(self, response): yield FormRequest(url='http://www.mingxifund.com', formdata={'mingxi': ''}, method='POST', callback=self.parse_next_login) def parse_next_login(self, response): url = 'http://www.mingxifund.com/signin/' yield FormRequest(url=url, formdata={'name': self.username, 'pwd': self.password}, callback=self.parse_login) def parse_login(self, response): self.fps = [{ 'url': 'http://www.mingxifund.com/page-services.html#/CTA1', 'ref': response.url }] def parse_fund(self, response): funds = response.xpath('/html/body/div/div[2]/div[@class="container-fluid"]/div/ul/li/a') for fund in funds: url = fund.xpath('./@href').extract_first() fund_name = fund.xpath('./text()').extract_first() fund_id = url[1:] url = 'http://www.mingxifund.com/get_data/' self.ips.append({ 'url': url, 'form': {'pname': str(fund_id)}, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] fund_name = ext['fund_name'] rows = json.loads(response.text) for row in rows: item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url statistic_date = row['time'] added_nav = row['net_value'] / 10000 item['added_nav'] = float(added_nav) if added_nav is not None and added_nav != '' else None item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item <file_sep># -*- coding: utf-8 -*- import json from datetime import datetime from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class YiCunInvestSpider(GGFundNavSpider): name = 'FundNav_YiCunInvest' sitename = '一村投资' channel = '投资顾问' username = '17839170174' password = '<PASSWORD>' fps = [ { 'url': 'http://www.v-investment.com/api/pc/product/classify?by=INVEST_TARGET' } ] def start_requests(self): payload = {'userName': self.username, 'password': <PASSWORD>, 'userType': '1'} yield FormRequest(url='http://www.v-investment.com/api/user/login', body=json.dumps(payload), method='POST', headers={'Content-Type': 'application/json'}) def parse_fund(self, response): collection = json.loads(response.text)['collection'] for data in collection: rows = data['classifiedProducts'] for row in rows: product_id = row['productId'] fund_name = row['productShortName'] self.ips.append({ 'url': 'http://www.v-investment.com/api/pc/product/{0}/netValues?pageNum={1}'.format(product_id, 1), 'ref': response.url, 'pg': 1, 'ext': {'product_id': product_id, 'fund_name': fund_name} }) def parse_item(self, response): ext = response.meta['ext'] fund_name = ext['fund_name'] product_id = ext['product_id'] json_data = json.loads(response.text) rows = json_data['collection'] if rows: for row in rows: statistic_date = row['netDate'] nav = row['netValue'] added_nav = row['accumulatedNet'] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['added_nav'] = float(added_nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') yield item pg = response.meta['pg'] + 1 tp = int(json_data['property']['pages']) if pg <= tp: self.ips.append({ 'url': 'http://www.v-investment.com/api/pc/product/{0}/netValues?pageNum={1}'.format(product_id, pg), 'ref': response.url, 'pg': pg, 'ext': {'product_id': product_id, 'fund_name': fund_name} }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider from urllib.parse import urljoin from scrapy.utils.response import get_base_url import re class XingHongAssetSpider(GGFundNoticeSpider): name = 'FundNotice_XingHongAsset' sitename = '星鸿资产' entry = 'http://www.starluckwm.com/' ips = [{'url': 'http://www.starluckwm.com/?p=home_xhnews_list&type=board', 'ref': 'http://www.starluckwm.com/'}, {'url': 'http://www.starluckwm.com/?p=home_xhnews_list&type=disclosure', 'ref': 'http://www.starluckwm.com/'}] def parse_item(self, response): next_url = response.xpath('//*[@id="main-content"]/div[2]//div[@class="page-nbm"]/a[text()="Next > "]/@href').extract_first() rows = response.xpath('//*[@id="main-content"]/div[2]/ul/li/h4') for row in rows: title = row.xpath('./a/text()').extract_first() url = row.xpath('./a/@href').extract_first() publish_time = row.xpath('./span/text()').extract_first() publish_time = datetime.strptime(publish_time, '%Y-%m-%d') item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['url'] = urljoin(get_base_url(response), url) item['title'] = title item['publish_time'] = publish_time yield item if next_url: next_url = urljoin(get_base_url(response), next_url) self.ips.append({ 'url': next_url, 'ref': response.url }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-21 from datetime import datetime from scrapy import FormRequest from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class TianQiDeXingInvestSpider(GGFundNavSpider): name = 'FundNav_TianQiDeXingInvest' sitename = '天启德鑫' channel = '投顾净值' username = 'ZYYXSM' password = '<PASSWORD>' fps = [{'url': 'http://www.year30.com/Cases'}] def start_requests(self): yield FormRequest(url='http://www.year30.com/userlogin?returnurl=', formdata={ 'Username': self.username, 'Password': self.<PASSWORD> }) def parse_fund(self, response): href_list = response.xpath('//div[@id="view_list_21_1007"]//a[contains(text(),"净值")]/@href').extract() for href in href_list: self.ips.append({ 'url': 'http://www.year30.com' + href, 'ref': response.url }) def parse_item(self, response): rows = response.css('tbody tr')[1:] for r in rows: td_dt = r.css('td:nth-child(1)::text').extract_first(default='') td_nav = r.css('td:nth-child(2)::text').extract_first(default='') td_add_nav = r.css('td:nth-child(3)::text').extract_first(default='') fund_name = response.css('h1.news_view_title::text').re_first('(.*)净值') if '分红' in td_nav or '分红' in td_add_nav: continue reg_number = re.compile('^[0-9]*.*[0-9]+$') nav = float(td_nav.strip()) if reg_number.match(str(td_nav)) else None if reg_number.match(str(td_add_nav)): if '+' in td_add_nav: num1 = float(td_add_nav.split('+')[0].strip()) num2 = float(td_add_nav.split('+')[1].strip()) add_nav = num1 + num2 else: add_nav = float(td_add_nav.strip()) else: add_nav = None if '20132-11-29' in td_dt: td_dt = '2013-11-29' date = td_dt.replace('-', '').strip() if nav or add_nav: item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = nav item['added_nav'] = add_nav item['statistic_date'] = datetime.strptime(date, '%Y%m%d') yield item <file_sep># -*- coding: utf-8 -*- from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider import json class ChongQingGuoJiTrustSpider(GGFundNoticeSpider): name = 'FundNotice_ChongQingGuoJiTrust' sitename = '重庆国际信托' entry = 'http://www.cqitic.com/' lps = [{'url': 'http://www.cqitic.com/info/'}] def parse_list(self, response): funds = response.xpath('//*[@id="ourBusinessSlider"]/div[@class="item"]') fund_names = '成立公告,管理报告,清算公告,其他公告' for fund in funds: fund_name = fund.xpath('./img/@title').extract_first() if fund_name in fund_names: fund_id = fund.xpath('.//a/@sitemapid').extract_first() url = 'http://www.cqitic.com/more/'+fund_id+'_1_20.shtml' self.ips.append({'url': url, 'ref': response.url, 'ext': {'page': '1', 'fund_id': fund_id} }) def parse_item(self, response): ext = response.meta['ext'] page = int(ext['page']) fund_id = ext['fund_id'] if response.text: rows = json.loads(response.text) for row in rows: item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry url = row['url'] title = row['title'] publish_time = row['displayTime'] publish_time = datetime.strptime(publish_time, '%Y.%m.%d') item['url'] = url item['title'] = title item['publish_time'] = publish_time yield item url = 'http://www.cqitic.com/more/' + fund_id + '_'+str(page+1)+'_20.shtml' self.ips.append({'url': url, 'ref': response.url, 'ext': {'page': str(page+1), 'fund_id': fund_id} }) <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-23 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class HarvestCapitalSpider(GGFundNavSpider): name = 'FundNav_HarvestCapital' sitename = '嘉实资本' channel = '公募专户净值' username = '<EMAIL>' password = '<PASSWORD>.' cookies = 'JSESSIONID=CF0EDB5BE1DB365D6A5F93B0288261F9' # 每次爬取需更换cookies fps = [{ 'url': 'http://www.harvestcm.com/publicPage/web_cn/netWorth_list.action?language=cn&pageNum_networth=1&pageSize_networth=10', 'ref': 'http://www.harvestcm.com/publicPage/web_cn/mediaIndex_index.action?contentType=0&language=cn', 'pg': 1 }] def parse_fund(self, response): page_1 = response.meta['pg'] page_number_1 = response.xpath('//div[@id="PageSelectorSelectorArea"]/a[@title="尾页"]/@href').extract_first() end_page_1 = int(page_number_1.replace('javascript: gotoPage_networth(', '').replace(')', '')) if page_1 < end_page_1: next_pg_1 = page_1 + 1 next_url = response.url.replace('&pageNum_networth=' + str(page_1), '&pageNum_networth=' + str(next_pg_1)) self.fps.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg_1 }) fund_link_key = response.xpath( '//div[@id="netWorthList"]/div[@id="MainArea"]/table[@id="J_approval2"]/tbody[@id="TableData"]/tr/td[3]/a/@href').extract() pg = 1 for key in fund_link_key: key_code = key.replace('netWorth_detailList.action?language=cn', '') fund_link = 'http://www.harvestcm.com/publicPage/web_cn/netWorth_detailList.action?language=cn' + '&pageNum_networth=' + str( pg) + '&pageSize_networth=10' + key_code self.ips.append({ 'url': fund_link, 'ref': response.url, 'pg': pg }) def parse_item(self, response): page_number = response.xpath('//div[@id="PageSelectorSelectorArea"]/a[@title="尾页"]/@href').extract_first() end_page = int(page_number.replace('javascript: gotoPage_networth(', '').replace(')', '')) nav_rows = response.xpath('//tr[@class="TableDetail1 template"]') for row in nav_rows: row_info = row.xpath('td/text()').extract() fund_name = row_info[3].strip() statistic_date = row_info[1].strip().replace('/', '-') nav = row_info[4].strip() added_nav = row_info[5].strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None item['nav'] = float(nav) if nav else None item['added_nav'] = float(added_nav) if added_nav else None yield item pg = response.meta['pg'] if pg < end_page: next_pg = pg + 1 next_url = response.url.replace('&pageNum_networth=' + str(pg), '&pageNum_networth=' + str(next_pg)) self.ips.append({ 'url': next_url, 'ref': response.url, 'pg': next_pg }) <file_sep># -*- coding: utf-8 -*- from datetime import datetime from urllib.parse import urljoin from scrapy.utils.response import get_base_url from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider class ZhongGangFuturesSpider(GGFundNavSpider): name = 'FundNav_ZhongGangFutures' sitename = '中钢期货' channel = '期货净值' fps = [ { 'url': 'http://www.zgfcc.com/zhonggang/tbzl7.aspx?id=236&idl=0&ex=3&yjml=236&ejml=' } ] def parse_fund(self, response): rows = response.xpath('//table/tr/td/a') for row in rows: url = row.xpath('./@href').extract_first() url = urljoin(get_base_url(response), url) self.ips.append({ 'url': url, 'ref': response.url }) def parse_item(self, response): rows = response.xpath('//tbody/tr')[1:] if response.xpath('//tbody/tr[1]/td[1]/text()').extract_first().strip() == '产品名称' else response.xpath('//table/tbody/tr/td[1]/table/tbody/tr')[1:] for row in rows: fund_name = row.xpath('./td[1]/text()').extract_first().strip() statistic_date = row.xpath('./td[2]/text()').re_first('\d+/\d+/\d+') nav = row.xpath('./td[3]/text()').re_first('[0-9.]+') item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['nav'] = float(nav) item['statistic_date'] = datetime.strptime(statistic_date, '%Y/%m/%d') yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-08 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from scrapy.utils.response import get_base_url from urllib.parse import urljoin import re class CaiKaFeiFundSalesSpider(GGFundNavSpider): name = 'FundNav_CaiKaFeiFundSales' sitename = '上海财咖啡基金销售有限公司' channel = '投顾净值' fps = [{ 'url': 'http://www.rffund.com/list/407/1.shtml', 'pg': 1 }] def parse_fund(self, response): if response.status != '404': href_list = response.xpath('//a[contains(@title,"净值公告")]/@href').extract() for href in href_list: self.ips.append({ 'url': urljoin(get_base_url(response), href), 'ref': response.url, }) next_pg = response.meta['pg'] + 1 self.fps.append({ 'url': re.sub('\d+\.shtml', str(next_pg) + r'.shtml', response.url), 'ref': response.url, 'pg': next_pg }) def parse_item(self, response): title = response.css('h2.padding-top35::text').extract_first() content = response.xpath('string(//div[@class="new-detaiList padding-bottom25"])').extract_first() # 截至2015年10月30日,日发资产灵活配置9号基金基金净值为0.77元 date_reg = re.compile('截\D+(\d+年\d+月\d+日)', re.DOTALL) # name_reg = re.compile('(日发.*)基金净值', re.DOTALL) nav_reg = re.compile('净值\D*(\d\.\d*)', re.DOTALL) fund_name = title.split('基金')[0] date = date_reg.findall(content) # name = name_reg.findall(content) nav = nav_reg.findall(content) item = GGFundNavItem() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav[0]) if nav else None item['statistic_date'] = datetime.strptime(date[0], '%Y年%m月%d日') if date else None yield item <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-06-01 # Alter_date : 2018-06-01 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import re class GuoDuSecuritiesSpider(GGFundNavSpider): name = 'FundNav_GuoDuSecurities' sitename = '国都证券' channel = '券商资管净值' fps = [{'url': 'http://www.guodu.com/finance/financing_zxjz.jsp'}] def parse_fund(self, response): pid_list = response.css('div.container_common td a::attr(href)').re('productMore\.jsp\?(.*)') pname_list = response.css('div.container_common td a::text').extract() stamp = int(datetime.now().timestamp() * 1000) for pid, pname in zip(pid_list, pname_list): self.ips.append({ 'url': 'http://www.guodu.com/finance/ajax/product_cpjz.jsp?' + pid + '&random=%s' % stamp, 'form': { 'byAjax': '1', 'pagesize': '200', 'pageNo': '1', 'status': '2', 'columnid': '3' }, 'ref': response.url, 'pg': 1, 'ext': re.sub('(.*|\(.*', '', pname) }) def parse_item(self, response): rows = response.css('tr') f_name = response.meta['ext'] col_cnt = len(response.css('tr.tr_class_color ::text').re('\S+')) col_str = '/'.join(response.css('tr.tr_class_color ::text').re('\S+')) for r in rows[1:-1]: date = r.xpath('td[1]/text()').extract_first() item = GGFundNavItem() if '七日年化' in response.text: per_ten = r.xpath('td[2]/text()').extract_first() d7 = r.xpath('td[3]/text()').extract_first() item['sitename'] = self.sitename item['fund_name'] = f_name item['channel'] = self.channel item['url'] = response.url item['income_value_per_ten_thousand'] = float(per_ten) if per_ten else None item['d7_annualized_return'] = float(d7) if d7 else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item elif '优先级' in col_str: fund_name = f_name if col_cnt == 5 and '中间级' in col_str: nav = r.xpath('td[2]/text()').extract_first() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav) if nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item nav_middle = r.xpath('td[3]/text()').extract_first() item['sitename'] = self.sitename item['fund_name'] = f_name + '优先级' item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav_middle) if nav_middle else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item nav_ordinary = r.xpath('td[4]/text()').extract_first() item['sitename'] = self.sitename fund_name = f_name + '中间级' item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav_ordinary) if nav_ordinary else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item nav_ordinary = r.xpath('td[5]/text()').extract_first() item['sitename'] = self.sitename fund_name = f_name + '普通级' item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav_ordinary) if nav_ordinary else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item else: nav = r.xpath('td[2]/text()').extract_first() add_nav = r.xpath('td[5]/text()').extract_first() item['sitename'] = self.sitename item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav) if nav else None item['added_nav'] = float(add_nav) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item nav_priority = r.xpath('td[3]/text()').extract_first() add_nav_priority = r.xpath('td[6]/text()').extract_first() item['sitename'] = self.sitename item['fund_name'] = f_name + '优先级' item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav_priority) if nav_priority else None item['added_nav'] = float(add_nav_priority) if add_nav_priority else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item nav_ordinary = r.xpath('td[4]/text()').extract_first() add_nav_ordinary = r.xpath('td[7]/text()').extract_first() item['sitename'] = self.sitename if '进取级' in col_str: fund_name = f_name + '进取级' elif '普通级' in col_str: fund_name = f_name + '普通级' item['fund_name'] = fund_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav_ordinary) if nav_ordinary else None item['added_nav'] = float(add_nav_ordinary) if add_nav_ordinary else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item elif 'B类份额' in response.text: nav = r.xpath('td[2]/text()').extract_first() add_nav = r.xpath('td[5]/text()').extract_first() item['sitename'] = self.sitename item['fund_name'] = f_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav) if nav else None item['added_nav'] = float(add_nav) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item nav_a = r.xpath('td[3]/text()').extract_first() add_nav_a = r.xpath('td[6]/text()').extract_first() item['sitename'] = self.sitename item['fund_name'] = f_name + 'A类' item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav_a) if nav_a else None item['added_nav'] = float(add_nav_a) if add_nav_a else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item nav_b = r.xpath('td[4]/text()').extract_first() add_nav_b = r.xpath('td[7]/text()').extract_first() item['sitename'] = self.sitename item['fund_name'] = f_name + 'B类' item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav_b) if nav_b else None item['added_nav'] = float(add_nav_b) if add_nav_b else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item else: nav = r.xpath('td[2]/text()').extract_first() add_nav = r.xpath('td[3]/text()').extract_first() item['sitename'] = self.sitename item['fund_name'] = f_name item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav.replace('..', '.')) if nav else None item['added_nav'] = float(add_nav.replace('..', '.')) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item if len(rows) > 2: next_pg = response.meta['pg'] + 1 self.ips.append({ 'url': response.url, 'form': { 'byAjax': '1', 'pagesize': '200', 'pageNo': str(next_pg), 'status': '2', 'columnid': '3' }, 'ref': response.url, 'pg': next_pg, 'ext': f_name }) <file_sep># -*- coding: utf-8 -*- # Department : 保障部 # Author : 李婧 # Create_date : 2018-05-10 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from urllib.parse import urljoin class EtenalGrandSpider(GGFundNavSpider): name = 'FundNav_EtenalGrand' sitename = '深圳恒泰融安投资' channel = '投顾净值' allowed_domains = ['www.eternalgrand.com'] username = 'ZYYXSM' password = '<PASSWORD>' cookies = '__guid=88917149.2507931099894912000.1525935285317.8052; monitor_count=15', fps = [{'url': 'http://www.eternalgrand.com/fuwuxiangmu/jingzhipilu/'}] def parse_fund(self, response): href_list = response.xpath('//ul[@class="cppu-contant"]//li//@href').extract() fund_names = response.xpath('//ul[@class="cppu-contant"]//li/p[1]//text()').extract() for url, name in zip(href_list, fund_names): ips_url = urljoin('http://www.eternalgrand.com/fuwuxiangmu/jingzhipilu/', url) fund_name = name self.ips.append({ 'url': ips_url, 'ref': response.url, 'ext': {'fund_name': fund_name} }) def parse_item(self, response): rows = response.xpath('//div[@class="content"]/div/table//tr') fund_name = response.meta['ext']['fund_name'] for row in rows[1:]: fund_date = row.xpath('.//td[2]//text()').extract_first().strip() fund_nav = row.xpath('.//td[3]//text()').extract_first().strip() item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(fund_date, '%Y/%m/%d') item['nav'] = float(fund_nav) yield item <file_sep># -*- coding: utf-8 -*- import json from datetime import datetime from FundNoticeSpiders import GGFundNoticeItem from FundNoticeSpiders import GGFundNoticeSpider class ZhongYouSecuritySpider(GGFundNoticeSpider): name = 'FundNotice_ZhongYouSecurity' sitename = '中邮证券' entry = 'http://www.cnpsec.com.cn/web/list.htm?menuId=08&subId=0801&classId=080104' ips = [ { 'url': 'http://www.cnpsec.com.cn/web/list.ashx', 'form': {'classid': '080104', 'pageIndex': '1', 'infoFlag': 'finfo', 'type': '1', 'keywords': 'null', 'datalen': '20', 'hrefURL': 'L2N0enEvenh6eC96eDAzLmh0bWw/bWVudUlkPTA4JnN1YklkPTA4MDEmY2xhc3NJZD0wODAxMDQ=', 'jsontype': 'json_4' }, 'pg': 1 } ] def parse_item(self, response): json_data = json.loads(response.text) rows = json_data['result'] for row in rows: title = row['title'] url = 'http://www.cnpsec.com.cn/web/News.htm?infoid={0}&subId=0801&classId=080104'.format(row['infoid']) publish_time = row['originaltime'] item = GGFundNoticeItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url_entry'] = self.entry item['title'] = title item['url'] = url item['publish_time'] = datetime.strptime(publish_time, '%Y/%m/%d %H:%M:%S') yield item tp = json_data['totalPages'] pg = response.meta['pg'] + 1 if pg <= tp: self.ips.append({ 'url': 'http://www.cnpsec.com.cn/web/list.ashx', 'form': {'classid': '080104', 'pageIndex': str(pg), 'infoFlag': 'finfo', 'type': '1', 'keywords': 'null', 'datalen': '20', 'hrefURL': 'L2N0enEvenh6eC96eDAzLmh0bWw/bWVudUlkPTA4JnN1YklkPTA4MDEmY2xhc3NJZD0wODAxMDQ=', 'jsontype': 'json_4' }, 'pg': pg }) <file_sep># Department : 保障部 # Author : 钱斌 # Create_date : 2018-05-22 from datetime import datetime from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider import json import re class NanJingSecuritySpider(GGFundNavSpider): name = 'FundNav_NanJingSecurity' sitename = '南京证券' channel = '券商资管净值' trs_keycode = [13, 14, 15, 16, 17, 19, 24] ips = [] for k in trs_keycode: href = 'productId=%s&current_page=1&pageSize=300' % k ips.append({ 'url': 'http://klyg.njzq.cn/iphone/callback/zg/include_cpjz.jsp?' + href, 'pg': 1, }) def parse_item(self, response): if 'null()' not in response.text: json_data = re.findall('null\((.*)\)', response.text, re.DOTALL) data = json.loads(json_data[0])['values'] for d in data: fname = d['productName'] date = d['netValueDateString'] nav = d['strProductNetValue'] add_nav = d['strCumulateNetValue'] item = GGFundNavItem() if 'productId=17' in response.url: item['sitename'] = self.sitename item['fund_name'] = fname item['channel'] = self.channel item['url'] = response.url item['annualized_return'] = float(nav.replace('.', '.')) if nav else None item['d7_annualized_return'] = float(add_nav.replace(' ', '')) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item continue item['sitename'] = self.sitename item['fund_name'] = fname item['channel'] = self.channel item['url'] = response.url item['nav'] = float(nav.replace('.', '.')) if nav else None item['added_nav'] = float(add_nav.replace(' ', '')) if add_nav else None item['statistic_date'] = datetime.strptime(date, '%Y-%m-%d') if date else None yield item next_pg = response.meta['pg'] + 1 next_url = re.sub('current_page=\d+', 'current_page=' + str(next_pg), response.url) self.ips.append({ 'url': next_url, 'pg': next_pg, }) <file_sep># Department : 保障部 # Author : 陈雅婷 # Create_date : 2018-05-04 from urllib.parse import urljoin from FundNavSpiders import GGFundNavItem from FundNavSpiders import GGFundNavSpider from datetime import datetime class JiaDeCapitalSpider(GGFundNavSpider): name = 'FundNav_JiaDeCapital' sitename = '嘉得资产' channel = '投顾净值' fps = [{'url': 'http://www.zj-jd.cn/touzizheguanxi/jijinjingzhi'}] def parse_fund(self, response): link_key = response.xpath('//div[@class="news-zx"]/ul/li/a/@href').extract() for key in link_key: fund_link = urljoin('http://www.zj-jd.cn/', key) self.ips.append({ 'url': fund_link, 'ref': response.url }) def parse_item(self, response): fund_info = response.xpath('//div[@class="title"]/h1/text()').extract_first() nav_rows = response.xpath('//div[@class="content"]/table/tbody/tr') title = response.xpath('//div[@class="content"]//table/tbody/tr/td[2]/text()').extract_first() if '净值' in title: for row in nav_rows[1:]: nav_info = row.xpath('td/text()').extract() fund_name = fund_info.replace('净值', '') statistic_date = nav_info[0].replace('.', '-').strip() nav = nav_info[1] added_nav = nav_info[1] item = GGFundNavItem() item['sitename'] = self.sitename item['channel'] = self.channel item['url'] = response.url item['fund_name'] = fund_name item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if fund_name == '嘉得趋势策略二号基金': item['nav'] = float(nav) if nav is not None else None else: item['added_nav'] = float(added_nav) if added_nav is not None else None yield item
3591ab22e1cc0fc1362f909017a8aa5c2b53bd92
[ "Python" ]
292
Python
Wnltc/ggscrapy
bf929112e14b875a583803fe92980fe67129bdac
ef7e9559ce6140e7147f539778e25fc7f6cbee4c
refs/heads/master
<repo_name>sdtsztom/Tools.Efficiency<file_sep>/plugin.ini [Common] FolderName=Tools.Efficiency AppName=Tools for efficiency AppName_2052=效率工具 AppName_1028=效率工具 AppGUID={10b03cc5-df10-429a-a46f-f5d930c7a440} AppType=Tools AppVersion=0.1 PluginCount=4 SupportVersion=2 [Plugin_0] Caption=add_button Caption_2052=添加按钮 Caption_1028=添加按钮 GUID={fe4d686d-eb3c-493b-b2fa-b0dee3bdfc80} ScriptFileName=add_button.js Type=Global [Plugin_1] MenuType=Tools Caption=Jump Caption_2052=跳转 Caption_1028=跳转 GUID={21f8dbe0-2271-4ba4-b442-29d124fadff6} HtmlDialogFileName=jump.html Type=HtmlDialog [Plugin_2] MenuType=Tools Caption=Classify Caption_2052=归档 Caption_1028=归档 GUID={71d7c173-dbe0-4a20-8e81-18d50b382273} ScriptFileName=classify.js Type=ExecuteScript [Plugin_3] MenuType=Tools Caption=Help Caption_2052=帮助 Caption_1028=帮助 GUID={83f97ef3-8856-4cb1-938a-494f7c43f57e} HtmlDialogFileName=help.html Type=HtmlDialog HtmlDialogTitle=Help HtmlDialogTitle_2052=帮助 HtmlDialogTitle_1028=帮助 HtmlDialogWidth=700 HtmlDialogHeight=250 [Strings] strJump=Jump strJump_2052=跳转 strJump_1028=跳转 strClassify=Classify strClassify_2052=归档 strClassify_1028=归档<file_sep>/README.md # Tools.Efficiency wizPlugin 使用说明 - 本插件包含两个模块:**跳转**,**归档**。 - 下面的说明希望能让更多的人让看懂,因此在叙述上可能稍显冗余。 - 此说明文档的例子大多很重要,因为这之中包含了功能或者必须要注意到的事项,因此,请不要随意略过。 ## 跳转 跳转是可以快速为你定位到你想要的文件夹,跳转的方式会有两种(这由程序自动选择)分别是`fast jump`和`normal jump`。当你的关键词没有空格的时候,会优先使用前者,当在配置文件中没有相对应关键词的配置的时候,会自动执行后者。而当你的关键词包含空格的时候,会直接进行`normal jump`。 ## fast jump fast jump不支持多个关键词,所以当有多个关键词时,程序会直接使用normal jump。fast jump,你又可以叫他alias jump,这两种名字包含了它的两种特性:一个是你可以以你自定义的名称去跳转到你所指定的文件夹,另一个是这种方式更快,因为是直接读取配置文件`set_effi_tool`中的配置。具体设置方式见下面的"配置文件:`set_effi_tool`"部分 ## normal jump normal jump支持多个关键词,多个关键词之间用空格隔开。normal jump是通过搜索所有的路径,找到能够匹配你的所有关键词**最短匹配项**打开。 ### 关于**最短匹配项** - Exp1.比如,你有一个文件夹`/English/2018`,那么如果你搜索`English`,那么会选择跳转到`/English`,而非`/English`下的任何子目录中,虽然这些子目录的路径也包含`English`关键词。 - Exp2.如果你还有一个文件夹`/journals/2018`,如果你想跳转到这个文件夹,那么你输入`2018`,那么程序按理会跳转到`/English/2018`这个文件夹,因为这个文件夹的路径名的字符长度更短。因此,你应该采用多个关键词的方式来跳转到你想要的`/journals/2018`。比如,你可以输入`jour 18`等诸如此类的关键词以确保你可以跳转到`/journals/2018`,因为只有`/journals/2018`既包含`jour`又包含`18` ## 归档 以指定关键词开头的**当前文档**(也就是你开着并看见的那个)自动移动到你配置好的文件夹中。 - Exp1.比如我想把当前浏览的文档移动到`/journals/2018`这个文件夹,那么,首先在配置文件`set_effi_tool`中配置好相应的关键字和要移动到的路径(配置方式见下文)。那么,我可以直接在创建的时候就以此关键词开头,假设我配置的关键词是`journal-18`,那么我可以创建一篇名为`journal-18mmdd`的日记,在写完以后,保存,然后使用归档,就会将此日记移动到`journals/2018` - Exp2.如果你不想你的日记保留`journal-18`的前缀,那么你可以保持你在配置文件中的关键词不变,只需在创建文件的时候使用`@关键词`(对应的日记名改为`@journal-18mmdd`),那么归档会将此文件移动指定的文件夹,不过会去除这个关键词前缀,即在程序被移动到指定文件夹后,文件名改为了`mmdd`。 ## 配置文件:`set_effi_tool` - 首先,在你的`/我的笔记`下创建一个名为`set_effi_tool`的笔记 - 笔记内容应该遵循或者说最好遵循这样的格式: ``` [classify] 'key=value' ...... [jump] 'key=value' ...... ``` 上面的key就是上文一直提到的关键词,value就是对应的指定文件夹 - Exp1.对应上面的例子,我应该在`[classify]`的部分写下一行`'journal-18=/journals/2018`,又或者,如果我想用`j8`这个关键词让我快速跳转到`/journals/2018`文件夹,那么我应该在`[jump]`的部分写下一行`'j8=/journals/2018'`, - Exp2.如果你分类用的关键词(注意跳转用的关键词不应该含有空格),或者你的路径中包含空格,那么你在`set_effi_tool`的书写中应该用`#`去代替空格,比如,我想把`English Learning-18`开头的笔记移动到`/English/2018`,那么我应该这样设置`'English#Learning-18=/English/2018'`(所以注意你想要取得关键词或者你要设置得路径中不要包含#,因为你写入设置得所有的#都会被转化成空格) - 为知笔记的有些程序自己自带的文件夹的名字不一定是他所显示的名字,比如`我的笔记`这个文件夹,他的真实名字是`My Notes`,又比如`我的日记`这个文件夹,他的真实名字是`My Journals`,当然,你自己创建的文件夹没有这样的问题。那么如何得知这个一个文件夹的真实名字的,可以打开你存储数据的文件夹(可以在`选项/数据存储`页面找到),在那里文件夹的名字是以真实名字保存的。 ## 安装 - 在github选择download zip,那么你下载到的应该是名为一个`Tools.Efficiency-master.zip`的压缩文件,将其改名为`Tools.Efficiency.wizplugin`,然后双击打开安装,并重启你的为知笔记即可 ## final if there are any problems,bug or advice ,feel free to contact me. My email is <EMAIL><file_sep>/add_button.js function tlef_onJumpClicked(){ //objApp.ExecutePlugin('21f8dbe0-2271-4ba4-b442-29d124fadff6'); var path=objApp.GetPluginPathByScriptFileName('add_button.js'); //objWindow.ShowHtmlDialog('',path+'jump.html',500,500,''); objWindow.ShowHtmlDialogEx(false, "Jump", path+'jump.html', 300, 100, "", null, null); } function tlef_onClassifyClicked(){ //objApp.ExecutePlugin('71d7c173-dbe0-4a20-8e81-18d50b382273'); var path=objApp.GetPluginPathByScriptFileName('add_button.js'); objApp.RunScriptFile(path+'classify.js','javascript'); } function tlef_init(){ /* var str_jump=objApp.TranslateString('Jump'); var str_classify=objApp.TranslateString('Classify');*/ var path=objApp.GetPluginPathByScriptFileName('add_button.js'); var str_jump=objApp.LoadStringFromFile(path+'plugin.ini','strJump'); var str_classify=objApp.LoadStringFromFile(path+'plugin.ini','strClassify'); objWindow.AddToolButton('main','jump',str_jump,'','tlef_onJumpClicked'); objWindow.AddToolButton('main','classify',str_classify,'','tlef_onClassifyClicked'); } tlef_init();
5050492ae6a5e2b2ff81d152e6f9205b6e0ae189
[ "Markdown", "JavaScript", "INI" ]
3
INI
sdtsztom/Tools.Efficiency
118356da4b4852d1ab58eae801c2df248753aa4d
be7af0510eb3403645a7128b9343678a1ee64a01
refs/heads/master
<file_sep>;(function (window,undefined){ function Hotspot(){ this.init(); } Hotspot.prototype = { init :function(){ this.onHotspotHover(); }, //定位点显示隐藏 onHotspotHover:function(){ var hotSports = this.$$('Hotspot'), len = hotSports.length, i, that = this, currDetiaImg; for(i=0;i<len;i++){ currDetiaImg = that.$$('detailImg',hotSports[i])[0]; currDetiaImg.timer = null; currDetiaImg.alpha = 0; hotSports[i].onmouseover = function(e){ that.doTransform(that.$$('detailImg',this)[0],100); that.$$('hotSpotSpan',this)[0].style.display = 'none'; } hotSports[i].onmouseout = function(e){ that.doTransform(that.$$('detailImg',this)[0],0); that.$$('hotSpotSpan',this)[0].style.display = 'block'; } } }, //细节图展开 doTransform:function(me,alpha){ var times = 0; if (alpha == 100) { times = 5; }else{ times = -5; } me.style.display = 'block'; clearInterval(me.timer); me.timer = setInterval(functioin(){ if (me.alpha == alpha) { clearInterval(me.timer); if (alpha == 0) { me.style.display = 'none'; }else{ me.alpha += times; me.style.opacity = me.alpha/100; me.style.filter = 'alpha(opacity:'+me.alpha+')';//兼容ie } } },30); }, $$: function(clsName,ele){ if (document.getElementByClassName) { return (ele || document).getElementByClassName(clsName); }else{ var nodes = (ele || document).getElementsByTagName('*'), eles = [], len = nodes.length, i, j, currNode, clsNames, clsLen; for(i=0;i<len;i++){ currNode = nodes[i]; clsNames = currNode.clsName.split(' '); clsLen = clsNames.length; for(j=0;j<clsLen;j++){ if (clsNames[j] == clsName) { eles.push(currNode); break; } } } return eles; } } } new Hotspot(); })(window);
7ac2c6647012bc41eb69bae7d6582c23fbc394fd
[ "JavaScript" ]
1
JavaScript
zhangcw4014/mouse-hover
d03020b702ff66888b286bfb9fb24ccf8a4fd35b
bc3231aa31b3e2e1fa35823737841a6b620ceedc
refs/heads/master
<repo_name>jacobsyentl/PuzzleBobble<file_sep>/src/Game/View/MultiPlayerPane.java package Game.View; import Game.Controller.MPController; import Game.Database.Player; import javafx.event.EventHandler; import javafx.scene.control.Label; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import javafx.scene.shape.Line; import java.util.HashMap; import java.util.Map; public class MultiPlayerPane extends Pane{ private MPController parent; private StackPane rootPane; private Pane pane; private Line hBorder; private Line vBorder; public MultiPlayerPane(MPController parent, StackPane rootPane) { this.parent = parent; this.rootPane = rootPane; pane = this; initComponents(); addComponents(); eventHandlers(); parent.invokeGameBoardController(this); } private void initComponents() { pane.setMaxSize(640, 640); pane.setPrefSize(640, 640); hBorder = new Line(0, 20, 640, 20); vBorder = new Line(320,20,320,660 ); hBorder.getStrokeDashArray().addAll(2.0); vBorder.getStrokeDashArray().addAll(2.0); } private void addComponents() { pane.getChildren().addAll(hBorder,vBorder); rootPane.getChildren().add(pane); } private void eventHandlers() { pane.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { KeyCode keyCode = event.getCode(); if (keyCode == KeyCode.Q) { parent.leftKeyPressed(0); } if (keyCode == KeyCode.D) { parent.rightKeyPressed(0); } if (keyCode == KeyCode.LEFT) { parent.leftKeyPressed(1); } if (keyCode == KeyCode.RIGHT) { parent.rightKeyPressed(1); } event.consume(); } }); pane.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { KeyCode keyCode = event.getCode(); if (keyCode == KeyCode.Q || keyCode == KeyCode.D ) { parent.leftRightKeyReleased(0); } if (keyCode == KeyCode.Z) { parent.upKeyReleased(0); } if (keyCode == KeyCode.LEFT || keyCode == KeyCode.RIGHT ) { parent.leftRightKeyReleased(1); } if (keyCode == KeyCode.UP) { parent.upKeyReleased(1); } event.consume(); } }); } public void displayActivePowerBubbles(HashMap<String,Integer> powerBubbles, Player player){ for (Map.Entry<String,Integer> entry: powerBubbles.entrySet()){ String key = entry.getKey(); int value = entry.getValue(); Label label = new Label(key+": "+value); label.setLayoutX(10); this.getChildren().add(label); } } public void setRemainingBalls(int player,int remainingBalls) { Label label =new Label(player+": "+remainingBalls); label.setLayoutX(50); this.getChildren().add(label); } }<file_sep>/src/Game/Controller/SettingsController.java package Game.Controller; import Game.Database.Player; import Game.View.SettingsPane; import javafx.scene.layout.StackPane; public class SettingsController { private StackPane rootPane; public SettingsController(StackPane rootPane){ this.rootPane = rootPane; invokeView(); } private void invokeView() { new SettingsPane(rootPane, this); } public void invokeMenuController(){ new MenuController(rootPane); } public void invokeSPController(Player player){ new SPController(rootPane, player); } } <file_sep>/src/Game/View/MainScene.java package Game.View; import javafx.geometry.Pos; import javafx.scene.image.Image; import javafx.scene.layout.StackPane; import javafx.scene.paint.ImagePattern; import javafx.scene.shape.Rectangle; public class MainScene extends StackPane { public MainScene() { styleMainGamePane(); } private void styleMainGamePane() { stylePane(); makeLandscape(); } private void stylePane(){ this.setPrefSize(875.0,720.0); this.setMinSize(875.0,720.0); this.setMaxSize(875.0,720.0); this.setId("mainPane"); } private void makeLandscape() { Rectangle rect = new Rectangle(900,250); this.setAlignment(rect, Pos.BOTTOM_CENTER); Image background = new Image("file:../../assets/images/Green_landscape.png"); rect.setFill(new ImagePattern(background)); this.getChildren().add(rect); } }<file_sep>/README.md # PuzzleBobble ## About the project Arcade game based on the original Puzzle Bobble, but space themed. This group project was part of my high school's curriculum and focused on creating a game with java. Group participants: * [<NAME>](https://github.com/JSadones) * [<NAME>](https://github.com/pirardlucas) * [<NAME>](https://github.com/ShaneDeconinck) * [<NAME>](https://github.com/jacobsyentl) ## Screenshot ![app Demo](https://github.com/jacobsyentl/PuzzleBobble/blob/master/demo/Demo.png "Demo of the application") <file_sep>/src/Game/Controller/HighscoresController.java package Game.Controller; import Game.Database.BubbleDB; import Game.Database.HighscorePerLevel; import Game.Database.Level; import Game.Database.Player; import Game.View.HighscoresPane; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.layout.StackPane; import java.util.ArrayList; public class HighscoresController { private StackPane rootPane; BubbleDB bubbleDB = BubbleDB.getInstance(); public HighscoresController(StackPane rootPane){ this.rootPane = rootPane; invokeView(); } private void invokeView() { new HighscoresPane(rootPane, this); } public void invokeMenuController(){ new MenuController(rootPane); } public ObservableList<HighscorePerLevel> getLevelData(int levelNumber){ String[][] data = bubbleDB.getHighscoresFromLevel(levelNumber); ArrayList<HighscorePerLevel> dataArrayList = new ArrayList<HighscorePerLevel>(); for(int i = 0; i < data.length; i++){ dataArrayList.add(new HighscorePerLevel(Integer.parseInt(data[i][1]), data[i][0])); } ObservableList<HighscorePerLevel> objects = FXCollections.observableArrayList(dataArrayList); return objects; } public ArrayList<String> getLevels(){ ArrayList<Level> levelData; ArrayList<String> data = new ArrayList<String>(); levelData = bubbleDB.getLevels(); for(int i = 0; i < levelData.size(); i++){ data.add(levelData.get(i).getLevelName()); } return data; } public ObservableList<Player> getPlayers(){ ArrayList<Player> players; players = bubbleDB.getMultiplayerData(); ObservableList<Player> objects2 = FXCollections.observableArrayList(players); return objects2; } }<file_sep>/src/Game/Controller/GameBoardController.java package Game.Controller; import Game.Database.Bubble; import Game.Database.BubbleDB; import Game.Database.Player; import Game.Logic.*; import Game.View.GameBoardPane; import Game.View.PausedPane; import Game.View.WinPane; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import java.util.*; public class GameBoardController { private StackPane rootPane; private boolean gameStatus; private int score, shooterOffset, currentLevel = 1; private Board board; private BubbleDB bubbleDB = BubbleDB.getInstance(); private Seed seed = new Seed(); private String levelSeed; private Bubble currentBubble, nextBubble; private BubbleFactory bubbleFactory; private int rows, columns; private GameController parent; private GameBoardPane gameBoardPane; private Pane root; private List<Integer> typeBubbles; private String currentSeed = ""; private boolean isAnimationFinished = false; private char position; private Player player; HashMap<String, Integer> lesserChoiceCounter; private int colorblindCounter; private int remainingBubbles; int playerNumber; public GameBoardController(){ this(null,null,null, 15, 8,'s', null); } public GameBoardController(Pane root,StackPane rootPane, GameController parent, int rows, int columns, char pos, Player player) { this.rootPane=rootPane; this.rows = rows; this.columns = columns; this.player = player; shooterOffset = 4; board = new Board(this.rows, this.columns, shooterOffset, this); score = 0; this.root = root; this.parent = parent; bubbleFactory = this.parent.bubbleFactory; this.position = pos; this.colorblindCounter = 0; this.lesserChoiceCounter = new HashMap<String, Integer>(); this.remainingBubbles = 30; BubbleDB bubbleDB = BubbleDB.getInstance(); levelSeed = bubbleDB.getLevels().get(currentLevel - 1).getLevelSeed(); invokeView(root, pos); } private void invokeView(Pane rootPane,char position) { if(rootPane!=null){ this.gameBoardPane = new GameBoardPane(rootPane,this,shooterOffset,position); } } public void invokePausedPane(){ new PausedPane(root, this); } public void loadLevel(){ if(position == 's') { String levelSeed = bubbleDB.getLevelFromNumber(currentLevel); board.loadLevel(levelSeed); typeBubbles = seed.analyseSeed(levelSeed); } else{ String levelseed = parent.getRandomSeed(); board.loadLevel(levelseed); typeBubbles = seed.analyseSeed(levelseed); } } public void start(){ gameStatus = true; } public void stop(){ gameStatus = false; } public boolean isStarted(){ return gameStatus; } public boolean isStopped(){ if(gameStatus) return false; else return true; } public int getRows() { return rows; } public int getScore() { return score; } public Board getBoard(){return board;} public void checkEmpty(char position){ if (board.isBoardEmpty()){ parent.setGamePaused(true); if(position == 's'){ new WinPane(root, this); writeScore(); } } } public Hashtable<String, Object> shoot(double thetaFromPointerInRadians) { int currentRow = 0; LogicCoord currentPositionOfProjectile = new LogicCoord(0,-shooterOffset); LogicCoord lastPositionOfProjectileConfirmedToFitInBoard = currentPositionOfProjectile; currentPositionOfProjectile = board.getLogicCoordOfCollisionWithBottomOfLogicRow(thetaFromPointerInRadians, currentRow, currentPositionOfProjectile.convertToAspectLogicCoord(shooterOffset)); Hashtable<String, Object> result = new Hashtable<>(); ArrayList<VisualCoord> queueProjectile = new ArrayList<>(); do { while (board.containsXOf(currentPositionOfProjectile) && currentRow < board.getNumberOfRows()) { lastPositionOfProjectileConfirmedToFitInBoard = currentPositionOfProjectile; ArrayList<LogicCoord> potentialCoordsOfCollision = board.getBubblesWithinRangeOfProjectile(currentPositionOfProjectile, thetaFromPointerInRadians); potentialCoordsOfCollision = board.filterLogicCoordsByBallsOnBoard(potentialCoordsOfCollision); ArrayList<LogicCoord> collisions = board.getCollisions(potentialCoordsOfCollision, currentPositionOfProjectile, thetaFromPointerInRadians); if (collisions.size() > 0){ result = board.getCollisionResult(collisions, thetaFromPointerInRadians, queueProjectile, currentPositionOfProjectile); if (result != null) { if (board.isBoardEmpty()) { setGamePaused(true); } int score = 0; int multiplier =0; if (result.containsKey("bubblesInCluster")) { ArrayList<Bubble> bubblesInCluster = (ArrayList) result.get("bubblesInCluster"); for (Bubble bubble : bubblesInCluster) { score += bubble.getBubbleScore(); multiplier++; } } if (result.containsKey("bubblesInClusterToDrop")) { ArrayList<Bubble> bubblesInClusterToDrop = (ArrayList) result.get("bubblesInClusterToDrop"); for (Bubble bubble : bubblesInClusterToDrop) { score += bubble.getBubbleScore(); multiplier++; } } incrementScore(score * multiplier); return result; } else { return null; } } currentRow++; currentPositionOfProjectile = board.getLogicCoordOfCollisionWithBottomOfLogicRow(thetaFromPointerInRadians, currentRow, currentPositionOfProjectile.convertToAspectLogicCoord(shooterOffset)); } currentPositionOfProjectile = board.getCoordOfCollisionWithEdge(thetaFromPointerInRadians, lastPositionOfProjectileConfirmedToFitInBoard); queueProjectile.add(currentPositionOfProjectile.convertToVisualCoord(board.getNumberOfRows(), board.getNumberOfColumns())); thetaFromPointerInRadians *= -1; } while (currentPositionOfProjectile.getY() < rows*2); queueProjectile.remove(queueProjectile.size()-1); LogicCoord collisionWithTop = board.getLogicCoordOfCollisionWithBottomOfLogicRow(thetaFromPointerInRadians*-1,rows,lastPositionOfProjectileConfirmedToFitInBoard.convertToAspectLogicCoord(shooterOffset)); LogicCoord snapPosition = board.getSnapPositionOf(collisionWithTop ,thetaFromPointerInRadians); board.setBubbleAt(snapPosition, currentBubble); Hashtable<Bubble, Integer> tree = board.hitResultTree(board.getBubbleAt(snapPosition)); ArrayList<Bubble> bubblesInCluster = board.filterHashtableToCluster(tree); if (bubblesInCluster.size() >= 3 || board.clusterContainsBubbleWithName(bubblesInCluster, "Rainbow") || board.clusterContainsBubbleWithName(bubblesInCluster, "Bomb") || board.clusterContainsBubbleWithName(bubblesInCluster, "More chances") || board.clusterContainsBubbleWithName(bubblesInCluster, "Color Blind") || board.clusterContainsBubbleWithName(bubblesInCluster, "Less Choice")) { board.removeClusterFromBoard(bubblesInCluster); } else bubblesInCluster = new ArrayList<>(); ArrayList<Bubble> bubblesUnderClusterToDrop = board.getBallsUnderClusterToDrop(bubblesInCluster); board.removeClusterFromBoard(bubblesUnderClusterToDrop); queueProjectile.add(board.getSnapPositionOf(board.getLogicCoordOfCollisionWithBottomOfLogicRow(thetaFromPointerInRadians * -1, rows, lastPositionOfProjectileConfirmedToFitInBoard.convertToAspectLogicCoord(shooterOffset)), thetaFromPointerInRadians).convertToVisualCoord(board.getNumberOfRows(), board.getNumberOfColumns())); result.put("projectile", queueProjectile); result.put("bubblesInCluster", bubblesInCluster); result.put("bubblesUnderCluster", bubblesUnderClusterToDrop); if (board.isBoardEmpty()) { setGamePaused(true); } return result; } private void incrementScore (int increment) { setScore(this.getScore()+increment); gameBoardPane.setScore(this.getScore()); } public int randomBubble(){ int length = typeBubbles.size(); Random rand = new Random(); int randomBubble = typeBubbles.get(rand.nextInt(length)); return randomBubble; } public void nextMove(){ typeBubbles = null; remainingBubbles--; Bubble[][] gameBoard = board.getBoard(); currentSeed = ""; for(int i = 0; i < gameBoard.length; i++){ for(int j = 0; j < gameBoard[i].length; j++){ if(gameBoard[i][j] != null){ if (!lesserChoiceCounter.containsKey(gameBoard[i][j].getBubbleName())) { currentSeed += gameBoard[i][j].getBubbleGameId(); } } } } typeBubbles = seed.analyseSeed(currentSeed); } public Bubble generateBubble(){ Bubble bubble = bubbleFactory.createBubble(randomBubble()); return bubble; } public void generateFirstBubbles(){ DataCoord positionCurrentBubble = new LogicCoord(0,-shooterOffset).convertToDataCoord(rows, columns); DataCoord positionNextBubble = new LogicCoord(-6,-shooterOffset).convertToDataCoord(rows, columns); currentBubble = generateBubble(); currentBubble.setDataCoord(positionCurrentBubble); nextBubble = generateBubble(); nextBubble.setDataCoord(positionNextBubble); } public void nextBubbleIsCurrentBubble(){ currentBubble = nextBubble; DataCoord positionCurrentBubble = new LogicCoord(0,-shooterOffset).convertToDataCoord(rows, columns); currentBubble.setDataCoord(positionCurrentBubble); nextBubble = generateBubble(); DataCoord positionNextBubble = new LogicCoord(-6,-shooterOffset).convertToDataCoord(rows, columns); nextBubble.setDataCoord(positionNextBubble); } public Bubble getCurrentBubble() { return currentBubble; } public Bubble getNextBubble() { return nextBubble; } public void setGamePaused(boolean gamePaused) { parent.setGamePaused(gamePaused); } public boolean getGamePaused(){ return parent.isGamePaused(); } public int getCurrentLevel(){ return currentLevel; } public void nextLevel(){ board.clearBoard(); currentLevel += 1; String levelSeed = bubbleDB.getLevelFromNumber(currentLevel); board.loadLevel(levelSeed); typeBubbles = seed.analyseSeed(levelSeed); board.clearBoard(); loadLevel(); gameBoardPane.setVisualBubbles(board.getBoard()); gameBoardPane.fillRowsWithBalls(); generateFirstBubbles(); gameBoardPane.showBubbles(); gameBoardPane.drawBubbles(); parent.setGamePaused(false); score = 0; } public void resumeGame(){ parent.setGamePaused(false); } public boolean getIsAnimationFinished(){ return isAnimationFinished; } public void setIsAnimationFinished(boolean isAnimationFinished){ this.isAnimationFinished = isAnimationFinished; } public void leftKeyPressed() { if (!parent.isGamePaused()) { gameBoardPane.rotate(20); } } public void leftRightKeyReleased() { if (!parent.isGamePaused()) { gameBoardPane.stopRotation(); } } private void reduceAllLesserChoiceCounts() { Set<String> treeKeys = lesserChoiceCounter.keySet(); Iterator<String> iterator = treeKeys.iterator(); String key; while (iterator.hasNext()) { key = iterator.next(); if (lesserChoiceCounter.get(key) != 0) { lesserChoiceCounter.put(key, lesserChoiceCounter.get(key)-1); } if (lesserChoiceCounter.get(key) == 0) { iterator.remove(); } } } public void upKeyReleased() { if (!parent.isGamePaused()) { if (0 < colorblindCounter ) { colorblindCounter--; } board.makeAllBallsGray(false); reduceAllLesserChoiceCounts(); double angle = gameBoardPane.getAngleInRadians(); Hashtable<String, Object> interactionBubbles = shoot(angle); if (interactionBubbles != null) { if (!((ArrayList) interactionBubbles.get("projectile")).isEmpty()) { gameBoardPane.bubbleProjectileAnimation(interactionBubbles); } } else { System.out.println("Game over"); } nextBubbleIsCurrentBubble(); nextMove(); gameBoardPane.showBubbles(); } } public void rightKeyPressed() { if (!parent.isGamePaused()) { gameBoardPane.rotate(160); } } public String getPlayerName() { return player.getPlayerName(); } public void setScore(int score) { this.score = score; } private void writeScore(){ int scoreFromDB = bubbleDB.checkIfPlayerHasLevelScore(player.getPlayerId(), currentLevel); if(scoreFromDB >= 0){ if(score > scoreFromDB){ bubbleDB.updateHighscore(player.getPlayerId(), currentLevel, score); } }else{ bubbleDB.writeScore(player.getPlayerId(), currentLevel, score); } } public void setLesserChoiceCounter(String bubbleName) { lesserChoiceCounter.put(bubbleName, 5); } public void setColorblindCounter(int count) { this.colorblindCounter = count; board.makeAllBallsGray(true); } public void incrementRemainingBubbles(int i) { this.remainingBubbles += 5; } public BubbleFactory getBubbleFactory() { return bubbleFactory; } public void backToMenu() { new MenuController(rootPane); // parent.removeEventHandlers(); gameBoardPane.removeAllComponents(); } }<file_sep>/src/Game/View/HighscoresPane.java package Game.View; import Game.Controller.HighscoresController; import Game.Database.HighscorePerLevel; import Game.Database.Player; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; import java.util.ArrayList; public class HighscoresPane extends Pane { private StackPane rootPane; private Pane pane = this; private HighscoresController parent; private TableView tvSP, tvMP; private String selectedItem; private TableColumn playerSP, scoreSP, playerMP, scoreMP; private Button btnBack; private ChoiceBox levelChoice; Label lblSP, lblMP; ObservableList<HighscorePerLevel> highscoreData; ObservableList<Player> mpData; Background background; public HighscoresPane(StackPane rootPane, HighscoresController parent){ this.rootPane = rootPane; this.parent = parent; initComponents(); background = new Background(rootPane, 700, 690); addComponents(); addEventHandlers(); }//Constructor: Creates a Pane and adds it to the StackPanel private void initComponents() { //Singeplayer pane.setMaxSize(330, 640); pane.setPrefSize(330, 640); lblSP = new Label("Singleplayer Highscores"); lblSP.setLayoutX(-150); lblSP.setLayoutY(13); lblSP.setId("labelHighScores"); Image backIcon = new Image("file:../../assets/images/buttons/back.png"); ImageView backIconView = new ImageView(backIcon); btnBack = new Button(); btnBack.setGraphic(backIconView); btnBack.setId("mainMenuButton"); btnBack.setPrefSize(80, 50); btnBack.setLayoutX(pane.getMaxWidth() / 2 - 35); btnBack.setLayoutY(pane.getMaxHeight() / 2 + 250); levelChoice = new ChoiceBox(); levelChoice.setId("selectBox"); levelChoice.setPrefSize(250, 50); levelChoice.setLayoutX(10 - levelChoice.getPrefWidth() / 2); levelChoice.setLayoutY(pane.getMaxHeight() / 2 - 250); ArrayList<String> levels; levels = parent.getLevels(); ObservableList<String> levelsObservableList = FXCollections.observableArrayList(levels); levelChoice.setItems(levelsObservableList); levelChoice.getSelectionModel().selectFirst(); selectedItem = levelChoice.getSelectionModel().getSelectedItem().toString(); tvSP = new TableView(); tvSP.setEditable(false); tvSP.setPrefSize(250, 400); tvSP.setLayoutX(10 - tvSP.getPrefWidth() / 2); tvSP.setLayoutY(pane.getMaxHeight() / 2 - 185); tvSP.setId("tableView"); tvSP.setPlaceholder(new Label("No highscores found for selected level.")); playerSP = new TableColumn("Player"); scoreSP = new TableColumn("Score"); loadLevelData(); tvSP.getColumns().addAll(playerSP, scoreSP); playerSP.setPrefWidth(tvSP.getPrefWidth() / 2 - 5 + 35); playerSP.setResizable(false); scoreSP.setPrefWidth(tvSP.getPrefWidth() / 2 - 5 - 35); scoreSP.setResizable(false); //Multiplayer lblMP = new Label("Mutliplayer Highscores"); lblMP.setLayoutX(pane.getPrefWidth() / 2 + 25); lblMP.setLayoutY(13); lblMP.setId("labelHighScores"); tvMP = new TableView(); tvMP.setEditable(false); tvMP.setPrefSize(250, 400); tvMP.setLayoutX(pane.getPrefWidth() - tvSP.getPrefWidth() / 2); tvMP.setLayoutY(pane.getMaxHeight() / 2 - 185); tvMP.setId("tableView"); tvMP.setPlaceholder(new Label("No players found with more than 0 wins.")); playerMP = new TableColumn("Player"); scoreMP = new TableColumn("Wins"); playerMP.setPrefWidth(tvSP.getPrefWidth() / 2 - 5 + 35); playerMP.setResizable(false); scoreMP.setPrefWidth(tvSP.getPrefWidth() / 2 - 5 - 35); scoreMP.setResizable(false); loadMPData(); tvMP.getColumns().addAll(playerMP, scoreMP); }//Initializes the objects that are going to be put on the pane private void addComponents() { pane.getChildren().addAll(btnBack, levelChoice, tvSP, lblSP, lblMP, tvMP); rootPane.getChildren().add(pane); }//Adds this pane to the StackPanel private void addEventHandlers() { btnBack.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { removeAllComponents(); parent.invokeMenuController(); } }); levelChoice.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { selectedItem = levelChoice.getSelectionModel().getSelectedItem().toString(); loadLevelData(); } }); }//Adds the event handlers for the button and the option box private void removeAllComponents(){ rootPane.getChildren().removeAll(pane, background.getBeige(), background.getWood()); }//Removes this panel from the StackPanel private void loadLevelData(){ highscoreData = parent.getLevelData(Integer.parseInt(selectedItem.substring(6))); playerSP.setCellValueFactory( new PropertyValueFactory<HighscorePerLevel, String>("playerName") ); scoreSP.setCellValueFactory( new PropertyValueFactory<HighscorePerLevel, Integer>("highscore") ); tvSP.setItems(highscoreData); }//Loads the data from the database private void loadMPData(){ mpData = parent.getPlayers(); playerMP.setCellValueFactory( new PropertyValueFactory<Player, String>("playerName") ); scoreMP.setCellValueFactory( new PropertyValueFactory<Player, Integer>("mpHighScoreCount") ); tvMP.setItems(mpData); } }<file_sep>/src/Game/Database/HighscorePerLevel.java package Game.Database; public class HighscorePerLevel { private int highscore; private String playerName; public HighscorePerLevel(int highscore, String playerName){ this.highscore = highscore; this.playerName = playerName; } public int getHighscore() { return highscore; } public void setHighscore(int highscore) { this.highscore = highscore; } public String getPlayerName() { return playerName; } public void setPlayerName(String playerName) { this.playerName = playerName; } } <file_sep>/src/Game/Database/Bubble.java package Game.Database; import Game.Logic.DataCoord; import Game.Logic.LogicCoord; import javafx.scene.image.Image; import javafx.scene.paint.ImagePattern; import javafx.scene.shape.Circle; import java.util.Comparator; public class Bubble extends Circle { private int bubbleGameId, bubbleScore, bubblePowerId; private String bubbleName, url; private DataCoord dataCoord; public Bubble(int bubbleGameId, String bubbleName, int bubbleScore, String url, int bubblePowerId, ImagePattern fill){ this.bubbleGameId = bubbleGameId; this.bubbleName = bubbleName; this.url = url; this.bubbleScore = bubbleScore; this.bubblePowerId = bubblePowerId; this.setFill(fill); } public int getBubbleScore() { return bubbleScore; } public void setBubbleScore(int bubbleScore) { this.bubbleScore = bubbleScore; } public int getBubblePowerId() { return bubblePowerId; } public void setBubblePowerId(int bubblePowerId) { this.bubblePowerId = bubblePowerId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getBubbleName() { return bubbleName; } public void setBubbleName(String bubbleName) { this.bubbleName = bubbleName; } public boolean invokedBy(Bubble currentBubble) { if (!getBubbleName().equals("fixed")) { if ( (getBubbleName().equals(currentBubble.getBubbleName()) || currentBubble.getBubbleName().equals("Rainbow"))) { return true; } } return false; } public DataCoord getDataCoord() { return dataCoord; } public void setDataCoord(DataCoord dataCoord) { this.dataCoord = dataCoord; } public int getBubbleGameId() { return bubbleGameId; } public void setBubbleGameId(int bubbleGameId) { this.bubbleGameId = bubbleGameId; } @Override public String toString() { if (getDataCoord() != null) { return getDataCoord().toString(); } else return "null"; } } <file_sep>/src/Game/Database/Player.java package Game.Database; public class Player { int playerId, mpHighScoreCount; String playerName, avatar; public Player(int playerId, String avatar, String playerName, int mpHighScoreCount){ this.playerId = playerId; this.avatar = avatar; this.playerName = playerName; this.mpHighScoreCount = mpHighScoreCount; } public int getPlayerId(){ return playerId; } public String getPlayerName() { return playerName; } public int getMpHighScoreCount(){ return mpHighScoreCount; } }<file_sep>/src/Game/Database/PowerBubble.java package Game.Database; import javafx.scene.paint.ImagePattern; public class PowerBubble extends Bubble{ private int bubblePowerId, isDroppable, isProjectile, timeConstraint, gameParameterId; private String activationType; public PowerBubble(Bubble bubble, int bubblePowerId, int isDroppable, int isProjectile, String activationType, int timeConstraint, int gameParameterId, ImagePattern fill){ super(bubble.getBubbleGameId(), bubble.getBubbleName(), bubble.getBubbleScore(), bubble.getUrl(), bubble.getBubblePowerId(), null); this.bubblePowerId = bubblePowerId; this.isDroppable = isDroppable; this.isProjectile = isProjectile; this.activationType = activationType; this.timeConstraint = timeConstraint; this.gameParameterId = gameParameterId; } @Override public int getBubblePowerId() { return bubblePowerId; } @Override public void setBubblePowerId(int bubblePowerId) { this.bubblePowerId = bubblePowerId; } public int getIsDroppable() { return isDroppable; } public void setIsDroppable(int isDroppable) { this.isDroppable = isDroppable; } public int getIsProjectile() { return isProjectile; } public void setIsProjectile(int isProjectile) { this.isProjectile = isProjectile; } public int getTimeConstraint() { return timeConstraint; } public void setTimeConstraint(int timeConstraint) { this.timeConstraint = timeConstraint; } public int getGameParameterId() { return gameParameterId; } public void setGameParameterId(int gameParameterId) { this.gameParameterId = gameParameterId; } public String getActivationType() { return activationType; } public void setActivationType(String activationType) { this.activationType = activationType; } }<file_sep>/src/Game/Controller/CreditsController.java package Game.Controller; import Game.View.CreditsPane; import javafx.scene.layout.StackPane; public class CreditsController { private StackPane rootPane; private int score; private String name; public CreditsController(StackPane rootPane){ this.rootPane = rootPane; invokeView(); } private void invokeView() { new CreditsPane(this, rootPane); } public void invokeMenuController() { new MenuController(rootPane); } }<file_sep>/src/Game/Logic/DataCoord.java package Game.Logic; import javafx.geometry.Point2D; public class DataCoord extends Point2D { private int score; public DataCoord(double x, double y){ super(x,y); } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public LogicCoord convertToLogicCoord(int rows, int columns) { int xOffset; int yOffset = 0; if (getY() %2 ==1) { xOffset = 1; }else{ xOffset =0; } double x =getX()*2 - (columns-1) + xOffset; double y = (rows-(getY()+1)) * 2 + 1 + yOffset; return new LogicCoord(x,y); } }
f184d52c0ad3081fc559b4fff215b423a491568f
[ "Markdown", "Java" ]
13
Java
jacobsyentl/PuzzleBobble
2e38b81de8f7f38d994b3bda1f749ed987ce6ee8
8517bd9e217f93f181ff3edfc0a40388f47393ba
refs/heads/master
<repo_name>santiagoesdras/keneth_esta_bien0.0<file_sep>/kenethhueco.js var kenethestabien=0; var pedirperdon=0; var prompt = require('prompt-sync')(); var laculpaesde = prompt("La culpa es de Esdras?"); if ((laculpaesde==="Si")||(laculpaesde==="si")) { console.log("Si la culpa es de Esdras"); console.log("<NAME> no quise ser hiriente"); } else if((laculpaesde==="No")||(laculpaesde==="no")) { console.log("La culpa no es de Esdras"); console.log("Keneth dejate de huecadas Esdras no te hizo nada"); } else { console.log("No sabemos de quien es la culpa"); } //saludos keneth hueco
49e1b56a090abdc98404b3868c19ba2cad3056c7
[ "JavaScript" ]
1
JavaScript
santiagoesdras/keneth_esta_bien0.0
e9f59cf092b85124d93b01bf9978e0cf18430504
59f1fbf89a4b8f1904527293587a04c8e02db010
refs/heads/master
<file_sep>""" Pygame P01.1 Description: Moving a player with Mouse (no clicking necessary) """ # Import and initialize the pygame library import pygame import sys import os import math # Tells OS where to open the window os.environ['SDL_VIDEO_WINDOW_POS'] = str(460) + "," + str(40) # helper function that processes commandline arguments into key-value pairs or a list of arguments from helper_module import mykwargs # returns the euclidian distance of two points in 2D space from helper_module import straightDistance # returns a dictionary of color names and their hex/rgb values from helper_module import load_colors # grab command line arguments _, argDict = mykwargs(sys.argv) # grab json info from colors.json and load into a dictionary colors = load_colors('colors.json') class Player(pygame.sprite.Sprite): """ A pygame sprite class visible on screen as an image A sprite in pygame is a moveable object on the screen The sprite created with this class in this program will be moveable with the mouse and will not exit the window boundaries. The mouse must be hovering over the window for the sprite to move. """ def __init__(self): pygame.sprite.Sprite.__init__(self) # load the sprite as an image self.image = pygame.image.load(argDict["image"]) # create a pygame rectable from the dimensions of the image self.rect = self.image.get_rect() # set the dimensions as member variables self.width = int(argDict["width"]) self.height = int(argDict["height"]) # set the position of the sprite on the window self.x = self.width / 2 self.y = self.height / 2 # record the previous position of the sprite self.old_loc = (self.x, self.y) # set how many pixels the sprite will move per frame (fps is set in the commandline) self.speed = 5 # position the sprite on the screen self.rect.center = (self.x, self.y) def Move(self, mouse_position): """ Move controls the position of the sprite by mouse movement """ # establish the desired position of the sprite self.target_location = mouse_position # calculate the position of the mouse self.MoveWithMouse() # position the sprite on the screen self.rect.center = (self.x, self.y) # if the new position of the sprite would put it outside the boundaries of the window, # revert to the previous position if self.rect.left <= 0 or self.rect.right >= self.width or self.rect.top <= 0 or self.rect.bottom >= self.height: # print("Too far!") self.rect.center = self.old_loc # print(f"current location at: {self.rect.center}") # print(f"current left at: {self.rect.left}") # print(f"old location at: {self.old_loc}") def MoveWithMouse(self): """ MoveWithMouse calculates the new position of the sprite based on the mouse's position """ # record the current, unchanged position of the sprite self.old_loc = self.rect.center x = self.target_location[0] y = self.target_location[1] # find the distance from sprite's current position and desired one dx = x - self.x dy = y - self.y # use the arctan function to find the angle from the horizontal to the desired position angle = math.atan2(dy, dx) # if the euclidian distance from the original sprite position to the desired is within 10 pixels # perform basic trig to move a multiple of `self.speed` towards the desired position if straightDistance(self.x, self.y, x, y) > 10: self.x += int(self.speed * math.cos(angle)) self.y += int(self.speed * math.sin(angle)) def main(): pygame.init() # sets the window title using title found in command line instruction pygame.display.set_caption(argDict["title"]) # Set up the drawing window screen = pygame.display.set_mode((int(argDict["width"]), int(argDict["height"]))) # for controlling frames per second clock = pygame.time.Clock() # construct the ball p1 = Player() # group for all sprites all_sprites = pygame.sprite.Group() # add sprites to the sprite group all_sprites.add(p1) # Run until the user asks to quit game loop running = True while running: # fill screen with white screen.fill(colors[argDict["color"]]['rgb']) # sets frames per second to what's found in commandline instruction clock.tick(int(argDict["fps"])) # Did the user click the window close button? for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # attempt to move the player if pygame.mouse.get_focused(): p1.Move(pygame.mouse.get_pos()) # draw the sprites to the screen all_sprites.draw(screen) # show screen pygame.display.flip() # Done! Time to quit. pygame.quit() if __name__=='__main__': main()<file_sep># A03 - Sample Tkinter Program ## <NAME> ## Assignment Description ### This program tests if Python is installed correctly by using the Tkinter library to create a tiny "Hello World" styled window. Also, the program must be executed through the command line ## Folder Structure | # | File | Assignment Description | | :---: | ----------- | ---------------------- | | 1 | [main.py](main.py) | main driver code that lauches Hello World window | ## Instructions 1. Ensure the latest version of Python is installed on your system. This code was originally run with Python 3.8.3 2. Check if Tkinter is install by typing `python -m tkinter` in a command prompt / terminal. If a little window appears with the Tkinter version info (along with a "Click me" and "Quit" button) you're good to go. If you're interested in more, check out the [tkinter page](https://docs.python.org/3/library/tkinter.html) in the Python documentation 3. Open a command prompt / terminal in the `A03` folder 4. Run `main.py` by typing `python ./main.py` on Windows and `python main.py` on Linux/Mac <file_sep># Assignments Folder | # | Folder Link | Assignment Description | | :---: | ----------- | ---------------------- | | 1 | [A03](A03) | Sample Tkinter program | | 2 | [A04](A04) | Tkinter program with commandline parameter handling | | 3 | [P01.1](P01.1) | Pygame app with a sprite moveable with the mouse | | 4 | [P01.2](P01.2) | Pygame app with a sprite moveable with the mouse, implemented scrolling | | 5 | [P01.3](P01.3) | Pygame app with a sprite moveable with the mouse, implemented animations | | 6 | [P01.4](P01.4) | Pygame app with a sprite moveable with the mouse, implemented animations, shootable enemies, and bullets | | 7 | [P02](P02) | Pygame platformer with a moveable character and three levels | <file_sep># A04 - Sample Tkinter Program w/ Input File ## <NAME> ## Assignment Description ### This program uses the Tkinter library to create a tiny "Introduction" window filled with simulated player info read in from a `.json` file. The input file is submitted as a command line parameter. ## Folder Structure | # | File | Assignment Description | | :---: | ----------- | ---------------------- | | 1 | [main.py](main.py) | main driver code that lauches Introduction window | | 2 | [player_info.json](player_info.json) | `json` file holding player information | | 3 | [output_window_player_info.png](output_window_player_info.png) | image of Tkinter window | ## Instructions 1. Ensure the latest version of Python is installed on your system. This code was originally run with Python 3.8.3 2. Check if Tkinter is install by typing `python -m tkinter` in a command prompt / terminal. If a little window appears with the Tkinter version info (along with a "Click me" and "Quit" button) you're good to go. If you're interested in more, check out the [tkinter page](https://docs.python.org/3/library/tkinter.html) in the Python documentation 3. Open a command prompt / terminal in the `A04` folder 4. Run `main.py` by typing `python ./main.py player_info.json` on Windows and `python main.py player_info.json` on Linux/Mac 5. Output should look something like this: ![output](https://github.com/Pirhomega/4443-2D-PyGame-Matamoros/blob/master/Assignments/A04/output_window_player_info.png?raw=true) <file_sep># P01.3 - CovidZAR.EIEIO ## <NAME> ## Assignment Description ### This program uses the pygame library to move a sprite (textured/colored circle) around a game world while staying centered in the window. The sprite is not allowed to travel off the world (represented by the background image), which is surrounded by white. When the sprite is not moving, the "idle" animation plays. When the sprite hits a boundary, it plays a "dying" animation ## Folder Structure | # | File | Assignment Description | | :---: | ----------- | ---------------------- | | 1 | [game_pt3.py](game_pt2.py) | main driver code that lauches Pygame application | | 2 | [helper_module.py](helper_module.py) | helper code written by Dr. Griffin | | 3 | [grab_colors.py](grab_colors.py) | mini program written by Corbin that prints all color options to the `color_list.txt` | | 4 | [color_list.txt](color_list.txt) | list of available window background colors | | 5 | [colors.json](colors.json) | `.json` file of names of colors and their RGB/Hex values | | 6 | [info.json](./playersprites/info.json) | `.json` file of each animations' file name, number of frames in each animation, and speed at which the animation should play | | 7 | [ball_48x48.png](ball_48x48.png) | image used to represent the player in the Pygame application | | 8 | [background.jpg](background.jpg) | image used to represent the world in which the player resides | ## Instructions 1. Ensure the latest version of Python is installed on your system. This code was originally run with Python 3.8.3 2. Follow the instructions on the [pygame wiki](https://www.pygame.org/wiki/GettingStarted) to get it installed. 3. Open a command prompt / terminal in the `P01.3` folder 4. Run `game_pt3.py` by typing `python game_pt3.py title= width= height= startx= starty= fps= player_image= color= background_image=`. Select for yourself the window title (`title`), dimensions in pixels (`width` and `height`), the starting location of your character (`startx` and `starty`), refresh rate (`fps`), your character's image (`player_image`), screen background color (`color`), and the background image (`background_image`). Select the color from [color_list.txt](color_list.txt). 5. To move your player, keep your mouse over the window and move it around (clicking won't do anything). If the mouse leaves the window, the player will stop moving. 6. Close the window to exit the game ## Example The following is an example of the Pygame app if run with this command: `python game_pt3.py title="Pygame Example" width=1280 height=720 startx=20 starty=20 fps=60 player_image="./ball_48x48.png" color=white background_image="./background.jpg"` ### Gif ![sprite movement video](https://media.giphy.com/media/XyOmBlux6Azs1J3rpu/giphy.gif) ### Screenshots There are no screenshots. Instead I created a gif above. <file_sep># P01.4 - CovidZAR.EIEIO ## <NAME> ## Assignment Description ### This program uses the pygame library to move a sprite (textured/colored circle) around a game world while staying centered in the window. The sprite is not allowed to travel off the world (represented by the background image), which is surrounded by white. When the sprite is not moving, the "idle" animation plays. When the sprite hits a boundary, it plays a "dying" animation. The player can also shoot projectiles at randomly dispersed mobs, causing them to explode if hit ## Folder Structure | # | File | Assignment Description | | :---: | ----------- | ---------------------- | | 1 | [game_pt4.py](game_pt2.py) | main driver code that lauches Pygame application | | 2 | [helper_module.py](helper_module.py) | helper code written by Dr. Griffin | | 3 | [grab_colors.py](grab_colors.py) | mini program written by Corbin that prints all color options to the `color_list.txt` | | 4 | [color_list.txt](color_list.txt) | list of available window background colors | | 5 | [colors.json](colors.json) | `.json` file of names of colors and their RGB/Hex values | | 6 | [info.json](./playersprites/info.json) | a `.json` file of each animations' file name, number of frames in each animation, and speed at which the animation should play | | 7 | [background.jpg](background.jpg) | image used to represent the world in which the player resides | | 8 | [playersprites](./playersprites) | file holding all animations for the player | | 9 | [mob](./mob) | file holding all animations for the enemies/mobs | | 10 | [snowball](./snowball) | file holding all animations for the projectiles the player can throw | | 11 | [sounds](./sounds) | file holding all sounds played in the game | ## Instructions 1. Ensure the latest version of Python is installed on your system. This code was originally run with Python 3.8.3 2. Follow the instructions on the [pygame wiki](https://www.pygame.org/wiki/GettingStarted) to get it installed. 3. Open a command prompt / terminal in the `P01.4` folder 4. Run `game_pt4.py` by typing `python game_pt4.py title= width= height= startx= starty= fps= player_image= color= background_image= enemy_count=`. Select for yourself the window title (`title`), dimensions in pixels (`width` and `height`), the starting location of your character (`startx` and `starty`), refresh rate (`fps`), your character's image (`player_image`), screen background color (`color`), the background image (`background_image`), and the number of enemies to spawn around the world (`enemy_count`). Select the color from [color_list.txt](color_list.txt). 5. To move your player, keep your mouse over the window and move it around (clicking won't do anything). If the mouse leaves the window, the player will stop moving. 6. To throw a snowball at an enemy, click the left mouse button in the direction of the enemy 7. Close the window to exit the game ## Example The following is an example of the Pygame app if run with this command: `python game_pt4.py title="Pygame Example" width=1280 height=720 startx=2 starty=2 fps=30 player_image="./playersprites/Idle (1).png" color=white background_image="./background.jpg" enemy_count=5` ### Video with sound [![Sprite Movement Video with Sound](https://img.youtube.com/vi/L64TXapkkA0/0.jpg)](https://www.youtube.com/watch?v=L64TXapkkA0) ### Screenshots There are no screenshots. Instead I created a gif above. <file_sep># python main.py title="Pygame Example" levels="./resources/levels" tile_width=32 tile_height=32 width=25 height=16 fps=30 player_images="./resources/player" map_images="./resources/map_gen" mob_images="./resources/mob" item_images="./resources/item" sounds="./resources/sounds" """ Pygame P01.4 Description: Moving a player with Mouse (no clicking necessary) in a large world. The camera will move along with the player. Player has three animations that play either while moving, staying still, or running into the world border. Player can shoot snowballs at surrounding snowmen enemies to kill them. Snowballs/Bullets face the correct direction when thrown and have an animation as they fly. Snowmen have an idling animation and have a death animation when hit with a snowball. """ # Import libraries import pygame import sys import random import os import math import time from PIL import Image # Tells OS where to place the window os.environ['SDL_VIDEO_WINDOW_POS'] = str(460) + "," + str(40) # helper function that processes commandline arguments into key-value pairs or a list of arguments from helper_module import mykwargs # returns a dictionary of color names and their hex/rgb values from helper_module import load_json # grab command line arguments using the helper function and put them into a dictionary _, ARGDICT = mykwargs(sys.argv) # constants TILE_WIDTH = int(ARGDICT['tile_width']) TILE_HEIGHT = int(ARGDICT['tile_height']) WINDOW_WIDTH_TILE = int(ARGDICT["width"]) WINDOW_HEIGHT_TILE = int(ARGDICT["height"]) WINDOW_WIDTH = WINDOW_WIDTH_TILE*TILE_WIDTH WINDOW_HEIGHT = WINDOW_HEIGHT_TILE*TILE_HEIGHT WINDOW_TITLE = ARGDICT["title"] GAME_FPS = int(ARGDICT["fps"]) # each set of sprite animation frames has an info file that contains the names of the frames, how many exist per set, # and a value for adjusting the rate each frame plays. Since each animation is stored in its own folder, we only need to know # how many frames there are and stick that value into the info file. We'll use a loop to iterate through each frame. player_animations = load_json(ARGDICT["player_images"]+"/info.json") mob_animations = load_json(ARGDICT["mob_images"]+"/info.json") level_info = load_json(ARGDICT["levels"]+"/info.json") class Level(pygame.sprite.Sprite): """ A class that loads a level """ def __init__(self, level): # open the level's background image background = Image.open(ARGDICT["map_images"]+"/background.png") # the level is stored in memory as a 2D array of tiles. The tile dimensions # are given as a command line argument self.level = [] # level objectives are stored here self.score_needed = level_info[level]["objectives"]["points"] self.enemy_needed = level_info[level]["objectives"]["enemies"] # enemies, items, and the player locations are indicated in each level's .txt # file and their positions are stored here. self.enemy_locs = [] self.item_locs = [] self.player_pos = () # this stored all text to be displayed in the level and was sorta hardcoded in... # I was in a rush... self.text_locs = [] # opens the level's .txt file to begin creating it with open(ARGDICT["levels"]+'/'+level+'.txt','r') as infile: row = 0 map_data = infile.read() map_data = map_data.split("\n") # for every line in the .txt file for line in map_data: col = 0 sub = [] # the .txt file is a bunch of two character pairs that represent a part of the level # Empty space is '..', enemies are '00', terrain is '01'/'02'/etc., etc. for i in range(0,len(line),2): section = line[i]+line[i+1] # if the pair represents anything besides empty space (i.e. '..') if not '.' in section: # if we read in an item if '14' in section: sub.append('..') section = '..' self.item_locs.append((col*TILE_WIDTH, (row*TILE_HEIGHT))) # if we read in an ememy elif '00' in section: sub.append('..') section = '..' self.enemy_locs.append((col*TILE_WIDTH, (row*TILE_HEIGHT)-TILE_HEIGHT)) # if we read in the player elif '--' in section: sub.append('..') self.player_pos = (col*TILE_WIDTH, (row*TILE_HEIGHT)-TILE_HEIGHT) # otherwise, we have read in terrain, so fill in the terrain by pasting it to # the background image else: sub.append(section) tile = Image.open(ARGDICT["map_images"]+'/'+section+".png").convert("RGBA") tile_top_left = (col*TILE_WIDTH, row*TILE_HEIGHT) background.paste(tile, box=tile_top_left, mask=tile) # we read in empty space / air, so just stick it in the array else: sub.append(section) col += 1 self.level.append(sub) row += 1 # save the background image with the new level tiles pasted on background.save("level"+level+".png", quality=95) # so now we have a 2D array with each two-character pair stored in each element. We will # use this array when we implement gravity and falling. pygame.sprite.Sprite.__init__(self) # load the sprite as an image self.image = pygame.image.load("level"+level+".png").convert() # create a pygame rectangle from the dimensions of the background image self.rect = self.image.get_rect() # place it at 0, 0 self.rect.topleft = (0, 0) # sprite_bottom is a tuple of tuples. It's a tuple of the sprite's bottom left and bottom right corners, which are tuples. # getFloor returns the nearest terrain element stored in the 2D level matrix that is directly under the player's sprite. # If the player is falling, the function will loop down from the left and right edges of the sprite # until it either reaches the bottom of the window or a solid block. def getFloor(self, sprite_bottom): # grabs the x-coord of the sprite's bottom left and right tuple sprite_left = sprite_bottom[0][0] # grabs the x-coord of the bottom left sprite_right = sprite_bottom[1][0] # grabs the x-coord of the bottom right sprite_row = sprite_bottom[0][1] # grabs the y-coord of the bottom left (could just as well have been the bottom right; they're the same) # returns the level matrix location the sprite's bottom left/right corner is in sprite_col_l = math.floor(sprite_left / TILE_WIDTH) sprite_col_r = math.floor(sprite_right / TILE_WIDTH) # the tile the sprite's bottom side sits in sprite_row = math.floor((sprite_bottom[0][1]-1) / TILE_HEIGHT) for tile in range(sprite_row,WINDOW_HEIGHT_TILE): if '.' not in self.level[tile][sprite_col_l] or '.' not in self.level[tile][sprite_col_r]: return tile # if the player has nothing under their feet, return the height of the window return WINDOW_HEIGHT_TILE class Enemy(pygame.sprite.Sprite): """ A pygame sprite class visible on screen as an image A sprite in pygame is a moveable object on the screen The sprite created with this class in this program will be unmovable, but will kill the player if they contact each other """ def __init__(self, enemy_loc): pygame.sprite.Sprite.__init__(self) # load the sprite as an image # There is one animation that will play in this game: Idle, located in the `./resources/mob` folder # Animations are loop-played, meaning, since each frame of every animation are numbered (e.g. `dead1.png`, `dead2.png`, etc.), # we can loop through them using the `<animation_name>_imagenum` variable. `<animation_name>_imagelimit` # keeps the program from trying to load an image that doesn't exist. (We don't want to open `8.png` if # there are only 7 frames in the 'dead' animation.) `<animation_name>_imagelimit` gets its value from the `info.json` # file in the `mob` folder. self.idle_imagenum = 1 # self.attack_imagenum = 1 self.idle_imagelimit = mob_animations["idle"]["count"] # self.attack_imagelimit = mob_animations["attack"]["count"] # this is how we will load any frame of an animation. (Here, we load the first `idle` frame) # For example, the first image that loads will be at "./mob/+idle+/+1+.png". I kept the plus signs in so you can see how each part # of the below instruction contributes. The plus's aren't actually in the string. self.image = pygame.image.load("./resources/mob/idle/"+str(self.idle_imagenum)+".png") # create a pygame rectangle from the dimensions of the image self.rect = self.image.get_rect() # set the position of the sprite on the window # but don't position the sprite just yet self.x, self.y = enemy_loc # place the sprite at the location determined above, record its actual position in world coordinates self.rect.topleft = self.actual_position = (self.x, self.y) # hit will stay true if the sprite has NOT been hit by a Bullet. False, otherwise. We'll use this # variable in the `update` member function self.hit = True # # adds the offset calculated in the camera class to the enemy's actual position in the world (not with respect to the game window) # def update(self, position): # # if the enemy has not been hit by a Bullet, play its 'idle' animation # if self.hit: # # We use the `max` function since there are no animation frames with a 0 in their name, # # and the mod function will return a 0 if self.<animation>_imagenum = self.<animation>_imagelimit # self.idle_imagenum = max(1, (self.idle_imagenum + 1) % self.idle_imagelimit) # self.image = pygame.image.load("./mob/"+self.idle_pictureset["name"]+'/'+self.idle_pictureset["name"]+str(self.idle_imagenum)+".png") # # if it has been hit # elif not self.hit: # self.dead_imagenum += 1 # # if the entire 'dead' animation has played, kill the enemy and remove it from view # if self.dead_imagenum == self.dead_imagelimit: # self.dead_imagenum = 1 # self.kill() # # if the animation hasn't finished, play the next frame # else: # self.image = pygame.image.load("./mob/"+self.dead_pictureset["name"]+'/'+self.dead_pictureset["name"]+str(self.dead_imagenum)+".png") class Player(pygame.sprite.Sprite): """ A pygame sprite class visible on screen as an image A sprite in pygame is a moveable object on the screen The sprite created with this class in this program will be moveable with the keyboard and will not exit the window boundaries. The mouse must be hovering over the window for the sprite to move. """ def __init__(self, player_loc): pygame.sprite.Sprite.__init__(self) # load the sprite as an image # There are three animations that will play in this game: Idle, Dead, and Walk. # Animations are loop-played, meaning, since each frame of every animation are numbered (e.g. `Dead (1).png`, `Dead (2).png`, etc.), # we can loop through them using the `<animation_name>_imagenum` variable. `<animation_name>_imagelimit` # keeps the program from trying to load an image that doesn't exist. (We don't want to open `Dead (17).png` if # there are only 16 frames in the Dead animation.) `<animation_name>_imagelimit` gets its value from the `info.json` # file in the `playersprites` folder. self.idle_imagenum = 1 self.dead_imagenum = 1 self.walk_imagenum = 1 # self.jump_imagenum = 1 self.idle_imagelimit = player_animations["idle"]["count"] self.dead_imagelimit = player_animations["dead"]["count"] self.walk_imagelimit = player_animations["walk"]["count"] # self.jump_imagelimit = player_animations["jump"]["count"] # this is how we will load any frame of an animation (here, we load the first frame indicated in the commandline parameters) self.image = pygame.image.load(ARGDICT["player_images"]+'/idle/'+str(self.idle_imagenum)+'.png') # create a pygame rectangle from the dimensions of the image self.rect = self.image.get_rect() # set the position of the sprite on the window in world coordinates self.x, self.y = player_loc # possible states the player can have are 'i' (idle), 'l' (walking left), and 'r' (walking right) self.state = 'i' # these states are true when the player is jumping, falling, or dying, respectively self.jumping = False self.falling = False self.dying = False # how high the player can jump self.vertical_speed = 7 self.old_vertical_speed = self.vertical_speed # how fast the player will fall self.gravity = 5 # the player's score self.score = 0 # place the sprite at the location determined above, record its actual position in world coordinates, # and lastly record that position as the last viable position it has been in (more on that in this class's # `update` member function) self.rect.topleft = self.old_loc = (self.x, self.y) def Move(self, floor_y): """ Move controls the position of the sprite """ self.old_loc = self.rect.topleft # if the player is moving to the right if self.state == 'r': # prevents the player from leaving the window from the right side if (self.rect.right + 4) <= WINDOW_WIDTH: self.x += 4 self.rect.topleft = (self.x, self.rect.topleft[1]) # if the player is moving left if self.state == 'l': # prevents the player from leaving the window from the left side if (self.rect.left - 4) >= 0: self.x -= 4 self.rect.topleft = (self.x, self.rect.topleft[1]) # if the player is not falling AND is jumping, make them jump if self.jumping and not self.falling: # calculate the number of pixels to move the player upwards energy = self.vertical_speed * self.vertical_speed # if the jump won't put us outside the window, move the player upwards if self.rect.topleft[1] - energy >= 0: self.rect.topleft = (self.x, self.rect.topleft[1] - energy) # decrease the jumping speed by one so the jump tapers off self.vertical_speed -= 1 # if the player has hit the top of the window OR the jump speed has reached zero # # switch them from a jumping state to a falling state if self.rect.topleft[1] < 0 or self.vertical_speed == 0: self.falling = True self.jumping = False # if the player is falling if self.falling: # prevent them from falling below the floor (which was determined with the getFloor function) if self.rect.bottom + self.gravity <= floor_y: self.rect.bottom += self.gravity # once the player has reached the floor, reset speed, else: self.vertical_speed = self.old_vertical_speed # stick the player on th ground self.rect.bottom = floor_y self.state = 'i' self.falling = False # this activates the falling state if the player has walked off an edge if (not self.jumping) and (self.rect.bottom < floor_y): self.falling = True # applies changes to the player sprite, such as animation and position def update(self): # if the player isn't moving, play the idle animation if self.rect.topleft == self.old_loc and not self.dying: self.idle_imagenum = max(1, (self.idle_imagenum + 1) % self.idle_imagelimit) self.image = pygame.image.load(ARGDICT["player_images"]+'/idle/'+str(self.idle_imagenum)+'.png') # If the player isn't dying, play the walking right animation elif self.state == 'r' and not self.dying: self.walk_imagenum = max(1, (self.walk_imagenum + 1) % self.walk_imagelimit) self.image = pygame.image.load(ARGDICT["player_images"]+'/walk/'+str(self.walk_imagenum)+'.png') self.state = 'i' # if the player isn't dying, play the walking left animation (we flip the image of the original frame here) elif self.state == 'l' and not self.dying: self.walk_imagenum = max(1, (self.walk_imagenum + 1) % self.walk_imagelimit) image_unrot = pygame.image.load(ARGDICT["player_images"]+'/walk/'+str(self.walk_imagenum)+'.png') self.image = pygame.transform.flip(image_unrot, True, False) self.state = 'i' # code to play the jumping animation (not done yet) elif self.jumping: pass # if the player's dying state is true, play the dying animation. elif self.dying: if self.dead_imagenum < self.dead_imagelimit: self.dead_imagenum = self.dead_imagenum + 1 % self.dead_imagelimit self.image = pygame.image.load(ARGDICT["player_images"]+'/dead/'+str(self.dead_imagenum)+'.png') # After playing the entire animation, kill the sprite else: self.dying = False self.kill() class Item(pygame.sprite.Sprite): """ A pygame sprite class visible on screen as an image A sprite in pygame is a moveable object on the screen This sprite will act as a collectible for the player """ def __init__(self,item_pos): pygame.sprite.Sprite.__init__(self) # there's only one sprite image for the item. Load it here. self.image = pygame.image.load(ARGDICT["item_images"]+'/1.png') # create a pygame rectangle from the dimensions of the image self.rect = self.image.get_rect() # set the position of the sprite on the window # but don't position the sprite just yet self.x, self.y = item_pos # place the sprite at the location determined above, record its actual position in world coordinates self.rect.topleft = (self.x, self.y) # hit will stay false if the sprite has NOT been touched by the player. False, otherwise. We'll use this # variable in the `update` member function self.hit = False def update(self): # if the item was contacted by the player, kill it if self.hit: self.kill() class LevelInfoHolder(): ''' This class will hold all the session information for each level ''' def __init__(self, level_type): # set up the background music unless the level is the splash screen if level_type != '6': pygame.mixer.init(buffer=64) self.background_music = pygame.mixer.Sound(ARGDICT["sounds"]+'/'+level_type+'.ogg') # the sound was really finicky with volume, so these if/else statements are custom # just to fix that (I think). Did it? Nope... if level_type == '2': self.background_music.set_volume(0.01) else: self.background_music.set_volume(0.1) self.background_music.play() # create sprite groups for the player, mobs, and items self.main_sprites = pygame.sprite.Group() self.item_sprites = pygame.sprite.Group() self.mob_sprites = pygame.sprite.Group() self.level_type = level_type # generate the level self.level_world = Level(self.level_type) # create the player sprite and place them in the level self.player = Player(self.level_world.player_pos) # place the enemies about the level for loc in self.level_world.enemy_locs: self.mob_sprites.add(Enemy(loc)) # place the item about the level for loc in self.level_world.item_locs: self.item_sprites.add(Item(loc)) # stick the level and player into the main_sprite's group self.main_sprites.add(self.level_world) self.main_sprites.add(self.player) # if the level is true, it's a splash screen and will only appear for a little bit self.temporal = level_info[level_type]["stipulations"]['life'] # store the next level after this one is passed self.next_level = level_info[level_type]["next_level"] def main(): pygame.init() # initialize the mixer and load the sounds effects pygame.mixer.init(buffer=64) snowball_hit = pygame.mixer.Sound(ARGDICT["sounds"]+"/hit.ogg") santa_death = pygame.mixer.Sound(ARGDICT["sounds"]+"/death.ogg") santa_death.set_volume(0.1) snowball_hit.set_volume(0.1) # sets the window title using title found in command line instruction pygame.display.set_caption(WINDOW_TITLE) # Set up the drawing window screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) # for controlling frames per second clock = pygame.time.Clock() # the level the player is in currently current_level = LevelInfoHolder("6") # Run until the user asks to quit game loop running = True while running: # sets frames per second to what's found in commandline instruction clock.tick(GAME_FPS) # grab the nearest floor the player could stand on. If no floor is below, return the window height current_floor = current_level.level_world.getFloor((current_level.player.rect.bottomleft,current_level.player.rect.bottomright)) # convert the floor from number of tiles to pixels floor_y = current_floor*TILE_HEIGHT # Did the user click the window close button? for event in pygame.event.get(): if event.type == pygame.QUIT: running = False key_depressed = pygame.key.get_pressed() # set the state to move the player right if key_depressed[pygame.K_d]: current_level.player.state = 'r' # set the state to move the player left if key_depressed[pygame.K_a]: current_level.player.state = 'l' # set the state to make player jump if key_depressed[pygame.K_SPACE]: current_level.player.jumping = True # actually move the player current_level.player.Move(floor_y) # loop through all item and mob sprites and check for collisions between items/mob and the player for item in current_level.item_sprites: # if the player hits an item if item.rect.colliderect(current_level.player.rect): # play the sound snowball_hit.play() item.hit = True current_level.player.score += 1 for mob in current_level.mob_sprites: if mob.rect.colliderect(current_level.player.rect): current_level.background_music.stop() santa_death.play() current_level.player.dying = True # loop through all sprites in all groups and apply the camera offset to them for sprite in current_level.main_sprites: sprite.update() for sprite in current_level.item_sprites: sprite.update() # # draw the sprites to the screen current_level.main_sprites.draw(screen) current_level.item_sprites.draw(screen) current_level.mob_sprites.draw(screen) # show screen pygame.display.flip() # if the gamer has gotten enough canes, move them to the next level if current_level.player.score >= current_level.level_world.score_needed: current_level.background_music.stop() current_level = LevelInfoHolder(current_level.next_level) if current_level.temporal: current_level = LevelInfoHolder(current_level.next_level) pygame.time.wait(2000) # Done! Time to quit. pygame.quit() if __name__=='__main__': main() <file_sep># P02 - Sleigher ## <NAME> ## Assignment Description ### This program uses the pygame library to move a sprite about one of three levels. Levels are generated based on a text file. Each level has a number of enemies that must be killed and items you must collect before you can progress to the next level. If the player touches an enemy, they die. If they pass all three levels, they win. The game has a starting screen, splash (loading) screen, and a gameover screen. ## Folder Structure | # | File | Assignment Description | | :---: | ----------- | ---------------------- | | 1 | [main.py](main.py) | main driver code that lauches Pygame application | | 2 | [helper_module.py](helper_module.py) | helper code written by Dr. Griffin | | 3 | [resources](./resources) | Folder containing game assets | | 4 | info.json | a `.json` file found throughout the mob and player asset folders (in [resources](./resources)) of each animations' file name, number of frames in each animation, and speed at which the animation should play | | 5 | [info.json](./resources/levels/info.json) | contains the objectives to complete each level, the level that follows, and whether that level is a splash screen or not (life = True if level is a splash screen) | | 6 | [helper_scripts](./helper_scripts) | Contains scripts I wrote to rename files and resize images in a folder | ## Instructions 1. Ensure the latest version of Python is installed on your system. This code was originally run with Python 3.8.3 2. Follow the instructions on the [pygame wiki](https://www.pygame.org/wiki/GettingStarted) to get it installed. 3. Open a command prompt / terminal in the `P02` folder 4. Run `main.py` by typing `python main.py title= levels= tile_width= tile_height= width= height= fps= player_images= map_images= mob_images= item_images= sounds=`. Select for yourself the window title (`title`), the location of the level text files (`levels`), the width and height of the tiles used to create the level (`tile_width` and `tile_height`), window width and height (`width` and `height`), refresh rate (`fps`), your character's image folder (`player_images`), the tile images folder (`map_images`), the mob image folder (`mob_images`), the item images folder (`item_images`), and sounds folder (`sounds`). 5. To move your player, use 'd' to move right, 'a' to move left, and SPACE to jump. Use these mechanics to pick up items while avoiding the enemies strewn about. Complete all levels to win the game. 7. Close the window to exit the game ## Example Here is a example command you can run: `python main.py title="Sleigher" levels="./resources/levels" tile_width=32 tile_height=32 width=25 height=16 fps=30 player_images="./resources/player" map_images="./resources/map_gen" mob_images="./resources/mob" item_images="./resources/item" sounds="./resources/sounds"` <file_sep># 4443-2D-PyGame-Matamoros ## Repository owner: <NAME> ## Owner email: <EMAIL> ## Owner picture ![Github 5373 pfp](https://i.imgur.com/b9zkdym.png) ## Slack and Discord avatar ![Corbin M avatar](https://i.imgur.com/BOzk6Pg.png) Repository for the Platform-based 2D Games in Python class with Dr. Terry Griffin at MSU Texas. ## Repository Structure ```txt /4443-2D-PyGame-Matamoros ├── README.md ├── Assignments ├────── A03 ├────── A04 ├────── P01.1 ├────── P01.2 ├────── P01.3 ├────── P01.4 ├────── P02 ``` <file_sep>import tkinter as tk import sys import json # GUI window is a subclass of the basic tkinter Frame object class HelloWorldFrame(tk.Frame): def __init__(self, master, content): # used to place labels in the window label_row = 0 label_col = 0 # Call superclass constructor tk.Frame.__init__(self, master) # Place frame into main window self.grid() # loops through every key in 'content' dictionary for key in content: # print(key, content[key]) # print dictionary key to window label_key = tk.Label(self, text=f"{key}") label_key.grid(row=label_row, column=label_col, sticky='W') # print colon to window label_col = 1 label_colon = tk.Label(self, text=f":") label_colon.grid(row=label_row, column=label_col, sticky='W') # print value to window label_col = 2 value_string = "" # if the value is a list of items, create a string of all items in list if isinstance(content[key], list): separator = ", " value_string = separator.join(content[key]) else: value_string = content[key] label_value = tk.Label(self, text=f"{value_string}") label_value.grid(row=label_row, column=label_col, sticky='W') # adjust label placement variables for next set of key-values label_row += 1 label_col = 0 # Spawn window if __name__ == "__main__": # extract commandline param that has json file name, open the file, # and dump the json object into a dictionary player_info = json.load(open(sys.argv[1], 'r')) # Create main window object ROOT = tk.Tk() # Set title of window ROOT.title("Introduction") # Instantiate HelloWorldFrame object WELCOME_FRAME = HelloWorldFrame(ROOT, player_info) # Start GUI WELCOME_FRAME.mainloop() <file_sep># P01.2 - CovidZAR.EIEIO ## <NAME> ## Assignment Description ### This program uses the pygame library to move a sprite (textured/colored circle) around a game world while staying centered in the window. The sprite is not allowed to travel off the world (represented by the background image), which is surrounded by white ## Folder Structure | # | File | Assignment Description | | :---: | ----------- | ---------------------- | | 1 | [game_pt2.py](game_pt2.py) | main driver code that lauches Pygame application | | 2 | [helper_module.py](helper_module.py) | helper code written by Dr. Griffin | | 3 | [color_list.txt](color_list.txt) | list of available window background colors | | 4 | [grab_colors.py](grab_colors.py) | mini program written by Corbin that prints all color options to the `color_list.txt` | | 5 | [colors.json](colors.json) | `.json` file of names of colors and their RGB/Hex values | | 6 | [ball_48x48.png](ball_48x48.png) | image used to represent the player in the Pygame application | | 7 | [background.jpg](background.jpg) | image used to represent the world in which the player resides | | 8 | [screenshot1.png](screenshot1.png) | image showing player on left side of screen | | 9 | [screenshot2.png](screenshot2.png) | image showing player on right side of screen | | 10 | [screenshot3.png](screenshot3.png) | image showing player at bottom of screen | | 11 | [screenshot4.png](screenshot3.png) | image showing player at top left corner of screen | ## Instructions 1. Ensure the latest version of Python is installed on your system. This code was originally run with Python 3.8.3 2. Follow the instructions on the [pygame wiki](https://www.pygame.org/wiki/GettingStarted) to get it installed. 3. Open a command prompt / terminal in the `P01.2` folder 4. Run `game_pt2.py` by typing `python game_pt2.py title= width= height= startx= starty= fps= player_image= color= background_image=`. Select for yourself the window title (`title`), dimensions in pixels (`width` and `height`), the starting location of your character (`startx` and `starty`), refresh rate (`fps`), your character's image (`player_image`), screen background color (`color`), and the background image (`background_image`). Select the color from [color_list.txt](color_list.txt). 5. To move your player, keep your mouse over the window and move it around (clicking won't do anything). If the mouse leaves the window, the player will stop moving. 6. Close the window to exit the game ## Example The following is an example of the Pygame app if run with this command: `python game_pt2.py title="Pygame Example" width=1280 height=720 startx=320 starty=240 fps=60 player_image="./ball_48x48.png" color=black background_image="./background.jpg"` ### Gif ![sprite movement video](https://media.giphy.com/media/Y0VzvUn2FMrFGHDf1b/giphy.gif) ### Screenshot 1 `python game_pt2.py title="Pygame Example" width=640 height=480 startx=320 starty=240 fps=60 player_image="./ball_48x48.png" color=black background_image="./background.jpg"` <img src="screenshot1.png" width="300"> ### Screenshot 2 `python game_pt2.py title="Pygame Example" width=1000 height=1000 startx=320 starty=240 fps=60 player_image="./ball_48x48.png" color=black background_image="./background.jpg"` <img src="screenshot2.png" width="300"> ### Screenshot 3 `python game_pt2.py title="Pygame Example" width=1280 height=720 startx=320 starty=240 fps=60 player_image="./ball_48x48.png" color=black background_image="./background.jpg"` <img src="screenshot3.png" width="300"> ### Screenshot 4 `python game_pt2.py title="Pygame Example" width=1280 height=720 startx=320 starty=240 fps=60 player_image="./ball_48x48.png" color=black background_image="./background.jpg"` <img src="screenshot4.png" width="300"><file_sep>from helper_module import load_colors colors = load_colors('colors.json') with open("output.txt", 'w') as output: for color in colors: output.write(color) output.write('\n') <file_sep># stolen from https://www.tutorialspoint.com/rename-multiple-files-using-python#:~:text=rename()%20method%20is%20used,part%20of%20the%20os%20module. # renames all files in a folder import os # Function to rename multiple files def main(): i = 0 # path="C:/Users/TP/Desktop/sample/Travel/west bengal/bishnupur/" for i in range(1,8): my_source = "./" + "idle" + str(i) + ".png" my_dest = "./" + str(i) + ".png" # rename() function will # rename all the files os.rename(my_source, my_dest) i += 1 # Driver Code if __name__ == '__main__': # Calling main() function main()<file_sep># python game_pt3.py title="Pygame Example" width=1280 height=720 startx=20 starty=20 fps=60 player_image="./ball_48x48.png" color=black background_image="./background.jpg" """ Pygame P01.3 Description: Moving a player with Mouse (no clicking necessary) in a large world. The camera will move along with the player. Player has three animations that play either while moving, staying still, or running into the world border. """ # Import and initialize the pygame library import pygame import sys import os import math # Tells OS where to open the window os.environ['SDL_VIDEO_WINDOW_POS'] = str(460) + "," + str(40) # helper function that processes commandline arguments into key-value pairs or a list of arguments from helper_module import mykwargs # returns the euclidian distance of two points in 2D space from helper_module import straightDistance # returns a dictionary of color names and their hex/rgb values from helper_module import load_json # grab command line arguments _, argDict = mykwargs(sys.argv) # constants WINDOW_WIDTH = int(argDict["width"]) WINDOW_HEIGHT = int(argDict["height"]) HALF_WINDOW_WIDTH = int(WINDOW_WIDTH / 2) HALF_WINDOW_HEIGHT = int(WINDOW_HEIGHT / 2) WINDOW_TITLE = argDict["title"] GAME_FPS = int(argDict["fps"]) # grab json info from colors.json and load into a dictionary colors = load_json('colors.json') player_animations = load_json('./playersprites/info.json') class Camera(): """ Used to create an offset in pixels, that when added to all sprites in the game, creates a scrolling effect, keeping the targeted sprite in the center of the window """ def __init__(self): self.camera_offset = (0,0) # moves the camera to focus in on 'target' def update(self, player_target): # grabs the left and top points of the targeted sprite l, t, _, _ = player_target.rect # l = left, t = top # adjusts the camera position based on targeted sprite # subtracting half of the window's width and height gets the distance from the sprite's # current location in the world to the window's center. self.camera_offset = (HALF_WINDOW_WIDTH-l, HALF_WINDOW_HEIGHT-t) # returns the offset from the update() call to all sprites in the game, including the player. # The actual addition doesn't happen in this function, though. It's performed in each sprite's update() class member def apply(self): return self.camera_offset class Background(pygame.sprite.Sprite): """ A pygame sprite class visible on screen as an image A sprite in pygame is a moveable object on the screen The sprite created with this class in this program will be static, acting as the background of the game. """ def __init__(self): pygame.sprite.Sprite.__init__(self) # load the sprite as an image self.image = pygame.image.load(argDict["background_image"]).convert() # create a pygame rectangle from the dimensions of the background image self.rect = self.image.get_rect() # place it at 0, 0 self.rect.topleft = (0, 0) # sets the position of the background with respect to the offset generated in the camera class and passed in as an argument # No addition is performed here because the background image was initially placed at 0, 0 and never moves (like the player does) def update(self, position): self.rect.topleft = (position[0], position[1]) class Player(pygame.sprite.Sprite): """ A pygame sprite class visible on screen as an image A sprite in pygame is a moveable object on the screen The sprite created with this class in this program will be moveable with the mouse and will not exit the window boundaries. The mouse must be hovering over the window for the sprite to move. """ def __init__(self): pygame.sprite.Sprite.__init__(self) # the current set of sprite images to use self.idle_pictureset = player_animations["Idle"] self.dead_pictureset = player_animations["Dead"] self.walk_pictureset = player_animations["Walk"] # load the sprite as an image # There are three animations that will play in this game: Idle, Dead, and Walk. # Animations are loop-played, meaning, since each frame of every animation are numbered (e.g. `Dead (1).png`, `Dead (2).png`, etc.), # we can loop through them using the `<animation_name>_imagenum` variable. `<animation_name>_imagelimit` # keeps the program from trying to load an image that doesn't exist. (We don't want to open `Dead (17).png` if # there are only 16 frames in the Dead animation.) `<animation_name>_imagelimit` gets its value from the `info.json` # file in the `playersprites` folder. self.idle_imagenum = 1 self.dead_imagenum = 1 self.walk_imagenum = 1 self.idle_imagelimit = self.idle_pictureset["count"] self.dead_imagelimit = self.dead_pictureset["count"] self.walk_imagelimit = self.walk_pictureset["count"] # self.idle_imageshowrate = self.idle_pictureset["fps"] # self.dead_imageshowrate = self.dead_pictureset["fps"] # self.walk_imageshowrate = self.walk_pictureset["fps"] # this is how we will load any frame of an animation (here, we load the first `Idle` frame) self.image = pygame.image.load("./playersprites/"+self.idle_pictureset["name"]+str(self.idle_imagenum)+").png") # create a pygame rectangle from the dimensions of the image self.rect = self.image.get_rect() # set the position of the sprite on the window self.x = int(argDict["startx"]) self.y = int(argDict["starty"]) # record the previous position of the sprite and position the sprite on the screen self.rect.topleft = self.actual_position = self.old_loc = (self.x, self.y) # set the distance from the mouse pointer to the sprite's topleft corner and # set how many pixels the sprite will move per frame (fps is set in the commandline) self.distance = 0 self.speed = 5 # location to which the mouse points self.target_location = (0,0) def Move(self, mouse_position): """ Move controls the position of the sprite by mouse movement """ # establish the desired position of the sprite # is equal to the mouse's distance from the center of the window plus the actual position of the player self.target_location = (mouse_position[0]-HALF_WINDOW_WIDTH+self.actual_position[0], mouse_position[1]-HALF_WINDOW_HEIGHT+self.actual_position[1]) # calculate the position of the mouse self.MoveWithMouse() # position the sprite on the screen # A distinction has to be made between the sprite's position in the game window (self.rect.topleft) and in the game world (self.actual_position) # The sprite's game window position is what the user sees, but for that positioning to be calculated correctly, the sprite's # actual position must be remembered. self.rect.topleft = self.actual_position = (self.x, self.y) def MoveWithMouse(self): """ MoveWithMouse calculates the new position of the sprite based on the mouse's position """ # record the current, unchanged position of the sprite self.old_loc = self.rect.topleft # grabs the x and y coordinate of the mouse's position on the screen x = self.target_location[0] y = self.target_location[1] # find the distance from sprite's current position and desired one dx = x - self.x dy = y - self.y # use the arctan function to find the angle from the horizontal to the desired position angle = math.atan2(dy, dx) # if the euclidian distance from the original sprite position to the desired is within 10 pixels # perform basic trig to move a multiple of `self.speed` towards the desired position self.distance = straightDistance(self.x, self.y, x, y) self.x += int(min(5, self.distance/10) * math.cos(angle)) self.y += int(min(5, self.distance/10) * math.sin(angle)) # adds the offset calculated in the camera class to its actual position in the world (not with respect to the game window) def update(self, position): # If the distance from the mouse to the player is less than 10, loop-play the "Idle" animation. if self.distance < 10: # We use the `max` function since there are no images with a 0 in their name, # and the mod function will return a 0 if self.<animation>_imagenum = self.<animation>_imagelimit self.idle_imagenum = max(1, (self.idle_imagenum + 1) % self.idle_imagelimit) self.image = pygame.image.load("./playersprites/"+self.idle_pictureset["name"]+str(self.idle_imagenum)+").png") # otherwise, loop-play the "Walk" animation elif self.distance >= 10: self.walk_imagenum = max(1, (self.walk_imagenum + 1) % self.walk_imagelimit) self.image = pygame.image.load("./playersprites/"+self.walk_pictureset["name"]+str(self.walk_imagenum)+").png") # if the new position of the sprite would put it outside the boundaries of the window, # revert to the previous position # Also, load the "Dead" animation frames when the player hits a wall if self.rect.left <= 0 or self.rect.right >= 1920 or self.rect.top <= 0 or self.rect.bottom >= 1080: self.dead_imagenum = max(1, (self.dead_imagenum + 1) % self.dead_imagelimit) self.image = pygame.image.load("./playersprites/"+self.dead_pictureset["name"]+str(self.dead_imagenum)+").png") self.actual_position = self.old_loc # add the camera offset to the player sprite's actual position in the game world, "moving" them to the center of the window self.rect.topleft = (self.actual_position[0]+position[0], self.actual_position[1]+position[1]) def main(): pygame.init() # sets the window title using title found in command line instruction pygame.display.set_caption(WINDOW_TITLE) # Set up the drawing window screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) # for controlling frames per second clock = pygame.time.Clock() # construct the ball p1 = Player() # construct the background image bkgr = Background() # construct the camera (image dimensions are hardcoded for now) camera = Camera() # group for all sprites that are not the player all_sprites = pygame.sprite.Group() # add sprites to the sprite group # The order we add these to the group is the order they are drawn to the screen, # so we add the background first to keep the player from being covered all_sprites.add(bkgr) all_sprites.add(p1) # Run until the user asks to quit game loop running = True while running: # fill screen with color from commandline screen.fill(colors[argDict["color"]]['rgb']) # sets frames per second to what's found in commandline instruction clock.tick(GAME_FPS) # Did the user click the window close button? for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # attempt to move the player by sending the positioning of the mouse if pygame.mouse.get_focused(): p1.Move(pygame.mouse.get_pos()) # focuses in on the player so that it is always centered in the game window camera.update(p1) # loop through all sprites in the group and apply the camera offset to them for sprite in all_sprites: sprite.update(camera.apply()) # draw the sprites to the screen all_sprites.draw(screen) # show screen pygame.display.flip() # Done! Time to quit. pygame.quit() if __name__=='__main__': main() <file_sep># python game_pt4.py title="Pygame Example" width=1280 height=720 startx=20 starty=20 fps=30 player_image="./playersprites/Idle (1).png" color=white background_image="./background.jpg" enemy_count=50 """ Pygame P01.4 Description: Moving a player with Mouse (no clicking necessary) in a large world. The camera will move along with the player. Player has three animations that play either while moving, staying still, or running into the world border. Player can shoot snowballs at surrounding snowmen enemies to kill them. Snowballs/Bullets face the correct direction when thrown and have an animation as they fly. Snowmen have an idling animation and have a death animation when hit with a snowball. """ # Import libraries import pygame import sys import random import os import math import time # Tells OS where to place the window os.environ['SDL_VIDEO_WINDOW_POS'] = str(460) + "," + str(40) # helper function that processes commandline arguments into key-value pairs or a list of arguments from helper_module import mykwargs # returns the euclidian distance of two points in 2D space from helper_module import straightDistance # returns a dictionary of color names and their hex/rgb values from helper_module import load_json # grab command line arguments using the helper function and put them into a dictionary _, argDict = mykwargs(sys.argv) # constants WINDOW_WIDTH = int(argDict["width"]) WINDOW_HEIGHT = int(argDict["height"]) HALF_WINDOW_WIDTH = int(WINDOW_WIDTH / 2) HALF_WINDOW_HEIGHT = int(WINDOW_HEIGHT / 2) WINDOW_TITLE = argDict["title"] GAME_FPS = int(argDict["fps"]) # grab json info from colors.json and load into a dictionary colors = load_json('colors.json') # each set of sprite animation frames has an info file that contains the names of the frames, how many exist per set, # and a value for adjusting the rate each frame plays. For example, if you check the `info.json` file in the `playersprites` folder # the player's Idle animation frames all have "Idle (" as part of their name (that's why the 'name' field is "Idle (" ), # and there are 16 frames in the animation. The `fps` parameter has yet to be implemented, but that value just means the next frame # will play every 30 iterations of the game's main event loop player_animations = load_json('./playersprites/info.json') mob_animations = load_json('./mob/info.json') bullet_animations = load_json('./snowball/info.json') class Camera(): """ Used to create an offset in pixels, that when added to all sprites in the game, creates a scrolling effect, keeping the targeted sprite in the center of the window. Users can pass in whatever sprite they want centered on when they call the `update` function. The `apply` function must then be called on every sprite (including the one you called `update` with) to apply the offset. """ def __init__(self): self.camera_offset = (0,0) # moves the camera to focus in on 'target' def update(self, player_target): # grabs the left and top points of the targeted sprite l, t = player_target.actual_position # l = left, t = top # adjusts the camera position based on targeted sprite # subtracting half of the window's width and height gets the distance from the sprite's # current location in the world to the window's center. self.camera_offset = (HALF_WINDOW_WIDTH-l, HALF_WINDOW_HEIGHT-t) # returns the offset from the update() call to all sprites in the game, including the player. # The actual addition doesn't happen in this function, though. It's performed in each sprite's update() class member def apply(self): return self.camera_offset class Background(pygame.sprite.Sprite): """ A pygame sprite class visible on screen as an image A sprite in pygame is a moveable object on the screen The sprite created with this class in this program will be static, acting as the background of the game. """ def __init__(self): pygame.sprite.Sprite.__init__(self) # load the sprite as an image self.image = pygame.image.load(argDict["background_image"]).convert() # create a pygame rectangle from the dimensions of the background image self.rect = self.image.get_rect() # place it at 0, 0 self.rect.topleft = (0, 0) # The update method for sprites doesn't do anything unless defined by the programmer. # Sets the position of the background with respect to the offset generated in the camera class and passed in as an argument # No addition is performed here because the background image was initially placed at 0, 0 and never moves def update(self, position): self.rect.topleft = (position[0], position[1]) class Enemy(pygame.sprite.Sprite): """ A pygame sprite class visible on screen as an image A sprite in pygame is a moveable object on the screen The sprite created with this class in this program will be unmovable, acting as a stationary target for the player character to shoot at. The enemy dies when hit by a Bullet """ def __init__(self): pygame.sprite.Sprite.__init__(self) # the current set of sprite images to use self.dead_pictureset = mob_animations["Dead"] self.idle_pictureset = mob_animations["Idle"] # load the sprite as an image # There are two animations that will play in this game: Idle and Dead, located in the `./mob` folder # Animations are loop-played, meaning, since each frame of every animation are numbered (e.g. `dead1.png`, `dead2.png`, etc.), # we can loop through them using the `<animation_name>_imagenum` variable. `<animation_name>_imagelimit` # keeps the program from trying to load an image that doesn't exist. (We don't want to open `dead8.png` if # there are only 7 frames in the 'dead' animation.) `<animation_name>_imagelimit` gets its value from the `info.json` # file in the `mob` folder. self.idle_imagenum = 1 self.dead_imagenum = 0 self.idle_imagelimit = self.idle_pictureset["count"] self.dead_imagelimit = self.dead_pictureset["count"] # this is how we will load any frame of an animation. (Here, we load the first `idle` frame) # For example, the first image that loads will be at "./mob/+idle+/+idle+1+.png". I kept the plus signs in so you can see how each part # of the below instruction contributes. The plus's aren't actually in the string. self.image = pygame.image.load("./mob/"+self.idle_pictureset["name"]+'/'+self.idle_pictureset["name"]+str(self.idle_imagenum)+".png") # create a pygame rectangle from the dimensions of the image self.rect = self.image.get_rect() # set the position of the sprite on the window # but don't position the sprite just yet self.x = random.randint(0,WINDOW_WIDTH) self.y = random.randint(0,WINDOW_HEIGHT) # place the sprite at the location determined above, record its actual position in world coordinates self.rect.topleft = self.actual_position = (self.x, self.y) # hit will stay true if the sprite has NOT been hit by a Bullet. False, otherwise. We'll use this # variable in the `update` member function self.hit = True # adds the offset calculated in the camera class to the enemy's actual position in the world (not with respect to the game window) def update(self, position): # if the enemy has not been hit by a Bullet, play its 'idle' animation if self.hit: # We use the `max` function since there are no animation frames with a 0 in their name, # and the mod function will return a 0 if self.<animation>_imagenum = self.<animation>_imagelimit self.idle_imagenum = max(1, (self.idle_imagenum + 1) % self.idle_imagelimit) self.image = pygame.image.load("./mob/"+self.idle_pictureset["name"]+'/'+self.idle_pictureset["name"]+str(self.idle_imagenum)+".png") # if it has been hit elif not self.hit: self.dead_imagenum += 1 # if the entire 'dead' animation has played, kill the enemy and remove it from view if self.dead_imagenum == self.dead_imagelimit: self.dead_imagenum = 1 self.kill() # if the animation hasn't finished, play the next frame else: self.image = pygame.image.load("./mob/"+self.dead_pictureset["name"]+'/'+self.dead_pictureset["name"]+str(self.dead_imagenum)+".png") # add the camera offset self.rect.topleft = (self.actual_position[0]+position[0], self.actual_position[1]+position[1]) class Player(pygame.sprite.Sprite): """ A pygame sprite class visible on screen as an image A sprite in pygame is a moveable object on the screen The sprite created with this class in this program will be moveable with the mouse and will not exit the window boundaries. The mouse must be hovering over the window for the sprite to move. """ def __init__(self): pygame.sprite.Sprite.__init__(self) # the current set of sprite images to use for the player's animations self.idle_pictureset = player_animations["Idle"] self.dead_pictureset = player_animations["Dead"] self.walk_pictureset = player_animations["Walk"] # load the sprite as an image # There are three animations that will play in this game: Idle, Dead, and Walk. # Animations are loop-played, meaning, since each frame of every animation are numbered (e.g. `Dead (1).png`, `Dead (2).png`, etc.), # we can loop through them using the `<animation_name>_imagenum` variable. `<animation_name>_imagelimit` # keeps the program from trying to load an image that doesn't exist. (We don't want to open `Dead (17).png` if # there are only 16 frames in the Dead animation.) `<animation_name>_imagelimit` gets its value from the `info.json` # file in the `playersprites` folder. self.idle_imagenum = 1 self.dead_imagenum = 1 self.walk_imagenum = 1 self.idle_imagelimit = self.idle_pictureset["count"] self.dead_imagelimit = self.dead_pictureset["count"] self.walk_imagelimit = self.walk_pictureset["count"] # this is how we will load any frame of an animation (here, we load the first frame indicated in the commandline parameters) self.image = pygame.image.load(argDict["player_image"]) # create a pygame rectangle from the dimensions of the image self.rect = self.image.get_rect() self.IMAGE_WIDTH = self.rect.right - self.rect.left self.IMAGE_HEIGHT = self.rect.bottom - self.rect.top # set the position of the sprite on the window in world coordinates self.x = int(argDict["startx"]) self.y = int(argDict["starty"]) # place the sprite at the location determined above, record its actual position in world coordinates, # and lastly record that position as the last viable position it has been in (more on that in this class's # `update` member function) self.rect.topleft = self.actual_position = self.old_loc = (self.x, self.y) # distance is from the mouse pointer to the sprite's topleft corner # speed is how fast the player sprite will travel across the screen self.distance = 0 self.speed = 5 # location to which the mouse points self.target_location = (0,0) def Move(self, mouse_position): """ Move controls the position of the sprite by mouse movement """ # establish the desired position of the sprite # is equal to the mouse's distance from the center of the window plus the actual position of the player in world coordinates world_coord_x = mouse_position[0]-HALF_WINDOW_WIDTH+self.actual_position[0] world_coord_y = mouse_position[1]-HALF_WINDOW_HEIGHT+self.actual_position[1] self.target_location = (world_coord_x,world_coord_y) # calculate the position of the mouse self.MoveWithMouse() # A distinction has to be made between the sprite's position in the game window (self.rect.topleft) and in the game world (self.actual_position) # The sprite's game window position is what the user sees, but for that positioning to be calculated correctly, the sprite's # actual position must be remembered. self.actual_position = (self.x, self.y) def MoveWithMouse(self): """ MoveWithMouse calculates the new position of the sprite based on the mouse's position """ # record the current, unchanged position of the sprite # self.old_loc = self.rect.topleft self.old_loc = self.actual_position # okay doing this one actually plays the dead animation, but the camera still follows an invisible santa into the void # grabs the x and y coordinate of the mouse's position on the screen x = self.target_location[0] y = self.target_location[1] # find the distance from sprite's current position and desired one dx = x - self.x dy = y - self.y # use the arctan function to find the angle from the horizontal to the desired position angle = math.atan2(dy, dx) # perform basic trig to move a multiple of `self.speed` towards the desired position # Using "min(5, self.distance/10)" lets the sprite move at a speed of 5 to self.distance/10, # so that its speed is a function of the distance from it to the mouse self.distance = straightDistance(self.x, self.y, x, y) self.x += int(min(5, self.distance/10) * math.cos(angle)) self.y += int(min(5, self.distance/10) * math.sin(angle)) # applies changes to the player sprite, such as animation and position def update(self, position): # If the distance from the mouse to the player is less than 10, loop-play the "Idle" animation, because the player isn't moving if self.distance < 10: self.idle_imagenum = max(1, (self.idle_imagenum + 1) % self.idle_imagelimit) self.image = pygame.image.load("./playersprites/"+self.idle_pictureset["name"]+str(self.idle_imagenum)+").png") # otherwise, loop-play the "Walk" animation elif self.distance >= 10: self.walk_imagenum = max(1, (self.walk_imagenum + 1) % self.walk_imagelimit) self.image = pygame.image.load("./playersprites/"+self.walk_pictureset["name"]+str(self.walk_imagenum)+").png") # if the new position of the sprite would put it outside the boundaries of the window, revert to the previous position stored in `self.old_loc` # Also, load the "Dead" animation frames when the player hits a wall if self.actual_position[0] <= 0 or self.actual_position[0]+self.IMAGE_WIDTH >= 1920 or self.actual_position[1] <= 0 or self.actual_position[1]+self.IMAGE_HEIGHT >= 1080: self.dead_imagenum = max(1, (self.dead_imagenum + 1) % self.dead_imagelimit) self.image = pygame.image.load("./playersprites/"+self.dead_pictureset["name"]+str(self.dead_imagenum)+").png") self.actual_position = self.old_loc # add the camera offset to the player sprite's actual position in the game world, "moving" them to the center of the window self.rect.topleft = (self.actual_position[0]+position[0], self.actual_position[1]+position[1]) class Bullet(pygame.sprite.Sprite): """ A pygame sprite class visible on screen as an image A sprite in pygame is a moveable object on the screen The sprite created with this class in this program will be move in a straight line toward the mouse pointer's position when the mouse left button is clicked. If the bullet comes in contact with a mob, the mob dies. """ def __init__(self,player_pos,mouse_pos): pygame.sprite.Sprite.__init__(self) # the current set of sprite images to use self.bullet_pictureset = bullet_animations["Shot"] # load the sprite as an image # There are three animations that will play in this game: Idle, Dead, and Walk. # Animations are loop-played, meaning, since each frame of every animation are numbered (e.g. `Dead (1).png`, `Dead (2).png`, etc.), # we can loop through them using the `<animation_name>_imagenum` variable. `<animation_name>_imagelimit` # keeps the program from trying to load an image that doesn't exist. (We don't want to open `Dead (17).png` if # there are only 16 frames in the Dead animation.) `<animation_name>_imagelimit` gets its value from the `info.json` # file in the `playersprites` folder. self.bullet_imagenum = 1 self.bullet_imagelimit = self.bullet_pictureset["count"] # this is how we will load any frame of an animation (here, we load the first `Idle` frame). # Here, we save the upright, unrotated version of the sprite (we want to rotate it so that it faces the direction it's shot at) self.image_unrot = pygame.image.load("./snowball/"+self.bullet_pictureset["name"]+str(self.bullet_imagenum)+".png") # create a pygame rectangle from the dimensions of the image self.rect = self.image_unrot.get_rect() # angle between the horizontal and the mouse pointer. # Using the same trigonometry to move the player sprite, we will save the angle the bullet will # fly at. self.angle = self.getBulletDirection(mouse_pos) # rotate the sprite to face the direction saved in `self.angle`. We convert it from radians to degrees # and add 180 to it (because when I did the math, bullets were facing the opposite direction) self.image = pygame.transform.rotate(self.image_unrot, (self.angle*57.29578)+180) # set the position of the sprite on the window self.x = player_pos[0] self.y = player_pos[1] # position the sprite and record it's actual position (world coords) self.rect.topleft = self.actual_position = (self.x, self.y) def getBulletDirection(self, mouse_pos): """ MoveWithMouse calculates the new position of the sprite based on the mouse's position """ # grabs the x and y coordinate of the mouse's position on the screen x = mouse_pos[0] y = mouse_pos[1] # find the distance from sprite's current position and desired one dx = x - HALF_WINDOW_WIDTH dy = y - HALF_WINDOW_HEIGHT # use the arctan function to find the angle from the horizontal to the desired position return math.atan2(dy, dx) # adds the offset calculated in the camera class to its actual position in the world (not with respect to the game window) def update(self, position): # get next frame of the bullet animation self.bullet_imagenum = max(1, (self.bullet_imagenum + 1) % self.bullet_imagelimit) self.image_unrot = pygame.image.load("./snowball/"+self.bullet_pictureset["name"]+str(self.bullet_imagenum)+".png") # rotate the bullet to face the right direction and load self.image = pygame.transform.rotate(self.image_unrot, (self.angle*-57.29578)+180) # adjust the position of the bullet with respect to the `self.angle`. Speed of bullet is "10" self.x += int(10 * math.cos(self.angle)) self.y += int(10 * math.sin(self.angle)) # save new position in world coords self.actual_position = (self.x,self.y) # if the new position of the sprite would put it outside the boundaries of the window, # kill the sprite if self.actual_position[0] <= 0 or self.actual_position[0] >= 1920 or self.actual_position[1] <= 0 or self.actual_position[1] >= 1080: self.kill() # add the camera offset to the player sprite's actual position in the game world, "moving" them to the center of the window else: self.rect.topleft = (self.actual_position[0]+position[0], self.actual_position[1]+position[1]) def main(): pygame.init() # initialize the mixer and load the sounds effects pygame.mixer.init(buffer=64) snowball_thrown = pygame.mixer.Sound("./sounds/throw.wav") snowball_hit = pygame.mixer.Sound("./sounds/hit.wav") snowball_thrown.set_volume(0.5) snowball_hit.set_volume(0.5) # sets the window title using title found in command line instruction pygame.display.set_caption(WINDOW_TITLE) # Set up the drawing window screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) # for controlling frames per second clock = pygame.time.Clock() # get how many enemies to spawn in the world from the commandline parameters num_enemies = int(argDict["enemy_count"]) # construct the ball p1 = Player() # construct the background image bkgr = Background() # construct the camera camera = Camera() # groups for all sprites that are not the player main_sprites = pygame.sprite.Group() bullet_sprites = pygame.sprite.Group() mob_sprites = pygame.sprite.Group() # add sprites to the sprite group # The order we add these to the group is the order they are drawn to the screen, # so we add the background first to keep the player from being covered main_sprites.add(bkgr) main_sprites.add(p1) # create the enemy objects and add them to the `mob_sprites` group for x in range(num_enemies): mob_sprites.add(Enemy()) # Run until the user asks to quit game loop running = True while running: # fill screen with color from commandline screen.fill(colors[argDict["color"]]['rgb']) # sets frames per second to what's found in commandline instruction clock.tick(GAME_FPS) # Did the user click the window close button? for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # if the user clicks the left mouse button if event.type == pygame.MOUSEBUTTONDOWN: # play the sound of a thrown snowball snowball_thrown.play() # create the snowball object snow_bullet = Bullet(p1.actual_position,mouse_pos) # add it to the bullet_sprites group bullet_sprites.add(snow_bullet) # attempt to move the player by sending the positioning of the mouse if pygame.mouse.get_focused(): mouse_pos = pygame.mouse.get_pos() p1.Move(mouse_pos) # focuses in on the player so that it is always centered in the game window camera.update(p1) # loop through all sprites in all groups and apply the camera offset to them for sprite in main_sprites: sprite.update(camera.apply()) for sprite in bullet_sprites: sprite.update(camera.apply()) for sprite in mob_sprites: sprite.update(camera.apply()) # loop through all bullet and mob sprites and check for collisions between bullets and mobs for bullet in bullet_sprites: for mob in mob_sprites: # if a bullet hits a mob if bullet.rect.colliderect(mob.rect): # play the sound snowball_hit.play() # kill the bullet bullet.kill() # switch the mob's hit variable to false so it starts playing its death animation mob.hit = False # draw the sprites to the screen main_sprites.draw(screen) bullet_sprites.draw(screen) mob_sprites.draw(screen) # show screen pygame.display.flip() # Done! Time to quit. pygame.quit() if __name__=='__main__': main() <file_sep># P01.1 - CovidZAR.EIEIO ## <NAME> ## Assignment Description ### This program uses the pygame library to move a sprite (textured/colored circle) around a window. The sprite is not allowed to travel off the window at all ## Folder Structure | # | File | Assignment Description | | :---: | ----------- | ---------------------- | | 1 | [game.py](game.py) | main driver code that lauches Pygame application | | 2 | [helper_module.py](helper_module.py) | helper code written by Dr. Griffin | | 3 | [color_list.txt](color_list.txt) | list of available window background colors | | 4 | [colors.json](colors.json) | `.json` file of names of colors and their RGB/Hex values | | 5 | [ball_48x48.png](ball_48x48.png) | image used to represent the player in the Pygame application | | 6 | [screenshot1.png](screenshot1.png) | image showing player in bottom right corner of screen | | 7 | [screenshot2.png](screenshot2.png) | image showing player on left side of screen | | 8 | [screenshot3.png](screenshot3.png) | image showing player at top of screen | ## Instructions 1. Ensure the latest version of Python is installed on your system. This code was originally run with Python 3.8.3 2. Follow the instructions on the [pygame wiki](https://www.pygame.org/wiki/GettingStarted) to get it installed. 3. Open a command prompt / terminal in the `P01.1` folder 4. Run `game.py` by typing `python game.py title= width= height= fps= image= color=`. Select for yourself the Windows title (`title`), dimensions in pixels (`width` and `height`), refresh rate (`fps`), player image (`image`), and screen background color (`color`). Select the color from [color_list.txt](color_list.txt). 5. To move your player, keep your mouse over the window and move it around (clicking won't do anything). If the mouse leaves the window, the player will stop moving. 6. Close the window to exit the game ## Example The following is an example of the Pygame app if run with this command: `python game.py title="Pygame Example" width=640 height=480 fps=60 image="./ball_48x48.png" color=bisque` ### Gif ![sprite movement video](https://media.giphy.com/media/U6YEDrQ1EzoKWhl9hl/giphy.gif) ### Screenshot 1 <img src="screenshot1.png" width="300"> ### Screenshot 2 <img src="screenshot2.png" width="300"> ### Screenshot 3 <img src="screenshot3.png" width="300"><file_sep># resizes all image in a folder from PIL import Image for i in range(1,17): image = Image.open(str(i)+'.png').convert("RGBA") image = image.crop(box=(5, 0, 64, 64)) image.save(str(i)+'.png', quality=95)
58d99abb42f1fbd773810b6d006b86a2909e364e
[ "Markdown", "Python" ]
17
Python
Pirhomega/4443-2D-PyGame-Matamoros
73a3f11a98c2e562d6ea5b1cae0d7c0396bac6ba
efb97c101c50d595fb24e8d82c279e8d3e7a3df6
refs/heads/master
<file_sep>using Libs; using Owin; namespace WebApp { public class Startup { public void Configuration(IAppBuilder app) { app.Use((context, next) => { return context.Response.WriteAsync($"{Constants.Feature1}<br/>{Constants.Feature2}<br/>{Constants.Feature3}<br/>{Constants.Feature4}"); }); } } }<file_sep># git-branching-versioning<file_sep>namespace Libs { public class Constants { public const string Feature1 = "Feature 1 added."; public const string Feature2 = "Feature 2 added. Bug fixed after pulled to release."; public const string Feature3 = "Feature 3 added. Bug fixed after pulled to production release."; public const string Feature4 = "Feature 4 added."; } }
01f63ff50df7364a42aa0685774cbd519534a394
[ "Markdown", "C#" ]
3
C#
cchongchong/git-branching-versioning
59b148aa3cadbe6b8404fb03e2a4808698846079
d6d93636749c7032cca432448b0e0286e4ae6b4d
refs/heads/master
<file_sep>This is one of my old projects; it was created in 2011. It doesn't work on platforms that don't allow execution of heap. Today I fixed it for 64bit Linux. Compile with -m32 flag. # BFJIT bfjit is a fast, optimizing heap/aot compiler for brainfuck. The program directly translates the brainfuck code into 80386 opcodes, writes these onto the heap and then executes them. ## INDEX 1. Usage 2. Brainfuck commands 3. Speed 4. Portability ## 1. USAGE The program should be executed from the command line like this: C:\> bfjit [file] [-16|-32] [-0|-255] [-s start] [-m size] file name of input file -m size of programs memory (standard 32768) -s start point of the memory pointer (>=0) (standard 16384) -16 set cell size to 16 bit -32 set cell size to 32 bit -0 writes 0 into cell, if eof is read -255 writes 255 into cell, if eof is read -hhelp message - if you call bfjit without a filename, you can type the program into the commandline. - the parameters don't have to be written in this order. ## 2. COMMANDS The stock commands + - > < . , [ ] and additionally ! and # are supported. bang (!) is only recognized when in console mode. It seperates code from data (that would be impossible otherwise) hash (#) enters debug query mode. Enter a single number or two numbers seperated by a comma (note, that the second one must be greater than the first one). Then the contents of this/these cell(s) are echoed. Example: -5,5 [-5] = 00 0 [-4] = 00 0 [-3] = 00 0 [-2] = 00 0 [-1] = 00 0 [0] = 00 0 [1] = 00 0 [2] = 00 0 [3] = 00 0 [4] = 00 0 [5] = 00 0 ## 3. SPEED bfjit is able to compete with the most brainfuck compilers and is about 24.000 and much more times faster than most interpreters. Well, how is this speed achieved? The biggest part of this is made up by the compilation but bfjit's optimization does also speed the progress up a little. Optimization is done by pooling connected ( +'s and -'s ) and ( >'s and <'s ) and combine them in one instruction (by the way: bfjit tries to generate the shortest x86 Instruction possible). The constructs [-] [>>] and [<<] are replaced by a predefined opcode sequence. You can deactivate the replacement of the latter two by putting commentation marks before '#define USE_STRINGFUNCTIONS'. ## 4. PORTABILITY Obviously, bfjit currently only works on 80386 processor family, because it generates opcodes for this plattform and relies on some inline assembler instruction in its code. Nevertheless it should run on EVERY 80386 32/64 bit OS! (64 bit OS'es may not support bfjit's 16 bit mode) The OS only has to provide a C compiler a libc and allow execution of heap. I tried to write bfjit so that it will be easy to port it to other plattforms. <file_sep>/* BFJIT a fast, optimizing brainfuck heap compiler The MIT License (MIT) Copyright (c) 2011-2015 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <time.h> #include <errno.h> /*********************************************************************************************/ /* Predefined Modifications */ // if your system gives 13 and 10 instead of 10 on return, activate this //#define USE_NEWLINE_HACK_13 // tries to optimize [>>] and [<<] by using x86 string functions #define USE_STRINGFUNCTIONS // Remove the ifdef if needed #if defined(__unix__) || defined(__MACH__) #define USE_POSIX #else #warning could not determine OS type, bfjit is likely to crash due to heap execution restrictions #endif //#define DEBUGMODE /* End of Modifications */ /*********************************************************************************************/ #ifdef USE_POSIX #include <sys/mman.h> #include <unistd.h> #endif #ifdef DEBUGMODE #define DEBUG(X) X #else #define DEBUG(X) #endif // Needn't to be changed, as it can be changed by the user via commandline #define STANDARD_MEMLEN 0x8000 #define STANDARD_MEMSTART STANDARD_MEMLEN/2 /*********************************************************************************************/ /* Macros to keep * Modifications for plattforms different from 80386 can be made here * Note, that I used inline assembler in the stub functions below! */ #define INC_PTR_ESI if(cellsize==1){INC_PTR8_ESI}else if(cellsize==2){INC_PTR16_ESI}else{INC_PTR32_ESI} #define DEC_PTR_ESI if(cellsize==1){DEC_PTR8_ESI}else if(cellsize==2){DEC_PTR16_ESI}else{DEC_PTR32_ESI} #define ADD_PTR_ESI(X) if(cellsize==1){ADD_PTR8_ESI(X)}else if(cellsize==2){ADD_PTR16_ESI(X)}else{ADD_PTR32_ESI(X)} #define PTR_ESI_TO_ZERO if(cellsize==1){PTR8_ESI_TO_ZERO}else if(cellsize==2){PTR16_ESI_TO_ZERO}else{PTR32_ESI_TO_ZERO} #define TEST_PTR_ESI if(cellsize==1){TEST_PTR8_ESI}else if(cellsize==2){TEST_PTR16_ESI}else{TEST_PTR32_ESI} #define FIND_NONZERO_R if(cellsize==1){FIND_NONZERO8_R}else if(cellsize==2){FIND_NONZERO16_R}else{FIND_NONZERO32_R} #define FIND_NONZERO_L if(cellsize==1){FIND_NONZERO8_L}else if(cellsize==2){FIND_NONZERO16_L}else{FIND_NONZERO32_L} #define INC_PTR8_ESI *codei++=0xFE;*codei++=0x06; #define INC_PTR16_ESI *codei++=0x66;*codei++=0xFF;*codei++=0x06; #define INC_PTR32_ESI *codei++=0xFF;*codei++=0x06; #define FIND_NONZERO8_R *codei++=0x30;*codei++=0xC0;*codei++=0xFD;*codei++=0xF3;*codei++=0xAE;*codei++=0x46; #define FIND_NONZERO16_R *codei++=0x66;*codei++=0x31;*codei++=0xC0;*codei++=0xFD;*codei++=0xF3;*codei++=0x66;\ *codei++=0xAF;*codei++=0x46; #define FIND_NONZERO32_R *codei++=0x31;*codei++=0xC0;*codei++=0xFD;*codei++=0xF3;*codei++=0xAF;*codei++=0x46; #define FIND_NONZERO8_L *codei++=0x30;*codei++=0xC0;*codei++=0xFC;*codei++=0xF3;*codei++=0xAE;*codei++=0x4E; #define FIND_NONZERO16_L *codei++=0x66;*codei++=0x31;*codei++=0xC0;*codei++=0xFC;*codei++=0xF3;*codei++=0x66;\ *codei++=0xAF;*codei++=0x4E; #define FIND_NONZERO32_L *codei++=0x31;*codei++=0xC0;*codei++=0xFC;*codei++=0xF3;*codei++=0xAF;*codei++=0x4E; #define DEC_PTR8_ESI *codei++=0xFE;*codei++=0x0E; #define DEC_PTR16_ESI *codei++=0x66;*codei++=0xFF;*codei++=0x0E; #define DEC_PTR32_ESI *codei++=0xFF;*codei++=0x0E; #define ADD_PTR8_ESI(X) *codei++=0x80;*codei++=0x06;*codei++=X; #define ADD_PTR16_ESI(X) *codei++=0x66;*codei++=0x81;*codei++=0x06;*codei++=X&0xFF;*codei++=(X>>8)&0xFF; #define ADD_PTR32_ESI(X) *codei++=0x81;*codei++=0x06;*codei++=X&0xFF;*codei++=(X>>8)&0xFF; \ *codei++=(X>>16)&0xFF;*codei++=X>>24; #define INC_ESI *codei++=0x46; #define DEC_ESI *codei++=0x4E; #define ADD_BYTE_ESI(X) *codei++=0x83;*codei++=0xC6;*codei++=X; #define SUB_BYTE_ESI(X) *codei++=0x83;*codei++=0xEE;*codei++=X; #define ADD_ESI(X) *codei++=0x81;*codei++=0xC6;*codei++=X&0xFF;\ *codei++=(X>>8)&0xFF;*codei++=(X>>16)&0xFF;*codei++=X>>24; #define FARCALL(X) *codei++=0xBB;*codei++=X&0xFF;*codei++=(X>>8)&0xFF;*codei++=(X>>16)&0xFF;\ *codei++=X>>24;*codei++=0xFF;*codei++=0xD3; #define SET_LOOPSTART_JMP(X) loopstart[1]=X&0xFF;loopstart[2]=(tmp>>8)&0xFF;\ loopstart[3]=(tmp>>16)&0xFF;loopstart[4]=tmp>>24; #define PTR8_ESI_TO_ZERO *codei++=0xC6;*codei++=0x06;*codei++=0x00; #define PTR16_ESI_TO_ZERO *codei++=0x66;*codei++=0xC7;*codei++=0x06;*codei++=0x00;*codei++=0x00; #define PTR32_ESI_TO_ZERO *codei++=0xC7;*codei++=0x06;*codei++=0x00;*codei++=0x00;*codei++=0x00;*codei++=0x00; #define LOOP_BEGIN *codei++=0xE9;codei+=4; #define TEST_PTR8_ESI *codei++=0x80;*codei++=0x3E;*codei++=0x00; #define TEST_PTR16_ESI *codei++=0x66;*codei++=0x83;*codei++=0x3E;*codei++=0x00; #define TEST_PTR32_ESI *codei++=0x83;*codei++=0x3E;*codei++=0x00; #define JNE_SHORT(X) *codei++=0x75;*codei++=(X+4)&0xFF; #define JNE_NEAR(X) *codei++=0x0F;*codei++=0x85;*codei++=X&0xFF;*codei++=(X>>8)&0xFF;\ *codei++=(X>>16)&0xFF;*codei++=X>>24; #define INCDEC_PTR_ESI_LEN ((cellsize==1)?INCDEC_PTR8_ESI_LEN:((cellsize==2)?INCDEC_PTR16_ESI_LEN:INCDEC_PTR32_ESI_LEN)) #define ADD_PTR_ESI_LEN ((cellsize==1)?ADD_PTR8_ESI_LEN:((cellsize==2)?ADD_PTR16_ESI_LEN:ADD_PTR32_ESI_LEN)) #define PTR_ESI_TO_ZERO_LEN ((cellsize==1)?PTR8_ESI_TO_ZERO_LEN:((cellsize==2)?PTR16_ESI_TO_ZERO_LEN:PTR32_ESI_TO_ZERO_LEN)) #define LOOP_END_LEN ((cellsize==1)?LOOP_END8_LEN:((cellsize==2)?LOOP_END16_LEN:LOOP_END32_LEN)) #define FIND_NONZERO_LEN ((cellsize==1)?FIND_NONZERO8_LEN:((cellsize==2)?FIND_NONZERO16_LEN:FIND_NONZERO32_LEN)) #define INCDEC_PTR8_ESI_LEN 2 #define INCDEC_PTR16_ESI_LEN 3 #define INCDEC_PTR32_ESI_LEN 2 #define ADD_PTR8_ESI_LEN 3 #define ADD_PTR16_ESI_LEN 5 #define ADD_PTR32_ESI_LEN 7 #define FIND_NONZERO8_LEN 7 #define FIND_NONZERO16_LEN 7 #define FIND_NONZERO32_LEN 7 #define PTR8_ESI_TO_ZERO_LEN 3 #define PTR16_ESI_TO_ZERO_LEN 5 #define PTR32_ESI_TO_ZERO_LEN 6 #define INCDEC_ESI 1 #define ADDSUB_BYTE_ESI 3 #define ADDSUB_ESI 6 #define FARCALL_LEN 7 #define LOOP_BEGIN_LEN 5 #define LOOP_END8_LEN 9 #define LOOP_END16_LEN 10 #define LOOP_END32_LEN 9 /*********************************************************************************************/ FILE *datei; const char *compilername; unsigned char *bfcode,*bfcodei; unsigned char *code,look,*codei; unsigned char *mem, *filename; int add_pn=0,codelen,memlen,memstart,filesize; int error=0; unsigned int add_pm=0; int extended=0; int newlinehack; int cellsize=1; int oneof=10; /* * oneof: 0 ... writes zero to cell, if eof is read * 255 ... writes 255 to cell, if eof is read * anything else ... leaves the cell unchanged, if eof is read */ void check_pm(void){ if(add_pm!=0){ switch(add_pm){ case 1: INC_PTR_ESI break; case -1: DEC_PTR_ESI break; default: ADD_PTR_ESI(add_pm) break; } add_pm=0; } } void check_pn(void){ if(add_pn!=0){ if(add_pn==1){ INC_ESI }else if(add_pn==-1){ DEC_ESI }else if(add_pn>=2 && add_pn<=0x7F){ ADD_BYTE_ESI(add_pn) }else if(add_pn>=-0x7F && add_pn<=-2){ SUB_BYTE_ESI((-add_pn)) }else{ ADD_ESI(add_pn) } add_pn=0; } } void usage(void){ printf( "\nusage: %s [file] [-16|-32] [-0|-255] [-s start] [-m size]\n" \ "\nfile\t\tname of input file\n" \ "-m\t\tsize of programs memory (standard %d)\n" \ "-s\t\tstart point of the memory pointer (>=0) (standard %d)\n" \ "-16\t\tset cell size to 16 bit\n" \ "-32\t\tset cell size to 32 bit\n" \ "-0\t\twrites 0 into cell, if eof is read\n" \ "-255\t\twrites 255 into cell, if eof is read\n" \ "-h\t\tshows this message\n" \ "\n", compilername,STANDARD_MEMLEN,STANDARD_MEMSTART); exit(0); } void len_pm(int *len){ if(add_pm!=0){ if(add_pm==1 || add_pm==255){ *len+=INCDEC_PTR_ESI_LEN; }else{ *len+=ADD_PTR_ESI_LEN; } add_pm=0; } } void len_pn(int *len){ if(add_pn!=0){ if(add_pn==1 || add_pn==-1){ *len+=INCDEC_ESI; }else if(add_pn>=-0x7F && add_pn<=0x7F){ *len+=ADDSUB_BYTE_ESI; }else{ *len+=ADDSUB_ESI; } add_pn=0; } } int proglen(void){ int len; for(len=1,look=*bfcodei++;*bfcodei!=0;look=*bfcodei++){ switch(look){ case '+': len_pn(&len); add_pm++; break; case '-': len_pn(&len); add_pm--; break; case '>': len_pm(&len); add_pn+=cellsize; break; case '<': len_pm(&len); add_pn-=cellsize; break; case '.': len_pm(&len); len_pn(&len); len+=FARCALL_LEN; break; case ',': len_pm(&len); len_pn(&len); len+=FARCALL_LEN; break; case '0': len_pn(&len); len+=PTR_ESI_TO_ZERO_LEN; break; #ifdef USE_STRINGFUNCTIONS case 'r': case 'l': check_pm(); check_pn(); len+=FIND_NONZERO_LEN; break; #endif case '#': len_pm(&len); len_pn(&len); len+=FARCALL_LEN; break; case '[': len_pm(&len); len_pn(&len); len+=LOOP_BEGIN_LEN; break; case ']': len_pm(&len); len_pn(&len); len+=LOOP_END_LEN; break; } } len_pm(&len); len_pn(&len); return len; } unsigned char *esi; int getnum(int *zahl){ int ret=0,min=0; look=getchar(); if(look=='-'){ look=getchar(); min=1; } if(!isdigit(look)) return 0; while(isdigit(look)){ ret=10*ret+look-'0'; look=getchar(); } if(min) ret=-ret; *zahl=ret; return 1; } void extension_debug_output(int i){ unsigned int z; switch(cellsize){ case 1: z=(mem+memstart)[i]; if(z>=32 && z<=126) printf("[%d]\t= %02X %3d\t\'%c\'\n",i,z,z,z); else printf("[%d]\t= %02X %3d\n",i,z,z); break; case 2: z=((short*)(mem+memstart))[i]; if(z>=32 && z<=126) printf("[%d]\t= %04X %5d\t\'%c\'\n",i,z,z,z); else printf("[%d]\t= %04X %5d\n",i,z,z); break; case 4: z=((int*)(mem+memstart))[i]; if(z>=32 && z<=126) printf("[%d]\t= %08X %10d\t\'%c\'\n",i,z,z,z); else printf("[%d]\t= %08X %10d\n",i,z,z); break; } } /*********************************************************************************************/ /* runtime stubs - these functions are called AT RUNTIME! Except the extension_debug_stub, they * should be extremely fast! * So, here is the rest of the plattform-specific stuff (inline assembler) */ void extension_debug_stub(void){ asm volatile("movl %%esi,%0\n" :: "m" (esi)); int zahl1,zahl2; printf("\nDEBUG QUERY\t\tcell pointer at: %p ",esi-(size_t)mem-memstart); if(esi>=mem && esi<mem+memlen) printf("(ok)"); else printf("!! out of bounds !!"); printf("\n\n"); fflush(stdin); for(;;){ printf("> "); if(getnum(&zahl1)){ if(zahl1>=-memstart && zahl1<memlen-memstart){ if(look==','){ if(getnum(&zahl2)){ if(zahl2>=-memstart && zahl2<memlen-memstart && zahl2>zahl1){ for(;zahl1<=zahl2;zahl1++) extension_debug_output(zahl1); } } }else{ extension_debug_output(zahl1); } } }else{ break; } } fflush(stdin); asm volatile("movl %0,%%esi\n" :: "m" (esi)); } void print_stub(void){ asm volatile( "movl %%esi,%0\n" "xorl %%eax,%%eax\n" "movb (%%esi),%%al\n" "push %%eax\n" "call *%1\n" "pop %%eax\n" // shorter than "add $4, %%esp" :: "m" (esi), "b" ((size_t)putchar) : "cc", "eax", "esi"); } void input_stub(void){ asm volatile("mov %%esi,%0" :: "m" (esi)); int x = getchar(); if(x == EOF){ switch(oneof){ case 0: x = 0; break; case 255: x = 255; break; default: return; } } #ifdef USE_NEWLINE_HACK_13 if (x == '\r') return; #endif *esi = (unsigned char) x; asm volatile("mov %0,%%esi\n" :: "m" (esi)); } void program(void){ ptrdiff_t tmp; unsigned char *loopstart; for(look=*bfcodei++;*(bfcodei-1)!=0;look=*bfcodei++){ switch(look){ case '+': check_pn(); add_pm++; break; case '-': check_pn(); add_pm--; break; case '>': check_pm(); add_pn+=cellsize; break; case '<': check_pm(); add_pn-=cellsize; break; #ifdef USE_STRINGFUNCTIONS case 'r': check_pm(); check_pn(); FIND_NONZERO_R break; case 'l': check_pm(); check_pn(); FIND_NONZERO_L break; #endif case '#': check_pm(); check_pn(); FARCALL((size_t)extension_debug_stub) break; case '.': check_pm(); check_pn(); FARCALL((size_t)print_stub) break; case ',': check_pm(); check_pn(); FARCALL((size_t)input_stub); break; case '0': check_pn(); PTR_ESI_TO_ZERO break; case '[': check_pm(); check_pn(); loopstart=codei; LOOP_BEGIN program(); tmp=codei-loopstart-5; SET_LOOPSTART_JMP(tmp) TEST_PTR_ESI tmp=loopstart-codei-1; if(tmp>=-0x7F){ JNE_SHORT(tmp) }else{ JNE_NEAR(tmp) } break; case ']': check_pm(); check_pn(); return; } } check_pm(); check_pn(); error++; } void parsecmdln(int argc, char *argv[]){ int i; if(argc>1){ for(i=1;i<argc;i++){ if(argv[i][0]=='-'){ if(strcmp(argv[i]+1,"16")==0){ cellsize=2; }else if(strcmp(argv[i]+1,"32")==0){ cellsize=4; }else if(strcmp(argv[i]+1,"0")==0){ oneof=0; }else if(strcmp(argv[i]+1,"255")==0){ oneof=255; }else{ switch(argv[i][1]){ case 'm': if(argc==i+1) usage(); memlen=atoi(argv[++i]); break; case 's': if(argc==i+1) usage(); memstart=atoi(argv[++i]); break; case 'h': usage(); break; } } } } } } void parsebf1(void){ int tmp; for(look=fgetc(datei);bfcodei-bfcode<=filesize && !feof(datei);look=fgetc(datei)){ if(datei==stdin && look=='!') break; if( look=='+' || look=='-' || look=='>' || look=='<' || look=='.' || \ look==',' || look==']' || look=='[' || look=='#'){ *bfcodei++=look; }else if(look=='['){ // make "[-]" to single instruction // make "[>>]" to single instruction // make "[<<]" to single instruction tmp=fgetc(datei); if(tmp=='-'){ tmp=fgetc(datei); if(tmp==']'){ *bfcodei++='0'; }else{ *bfcodei++='['; *bfcodei++='-'; *bfcodei++=(char) tmp; } #ifdef USE_STRINGFUNCTIONS }else if(tmp=='>'){ tmp=fgetc(datei); if(tmp=='>'){ tmp=fgetc(datei); if(tmp==']'){ *bfcodei++='r'; }else{ *bfcodei++='['; *bfcodei++='>'; *bfcodei++='>'; *bfcodei++=(char) tmp; } }else{ *bfcodei++='['; *bfcodei++='>'; *bfcodei++=(char) tmp; } }else if(tmp=='<'){ tmp=fgetc(datei); if(tmp=='<'){ tmp=fgetc(datei); if(tmp==']'){ *bfcodei++='l'; }else{ *bfcodei++='['; *bfcodei++='<'; *bfcodei++='<'; *bfcodei++=(char) tmp; } }else{ *bfcodei++='['; *bfcodei++='<'; *bfcodei++=(char) tmp; } #endif }else{ *bfcodei++='['; *bfcodei++=(char) tmp; } } } filesize=bfcodei-bfcode; *bfcodei=0; } unsigned char* alloc_execmem(int len){ unsigned char* execmem; #ifdef USE_POSIX long pagesz = sysconf(_SC_PAGE_SIZE); execmem = malloc(len+pagesz); size_t e = (size_t) execmem; e += (e % pagesz == 0) ? (size_t) pagesz : pagesz - (e % pagesz); execmem = (void*) e; #else execmem = malloc(len+4096); #endif if(execmem == NULL) exit(17); return execmem; } void bypass_nx(void *mem){ #ifdef USE_POSIX mprotect(mem, codelen, PROT_READ | PROT_EXEC); #endif } unsigned char* compile(void){ unsigned char *execmem; parsebf1(); if(datei!=stdin) fclose(datei); bfcodei=bfcode; codelen=proglen(); execmem = alloc_execmem(codelen); codei = code = execmem; mem=malloc(memlen*cellsize); memset(mem,0,memlen); bfcodei=bfcode; program(); *codei++=0xC3; // Return return execmem; } int openfile(int argc, char *argv[]){ int i; for(i=1,datei=NULL;i<argc && datei==NULL;i++){ datei=fopen(argv[i],"r"); } return (datei!=NULL); } int main(int argc, char *argv[]){ unsigned char *execmem; compilername=argv[0]; memlen=STANDARD_MEMLEN; memstart=STANDARD_MEMSTART; parsecmdln(argc,argv); if(openfile(argc,argv)){ for(filesize=0;!feof(datei);filesize++) fgetc(datei); fseek(datei,0,SEEK_SET); }else{ datei=stdin; printf("Program length: "); while(scanf("%d",&filesize) == 0); } bfcodei=bfcode=malloc(filesize+1); execmem = compile(); free(bfcode); bfcodei=bfcode=NULL; if(error!=1) return 1; // if sourcecode is wrong, for instance: "[[++]" #ifdef DEBUGMODE printf("compilation completed with no errors\n"); printf("execmem: %p\tcodelen: %d\tmem: %p\tmemlen: %d cells\n", execmem, codelen, mem, memlen); #endif DEBUG(printf("marking execmem as executable...\n")); bypass_nx(execmem); DEBUG(printf("executing...\n")); asm volatile("call *%0" :: "m" (code), "S" (mem+memstart)); // again plattform specific printf("\n"); return 0; } <file_sep>SHELL ?= /bin/sh CC ?= gcc MAKE ?= make RM ?= rm CFLAGS := -O2 -pipe -g -Wall -Wextra $(CXXFLAGS) OBJS := bfjit.o all: bfjit %.o: %.c $(CC) -m32 -no-pie -fno-pic $(CFLAGS) -c -o $@ $< bfjit: $(OBJS) $(CC) -m32 -no-pie -fno-pic -o $@ $(OBJS) clean: $(RM) $(OBJS) bfjit .PHONY: all clean
ce5d3ea7410e1520948ceabce4afd56541f93022
[ "Markdown", "C", "Makefile" ]
3
Markdown
chtisgit/bfjit
33feec24b286aed102dcdab5d08a24c7141b85d5
bc70d04841492f4b10d1077b8c63dab3c9850e47
refs/heads/main
<repo_name>BUUZKA/kalkulator<file_sep>/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { } private void CalculateIP(object sender, EventArgs e) { IPAddress ipAddress = IPAddress.Parse(IPAdressTextBox.Text); IPAddress maskAddress = IPAddress.Parse(MaskTextBox.Text); byte[] ip = ipAddress.GetAddressBytes(); byte[] mask = maskAddress.GetAddressBytes(); byte[] network = new byte[4]; byte[] broadcast = new byte[4]; for (int i = 0; i < 4; i++) { network[i] = (byte)(ip[i] & mask[i]); } Array.Copy(network, broadcast, 4); string networkAddressString = ""; string broadcastAddressString = ""; for (int i = 0; i < 4; i++) { String ipFragment = network[i].ToString(); ipFragment = ipFragment.PadLeft(3, '0'); networkAddressString += ipFragment; ipFragment = broadcast[i].ToString(); ipFragment = ipFragment.PadLeft(3, '0'); broadcastAddressString += ipFragment; } networkAddressTextBox.Text = networkAddressString; } } }
8f22360dc22b12c9b371143f418b3eb69b94ebc2
[ "C#" ]
1
C#
BUUZKA/kalkulator
079425813cb7caab46ab53cd02ed37cbf2059ce6
674c25fd7a78645da993797e6b1316788ba0690d
refs/heads/master
<repo_name>bcompter/Data-Structures<file_sep>/linked-list/linked_list.h #ifndef LINKED_LIST_H #define LINKED_LIST_H #ifdef __cplusplus extern "C" { #endif #include <stdio.h> /** * A node in our list */ typedef struct Node Node; struct Node { Node * next; Node * prev; int data; }; /** * Our linked list */ typedef struct{ Node * head; int size; } List; /** * Add a Node to the end of this list which becomes the new Tail */ void Add(Node * n, List * l); /** * Remove and return the tail from a list * Returns NULL if the list is empty */ Node * Remove(List * l); /** * Traverse our list and print out the data of each Node */ void Display(List l); #ifdef __cplusplus } #endif #endif /* LINKED_LIST_H */ <file_sep>/pointers/example01/README.md # Pointers, Example 01 Outputs the following on my machine. Your memory locations will vary. Our integer is 42 It is located at memory address 2686744, (0x28ff18) We can dereference our pointer to get the original data like so, 42 <file_sep>/pointers/example01/main.cpp #include <cstdlib> #include <stdio.h> using namespace std; /** * A brief introduction to pointers */ int main(int argc, char** argv) { // Lets make an integer! int myInteger = 42; /** * And now an int pointer to that integer * Keep in mind I am using integers here but you could substitute just * about any object you wish. * * I am using the & operator to get the address of myInteger for my pointer * to point to. */ int * ptr_myInteger = &myInteger; /** * Lets print some stuff out to see what we have * Take a careful look at the use of the dereference operator * in the third * printf. We can use this to look at data located at a location in memory */ printf("Our integer is %d\n", myInteger); printf("It is located at memory address %d, (0x%x)\n", ptr_myInteger, ptr_myInteger); printf("We can dereference our pointer to get the original data like so, %d\n", *ptr_myInteger); return 0; }<file_sep>/README.md # Data-Structures A compilation of different data structures and algorithms for practice and fun. <file_sep>/linked-list/main.c /** * An example of a custom linked list implemented in C */ #include <stdio.h> #include <stdlib.h> #include "linked_list.h" /** * Main entry point to test our implementation */ int main(int argc, char** argv) { // Create a list for us to test with List test_list; test_list.head = NULL; test_list.size = 0; // And some test nodes Node test_node_1; test_node_1.data = 42; Node test_node_2; test_node_2.data = 24; Node test_node_3; test_node_3.data = 14; Node test_node_4; test_node_4.data = 7; // Add and display our list Add(&test_node_1, &test_list); Display(test_list); Add(&test_node_2, &test_list); Display(test_list); Add(&test_node_3, &test_list); Display(test_list); Node * test = Remove(&test_list); Display(test_list); printf("Removed %d\n", test->data); Add(&test_node_4, &test_list); Display(test_list); return (EXIT_SUCCESS); } /* end main */ <file_sep>/linked-list/linked_list.c #include "Linked_list.h" /** * Add a Node to the end of this list which becomes the new Tail */ void Add(Node * n, List * l) { if (l->head == NULL) { l->head = n; n->next = n; n->prev = n; l->size = 1; } else { Node * tail = l->head->prev; Node * head = l->head; head->prev = n; tail->next = n; n->next = head; n->prev = tail; l->size++; } } /* end Add */ /** * Remove and return the tail from a list * Returns NULL if the list is empty */ Node * Remove(List * l) { Node * tail = l->head->prev; Node * head = l->head; Node * new_tail = tail->prev; head->prev = new_tail; new_tail->next = head; if (l->size > 0) l->size--; if (l->size == 0) l->head = NULL; return tail; } /** * Traverse our list and print out the data of each Node */ void Display(List l) { int i; Node * n = l.head; for(i = 0; i < l.size; i++) { printf("%d, ", n->data); n = n->next; } printf("\n"); } // end Display
f4856a9e95f2a69824ddacf0dd522d9c4122155b
[ "Markdown", "C", "C++" ]
6
C
bcompter/Data-Structures
4366763d23b2ba63087898ad68e0a9ebee0b8b4c
a1de004be05f4d7c09f2f40860144c1b13db963d
refs/heads/master
<repo_name>danonechik94/Tic-Tac-Toe<file_sep>/src/com/Haven/Field.java package com.Haven; public class Field { private final char[][] field; private static final int DEFAULT_FIELD_SIZE = 3; private static final int MIN_FIELD_SIZE = DEFAULT_FIELD_SIZE; private static final int MAX_FIELD_SIZE = 10; private int fieldSize; public static int getFieldSize() { return fieldSize; } public static void setFieldSize(int fieldSize) { Field.fieldSize = fieldSize; } public Field() { this(DEFAULT_FIELD_SIZE); } public Field(int fieldSize) { if (fieldSize >= MIN_FIELD_SIZE && fieldSize <= MAX_FIELD_SIZE) this.fieldSize = fieldSize; field = new char[fieldSize][fieldSize]; clearField(); } public void clearField() { for (int i = 0; i < fieldSize; i++) { clearLine(i); } } private void clearLine(int lineNumber) { for (int i = 0; i < fieldSize; i++) { field[lineNumber][i] = ' '; } } public void showField() { StringBuilder xInLine = new StringBuilder(" "); for (int i = 0; i < fieldSize; i++) xInLine.append(i + " "); xInLine.append("X"); System.out.print(xInLine + "\n"); for (int i = 0; i < fieldSize; i++) { System.out.print(i); showLine(i); System.out.println(); } System.out.print("Y"); } public void showLine(int lineNumber) { for (int i = 0; i < fieldSize; i++) { System.out.print("[" + field[lineNumber][i] + "]"); } } public boolean checkLine(int lineNumber) { for (int i = 0; i < fieldSize; i++) { if (!(field[lineNumber][i] == 'X' || field[lineNumber][i] == 'O')) { return false; } } return true; } public boolean checkColumn(int columnNumber) { for (int i = 0; i < fieldSize; i++) { if (!(field[i][columnNumber] == 'X' || field[i][columnNumber] == 'O')) { return false; } } return true; } public boolean checkDiagonalUp() { for (int i = 0; i < fieldSize; i++) { if (!(field[i][i] == 'X' || field[i][i] == 'O')) { return false; } } return true; } public boolean checkDiagonalDown() { for (int i = fieldSize - 1; i < fieldSize; i--) { if (!(field[i][i] == 'X' || field[i][i] == 'O')) { return false; } } return true; } public boolean checkField() { for (int i = 0; i < fieldSize; i++) { if (checkColumn(i) || checkLine(i) || checkDiagonalUp() || checkDiagonalDown()) { return true; } } return false; } public void setFieldCell(int y, int x, char cell) { field[y][x] = cell; } } <file_sep>/README.md Игра крестики-нолики с консольным интерфейсом. Пока реализована игра за одним компьютером Игрок-против-Игрока. В дальнейшем планируется добавить поддержку игры с ИИ и сетевую игру с человеком.
6b9a4a7889f748f3e63be3a493dd18c497439543
[ "Markdown", "Java" ]
2
Java
danonechik94/Tic-Tac-Toe
534b9f12697c3c2b3bbad425d1ca4013d348e87f
3966f4c27279f175728d689b0a72ebda92fd7702
refs/heads/master
<repo_name>pebblecode/tanks-for-nothing<file_sep>/Assets/Menu.cs using UnityEngine; using System.Collections; using System.Timers; using UnityEngine.UI; public class Menu : MonoBehaviour { Timer tmr = new Timer(1000); public float spawnWait; public float startWait; public float waveWait; public int tankCount; public GameObject bouncyTank; public Vector3 spawnValues; // Use this for initialization void Start () { StartCoroutine (SpawnWaves ()); // tmr.Interval = 1000; // 0.1 second // tmr.Elapsed += timerHandler; // We'll write it in a bit // tmr.Start(); // The countdown is launched! } // private void timerHandler (object sender, ElapsedEventArgs e) { // var thisText = GetComponent<Text> (); // thisText.text = "Tanks"; // tmr.Stop(); // } IEnumerator SpawnWaves () { yield return new WaitForSeconds (startWait); { for (int i = 0; i < tankCount; i++) { Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, Random.Range (-spawnValues.z, spawnValues.z)); Quaternion spawnRotation = Quaternion.identity; Instantiate (bouncyTank, spawnPosition, spawnRotation); yield return new WaitForSeconds (spawnWait); } //yield return new WaitForSeconds (waveWait); } } // Update is called once per frame void Update () { } } <file_sep>/Assets/Shell.cs using UnityEngine; using System.Collections; public class Shell : MonoBehaviour { public GameObject owner; public float created; // Use this for initialization void Start () { created = Time.time; } } <file_sep>/README.md # Tanks For Nothing A 4 player Unity game <file_sep>/Assets/Audio.cs using UnityEngine; using System.Collections; public class Audio : MonoBehaviour { public AudioSource fireAudioSource; public AudioClip [] fire; public AudioSource engineAudioSource; public AudioClip idle; public AudioClip driving; private float lastShot; private PlayerController _player; private PlayerController player { get { if (_player == null) { _player = GetComponent<PlayerController> (); } return _player; } } public void Fire() { fireAudioSource.clip = fire[player.playerNumber-1]; fireAudioSource.Play(); } public void Update () { if (player.leftStick.magnitude > 0 && engineAudioSource.clip != driving) { engineAudioSource.clip = driving; engineAudioSource.Play (); } if (player.leftStick.magnitude <= 0 && engineAudioSource.clip != idle) { engineAudioSource.clip = idle; engineAudioSource.Play (); } } } <file_sep>/Assets/GameManager.cs using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { public Color[] tankColours = new Color[] { new Color(0,0,0), new Color(0.1f,0.5f,0.2f), new Color(0.5f,0.1f,0.2f), new Color(0.5f,0,0), new Color(0,0.5f,0.5f)}; public GameObject pickup; public GameObject badPickup; public Vector3 spawnValues; public int pickupCount; public int badPickupCount; public int goalCount; public float spawnWait; public float startWait; public float waveWait; public AudioSource music; public float restartTimer; // Use this for initialization void Start () { StartCoroutine (SpawnWaves ()); var controllers = Input.GetJoystickNames (); var resource = Resources.Load<GameObject>("Player"); for (int i = 1; i <= controllers.Length; ++i) { var playerClone = (GameObject)Instantiate(resource, new Vector3(5*i,0,1), new Quaternion()); var pc = playerClone.GetComponent<PlayerController> (); pc.playerNumber = i; pc.tankColour = tankColours[i]; } CreateLevel (); } void Update() { var players = GameObject.FindGameObjectsWithTag ("Player"); if (players.Length == 1 && restartTimer == 0) { restartTimer = Time.time + 30; } if (players.Length == 1 && restartTimer != 0 && restartTimer < Time.time) { SceneManager.LoadScene ("Arena"); } } Vector3 PointInLevel() { return new Vector3(Random.Range(-40.0f, 40.0f), 0, Random.Range(-40.0f, 40.0f)); } Vector3 RandomDirection() { return new Vector3(Random.Range(-1.0f, 1.0f), 0, Random.Range(-1.0f, 1.0f)); } string[] duneResources = new string[] { "Dune1", "Dune2", "Concrete", "Crater01" }; string[] treeResources = new string[] { "Cactus", "Tree", "PalmTree" }; void CreateLevel () { // Dunes for (int i = 0; i < 20; ++i) { var resource = Resources.Load (duneResources [Random.Range (0, duneResources.Length)]); Instantiate(resource, PointInLevel(), Quaternion.LookRotation(RandomDirection())); } // Tree for (int i = 0; i < 10; ++i) { var resource = Resources.Load (treeResources [Random.Range (0, treeResources.Length)]); Instantiate(resource, PointInLevel(), Quaternion.LookRotation(RandomDirection())); } } IEnumerator SpawnWaves () { yield return new WaitForSeconds (startWait); { for (int i = 0; i < pickupCount; i++) { Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, Random.Range (-spawnValues.z, spawnValues.z)); Quaternion spawnRotation = Quaternion.identity; Instantiate (pickup, spawnPosition, spawnRotation); yield return new WaitForSeconds (spawnWait); } for (int i = 0; i < badPickupCount; i++) { Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, Random.Range (-spawnValues.z, spawnValues.z)); Quaternion spawnRotation = Quaternion.identity; Instantiate (badPickup, spawnPosition, spawnRotation); yield return new WaitForSeconds (spawnWait); } //yield return new WaitForSeconds (waveWait); } } } <file_sep>/Assets/Turret.cs using UnityEngine; using System.Collections; public class Turret : MonoBehaviour { float lastShot; // Use this for initialization void Start () { } // Update is called once per frame void Update () { var playerController = GetComponent<PlayerController> (); var audio = GetComponent<Audio> (); var turret = transform.Find("Tank/TankRenderers/TankTurret"); var turretFire = transform.Find("Tank/TankRenderers/TankTurret/Fire"); var dir = new Vector3(playerController.rightStick.x, 0, -playerController.rightStick.z); if (dir.sqrMagnitude > 0.1) { //Debug.Log(string.Format("Right: x= {0} z={1} ", playerController.rightStick.x, playerController.rightStick.z)); turret.rotation = Quaternion.LookRotation (dir); } var health = GetComponent<TankHealth> (); if (health.ammo > 0 && playerController.rightTrigger > 0.5 && lastShot + 0.5 < Time.time) { audio.Fire (); lastShot = Time.time; health.ammo -= 1; var shell = Resources.Load<GameObject>("Shell"); var shellInstane = (GameObject)Instantiate(shell, turretFire.position, new Quaternion()); var shellComponent = shellInstane.GetComponent<Shell> (); shellComponent.owner = gameObject; var shellRigidbody = shellInstane.GetComponent<Rigidbody> (); shellRigidbody.velocity = turret.forward * 60; shellRigidbody.rotation = Quaternion.LookRotation (turret.forward); } } } <file_sep>/Assets/TankHealth.cs using UnityEngine; using System.Collections; public class TankHealth : MonoBehaviour { public float health = 100; public int ammo = 0; // Use this for initialization void Start () { health = 100; } void OnCollisionEnter(Collision collision) { if (collision.gameObject.name.Contains ("Shell") && collision.gameObject.GetComponent<Shell>().owner != gameObject && collision.relativeVelocity.sqrMagnitude > 1000) { health -= (collision.relativeVelocity.sqrMagnitude/220.0f); Debug.Log ("Hit: " + health); if (health < 0) { Debug.Log ("Dead"); Destroy (gameObject); } } if (collision.relativeVelocity.sqrMagnitude < 1000 && collision.gameObject.name.Contains ("Shell")) { ammo += 1; //Destroy (collision.gameObject); collision.gameObject.SetActive(false); } } } <file_sep>/Assets/PlayerController.cs using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { public int playerNumber = 0; public Vector3 leftStick; public Vector3 rightStick; public float leftTrigger; public float rightTrigger; public Color tankColour; public bool aButton; public int ballCount = 0; // Use this for initialization void Start () { MeshRenderer[] renderers = GetComponentsInChildren<MeshRenderer> (); // Go through all the renderers... for (int i = 0; i < renderers.Length; i++) { // ... set their material color to the color specific to this tank. renderers[i].material.color = tankColour; } ballCount = 0; // SetCountText (); } // Update is called once per frame void Update () { var i = playerNumber; leftStick = new Vector3 (Input.GetAxis ("L_XAxis_"+i), 0, Input.GetAxis ("L_YAxis_"+i)); rightStick = new Vector3 (Input.GetAxis ("R_XAxis_"+i), 0, Input.GetAxis ("R_YAxis_"+i)); leftTrigger = Input.GetAxis ("TriggersL_"+i); rightTrigger = Input.GetAxis ("TriggersR_"+i); aButton = Input.GetButtonDown ("A_"+i); } void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag ("Pick Up")) { Destroy (other.gameObject.GetComponent<Rigidbody>()); other.gameObject.SetActive (false); ballCount = ballCount + 1; // SetCountText (); } // if (other.gameObject.CompareTag ("Bad Pickup")) { // other.gameObject.SetActive (false); // } // if (other.gameObject.CompareTag ("Goal")) { // } } <file_sep>/Assets/Movement.cs using UnityEngine; using System.Collections; public class Movement : MonoBehaviour { public float distToGround; public bool isGrounded; public int speedMultiplier; // Use this for initialization void Start () { } // Update is called once per frame void Update () { var playerController = GetComponent<PlayerController> (); distToGround = (playerController.GetComponent<Collider>().bounds.extents.y + 0.1f); isGrounded = Physics.Raycast(transform.position, -Vector3.up, distToGround); var rb = GetComponent<Rigidbody> (); var movement = new Vector3 (playerController.leftStick.x, 0, -playerController.leftStick.z); speedMultiplier = 30; if (isGrounded) { speedMultiplier = 25; if (movement.sqrMagnitude > 0.1) transform.rotation = Quaternion.LookRotation(movement); if (playerController.aButton) { rb.AddForce(new Vector3(0, 100, 0) * 25); } } rb.AddForce (movement * 40); var turret = transform.Find("Tank/TankRenderers/TankTurret"); if (playerController.rightStick.sqrMagnitude > 0.1) { //Debug.Log(string.Format("Right: x= {0} z={1} ", playerController.rightStick.x, playerController.rightStick.z)); var dir = new Vector3(playerController.rightStick.x, 0, -playerController.rightStick.z); turret.rotation = Quaternion.LookRotation (dir); } } } <file_sep>/Assets/TowerGenerator.cs using UnityEngine; using System.Collections; public class TowerGenerator : MonoBehaviour { void Start () { // var towerResource = Resources.Load("Tower"); // int i = 0; // while (i < 5) { // Quaternion spawnRotation = Quaternion.identity; // var tower = (GameObject)Instantiate(towerResource, new Vector3(5*i,0,1), new Quaternion()); // tower.transform.position = Vector3.MoveTowards(tower.transform.position, new Vector3(0, 0, 0) + transform.position, 1.0f); // ++i; // } } // Update is called once per frame void Update () { } } <file_sep>/Assets/Hud.cs using UnityEngine; using System.Collections; using UnityEngine.UI; using System.Text; using System.Linq; public class Hud : MonoBehaviour { public Text score; public GameObject[] players; public UnityEngine.UI.Text[] scores; public UnityEngine.UI.Text winner; // Use this for initialization void Start () { var children = GetComponentsInChildren<UnityEngine.UI.Text> (); scores = children.Where(s => s.name.Contains("Score")).ToArray(); foreach (var s in scores) { s.gameObject.SetActive (false); } } // Update is called once per frame void Update () { players = GameObject.FindGameObjectsWithTag ("Player"); foreach (var player in players) { var playerController = player.GetComponent<PlayerController> (); var health = player.GetComponent<TankHealth> (); var pi = playerController.playerNumber - 1; scores [pi].gameObject.SetActive (true); scores [pi].text = string.Format("Health: {0}\nAmmo: {1}\n", Mathf.Ceil(health.health), health.ammo); scores [pi].color = playerController.tankColour; } if (players.Length == 1 && winner != null) { //Debug.Log ("One player"); var playerController = players[0].GetComponent<PlayerController> (); winner.color = playerController.tankColour; winner.text = string.Format ("Player {0} Wins!", playerController.playerNumber); } else winner.text = ""; } }
6ef52c9c0367d6c4228d53b2ced058b8dc6c8d87
[ "Markdown", "C#" ]
11
C#
pebblecode/tanks-for-nothing
fbb056e99ee2baf0d192e07867322fa67c3b1986
a39590e8da299cd83986055440bf31d1b58214f9
refs/heads/master
<repo_name>Juilee2610/Java<file_sep>/trip application/src/main/Main.java package main; import java.util.Scanner; import serviceUtil.Service; import util.Util; public class Main { public static void main(String[] args) throws InterruptedException { Scanner scanner = new Scanner(System.in); System.out.println("Welcome to idk Car application\n\tYOUR RIDE YOUR CHOICE"); String nationality = Util.getString("Please enter your nationality foreign or regional"); System.out.println("Enter your choice"); System.out.println("1.Find ride\n2.Offer ride\n3.About us\n4.Quit"); //enter your choice while(true) { int choice = Util.getInteger("Enter your choice"); if(nationality.equalsIgnoreCase("foreign")) { System.out.println("Enter your passport id"); String information = scanner.nextLine(); System.out.println("Your passport is "+ information); Thread.sleep(2000); } else if(nationality.equalsIgnoreCase("regional")) { } else { System.out.println("Please enter valid nationality"); continue; } //check for choice if(choice==1) { Service.menu1(); break; } else if(choice==2) { Service.menu2(); break; } else if(choice==3) { System.out.println("The reckless years of one’s 20s are perhaps the most illuminating ones. There’s plenty to be learnt, a bevvy of experiences that temper you into the man/woman you become later. However, as you reach the respectable figure of 30, there is an air of nostalgia of leaving your youthful days behind. Hence, as the number of candles on my birthday cake was about to reach 30, my mind started wandering and I started looking for ways to etch a permanent mark on my life. Wanderlust struck me and all I wanted to do was get out of my comfort zone.\r\n" + "\r\n" + "Here are ten of the best road trips you can take"); } else if(choice ==4) { System.out.println("Quitting from system"); break; } else { System.out.println("Enter valid option"); } } } } <file_sep>/BankApplication/src/Transaction.java import java.util.Scanner; public class Transaction extends Account{ Transaction(String CN, int CI) { super(CN, CI); // TODO Auto-generated constructor stub } public static void main(String args[]) { Scanner scan = new Scanner(System.in); System.out.println("Enter you name"); String name = scan.nextLine(); System.out.println("Enter customer Id"); int id = scan.nextInt(); System.out.println("Welcome "+name); Account obj = new Account(name,id); String option; do { System.out.println("Enter the option "); System.out.println("A. View your savings"); System.out.println("B. Deposit money"); System.out.println("C. Withfraw money"); System.out.println("D. View Previous transaction"); System.out.println("E. Exit"); option = scan.next(); switch(option){ case "A":{ System.out.println("Your current balance is "+Math.abs(obj.balance)); break; } case "B":{ System.out.println("Enter the amount to be deposited: "); int amount = scan.nextInt(); obj.deposit(amount); System.out.println("The amount has been deposited"); break; } case "C":{ System.out.println("Enter the amount to be deposited: "); int amount = scan.nextInt(); obj.withdraw(amount); break; } case "D":{ obj.previousTransaction(); break; } case "E":{ System.out.println("Thank you for visiting"); break; } default: System.out.println("Please enter valid option"); break; } } while(option!="E"); } }
0a28a56515b40ae30fa9a6fdd4b8e300cd5f193d
[ "Java" ]
2
Java
Juilee2610/Java
17b60b2411e70c27b2f1600e402d166ede7048e5
c403052fdb2add78f2ae26c58a39c29631674a68
refs/heads/master
<repo_name>coby193/Ph20<file_sep>/Ph20Set3Oscillator.py import math, numpy, sys import matplotlib.pyplot as pplot # Exciting change # Read input, optional last argument plots errors instead of values filename = sys.argv[1] initialx = float(sys.argv[2]) initialv = float(sys.argv[3]) step = float(sys.argv[4]) cycles = int(sys.argv[5]) plottype = sys.argv[6] def nextx(oldx, oldv, h): return oldx + h*oldv def nextv(oldx, oldv, h): return oldv - h*oldx def oscillate(startx, startv, h, laps): counter = 0 position = 0 x = [startx] v = [startv] time = [0] while(counter < laps): x.append(nextx(x[position],v[position],h)) v.append(nextv(x[position],v[position],h)) position += 1 time.append(position*h) if(x[position] >= startx and x[position-1] < startx): counter += 1 return [x,v,time] def computeimplicites(startx, startv, h, laps): counter = 0 p = 0 x = [startx] v = [startv] time = [0] while(counter < laps): v.append((v[p]-h*x[p])/(1+h*h)) x.append((h*v[p] + x[p])/(1+h*h)) p += 1 time.append(p*h) if(x[p] >= startx and x[p-1] < startx): counter += 1 return [x,v,time] def symplecticeuler(startx, startv, h, laps): counter = 0 p = 0 x = [startx] v = [startv] time = [0] while(counter < laps): v.append((1-h*h)*v[p] - h*x[p]) x.append(x[p] + h*v[p]) p += 1 time.append(p*h) if(x[p] >= startx and x[p-1] < startx): counter += 1 return [x,v,time] def computereals(xamp,vamp,omega,h,steps): x = [] v = [] t = [] for i in range(steps): x.append(xamp*math.sin(omega*h*i)) v.append(vamp*math.cos(omega*h*i)) t.append(h*i) return [x,v,t] if(plottype == "plot"): numericals = oscillate(initialx, initialv, step, cycles) pplot.plot(numericals[2],numericals[0],c='g') pplot.plot(numericals[2],numericals[1],c='r') pplot.title("Position (green) and velocity (red) for a mass on a spring") pplot.xlabel("time") pplot.ylabel("Position/Velocity") pplot.savefig(filename) elif(plottype == "errors"): numericals = oscillate(initialx, initialv, step, cycles) reals = computereals(1,1,1,step,len(numericals[0])) errors = [[],[],[]] errors[0] = [reals[0][i] - numericals[0][i] for i in range(len(reals[0]))] errors[1] = [reals[1][i] - numericals[1][i] for i in range(len(reals[1]))] errors[2] = reals[2] pplot.plot(errors[2],errors[0],c='g') pplot.plot(errors[2],errors[1],c='r') pplot.title("Position (green) and velocity (red) error in euler's method") pplot.xlabel("time") pplot.ylabel("errors") pplot.savefig(filename) elif(plottype == "hcomparison"): thingstoplot = [[],[]] hs = [step, step/2, step/4, step/8, step/16] for i in range(len(hs)): numerical = oscillate(initialx, initialv, hs[i], cycles) real = computereals(1,1,1,hs[i],len(numerical[0])) error = [[],[],[]] error[0] = [real[0][i] - numerical[0][i] for i in range(len(real[0]))] error[1] = [real[1][i] - numerical[1][i] for i in range(len(real[1]))] thingstoplot[0].append(max(error[0])) thingstoplot[1].append(max(error[1])) pplot.plot(hs,thingstoplot[0],c='g') pplot.plot(hs,thingstoplot[1],c='r') pplot.title("Maximum error vs step size, xerror in green and verror in red") pplot.xlabel("Step size") pplot.ylabel("Maximum error") pplot.savefig(filename) elif(plottype == "energy"): numericals = oscillate(initialx, initialv, step, cycles) energies = [numericals[0][i]**2 + numericals[1][i]**2 for i in range(len(numericals[0]))] pplot.plot(numericals[2], energies) pplot.title("Evolution of total energy over time, should be constant") pplot.xlabel("Time") pplot.ylabel("Normalized total energy") pplot.savefig(filename) elif(plottype == "impliciterror"): numericals = oscillate(initialx, initialv, step, cycles) implicites = computeimplicites(initialx,initialv,step,cycles) reals = computereals(1,1,1,step,len(numericals[0])) impreals = computereals(1,1,1,step,len(implicites[0])) errors = [[],[],[],[]] errors[0] = [reals[0][i] - numericals[0][i] for i in range(len(reals[0]))] errors[1] = [reals[1][i] - numericals[1][i] for i in range(len(reals[1]))] errors[2] = [impreals[0][i] - implicites[0][i] for i in range(len(impreals[0]))] errors[3] = [impreals[1][i] - implicites[1][i] for i in range(len(impreals[1]))] pplot.plot(reals[2],errors[0],c='g') pplot.plot(reals[2],errors[1],c='r') pplot.plot(impreals[2],errors[2],c='c') pplot.plot(impreals[2],errors[3],c='y') pplot.title("Explicit position (g), velocity (r), Implicity position(b), velocity(y) errors") pplot.xlabel("time") pplot.ylabel("errors") # pplot.axis([0,35,-.002,.002]) pplot.savefig(filename) elif(plottype == "expphase"): numericals = oscillate(initialx, initialv, step, cycles) pplot.plot(numericals[0],numericals[1],c='g') pplot.title("Position vs Velocity for explicit Euler method") pplot.xlabel("Position") pplot.ylabel("Velocity") pplot.savefig(filename) elif(plottype == "impphase"): implicites = computeimplicites(initialx, initialv, step, cycles) pplot.plot(implicites[0],implicites[1],c='g') pplot.title("Position vs Velocity for implicit Euler method") pplot.xlabel("Position") pplot.ylabel("Velocity") pplot.savefig(filename) elif(plottype == "symphase"): positions = symplecticeuler(initialx, initialv, step, cycles) pplot.plot(positions[0],positions[1],c='g') pplot.title("Position vs Velocity for symplectic Euler method") pplot.xlabel("Position") pplot.ylabel("Velocity") pplot.savefig(filename) elif(plottype == "symenergy"): positions = symplecticeuler(initialx, initialv, step, cycles) energies = [positions[0][i]**2 + positions[1][i]**2 for i in range(len(positions[0]))] pplot.plot(positions[2], energies) pplot.title("Evolution of total energy over time for symplectic Euler method") pplot.xlabel("Time") pplot.ylabel("Normalized total energy") pplot.savefig(filename) elif(plottype == "phasecheck"): symplects = symplecticeuler(initialx,initialv,step,1000*cycles) reals = computereals(1,1,1,step,len(symplects[0])) length = len(symplects[0]) start = int(length/1000)*999 pplot.plot(symplects[2][start:],symplects[0][start:],c='g') pplot.plot(reals[2][start:],reals[0][start:],c='r') pplot.title("Analytic solution (red) vs symplectic euler method (green), cycles") pplot.xlabel("Time") pplot.ylabel("Position") pplot.savefig(filename) else: print "6th command must be the type of plot, 'plot', 'errors', 'energy', 'implicites', 'expphase', 'symenergy', 'symphase', 'phasecheck', or 'hcomparison'" <file_sep>/README.md # Ph20 Ph 20 <file_sep>/Makefile Ph20Set4Latex.tex: Ph20Set3OscillatorFigure1.png Ph20Set3ErrorPlot.png Ph20Set3hcomparison.png Ph20Set3Energies.png Ph20Set3ImplicitErrors.png Ph20Set3ExplicitPhase.png Ph20Set3ImplicitPhase.png Ph20Set3SymplecticPhase.png Ph20Set3SymplecticEnergy1.png Ph20Set3SymplecticEnergy2.png Ph20Set3PhaseComparison.png pdflatex Ph20Set4Latex.tex Ph20Set3OscillatorFigure1.png: Makefile Ph20Set3Oscillator.py python Ph20Set3Oscillator.py Ph20Set3OscillatorFigure1.png 0 1 .0001 5 plot Ph20Set3ErrorPlot.png: Makefile Ph20Set3Oscillator.py python Ph20Set3Oscillator.py Ph20Set3ErrorPlot.png 0 1 .0001 5 errors Ph20Set3hcomparison.png: Makefile Ph20Set3Oscillator.py python Ph20Set3Oscillator.py Ph20Set3hcomparison.png 0 1 .0016 5 hcomparison Ph20Set3Energies.png: Makefile Ph20Set3Oscillator.py python Ph20Set3Oscillator.py Ph20Set3Energies.png 0 1 .0001 5 energy Ph20Set3ImplicitErrors.png: Makefile Ph20Set3Oscillator.py python Ph20Set3Oscillator.py Ph20Set3ImplicitErrors.png 0 1 .0001 5 impliciterror Ph20Set3ExplicitPhase.png: Makefile Ph20Set3Oscillator.py python Ph20Set3Oscillator.py Ph20Set3ImplicitPhase.png 0 1 .01 5 expphase Ph20Set3ImplicitPhase.png: Makefile Ph20Set3Oscillator.py python Ph20Set3Oscillator.py Ph20Set3ImplicitPhase.png 0 1 .01 5 impphase Ph20Set3SymplecticPhase.png: Makefile Ph20Set3Oscillator.py python Ph20Set3Oscillator.py Ph20Set3SymplecticPhase.png 0 1 .01 5 symphase Ph20Set3SymplecticEnergy1.png: Makefile Ph20Set3Oscillator.py python Ph20Set3Oscillator.py Ph20Set3SymplecticEnergy1.png 0 1 .01 5 symenergy Ph20Set3SymplecticEnergy2.png: Makefile Ph20Set3Oscillator.py python Ph20Set3Oscillator.py Ph20Set3SymplecticEnergy2.png 0 1 .1 5 symenergy Ph20Set3PhaseComparison.png: Makefile Ph20Set3Oscillator.py python Ph20Set3Oscillator.py Ph20Set3PhaseComparison.png 0 1 .01 5 phasecheck
317b7b348608cd50f470d2839515ee305f36766e
[ "Markdown", "Python", "Makefile" ]
3
Python
coby193/Ph20
302a6f4c7ce6d7a6635798d7532f6cac9c2c7bd8
5601b6ecd51ea7fa0c3fbfb3c208bd0c42a5d8b5
refs/heads/master
<file_sep>package com.example.mehmetsabir.puzzlegamekotlin import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.Button import java.util.* class CustomAdapter(buttons: ArrayList<Button>, columnWidth: Int, columnHeight: Int) : BaseAdapter() { private var mButtons: ArrayList<Button>? = null private var mColumnWidth: Int = 0 private var mColumnHeight: Int = 0 init { mButtons = buttons mColumnWidth =columnWidth mColumnHeight = columnHeight } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val button: Button = if (convertView == null) { mButtons?.get(position)!! } else { convertView as Button } val params = android.widget.AbsListView.LayoutParams(mColumnWidth, mColumnHeight) button.layoutParams = params return button } override fun getItem(position: Int): Any { return mButtons?.get(position)!! } override fun getItemId(position: Int): Long { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getCount(): Int { return mButtons?.size!! } }<file_sep>package com.example.mehmetsabir.puzzlegamekotlin import android.annotation.SuppressLint import android.content.Context import android.os.Build import android.support.annotation.RequiresApi import android.support.constraint.solver.widgets.Helper import android.util.AttributeSet import android.view.GestureDetector import android.view.MotionEvent import android.widget.GridView class GestureDetectGridView : GridView { private var gDetector: GestureDetector? = null private var mFlingConfirmed = false private var mTouchX: Float = 0.toFloat() private var mTouchY: Float = 0.toFloat() private val SWIPE_MIN_DISTANCE = 100 private val SWIPE_MAX_OFF_PATH = 100 private val SWIPE_THRESHOLD_VELOCITY = 100 constructor(context: Context) : super(context) { init(context) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(context) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(context) } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super( context, attrs, defStyleAttr, defStyleRes ) { init(context) } private fun init(context: Context) { gDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() { override fun onDown(event: MotionEvent): Boolean { return true } override fun onFling( e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float ): Boolean { val position = this@GestureDetectGridView.pointToPosition(Math.round(e1.x), Math.round(e1.y)) if (Math.abs(e1.y - e2.y) > SWIPE_MAX_OFF_PATH) { if (Math.abs(e1.x - e2.x) > SWIPE_MAX_OFF_PATH || Math.abs(velocityY) < SWIPE_THRESHOLD_VELOCITY) { return false } if (e1.y - e2.y > SWIPE_MIN_DISTANCE) { HelperPuzzle.instance.moveTiles(context, PuzzleActivity.up, position) } else if (e2.y - e1.y > SWIPE_MIN_DISTANCE) { HelperPuzzle.instance.moveTiles(context, PuzzleActivity.down, position) } } else { if (Math.abs(velocityX) < SWIPE_THRESHOLD_VELOCITY) { return false } if (e1.x - e2.x > SWIPE_MIN_DISTANCE) { HelperPuzzle.instance.moveTiles(context, PuzzleActivity.left, position) } else if (e2.x - e1.x > SWIPE_MIN_DISTANCE) { HelperPuzzle.instance.moveTiles(context, PuzzleActivity.right, position) } } return super.onFling(e1, e2, velocityX, velocityY) } }) } override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { val action = ev.actionMasked gDetector?.onTouchEvent(ev) if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { mFlingConfirmed = false } else if (action == MotionEvent.ACTION_DOWN) { mTouchX = ev.x mTouchY = ev.y } else { if (mFlingConfirmed) { return true } val dX = Math.abs(ev.x - mTouchX) val dY = Math.abs(ev.y - mTouchY) if (dX > SWIPE_MIN_DISTANCE || dY > SWIPE_MIN_DISTANCE) { mFlingConfirmed = true return true } } return super.onInterceptTouchEvent(ev) } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(ev: MotionEvent): Boolean { return gDetector?.onTouchEvent(ev)!! } }<file_sep>package com.example.mehmetsabir.puzzlegamekotlin import android.content.Context import android.os.Build import android.os.Bundle import android.support.annotation.RequiresApi import android.support.v7.app.AppCompatActivity import android.view.ViewTreeObserver import android.view.WindowManager import java.util.* class PuzzleActivity() : AppCompatActivity() { var level: String? = null var numberOfPicture: Int? = 0 var bundle: Bundle? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_puzzle) window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN) getS() init() scramble() setDimensions() } fun getS() { bundle = intent.extras level = bundle?.getString("level") numberOfPicture = bundle?.getInt("numberOfPicture") } private fun init() { mGridView = findViewById<GestureDetectGridView>(R.id.grid) mGridView?.numColumns = COLUMNS tileList = arrayOfNulls<String>(DIMENSIONS) for (i in 0 until DIMENSIONS) { tileList!![i] = i.toString() } } private fun scramble() { var index: Int var temp: String val random = Random() for (i in tileList?.size!! - 1 downTo 1) { index = random.nextInt(i + 1) temp = tileList!![index]!! tileList!![index] = tileList!![i] tileList!![i] = temp } } private fun setDimensions() { val vto = mGridView?.getViewTreeObserver() vto?.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) override fun onGlobalLayout() { mGridView?.viewTreeObserver?.removeOnGlobalLayoutListener(this) val displayWidth = mGridView?.measuredWidth val displayHeight = mGridView?.measuredHeight val statusbarHeight = getStatusBarHeight(applicationContext) val requiredHeight = displayHeight!! - statusbarHeight mColumnWidth = displayWidth!! / COLUMNS mColumnHeight = requiredHeight / COLUMNS HelperPuzzle.instance.display(applicationContext, intent) } }) } private fun getStatusBarHeight(context: Context): Int { var result = 0 val resourceId = context.resources.getIdentifier( "status_bar_height", "dimen", "android" ) if (resourceId > 0) { result = context.resources.getDimensionPixelSize(resourceId) } return result } fun isSolved(): Boolean { var solved = false for (i in tileList?.indices!!) { if (tileList!![i] == i.toString()) { solved = true } else { solved = false break } } return solved } companion object { val COLUMNS = 3 val DIMENSIONS = 3 * COLUMNS const val up = "up" const val down = "down" const val left = "left" const val right = "right" var tileList: Array<String?>? = null var mGridView: GestureDetectGridView? = null var mColumnWidth: Int = 0 var mColumnHeight: Int = 0 } } <file_sep>package com.example.mehmetsabir.puzzlegamekotlin import android.content.Context import android.content.Intent import android.widget.Button import android.widget.Toast import java.util.* class HelperPuzzle { private var list: java.util.ArrayList<Int>? = null private var bundleIntent: Intent? = null fun swap(context: Context, currentPosition: Int, swap: Int) { val newPosition = PuzzleActivity.tileList!![currentPosition + swap] PuzzleActivity.tileList!![currentPosition + swap] = PuzzleActivity.tileList!![currentPosition] PuzzleActivity.tileList!![currentPosition] = newPosition display(context, this.bundleIntent!!) if (PuzzleActivity().isSolved()) Toast.makeText(context, "YOU WIN!", Toast.LENGTH_SHORT).show() } fun display(context: Context, bundleIntent: Intent) { this.bundleIntent = bundleIntent val buttons = java.util.ArrayList<Button>() var button: Button list = getResId(context, bundleIntent.extras.getString("level"), bundleIntent.extras.getInt("numberOfPicture")); for (i in PuzzleActivity.tileList?.indices!!) { button = Button(context) if (PuzzleActivity.tileList!![i] == "0") button.setBackgroundResource(list!![0]) else if (PuzzleActivity.tileList!![i] == "1") button.setBackgroundResource(list!![1]) else if (PuzzleActivity.tileList!![i] == "2") button.setBackgroundResource(list!![2]) else if (PuzzleActivity.tileList!![i] == "3") button.setBackgroundResource(list!![3]) else if (PuzzleActivity.tileList!![i] == "4") button.setBackgroundResource(list!![4]) else if (PuzzleActivity.tileList!![i] == "5") button.setBackgroundResource(list!![5]) else if (PuzzleActivity.tileList!![i] == "6") button.setBackgroundResource(list!![6]) else if (PuzzleActivity.tileList!![i] == "7") button.setBackgroundResource(list!![7]) else if (PuzzleActivity.tileList!![i] == "8") button.setBackgroundResource(list!![8]) buttons.add(button) } PuzzleActivity.mGridView?.adapter = CustomAdapter( buttons, PuzzleActivity.mColumnWidth, PuzzleActivity.mColumnHeight ) } fun getResId(context: Context, level: String, randomNumber: Int): java.util.ArrayList<Int> { val images: java.util.ArrayList<Int> = java.util.ArrayList<Int>(); for (i in 1..9) { val randomDrawableIndexWithTwoDigits: String = String.format(Locale.ENGLISH, "%02d", randomNumber) val indexWithTwoDigits: String = String.format(Locale.ENGLISH, "%02d", i) images.add( context.resources.getIdentifier( "ic_" + level + "_" + randomDrawableIndexWithTwoDigits + "_" + indexWithTwoDigits, "drawable", context.packageName ) ) } return images } fun moveTiles(context: Context, direction: String, position: Int) { // Upper-left-corner tile if (position == 0) { if (direction == PuzzleActivity.right) swap(context, position, 1) else if (direction == PuzzleActivity.down) swap(context, position, PuzzleActivity.COLUMNS) else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show() // Upper-center tiles } else if (position > 0 && position < PuzzleActivity.COLUMNS - 1) { if (direction == PuzzleActivity.left) swap(context, position, -1) else if (direction == PuzzleActivity.down) swap(context, position, PuzzleActivity.COLUMNS) else if (direction == PuzzleActivity.right) swap(context, position, 1) else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show() // Upper-right-corner tile } else if (position == PuzzleActivity.COLUMNS - 1) { if (direction == PuzzleActivity.left) swap(context, position, -1) else if (direction == PuzzleActivity.down) swap(context, position, PuzzleActivity.COLUMNS) else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show() // Left-side tiles } else if (position > PuzzleActivity.COLUMNS - 1 && position < PuzzleActivity.DIMENSIONS - PuzzleActivity.COLUMNS && position % PuzzleActivity.COLUMNS == 0 ) { if (direction == PuzzleActivity.up) swap(context, position, -PuzzleActivity.COLUMNS) else if (direction == PuzzleActivity.right) swap(context, position, 1) else if (direction == PuzzleActivity.down) swap(context, position, PuzzleActivity.COLUMNS) else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show() // Right-side AND bottom-right-corner tiles } else if (position == PuzzleActivity.COLUMNS * 2 - 1 || position == PuzzleActivity.COLUMNS * 3 - 1) { if (direction == PuzzleActivity.up) swap(context, position, -PuzzleActivity.COLUMNS) else if (direction == PuzzleActivity.left) swap(context, position, -1) else if (direction == PuzzleActivity.down) { // Tolerates only the right-side tiles to swap downwards as opposed to the bottom- // right-corner tile. if (position <= PuzzleActivity.DIMENSIONS - PuzzleActivity.COLUMNS - 1) swap( context, position, PuzzleActivity.COLUMNS ) else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show() } else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show() // Bottom-left corner tile } else if (position == PuzzleActivity.DIMENSIONS - PuzzleActivity.COLUMNS) { if (direction == PuzzleActivity.up) swap(context, position, -PuzzleActivity.COLUMNS) else if (direction == PuzzleActivity.right) swap(context, position, 1) else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show() // Bottom-center tiles } else if (position < PuzzleActivity.DIMENSIONS - 1 && position > PuzzleActivity.DIMENSIONS - PuzzleActivity.COLUMNS) { if (direction == PuzzleActivity.up) swap(context, position, -PuzzleActivity.COLUMNS) else if (direction == PuzzleActivity.left) swap(context, position, -1) else if (direction == PuzzleActivity.right) swap(context, position, 1) else Toast.makeText(context, "Invalid move", Toast.LENGTH_SHORT).show() // Center tiles } else { if (direction == PuzzleActivity.up) swap(context, position, -PuzzleActivity.COLUMNS) else if (direction == PuzzleActivity.left) swap(context, position, -1) else if (direction == PuzzleActivity.right) swap(context, position, 1) else swap(context, position, PuzzleActivity.COLUMNS) } } companion object { private var INSTANCE: HelperPuzzle? = null val instance: HelperPuzzle get() { if (INSTANCE == null) { INSTANCE = HelperPuzzle() } return INSTANCE as HelperPuzzle } } }
c3ad0d2885da682ab9a90a0fa1844216308c6170
[ "Kotlin" ]
4
Kotlin
mskahraman/GameForSmartAlarm
89fe717d5de1d7763c9f2d267725397eadab158e
ed94efeef3f7ea983e328daa90d36e003c6a99b5
refs/heads/master
<repo_name>NicosaurusRex99/FunTNT<file_sep>/src/main/java/naturix/funtnt/proxy/CommonProxy.java package naturix.funtnt.proxy; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod.EventBusSubscriber public class CommonProxy { public void preInit(FMLPreInitializationEvent e) { } public void init(FMLInitializationEvent e) { } public void postInit(FMLPostInitializationEvent e) { } public void registerItemRenderer(Item itemBlock, int i, String name) { } }
a397ceecca73be9b6635f248bc55b8214a08e985
[ "Java" ]
1
Java
NicosaurusRex99/FunTNT
54388485963d169f8c045bdcdcdeeb93df2f2c2a
5aa5e80c00b9b13281d7d395dd5d211ed24b43b1
refs/heads/master
<file_sep>/* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <errno.h> #include <limits.h> #include <sys/types.h> #if defined(_MSC_VER) #include <windows.h> #include "googleapis/base/windows_compatability.h" #else #include <unistd.h> #endif #if __APPLE__ #include "TargetConditionals.h" #if !TARGET_OS_IPHONE #define HAVE_LIBPROC #include <libproc.h> #endif #endif #include <string> using std::string; #include "googleapis/client/util/program_path.h" namespace googleapis { namespace client { #ifdef HAVE_LIBPROC std::string GetCurrentProgramFilenamePath() { // OSX version char buf[PROC_PIDPATHINFO_MAXSIZE]; int ret = proc_pidpath(getpid(), buf, sizeof(buf)); if (ret <= 0) { // TODO(user): Fix the API to return the path and a status. Logging the // error and returning a bad path is useless. // LOG(ERROR) << "Could not get pidpath"; return "./"; } return std::string(buf); } #elif defined(_MSC_VER) std::string GetCurrentProgramFilenamePath() { // Windows version char* value = NULL; if (_get_pgmptr(&value)) return "./"; // Convert windows path to unix style path so our public interface // is consistent, especially when we operate on paths. return FromWindowsPath(value); } #else std::string GetCurrentProgramFilenamePath() { // Linux (default) version std::string path_to_proc_info("/proc/"); path_to_proc_info.append(std::to_string(getpid())).append("/exe"); char buf[PATH_MAX]; int bytes = readlink(path_to_proc_info.c_str(), buf, sizeof(buf)); if (bytes <= 0) { // LOG(ERROR) << "Could not read " << path_to_proc_info; return "./"; } return std::string(buf, bytes); } #endif } // namespace client } // namespace googleapis
752d26ecdba2229f14f1000c05a84eadb60c0e57
[ "C++" ]
1
C++
sulian0/google-api-cpp-client
eb942f15b496c92d136a70cbc963ed70e47793fb
820d05fce30e82a5bd6462fc4708398b31269c6a
refs/heads/master
<file_sep>import { Card } from "react-bootstrap"; import ImageEvent from "./ImageEvent.jpeg"; export const Gallery = () => { return ( <div> <div>Gallery</div> <div id="cards"> <Card style={{ width: "18rem" }}> <Card.Body> <img style={{ width: "15rem" }} src={ImageEvent} /> </Card.Body> </Card> <Card style={{ width: "18rem" }}> <Card.Body> <img style={{ width: "15rem" }} src={ImageEvent} /> </Card.Body> </Card> <Card style={{ width: "18rem" }}> <Card.Body> <img style={{ width: "15rem" }} src={ImageEvent} /> </Card.Body> </Card> <Card style={{ width: "18rem" }}> <Card.Body> <img style={{ width: "15rem" }} src={ImageEvent} /> </Card.Body> </Card> {/* second image group */} <Card style={{ width: "18rem" }}> <Card.Body> <img style={{ width: "15rem" }} src={ImageEvent} /> </Card.Body> </Card> <Card style={{ width: "18rem" }}> <Card.Body> <img style={{ width: "15rem" }} src={ImageEvent} /> </Card.Body> </Card> <Card style={{ width: "18rem" }}> <Card.Body> <img style={{ width: "15rem" }} src={ImageEvent} /> </Card.Body> </Card> <Card style={{ width: "18rem" }}> <Card.Body> <img style={{ width: "15rem" }} src={ImageEvent} /> </Card.Body> </Card> </div> </div> ); }; <file_sep>import React from "react"; import ImageEvent from "./ImageEvent.jpeg"; export const UpComingEvent = () => { return ( <div> <h2>Upcoming event</h2> <div className="Upcoming"> <section id="details"> <section> <i>Gatundu Children's Home</i> <h4>Kids Population: 54</h4> </section> <div className="sections"> <section id="lists"> <li>16 Secondary kids</li> <li>5 kids to join secondary</li> <li>33 Primary going kids</li> </section> <section> <ul>Youngest 5 years</ul> <ul>Oldest 20 years</ul> </section> <section> <ul>32 girls</ul> <ul>22 boys</ul> </section> </div> {/* <h5>Expected 34 kids on the day of the event</h5> */} <div id="secpart"> <section> <h3>Donations</h3> <div id="lists"> <li>Dry foods</li> <li>Cereals</li> <li>Toiletries</li> <li>Sanitary towels</li> <li>Books/stationary</li> <li>Milk</li> </div> </section> <section> <h4>Let's meet at Bata Hilton 8am</h4> </section> </div> </section> <div> <img style={{ width: "600px", maxHeight: "700px" }} src={ImageEvent} /> </div> </div> </div> ); }; <file_sep>import { UpComingEvent } from "./UpComingEvent"; export const Events = () => { return ( <div> <div> <UpComingEvent /> </div> </div> ); }; <file_sep>import { useState } from "react"; import Logo from "./hopeLogo.jpeg"; import { UpComingEvent } from "./UpComingEvent"; import { Carousel } from "react-bootstrap"; import Pic from "./pic.jpg"; import Pic2 from "./pic2.jpg"; import MissionVision from "./MissionVision"; export const Home = () => { const [index, setIndex] = useState(1); const handleSelect = (selectedIndex, e) => { setIndex(selectedIndex); }; //end handleSelect let datx = [ ["first slide", "second slide"], ["First Image", "Second Image"], ]; //let pictures = [Pic, Pic2]; // const captions = ["first slide", "second slide"]; // const captionsDetails = ["First Image", "Second Image"]; return ( <div id="home"> <section id="seck1"> <MissionVision /> </section> <section id="seck2"> <h3>Mission: Touch every kid's life</h3> <h4>Vision: See that every kid's life is touched</h4> </section> <section> <h1>Section ya tatu</h1> section three </section> {/* <div style={{ border: "dotted" }} id=""> <div id="logo-section"> <img src={Logo} style={{ width: "100%" }} /> <div>We believe in giving hope to less fortunate.</div> <div>Want to join?</div> <button>Join</button> <button>Donate</button> </div> <Carousel id="carousel-section" activeIndex={index} onSelect={handleSelect} interval={4000} fade style={{ border: "double", margin: "15px" }} > {datx.map((y) => ( <Carousel.Item> <img style={{ width: "100%", maxHeight: "700px" }} src={Pic} />; <Carousel.Caption> <h3>{y[0]}</h3> <p>{y[1]}</p> </Carousel.Caption> </Carousel.Item> ))} </Carousel> </div> */} </div> ); }; <file_sep>import { Link } from "react-router-dom"; export const NavBar = () => { return ( <div id="navo"> <Link to="/"> <h4> <i>Hope Generation</i> </h4> </Link> <ul className="listItems"> <Link to="/events"> <li>Events</li> </Link> <Link to="/gallery"> <li>Gallery</li> </Link> <Link to="/donate"> <li>Donate</li> </Link> <Link to="/shop"> <li>Shop</li> </Link> </ul> </div> ); }; <file_sep>import { Card } from "react-bootstrap"; import Cap from "./cap.jpg"; import Tshirt from "./tshirts.jpg"; export const Shop = () => { return ( <div id="shop"> <Card style={{ width: "47rem" }}> <Card.Body> <img style={{ width: "43rem" }} src={Tshirt} /> </Card.Body> </Card> <Card style={{ width: "47rem" }}> <Card.Body> <img style={{ width: "43rem" }} src={Cap} /> </Card.Body> </Card> </div> ); };
1018ef162b01a78a11840eef41f4d508a2c1d4ce
[ "JavaScript" ]
6
JavaScript
kevinmuchene/hope-generation
4620d16fdada40b3a9c098846918a358b91f0bf7
c7efd00635c6464dc0e0d9ca5b6667b1cccf7889
refs/heads/master
<repo_name>hunglv51/MyTimer<file_sep>/Timer/INotifier.cs using System; using System.Collections.Generic; using System.Text; namespace WorkTimer { public interface INotifier { void Notify(string s); } } <file_sep>/ConsoleTimer/Program.cs using System; using WorkTimer; namespace ConsoleTimer { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); var displayer = new ConsoleNotifier(); var worker = new Worker(displayer); worker.Start(); Console.ReadKey(); } } } <file_sep>/Timer/Worker.cs using System; using System.Timers; namespace WorkTimer { public class Worker : IDisposable { private Timer _timer; private readonly Random _random; public INotifier Notifier { get; private set; } public bool IsRunning { get; private set; } public Worker() { _random = new Random(); } public Worker(INotifier notifier) : this() { Notifier = notifier; } public int WorkingMinute { get; private set; } public void Start() { _timer = new Timer(); TakeRest(); IsRunning = true; } public void TakeRest() { _timer.Dispose(); _timer = new Timer(); Notifier.Notify("Toi dang nghi ngoi"); var nextWorkDuration = 3; _timer.Interval = nextWorkDuration * 1000; _timer.Elapsed -= (s, e) => TakeRest(); _timer.Elapsed += DoWork; _timer.Start(); } public void DoWork(object source, ElapsedEventArgs e) { _timer.Dispose(); _timer = new Timer(); var nextWorkDuration = _random.Next(1, 10); Notifier.Notify(string.Format("Toi dang lam task thoi gian {0} s", nextWorkDuration)); _timer.Interval = nextWorkDuration * 1000; _timer.Elapsed += (s, evt) => TakeRest(); _timer.Elapsed -= DoWork; _timer.Start(); } public void Stop() { _timer.Stop(); _timer.Dispose(); IsRunning = false; } public void Dispose() { Stop(); } } } <file_sep>/WebTimer/Utils/HubNotifier.cs using Microsoft.AspNetCore.SignalR; using WebTimer.Hubs; using WorkTimer; namespace WebTimer.Utils { public class HubNotifier : INotifier { private readonly IHubContext<WorkerHub> _hubContext; public HubNotifier(IHubContext<WorkerHub> hubContext) { _hubContext = hubContext; } public void Notify(string s) { _hubContext.Clients.All.SendAsync("ReceiveMessage", s).Wait(); } } } <file_sep>/WebTimer/Pages/Index.cshtml.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.SignalR; using WorkTimer; namespace WebTimer.Pages { public class IndexModel : PageModel { private readonly Worker _worker; public IndexModel(Worker worker) { _worker = worker; } public void OnGet() { if (!_worker.IsRunning) { _worker.Start(); } } } } <file_sep>/ConsoleTimer/ConsoleNotifier.cs using System; using System.Collections.Generic; using System.Text; using WorkTimer; namespace ConsoleTimer { public class ConsoleNotifier : INotifier { public void Notify(string s) { Console.WriteLine(s); } } } <file_sep>/WebTimer/Hubs/WorkerHub.cs using Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; namespace WebTimer.Hubs { public class WorkerHub : Hub { public async Task SendMessage(string msg) { await Clients.Caller.SendAsync("ReceiveMessage", msg); } } }
da4b9f4eb1c5bf4a09df61439bf8b6a419138fcd
[ "C#" ]
7
C#
hunglv51/MyTimer
c164e1a819fec2e75afb97c0deb17cf723b70a2e
c0ad82ca4e82221a340602ddd32562ddbfd6e2b4
refs/heads/master
<repo_name>Expanduino/Expanduino-Python<file_sep>/expanduino/classes/meta.py #!/usr/bin/python from expanduino.subdevice import Subdevice from expanduino.codec import * from enum import IntEnum from functools import lru_cache from cached_property import cached_property class MetaSubdevice(Subdevice): class Command(IntEnum): VENDOR_NAME = 0 PRODUCT_NAME = 1 SHORT_NAME = 2 SERIAL_NUMBER = 3 RESET = 4 GET_INTERRUPTION = 5 GET_INTERRUPTION_ENABLED = 6 SET_INTERRUPTION_ENABLED = 7 NUM_SUBDEVICES = 8 SUBDEVICE_TYPE = 9 SUBDEVICE_NAME = 10 SUBDEVICE_SHORT_NAME = 11 def __init__(self, container, devNum): Subdevice.__init__(self, container, devNum) @cached_property def device_vendor_name(self): return self.call(MetaSubdevice.Command.VENDOR_NAME, parser=parseString) @cached_property def device_product_name(self): return self.call(MetaSubdevice.Command.PRODUCT_NAME, parser=parseString) @cached_property def device_short_name(self): return self.call(MetaSubdevice.Command.SHORT_NAME, parser=parseString) @cached_property def device_serial_number(self): return self.call(MetaSubdevice.Command.SERIAL_NUMBER, parser=parseString) def device_reset(self): self.call(MetaSubdevice.Command.RESET) @cached_property def num_subdevices(self): return self.call(MetaSubdevice.Command.NUM_SUBDEVICES, parser=parseByte) def subdevice_reset(self, devNum): return self.call(MetaSubdevice.Command.RESET, args=[devNum]) def subdevice_type(self, devNum): return self.call(MetaSubdevice.Command.SUBDEVICE_TYPE, args=[devNum], parser=parseEnum(Subdevice.Type)) def subdevice_name(self, devNum): return self.call(MetaSubdevice.Command.SUBDEVICE_NAME, args=[devNum], parser=parseString) def subdevice_short_name(self, devNum): return self.call(MetaSubdevice.Command.SUBDEVICE_SHORT_NAME, args=[devNum], parser=parseString) def subdevice_get_interrupt_enabled(self, devNum): return self.call(MetaSubdevice.Command.GET_INTERRUPTION_ENABLED, args=[devNum], parser=parseBool) def subdevice_set_interrupt_enabled(self, devNum, enabled): self.call(MetaSubdevice.Command.SET_INTERRUPTION_ENABLED, args=[devNum, enabled])<file_sep>/expanduino/transport/i2c.py from expanduino.expanduino import Expanduino from expanduino.classes.meta import MetaSubdevice from smbus2 import SMBus, i2c_msg, I2cFunc import os import time from retry import retry import asyncio import threading from time import sleep #import RPi.GPIO as GPIO class ExpanduinoI2C(Expanduino): def __init__(self, bus_num, i2c_addr, interrupt_pin): self.bus_num = bus_num self.i2c_addr = i2c_addr self.interrupt_pin = interrupt_pin self.bus = SMBus(bus_num) self.lock = threading.Lock() Expanduino.__init__(self) async def attach_interruptions(self): #GPIO.setmode(GPIO.BOARD) #GPIO.setup(self.interrupt_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) #interruption_future = asyncio.Future() #def interrupted(_): #try: #interruption_future.set_result(None) #except asyncio.futures.InvalidStateError: #pass #GPIO.add_event_detect(self.interrupt_pin, GPIO.FALLING, callback=interrupted) #try: #while True: #if GPIO.input(self.interrupt_pin) == 1: #interruption_future = asyncio.Future() #if GPIO.input(self.interrupt_pin) == 1: ##await asyncio.wait([self.interruption_future], timeout=0.01) #await interruption_future #payload = self.meta.call(MetaSubdevice.Command.GET_INTERRUPTION, parser=bytes) #if payload: #self.subdevices[payload[0]].handleInterruption(payload[1:]) #finally: #GPIO.remove_event_detect(self.interrupt_pin) #GPIO.setup(self.interrupt_pin, GPIO.IN) while True: payload = self.meta.call(MetaSubdevice.Command.GET_INTERRUPTION, parser=bytes) if payload: self.subdevices[payload[0]].handleInterruption(payload[1:]) else: await asyncio.sleep(0.005) @property def phys(self): return "expanduino@i2c-%x-%x" % (self.bus_num, self.i2c_addr) def _call(self, devNum, cmd, args, parser): with self.lock: # FIXME Should be an asyncio lock opcode = (devNum << 4) + cmd if args is None: send_xfer = i2c_msg.write(self.i2c_addr, [opcode]) else: send_xfer = i2c_msg.write(self.i2c_addr, [opcode, len(args)] + args) if parser is None: i2c_ops = [send_xfer] else: recvSize = 1 if hasattr(parser, 'expectedSize'): recvSize = parser.expectedSize + 1 recv_xfer = i2c_msg.read(self.i2c_addr, recvSize) i2c_ops = [send_xfer, recv_xfer] self.bus.i2c_rdwr(*i2c_ops) if parser is not None: resp = bytes(recv_xfer) resp_sz = resp[0] resp = resp[1:] #We don't have the whole response -- Probably because of a dynamic-size field, like a string if len(resp) != resp_sz: recv_xfer = i2c_msg.read(self.i2c_addr, resp_sz + 1) self.bus.i2c_rdwr(recv_xfer) resp = bytes(recv_xfer) resp_sz = resp[0] resp = resp[1:] #Maybe we transferred more bytes than necessary? just throw away the garbage resp = resp[:resp_sz] return parser(resp) <file_sep>/README.md # Expanduino-Python Ideally, expanduino should plug directly into a Linux modulel. But writing a kernel modules is a bit more difficult than implementing userspace drivers. Until the firmware gets stable, this Python tool will be the primary tool for development <file_sep>/expanduino/classes/leds.py #!/usr/bin/python from expanduino.subdevice import Subdevice from expanduino.codec import * from enum import IntEnum from time import time from cached_property import cached_property import math import asyncio class LedsSubdevice(Subdevice): class Command(IntEnum): NUM_LEDS = 0 NAME = 1 GET_BRIGHTNESS = 2 SET_BRIGHTNESS = 3 class Led: def __init__(self, subdevice, ledNum): self.subdevice = subdevice self.ledNum = ledNum @cached_property def name(self): return self.subdevice.call(LedsSubdevice.Command.NAME, args=[self.ledNum], parser=parseString) @property def brightness(self): return self.subdevice.call(LedsSubdevice.Command.GET_BRIGHTNESS, args=[self.ledNum], parser=parseByte) / 255 @brightness.setter def brightness(self, value): value = round(max(0, min(255, 255 * value))) return self.subdevice.call(LedsSubdevice.Command.SET_BRIGHTNESS, args=[self.ledNum, value]) def __str__(self): return "#%d %s = %.0f%%" % (self.ledNum, self.name, self.brightness*100) def __init__(self, container, devNum): Subdevice.__init__(self, container, devNum) @cached_property def leds(self): num_leds = self.call(LedsSubdevice.Command.NUM_LEDS, parser=parseByte) return [ LedsSubdevice.Led(self, i) for i in range(num_leds) ] async def attach(self): for led in self.leds: print(" ", led) timeBegin = time() leds = self.leds while True: elapsed = time() - timeBegin for i, led in enumerate(leds): led.brightness = math.sin(math.pi * (elapsed + 1.0*i/len(leds)))**2 await asyncio.sleep(0.05) <file_sep>/expanduino/expanduino.py from expanduino.classes.meta import MetaSubdevice from expanduino.classes.leds import LedsSubdevice from expanduino.classes.lcd import LcdSubdevice from expanduino.classes.linuxinput import LinuxInputSubdevice from expanduino.classes.serial import SerialSubdevice from expanduino.subdevice import Subdevice from expanduino.codec import defaultEncoder from cached_property import cached_property from .utils import run_coroutines class Expanduino: def __init__(self): self.meta = MetaSubdevice(self, 0) def call(self, devNum, cmd, args=None, encoder=defaultEncoder, parser=None): if args is not None: args = list(encoder(args)) return self._call(devNum, cmd, args, parser) @property def phys(self): return "expanduino" @property def vendor_name(self): return self.meta.device_vendor_name @property def product_name(self): return self.meta.device_product_name @property def short_name(self): return self.meta.device_short_name @property def serial_number(self): return self.meta.device_serial_number def reset(self): return self.meta.device_reset() @cached_property def subdevices(self): subdevice_classes = { Subdevice.Type.LEDS: LedsSubdevice, Subdevice.Type.LINUX_INPUT: LinuxInputSubdevice, Subdevice.Type.SERIAL: SerialSubdevice, Subdevice.Type.LCD: LcdSubdevice, } subdevices = [self.meta] + [ subdevice_classes.get(self.meta.subdevice_type(i), Subdevice)(self, i) for i in range(1, self.meta.num_subdevices) ] return subdevices async def attach_interruptions(self): #Override this on transport class pass # Attaches this device in the OS (Using UInput, PTY, etc) # The coroutine will be executed on the event loop until the program quits, when it get cancelled async def attach(self): self.reset() print("Vendor:", self.vendor_name) print("Product:", self.product_name) print("Short name:", self.short_name) print("S/N:", self.serial_number) try: coroutines = [] coroutines.append(self.attach_interruptions()) for subdevice in self.subdevices: async def printAndCall(subdevice): print("Attaching", subdevice) await subdevice.attach() coroutines.append(printAndCall(subdevice)) await run_coroutines(*coroutines) finally: self.reset() <file_sep>/expanduino/subdevice.py from enum import IntEnum from cached_property import cached_property class Subdevice: class Type(IntEnum): MISSING = 0 META = 1 LEDS = 2 GPIO = 3 LINUX_INPUT = 4 HID = 5 SERIAL = 6 MISC = 7 I2C = 8 SPI = 9 LCD = 10 def __init__(self, container, devNum): self.container = container self.devNum = devNum def call(self, *args, **kwargs): return self.container.call(self.devNum, *args, **kwargs) @cached_property def type(self): return self.container.meta.subdevice_type(self.devNum) @cached_property def name(self): return self.container.meta.subdevice_name(self.devNum) @cached_property def short_name(self): return self.container.meta.subdevice_short_name(self.devNum) @property def phys(self): return "%s/%s@%x" % (self.container.phys, self.short_name, self.devNum) @property def interruptionEnabled(self): return self.container.meta.subdevice_get_interrupt_enabled(self.devNum) @interruptionEnabled.setter def interruptionEnabled(self, enabled): self.container.meta.subdevice_set_interrupt_enabled(self.devNum, enabled) def reset(self): self.container.meta.subdevice_reset(self.devNum) def with_interruptions(self): class Context: def __init__(self, subdevice): self.subdevice = subdevice self.old_value = None def __enter__(self): self.old_value = self.subdevice.interruptionEnabled self.subdevice.interruptionEnabled = True def __exit__(self, exc_type, exc, tb): self.subdevice.interruptionEnabled = self.old_value self.old_value = None return Context(self) def handleInterruption(self, data): print(self.name, "Got interrupt", data) async def attach(self): pass def __str__(self): return "%s (%s@%d - %s - %s)" % (self.name, self.short_name, self.devNum, self.phys, self.type.name)<file_sep>/expanduino/classes/serial.py #!/usr/bin/python from expanduino.subdevice import Subdevice from expanduino.codec import * from enum import IntEnum from time import time from cached_property import cached_property import asyncio import os import termios import re from fcntl import ioctl from ..utils import run_coroutines, create_link, forever, fd_reader EXTPROC = 0o200000 TIOCPKT_IOCTL = 64 BAUD_CONSTANTS = { getattr(termios, x): int(x[1:]) for x in filter(lambda x: re.match("B\\d+", x), dir(termios)) } CHARACTER_SIZE_CONSTANTS = { getattr(termios, x): int(x[2:]) for x in filter(lambda x: re.match("CS\\d+", x), dir(termios)) } class SerialSubdevice(Subdevice): class Command(IntEnum): NUM_SERIALS = 0, NAME = 1, WRITE = 2, READ = 3, AVAILABLE = 4 class Serial: def __init__(self, subdevice, serialNum): self.subdevice = subdevice self.serialNum = serialNum self.ptyMaster = None self.ptySlave = None self.ptyLink = None @cached_property def name(self): return self.subdevice.call(SerialSubdevice.Command.NAME, args=[self.serialNum], parser=parseString) @property def available(self): return self.subdevice.call(SerialSubdevice.Command.AVAILABLE, args=[self.serialNum], parser=parseByte) def read(self, n): return self.subdevice.call(SerialSubdevice.Command.READ, args=[self.serialNum, n], parser=parseBytes) def write(self, data): self.subdevice.call(SerialSubdevice.Command.WRITE, args=bytes([self.serialNum]) + bytes(data)) def __str__(self): return "#%-3d %s" % (self.serialNum, self.name) async def attach(self): if self.ptyMaster: return self.ptyMaster, self.ptySlave = os.openpty() try: attr = termios.tcgetattr(self.ptyMaster) attr[3] |= EXTPROC termios.tcsetattr(self.ptyMaster, termios.TCSANOW, attr) ioctl(self.ptyMaster, termios.TIOCPKT, b'\1') def got_packet(packet): if packet[0] == termios.TIOCPKT_DATA: self.write(packet[1:]) if packet[0] & TIOCPKT_IOCTL: attr = termios.tcgetattr(self.ptyMaster) # Dont let the slave clear the EXTPROC flag (e.g., screen does so) # IMO, allowing the slave fd to do this sounds pretty dumb if not attr[3] & EXTPROC: attr[3] |= EXTPROC termios.tcsetattr(self.ptyMaster, termios.TCSANOW, attr) ibaud = BAUD_CONSTANTS[attr[4]] obaud = BAUD_CONSTANTS[attr[5]] #FIXME: Pty driver assumes 8 bits, no parity, ALWAYS #https://github.com/torvalds/linux/blob/master/drivers/tty/pty.c#L290-L291 bits = CHARACTER_SIZE_CONSTANTS[attr[2] & termios.CSIZE] if attr[2] & termios.PARENB: if attr[2] & termios.PARODD: parity = 'O' else: parity = 'E' else: parity = 'N' if attr[2] & termios.CSTOPB: stop_bits = 2 else: stop_bits = 1 print("Changed %s config: %d:%d %d%s%d" % (self, ibaud, obaud, bits, parity, stop_bits)) #TODO: Reconfigure the port async with create_link(os.ttyname(self.ptySlave), "/dev/ttyExpanduino%d") as link: async with fd_reader(self.ptyMaster, n=20, callback=got_packet): await forever() finally: os.close(self.ptySlave) os.close(self.ptyMaster) self.ptyMaster = None def handleInterruption(self, data): if self.ptyMaster: os.write(self.ptyMaster, data) def __init__(self, container, devNum): Subdevice.__init__(self, container, devNum) def handleInterruption(self, data): if data: serialNum = data[0] payload = data[1:] if serialNum < len(self.serials): self.serials[serialNum].handleInterruption(payload) @cached_property def serials(self): num_serials = self.call(SerialSubdevice.Command.NUM_SERIALS, parser=parseByte) return [ SerialSubdevice.Serial(self, i) for i in range(num_serials) ] async def attach(self): serials = self.serials with self.with_interruptions(): coroutines = [] for serial in serials: print(" ", serial) coroutines.append(serial.attach()) await run_coroutines(*coroutines) <file_sep>/expanduino/classes/linuxinput.py #!/usr/bin/python from expanduino.subdevice import Subdevice from expanduino.codec import * from enum import IntEnum from time import time import math import evdev import asyncio from collections import namedtuple, defaultdict from cached_property import cached_property import struct import io class LinuxInputSubdevice(Subdevice): class Command(IntEnum): ID = 0 NUM_COMPONENTS = 1 COMPONENT_TYPE = 2 COMPONENT_ABS_INFO = 3 GET_COMPONENT_VALUE = 4 SET_COMPONENT_VALUE = 5 AbsInfo = namedtuple('AbsInfo', ['max', 'min', 'fuzz', 'flat']) class Component: def __init__(self, subdevice, componentNum): self.subdevice = subdevice self.componentNum = componentNum @cached_property def type(self): return self.subdevice.call(LinuxInputSubdevice.Command.COMPONENT_TYPE, args=[self.componentNum], parser=parsePacked("HH")) @cached_property def abs_info(self): if self.type[0] == evdev.ecodes.EV_ABS: return LinuxInputSubdevice.AbsInfo(*self.subdevice.call(LinuxInputSubdevice.Command.COMPONENT_ABS_INFO, args=[self.componentNum], parser=parsePacked("iiii"))) @property def value(self): return self.subdevice.call(LinuxInputSubdevice.Command.GET_COMPONENT_VALUE, args=[self.componentNum], parser=parsePacked("i"))[0] @value.setter def value(self, value): return self.subdevice.call(LinuxInputSubdevice.Command.SET_COMPONENT_VALUE, args=[self.componentNum, value], encoder=encodePacked("Bi")) def __str__(self): type = self.type return "#%-3d %-20s = %-5d %s" % (self.componentNum, evdev.ecodes.bytype[type[0]][type[1]], self.value, self.abs_info or "") def __init__(self, container, devNum): Subdevice.__init__(self, container, devNum) self.uinput = None @cached_property def components(self): num_components = self.call(LinuxInputSubdevice.Command.NUM_COMPONENTS, parser=parseByte) return [ LinuxInputSubdevice.Component(self, i) for i in range(num_components) ] @cached_property def components_by_type(self): return { component.type : component for component in self.components } def handleInterruption(self, data): if not self.uinput: return if not data: return def unpack(stream, fmt): size = struct.calcsize(fmt) buf = stream.read(size) if len(buf) != size: return None return struct.unpack(fmt, buf) stream = io.BytesIO(data) components = self.components while True: e = unpack(stream, '>Bi') if not e: break component = components[e[0]] self.uinput.write(component.type[0], component.type[1], e[1]) self.uinput.syn() async def attach(self): events = defaultdict(list) for component in self.components: print(" ", component) ev_type = component.type[0] ev_code = component.type[1] if ev_type == evdev.ecodes.EV_ABS: abs_info = component.abs_info ev_code = (ev_code, evdev.AbsInfo(max=abs_info.max, min=abs_info.min, fuzz=abs_info.fuzz, flat=abs_info.flat, value=0, resolution=0)) events[ev_type].append(ev_code) self.uinput = evdev.UInput(events=events, name=self.name, phys=self.phys) try: with self.uinput: with self.with_interruptions(): for component in self.components: self.uinput.write(component.type[0], component.type[1], component.value) async for ev in self.uinput.async_read_loop(): component = self.components_by_type[(ev.type, ev.code)] component.value = ev.value finally: self.uinput = None <file_sep>/expanduino/utils.py import asyncio import os import traceback async def run_coroutines(*coroutines): tasks = [ asyncio.ensure_future(coroutine) for coroutine in coroutines ] ex = [] while tasks: try: await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) except asyncio.CancelledError: pass except Exception as e: traceback.print_exc() ex.append(e) finally: pending = [] for task in tasks: if not task.done(): task.cancel() pending.append(task) else: try: task.result() except asyncio.CancelledError: pass except Exception as e: traceback.print_exc() ex.append(e) tasks = pending if ex: raise ex[0] def mklink(to, format): i=0 while True: try: link = format % (i,) os.symlink(to, link) return link except FileExistsError: i += 1 def create_link(to, format): class Context: def __init__(self): self.link = None async def __aenter__(self): self.link = mklink(to, format) print("Created", self.link, "=>", to) return self.link async def __aexit__(self, exc_type, exc, tb): os.remove(self.link) print("Removed", self.link, "=>", to) self.link = None return Context() def fd_reader(fd, callback, n=1024): class Context: async def __aenter__(self): def readFunc(): buffer = os.read(fd, n) callback(buffer) asyncio.get_event_loop().add_reader(fd, readFunc) async def __aexit__(self, exc_type, exc, tb): asyncio.get_event_loop().remove_reader(fd) return Context() async def forever(): while True: await asyncio.Future() <file_sep>/expanduino/codec.py import struct def encodePacked(pattern): def f(args): return struct.pack(">" + pattern, *args) return f def encodeByte(x): return bytes([x]) def encodeString(x): return bytes(x, "utf8") def defaultEncoder(x): if isinstance(x, str): return parseString(x) elif isinstance(x, bytes): return x elif isinstance(x, list): return bytes(x) else: raise TypeError("defaultEncoder supports String, Bytes and LIst<Byte>") def parseBool(x): return bool(x[0]) parseBool.expectedSize=1 def parseByte(x): return x[0] parseByte.expectedSize=1 def parseEnum(enum): ret = lambda x: enum(x[0]) ret.expectedSize = 1 return ret def parsePacked(pattern): pattern = ">" + pattern ret = lambda x: struct.unpack(pattern, x) ret.expectedSize = struct.calcsize(pattern) return ret def parseBytes(x): return x def parseString(x): return str(x, "utf8") <file_sep>/main.py #!/usr/bin/python3.5 from expanduino.transport.i2c import ExpanduinoI2C from expanduino.subdevice import Subdevice from expanduino.classes.meta import MetaSubdevice import time import asyncio import signal loop = asyncio.get_event_loop() expanduino = ExpanduinoI2C(bus_num=0, i2c_addr=0x56, interrupt_pin=7) task = asyncio.ensure_future(expanduino.attach()) def quit(*args): print("Exiting...") task.cancel() loop.add_signal_handler(signal.SIGINT, quit) loop.add_signal_handler(signal.SIGTERM, quit) try: loop.run_until_complete(task) finally: loop.close()<file_sep>/expanduino/classes/lcd.py #!/usr/bin/python from expanduino.subdevice import Subdevice from expanduino.codec import * from enum import IntEnum from time import time from cached_property import cached_property import math import asyncio import os from ..utils import create_link, forever, fd_reader class LcdSubdevice(Subdevice): class Command(IntEnum): CMD = 0, READ_TEXT = 1, WRITE_TEXT = 2, GET_BRIGHTNESS = 3, SET_BRIGHTNESS = 4 def cmd(self, cmd): chunk_size = 8 args = [cmd] while len(args): n = self.call(LcdSubdevice.Command.CMD, args=args[:chunk_size], parser=parseByte) args = args[n:] def write(self, text): chunk_size = 8 while len(text): n = self.call(LcdSubdevice.Command.WRITE_TEXT, args=text[:chunk_size], parser=parseByte) text = text[n:] def read(self, n): return self.call(LcdSubdevice.Command.READ_TEXT, args=[n], parser=parseBytes) @property def brightness(self): return self.call(LcdSubdevice.Command.GET_BRIGHTNESS, parser=parseByte) / 255 @brightness.setter def brightness(self, value): value = round(max(0, min(255, 255 * value))) return self.call(LcdSubdevice.Command.SET_BRIGHTNESS, args=[value]) async def attach(self): ptyMaster, ptySlave = os.openpty() try: current_data = b'' def got_data(data): nonlocal current_data current_data += data while len(current_data) >= 1: if current_data[0] == 0: self.reset() current_data = current_data[1:] elif current_data[0] == 1: if len(current_data) < 2: break self.cmd(current_data[1]) current_data = current_data[2:] elif current_data[0] == 2: if len(current_data) < 2: break self.brightness = current_data[1] / 255 current_data = current_data[2:] elif current_data[0] == 3: if len(current_data) < 2: break l = current_data[1] if len(current_data) < l+2: break self.write(current_data[2:l+2]) current_data = current_data[l+2:] else: # Oops? self.write(b'?') current_data = current_data[1:] async with create_link(os.ttyname(ptySlave), "/dev/xcharlcd%d") as link: async with fd_reader(ptyMaster, n=20, callback=got_data): await forever() finally: os.close(ptySlave) os.close(ptyMaster)
40ca022f789b274e63870354299e393d2ce93c97
[ "Markdown", "Python" ]
12
Python
Expanduino/Expanduino-Python
468b97091c5808158e05895cc1a9fb244dfdc6c7
0ae562a7eef5a41a854cb4f9e5e7f8e76c57e1f0
HEAD
<repo_name>joannecheng/chicago_density<file_sep>/geojson_collect.rb require 'json' require 'pg' conn = PG.connect :dbname => 'my_spatial_db' geojson = { "type" => "FeatureCollection", :features => [] } conn.exec("select st_asgeojson(geom), (cook_census_data.p001001/st_area(geom)) as density from cook_census_tracts LEFT JOIN cook_census_data on cook_census_tracts.geoid10 = cook_census_data.geoid where cook_census_data.p001001 > 0").each do |row| feature = { :type => "Feature", :geometry => JSON.parse(row['st_asgeojson']), :properties => { :density => row['density'].to_f }} geojson[:features] << feature end puts geojson.to_json <file_sep>/README.mkd I am bad at maps.
edfefed2f95f658d827ecff428391d5011614959
[ "Markdown", "Ruby" ]
2
Ruby
joannecheng/chicago_density
4660726151ef33dac14908954892ee74c69d6ef7
c2c176213d0bbf1a6b16c67030db6ebdce4e7cdd
refs/heads/main
<file_sep># ModernArt https://rosettayh.github.io/ModernArt/ <file_sep>const portfolioData = [ {"Realism (1840s-1880s)": [ {"Realism (1840s-1880s)": [ "", "In its specific sense realism refers to a mid nineteenth century artistic movement characterised by subjects painted from everyday life in a naturalistic manner; however the term is also generally used to describe artworks painted in a realistic almost photographic way.", "#realism", "https://galleryintell.com/wp-content/uploads/2014/02/%C3%89douard-Manet-Le-D%C3%A9jeuner-sur-lherbe1.jpg" ] }, {"<NAME> (1832–1883)": [ "French painter", "Movements: Impressionism, Realism, Modern art, Modernism", "#edouardmanet", "https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/%C3%89douard_Manet%2C_en_buste%2C_de_face_-_Nadar.jpg/1200px-%C3%89douard_Manet%2C_en_buste%2C_de_face_-_Nadar.jpg" ] }, {"<NAME> (1819–1877)": [ "French painter", "Movements: Realism, Romanticism, Academic art", "#gustavecourbet", "https://www.nationalgallery.org.uk/media/30089/courbet-gustave-c-face-half.jpg?center=0.26119402985074625,0.40460526315789475&mode=crop&width=430&bgcolor=fff&rnd=132138116838270000" ] } ] }, {"Impressionism (1862-1892)": [ {"Impressionism (1862-1892)": [ "", "Impressionism developed in France in the nineteenth century and is based on the practice of painting out of doors and spontaneously ‘on the spot’ rather than in a studio from sketches. Main impressionist subjects were landscapes and scenes of everyday life.", "#impressionism", "https://images.fineartamerica.com/images-medium-large-5/1-impression-sunrise-claude-monet.jpg" ] }, {"<NAME> (1840–1926)": [ "French painter", "Movements: Impressionism, Modern art, Realism", "#claudemonet", "https://upload.wikimedia.org/wikipedia/commons/a/a4/Claude_Monet_1899_Nadar_crop.jpg" ] }, {"<NAME> (1841–1995)": [ "French painter", "Movements: Impressionism, Modern art, Realism", "#berthemorisot", "https://i.pinimg.com/originals/9d/43/1c/9d431c58290796a55bf3dbb6385981c5.jpg" ] }, {"<NAME> (1841–1919)": [ "French artist", "Movements: Impressionism, Modern art, Realism", "#pierreaugusterenoir", "https://sothebys-com.brightspotcdn.com/dims4/default/8c17974/2147483647/strip/true/crop/328x328+101+105/resize/1200x1200!/quality/90/?url=http%3A%2F%2Fsothebys-brightspot.s3.amazonaws.com%2Fdotcom%2F8b%2Fcb%2Fad69237540228c98949afdfe9077%2Fpierre-auguste-renoir-uncropped-image.jpg" ] } ] }, {"Post-Impressionism (1886-1905)": [ {"Post-Impressionism (1886-1905)": [ "", "Post-Impressionism encompasses a wide range of distinct artistic styles that all share the common motivation of responding to the opticality of the Impressionist movement.", "#postimpressionism", "https://media.overstockart.com/optimized/cache/data/product_images/VG485-1000x1000.jpg" ] }, {"<NAME> (1839–1906)": [ "French artist", "Movements: Post-Impressionism, Modern art, Impressionism, Romanticism, Cubism", "#paulcézanne", "https://media.carredartistes.com/img/cms/Blog/2017-05-17%20-%20C%C3%A9zanne/2017-05-17-paul-cezanne.png" ] }, {"<NAME> (1853–1890)": [ "Dutch painter", "Movements: Realism, Post-Impressionism, Modern art, Impressionism, Japonisme, Cloisonnism, Pointillism, Neo-Impressionism", "#vincentvangogh", "https://www.biography.com/.image/ar_1:1%2Cc_fill%2Ccs_srgb%2Cg_face%2Cq_auto:good%2Cw_300/MTY2NTIzMzc4MTI2MDM4MjM5/vincent_van_gogh_self_portrait_painting_musee_dorsay_via_wikimedia_commons_promojpg.jpg" ] }, {"<NAME> (1848–1903)": [ "French painter, printmaker, sculptor", "Movements: Post-Impressionism, Modern art, Impressionism, Primitivism, Synthetism, Symbolism", "#paulgauguin", "https://1.bp.blogspot.com/-OY7IPdGBbzg/Vzvc1kABNCI/AAAAAAAAAUE/OpKpdcV8HQQC3mgkHWgLhvGkqEcT3kizgCLcB/s400/Portrait-of-Paul-Gauguin-from-1891.png" ] } ] }, {"Neo-Impressionism (1884-1886)": [ {"Neo-Impressionism (1884-1886)": [ "", "Neo-impressionism is the name given to the post-impressionist work of Georges Seurat, <NAME> and their followers who, inspired by optical theory, painted using tiny adjacent dabs of primary colour to create the effect of light.", "#neoimpressionism", "https://cdn.britannica.com/41/24341-050-DC561751/canvas-oil-La-Grande-Jatte-Georges-Seurat-1884.jpg" ] }, {"Georges Seurat (1859–1891)": [ "French artist", "Movements: Pointillism, Post-Impressionism, Impressionism, Modern art, Neo-Impressionism, Neoclassicism, Divisionism", "#georgesseurat", "https://upload.wikimedia.org/wikipedia/commons/7/76/Georges_Seurat_1888.jpg" ] } ] }, {"Cubism (1907-1922)": [ {"Cubism (1907-1922)": [ "", "Cubism was a revolutionary new approach to representing reality invented in around 1907–08 by artists <NAME> and <NAME>. They brought different views of subjects (usually objects or figures) together in the same picture, resulting in paintings that appear fragmented and abstracted.", "#cubism", "https://www.moma.org/media/W1siZiIsIjQzODQ1MiJdLFsicCIsImNvbnZlcnQiLCItcXVhbGl0eSA5MCAtcmVzaXplIDIwMDB4MTQ0MFx1MDAzZSJdXQ.jpg?sha=8b2a1c3992bba555" ] }, {"<NAME> (1881–1973)": [ "Spanish painter, sculptor, printmaker, ceramicist, theatre designer ", "Movements: Cubism, Surrealism, Expressionism, Post-Impressionism", "#pablopicasso", "https://www.biography.com/.image/t_share/MTY2NTIzNTAyNjgwMDg5ODQy/pablo-picasso-at-his-home-in-cannes-circa-1960-photo-by-popperfoto_getty-images.jpg" ] }, {"<NAME> (1882–1963)": [ "French painter, collagist, draughtsman, printmaker, sculptor", "Movements: Cubism, Synthetic cubism, Expressionism, Fauvism", "#georgesbraque", "https://www.thoughtco.com/thmb/_cpH4N5bjMFUgXiU9sSZE0onmrk=/1609x1052/filters:fill(auto,1)/georges-braque-older-ffa4ae583d9c4f4397a8cecba9c72d0e.jpg" ] } ] }, {"German Expressionism (1905-1933)": [ {"German Expressionism (1905-1933)": [ "", "German expressionism was an early twentieth century German art movement that emphasized the artist's inner feelings or ideas over replicating reality, and was characterised by simplified shapes, bright colours and gestural marks or brushstrokes.", "#germanexpressionism", "https://www.wassilykandinsky.net/images/works/35.jpg" ] }, {"Die Brücke (1905-1913)": [ "", "Progenitors of the movement later known as German Expressionism, Die Brücke formed in Dresden in 1905 as a bohemian collective of artists in staunch opposition to the older, established bourgeois social order of Germany.", "#diebrücke", "https://www.moma.org/media/W1siZiIsIjQyODY0NSJdLFsicCIsImNvbnZlcnQiLCItcXVhbGl0eSA5MCAtcmVzaXplIDIwMDB4MjAwMFx1MDAzZSJdXQ.jpg?sha=86361fae3acf4726" ] }, {"Der Blaue Reiter (1911-1914)": [ "", "Der Blaue Reiter was a German expressionist group originating in Munich in 1909.", "#derblaueReiter", "https://upload.wikimedia.org/wikipedia/commons/7/7b/Wassily_Kandinsky%2C_1903%2C_The_Blue_Rider_%28Der_Blaue_Reiter%29%2C_oil_on_canvas%2C_52.1_x_54.6_cm%2C_Stiftung_Sammlung_E.G._B%C3%BChrle%2C_Zurich.jpg" ] }, {"<NAME> (1880-1936)": [ "German painter, printmaker", "Movements: Expressionism, Modern art, German Expressionism, Cubism", "#ernstludwigkirchner", "https://sothebys-com.brightspotcdn.com/dims4/default/20f03ef/2147483647/strip/true/crop/1202x1202+2765+484/resize/1200x1200!/quality/90/?url=http%3A%2F%2Fsothebys-brightspot.s3.amazonaws.com%2Fdotcom%2F5f%2Fa1%2F69ebb9974da990fb11293267aeb2%2Fpa7t40.jpg" ] }, {"<NAME> (1867-1956)": [ "German-Danish painter, printmaker, watercolourist", "Movements: Expressionism, Modern art", "#emilmolder", "https://i0.wp.com/www.famouspainters.net/painters/emil-nolde.jpg" ] }, {"<NAME> (1866-1944)": [ "Russian painter, art theorist", "Movements: Expressionism, Abstract art, Post-Impressionism", "#wassilykandinsky", "https://i.pinimg.com/originals/b9/f4/d8/b9f4d8a1b56712728cddbe24cfe9e97f.jpg" ] }, {"<NAME> (1880-1916)": [ "German painter, printmaker", "Movements: Expressionism, Cubism, German Expressionism, Modern art, Der Blaue Reiter, Post-Impressionism, Impressionism, Realism", "#franzmarc", "https://www.franzmarc.com/Franz%20Marc.jpg" ] } ] }, {"Italian Futurism (1909-1944)": [ {"Italian Futurism (1909-1944)": [ "", "Futurism was an Italian art movement of the early twentieth century that aimed to capture in art the dynamism and energy of the modern world.", "#futurism", "https://upload.wikimedia.org/wikipedia/commons/b/b4/The_City_Rises_by_Umberto_Boccioni_1910.jpg" ] }, {"<NAME> (1882–1916)": [ "Italian painter, sculptor", "Movements: Futurism, Divisionism, Cubism, Post-Impressionism, Expressionism, Modern art, Impressionism", "#umbertoboccioni", "https://img.lacstatic.it/_photo/2019/dicembre/CULTURA/2019_boccioni.jpg" ] }, {"<NAME> (1883-1966)": [ "Italian painter", "Movements: Futurism, Cubism, Modern art, Neoclassicism", "#ginoseverini", "https://upload.wikimedia.org/wikipedia/commons/4/4b/Gino_Severini_at_the_opening_of_his_solo_exhibition_at_the_Marlborough_Gallery%2C_London%2C_1913_%28detail%29.jpg" ] }, {"<NAME> (1871-1958)": [ "Italian painter, art teacher, poet", "Movements: Futurism, Modern art, Abstract art, Pointillism, Divisionism, Impressionism", "#giacomoballa", "https://cs3cdn.haworth.com/sites/cassina.com/files/styles/scheda_designer/public/balla_big_0.jpg?itok=_3iiQ3rB" ] } ] }, {"Dada (1916-1924)": [ {"Dada (1916-1924)": [ "", "Dada was an art movement formed during the First World War in Zurich in negative reaction to the horrors and folly of the war. The art, poetry and performance produced by dada artists is often satirical and nonsensical in nature.", "#dada", "https://www.tate.org.uk/art/images/work/T/T07/T07573_9.jpg" ] }, {"<NAME> (1887–1968)": [ "French-American painter, sculptor, chess player, writer ", "Movements: Expressionism, Dada, Post-Impressionism, Cubism", "#marcelduchamp", "https://walker-web.imgix.net/cms/Duchamp_Marcel_19651.jpg?auto=format,compress&w=1920&h=1200&fit=max&dpr=1.5" ] }, {"Jean (Hans) Arp (1886–1966)": [ "German-French sculptor, painter, poet", "Movements: Surrealism, Abstract art, Dada, Modern art, Biomorphism", "#jeanarp", "https://photos1.blogger.com/blogger/3242/2391/1600/hans_arp.0.jpg" ] }, {"<NAME> (1889-1943)": [ "Swiss artist, painter, sculptor, textile designer, furniture and interior designer, architect, dancer", "Movements: Constructivism, Geometric abstraction, Abstract art, Dada, Modern art, Concrete art", "#sophietaeuberarp", "https://static01.nyt.com/images/2020/07/10/arts/09ARP1/09ARP1-mediumSquareAt3X.jpg" ] }, {"<NAME> (1889-1978)": [ "German artist", "Movements: Modern art, Dada", "#hannahhöch", "https://4.bp.blogspot.com/-N_5ZW69e8kM/WhHjvH95l-I/AAAAAAAAG94/8A0urCWAm4gaDw9V8P_12RaorpTXt7lAgCEwYBhgL/s1600/01%2BHannah-Hoch.jpg" ] }, {"<NAME> (1887-1948)": [ "German artist", "Movements: Dada, Modern art, Expressionism, Abstract art, Surrealism, Merz (art style)", "#kurtschwitters", "https://artedeximena.files.wordpress.com/2010/10/m-kurt-schwitters-0020.jpg?w=706" ] } ] }, {"Suprematism (1913-1920s)": [ {"Suprematism (1913-1920s)": [ "", "Name given by the Russian artist <NAME> to the abstract art he developed from 1913 characterised by basic geometric forms, such as circles, squares, lines and rectangles, painted in a limited range of colours.", "#suprematism", "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/White_on_White_%28Malevich%2C_1918%29.png/1200px-White_on_White_%28Malevich%2C_1918%29.png" ] }, {"<NAME> (1879–1935)": [ "Russian artist, art theorist", "Movements: Suprematism, Cubism, Cubo-Futurism, Naïve art", "#kazimirmalevich", "https://4.bp.blogspot.com/-uQXVKYkIQgk/XEUD4LRpcCI/AAAAAAAAlas/R-JbF_6UG5oYPfIQeMU_AvmvI6gFCjw9QCLcBGAs/s1600/Malevich%2BKazimir%2BvA.jpg" ] } ] }, {"Ashcan School (1900-1915)": [ {"Ashcan School (1900-1915)": [ "", "Known for its gritty urban subject matter, dark palette, and gestural brushwork, the Ashcan School was a loosely knit group of artists based in New York City who were inspired by the painter <NAME>.", "#ashcanschool", "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Bellows_CliffDwellers.jpg/1200px-Bellows_CliffDwellers.jpg" ] }, {"<NAME> (1865–1929)": [ "American painter, teacher", "Movements: Modern art, American Realism, Ashcan School, Realism", "#roberthenri", "https://crystalbridges.org/wp-content/uploads/2017/06/roberthenri.jpg" ] }, {"<NAME> (1871–1951)": [ "American painter", "Movements: Neoclassicism, American Realism, Ashcan School, Modern art, Realism", "#johnsloan", "https://www.illustrationhistory.org/images/made/images/uploads/John_French_Sloan_1_580_385_c1.jpg" ] }, {"<NAME> (1882–1925)": [ "American painter", "Movements: Modern art, American Realism, Ashcan School, Realism, American Impressionism, Impressionism", "#georgebellows", "https://3.bp.blogspot.com/-3OZFU8bbVhI/T7EiKcBOP9I/AAAAAAAADSg/z2UCNIXSdAY/s1600/George%2BBellows%252C%2B2.jpg" ] } ] }, {"Precisionism (1925-1945)": [ {"Precisionism (1925-1945)": [ "", "Precisionism was the first indigenous modern art movement in the United States and an early American contribution to the rise of Modernism.", "#precisionism", "https://www.artic.edu/iiif/2/80fda6aa-e094-324a-c26a-e6ca64596293/full/1200,/0/default.jpg?w=1200&h=800&fit=crop" ] }, {"<NAME> (1887–1986)": [ "American artist", "Movements: Abstract art, American modernism, Abstract expressionism, Modernism, Precisionism", "#georgiaokeeffe", "https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/gettyimages-517323730-1565187892.jpg?crop=1.00xw:0.797xh;0,0&resize=640:*" ] }, {"<NAME> (1887–1946)": [ "American-Italian painter", "Movements: Modern art, Futurism, American modernism, Modernism, Abstract art, Precisionism", "#josephstella", "https://www.thoughtco.com/thmb/w0JASrkFAUoxKWcZf0fPrnvDY4g=/576x576/smart/filters:no_upscale()/CharlesSheelerhorizontal-3d523fa4feb3445e8545afdbf7c97e53.png" ] }, {"<NAME> (1883–1965)": [ "American painter, commercial photographer", "Movements: American modernism, Modern art, Realism, Neoclassicism, Precisionism", "#charlessheeler", "https://www.thoughtco.com/thmb/w0JASrkFAUoxKWcZf0fPrnvDY4g=/576x576/smart/filters:no_upscale()/CharlesSheelerhorizontal-3d523fa4feb3445e8545afdbf7c97e53.png" ] }, {"<NAME> (1883–1935)": [ "American painter", "Movements: Expressionism, American modernism, Modern art, Modernism, Impressionism, Realism, Precisionism", "#charlesdemuth", "https://www.getty.edu/museum/media/images/web/enlarge/113826B1V1.jpg" ] } ] }, {"Regionalism (1928-1943)": [ {"Regionalism (1928-1943)": [ "", "At the height of the Great Depression, American Regionalists turned away from European modernism and urban abstraction to embrace subjects of the heartland.", "#precisionism", "https://i.pinimg.com/originals/23/8e/74/238e7461fd27d2f336c1797d7e58d969.jpg" ] }, {"<NAME> (1889–1975)": [ "American painter", "Movements: Social realism, Synchromism, American Realism, American modernism, Modern art, Regionalism", "#thomashartbenton", "https://s3.amazonaws.com/media.wbur.org/wordpress/18/files/2015/06/AP410428023.jpg" ] }, {"<NAME> (1891–1942)": [ "American painter", "Movements: Regionalism, Impressionism, Post-Impressionism, Social realism, Modern art, American modernism, Modernism", "#grantwood", "https://toomeyco.com/wp-content/uploads/2018/03/Grant_Wood_Portrait-2-468x480.jpg" ] } ] }, {"<NAME> (1920-1940s)": [ {"<NAME> (1920-1940s)": [ "", "The Harlem Renaissance was the development of the Harlem neighborhood in New York City as a black cultural mecca in the early 20th Century and the subsequent social and artistic explosion that resulted.", "#harlemrenaissance", "https://media.nga.gov/iiif/public/objects/1/6/6/4/4/4/166444-primary-0-nativeres.ptif/full/!440,400/0/default.jpg" ] }, {"<NAME> (1899–1979)": [ "American painter, illustrator, visual arts educator", "Movements: Social realism, Harlem Renaissance", "#aarondouglas", "https://bloximages.newyork1.vip.townnews.com/omaha.com/content/tncms/assets/v3/editorial/5/6c/56cf843d-7013-592a-9228-94eaca27a1d6/5d8505911a7d7.image.jpg" ] }, {"<NAME> (1905–1998)": [ "American Artist", "Movements: Harlem Renaissance", "#loismailoujones", "https://upload.wikimedia.org/wikipedia/commons/9/9c/Lois_Jones%2C_artist_and_teacher_-_NARA_-_559227.jpg" ] }, {"<NAME> (1890–1973)": [ "American painter", "Movements: Harlem Renaissance", "#palmerhayden", "https://cdn.britannica.com/97/192097-050-45567C44/Palmer-Hayden.jpg" ] }, {"<NAME> (1917–2000)": [ "American painter", "Movements: Cubism, Contemporary art, Social realism, Modern art, Harlem Renaissance", "#jacoblawrence", "https://jonathanboos.com/wp-content/uploads/jacob-lawrence.jpg" ] } ] }, {"Surrealism (1924-1966)": [ {"Surrealism (1924-1966)": [ "", "A twentieth-century literary, philosophical and artistic movement that explored the workings of the mind, championing the irrational, the poetic and the revolutionary.", "#surrealism", "https://cdn.britannica.com/10/182610-050-77811599/The-Persistence-of-Memory-canvas-collection-Salvador-1931.jpg" ] }, {"<NAME> (1904–1989)": [ "Spanish artist", "Movements: Surrealism, Expressionism, Post-Impressionism", "#salvadordalí", "https://www.biography.com/.image/t_share/MTIwNjA4NjMzNTM4MDUzNjQ0/salvador-dali-40389-2-402.jpg" ] }, {"<NAME> (1898–1967)": [ "Belgian artist", "Movements: Surrealism, Art Deco, Cubism, Post-Impressionism, Modern art, Dada", "#renémagritte", "https://www.renemagritte.org/images/rene-magritte-photo.jpg" ] }, {"<NAME> (1908–1954)": [ "Mexican painter", "Movements: Naïve art, Modern art, Surrealism, Magical Realism, Symbolism, Naturalism, Primitivism, Social realism, Cubism", "#fridakahlo", "https://www.tradesy.com/blog/wp-content/uploads/2015/07/Frida-Portrait-Thumbnail.jpg" ] } ] }, {"Abstract Expressionism (1943-1965)": [ {"Abstract Expressionism (1943-1965)": [ "", "Abstract expressionism is the term applied to new forms of abstract art developed by American painters such as <NAME>, <NAME> and <NAME> in the 1940s and 1950s. It is often characterised by gestural brush-strokes or mark-making, and the impression of spontaneity.", "#abstractexpressionism", "https://d7hftxdivxxvm.cloudfront.net/?resize_to=fill&src=https%3A%2F%2Fartsy-media-uploads.s3.amazonaws.com%2FHNQG7N1ltr6xNab49U3lWg%252Fjackson-pollock-number-1-1949-1949.jpg&width=800&height=600&quality=80" ] }, {"<NAME> (1912–1956)": [ "American painter", "Movements: Abstract expressionism, Expressionism, Modern art, Action painting", "#jacksonpollock", "https://sothebys-com.brightspotcdn.com/dims4/default/6926a54/2147483647/strip/true/crop/782x782+628+0/resize/1200x1200!/quality/90/?url=http%3A%2F%2Fsothebys-brightspot.s3.amazonaws.com%2Fdotcom%2Fc6%2Fdc%2Ff42d7f5c40cb94387f6e9c54a873%2F3548645.JPG" ] }, {"<NAME> (1893–1968)": [ "Ukrainian artist", "Movements: Abstract expressionism", "#janetsobel", "https://www.artnet.com/WebServices/images/ll170610llgNJfDrCWBHBAD/portrait-of-janet-sobel.jpg" ] }, {"<NAME> (1908–1984)": [ "American painter", "Movements: Abstract expressionism, Modern art", "#leekrasner", "https://sothebys-com.brightspotcdn.com/dims4/default/7b36052/2147483647/strip/true/crop/736x736+2020+690/resize/1200x1200!/quality/90/?url=http%3A%2F%2Fsothebys-brightspot.s3.amazonaws.com%2Fdotcom%2F65%2Fc8%2F87dbb7704b1f8cd1ffde866b52ed%2Fgettyimages-3227258.jpg" ] }, {"<NAME> (1904–1997)": [ "American-Dutch artist", "Movements: Abstract expressionism, Expressionism, Modern art", "#willemdekooning", "https://sothebys-com.brightspotcdn.com/dims4/default/8921da1/2147483647/strip/true/crop/949x949+1417+242/resize/1200x1200!/quality/90/?url=http%3A%2F%2Fsothebys-brightspot.s3.amazonaws.com%2Fdotcom%2Faa%2Ff8%2Fb59b91604fcdb0f916fbe4149d53%2Fgettyimages-3243871.jpg" ] }, {"<NAME> (1908–1984)": [ "American painter", "Movements: Abstract expressionism, Expressionism, Contemporary art", "#elainedekooning", "https://theartgorgeous.com/wp-content/uploads/2019/07/d7hftxdivxxvm.cloudfront.net_.jpeg" ] }, {"<NAME> (1904–1997)": [ "American painter", "Movements: Abstract expressionism, Harlem Renaissance", "#normanlewis", "https://m.theartstory.org/images20/new_design/c/c_lewis_norman.jpg" ] } ] } ]
97ed5c61668d2678bec8ba4907b4001313b56353
[ "Markdown", "JavaScript" ]
2
Markdown
RosettaYH/ModernArt
7f553276d12b6fcf91d0cad8c4bfc5ce1b3e6f7f
effb322e5917f961e57ea7d018488de6d4442394
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from 'src/app/services/auth.service'; import { CarService } from 'src/app/services/car.service'; @Component({ selector: 'app-admin', templateUrl: './admin.component.html', styleUrls: ['./admin.component.css'] }) export class AdminComponent implements OnInit { public cars; constructor(private carService:CarService, private authService:AuthService, private router: Router) { } ngOnInit(): void { this.getCars(); } getCars(){ this.carService.getCars().subscribe( data => {this.cars = data}, err => console.error(err), () => console.log('cars loaded') ); } logout(){ this.authService.logout(); } goToForm(){ this.router.navigate(['']); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpResponseBase } from '@angular/common/http'; import { Observable } from 'rxjs'; import { stringify } from '@angular/compiler/src/util'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; @Injectable() export class CarService { constructor(private http:HttpClient) { } getCars(){ return this.http.get('/server/api/v1/cars', { headers: new HttpHeaders({ 'Authorization': 'Bearer ' + localStorage.getItem('access_token') || '' }) }); } getCar(id: number){ return this.http.get('/server/api/v1/cars/'+id, { headers: new HttpHeaders({ 'Authorization': 'Bearer ' + localStorage.getItem('access_token') || '' }) }); } createCarRegistration(car){ let body = JSON.stringify(car); return this.http.post('/server/api/v1/cars', body, httpOptions); } deleteCar(id:number){ return this.http.delete('/server/api/v1/cars/'+id, { headers: new HttpHeaders({ 'Authorization': 'Bearer ' + localStorage.getItem('access_token') || '' }) }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { CarService } from 'src/app/services/car.service'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-view-registration', templateUrl: './view-registration.component.html', styleUrls: ['./view-registration.component.css'] }) export class ViewRegistrationComponent implements OnInit { public carReg; public tempId=this.route.snapshot.params.id; constructor(private carService: CarService, private route: ActivatedRoute, private router:Router) { } ngOnInit(): void { this.getCarReg(this.tempId); } getCarReg(id:number){ this.carService.getCar(id).subscribe( data =>{ this.carReg = data; }, err => console.error(err), () => console.log('cars loaded') ); } deleteCarFromRegistration(){ this.carService.deleteCar(this.tempId).subscribe( err => console.error(err), () => console.log('car deleted') ) this.router.navigate(['/admin']); } }
878d57f2e487d412557a4cd27441e47d776c0d4d
[ "TypeScript" ]
3
TypeScript
dudesup/register-system-angular
bf2c69c0a9a9204d2f40f807d12037fa3276bb22
36151dc6b7dc61711c276903af191b672255d5d2
refs/heads/master
<file_sep>#define GPS_RX 3 #define GPS_TX 2 #define GPS_Serial_Baud 4800 #include <SoftwareSerial.h> #include "TinyGPS++.h" //Libs referente ao display #include <SPI.h> #include <Adafruit_GFX.h> #include <Adafruit_PCD8544.h> Adafruit_PCD8544 display = Adafruit_PCD8544(11,10,9,8,7); // Software SPI (slower updates, more flexible pin options): // pin 7 - Serial clock out (SCLK) // pin 6 - Serial data out (DIN) // pin 5 - Data/Command select (D/C) // pin 4 - LCD chip select (CS) // pin 3 - LCD reset (RST) SoftwareSerial gpsSerial(GPS_RX, GPS_TX); TinyGPSPlus gps; float gpsLat0; float gpsLong0; float gpsLatUltimoLido = 0.00; float gpsLongUltimoLido = 0.00; float somaDistancia = 0.00; const double larguraPneu = 165.00; const double perfilPneu = 70.00; //Perfil original 75, tirando 5 para compensar o amassado no asfalta (<NAME>) const double aroPneu = 14.00; const double relacaoMarchaPrimeira = 3.846; const double relacaoMarchaSegunda = 2.038; const double relacaoMarchaTerceira = 1.281; const double relacaoMarchaQuarta = 0.951; const double relacaoMarchaQuinta = 0.756; const double relacaoMarchaRe = 3.615; const double relacaoMarchaDiferencial = 4.73; /* tabela de cursos de direcao Este - Nordeste ENE Este - Sudeste ESE Leste E Nordeste NE Noroeste NW Norte - Nordeste NNE Norte - Noroeste NNW Oeste W Oeste - Noroeste WNW Oeste - Sudoeste WSW Sudeste SE Sudoeste SW Sul S Sul - Sudeste SSE Sul - Sudoeste SSW */ void setup() { Serial.begin(115200); gpsSerial.begin(GPS_Serial_Baud); display.begin(); display.setContrast(50); display.display(); // show splashscreen delay(2000); display.clearDisplay(); // clears the screen and buffer } void loop() { //int POT = analogRead(0); // Potenciometro - pino central no pino A0 //double velocidade = (map(POT, 0, 1023, 200, 1)); bool newData = false; unsigned long chars; // For one second we parse GPS data and report some key values for (unsigned long start = millis(); millis() - start < 200;) { while (gpsSerial.available()) { char c = gpsSerial.read(); // Serial.write(c); //apague o comentario para mostrar os dados crus if (gps.encode(c)) // Atribui true para newData caso novos dados sejam recebidos newData = true; } } if (newData) { //colegio avante 970m carro, ape 600m const double AVANTE_LAT = -22.692943; const double AVANTE_LNG = -46.988746; //Gerando o ponto inicial fixo do momento que pegou sinal do GPS. if (gpsLat0 == 0.0) { gpsLat0 = gps.location.lat(); gpsLong0 = gps.location.lng(); } if (gpsLatUltimoLido == 0.0) { somaDistancia = 0.00; gpsLatUltimoLido = gps.location.lat(); gpsLongUltimoLido = gps.location.lng(); } else { somaDistancia = somaDistancia + (gps.distanceBetween(gps.location.lat(),gps.location.lng(),gpsLatUltimoLido,gpsLongUltimoLido) / 1000.0); gpsLatUltimoLido = gps.location.lat(); gpsLongUltimoLido = gps.location.lng(); } double distanceKmAvante = gps.distanceBetween(gps.location.lat(),gps.location.lng(),AVANTE_LAT,AVANTE_LNG) / 1000.0; double courseToAvante = gps.courseTo(gps.location.lat(),gps.location.lng(),AVANTE_LAT,AVANTE_LNG); double distanceKmPercorrida = gps.distanceBetween(gps.location.lat(),gps.location.lng(),gpsLat0,gpsLong0) / 1000.0; double velocidade = gps.speed.kmph(); //double velocidade = random(170); /* Serial.println("########################################################################"); Serial.print("Velocidade: " + String(gps.speed.kmph()) + " RPM Primeira: "); Serial.println((velocidade * 1000 * relacaoMarchaPrimeira * relacaoMarchaDiferencial) / (60 * 3.1416 * (larguraPneu * perfilPneu * 0.00002 + aroPneu * 0.0254)),0); Serial.print("Velocidade: " + String(gps.speed.kmph()) + " RPM Segunda: "); Serial.println((velocidade * 1000 * relacaoMarchaSegunda * relacaoMarchaDiferencial) / (60 * 3.1416 * (larguraPneu * perfilPneu * 0.00002 + aroPneu * 0.0254)),0); Serial.print("Velocidade: " + String(gps.speed.kmph()) + " RPM Terceira: "); Serial.println((velocidade * 1000 * relacaoMarchaTerceira * relacaoMarchaDiferencial) / (60 * 3.1416 * (larguraPneu * perfilPneu * 0.00002 + aroPneu * 0.0254)),0); Serial.print("Velocidade: " + String(gps.speed.kmph()) + " RPM Quarta: "); Serial.println((velocidade * 1000 * relacaoMarchaQuarta * relacaoMarchaDiferencial) / (60 * 3.1416 * (larguraPneu * perfilPneu * 0.00002 + aroPneu * 0.0254)),0); Serial.print("Velocidade: " + String(gps.speed.kmph()) + " RPM Quinta: "); Serial.println((velocidade * 1000 * relacaoMarchaQuinta * relacaoMarchaDiferencial) / (60 * 3.1416 * (larguraPneu * perfilPneu * 0.00002 + aroPneu * 0.0254)),0); */ display.clearDisplay(); display.setTextSize(3); display.setTextColor(BLACK); display.setCursor(0,0); display.println(" " + String(velocidade,0)); display.println((velocidade * 1000 * relacaoMarchaTerceira * relacaoMarchaDiferencial) / (60 * 3.1416 * (larguraPneu * perfilPneu * 0.00002 + aroPneu * 0.0254)),0); display.display(); //display.setTextSize(2); //display.setTextColor(BLACK); //display.println(velocidade,0); //display.setTextSize(1); //display.setTextColor(BLACK); //display.println("RPM"); //display.setTextSize(2); //display.setTextColor(BLACK); //display.println((velocidade * 1000 * relacaoMarchaQuinta * relacaoMarchaDiferencial) / (60 * 3.1416 * (larguraPneu * perfilPneu * 0.00002 + aroPneu * 0.0254)),0); } } <file_sep># calculo-rpm-por-velocidade-arduino Calculo do RPM baseado na velocidade do carro. TO-DO 1. Indicador de marcha para fazer a relacao de marchas corretamente, por TPS ou sensor cambio, para identificacao automatica da Marcha. 2. Troca do Display atual pelo RealDash. 3. Postar Esquema de ligacao
4faa956cc61424f9eec59ae226db61c8992cb16d
[ "Markdown", "C++" ]
2
C++
wfp2002/calculo-rpm-por-velocidade-arduino
6e6d140370df2518ca177c87539bc760694975c8
4bcea77564ba564521c3c79caa9b55dedc48fb95
refs/heads/master
<repo_name>QwXm/SignSystem<file_sep>/src/config/AppConfig.java package config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; /** * Created by Administrator on 2016/10/11. */ @Configuration @EnableJpaRepositories(basePackages = "dao" ) public class AppConfig { @Bean(name = "entityManagerFactory")//使用Spring Data方式,这里的Bean名称必须为 entityManagerFactory public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource); entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter); entityManagerFactoryBean.setPackagesToScan("entity"); return entityManagerFactoryBean; } @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .build(); } @Bean public JpaVendorAdapter jpaVendorAdapter() { HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); jpaVendorAdapter.setDatabase(Database.H2); jpaVendorAdapter.setGenerateDdl(true); jpaVendorAdapter.setShowSql(true); jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.H2Dialect"); return jpaVendorAdapter; } @Bean//必须有一个名为transactionManager的Bean public PlatformTransactionManager transactionManagers(EntityManagerFactory factory) { return new JpaTransactionManager(factory); } } <file_sep>/src/dao/StudentDao.java package dao; import entity.Student; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by Administrator on 2016/10/11. */ @Repository public interface StudentDao extends JpaRepository<Student,Integer> { Student findByName(String name); List<Student> findByAgeBetween(int min,int max); } <file_sep>/src/test/StudentTest.java package test; import config.AppConfig; import dao.StudentDao; import entity.Student; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import java.util.Date; import java.util.List; import static org.junit.Assert.assertEquals; /** * Created by Administrator on 2016/10/11. */ @RunWith(SpringRunner.class) @ContextConfiguration(classes = AppConfig.class) public class StudentTest { @Autowired private StudentDao studentDao; @Test public void testAdd() { Student student = new Student(); student.setAddress("天津市西青区津静路26号"); student.setName("王五"); student.setAge(23); student.setBrithday(new Date()); studentDao.save(student); assertEquals(1,studentDao.count()); } @Test public void testGetStudentWithAge() { testAdd(); List<Student> students = studentDao.findByAgeBetween(10,30); assertEquals(1,students.size()); } }
987f37015b838bb2703cc73f57f7e57124787404
[ "Java" ]
3
Java
QwXm/SignSystem
5a7bcd012d6cc25ea78d864622dc6446314a65b5
ef844d7712ec9b16a5ce9fef925352cb2cbff261
refs/heads/master
<repo_name>sumenkov/alien_invasion<file_sep>/game_finctions.go package main import ( "fmt" "github.com/veandco/go-sdl2/sdl" ) // Подгружаем картинки func textureFromBMP(renderer *sdl.Renderer, filename string) *sdl.Texture { img, err := sdl.LoadBMP(filename) if err != nil { panic(fmt.Errorf("loading %v: %v", filename, err)) } defer img.Free() tex, err := renderer.CreateTextureFromSurface(img) if err != nil { panic(fmt.Errorf("creating texture from %v: %v", filename, err)) } return tex } <file_sep>/main.go package main import ( "github.com/veandco/go-sdl2/sdl" ) const ( screenWidth = 1366 screenHeight = 688 ) var window *sdl.Window var renderer *sdl.Renderer var err error func main() { if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil { println("initializing SDL:", err) return } window, err = sdl.CreateWindow( "Alien Invasion", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, screenWidth, screenHeight, sdl.WINDOW_OPENGL) if err != nil { println("initializing Window:", err) return } defer window.Destroy() renderer, err = sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED) if err != nil { println("initializing Renderer:", err) return } defer renderer.Destroy() ship := newShip(renderer) var alienPool []alien // Вычисляем количество пришельцев numAlienX := (screenWidth - alienWidth*2.0) / (alienWidth * 2.0) numAlienY := (screenHeight - alienWidth*3) / (alienWidth * 2) for i := 0; i < int(numAlienX); i++ { for j := 0; j < numAlienY; j++ { x := float64(i)/numAlienX*screenWidth + alienWidth*1.5 y := float64(j)*alienHeight*3.0/2 + alienHeight*1.5 alien := newAlien(renderer, x, y) alienPool = append(alienPool, alien) } } initBulletPool(renderer) for { for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() { switch event.(type) { case *sdl.QuitEvent: return } } renderer.SetDrawColor(230, 230, 230, 230) renderer.Clear() // Помещаем объекты в окно ship.draw(renderer) for _, alien := range alienPool { alien.draw(renderer) } for _, b := range bulletPool { b.draw(renderer) b.update() } // Обновляем положение объектов ship.update() renderer.Present() } } <file_sep>/bullet.go package main import ( "math" "github.com/veandco/go-sdl2/sdl" ) const ( bulletWidth = 3 bulletHeight = 15 bulletSpeed = 0.4 ) type bullet struct { tex *sdl.Texture x, y float64 angle float64 active bool } func newBullet(renderer *sdl.Renderer) (b bullet) { b.tex = textureFromBMP(renderer, "images/bullet.bmp") return b } func (b *bullet) draw(renderer *sdl.Renderer) { if !b.active { return } x := int32(b.x) y := int32(b.y) renderer.Copy(b.tex, &sdl.Rect{W: bulletWidth, H: bulletHeight}, &sdl.Rect{X: x, Y: y, W: bulletWidth, H: bulletHeight}) } func (b *bullet) update() { // Направление движения пули b.x += bulletSpeed * math.Cos(b.angle) b.y += bulletSpeed * math.Sin(b.angle) // убираем пулю, если она вышла за размер окна // b.x > screenWidth || b.x < 0 || b.y > screenHeight || b.y < 0 if b.y < 0 { b.active = false } } var bulletPool []*bullet func initBulletPool(renderer *sdl.Renderer) { for i := 0; i < 10; i++ { b := newBullet(renderer) bulletPool = append(bulletPool, &b) } } func bulletFromPool() (*bullet, bool) { for _, b := range bulletPool { if !b.active { return b, true } } return nil, false } <file_sep>/ship.go package main import ( "math" "time" "github.com/veandco/go-sdl2/sdl" ) const ( shipSpeed = 0.2 shipWidth = 60 shipHeight = 48 shipShotCooldown = time.Millisecond * 250 // 0.25 sec ) type ship struct { tex *sdl.Texture x, y float64 lastShot time.Time } // newShip - создаем новый корабль func newShip(renderer *sdl.Renderer) (s ship) { s.tex = textureFromBMP(renderer, "images/ship.bmp") // Стартовое положение корабля s.x = (screenWidth - shipWidth) / 2.0 s.y = screenHeight - shipHeight return s } func (s *ship) draw(renderer *sdl.Renderer) { renderer.Copy(s.tex, &sdl.Rect{W: shipWidth, H: shipHeight}, &sdl.Rect{X: int32(s.x), Y: int32(s.y - 10), W: shipWidth, H: shipHeight}) // s.y - 10 Просто для красоты } // Обновляем положение корабля func (s *ship) update() { keys := sdl.GetKeyboardState() if keys[sdl.SCANCODE_LEFT] == 1 { // Перемещение в лево if s.x > 0 { s.x -= shipSpeed } } else if keys[sdl.SCANCODE_RIGHT] == 1 { // Перемещение в право if s.x < screenWidth-shipWidth { s.x += shipSpeed } } if keys[sdl.SCANCODE_SPACE] == 1 { if time.Since(s.lastShot) >= shipShotCooldown { // задержка появления новой пули s.shoot(s.x+16, s.y-16) s.shoot(s.x+42, s.y-16) s.lastShot = time.Now() // время появления пули } } } func (s *ship) shoot(x, y float64) { if b, ok := bulletFromPool(); ok { b.active = true b.x = x b.y = y b.angle = 270 * (math.Pi / 180) // Переводим в радианы } } <file_sep>/alien.go package main import ( "github.com/veandco/go-sdl2/sdl" ) const ( //alienSpeed = 0.05 alienWidth = 60 alienHeight = 58 ) type alien struct { tex *sdl.Texture x, y float64 } func newAlien(renderer *sdl.Renderer, x, y float64) (a alien) { a.tex = textureFromBMP(renderer, "images/alien.bmp") // Стартовое положение пришельца a.x = x a.y = y return a } func (a *alien) draw(renderer *sdl.Renderer) { x := a.x - alienWidth y := a.y - alienHeight renderer.CopyEx(a.tex, &sdl.Rect{W: alienWidth, H: alienHeight}, &sdl.Rect{X: int32(x), Y: int32(y), W: alienWidth, H: alienHeight}, 180, &sdl.Point{X: alienWidth / 2.0, Y: alienHeight / 2.0}, sdl.FLIP_NONE) }
6b8b387f00c2f194a9acabf3937d4781439749e5
[ "Go" ]
5
Go
sumenkov/alien_invasion
da5cd893687af634ecd9e24e0d86ca81877560a9
0cc3bf1ea1d0dc9a5ceb7ada5eb41fd7e86a1e62
refs/heads/master
<repo_name>yzp3/TaskPathPlan<file_sep>/pages/myMap/myMap.js // pages/myMap.js // 引入SDK核心类 var QQMapWX = require('../../libs/qqmap-wx-jssdk.js'); // 实例化API核心类 var qqmapsdk = new QQMapWX({ key: '<KEY>' // 必填 }); Page({ /** * 页面的初始数据 */ data: { longitude: 116.46, latitude: 39.92, scale: 13, polyline: [], markers: [], }, myGet: function(){ var that = this; wx.getLocation({ type: 'wgs84', //返回可以用于wx.openLocation的经纬度 success: function (res) { var log = res.longitude var lat = res.latitude that.setData({ longitude: log, latitude: lat }) }, fail: function () { wx.showModal({ title: '授权失败', content: '获取位置信息失败,使用功能将受到限制!', confirmText: '授权开启', cancelText: '我知道了', }) } }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { let that = this; // 获取位置信息 wx.getSetting({ success: (res) => { console.log(res) if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权 wx.showModal({ title: '是否授权当前位置', content: '需要获取您的地理位置,请确认授权,否则无法获取您所需数据', success: function (res) { console.log(res) if (res.cancel) { that.setData({ isshowCIty: false }) wx.showToast({ title: '授权失败', icon: 'success', duration: 1000 }) } else if (res.confirm) { wx.openSetting({ success: function (dataAu) { console.log(dataAu) if (dataAu.authSetting["scope.userLocation"] == true) { wx.showToast({ title: '授权成功', icon: 'success', duration: 1000 }) //再次授权,调用getLocationt的API that.myGet(); } else { wx.showToast({ title: '授权失败', icon: 'success', duration: 1000 }) } } }) } } }) } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化进入 that.myGet(); } else { //授权后默认加载 that.myGet(); } } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { this.mapCtx = wx.createMapContext('myMap'); }, /** * 生命周期函数--监听页面显示 */ onShow: function () { // this.mapCtx.moveToLocation() }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, /** * 点击事件 */ controltap: function (e) { console.log(e); var cid = e.currentTarget.id; if (cid == "moveToLocation") {//点击了定位图片 this.mapCtx.moveToLocation() } else if (cid == "plus") {//点击了加号 let scale = this.data.scale; if (scale >= 5 && scale <= 18) { scale++; if(scale > 18){ scale = 18 } if (scale < 5) { scale = 5 } this.setData({ scale }) } } else if (cid == "reduce") { let scale = this.data.scale; if (scale >= 5 && scale <= 18) { scale--; if (scale > 18) { scale = 18 } if (scale < 5) { scale = 5 } this.setData({ scale }) } } else{ wx.navigateTo({ url: '/pages/'+cid+'/'+cid, }) } // if(cid == "route"){ // wx.navigateTo({ // url: '/pages/selectPoint/selectPoint', // }) // } // if(cid == "search"){ // wx.navigateTo({ // url: '/pages/search/search', // }) // } // if (cid == "user") { // wx.navigateTo({ // url: '/pages/user/user', // }) // } }, })<file_sep>/pages/mapPoint/mapPoint.js // mapPoint/mapPoint.js Page({ /** * 页面的初始数据 */ data: { point:"", longitude:116, latitude:39, }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { console.log(options); var cid = options.cid; var that = this; wx.getLocation({ type:"gcj02", success: function(res) { var log = res.longitude; var lat = res.latitude; that.setData({ longitude: log, latitude: lat, point: cid }) }, }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { var that = this; wx.chooseLocation({ success: function(res) { var point = that.data.point; var dataPoint = { id: point, lat: res.latitude, log: res.longitude, name: res.name } //回传数据 var pages = getCurrentPages(); var currentPage = pages[pages.length-1]; var prePage = pages[pages.length-2]; if (point === "startPoint") { console.log(1); prePage.setData({ startPoint: dataPoint }) } else if (point === "endPoint") { console.log(2); prePage.setData({ endPoint: dataPoint }) } else { console.log(3); var routePoint = prePage.data.routePoint; routePoint.pop(); routePoint.push(dataPoint); prePage.setData({ routePoint }) } wx.navigateBack({ delta: 1 }) }, }) }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })<file_sep>/pages/selectPoint/selectPoint.js // selectPoint/selectPoint.js// 引入SDK核心类 var QQMapWX = require('../../libs/qqmap-wx-jssdk.js'); // 实例化API核心类 var qqmapsdk = new QQMapWX({ key: '<KEY>' // 必填 }); Page({ /** * 页面的初始数据 */ data: { isDisplay: false, error: "", startPoint: {}, endPoint: {}, routePoint: [], longitude: 0, latitude: 0, polyline: [{ points: [], color: '#0ff51a', width: 5 }], markers: [{}, {}], imgSrc: [ "/imgs/car-active.png", "/imgs/bus.png", "/imgs/walk.png", ], myMode: 'driving', current: 0, info: [], distance: 0, time: 0, busInfo: [], sortPoint: [], flag: false }, /** * 导航预览 */ previewtap: function(e){ var id = e.target.id; var ins = ""; var mode = this.data.myMode if(mode==="driving" || mode==="walking"){ let info = this.data.info; if (mode === "driving"){ ins += "从起点出发"; } for (let i in info) { ins += info[i]; ins += "\n"; } ins = ins + "到达" + this.data.endPoint.name; }else if(mode==="transit"){ let info = this.data.busInfo[id].ins; for (let i in info) { ins += info[i]; ins += "\n"; } ins = ins + "到达" + this.data.endPoint.name; } wx.navigateTo({ url: '../routeNavigation/routeNavigation?context='+ins, }) }, /** * 模式选择,点击图片 */ imgtap: function(e){ var cid = e.currentTarget.id; if(cid == 0){ this.setData({ imgSrc: [ "/imgs/car-active.png", "/imgs/bus.png", "/imgs/walk.png", ], myMode: 'driving', current: 0, }) }else if(cid == 1){ this.setData({ imgSrc: [ "/imgs/car.png", "/imgs/bus-active.png", "/imgs/walk.png", ], myMode: 'transit' }) }else if(cid == 2){ this.setData({ imgSrc: [ "/imgs/car.png", "/imgs/bus.png", "/imgs/walk-active.png", ], myMode: 'walking', current: 0, }) } this.pathPlantap(); }, /** * 输入框获得焦点 */ pointtap: function(e){ var cid = e.currentTarget.id; var that = this; wx.chooseLocation({ success: function (res) { var point = cid; var dataPoint = { id: point, lat: res.latitude, log: res.longitude, name: res.name } //回传数据 var prePage = that; if (point === "startPoint") { console.log(1); prePage.setData({ startPoint: dataPoint }) } else if (point === "endPoint") { console.log(2); prePage.setData({ endPoint: dataPoint }) } else { console.log(3); var routePoint = prePage.data.routePoint; routePoint[dataPoint.id] = dataPoint; prePage.setData({ routePoint }) } }, }) }, /** * 添加途径点 */ addPointtap: function(e){ var point = this.data.routePoint; point.push({ }) this.setData({ routePoint: point }) }, /** * 计算距离 */ calDistance: function(newFrom, route){ var sortPoint = this.data.sortPoint; sortPoint.push(newFrom); var _this = this; qqmapsdk.calculateDistance({ mode: "straight", from: newFrom, to: route, success: function (res) {//成功后的回调 var ele = res.result.elements; ele.sort(function cmp(a, b) { return a.distance - b.distance; }) var to = ele.shift().to; newFrom = { latitude: to.lat, longitude: to.lng } route = []; if (ele.length > 0) { for (let i in ele) { route.push({ latitude: ele[i].to.lat, longitude: ele[i].to.lng }); } _this.calDistance(newFrom, route); }else{ sortPoint.push({ latitude: to.lat, longitude: to.lng }); sortPoint.push({ latitude: _this.data.endPoint.lat, longitude: _this.data.endPoint.log }); console.log(sortPoint) } _this.setData({ sortPoint: sortPoint }) }, fail: function (error) { console.error(error); }, complete: function (res) { console.log(res); } }) }, /** * 多地点路径规划 */ mutiPoint: function(){ var routePoint = this.data.routePoint; var _this = this; if(routePoint.length == 0){ var sortPoint = []; sortPoint.push( { latitude: _this.data.endPoint.lat, longitude: _this.data.endPoint.log }, { latitude: _this.data.startPoint.lat, longitude: _this.data.startPoint.log }, ); _this.setData({ sortPoint: sortPoint }) return true; } var route = []; for(let i in routePoint){ route.push({ latitude: routePoint[i].lat, longitude: routePoint[i].log }); } var newFrom ={ latitude: this.data.startPoint.lat, longitude: this.data.startPoint.log } this.calDistance(newFrom, route); return true; }, /** * 开始规划 */ pathPlantap: function (e) { this.setData({ sortPoint: [], markers: [], polyline: [{ points: [], color: '#0ff51a', width: 5 }], flag: true, info: [], distance: 0, time: 0, busInfo: [], }) if(this.data.flag && this.mutiPoint()){ var _this = this; let data = this.data; console.log(this); //调用距离计算接口 var myMode = _this.data.myMode; var sortPoint = _this.data.sortPoint; var colors = ["#0ff51a", "#ffb6c1", "#4169e1", "#ff8c00"]; var c = 0; for(var j = 0; j < sortPoint.length-1; j++){ let markers = _this.data.markers; if(c == 4){ c = 0; } markers.push( { id: j, title: j+1, callout:{ content: j+1, fontSize: 20, textAlign: 'center' }, latitude: sortPoint[j].latitude, longitude: sortPoint[j].longitude, iconPath: "/imgs/location.png", width: 30, height: 30, }, { id: j + 1, title: j + 2, callout: { content: j + 2, fontSize: 20, textAlign: 'center' }, latitude: sortPoint[j+1].latitude, longitude: sortPoint[j+1].longitude, iconPath: "/imgs/location.png", width: 30, height: 30, } ) _this.setData({ markers: markers }) qqmapsdk.direction({ mode: myMode,//'transit'(公交路线规划) //from参数不填默认当前地址 from: sortPoint[j], to: sortPoint[j+1], success: function (res) { console.log(res); // 驾车或步行 if (myMode === 'driving' || myMode === 'walking') { let ret = res; var coors = ret.result.routes[0].polyline; var pl = []; //坐标解压(返回的点串坐标,通过前向差分进行压缩) var kr = 1000000; for (var i = 2; i < coors.length; i++) { coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr; } //将解压后的坐标放入点串数组pl中 for (var i = 0; i < coors.length; i += 2) { pl.push({ latitude: coors[i], longitude: coors[i + 1] }) } var step = res.result.routes[0].steps, ins = _this.data.info; for (let s in step) { ins.push(step[s].instruction); } if (j < sortPoint.length - 2){ ins.push("到达"+_this.data.routePoint[j].name) } var poly = _this.data.polyline; poly.push({ points: pl, color: colors[c], width: 5 }); //设置polyline属性,将路线显示出来,将解压坐标第一个数据作为起点 _this.setData({ latitude: pl[0].latitude, longitude: pl[0].longitude, polyline: poly, distance: _this.data.distance+res.result.routes[0].distance, time: _this.data.time+res.result.routes[0].duration, info: ins, flag: false }) console.log(ins) } // 公交 else if (myMode === 'transit') { var rs = []; for (let k in res.result.routes) { var ret = res.result.routes[k]; var count = ret.steps.length; var pl = []; var coors = []; //路线 var route = { distance: ret.distance, time: ret.duration, ins: [], lines: [], title: "", walk: 0, } // var ins = []; //获取各个步骤的polyline for (var i = 0; i < count; i++) { if (ret.steps[i].mode == 'WALKING' && ret.steps[i].polyline) { coors.push(ret.steps[i].polyline); route.walk += ret.steps[i].distance; let step = ret.steps[i].steps; // ins.push("步行") for (let s in step) { route.ins.push(step[s].instruction); } // route.ins.push(ins); // ins = []; } if (ret.steps[i].mode == 'TRANSIT' && ret.steps[i].lines[0].polyline) { coors.push(ret.steps[i].lines[0].polyline); var line = ret.steps[i].lines[0];//TODO route.title = (line.title + "路"); route.ins.push("乘坐开往" + line.destination.title + "方向的" + line.title + "路"); route.ins.push("在" + line.geton.title + "上车," + "在" + line.getoff.title + "下车,"); } } //坐标解压(返回的点串坐标,通过前向差分进行压缩) var kr = 1000000; for (var i = 0; i < coors.length; i++) { for (var j = 2; j < coors[i].length; j++) { coors[i][j] = Number(coors[i][j - 2]) + Number(coors[i][j]) / kr; } } //定义新数组,将coors中的数组合并为一个数组 var coorsArr = []; for (var i = 0; i < coors.length; i++) { coorsArr = coorsArr.concat(coors[i]); } //将解压后的坐标放入点串数组pl中 for (var i = 0; i < coorsArr.length; i += 2) { pl.push({ latitude: coorsArr[i], longitude: coorsArr[i + 1] }) } rs.push(route); route = {}; } var poly = _this.data.polyline; poly.push({ points: pl, color: colors[c], width: 5 }); //设置polyline属性,将路线显示出来,将解压坐标第一个数据作为起点 _this.setData({ latitude: pl[0].latitude, longitude: pl[0].longitude, polyline: poly, busInfo: rs, flag: false }) }//else if (myMode === 'walking') { // } if (_this.data.endPoint != null) { _this.setData({ isDisplay: true }) } }, fail: function (error) { console.error(error); _this.setData({ error: error.message, isDisplay: false, }) }, complete: function (res) { console.log(res); c++; } }); } //保存历史记录 let startName = _this.data.startPoint.name === undefined ? '我的位置' : _this.data.startPoint.name; let endName = _this.data.endPoint.name === undefined ? '' : _this.data.endPoint.name; var dataRecord = '->'; for (let t in _this.data.routePoint){ dataRecord = dataRecord + _this.data.routePoint[t].name + '->'; } dataRecord = startName + dataRecord + endName; var recs = wx.getStorageSync('records'); if(recs){ recs.push(dataRecord); let x = new Set(recs); recs = [...x]; }else{ recs = [dataRecord]; } wx.setStorageSync('records', recs); } }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; wx.getLocation({ type: "gcj02", success: function (res) { var log = res.longitude; var lat = res.latitude; // var start = { // log: log, // lat: lat, // id: "startPoint" // } that.data.startPoint.log = log; that.data.startPoint.lat = lat; that.data.startPoint.id = "startPoint"; that.setData({ latitude: lat, longitude: log, }) }, }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })<file_sep>/pages/search/search.js // pages/search/search.js var QQMapWX = require('../../libs/qqmap-wx-jssdk.js'); // 实例化API核心类 var qqmapsdk = new QQMapWX({ key: '<KEY>' // 必填 }); Page({ /** * 页面的初始数据 */ data: { displayKey: true, searchKey: [ "美食", "酒店", "景点", "超市", "银行", "网吧", ], markers: [], suggestion: [], backfill: "", }, /** * 确认 */ confirmtap: function(e){ console.log(e) var _this = this; //回传数据 var pages = getCurrentPages(); var currentPage = pages[pages.length - 1]; var prePage = pages[pages.length - 2]; if (e.detail.lat === undefined) { qqmapsdk.search({ keyword: e.detail.value, success: function (res) { var mks = [] for (var i = 0; i < res.data.length; i++) { mks.push({ // 获取返回结果,放到mks数组中 title: res.data[i].title, id: res.data[i].id, latitude: res.data[i].location.lat, longitude: res.data[i].location.lng, iconPath: "/imgs/location.png", //图标路径 width: 30, height: 30 }) } prePage.setData({ //设置markers属性,将搜索结果显示在地图中 // scale: 15, markers: mks, }) }, fail: function (res) { console.log(res); }, complete: function (res) { console.log(res); } }) }else{ prePage.setData({ //设置markers属性,将搜索结果显示在地图中 // scale: 15, markers: [{ // 获取返回结果,放到mks数组中 title: e.detail.value, id: 0, latitude: e.detail.lat, longitude: e.detail.lng, iconPath: "/imgs/location.png", //图标路径 width: 30, height: 30 }], latitude: e.detail.lat, longitude: e.detail.lng, }) } wx.navigateBack(); }, //数据回填方法 backfill: function (e) { var id = e.currentTarget.id; for (var i = 0; i < this.data.suggestion.length; i++) { if (i == id) { var title = this.data.suggestion[i].title this.setData({ backfill: title }); this.confirmtap({ detail: { value: title, lat: this.data.suggestion[i].latitude, lng: this.data.suggestion[i].longitude, } }) } } }, //触发关键词输入提示事件 getsuggest: function (e) { var _this = this; var loc = ""; wx.getLocation({ success: function(res) { var lat = res.latitude; var lng = res.longitude; loc = lat+","+lng; }, }) //调用关键词提示接口 qqmapsdk.getSuggestion({ //获取输入框值并设置keyword参数 keyword: e.detail.value, //用户输入的关键词,可设置固定值,如keyword:'KFC' location: loc, //region:'安徽', //设置城市名,限制关键词所示的地域范围,非必填参数 success: function (res) {//搜索成功后的回调 var sug = []; for (var i = 0; i < res.data.length; i++) { sug.push({ // 获取返回结果,放到sug数组中 title: res.data[i].title, id: res.data[i].id, addr: res.data[i].address, city: res.data[i].city, district: res.data[i].district, latitude: res.data[i].location.lat, longitude: res.data[i].location.lng }); } _this.setData({ //设置suggestion属性,将关键词搜索结果以列表形式展示 suggestion: sug, displayKey: false }); }, fail: function (error) { console.error(error); }, complete: function (res) { console.log(res); } }); }, /** * 返回 */ backtap: function(e){ wx.navigateBack({ }) }, /** * 关键字 */ searchCommon: function(e){ var key = e.target.id; this.setData({ backfill: key, }) this.confirmtap({ detail: {value: key} }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })<file_sep>/README.md # TaskPathPlan 基于微信小程序的任务路径规划系统,支持多点导航(base Wechat MiniProgram)
738ae5c56706be876aeaede2056688a0a08cb28e
[ "JavaScript", "Markdown" ]
5
JavaScript
yzp3/TaskPathPlan
df4b0800dbd43cc5ea1aa793159e73be3de6e2bb
0f0c5725830e7608edfa412fbe80510a2ce6ce35
refs/heads/master
<repo_name>microsoft/onnxruntime-tvm<file_sep>/python/tvm/micro/__init__.py """uTVM module for bare-metal backends. uTVM (or the micro backend) enables provides support for bare-metal devices. Its targets currently include a host-emulated device which is used for testing, and JTAG-based openocd device which allows actual interfacing with microdevices. """ from ..contrib import binutil from .base import Session, cross_compiler, create_micro_lib <file_sep>/apps/sgx/enclave/Makefile # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. MODEL ?= resnet NUM_THREADS ?= 4 BATCH_SIZE ?= 64 TRAINING ?= true DEBUG ?= false build_dir := ../build ifeq ($(DEBUG), false) debug := release xargo_args := --release else debug := debug endif target=target/x86_64-unknown-linux-sgx/$(debug)/libmodel-enclave.a $(target): $(build_dir)/libmodel.a **/* $(TVM_DIR)/rust/patched.txt RUST_TARGET_PATH=$(shell pwd) \ RUST_TARGET_DIR=$(shell pwd)/target \ RUSTFLAGS="-Z force-unstable-if-unmarked" \ TVM_NUM_THREADS=$(NUM_THREADS) \ BUILD_DIR=../build \ xargo build --target x86_64-unknown-linux-sgx $(xargo_args) -q $(TVM_DIR)/rust/patched.txt: $(shell pwd)/sgx-deps.diff echo $(TVM_DIR) cd $(TVM_DIR) && git apply $< touch $@ $(build_dir)/libmodel.a: $(build_dir)/model.o $(AR) cr $@ $^ $(build_dir)/model.o: $(build_dir)/model.bc $(CC) -c $< -o $@ -fPIC -O3 objcopy --globalize-symbol __tvm_module_startup $@ $(build_dir)/model.bc: src/build_model.py python3 $< -o $(build_dir) clean: xargo clean <file_sep>/vta/hardware/intel/Makefile # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # Directories ROOTDIR = $(CURDIR) BUILD_NAME = build BUILD_DIR = $(ROOTDIR)/../../$(BUILD_NAME)/hardware/intel SCRIPT_DIR = $(ROOTDIR)/scripts SRC_DIR = $(ROOTDIR)/../chisel # Process VTA JSON config VTA_CONFIG = python $(CURDIR)/../../config/vta_config.py # Debug flag DEBUG = false # Prevent generation of DSP NO_DSP = true # Device DEVICE = $(shell $(VTA_CONFIG) --get-fpga-dev) # Device family DEVICE_FAMILY = $(shell $(VTA_CONFIG) --get-fpga-family) # Project name PROJECT = de10_nano_top #--------------------- # Compilation parameters #-------------------- # Derive config name CONF = $(shell ${VTA_CONFIG} --cfg-str) IP_BUILD_PATH = $(BUILD_DIR)/chisel/$(CONF) HW_BUILD_PATH = $(BUILD_DIR)/quartus/$(CONF) ifeq ($(NO_DSP), true) DSP_FLAG = else DSP_FLAG = --dsp endif # IP file path IP_PATH = $(IP_BUILD_PATH)/VTA.DefaultDe10Config.v # Bitstream file path BIT_PATH = $(HW_BUILD_PATH)/export/vta.rbf # System design file path QSYS_PATH = $(HW_BUILD_PATH)/soc_system.qsys .PHONY: all ip bit qsys clean all: bit ip: $(IP_PATH) bit: $(BIT_PATH) qsys: $(QSYS_PATH) $(IP_PATH): $(SRC_DIR) mkdir -p $(IP_BUILD_PATH) cd $(SRC_DIR) && \ make CONFIG=DefaultDe10Config chisel_build_dir=$(IP_BUILD_PATH) verilog $(QSYS_PATH): $(IP_PATH) mkdir -p $(HW_BUILD_PATH) cd $(HW_BUILD_PATH) && \ cp -r $(SCRIPT_DIR)/* $(HW_BUILD_PATH) && \ python3 $(SCRIPT_DIR)/set_attrs.py -i $(IP_PATH) -o $(HW_BUILD_PATH)/ip/vta/VTAShell.v $(DSP_FLAG) && \ qsys-script --script=soc_system.tcl $(DEVICE) $(DEVICE_FAMILY) $(BIT_PATH): $(QSYS_PATH) cd $(HW_BUILD_PATH) && \ quartus_sh -t $(SCRIPT_DIR)/compile_design.tcl $(DEVICE) $(PROJECT) && \ mkdir -p $(shell dirname $(BIT_PATH)) && \ quartus_cpf -c $(HW_BUILD_PATH)/$(PROJECT).sof $(BIT_PATH) clean: rm -rf $(BUILD_DIR) <file_sep>/nnvm/tests/cpp/unittest.mk GTEST_LIB=$(GTEST_PATH)/lib/ GTEST_INC=$(GTEST_PATH)/include/ TEST_SRC = $(wildcard tests/cpp/*_test.cc) TEST = $(patsubst tests/cpp/%_test.cc, tests/cpp/%_test, $(TEST_SRC)) tests/cpp/%_test: tests/cpp/%_test.cc lib/libnnvm.a $(CXX) -std=c++11 $(CFLAGS) -MM -MT tests/cpp/$* $< >tests/cpp/$*.d $(CXX) -std=c++11 $(CFLAGS) -I$(GTEST_INC) -o $@ $(filter %.cc %.a, $^) \ -L$(GTEST_LIB) $(LDFLAGS) -lgtest -include tests/cpp/*.d <file_sep>/topi/python/topi/x86/__init__.py # pylint: disable=redefined-builtin, wildcard-import """x86 specific declaration and schedules.""" from __future__ import absolute_import as _abs from .conv2d import schedule_conv2d, schedule_conv2d_nhwc from .binarize_pack import schedule_binarize_pack from .binary_dense import schedule_binary_dense from .nn import * from .injective import * from .pooling import schedule_pool, schedule_adaptive_pool from .bitserial_conv2d import schedule_bitserial_conv2d from .bitserial_dense import schedule_bitserial_dense from .depthwise_conv2d import schedule_depthwise_conv2d_NCHWc from .dense import _schedule_dense, _schedule_dense_pack, _schedule_dense_nopack from .batch_matmul import schedule_batch_matmul from .roi_align import roi_align_nchw from .conv2d_transpose import schedule_conv2d_transpose from .sparse import * <file_sep>/python/tvm/_ffi/node.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Node namespace""" # pylint: disable=unused-import from __future__ import absolute_import import ctypes import sys from .. import _api_internal from .node_generic import NodeGeneric, convert_to_node, const from .base import _LIB, check_call, c_str, py_str, _FFI_MODE IMPORT_EXCEPT = RuntimeError if _FFI_MODE == "cython" else ImportError try: # pylint: disable=wrong-import-position if _FFI_MODE == "ctypes": raise ImportError() if sys.version_info >= (3, 0): from ._cy3.core import _register_node, NodeBase as _NodeBase else: from ._cy2.core import _register_node, NodeBase as _NodeBase except IMPORT_EXCEPT: # pylint: disable=wrong-import-position from ._ctypes.node import _register_node, NodeBase as _NodeBase def _new_object(cls): """Helper function for pickle""" return cls.__new__(cls) class NodeBase(_NodeBase): """NodeBase is the base class of all TVM language AST object.""" def __repr__(self): return _api_internal._format_str(self) def __dir__(self): plist = ctypes.POINTER(ctypes.c_char_p)() size = ctypes.c_uint() check_call(_LIB.TVMNodeListAttrNames( self.handle, ctypes.byref(size), ctypes.byref(plist))) names = [] for i in range(size.value): names.append(py_str(plist[i])) return names def __hash__(self): return _api_internal._raw_ptr(self) def __eq__(self, other): return self.same_as(other) def __ne__(self, other): return not self.__eq__(other) def __reduce__(self): cls = type(self) return (_new_object, (cls, ), self.__getstate__()) def __getstate__(self): handle = self.handle if handle is not None: return {'handle': _api_internal._save_json(self)} return {'handle': None} def __setstate__(self, state): # pylint: disable=assigning-non-slot handle = state['handle'] if handle is not None: json_str = handle other = _api_internal._load_json(json_str) self.handle = other.handle other.handle = None else: self.handle = None def same_as(self, other): """check object identity equality""" if not isinstance(other, NodeBase): return False return self.__hash__() == other.__hash__() def register_node(type_key=None): """register node type Parameters ---------- type_key : str or cls The type key of the node """ node_name = type_key if isinstance(type_key, str) else type_key.__name__ def register(cls): """internal register function""" tindex = ctypes.c_int() ret = _LIB.TVMNodeTypeKey2Index(c_str(node_name), ctypes.byref(tindex)) if ret == 0: _register_node(tindex.value, cls) return cls if isinstance(type_key, str): return register return register(type_key) <file_sep>/src/relay/qnn/op/requantize.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2019 by Contributors * \file src/relay/qnn/op/requantize.cc * \brief QNN requantize operator. */ #include <tvm/relay/analysis.h> #include <tvm/relay/op_attr_types.h> #include <tvm/relay/qnn/attrs.h> #include "../../pass/pattern_util.h" #include "../util.h" namespace tvm { namespace relay { namespace qnn { TVM_REGISTER_NODE_TYPE(RequantizeAttrs); // Lowering of qnn.requantize op /* * \brief Convert FP32 representation into fixed point representation. * \param double_multplier The input FP32 number. * \return The pair of multiplier and shift for fixed point representation. * \note Converts a floating point number so that it can be represented by * integers. The representation is * float_number = (significand) * 2^(exponent) * * The significand is a number between 0.5 and 1. This is represented by * an integer number. For example, if it is int32, then the decimal point * exists between bit 31 and 30 from LSB (or between first and second bit * from the left). * * Some examples are * 0.25 = (0.5) * 2^(-1) * 0.125 = (0.5) * 2^(-2) * * Credit to TFLite reference implementation. */ std::pair<int32_t, int32_t> GetFixedPointMultiplierShift(double double_multiplier) { int32_t significand, exponent; if (double_multiplier == 0.) { significand = 0; exponent = 0; return std::make_pair(significand, exponent); } // Get the significand and exponent. double significand_d = std::frexp(double_multiplier, &exponent); // Convert the double significand to int significand, i.e., convert into a // integer where the decimal point is between bit 31 and 30. This is done by // multiplying the double value with 2^31 and then casting to int. significand_d = std::round(significand_d * (1ll << 31)); auto significand_int64 = static_cast<int64_t>(significand_d); CHECK_LE(significand_int64, (1ll << 31)); if (significand_int64 == (1ll << 31)) { significand_int64 /= 2; ++exponent; } CHECK_LE(significand_int64, std::numeric_limits<int32_t>::max()); significand = static_cast<int32_t>(significand_int64); return std::make_pair(significand, exponent); } /* * \brief Lower requantize to a sequence of ops. * \param input_tensor The input tensor to requantize op. * \param param The requantize op attrs. * \param input_shape The input tensor shape of the requantize op. * \return The sequence of existing Relay ops. * \note Requantization using only integer computation. Here, the computation is * converted to a fixed point computation by computing output multiplier * and shift. This is useful, if the target device does not support/have * very expensive floating point computations. * * Original compuation is scale_fp32 * quantized_tensor. To convert into * integer computation, the multiplication with fp32 scalar can be * replaced by multiplication with an int value and then right shifting * the result. This approximates the floating point computation with a * fixed point computation. * * The whole computation this can be broken down into following steps * 1) Calculate the integer multiplier and integer shift. * 2) Subtract the input integer zero point. * 3) Multiply the fixed point multiplier with quantized tensor. * 4) Round the result. * 5) Right shift the result. * 6) Add the output zero point. * 7) Cast to the out_dtype. */ Expr RequantizeLower(const Expr& input_tensor, const RequantizeAttrs* param, const Array<IndexExpr>& input_shape, const DataType& out_dtype) { double double_multiplier = param->input_scale / param->output_scale; // Choose high precision datatype to be int64. This is for avoiding overflow // in multiplication of two int32 values. DataType hp_dtype = Int(64); // 1) Calculating the integer multiplier and integer shift int32_t fixed_point_multiplier, shift; std::tie(fixed_point_multiplier, shift) = GetFixedPointMultiplierShift(double_multiplier); int left_shift = shift > 0 ? shift : 0; int right_shift = shift > 0 ? 0 : -shift; // 2) Subtract the input_zero_point auto tensor = Cast(input_tensor, hp_dtype); if (param->input_zero_point != 0) { auto input_zp = MakeConstantScalar(hp_dtype, param->input_zero_point); tensor = Subtract(tensor, input_zp); } // If the input and output scales are same, we can skip the fixed point multiplication. auto scaled_int64_t = tensor; if (param->input_scale != param->output_scale) { // 3) Multiply the integer multiplier if (left_shift != 0) { tensor = Multiply(tensor, MakeConstantScalar(hp_dtype, 1 << left_shift)); } // Perform the multiplication in higher precision. // The scalar is a fixed point value of int32 where the decimal point is // between bits 31 and 30. After multiplying with input_tensor, the result is // in int64 where the decimal point is sitting between bits 31 and 30 (from // the right, rightmost bit is bit 0). The computation is performed in higher // precision to avoid overflow in multiplying two int32 values. Expr scalar = MakeConstantScalar(hp_dtype, fixed_point_multiplier); auto multiplied_t = Multiply(tensor, scalar); // 4) Find the rounding scalar. This depends on where the final decimal point // sits. As we will be right shifting the multiplied_t, we need to first // calculate the total_right_shift. int total_right_shift = right_shift + 31; int64_t pos_rounding_value = (1ll << (total_right_shift - 1)); tensor = multiplied_t; Expr round_scalar; if (param->rounding == "UPWARD") { round_scalar = MakeConstantScalar(hp_dtype, pos_rounding_value); } else if (param->rounding == "TONEAREST") { auto pos_rounder = MakeConstantScalar(hp_dtype, pos_rounding_value); auto neg_rounder = MakeConstantScalar(hp_dtype, pos_rounding_value - 1); auto pos_rounder_t = Full(pos_rounder, input_shape, hp_dtype); auto neg_rounder_t = Full(neg_rounder, input_shape, hp_dtype); auto zero = MakeConstantScalar(hp_dtype, 0); auto zero_t = Full(zero, input_shape, hp_dtype); round_scalar = Where(GreaterEqual(tensor, zero_t), pos_rounder_t, neg_rounder_t); } // Add the rounding scalar. tensor = Add(tensor, round_scalar); // 5) Simply right shift the result to get the final output. scaled_int64_t = RightShift(tensor, MakeConstantScalar(hp_dtype, total_right_shift)); } // 6) Add the output zero point. auto shifted_int64_t = scaled_int64_t; if (param->output_zero_point != 0) { auto output_zp = MakeConstantScalar(hp_dtype, param->output_zero_point); shifted_int64_t = Add(output_zp, scaled_int64_t); } // 7) Clip to the out_dtype min/max. auto q_min = GetQmin(out_dtype); auto q_max = GetQmax(out_dtype); auto clipped_t = Clip(shifted_int64_t, q_min, q_max); return Cast(clipped_t, out_dtype); } /* * \brief Forward rewrite the requantize op. * \param ref_call The original call that will be lowered. * \param new_args The new mutated args to the call node. * \param ctx The node context. * \return The sequence of Relay ops for requantize op. * \note Lowering of the requantize operation. The requantize operator converts * one quantized tensor to another quantized tensor. For the output * tensor, we are provided with output scale and zero point. The * computation looks like this * * Q_output = zp_output + (scale_input)/(scale_ouptut) * (Q_input - zp_input) */ Expr RequantizeQnnCanonicalize(const Attrs& attrs, const Array<Expr>& new_args, const Array<tvm::relay::Type>& types) { CHECK_EQ(new_args.size(), 1); auto& quantized_data = new_args[0]; const auto* param = attrs.as<RequantizeAttrs>(); CHECK(param != nullptr); // Find input shape. CHECK_EQ(types.size(), 2); auto in_type = types[0]; auto in_tensor_type = in_type.as<TensorTypeNode>(); CHECK(in_tensor_type != nullptr) << "Type information missing." << " Please run infer_type pass."; Array<IndexExpr> input_shape = in_tensor_type->shape; // Find the output dtype. auto out_type = types[1]; auto out_tensor_type = out_type.as<TensorTypeNode>(); CHECK(out_tensor_type != nullptr) << "Type information missing." << " Please run infer_type pass."; auto out_dtype = out_tensor_type->dtype; // Check rounding validity. CHECK(param->rounding == "UPWARD" || param->rounding == "TONEAREST") << "QNN requantize supports two rounding modes - UPWARD and " << "TONEAREST"; return RequantizeLower(quantized_data, param, input_shape, out_dtype); } /* * \brief Infer shape function of Requantize op. * \param types The types of input args. * \param num_inputs The number of inputs. * \param attrs The op attributes. * \param reporter The type reporter that sets the dtype and shapes. * \return True if the infer shape succeeded. */ bool RequantizeRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { CHECK_EQ(types.size(), 2); const auto* data = types[0].as<TensorTypeNode>(); const auto in_dtype = data->dtype; CHECK(in_dtype == Int(8) || in_dtype == UInt(8) || in_dtype == Int(32)) << "Input type should be one of [int8, uint8, int32] but was " << in_dtype; const Array<tvm::Expr> oshape = data->shape; // assign output type const RequantizeAttrs* param = attrs.as<RequantizeAttrs>(); auto out_dtype = param->out_dtype; CHECK(out_dtype == Int(8) || out_dtype == UInt(8) || out_dtype == Int(32)) << "Output type should be one of [int8, uint8, int32] but was " << out_dtype; reporter->Assign(types[1], TensorTypeNode::make(oshape, out_dtype)); return true; } // Positional relay function to create qnn requantize operator // used by frontend FFI. Expr MakeRequantize(Expr data, double input_scale, int32_t input_zero_point, double output_scale, int32_t output_zero_point, std::string rounding, DataType out_dtype) { auto attrs = make_node<RequantizeAttrs>(); attrs->input_scale = std::move(input_scale); attrs->input_zero_point = std::move(input_zero_point); attrs->output_scale = std::move(output_scale); attrs->output_zero_point = std::move(output_zero_point); attrs->rounding = std::move(rounding); attrs->out_dtype = std::move(out_dtype); static const Op& op = Op::Get("qnn.requantize"); return CallNode::make(op, {data}, Attrs(attrs), {}); } RELAY_REGISTER_OP("qnn.requantize") .describe(R"code(Requantize operator. The requantize operator converts one quantized tensor to another quantized tensor. For the output tensor, we are provided with output scale and zero point. The computation looks like this Q_output = zp_output + (scale_input)/(scale_output) * (Q_input - zp_input) )code" TVM_ADD_FILELINE) .set_attrs_type_key("relay.attrs.RequantizeAttrs") .set_num_inputs(1) .add_argument("data", "Tensor", "The quantized input tensor.") .set_support_level(11) .add_type_rel("Requantize", RequantizeRel) .set_attr<FTVMLegalize>("FTVMQnnCanonicalize", RequantizeQnnCanonicalize); TVM_REGISTER_API("relay.qnn.op._make.requantize") .set_body_typed(MakeRequantize); } // namespace qnn } // namespace relay } // namespace tvm <file_sep>/python/tvm/relay/backend/profiler_vm.py # License .to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=no-else-return, unidiomatic-typecheck, undefined-variable, invalid-name """ The Relay Virtual Machine profiler. Provides extra APIs for profiling vm execution. """ import tvm from . import vm, _vm def _update_target(target): target = target if target else tvm.target.current_target() if target is None: raise ValueError("Target is not set in env or passed as argument.") tgts = {} if isinstance(target, (str, tvm.target.Target)): dev_type = tvm.expr.IntImm("int32", tvm.nd.context(str(target)).device_type) tgts[dev_type] = tvm.target.create(target) elif isinstance(target, dict): for dev, tgt in target.items(): dev_type = tvm.expr.IntImm("int32", tvm.nd.context(dev).device_type) tgts[dev_type] = tvm.target.create(tgt) else: raise TypeError("target is expected to be str, tvm.target.Target, " + "or dict of str to str/tvm.target.Target, but received " + "{}".format(type(target))) return tgts class VMCompilerProfiler(vm.VMCompiler): """Build Relay module to run on VM runtime.""" def __init__(self): super().__init__() self.mod = _vm._VMCompilerProfiler() self._compile = self.mod["compile"] self._get_vm = self.mod["get_vm"] def compile(self, mod, target=None, target_host=None): """ Parameters ---------- mod : relay.Module The Relay module to build. target : str, :any:`tvm.target.Target`, or dict of str(i.e. device/context name) to str/tvm.target.Target, optional For heterogeneous compilation, it is a dictionary indicating context to target mapping. For homogeneous compilation, it is a build target. target_host : str or :any:`tvm.target.Target`, optional Host compilation target, if target is device. When TVM compiles device specific program such as CUDA, we also need host(CPU) side code to interact with the driver to setup the dimensions and parameters correctly. target_host is used to specify the host side codegen target. By default, llvm is used if it is enabled, otherwise a stackvm intepreter is used. Returns ------- vm : VirtualMachineProfiler The profile VM runtime. """ target = _update_target(target) self._compile(mod, target, target_host) return VirtualMachineProfiler(self._get_vm()) class VirtualMachineProfiler(vm.VirtualMachine): """Relay profile VM runtime.""" def __init__(self, mod): super().__init__(mod) self._get_stat = self.mod["get_stat"] def get_stat(self): return self._get_stat() <file_sep>/tests/python/relay/benchmarking/benchmark_vm.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Benchmarking Relay VM using models from MXNet.""" import numpy as np import tvm from tvm.contrib import graph_runtime from tvm import relay from tvm.relay import testing def benchmark_execution(mod, params, measure=False, data_shape=(1, 3, 224, 224), out_shape=(1, 1000), dtype='float32'): def get_tvm_output(mod, data, params, target, ctx, dtype='float32'): with relay.build_config(opt_level=1): graph, lib, params = relay.build(mod, target, params=params) m = graph_runtime.create(graph, lib, ctx) # set inputs m.set_input("data", data) m.set_input(**params) m.run() out = m.get_output(0, tvm.nd.empty(out_shape, dtype)) if measure: print("Evaluate graph runtime inference time cost...") ftimer = m.module.time_evaluator("run", ctx, number=1, repeat=20) # Measure in millisecond. prof_res = np.array(ftimer().results) * 1000 print("Mean inference time (std dev): %.2f ms (%.2f ms)" % (np.mean(prof_res), np.std(prof_res))) return out.asnumpy() def get_tvm_vm_output(mod, data, params, target, ctx, dtype='float32'): ex = relay.create_executor('vm', mod=mod, ctx=ctx) result = ex.evaluate()(data, **params) return result.asnumpy().astype(dtype) # random input data = np.random.uniform(size=data_shape).astype(dtype) target = "llvm" ctx = tvm.cpu(0) tvm_out = get_tvm_output(mod, tvm.nd.array(data.astype(dtype)), params, target, ctx, dtype) vm_out = get_tvm_vm_output(mod, tvm.nd.array(data.astype(dtype)), params, target, ctx, dtype) tvm.testing.assert_allclose(vm_out, tvm_out, rtol=1e-5, atol=1e-5) def test_mlp(): image_shape = (1, 1, 28, 28) mod, params = testing.mlp.get_workload(1) benchmark_execution(mod, params, data_shape=image_shape, out_shape=(1, 10)) def test_vgg(): for n in [11, 16]: mod, params = testing.vgg.get_workload(1, num_layers=n) benchmark_execution(mod, params) def test_resnet(): for n in [18, 50]: mod, params = testing.resnet.get_workload(batch_size=1, num_layers=n) benchmark_execution(mod, params, True) def test_squeezenet(): for version in ['1.0', '1.1']: mod, params = testing.squeezenet.get_workload(version=version) benchmark_execution(mod, params) def test_inception_v3(): image_shape = (3, 299, 299) mod, params = testing.inception_v3.get_workload(image_shape=image_shape) benchmark_execution(mod, params, data_shape=(1, 3, 299, 299)) def test_dqn(): image_shape = (1, 4, 84, 84) mod, params = testing.dqn.get_workload( batch_size=1, image_shape=image_shape) benchmark_execution(mod, params, data_shape=image_shape, out_shape=(1, 18)) def test_dcgan(): image_shape = (1, 100) mod, params = testing.dcgan.get_workload(batch_size=1) benchmark_execution(mod, params, data_shape=image_shape, out_shape=(1, 3, 64, 64)) def test_mobilenet(): mod, params = testing.mobilenet.get_workload(batch_size=1) benchmark_execution(mod, params) # TODO: enable when the low building performance (several minutes) fixed. def test_mobilenet_nhwc(): image_shape = (1, 224, 224, 3) mod, params = testing.mobilenet.get_workload(batch_size=1, image_shape=image_shape[1:], layout='NHWC') benchmark_execution(mod, params, measure=False, data_shape=image_shape) def test_densenet(): mod, params = testing.densenet.get_workload(batch_size=1) benchmark_execution(mod, params) if __name__ == '__main__': test_resnet() test_vgg() test_squeezenet() test_mobilenet() test_densenet() test_inception_v3() test_mlp() test_dqn() test_dcgan() <file_sep>/apps/sgx/Makefile # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. SGX_SDK ?= /opt/sgxsdk RUST_SGX_SDK ?= /opt/rust-sgx-sdk SGX_MODE ?= SIM DEBUG ?= true NUM_THREADS ?= 4 TVM_DIR ?= $(shell git rev-parse --show-toplevel) export sgx_edger8r := $(SGX_SDK)/bin/x64/sgx_edger8r sgx_enclave_signer := $(SGX_SDK)/bin/x64/sgx_sign ifneq ($(SGX_MODE), HW) sgx_sim := _sim endif urts_library_name := sgx_urts$(sgx_sim) trts_library_name := sgx_trts$(sgx_sim) tservice_library_name := sgx_tservice$(sgx_sim) uservice_library_name := sgx_uae_service$(sgx_sim) pkg_cflags := -std=c++11 -fPIC \ -I$(SGX_SDK)/include \ -I$(TVM_DIR)/include \ -I$(TVM_DIR)/dlpack/include \ -I$(TVM_DIR)/dmlc-core/include pkg_ldflags := -L$(TVM_DIR)/build -ltvm_runtime ifneq ($(DEBUG), false) debug := debug enclave_cflags += -Og -g pkg_cflags += -Og -g else debug := release enclave_cflags += -O2 pkg_cflags += -O2 endif build_dir := build enclave_cflags := \ -I$(SGX_SDK)/include \ -I$(SGX_SDK)/include/tlibc \ -I$(SGX_SDK)/include/stdport \ -I$(SGX_SDK)/include/epid \ -I$(TVM_DIR)/include \ -I$(TVM_DIR)/dlpack/include \ -I$(TVM_DIR)/dmlc-core/include enclave_ldflags :=\ -L$(build_dir) -L$(TVM_DIR)/build \ -Wl,--no-undefined -nostdlib -nodefaultlibs -nostartfiles -L$(SGX_SDK)/lib64\ -Wl,--whole-archive -l$(trts_library_name) -Wl,--no-whole-archive\ -Wl,--start-group\ -lsgx_tstdc -lsgx_tstdcxx -lsgx_tcxx -lsgx_tcrypto -lsgx_tkey_exchange -l$(tservice_library_name)\ -lenclave -ltvm_t\ -Wl,--end-group\ -Wl,-Bstatic -Wl,-Bsymbolic -Wl,--no-undefined\ -Wl,-pie,-eenclave_entry -Wl,--export-dynamic\ -Wl,--defsym,__ImageBase=0 -Wl,--gc-sections\ -Wl,--version-script=enclave/enclave.lds .PHONY: enclave clean enclave: $(build_dir)/enclave.signed.so $(build_dir)/enclave.signed.so: $(build_dir)/enclave.so build/enclave_config.xml enclave/enclave.pem $(sgx_enclave_signer) sign -key enclave/enclave.pem -enclave $< -out $@ -config build/enclave_config.xml enclave/enclave.pem: curl -sSo $@ 'https://gist.githubusercontent.com/nhynes/8a2d80068a92e672f8b0b7d710ceb404/raw/2d5ae5fbe83198ede49465fdc6535065e093543b/tvm_sgx_demo.pem' build/enclave_config.xml: enclave/enclave_config.xml.in cpp $^ -P -o $@ -DNUM_THREADS=$$(( $(NUM_THREADS) + 1 )) $(build_dir)/enclave.so: $(build_dir)/libenclave.a $(TVM_DIR)/build/libtvm_t.a $(CXX) $< -o $@ $(enclave_ldflags) $(enclave_cflags) -ltvm_t $(build_dir)/libenclave.a: enclave/target/x86_64-unknown-linux-sgx/$(debug)/libmodel_enclave.a @mkdir -p $(@D) @cp $< $@ enclave/target/x86_64-unknown-linux-sgx/$(debug)/libmodel_enclave.a: enclave/**/* $(MAKE) -C enclave clean: $(MAKE) -s -C enclave clean rm -rf build <file_sep>/nnvm/python/nnvm/_cy2/__init__.py """Namespace for cython generated modules for python2""" <file_sep>/nnvm/python/nnvm/frontend/__init__.py """NNVM frontends.""" from __future__ import absolute_import from .mxnet import from_mxnet from .onnx import from_onnx from .coreml import from_coreml from .keras import from_keras from .darknet import from_darknet from .tensorflow import from_tensorflow from .caffe2 import from_caffe2 <file_sep>/tests/python/frontend/mxnet/model_zoo/__init__.py """MXNet model zoo for testing purposes.""" from __future__ import absolute_import from . import mlp, vgg, resnet, dqn, inception_v3, squeezenet, dcgan import tvm.relay.testing # mlp def mx_mlp(): num_class = 10 return mlp.get_symbol(num_class) def relay_mlp(): num_class = 10 return tvm.relay.testing.mlp.get_workload(1, num_class)[0] # vgg def mx_vgg(num_layers): num_class = 1000 return vgg.get_symbol(num_class, num_layers) def relay_vgg(num_layers): num_class = 1000 return tvm.relay.testing.vgg.get_workload( 1, num_class, num_layers=num_layers)[0] # resnet def mx_resnet(num_layers): num_class = 1000 return resnet.get_symbol(num_class, num_layers, '3,224,224') def relay_resnet(num_layers): num_class = 1000 return tvm.relay.testing.resnet.get_workload( 1, num_class, num_layers=num_layers)[0] # dqn mx_dqn = dqn.get_symbol def relay_dqn(): return tvm.relay.testing.dqn.get_workload(1)[0] # squeezenet def mx_squeezenet(version): return squeezenet.get_symbol(version=version) def relay_squeezenet(version): return tvm.relay.testing.squeezenet.get_workload(1, version=version)[0] # inception mx_inception_v3 = inception_v3.get_symbol def relay_inception_v3(): return tvm.relay.testing.inception_v3.get_workload(1)[0] # dcgan generator mx_dcgan = dcgan.get_symbol def relay_dcgan(batch_size): return tvm.relay.testing.dcgan.get_workload(batch_size=batch_size)[0] <file_sep>/topi/python/topi/vision/__init__.py # pylint: disable=wildcard-import """VISION network operators""" from __future__ import absolute_import as _abs from . import ssd from .reorg import * from .nms import * from .rcnn import * <file_sep>/tests/lint/add_asf_header.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Helper tool to add ASF header to files that cannot be handled by Rat.""" import os import sys header_cstyle = """ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ """.strip() header_mdstyle = """ <!--- Licensed to the Apache Software Foundation (ASF) under one --> <!--- or more contributor license agreements. See the NOTICE file --> <!--- distributed with this work for additional information --> <!--- regarding copyright ownership. The ASF licenses this file --> <!--- to you under the Apache License, Version 2.0 (the --> <!--- "License"); you may not use this file except in compliance --> <!--- with the License. You may obtain a copy of the License at --> <!--- http://www.apache.org/licenses/LICENSE-2.0 --> <!--- Unless required by applicable law or agreed to in writing, --> <!--- software distributed under the License is distributed on an --> <!--- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY --> <!--- KIND, either express or implied. See the License for the --> <!--- specific language governing permissions and limitations --> <!--- under the License. --> """.strip() header_pystyle = """ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """.strip() header_rststyle = """ .. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at .. http://www.apache.org/licenses/LICENSE-2.0 .. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """.strip() header_groovystyle = """ // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. """.strip() FMT_MAP = { "sh" : header_pystyle, "cc" : header_cstyle, "h" : header_cstyle, "py" : header_pystyle, "toml" : header_pystyle, "yml": header_pystyle, "yaml": header_pystyle, "rs" : header_cstyle, "md" : header_mdstyle, "cmake" : header_pystyle, "rst" : header_rststyle, "gradle" : header_groovystyle, "xml": header_mdstyle, "tcl": header_pystyle, } def add_header(fname, header): """Add header to file""" if not os.path.exists(fname): print("Cannot find %s ..." % fname) return orig = open(fname).read() if orig.find("Licensed to the Apache Software Foundation") != -1: print("Skip file %s ..." % fname) return with open(fname, "w") as outfile: skipline = False lines = orig.split('\n') ext = os.path.splitext(fname)[1][1:] if ext == 'sh' and lines[0][:2] == '#!': skipline = True elif ext == 'xml' and lines[0][:2] == '<?': skipline = True if skipline: outfile.write(lines[0] + "\n") outfile.write(header + "\n\n") outfile.write("\n".join(lines[1:])) outfile.write(header + "\n\n") outfile.write(orig) else: outfile.write(header + "\n\n") outfile.write(orig) print("Add header to %s" % fname) def main(args): if len(args) != 2: print("Usage: python add_asf_header.py <file_list>") for l in open(args[1]): if l.startswith("-----"): continue if l.find("File:") != -1: l = l.split(":")[-1] fname = l.strip() suffix = fname.split(".")[-1] if suffix in FMT_MAP: add_header(fname, FMT_MAP[suffix]) elif os.path.basename(fname) == 'gradle.properties': add_header(fname, FMT_MAP['h']) else: print("Cannot handle %s ..." % fname) if __name__ == "__main__": main(sys.argv) <file_sep>/src/relay/backend/vm/profiler/compiler.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2019 by Contributors * \file src/relay/backend/vm/profiler/compiler.cc * \brief A compiler from relay::Module to the VM byte code. */ #include "../../../../runtime/vm/profiler/vm.h" #include "../compiler.h" namespace tvm { namespace relay { namespace vm { class VMCompilerDebug : public VMCompiler { public: VMCompilerDebug() {} void InitVM() override { vm_ = std::make_shared<VirtualMachineDebug>(); } virtual ~VMCompilerDebug() {} }; runtime::Module CreateVMCompilerDebug() { std::shared_ptr<VMCompilerDebug> exec = std::make_shared<VMCompilerDebug>(); return runtime::Module(exec); } TVM_REGISTER_GLOBAL("relay._vm._VMCompilerProfiler") .set_body([](TVMArgs args, TVMRetValue* rv) { *rv = CreateVMCompilerDebug(); }); } // namespace vm } // namespace relay } // namespace tvm <file_sep>/topi/python/topi/opengl/__init__.py # pylint: disable=redefined-builtin, wildcard-import """CUDA specific declaration and schedules.""" from __future__ import absolute_import as _abs from .conv2d_nchw import schedule_conv2d_nchw from .injective import schedule_injective, schedule_elemwise, schedule_broadcast from .softmax import schedule_softmax from .dense import schedule_dense from .pooling import schedule_pool, schedule_adaptive_pool <file_sep>/vta/apps/tsim_example/python/__init__.py from . import tsim <file_sep>/python/tvm/relay/grammar/py3/RelayParser.py # Generated from /Users/doobs/Code/repo/sampl/tvm/python/tvm/relay/grammar/Relay.g4 by ANTLR 4.7.2 # encoding: utf-8 from antlr4 import * from io import StringIO from typing.io import TextIO import sys def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\62") buf.write("\u01fc\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7") buf.write("\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16") buf.write("\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23\t\23") buf.write("\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31") buf.write("\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36") buf.write("\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\3\2\3\2\7\2I\n\2") buf.write("\f\2\16\2L\13\2\3\2\5\2O\n\2\3\2\5\2R\n\2\3\2\3\2\3\3") buf.write("\3\3\3\3\7\3Y\n\3\f\3\16\3\\\13\3\3\4\3\4\3\4\3\5\3\5") buf.write("\3\5\3\6\3\6\3\6\3\7\3\7\3\7\7\7j\n\7\f\7\16\7m\13\7\5") buf.write("\7o\n\7\3\b\3\b\3\b\3\b\7\bu\n\b\f\b\16\bx\13\b\3\b\5") buf.write("\b{\n\b\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3") buf.write("\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\6\t\u0090\n\t\r\t\16\t") buf.write("\u0091\3\t\3\t\3\t\3\t\3\t\3\t\7\t\u009a\n\t\f\t\16\t") buf.write("\u009d\13\t\5\t\u009f\n\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t") buf.write("\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\5\t\u00b0\n\t\3\t\3\t") buf.write("\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3") buf.write("\t\3\t\3\t\3\t\5\t\u00c5\n\t\3\t\3\t\3\t\3\t\3\t\3\t\3") buf.write("\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t") buf.write("\3\t\3\t\3\t\7\t\u00de\n\t\f\t\16\t\u00e1\13\t\3\n\3\n") buf.write("\5\n\u00e5\n\n\3\n\3\n\3\n\3\n\3\n\5\n\u00ec\n\n\3\n\3") buf.write("\n\3\13\3\13\3\13\5\13\u00f3\n\13\3\13\3\13\3\13\3\13") buf.write("\3\13\5\13\u00fa\n\13\3\13\3\13\3\13\3\13\3\13\3\13\5") buf.write("\13\u0102\n\13\3\13\3\13\3\13\5\13\u0107\n\13\3\13\3\13") buf.write("\5\13\u010b\n\13\3\13\3\13\5\13\u010f\n\13\3\f\3\f\3\r") buf.write("\3\r\3\r\7\r\u0116\n\r\f\r\16\r\u0119\13\r\3\r\5\r\u011c") buf.write("\n\r\3\16\3\16\3\16\3\16\3\16\7\16\u0123\n\16\f\16\16") buf.write("\16\u0126\13\16\3\16\3\16\5\16\u012a\n\16\3\17\3\17\3") buf.write("\17\7\17\u012f\n\17\f\17\16\17\u0132\13\17\3\17\5\17\u0135") buf.write("\n\17\3\20\3\20\5\20\u0139\n\20\3\20\3\20\3\20\3\20\3") buf.write("\20\3\20\5\20\u0141\n\20\3\21\3\21\3\22\3\22\3\22\3\22") buf.write("\7\22\u0149\n\22\f\22\16\22\u014c\13\22\3\22\3\22\3\23") buf.write("\3\23\3\23\3\23\5\23\u0154\n\23\5\23\u0156\n\23\3\24\3") buf.write("\24\5\24\u015a\n\24\3\25\3\25\3\25\3\25\7\25\u0160\n\25") buf.write("\f\25\16\25\u0163\13\25\3\25\3\25\3\26\3\26\5\26\u0169") buf.write("\n\26\3\27\3\27\3\27\3\27\7\27\u016f\n\27\f\27\16\27\u0172") buf.write("\13\27\3\27\5\27\u0175\n\27\3\30\3\30\3\30\7\30\u017a") buf.write("\n\30\f\30\16\30\u017d\13\30\5\30\u017f\n\30\3\31\3\31") buf.write("\3\31\5\31\u0184\n\31\3\32\3\32\3\32\7\32\u0189\n\32\f") buf.write("\32\16\32\u018c\13\32\3\33\3\33\3\33\3\33\3\34\3\34\3") buf.write("\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\6\34\u019d") buf.write("\n\34\r\34\16\34\u019e\3\34\3\34\3\34\3\34\3\34\3\34\3") buf.write("\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\5\34\u01b0") buf.write("\n\34\3\34\3\34\3\34\3\34\7\34\u01b6\n\34\f\34\16\34\u01b9") buf.write("\13\34\5\34\u01bb\n\34\3\34\3\34\3\34\3\34\5\34\u01c1") buf.write("\n\34\3\35\3\35\3\35\3\35\7\35\u01c7\n\35\f\35\16\35\u01ca") buf.write("\13\35\3\35\3\35\3\36\3\36\3\36\3\36\3\36\3\36\6\36\u01d4") buf.write("\n\36\r\36\16\36\u01d5\3\36\3\36\3\36\5\36\u01db\n\36") buf.write("\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3 \3 \3 \3 \3") buf.write(" \3 \5 \u01eb\n \3!\3!\3!\3!\3\"\3\"\3\"\5\"\u01f4\n\"") buf.write("\3#\3#\3#\3#\5#\u01fa\n#\3#\2\3\20$\2\4\6\b\n\f\16\20") buf.write("\22\24\26\30\32\34\36 \"$&(*,.\60\62\64\668:<>@BD\2\b") buf.write("\4\2\6\6//\3\2$%\3\2&\'\3\2(+\3\2,-\3\2\32\33\2\u022d") buf.write("\2F\3\2\2\2\4U\3\2\2\2\6]\3\2\2\2\b`\3\2\2\2\nc\3\2\2") buf.write("\2\fn\3\2\2\2\16z\3\2\2\2\20\u00c4\3\2\2\2\22\u00e2\3") buf.write("\2\2\2\24\u010e\3\2\2\2\26\u0110\3\2\2\2\30\u0112\3\2") buf.write("\2\2\32\u011d\3\2\2\2\34\u012b\3\2\2\2\36\u0136\3\2\2") buf.write("\2 \u0142\3\2\2\2\"\u0144\3\2\2\2$\u0155\3\2\2\2&\u0157") buf.write("\3\2\2\2(\u015b\3\2\2\2*\u0168\3\2\2\2,\u0174\3\2\2\2") buf.write(".\u017e\3\2\2\2\60\u0180\3\2\2\2\62\u0185\3\2\2\2\64\u018d") buf.write("\3\2\2\2\66\u01c0\3\2\2\28\u01c2\3\2\2\2:\u01da\3\2\2") buf.write("\2<\u01dc\3\2\2\2>\u01ea\3\2\2\2@\u01ec\3\2\2\2B\u01f3") buf.write("\3\2\2\2D\u01f9\3\2\2\2FN\7\37\2\2GI\5\24\13\2HG\3\2\2") buf.write("\2IL\3\2\2\2JH\3\2\2\2JK\3\2\2\2KO\3\2\2\2LJ\3\2\2\2M") buf.write("O\5\20\t\2NJ\3\2\2\2NM\3\2\2\2OQ\3\2\2\2PR\7\62\2\2QP") buf.write("\3\2\2\2QR\3\2\2\2RS\3\2\2\2ST\7\2\2\3T\3\3\2\2\2UZ\7") buf.write("/\2\2VW\7\3\2\2WY\7/\2\2XV\3\2\2\2Y\\\3\2\2\2ZX\3\2\2") buf.write("\2Z[\3\2\2\2[\5\3\2\2\2\\Z\3\2\2\2]^\7\4\2\2^_\7/\2\2") buf.write("_\7\3\2\2\2`a\7\5\2\2ab\t\2\2\2b\t\3\2\2\2cd\7\5\2\2d") buf.write("e\7\61\2\2e\13\3\2\2\2fk\5\20\t\2gh\7\7\2\2hj\5\20\t\2") buf.write("ig\3\2\2\2jm\3\2\2\2ki\3\2\2\2kl\3\2\2\2lo\3\2\2\2mk\3") buf.write("\2\2\2nf\3\2\2\2no\3\2\2\2o\r\3\2\2\2p{\5\f\7\2qr\5\20") buf.write("\t\2rs\7\7\2\2su\3\2\2\2tq\3\2\2\2ux\3\2\2\2vt\3\2\2\2") buf.write("vw\3\2\2\2wy\3\2\2\2xv\3\2\2\2y{\5\62\32\2zp\3\2\2\2z") buf.write("v\3\2\2\2{\17\3\2\2\2|}\b\t\1\2}~\7\b\2\2~\177\5\20\t") buf.write("\2\177\u0080\7\t\2\2\u0080\u00c5\3\2\2\2\u0081\u0082\7") buf.write("\'\2\2\u0082\u00c5\5\20\t\26\u0083\u00c5\5\22\n\2\u0084") buf.write("\u0085\7\b\2\2\u0085\u00c5\7\t\2\2\u0086\u0087\7\b\2\2") buf.write("\u0087\u0088\5\20\t\2\u0088\u0089\7\7\2\2\u0089\u008a") buf.write("\7\t\2\2\u008a\u00c5\3\2\2\2\u008b\u008c\7\b\2\2\u008c") buf.write("\u008f\5\20\t\2\u008d\u008e\7\7\2\2\u008e\u0090\5\20\t") buf.write("\2\u008f\u008d\3\2\2\2\u0090\u0091\3\2\2\2\u0091\u008f") buf.write("\3\2\2\2\u0091\u0092\3\2\2\2\u0092\u0093\3\2\2\2\u0093") buf.write("\u0094\7\t\2\2\u0094\u00c5\3\2\2\2\u0095\u009e\7\n\2\2") buf.write("\u0096\u009b\5\20\t\2\u0097\u0098\7\7\2\2\u0098\u009a") buf.write("\5\20\t\2\u0099\u0097\3\2\2\2\u009a\u009d\3\2\2\2\u009b") buf.write("\u0099\3\2\2\2\u009b\u009c\3\2\2\2\u009c\u009f\3\2\2\2") buf.write("\u009d\u009b\3\2\2\2\u009e\u0096\3\2\2\2\u009e\u009f\3") buf.write("\2\2\2\u009f\u00a0\3\2\2\2\u00a0\u00c5\7\13\2\2\u00a1") buf.write("\u00a2\7\f\2\2\u00a2\u00a3\7\b\2\2\u00a3\u00a4\5\20\t") buf.write("\2\u00a4\u00a5\7\t\2\2\u00a5\u00a6\5@!\2\u00a6\u00a7\7") buf.write("\r\2\2\u00a7\u00a8\5@!\2\u00a8\u00c5\3\2\2\2\u00a9\u00aa") buf.write("\5 \21\2\u00aa\u00ab\7\b\2\2\u00ab\u00ac\5\20\t\2\u00ac") buf.write("\u00ad\7\t\2\2\u00ad\u00af\7\16\2\2\u00ae\u00b0\5\34\17") buf.write("\2\u00af\u00ae\3\2\2\2\u00af\u00b0\3\2\2\2\u00b0\u00b1") buf.write("\3\2\2\2\u00b1\u00b2\7\17\2\2\u00b2\u00c5\3\2\2\2\u00b3") buf.write("\u00b4\7\20\2\2\u00b4\u00b5\5\60\31\2\u00b5\u00b6\7\21") buf.write("\2\2\u00b6\u00b7\5\20\t\2\u00b7\u00b8\7\22\2\2\u00b8\u00b9") buf.write("\5\20\t\t\u00b9\u00c5\3\2\2\2\u00ba\u00bb\5\n\6\2\u00bb") buf.write("\u00bc\7\21\2\2\u00bc\u00bd\5\20\t\2\u00bd\u00be\7\22") buf.write("\2\2\u00be\u00bf\5\20\t\7\u00bf\u00c5\3\2\2\2\u00c0\u00c5") buf.write("\5D#\2\u00c1\u00c5\5B\"\2\u00c2\u00c5\5<\37\2\u00c3\u00c5") buf.write("\7#\2\2\u00c4|\3\2\2\2\u00c4\u0081\3\2\2\2\u00c4\u0083") buf.write("\3\2\2\2\u00c4\u0084\3\2\2\2\u00c4\u0086\3\2\2\2\u00c4") buf.write("\u008b\3\2\2\2\u00c4\u0095\3\2\2\2\u00c4\u00a1\3\2\2\2") buf.write("\u00c4\u00a9\3\2\2\2\u00c4\u00b3\3\2\2\2\u00c4\u00ba\3") buf.write("\2\2\2\u00c4\u00c0\3\2\2\2\u00c4\u00c1\3\2\2\2\u00c4\u00c2") buf.write("\3\2\2\2\u00c4\u00c3\3\2\2\2\u00c5\u00df\3\2\2\2\u00c6") buf.write("\u00c7\f\25\2\2\u00c7\u00c8\t\3\2\2\u00c8\u00de\5\20\t") buf.write("\26\u00c9\u00ca\f\24\2\2\u00ca\u00cb\t\4\2\2\u00cb\u00de") buf.write("\5\20\t\25\u00cc\u00cd\f\23\2\2\u00cd\u00ce\t\5\2\2\u00ce") buf.write("\u00de\5\20\t\24\u00cf\u00d0\f\22\2\2\u00d0\u00d1\t\6") buf.write("\2\2\u00d1\u00de\5\20\t\23\u00d2\u00d3\f\b\2\2\u00d3\u00d4") buf.write("\7\23\2\2\u00d4\u00de\5\20\t\t\u00d5\u00d6\f\27\2\2\u00d6") buf.write("\u00d7\7\b\2\2\u00d7\u00d8\5\16\b\2\u00d8\u00d9\7\t\2") buf.write("\2\u00d9\u00de\3\2\2\2\u00da\u00db\f\n\2\2\u00db\u00dc") buf.write("\7\3\2\2\u00dc\u00de\7\61\2\2\u00dd\u00c6\3\2\2\2\u00dd") buf.write("\u00c9\3\2\2\2\u00dd\u00cc\3\2\2\2\u00dd\u00cf\3\2\2\2") buf.write("\u00dd\u00d2\3\2\2\2\u00dd\u00d5\3\2\2\2\u00dd\u00da\3") buf.write("\2\2\2\u00de\u00e1\3\2\2\2\u00df\u00dd\3\2\2\2\u00df\u00e0") buf.write("\3\2\2\2\u00e0\21\3\2\2\2\u00e1\u00df\3\2\2\2\u00e2\u00e4") buf.write("\7\24\2\2\u00e3\u00e5\58\35\2\u00e4\u00e3\3\2\2\2\u00e4") buf.write("\u00e5\3\2\2\2\u00e5\u00e6\3\2\2\2\u00e6\u00e7\7\b\2\2") buf.write("\u00e7\u00e8\5,\27\2\u00e8\u00eb\7\t\2\2\u00e9\u00ea\7") buf.write("\25\2\2\u00ea\u00ec\5\66\34\2\u00eb\u00e9\3\2\2\2\u00eb") buf.write("\u00ec\3\2\2\2\u00ec\u00ed\3\2\2\2\u00ed\u00ee\5@!\2\u00ee") buf.write("\23\3\2\2\2\u00ef\u00f0\7\26\2\2\u00f0\u00f2\5\6\4\2\u00f1") buf.write("\u00f3\58\35\2\u00f2\u00f1\3\2\2\2\u00f2\u00f3\3\2\2\2") buf.write("\u00f3\u00f4\3\2\2\2\u00f4\u00f5\7\b\2\2\u00f5\u00f6\5") buf.write(",\27\2\u00f6\u00f9\7\t\2\2\u00f7\u00f8\7\25\2\2\u00f8") buf.write("\u00fa\5\66\34\2\u00f9\u00f7\3\2\2\2\u00f9\u00fa\3\2\2") buf.write("\2\u00fa\u00fb\3\2\2\2\u00fb\u00fc\5@!\2\u00fc\u010f\3") buf.write("\2\2\2\u00fd\u00fe\7\27\2\2\u00fe\u00ff\7\30\2\2\u00ff") buf.write("\u0101\5\4\3\2\u0100\u0102\58\35\2\u0101\u0100\3\2\2\2") buf.write("\u0101\u0102\3\2\2\2\u0102\u010f\3\2\2\2\u0103\u0104\7") buf.write("\30\2\2\u0104\u0106\5\4\3\2\u0105\u0107\58\35\2\u0106") buf.write("\u0105\3\2\2\2\u0106\u0107\3\2\2\2\u0107\u0108\3\2\2\2") buf.write("\u0108\u010a\7\16\2\2\u0109\u010b\5\30\r\2\u010a\u0109") buf.write("\3\2\2\2\u010a\u010b\3\2\2\2\u010b\u010c\3\2\2\2\u010c") buf.write("\u010d\7\17\2\2\u010d\u010f\3\2\2\2\u010e\u00ef\3\2\2") buf.write("\2\u010e\u00fd\3\2\2\2\u010e\u0103\3\2\2\2\u010f\25\3") buf.write("\2\2\2\u0110\u0111\7/\2\2\u0111\27\3\2\2\2\u0112\u0117") buf.write("\5\32\16\2\u0113\u0114\7\7\2\2\u0114\u0116\5\32\16\2\u0115") buf.write("\u0113\3\2\2\2\u0116\u0119\3\2\2\2\u0117\u0115\3\2\2\2") buf.write("\u0117\u0118\3\2\2\2\u0118\u011b\3\2\2\2\u0119\u0117\3") buf.write("\2\2\2\u011a\u011c\7\7\2\2\u011b\u011a\3\2\2\2\u011b\u011c") buf.write("\3\2\2\2\u011c\31\3\2\2\2\u011d\u0129\5\26\f\2\u011e\u011f") buf.write("\7\b\2\2\u011f\u0124\5\66\34\2\u0120\u0121\7\7\2\2\u0121") buf.write("\u0123\5\66\34\2\u0122\u0120\3\2\2\2\u0123\u0126\3\2\2") buf.write("\2\u0124\u0122\3\2\2\2\u0124\u0125\3\2\2\2\u0125\u0127") buf.write("\3\2\2\2\u0126\u0124\3\2\2\2\u0127\u0128\7\t\2\2\u0128") buf.write("\u012a\3\2\2\2\u0129\u011e\3\2\2\2\u0129\u012a\3\2\2\2") buf.write("\u012a\33\3\2\2\2\u012b\u0130\5\36\20\2\u012c\u012d\7") buf.write("\7\2\2\u012d\u012f\5\36\20\2\u012e\u012c\3\2\2\2\u012f") buf.write("\u0132\3\2\2\2\u0130\u012e\3\2\2\2\u0130\u0131\3\2\2\2") buf.write("\u0131\u0134\3\2\2\2\u0132\u0130\3\2\2\2\u0133\u0135\7") buf.write("\7\2\2\u0134\u0133\3\2\2\2\u0134\u0135\3\2\2\2\u0135\35") buf.write("\3\2\2\2\u0136\u0138\5\26\f\2\u0137\u0139\5\"\22\2\u0138") buf.write("\u0137\3\2\2\2\u0138\u0139\3\2\2\2\u0139\u013a\3\2\2\2") buf.write("\u013a\u0140\7\31\2\2\u013b\u013c\7\16\2\2\u013c\u013d") buf.write("\5\20\t\2\u013d\u013e\7\17\2\2\u013e\u0141\3\2\2\2\u013f") buf.write("\u0141\5\20\t\2\u0140\u013b\3\2\2\2\u0140\u013f\3\2\2") buf.write("\2\u0141\37\3\2\2\2\u0142\u0143\t\7\2\2\u0143!\3\2\2\2") buf.write("\u0144\u0145\7\b\2\2\u0145\u014a\5$\23\2\u0146\u0147\7") buf.write("\7\2\2\u0147\u0149\5$\23\2\u0148\u0146\3\2\2\2\u0149\u014c") buf.write("\3\2\2\2\u014a\u0148\3\2\2\2\u014a\u014b\3\2\2\2\u014b") buf.write("\u014d\3\2\2\2\u014c\u014a\3\2\2\2\u014d\u014e\7\t\2\2") buf.write("\u014e#\3\2\2\2\u014f\u0156\7\6\2\2\u0150\u0153\5\b\5") buf.write("\2\u0151\u0152\7\34\2\2\u0152\u0154\5\66\34\2\u0153\u0151") buf.write("\3\2\2\2\u0153\u0154\3\2\2\2\u0154\u0156\3\2\2\2\u0155") buf.write("\u014f\3\2\2\2\u0155\u0150\3\2\2\2\u0156%\3\2\2\2\u0157") buf.write("\u0159\5\26\f\2\u0158\u015a\5(\25\2\u0159\u0158\3\2\2") buf.write("\2\u0159\u015a\3\2\2\2\u015a\'\3\2\2\2\u015b\u015c\7\b") buf.write("\2\2\u015c\u0161\5*\26\2\u015d\u015e\7\7\2\2\u015e\u0160") buf.write("\5*\26\2\u015f\u015d\3\2\2\2\u0160\u0163\3\2\2\2\u0161") buf.write("\u015f\3\2\2\2\u0161\u0162\3\2\2\2\u0162\u0164\3\2\2\2") buf.write("\u0163\u0161\3\2\2\2\u0164\u0165\7\t\2\2\u0165)\3\2\2") buf.write("\2\u0166\u0169\5\b\5\2\u0167\u0169\5\26\f\2\u0168\u0166") buf.write("\3\2\2\2\u0168\u0167\3\2\2\2\u0169+\3\2\2\2\u016a\u0175") buf.write("\5.\30\2\u016b\u016c\5\60\31\2\u016c\u016d\7\7\2\2\u016d") buf.write("\u016f\3\2\2\2\u016e\u016b\3\2\2\2\u016f\u0172\3\2\2\2") buf.write("\u0170\u016e\3\2\2\2\u0170\u0171\3\2\2\2\u0171\u0173\3") buf.write("\2\2\2\u0172\u0170\3\2\2\2\u0173\u0175\5\62\32\2\u0174") buf.write("\u016a\3\2\2\2\u0174\u0170\3\2\2\2\u0175-\3\2\2\2\u0176") buf.write("\u017b\5\60\31\2\u0177\u0178\7\7\2\2\u0178\u017a\5\60") buf.write("\31\2\u0179\u0177\3\2\2\2\u017a\u017d\3\2\2\2\u017b\u0179") buf.write("\3\2\2\2\u017b\u017c\3\2\2\2\u017c\u017f\3\2\2\2\u017d") buf.write("\u017b\3\2\2\2\u017e\u0176\3\2\2\2\u017e\u017f\3\2\2\2") buf.write("\u017f/\3\2\2\2\u0180\u0183\5\b\5\2\u0181\u0182\7\34\2") buf.write("\2\u0182\u0184\5\66\34\2\u0183\u0181\3\2\2\2\u0183\u0184") buf.write("\3\2\2\2\u0184\61\3\2\2\2\u0185\u018a\5\64\33\2\u0186") buf.write("\u0187\7\7\2\2\u0187\u0189\5\64\33\2\u0188\u0186\3\2\2") buf.write("\2\u0189\u018c\3\2\2\2\u018a\u0188\3\2\2\2\u018a\u018b") buf.write("\3\2\2\2\u018b\63\3\2\2\2\u018c\u018a\3\2\2\2\u018d\u018e") buf.write("\7/\2\2\u018e\u018f\7\21\2\2\u018f\u0190\5\20\t\2\u0190") buf.write("\65\3\2\2\2\u0191\u0192\7\b\2\2\u0192\u01c1\7\t\2\2\u0193") buf.write("\u0194\7\b\2\2\u0194\u0195\5\66\34\2\u0195\u0196\7\7\2") buf.write("\2\u0196\u0197\7\t\2\2\u0197\u01c1\3\2\2\2\u0198\u0199") buf.write("\7\b\2\2\u0199\u019c\5\66\34\2\u019a\u019b\7\7\2\2\u019b") buf.write("\u019d\5\66\34\2\u019c\u019a\3\2\2\2\u019d\u019e\3\2\2") buf.write("\2\u019e\u019c\3\2\2\2\u019e\u019f\3\2\2\2\u019f\u01a0") buf.write("\3\2\2\2\u01a0\u01a1\7\t\2\2\u01a1\u01c1\3\2\2\2\u01a2") buf.write("\u01a3\5\4\3\2\u01a3\u01a4\58\35\2\u01a4\u01c1\3\2\2\2") buf.write("\u01a5\u01c1\5\4\3\2\u01a6\u01a7\7\35\2\2\u01a7\u01a8") buf.write("\7\n\2\2\u01a8\u01a9\5:\36\2\u01a9\u01aa\7\7\2\2\u01aa") buf.write("\u01ab\5\66\34\2\u01ab\u01ac\7\13\2\2\u01ac\u01c1\3\2") buf.write("\2\2\u01ad\u01af\7\24\2\2\u01ae\u01b0\58\35\2\u01af\u01ae") buf.write("\3\2\2\2\u01af\u01b0\3\2\2\2\u01b0\u01b1\3\2\2\2\u01b1") buf.write("\u01ba\7\b\2\2\u01b2\u01b7\5\66\34\2\u01b3\u01b4\7\7\2") buf.write("\2\u01b4\u01b6\5\66\34\2\u01b5\u01b3\3\2\2\2\u01b6\u01b9") buf.write("\3\2\2\2\u01b7\u01b5\3\2\2\2\u01b7\u01b8\3\2\2\2\u01b8") buf.write("\u01bb\3\2\2\2\u01b9\u01b7\3\2\2\2\u01ba\u01b2\3\2\2\2") buf.write("\u01ba\u01bb\3\2\2\2\u01bb\u01bc\3\2\2\2\u01bc\u01bd\7") buf.write("\t\2\2\u01bd\u01be\7\25\2\2\u01be\u01c1\5\66\34\2\u01bf") buf.write("\u01c1\7\6\2\2\u01c0\u0191\3\2\2\2\u01c0\u0193\3\2\2\2") buf.write("\u01c0\u0198\3\2\2\2\u01c0\u01a2\3\2\2\2\u01c0\u01a5\3") buf.write("\2\2\2\u01c0\u01a6\3\2\2\2\u01c0\u01ad\3\2\2\2\u01c0\u01bf") buf.write("\3\2\2\2\u01c1\67\3\2\2\2\u01c2\u01c3\7\n\2\2\u01c3\u01c8") buf.write("\5\4\3\2\u01c4\u01c5\7\7\2\2\u01c5\u01c7\5\4\3\2\u01c6") buf.write("\u01c4\3\2\2\2\u01c7\u01ca\3\2\2\2\u01c8\u01c6\3\2\2\2") buf.write("\u01c8\u01c9\3\2\2\2\u01c9\u01cb\3\2\2\2\u01ca\u01c8\3") buf.write("\2\2\2\u01cb\u01cc\7\13\2\2\u01cc9\3\2\2\2\u01cd\u01ce") buf.write("\7\b\2\2\u01ce\u01db\7\t\2\2\u01cf\u01d0\7\b\2\2\u01d0") buf.write("\u01d3\5> \2\u01d1\u01d2\7\7\2\2\u01d2\u01d4\5> \2\u01d3") buf.write("\u01d1\3\2\2\2\u01d4\u01d5\3\2\2\2\u01d5\u01d3\3\2\2\2") buf.write("\u01d5\u01d6\3\2\2\2\u01d6\u01d7\3\2\2\2\u01d7\u01d8\7") buf.write("\t\2\2\u01d8\u01db\3\2\2\2\u01d9\u01db\5> \2\u01da\u01cd") buf.write("\3\2\2\2\u01da\u01cf\3\2\2\2\u01da\u01d9\3\2\2\2\u01db") buf.write(";\3\2\2\2\u01dc\u01dd\7\36\2\2\u01dd\u01de\7\n\2\2\u01de") buf.write("\u01df\7/\2\2\u01df\u01e0\7\13\2\2\u01e0\u01e1\7\n\2\2") buf.write("\u01e1\u01e2\7\61\2\2\u01e2\u01e3\7\13\2\2\u01e3=\3\2") buf.write("\2\2\u01e4\u01eb\5<\37\2\u01e5\u01e6\7\b\2\2\u01e6\u01e7") buf.write("\5> \2\u01e7\u01e8\7\t\2\2\u01e8\u01eb\3\2\2\2\u01e9\u01eb") buf.write("\7\61\2\2\u01ea\u01e4\3\2\2\2\u01ea\u01e5\3\2\2\2\u01ea") buf.write("\u01e9\3\2\2\2\u01eb?\3\2\2\2\u01ec\u01ed\7\16\2\2\u01ed") buf.write("\u01ee\5\20\t\2\u01ee\u01ef\7\17\2\2\u01efA\3\2\2\2\u01f0") buf.write("\u01f4\7\60\2\2\u01f1\u01f4\7\61\2\2\u01f2\u01f4\7.\2") buf.write("\2\u01f3\u01f0\3\2\2\2\u01f3\u01f1\3\2\2\2\u01f3\u01f2") buf.write("\3\2\2\2\u01f4C\3\2\2\2\u01f5\u01fa\5\4\3\2\u01f6\u01fa") buf.write("\5\6\4\2\u01f7\u01fa\5\b\5\2\u01f8\u01fa\5\n\6\2\u01f9") buf.write("\u01f5\3\2\2\2\u01f9\u01f6\3\2\2\2\u01f9\u01f7\3\2\2\2") buf.write("\u01f9\u01f8\3\2\2\2\u01faE\3\2\2\28JNQZknvz\u0091\u009b") buf.write("\u009e\u00af\u00c4\u00dd\u00df\u00e4\u00eb\u00f2\u00f9") buf.write("\u0101\u0106\u010a\u010e\u0117\u011b\u0124\u0129\u0130") buf.write("\u0134\u0138\u0140\u014a\u0153\u0155\u0159\u0161\u0168") buf.write("\u0170\u0174\u017b\u017e\u0183\u018a\u019e\u01af\u01b7") buf.write("\u01ba\u01c0\u01c8\u01d5\u01da\u01ea\u01f3\u01f9") return buf.getvalue() class RelayParser ( Parser ): grammarFileName = "Relay.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ "<INVALID>", "'.'", "'@'", "'%'", "'_'", "','", "'('", "')'", "'['", "']'", "'if'", "'else'", "'{'", "'}'", "'let'", "'='", "';'", "';;'", "'fn'", "'->'", "'def'", "'extern'", "'type'", "'=>'", "'match'", "'match?'", "':'", "'Tensor'", "'meta'", "'v0.0.4'", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "'*'", "'/'", "'+'", "'-'", "'<'", "'>'", "'<='", "'>='", "'=='", "'!='" ] symbolicNames = [ "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "SEMVER", "COMMENT", "WS", "LINE_COMMENT", "QUOTED_STRING", "MUL", "DIV", "ADD", "SUB", "LT", "GT", "LE", "GE", "EQ", "NE", "BOOL_LIT", "CNAME", "FLOAT", "NAT", "METADATA" ] RULE_prog = 0 RULE_generalIdent = 1 RULE_globalVar = 2 RULE_localVar = 3 RULE_graphVar = 4 RULE_exprList = 5 RULE_callList = 6 RULE_expr = 7 RULE_func = 8 RULE_defn = 9 RULE_constructorName = 10 RULE_adtConsDefnList = 11 RULE_adtConsDefn = 12 RULE_matchClauseList = 13 RULE_matchClause = 14 RULE_matchType = 15 RULE_patternList = 16 RULE_pattern = 17 RULE_adtCons = 18 RULE_adtConsParamList = 19 RULE_adtConsParam = 20 RULE_argList = 21 RULE_varList = 22 RULE_var = 23 RULE_attrSeq = 24 RULE_attr = 25 RULE_typeExpr = 26 RULE_typeParamList = 27 RULE_shapeList = 28 RULE_meta = 29 RULE_shape = 30 RULE_body = 31 RULE_scalar = 32 RULE_ident = 33 ruleNames = [ "prog", "generalIdent", "globalVar", "localVar", "graphVar", "exprList", "callList", "expr", "func", "defn", "constructorName", "adtConsDefnList", "adtConsDefn", "matchClauseList", "matchClause", "matchType", "patternList", "pattern", "adtCons", "adtConsParamList", "adtConsParam", "argList", "varList", "var", "attrSeq", "attr", "typeExpr", "typeParamList", "shapeList", "meta", "shape", "body", "scalar", "ident" ] EOF = Token.EOF T__0=1 T__1=2 T__2=3 T__3=4 T__4=5 T__5=6 T__6=7 T__7=8 T__8=9 T__9=10 T__10=11 T__11=12 T__12=13 T__13=14 T__14=15 T__15=16 T__16=17 T__17=18 T__18=19 T__19=20 T__20=21 T__21=22 T__22=23 T__23=24 T__24=25 T__25=26 T__26=27 T__27=28 SEMVER=29 COMMENT=30 WS=31 LINE_COMMENT=32 QUOTED_STRING=33 MUL=34 DIV=35 ADD=36 SUB=37 LT=38 GT=39 LE=40 GE=41 EQ=42 NE=43 BOOL_LIT=44 CNAME=45 FLOAT=46 NAT=47 METADATA=48 def __init__(self, input:TokenStream, output:TextIO = sys.stdout): super().__init__(input, output) self.checkVersion("4.7.2") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class ProgContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def SEMVER(self): return self.getToken(RelayParser.SEMVER, 0) def EOF(self): return self.getToken(RelayParser.EOF, 0) def expr(self): return self.getTypedRuleContext(RelayParser.ExprContext,0) def METADATA(self): return self.getToken(RelayParser.METADATA, 0) def defn(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.DefnContext) else: return self.getTypedRuleContext(RelayParser.DefnContext,i) def getRuleIndex(self): return RelayParser.RULE_prog def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitProg" ): return visitor.visitProg(self) else: return visitor.visitChildren(self) def prog(self): localctx = RelayParser.ProgContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_prog) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 68 self.match(RelayParser.SEMVER) self.state = 76 self._errHandler.sync(self) token = self._input.LA(1) if token in [RelayParser.EOF, RelayParser.T__19, RelayParser.T__20, RelayParser.T__21, RelayParser.METADATA]: self.state = 72 self._errHandler.sync(self) _la = self._input.LA(1) while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << RelayParser.T__19) | (1 << RelayParser.T__20) | (1 << RelayParser.T__21))) != 0): self.state = 69 self.defn() self.state = 74 self._errHandler.sync(self) _la = self._input.LA(1) pass elif token in [RelayParser.T__1, RelayParser.T__2, RelayParser.T__5, RelayParser.T__7, RelayParser.T__9, RelayParser.T__13, RelayParser.T__17, RelayParser.T__23, RelayParser.T__24, RelayParser.T__27, RelayParser.QUOTED_STRING, RelayParser.SUB, RelayParser.BOOL_LIT, RelayParser.CNAME, RelayParser.FLOAT, RelayParser.NAT]: self.state = 75 self.expr(0) pass else: raise NoViableAltException(self) self.state = 79 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.METADATA: self.state = 78 self.match(RelayParser.METADATA) self.state = 81 self.match(RelayParser.EOF) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class GeneralIdentContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def CNAME(self, i:int=None): if i is None: return self.getTokens(RelayParser.CNAME) else: return self.getToken(RelayParser.CNAME, i) def getRuleIndex(self): return RelayParser.RULE_generalIdent def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitGeneralIdent" ): return visitor.visitGeneralIdent(self) else: return visitor.visitChildren(self) def generalIdent(self): localctx = RelayParser.GeneralIdentContext(self, self._ctx, self.state) self.enterRule(localctx, 2, self.RULE_generalIdent) try: self.enterOuterAlt(localctx, 1) self.state = 83 self.match(RelayParser.CNAME) self.state = 88 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,3,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 84 self.match(RelayParser.T__0) self.state = 85 self.match(RelayParser.CNAME) self.state = 90 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,3,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class GlobalVarContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def CNAME(self): return self.getToken(RelayParser.CNAME, 0) def getRuleIndex(self): return RelayParser.RULE_globalVar def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitGlobalVar" ): return visitor.visitGlobalVar(self) else: return visitor.visitChildren(self) def globalVar(self): localctx = RelayParser.GlobalVarContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_globalVar) try: self.enterOuterAlt(localctx, 1) self.state = 91 self.match(RelayParser.T__1) self.state = 92 self.match(RelayParser.CNAME) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class LocalVarContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def CNAME(self): return self.getToken(RelayParser.CNAME, 0) def getRuleIndex(self): return RelayParser.RULE_localVar def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitLocalVar" ): return visitor.visitLocalVar(self) else: return visitor.visitChildren(self) def localVar(self): localctx = RelayParser.LocalVarContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_localVar) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 94 self.match(RelayParser.T__2) self.state = 95 _la = self._input.LA(1) if not(_la==RelayParser.T__3 or _la==RelayParser.CNAME): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class GraphVarContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def NAT(self): return self.getToken(RelayParser.NAT, 0) def getRuleIndex(self): return RelayParser.RULE_graphVar def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitGraphVar" ): return visitor.visitGraphVar(self) else: return visitor.visitChildren(self) def graphVar(self): localctx = RelayParser.GraphVarContext(self, self._ctx, self.state) self.enterRule(localctx, 8, self.RULE_graphVar) try: self.enterOuterAlt(localctx, 1) self.state = 97 self.match(RelayParser.T__2) self.state = 98 self.match(RelayParser.NAT) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExprListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.ExprContext) else: return self.getTypedRuleContext(RelayParser.ExprContext,i) def getRuleIndex(self): return RelayParser.RULE_exprList def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitExprList" ): return visitor.visitExprList(self) else: return visitor.visitChildren(self) def exprList(self): localctx = RelayParser.ExprListContext(self, self._ctx, self.state) self.enterRule(localctx, 10, self.RULE_exprList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 108 self._errHandler.sync(self) _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << RelayParser.T__1) | (1 << RelayParser.T__2) | (1 << RelayParser.T__5) | (1 << RelayParser.T__7) | (1 << RelayParser.T__9) | (1 << RelayParser.T__13) | (1 << RelayParser.T__17) | (1 << RelayParser.T__23) | (1 << RelayParser.T__24) | (1 << RelayParser.T__27) | (1 << RelayParser.QUOTED_STRING) | (1 << RelayParser.SUB) | (1 << RelayParser.BOOL_LIT) | (1 << RelayParser.CNAME) | (1 << RelayParser.FLOAT) | (1 << RelayParser.NAT))) != 0): self.state = 100 self.expr(0) self.state = 105 self._errHandler.sync(self) _la = self._input.LA(1) while _la==RelayParser.T__4: self.state = 101 self.match(RelayParser.T__4) self.state = 102 self.expr(0) self.state = 107 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CallListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return RelayParser.RULE_callList def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class CallWithAttrContext(CallListContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.CallListContext super().__init__(parser) self.copyFrom(ctx) def attrSeq(self): return self.getTypedRuleContext(RelayParser.AttrSeqContext,0) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.ExprContext) else: return self.getTypedRuleContext(RelayParser.ExprContext,i) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitCallWithAttr" ): return visitor.visitCallWithAttr(self) else: return visitor.visitChildren(self) class CallNoAttrContext(CallListContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.CallListContext super().__init__(parser) self.copyFrom(ctx) def exprList(self): return self.getTypedRuleContext(RelayParser.ExprListContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitCallNoAttr" ): return visitor.visitCallNoAttr(self) else: return visitor.visitChildren(self) def callList(self): localctx = RelayParser.CallListContext(self, self._ctx, self.state) self.enterRule(localctx, 12, self.RULE_callList) try: self.state = 120 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,7,self._ctx) if la_ == 1: localctx = RelayParser.CallNoAttrContext(self, localctx) self.enterOuterAlt(localctx, 1) self.state = 110 self.exprList() pass elif la_ == 2: localctx = RelayParser.CallWithAttrContext(self, localctx) self.enterOuterAlt(localctx, 2) self.state = 116 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 111 self.expr(0) self.state = 112 self.match(RelayParser.T__4) self.state = 118 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) self.state = 119 self.attrSeq() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExprContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return RelayParser.RULE_expr def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class FuncExprContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def func(self): return self.getTypedRuleContext(RelayParser.FuncContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitFuncExpr" ): return visitor.visitFuncExpr(self) else: return visitor.visitChildren(self) class MetaExprContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def meta(self): return self.getTypedRuleContext(RelayParser.MetaContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMetaExpr" ): return visitor.visitMetaExpr(self) else: return visitor.visitChildren(self) class MatchContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def matchType(self): return self.getTypedRuleContext(RelayParser.MatchTypeContext,0) def expr(self): return self.getTypedRuleContext(RelayParser.ExprContext,0) def matchClauseList(self): return self.getTypedRuleContext(RelayParser.MatchClauseListContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMatch" ): return visitor.visitMatch(self) else: return visitor.visitChildren(self) class TensorContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.ExprContext) else: return self.getTypedRuleContext(RelayParser.ExprContext,i) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTensor" ): return visitor.visitTensor(self) else: return visitor.visitChildren(self) class GraphContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def graphVar(self): return self.getTypedRuleContext(RelayParser.GraphVarContext,0) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.ExprContext) else: return self.getTypedRuleContext(RelayParser.ExprContext,i) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitGraph" ): return visitor.visitGraph(self) else: return visitor.visitChildren(self) class IdentExprContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def ident(self): return self.getTypedRuleContext(RelayParser.IdentContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitIdentExpr" ): return visitor.visitIdentExpr(self) else: return visitor.visitChildren(self) class StringExprContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def QUOTED_STRING(self): return self.getToken(RelayParser.QUOTED_STRING, 0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitStringExpr" ): return visitor.visitStringExpr(self) else: return visitor.visitChildren(self) class CallContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self): return self.getTypedRuleContext(RelayParser.ExprContext,0) def callList(self): return self.getTypedRuleContext(RelayParser.CallListContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitCall" ): return visitor.visitCall(self) else: return visitor.visitChildren(self) class NegContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def SUB(self): return self.getToken(RelayParser.SUB, 0) def expr(self): return self.getTypedRuleContext(RelayParser.ExprContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitNeg" ): return visitor.visitNeg(self) else: return visitor.visitChildren(self) class TupleContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.ExprContext) else: return self.getTypedRuleContext(RelayParser.ExprContext,i) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTuple" ): return visitor.visitTuple(self) else: return visitor.visitChildren(self) class ParenContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self): return self.getTypedRuleContext(RelayParser.ExprContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitParen" ): return visitor.visitParen(self) else: return visitor.visitChildren(self) class ScalarExprContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def scalar(self): return self.getTypedRuleContext(RelayParser.ScalarContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitScalarExpr" ): return visitor.visitScalarExpr(self) else: return visitor.visitChildren(self) class LetContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def var(self): return self.getTypedRuleContext(RelayParser.VarContext,0) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.ExprContext) else: return self.getTypedRuleContext(RelayParser.ExprContext,i) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitLet" ): return visitor.visitLet(self) else: return visitor.visitChildren(self) class ProjectionContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self): return self.getTypedRuleContext(RelayParser.ExprContext,0) def NAT(self): return self.getToken(RelayParser.NAT, 0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitProjection" ): return visitor.visitProjection(self) else: return visitor.visitChildren(self) class IfElseContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.copyFrom(ctx) def expr(self): return self.getTypedRuleContext(RelayParser.ExprContext,0) def body(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.BodyContext) else: return self.getTypedRuleContext(RelayParser.BodyContext,i) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitIfElse" ): return visitor.visitIfElse(self) else: return visitor.visitChildren(self) class BinOpContext(ExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ExprContext super().__init__(parser) self.op = None # Token self.copyFrom(ctx) def expr(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.ExprContext) else: return self.getTypedRuleContext(RelayParser.ExprContext,i) def MUL(self): return self.getToken(RelayParser.MUL, 0) def DIV(self): return self.getToken(RelayParser.DIV, 0) def ADD(self): return self.getToken(RelayParser.ADD, 0) def SUB(self): return self.getToken(RelayParser.SUB, 0) def LT(self): return self.getToken(RelayParser.LT, 0) def GT(self): return self.getToken(RelayParser.GT, 0) def LE(self): return self.getToken(RelayParser.LE, 0) def GE(self): return self.getToken(RelayParser.GE, 0) def EQ(self): return self.getToken(RelayParser.EQ, 0) def NE(self): return self.getToken(RelayParser.NE, 0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitBinOp" ): return visitor.visitBinOp(self) else: return visitor.visitChildren(self) def expr(self, _p:int=0): _parentctx = self._ctx _parentState = self.state localctx = RelayParser.ExprContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 14 self.enterRecursionRule(localctx, 14, self.RULE_expr, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 194 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,12,self._ctx) if la_ == 1: localctx = RelayParser.ParenContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 123 self.match(RelayParser.T__5) self.state = 124 self.expr(0) self.state = 125 self.match(RelayParser.T__6) pass elif la_ == 2: localctx = RelayParser.NegContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 127 self.match(RelayParser.SUB) self.state = 128 self.expr(20) pass elif la_ == 3: localctx = RelayParser.FuncExprContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 129 self.func() pass elif la_ == 4: localctx = RelayParser.TupleContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 130 self.match(RelayParser.T__5) self.state = 131 self.match(RelayParser.T__6) pass elif la_ == 5: localctx = RelayParser.TupleContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 132 self.match(RelayParser.T__5) self.state = 133 self.expr(0) self.state = 134 self.match(RelayParser.T__4) self.state = 135 self.match(RelayParser.T__6) pass elif la_ == 6: localctx = RelayParser.TupleContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 137 self.match(RelayParser.T__5) self.state = 138 self.expr(0) self.state = 141 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 139 self.match(RelayParser.T__4) self.state = 140 self.expr(0) self.state = 143 self._errHandler.sync(self) _la = self._input.LA(1) if not (_la==RelayParser.T__4): break self.state = 145 self.match(RelayParser.T__6) pass elif la_ == 7: localctx = RelayParser.TensorContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 147 self.match(RelayParser.T__7) self.state = 156 self._errHandler.sync(self) _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << RelayParser.T__1) | (1 << RelayParser.T__2) | (1 << RelayParser.T__5) | (1 << RelayParser.T__7) | (1 << RelayParser.T__9) | (1 << RelayParser.T__13) | (1 << RelayParser.T__17) | (1 << RelayParser.T__23) | (1 << RelayParser.T__24) | (1 << RelayParser.T__27) | (1 << RelayParser.QUOTED_STRING) | (1 << RelayParser.SUB) | (1 << RelayParser.BOOL_LIT) | (1 << RelayParser.CNAME) | (1 << RelayParser.FLOAT) | (1 << RelayParser.NAT))) != 0): self.state = 148 self.expr(0) self.state = 153 self._errHandler.sync(self) _la = self._input.LA(1) while _la==RelayParser.T__4: self.state = 149 self.match(RelayParser.T__4) self.state = 150 self.expr(0) self.state = 155 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 158 self.match(RelayParser.T__8) pass elif la_ == 8: localctx = RelayParser.IfElseContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 159 self.match(RelayParser.T__9) self.state = 160 self.match(RelayParser.T__5) self.state = 161 self.expr(0) self.state = 162 self.match(RelayParser.T__6) self.state = 163 self.body() self.state = 164 self.match(RelayParser.T__10) self.state = 165 self.body() pass elif la_ == 9: localctx = RelayParser.MatchContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 167 self.matchType() self.state = 168 self.match(RelayParser.T__5) self.state = 169 self.expr(0) self.state = 170 self.match(RelayParser.T__6) self.state = 171 self.match(RelayParser.T__11) self.state = 173 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.CNAME: self.state = 172 self.matchClauseList() self.state = 175 self.match(RelayParser.T__12) pass elif la_ == 10: localctx = RelayParser.LetContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 177 self.match(RelayParser.T__13) self.state = 178 self.var() self.state = 179 self.match(RelayParser.T__14) self.state = 180 self.expr(0) self.state = 181 self.match(RelayParser.T__15) self.state = 182 self.expr(7) pass elif la_ == 11: localctx = RelayParser.GraphContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 184 self.graphVar() self.state = 185 self.match(RelayParser.T__14) self.state = 186 self.expr(0) self.state = 187 self.match(RelayParser.T__15) self.state = 188 self.expr(5) pass elif la_ == 12: localctx = RelayParser.IdentExprContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 190 self.ident() pass elif la_ == 13: localctx = RelayParser.ScalarExprContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 191 self.scalar() pass elif la_ == 14: localctx = RelayParser.MetaExprContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 192 self.meta() pass elif la_ == 15: localctx = RelayParser.StringExprContext(self, localctx) self._ctx = localctx _prevctx = localctx self.state = 193 self.match(RelayParser.QUOTED_STRING) pass self._ctx.stop = self._input.LT(-1) self.state = 221 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,14,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx self.state = 219 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,13,self._ctx) if la_ == 1: localctx = RelayParser.BinOpContext(self, RelayParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 196 if not self.precpred(self._ctx, 19): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 19)") self.state = 197 localctx.op = self._input.LT(1) _la = self._input.LA(1) if not(_la==RelayParser.MUL or _la==RelayParser.DIV): localctx.op = self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 198 self.expr(20) pass elif la_ == 2: localctx = RelayParser.BinOpContext(self, RelayParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 199 if not self.precpred(self._ctx, 18): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 18)") self.state = 200 localctx.op = self._input.LT(1) _la = self._input.LA(1) if not(_la==RelayParser.ADD or _la==RelayParser.SUB): localctx.op = self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 201 self.expr(19) pass elif la_ == 3: localctx = RelayParser.BinOpContext(self, RelayParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 202 if not self.precpred(self._ctx, 17): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 17)") self.state = 203 localctx.op = self._input.LT(1) _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << RelayParser.LT) | (1 << RelayParser.GT) | (1 << RelayParser.LE) | (1 << RelayParser.GE))) != 0)): localctx.op = self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 204 self.expr(18) pass elif la_ == 4: localctx = RelayParser.BinOpContext(self, RelayParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 205 if not self.precpred(self._ctx, 16): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 16)") self.state = 206 localctx.op = self._input.LT(1) _la = self._input.LA(1) if not(_la==RelayParser.EQ or _la==RelayParser.NE): localctx.op = self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 207 self.expr(17) pass elif la_ == 5: localctx = RelayParser.LetContext(self, RelayParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 208 if not self.precpred(self._ctx, 6): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 6)") self.state = 209 self.match(RelayParser.T__16) self.state = 210 self.expr(7) pass elif la_ == 6: localctx = RelayParser.CallContext(self, RelayParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 211 if not self.precpred(self._ctx, 21): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 21)") self.state = 212 self.match(RelayParser.T__5) self.state = 213 self.callList() self.state = 214 self.match(RelayParser.T__6) pass elif la_ == 7: localctx = RelayParser.ProjectionContext(self, RelayParser.ExprContext(self, _parentctx, _parentState)) self.pushNewRecursionContext(localctx, _startState, self.RULE_expr) self.state = 216 if not self.precpred(self._ctx, 8): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 8)") self.state = 217 self.match(RelayParser.T__0) self.state = 218 self.match(RelayParser.NAT) pass self.state = 223 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,14,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class FuncContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def argList(self): return self.getTypedRuleContext(RelayParser.ArgListContext,0) def body(self): return self.getTypedRuleContext(RelayParser.BodyContext,0) def typeParamList(self): return self.getTypedRuleContext(RelayParser.TypeParamListContext,0) def typeExpr(self): return self.getTypedRuleContext(RelayParser.TypeExprContext,0) def getRuleIndex(self): return RelayParser.RULE_func def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitFunc" ): return visitor.visitFunc(self) else: return visitor.visitChildren(self) def func(self): localctx = RelayParser.FuncContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_func) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 224 self.match(RelayParser.T__17) self.state = 226 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__7: self.state = 225 self.typeParamList() self.state = 228 self.match(RelayParser.T__5) self.state = 229 self.argList() self.state = 230 self.match(RelayParser.T__6) self.state = 233 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__18: self.state = 231 self.match(RelayParser.T__18) self.state = 232 self.typeExpr() self.state = 235 self.body() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class DefnContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return RelayParser.RULE_defn def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class ExternAdtDefnContext(DefnContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.DefnContext super().__init__(parser) self.copyFrom(ctx) def generalIdent(self): return self.getTypedRuleContext(RelayParser.GeneralIdentContext,0) def typeParamList(self): return self.getTypedRuleContext(RelayParser.TypeParamListContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitExternAdtDefn" ): return visitor.visitExternAdtDefn(self) else: return visitor.visitChildren(self) class FuncDefnContext(DefnContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.DefnContext super().__init__(parser) self.copyFrom(ctx) def globalVar(self): return self.getTypedRuleContext(RelayParser.GlobalVarContext,0) def argList(self): return self.getTypedRuleContext(RelayParser.ArgListContext,0) def body(self): return self.getTypedRuleContext(RelayParser.BodyContext,0) def typeParamList(self): return self.getTypedRuleContext(RelayParser.TypeParamListContext,0) def typeExpr(self): return self.getTypedRuleContext(RelayParser.TypeExprContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitFuncDefn" ): return visitor.visitFuncDefn(self) else: return visitor.visitChildren(self) class AdtDefnContext(DefnContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.DefnContext super().__init__(parser) self.copyFrom(ctx) def generalIdent(self): return self.getTypedRuleContext(RelayParser.GeneralIdentContext,0) def typeParamList(self): return self.getTypedRuleContext(RelayParser.TypeParamListContext,0) def adtConsDefnList(self): return self.getTypedRuleContext(RelayParser.AdtConsDefnListContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAdtDefn" ): return visitor.visitAdtDefn(self) else: return visitor.visitChildren(self) def defn(self): localctx = RelayParser.DefnContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_defn) self._la = 0 # Token type try: self.state = 268 self._errHandler.sync(self) token = self._input.LA(1) if token in [RelayParser.T__19]: localctx = RelayParser.FuncDefnContext(self, localctx) self.enterOuterAlt(localctx, 1) self.state = 237 self.match(RelayParser.T__19) self.state = 238 self.globalVar() self.state = 240 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__7: self.state = 239 self.typeParamList() self.state = 242 self.match(RelayParser.T__5) self.state = 243 self.argList() self.state = 244 self.match(RelayParser.T__6) self.state = 247 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__18: self.state = 245 self.match(RelayParser.T__18) self.state = 246 self.typeExpr() self.state = 249 self.body() pass elif token in [RelayParser.T__20]: localctx = RelayParser.ExternAdtDefnContext(self, localctx) self.enterOuterAlt(localctx, 2) self.state = 251 self.match(RelayParser.T__20) self.state = 252 self.match(RelayParser.T__21) self.state = 253 self.generalIdent() self.state = 255 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__7: self.state = 254 self.typeParamList() pass elif token in [RelayParser.T__21]: localctx = RelayParser.AdtDefnContext(self, localctx) self.enterOuterAlt(localctx, 3) self.state = 257 self.match(RelayParser.T__21) self.state = 258 self.generalIdent() self.state = 260 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__7: self.state = 259 self.typeParamList() self.state = 262 self.match(RelayParser.T__11) self.state = 264 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.CNAME: self.state = 263 self.adtConsDefnList() self.state = 266 self.match(RelayParser.T__12) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ConstructorNameContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def CNAME(self): return self.getToken(RelayParser.CNAME, 0) def getRuleIndex(self): return RelayParser.RULE_constructorName def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitConstructorName" ): return visitor.visitConstructorName(self) else: return visitor.visitChildren(self) def constructorName(self): localctx = RelayParser.ConstructorNameContext(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_constructorName) try: self.enterOuterAlt(localctx, 1) self.state = 270 self.match(RelayParser.CNAME) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AdtConsDefnListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def adtConsDefn(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.AdtConsDefnContext) else: return self.getTypedRuleContext(RelayParser.AdtConsDefnContext,i) def getRuleIndex(self): return RelayParser.RULE_adtConsDefnList def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAdtConsDefnList" ): return visitor.visitAdtConsDefnList(self) else: return visitor.visitChildren(self) def adtConsDefnList(self): localctx = RelayParser.AdtConsDefnListContext(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_adtConsDefnList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 272 self.adtConsDefn() self.state = 277 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,23,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 273 self.match(RelayParser.T__4) self.state = 274 self.adtConsDefn() self.state = 279 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,23,self._ctx) self.state = 281 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__4: self.state = 280 self.match(RelayParser.T__4) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AdtConsDefnContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def constructorName(self): return self.getTypedRuleContext(RelayParser.ConstructorNameContext,0) def typeExpr(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.TypeExprContext) else: return self.getTypedRuleContext(RelayParser.TypeExprContext,i) def getRuleIndex(self): return RelayParser.RULE_adtConsDefn def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAdtConsDefn" ): return visitor.visitAdtConsDefn(self) else: return visitor.visitChildren(self) def adtConsDefn(self): localctx = RelayParser.AdtConsDefnContext(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_adtConsDefn) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 283 self.constructorName() self.state = 295 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__5: self.state = 284 self.match(RelayParser.T__5) self.state = 285 self.typeExpr() self.state = 290 self._errHandler.sync(self) _la = self._input.LA(1) while _la==RelayParser.T__4: self.state = 286 self.match(RelayParser.T__4) self.state = 287 self.typeExpr() self.state = 292 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 293 self.match(RelayParser.T__6) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MatchClauseListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def matchClause(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.MatchClauseContext) else: return self.getTypedRuleContext(RelayParser.MatchClauseContext,i) def getRuleIndex(self): return RelayParser.RULE_matchClauseList def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMatchClauseList" ): return visitor.visitMatchClauseList(self) else: return visitor.visitChildren(self) def matchClauseList(self): localctx = RelayParser.MatchClauseListContext(self, self._ctx, self.state) self.enterRule(localctx, 26, self.RULE_matchClauseList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 297 self.matchClause() self.state = 302 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,27,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 298 self.match(RelayParser.T__4) self.state = 299 self.matchClause() self.state = 304 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,27,self._ctx) self.state = 306 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__4: self.state = 305 self.match(RelayParser.T__4) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MatchClauseContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def constructorName(self): return self.getTypedRuleContext(RelayParser.ConstructorNameContext,0) def expr(self): return self.getTypedRuleContext(RelayParser.ExprContext,0) def patternList(self): return self.getTypedRuleContext(RelayParser.PatternListContext,0) def getRuleIndex(self): return RelayParser.RULE_matchClause def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMatchClause" ): return visitor.visitMatchClause(self) else: return visitor.visitChildren(self) def matchClause(self): localctx = RelayParser.MatchClauseContext(self, self._ctx, self.state) self.enterRule(localctx, 28, self.RULE_matchClause) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 308 self.constructorName() self.state = 310 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__5: self.state = 309 self.patternList() self.state = 312 self.match(RelayParser.T__22) self.state = 318 self._errHandler.sync(self) token = self._input.LA(1) if token in [RelayParser.T__11]: self.state = 313 self.match(RelayParser.T__11) self.state = 314 self.expr(0) self.state = 315 self.match(RelayParser.T__12) pass elif token in [RelayParser.T__1, RelayParser.T__2, RelayParser.T__5, RelayParser.T__7, RelayParser.T__9, RelayParser.T__13, RelayParser.T__17, RelayParser.T__23, RelayParser.T__24, RelayParser.T__27, RelayParser.QUOTED_STRING, RelayParser.SUB, RelayParser.BOOL_LIT, RelayParser.CNAME, RelayParser.FLOAT, RelayParser.NAT]: self.state = 317 self.expr(0) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MatchTypeContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return RelayParser.RULE_matchType def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMatchType" ): return visitor.visitMatchType(self) else: return visitor.visitChildren(self) def matchType(self): localctx = RelayParser.MatchTypeContext(self, self._ctx, self.state) self.enterRule(localctx, 30, self.RULE_matchType) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 320 _la = self._input.LA(1) if not(_la==RelayParser.T__23 or _la==RelayParser.T__24): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class PatternListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def pattern(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.PatternContext) else: return self.getTypedRuleContext(RelayParser.PatternContext,i) def getRuleIndex(self): return RelayParser.RULE_patternList def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitPatternList" ): return visitor.visitPatternList(self) else: return visitor.visitChildren(self) def patternList(self): localctx = RelayParser.PatternListContext(self, self._ctx, self.state) self.enterRule(localctx, 32, self.RULE_patternList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 322 self.match(RelayParser.T__5) self.state = 323 self.pattern() self.state = 328 self._errHandler.sync(self) _la = self._input.LA(1) while _la==RelayParser.T__4: self.state = 324 self.match(RelayParser.T__4) self.state = 325 self.pattern() self.state = 330 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 331 self.match(RelayParser.T__6) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class PatternContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def localVar(self): return self.getTypedRuleContext(RelayParser.LocalVarContext,0) def typeExpr(self): return self.getTypedRuleContext(RelayParser.TypeExprContext,0) def getRuleIndex(self): return RelayParser.RULE_pattern def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitPattern" ): return visitor.visitPattern(self) else: return visitor.visitChildren(self) def pattern(self): localctx = RelayParser.PatternContext(self, self._ctx, self.state) self.enterRule(localctx, 34, self.RULE_pattern) self._la = 0 # Token type try: self.state = 339 self._errHandler.sync(self) token = self._input.LA(1) if token in [RelayParser.T__3]: self.enterOuterAlt(localctx, 1) self.state = 333 self.match(RelayParser.T__3) pass elif token in [RelayParser.T__2]: self.enterOuterAlt(localctx, 2) self.state = 334 self.localVar() self.state = 337 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__25: self.state = 335 self.match(RelayParser.T__25) self.state = 336 self.typeExpr() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AdtConsContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def constructorName(self): return self.getTypedRuleContext(RelayParser.ConstructorNameContext,0) def adtConsParamList(self): return self.getTypedRuleContext(RelayParser.AdtConsParamListContext,0) def getRuleIndex(self): return RelayParser.RULE_adtCons def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAdtCons" ): return visitor.visitAdtCons(self) else: return visitor.visitChildren(self) def adtCons(self): localctx = RelayParser.AdtConsContext(self, self._ctx, self.state) self.enterRule(localctx, 36, self.RULE_adtCons) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 341 self.constructorName() self.state = 343 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__5: self.state = 342 self.adtConsParamList() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AdtConsParamListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def adtConsParam(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.AdtConsParamContext) else: return self.getTypedRuleContext(RelayParser.AdtConsParamContext,i) def getRuleIndex(self): return RelayParser.RULE_adtConsParamList def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAdtConsParamList" ): return visitor.visitAdtConsParamList(self) else: return visitor.visitChildren(self) def adtConsParamList(self): localctx = RelayParser.AdtConsParamListContext(self, self._ctx, self.state) self.enterRule(localctx, 38, self.RULE_adtConsParamList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 345 self.match(RelayParser.T__5) self.state = 346 self.adtConsParam() self.state = 351 self._errHandler.sync(self) _la = self._input.LA(1) while _la==RelayParser.T__4: self.state = 347 self.match(RelayParser.T__4) self.state = 348 self.adtConsParam() self.state = 353 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 354 self.match(RelayParser.T__6) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AdtConsParamContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def localVar(self): return self.getTypedRuleContext(RelayParser.LocalVarContext,0) def constructorName(self): return self.getTypedRuleContext(RelayParser.ConstructorNameContext,0) def getRuleIndex(self): return RelayParser.RULE_adtConsParam def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAdtConsParam" ): return visitor.visitAdtConsParam(self) else: return visitor.visitChildren(self) def adtConsParam(self): localctx = RelayParser.AdtConsParamContext(self, self._ctx, self.state) self.enterRule(localctx, 40, self.RULE_adtConsParam) try: self.state = 358 self._errHandler.sync(self) token = self._input.LA(1) if token in [RelayParser.T__2]: self.enterOuterAlt(localctx, 1) self.state = 356 self.localVar() pass elif token in [RelayParser.CNAME]: self.enterOuterAlt(localctx, 2) self.state = 357 self.constructorName() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ArgListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return RelayParser.RULE_argList def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class ArgNoAttrContext(ArgListContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ArgListContext super().__init__(parser) self.copyFrom(ctx) def varList(self): return self.getTypedRuleContext(RelayParser.VarListContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitArgNoAttr" ): return visitor.visitArgNoAttr(self) else: return visitor.visitChildren(self) class ArgWithAttrContext(ArgListContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ArgListContext super().__init__(parser) self.copyFrom(ctx) def attrSeq(self): return self.getTypedRuleContext(RelayParser.AttrSeqContext,0) def var(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.VarContext) else: return self.getTypedRuleContext(RelayParser.VarContext,i) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitArgWithAttr" ): return visitor.visitArgWithAttr(self) else: return visitor.visitChildren(self) def argList(self): localctx = RelayParser.ArgListContext(self, self._ctx, self.state) self.enterRule(localctx, 42, self.RULE_argList) self._la = 0 # Token type try: self.state = 370 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,38,self._ctx) if la_ == 1: localctx = RelayParser.ArgNoAttrContext(self, localctx) self.enterOuterAlt(localctx, 1) self.state = 360 self.varList() pass elif la_ == 2: localctx = RelayParser.ArgWithAttrContext(self, localctx) self.enterOuterAlt(localctx, 2) self.state = 366 self._errHandler.sync(self) _la = self._input.LA(1) while _la==RelayParser.T__2: self.state = 361 self.var() self.state = 362 self.match(RelayParser.T__4) self.state = 368 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 369 self.attrSeq() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VarListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def var(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.VarContext) else: return self.getTypedRuleContext(RelayParser.VarContext,i) def getRuleIndex(self): return RelayParser.RULE_varList def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitVarList" ): return visitor.visitVarList(self) else: return visitor.visitChildren(self) def varList(self): localctx = RelayParser.VarListContext(self, self._ctx, self.state) self.enterRule(localctx, 44, self.RULE_varList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 380 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__2: self.state = 372 self.var() self.state = 377 self._errHandler.sync(self) _la = self._input.LA(1) while _la==RelayParser.T__4: self.state = 373 self.match(RelayParser.T__4) self.state = 374 self.var() self.state = 379 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VarContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def localVar(self): return self.getTypedRuleContext(RelayParser.LocalVarContext,0) def typeExpr(self): return self.getTypedRuleContext(RelayParser.TypeExprContext,0) def getRuleIndex(self): return RelayParser.RULE_var def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitVar" ): return visitor.visitVar(self) else: return visitor.visitChildren(self) def var(self): localctx = RelayParser.VarContext(self, self._ctx, self.state) self.enterRule(localctx, 46, self.RULE_var) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 382 self.localVar() self.state = 385 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__25: self.state = 383 self.match(RelayParser.T__25) self.state = 384 self.typeExpr() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AttrSeqContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def attr(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.AttrContext) else: return self.getTypedRuleContext(RelayParser.AttrContext,i) def getRuleIndex(self): return RelayParser.RULE_attrSeq def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAttrSeq" ): return visitor.visitAttrSeq(self) else: return visitor.visitChildren(self) def attrSeq(self): localctx = RelayParser.AttrSeqContext(self, self._ctx, self.state) self.enterRule(localctx, 48, self.RULE_attrSeq) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 387 self.attr() self.state = 392 self._errHandler.sync(self) _la = self._input.LA(1) while _la==RelayParser.T__4: self.state = 388 self.match(RelayParser.T__4) self.state = 389 self.attr() self.state = 394 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AttrContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def CNAME(self): return self.getToken(RelayParser.CNAME, 0) def expr(self): return self.getTypedRuleContext(RelayParser.ExprContext,0) def getRuleIndex(self): return RelayParser.RULE_attr def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitAttr" ): return visitor.visitAttr(self) else: return visitor.visitChildren(self) def attr(self): localctx = RelayParser.AttrContext(self, self._ctx, self.state) self.enterRule(localctx, 50, self.RULE_attr) try: self.enterOuterAlt(localctx, 1) self.state = 395 self.match(RelayParser.CNAME) self.state = 396 self.match(RelayParser.T__14) self.state = 397 self.expr(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TypeExprContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return RelayParser.RULE_typeExpr def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class TupleTypeContext(TypeExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.TypeExprContext super().__init__(parser) self.copyFrom(ctx) def typeExpr(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.TypeExprContext) else: return self.getTypedRuleContext(RelayParser.TypeExprContext,i) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTupleType" ): return visitor.visitTupleType(self) else: return visitor.visitChildren(self) class TypeCallTypeContext(TypeExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.TypeExprContext super().__init__(parser) self.copyFrom(ctx) def generalIdent(self): return self.getTypedRuleContext(RelayParser.GeneralIdentContext,0) def typeParamList(self): return self.getTypedRuleContext(RelayParser.TypeParamListContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTypeCallType" ): return visitor.visitTypeCallType(self) else: return visitor.visitChildren(self) class TypeIdentTypeContext(TypeExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.TypeExprContext super().__init__(parser) self.copyFrom(ctx) def generalIdent(self): return self.getTypedRuleContext(RelayParser.GeneralIdentContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTypeIdentType" ): return visitor.visitTypeIdentType(self) else: return visitor.visitChildren(self) class IncompleteTypeContext(TypeExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.TypeExprContext super().__init__(parser) self.copyFrom(ctx) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitIncompleteType" ): return visitor.visitIncompleteType(self) else: return visitor.visitChildren(self) class TensorTypeContext(TypeExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.TypeExprContext super().__init__(parser) self.copyFrom(ctx) def shapeList(self): return self.getTypedRuleContext(RelayParser.ShapeListContext,0) def typeExpr(self): return self.getTypedRuleContext(RelayParser.TypeExprContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTensorType" ): return visitor.visitTensorType(self) else: return visitor.visitChildren(self) class FuncTypeContext(TypeExprContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.TypeExprContext super().__init__(parser) self.copyFrom(ctx) def typeExpr(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.TypeExprContext) else: return self.getTypedRuleContext(RelayParser.TypeExprContext,i) def typeParamList(self): return self.getTypedRuleContext(RelayParser.TypeParamListContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitFuncType" ): return visitor.visitFuncType(self) else: return visitor.visitChildren(self) def typeExpr(self): localctx = RelayParser.TypeExprContext(self, self._ctx, self.state) self.enterRule(localctx, 52, self.RULE_typeExpr) self._la = 0 # Token type try: self.state = 446 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,47,self._ctx) if la_ == 1: localctx = RelayParser.TupleTypeContext(self, localctx) self.enterOuterAlt(localctx, 1) self.state = 399 self.match(RelayParser.T__5) self.state = 400 self.match(RelayParser.T__6) pass elif la_ == 2: localctx = RelayParser.TupleTypeContext(self, localctx) self.enterOuterAlt(localctx, 2) self.state = 401 self.match(RelayParser.T__5) self.state = 402 self.typeExpr() self.state = 403 self.match(RelayParser.T__4) self.state = 404 self.match(RelayParser.T__6) pass elif la_ == 3: localctx = RelayParser.TupleTypeContext(self, localctx) self.enterOuterAlt(localctx, 3) self.state = 406 self.match(RelayParser.T__5) self.state = 407 self.typeExpr() self.state = 410 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 408 self.match(RelayParser.T__4) self.state = 409 self.typeExpr() self.state = 412 self._errHandler.sync(self) _la = self._input.LA(1) if not (_la==RelayParser.T__4): break self.state = 414 self.match(RelayParser.T__6) pass elif la_ == 4: localctx = RelayParser.TypeCallTypeContext(self, localctx) self.enterOuterAlt(localctx, 4) self.state = 416 self.generalIdent() self.state = 417 self.typeParamList() pass elif la_ == 5: localctx = RelayParser.TypeIdentTypeContext(self, localctx) self.enterOuterAlt(localctx, 5) self.state = 419 self.generalIdent() pass elif la_ == 6: localctx = RelayParser.TensorTypeContext(self, localctx) self.enterOuterAlt(localctx, 6) self.state = 420 self.match(RelayParser.T__26) self.state = 421 self.match(RelayParser.T__7) self.state = 422 self.shapeList() self.state = 423 self.match(RelayParser.T__4) self.state = 424 self.typeExpr() self.state = 425 self.match(RelayParser.T__8) pass elif la_ == 7: localctx = RelayParser.FuncTypeContext(self, localctx) self.enterOuterAlt(localctx, 7) self.state = 427 self.match(RelayParser.T__17) self.state = 429 self._errHandler.sync(self) _la = self._input.LA(1) if _la==RelayParser.T__7: self.state = 428 self.typeParamList() self.state = 431 self.match(RelayParser.T__5) self.state = 440 self._errHandler.sync(self) _la = self._input.LA(1) if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << RelayParser.T__3) | (1 << RelayParser.T__5) | (1 << RelayParser.T__17) | (1 << RelayParser.T__26) | (1 << RelayParser.CNAME))) != 0): self.state = 432 self.typeExpr() self.state = 437 self._errHandler.sync(self) _la = self._input.LA(1) while _la==RelayParser.T__4: self.state = 433 self.match(RelayParser.T__4) self.state = 434 self.typeExpr() self.state = 439 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 442 self.match(RelayParser.T__6) self.state = 443 self.match(RelayParser.T__18) self.state = 444 self.typeExpr() pass elif la_ == 8: localctx = RelayParser.IncompleteTypeContext(self, localctx) self.enterOuterAlt(localctx, 8) self.state = 445 self.match(RelayParser.T__3) pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TypeParamListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def generalIdent(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.GeneralIdentContext) else: return self.getTypedRuleContext(RelayParser.GeneralIdentContext,i) def getRuleIndex(self): return RelayParser.RULE_typeParamList def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitTypeParamList" ): return visitor.visitTypeParamList(self) else: return visitor.visitChildren(self) def typeParamList(self): localctx = RelayParser.TypeParamListContext(self, self._ctx, self.state) self.enterRule(localctx, 54, self.RULE_typeParamList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 448 self.match(RelayParser.T__7) self.state = 449 self.generalIdent() self.state = 454 self._errHandler.sync(self) _la = self._input.LA(1) while _la==RelayParser.T__4: self.state = 450 self.match(RelayParser.T__4) self.state = 451 self.generalIdent() self.state = 456 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 457 self.match(RelayParser.T__8) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ShapeListContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def shape(self, i:int=None): if i is None: return self.getTypedRuleContexts(RelayParser.ShapeContext) else: return self.getTypedRuleContext(RelayParser.ShapeContext,i) def getRuleIndex(self): return RelayParser.RULE_shapeList def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitShapeList" ): return visitor.visitShapeList(self) else: return visitor.visitChildren(self) def shapeList(self): localctx = RelayParser.ShapeListContext(self, self._ctx, self.state) self.enterRule(localctx, 56, self.RULE_shapeList) self._la = 0 # Token type try: self.state = 472 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,50,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 459 self.match(RelayParser.T__5) self.state = 460 self.match(RelayParser.T__6) pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 461 self.match(RelayParser.T__5) self.state = 462 self.shape() self.state = 465 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 463 self.match(RelayParser.T__4) self.state = 464 self.shape() self.state = 467 self._errHandler.sync(self) _la = self._input.LA(1) if not (_la==RelayParser.T__4): break self.state = 469 self.match(RelayParser.T__6) pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 471 self.shape() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MetaContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def CNAME(self): return self.getToken(RelayParser.CNAME, 0) def NAT(self): return self.getToken(RelayParser.NAT, 0) def getRuleIndex(self): return RelayParser.RULE_meta def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMeta" ): return visitor.visitMeta(self) else: return visitor.visitChildren(self) def meta(self): localctx = RelayParser.MetaContext(self, self._ctx, self.state) self.enterRule(localctx, 58, self.RULE_meta) try: self.enterOuterAlt(localctx, 1) self.state = 474 self.match(RelayParser.T__27) self.state = 475 self.match(RelayParser.T__7) self.state = 476 self.match(RelayParser.CNAME) self.state = 477 self.match(RelayParser.T__8) self.state = 478 self.match(RelayParser.T__7) self.state = 479 self.match(RelayParser.NAT) self.state = 480 self.match(RelayParser.T__8) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ShapeContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return RelayParser.RULE_shape def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class ParensShapeContext(ShapeContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ShapeContext super().__init__(parser) self.copyFrom(ctx) def shape(self): return self.getTypedRuleContext(RelayParser.ShapeContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitParensShape" ): return visitor.visitParensShape(self) else: return visitor.visitChildren(self) class MetaShapeContext(ShapeContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ShapeContext super().__init__(parser) self.copyFrom(ctx) def meta(self): return self.getTypedRuleContext(RelayParser.MetaContext,0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitMetaShape" ): return visitor.visitMetaShape(self) else: return visitor.visitChildren(self) class IntShapeContext(ShapeContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ShapeContext super().__init__(parser) self.copyFrom(ctx) def NAT(self): return self.getToken(RelayParser.NAT, 0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitIntShape" ): return visitor.visitIntShape(self) else: return visitor.visitChildren(self) def shape(self): localctx = RelayParser.ShapeContext(self, self._ctx, self.state) self.enterRule(localctx, 60, self.RULE_shape) try: self.state = 488 self._errHandler.sync(self) token = self._input.LA(1) if token in [RelayParser.T__27]: localctx = RelayParser.MetaShapeContext(self, localctx) self.enterOuterAlt(localctx, 1) self.state = 482 self.meta() pass elif token in [RelayParser.T__5]: localctx = RelayParser.ParensShapeContext(self, localctx) self.enterOuterAlt(localctx, 2) self.state = 483 self.match(RelayParser.T__5) self.state = 484 self.shape() self.state = 485 self.match(RelayParser.T__6) pass elif token in [RelayParser.NAT]: localctx = RelayParser.IntShapeContext(self, localctx) self.enterOuterAlt(localctx, 3) self.state = 487 self.match(RelayParser.NAT) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BodyContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(RelayParser.ExprContext,0) def getRuleIndex(self): return RelayParser.RULE_body def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitBody" ): return visitor.visitBody(self) else: return visitor.visitChildren(self) def body(self): localctx = RelayParser.BodyContext(self, self._ctx, self.state) self.enterRule(localctx, 62, self.RULE_body) try: self.enterOuterAlt(localctx, 1) self.state = 490 self.match(RelayParser.T__11) self.state = 491 self.expr(0) self.state = 492 self.match(RelayParser.T__12) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ScalarContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def getRuleIndex(self): return RelayParser.RULE_scalar def copyFrom(self, ctx:ParserRuleContext): super().copyFrom(ctx) class ScalarFloatContext(ScalarContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ScalarContext super().__init__(parser) self.copyFrom(ctx) def FLOAT(self): return self.getToken(RelayParser.FLOAT, 0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitScalarFloat" ): return visitor.visitScalarFloat(self) else: return visitor.visitChildren(self) class ScalarBoolContext(ScalarContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ScalarContext super().__init__(parser) self.copyFrom(ctx) def BOOL_LIT(self): return self.getToken(RelayParser.BOOL_LIT, 0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitScalarBool" ): return visitor.visitScalarBool(self) else: return visitor.visitChildren(self) class ScalarIntContext(ScalarContext): def __init__(self, parser, ctx:ParserRuleContext): # actually a RelayParser.ScalarContext super().__init__(parser) self.copyFrom(ctx) def NAT(self): return self.getToken(RelayParser.NAT, 0) def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitScalarInt" ): return visitor.visitScalarInt(self) else: return visitor.visitChildren(self) def scalar(self): localctx = RelayParser.ScalarContext(self, self._ctx, self.state) self.enterRule(localctx, 64, self.RULE_scalar) try: self.state = 497 self._errHandler.sync(self) token = self._input.LA(1) if token in [RelayParser.FLOAT]: localctx = RelayParser.ScalarFloatContext(self, localctx) self.enterOuterAlt(localctx, 1) self.state = 494 self.match(RelayParser.FLOAT) pass elif token in [RelayParser.NAT]: localctx = RelayParser.ScalarIntContext(self, localctx) self.enterOuterAlt(localctx, 2) self.state = 495 self.match(RelayParser.NAT) pass elif token in [RelayParser.BOOL_LIT]: localctx = RelayParser.ScalarBoolContext(self, localctx) self.enterOuterAlt(localctx, 3) self.state = 496 self.match(RelayParser.BOOL_LIT) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class IdentContext(ParserRuleContext): def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1): super().__init__(parent, invokingState) self.parser = parser def generalIdent(self): return self.getTypedRuleContext(RelayParser.GeneralIdentContext,0) def globalVar(self): return self.getTypedRuleContext(RelayParser.GlobalVarContext,0) def localVar(self): return self.getTypedRuleContext(RelayParser.LocalVarContext,0) def graphVar(self): return self.getTypedRuleContext(RelayParser.GraphVarContext,0) def getRuleIndex(self): return RelayParser.RULE_ident def accept(self, visitor:ParseTreeVisitor): if hasattr( visitor, "visitIdent" ): return visitor.visitIdent(self) else: return visitor.visitChildren(self) def ident(self): localctx = RelayParser.IdentContext(self, self._ctx, self.state) self.enterRule(localctx, 66, self.RULE_ident) try: self.state = 503 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,53,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 499 self.generalIdent() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 500 self.globalVar() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 501 self.localVar() pass elif la_ == 4: self.enterOuterAlt(localctx, 4) self.state = 502 self.graphVar() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int): if self._predicates == None: self._predicates = dict() self._predicates[7] = self.expr_sempred pred = self._predicates.get(ruleIndex, None) if pred is None: raise Exception("No predicate with index:" + str(ruleIndex)) else: return pred(localctx, predIndex) def expr_sempred(self, localctx:ExprContext, predIndex:int): if predIndex == 0: return self.precpred(self._ctx, 19) if predIndex == 1: return self.precpred(self._ctx, 18) if predIndex == 2: return self.precpred(self._ctx, 17) if predIndex == 3: return self.precpred(self._ctx, 16) if predIndex == 4: return self.precpred(self._ctx, 6) if predIndex == 5: return self.precpred(self._ctx, 21) if predIndex == 6: return self.precpred(self._ctx, 8) <file_sep>/src/arithmetic/stmt_simplify.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2019 by Contributors * \file stmt_simplify.cc * \brief Statement simplifier based on analyzer */ #include <tvm/ir.h> #include <tvm/ir_pass.h> #include <tvm/arithmetic.h> #include <tvm/ir_mutator.h> #include <tvm/expr_operator.h> #include <tvm/arithmetic.h> namespace tvm { namespace arith { using namespace ir; class StmtSimplifier : public IRMutator { public: using IRMutator::Mutate; Expr Mutate(Expr expr) final { return analyzer_.Simplify(expr); } Stmt Simplify(Stmt stmt, Map<Var, Range> vrange) { for (auto kv : vrange) { analyzer_.Bind(kv.first, kv.second); } return Mutate(stmt); } Stmt Mutate_(const For* op, const Stmt& s) final { analyzer_.Bind(op->loop_var, Range::make_by_min_extent(op->min, op->extent)); return IRMutator::Mutate_(op, s); } Stmt Mutate_(const LetStmt* op, const Stmt& s) final { Expr value = this->Mutate(op->value); if (!ir::HasSideEffect(value)) { analyzer_.Bind(op->var, value); return this->Mutate(op->body); } Stmt body = this->Mutate(op->body); if (value.same_as(op->value) && body.same_as(op->body)) { return s; } else { return LetStmt::make(op->var, value, body); } } // IfThenElse Stmt Mutate_(const IfThenElse* op, const Stmt& s) { Expr condition = this->Mutate(op->condition); Stmt then_case, else_case; { With<ConstraintContext> ctx(&analyzer_, condition); then_case = this->Mutate(op->then_case); } if (op->else_case.defined()) { With<ConstraintContext> ctx(&analyzer_, Mutate(Not::make(condition))); else_case = this->Mutate(op->else_case); } if (is_one(condition)) return then_case; if (is_zero(condition)) { if (else_case.defined()) { return else_case; } return Evaluate::make(0); } if (condition.same_as(op->condition) && then_case.same_as(op->then_case) && else_case.same_as(op->else_case)) { return s; } else { return IfThenElse::make(condition, then_case, else_case); } } // AttrStmt Stmt Mutate_(const AttrStmt* op, const Stmt& s) { if (op->attr_key == attr::thread_extent || op->attr_key == attr::virtual_thread) { IterVar iv(op->node.node_); CHECK_NE(iv->thread_tag.length(), 0U); if (!var_dom_.count(iv->var.get())) { Range dom = Range::make_by_min_extent(0, op->value); var_dom_[iv->var.get()] = dom; analyzer_.Bind(iv->var, dom); } Stmt stmt = IRMutator::Mutate_(op, s); return stmt; } else { return IRMutator::Mutate_(op, s); } } // AssertStmt Stmt Mutate_(const AssertStmt* op, const Stmt& s) final { Expr condition = this->Mutate(op->condition); Expr message = this->Mutate(op->message); With<ConstraintContext> ctx(&analyzer_, condition); Stmt body = this->Mutate(op->body); if (condition.same_as(op->condition) && message.same_as(op->message) && body.same_as(op->body)) { return s; } else { return AssertStmt::make(condition, message, body); } } // eliminate useless stores Stmt Mutate_(const Store* op, const Stmt& s) { Stmt stmt = IRMutator::Mutate_(op, s); op = stmt.as<Store>(); if (const Load* load = op->value.as<Load>()) { if (load->buffer_var.same_as(op->buffer_var) && Equal(load->index, op->index)) { return Evaluate::make(0); } } return stmt; } protected: Analyzer analyzer_; // variable domain std::unordered_map<const Variable*, Range> var_dom_; }; } // namespace arith namespace ir { Stmt CanonicalSimplify(Stmt stmt, Map<Var, Range> vrange) { return arith::StmtSimplifier().Simplify( stmt, vrange); } Expr CanonicalSimplify(Expr expr, Map<Var, Range> vrange) { arith::Analyzer analyzer; for (auto kv : vrange) { analyzer.Bind(kv.first, kv.second); } return analyzer.canonical_simplify(expr); } Expr Simplify(Expr expr, Map<Var, Range> vrange) { arith::Analyzer analyzer; for (auto kv : vrange) { analyzer.Bind(kv.first, kv.second); } expr = analyzer.Simplify(expr); return expr; } Stmt Simplify(Stmt stmt, Map<Var, Range> vrange) { return arith::StmtSimplifier().Simplify( stmt, vrange); } } // namespace ir } // namespace tvm <file_sep>/tutorials/frontend/build_gcn.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Building a Graph Convolutional Network ===================== **Author**: `<NAME> <https://yulunyao.io/>`_ This article is an introductory tutorial to build a Graph Convolutional Network (GCN) with Relay. In this tutorial, we will run our GCN on Cora dataset to demonstrate. Cora dataset is a common benchmark for Graph Neural Networks (GNN) and frameworks that support GNN training and inference. We directly load the dataset from DGL library to do the apples to apples comparison against DGL. Please refer to DGL tutorial on installation at https://docs.dgl.ai/install/index.html GPU support and more sparse operators will soon follow. """ ###################################################################### # Define Graph Convolution Layer # ---------------------------- # To run GCN on TVM, we first need to implement Graph Convolution Layer. # # You may refer to https://github.com/dmlc/dgl/blob/master/python/dgl/nn/mxnet/conv.py for a GraphConv Layer implemented in DGL with MXNet Backend # # The layer is defined with below operations, note that we apply two transposes to keep adjacency matrix on right hand side of sparse_dense operator, # this method is temporary and will be updated in next few weeks when we have sparse matrix transpose and support for left sparse operator. # # .. math:: # # \mbox{GraphConv}(A, H, W) = A * H * W # = ((H * W)^t * A^t)^t # = ((W^t * H^t) * A^t)^t from tvm import relay def GraphConv( layer_name, input_dim, output_dim, adj, input, activation=None, norm=None, ): r""" Parameters ---------- layer_name: str Name of layer input_dim: int Input dimension per node feature output_dim: int, Output dimension per node feature adj: namedtuple, Graph representation (Adjacency Matrix) in Sparse Format (`data`, `indices`, `indptr`), where `data` has shape [num_nonzeros], indices` has shape [num_nonzeros], `indptr` has shape [num_nodes + 1] input: relay.Expr, Input feature to current layer with shape [num_nodes, input_dim] norm: relay.Expr, Norm passed to this layer to normalize features before and after Convolution. activation: <function relay.op.nn>, Activation function applies to the output. e.g. relay.nn.{relu, sigmoid, log_softmax, softmax, leaky_relu} Returns ---------- output: tvm.relay.Expr The Output Tensor for this layer [num_nodes, output_dim] """ if norm is not None: input = relay.multiply(input, norm) weight = relay.var(layer_name + "_weight", shape=(input_dim, output_dim)) weight_transposed = relay.transpose(weight) dense = relay.nn.dense(weight_transposed, input) output = relay.nn.sparse_dense(dense, adj) output_transposed = relay.transpose(output) if norm is not None: output_transposed = relay.multiply(output_transposed, norm) if activation is not None: output_transposed = activation(output_transposed) return output_transposed ###################################################################### # Load the dataset # ------------------ # You may substitute this part with your own dataset, here we load data from DGL to benchmark import tvm, dgl, scipy import numpy as np import networkx as nx from collections import namedtuple from dgl.data import load_data def load_dataset(dataset="cora"): args = namedtuple("args", ["dataset"]) dataset = load_data(args(dataset)) params = {} params['infeats'] = dataset.features.astype('float32') # Only support float32 as feature for now # Remove self-loops to avoid duplicate passing of a node's feature to itself g = dataset.graph g.remove_edges_from(g.selfloop_edges()) g.add_edges_from(zip(g.nodes, g.nodes)) # Generate adjacency matrix adjacency = nx.to_scipy_sparse_matrix(g) params['data'] = adjacency.data.astype('float32') params['indices'] = adjacency.indices.astype('int32') params['indptr'] = adjacency.indptr.astype('int32') # Normalization w.r.t. node degrees degs = [g.in_degree[i] for i in range(g.number_of_nodes())] params['norm'] = np.power(degs, -0.5).astype('float32') params['norm'] = params['norm'].reshape((params['norm'].shape[0], 1)) return params ###################################################################### # Set up model Parameters # ------------------ r""" Parameters ---------- num_hidden: int number of hidden layers hidden_dim: int input dimension of hidden layers num_classes: int dimension of model output (Number of classes) target: str currently only support llvm, GPU support will be added in next few weeks activation: <function relay.op.nn>, Activation function applied to the output. e.g. relay.nn.{relu, sigmoid, log_softmax, softmax, leaky_relu} dataset: str Name of dataset. You can pick from ['cora', 'citeseer', 'pubmed'] or you can use your own. """ num_hidden = 1 hidden_dim = 16 num_classes = 7 target = 'llvm' activation = relay.nn.relu dataset = "cora" params = load_dataset(dataset) # Check shape of features assert len(params['infeats'].shape) == 2 nnodes, input_dim = params['infeats'].shape # Check validity of adjacency matrix assert params['data'] is not None and params['indices'] is not None and params['indptr'] is not None assert nnodes == params['indptr'].shape[0] - 1 ###################################################################### # Put layers together # ------------------ layers = [] # Define input features, norms, adjacency matrix infeats = relay.var("infeats", shape=(nnodes, input_dim)) norm = relay.Constant(tvm.nd.array(params['norm'])) data = relay.Constant(tvm.nd.array(params['data'])) indices = relay.Constant(tvm.nd.array(params['indices'])) indptr = relay.Constant(tvm.nd.array(params['indptr'])) Adjacency = namedtuple('Adjacency', ['data', 'indices', 'indptr']) adj = Adjacency(data, indices, indptr) # Generate Input Layer layers.append(GraphConv( layer_name= 'in', input_dim= input_dim, output_dim= hidden_dim, adj = adj, input= infeats, activation= activation, norm= norm, )) # Generate Hidden Layers for i in range(num_hidden): layers.append(GraphConv( layer_name= str(i), input_dim= hidden_dim, output_dim= hidden_dim, adj = adj, input= layers[-1], activation= activation, norm= norm, )) # Generate Output Layer layers.append(GraphConv( layer_name= 'out', input_dim= hidden_dim, output_dim= num_classes, adj = adj, input= layers[-1], activation= activation, norm= norm, )) output = layers[-1] # Analyze free variables and generate function func = relay.Function(relay.analysis.free_vars(output), output) ###################################################################### # Compile and run # ------------------ # We achieved 6.5x speedup for this dataset against dgl given the same model parameters. # Output numerical difference < 10e-4 %. # # DGL version: https://github.com/dmlc/dgl/blob/master/examples/mxnet/gcn/gcn.py from tvm.contrib import graph_runtime import time # Set up weights. You can modify this part and use your own trained weights. params['in_weight'] = np.ones((input_dim, hidden_dim), dtype='float32') params['out_weight'] = np.ones((hidden_dim, num_classes), dtype='float32') for i in range(num_hidden): params["%s_weight"%(str(i))] = np.ones((hidden_dim, hidden_dim), dtype='float32') # Generate graph and library with relay.build_config(opt_level=0): # Currently only support opt_level=0 graph, lib, params = relay.build(func, target, params=params) lib.save("lib.o") # Generate module for llvm ctx = tvm.context(target, 0) m = graph_runtime.create(graph, lib, ctx) m.set_input(**params) print("finished compiling, testing inference time cost") totaltime = 0 for i in range(30): st = time.time() # One forward pass on the entire network m.run() end = time.time() # Retrieve output Tensor as numpy array outval = m.get_output(0).asnumpy() totaltime += (end-st) if i == 0: print("features of first five nodes \n %s" % outval[:5]) if i == 4: print("5 Cycle Average Forward Pass Time ", totaltime/5) print("30 Cycle Average Forward Pass Time ", totaltime/30) <file_sep>/src/relay/backend/vm/deserializer.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2019 by Contributors * \file src/relay/backend/vm/deserializer.h * \brief Define a deserializer for the serialized Relay VM. */ #ifndef TVM_RELAY_BACKEND_VM_DESERIALIZER_H_ #define TVM_RELAY_BACKEND_VM_DESERIALIZER_H_ #include <dmlc/memory_io.h> #include <tvm/packed_func_ext.h> #include <tvm/runtime/packed_func.h> #include <tvm/runtime/vm.h> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace tvm { namespace relay { namespace vm { using namespace tvm::runtime::vm; namespace runtime = tvm::runtime; class Deserializer : public runtime::ModuleNode { public: /*! * \brief Initialize the deserializer for creating a virtual machine object. * * \param code The serialized code. * \param lib The serialized runtime module/library that contains the * hardware dependent code. */ inline void Init(const std::string& code, const runtime::Module& lib); /*! * \brief Return the member function to the frontend. * * \param name The name of the function. * \param sptr_to_self The pointer to the module node. * * \return The corresponding member function. */ PackedFunc GetFunction(const std::string& name, const std::shared_ptr<ModuleNode>& sptr_to_self) final; const char* type_key() const final { return "Deserializer"; } /*! \brief Deserialize the serialized VM. */ void Deserialize(); virtual ~Deserializer() { delete strm_; } private: /*! \brief Deserialize the globals in `vm_`. */ void DeserializeGlobalSection(); /*! \brief Deserialize the constant pool in `vm_`. */ void DeserializeConstantSection(); /*! \brief Deserialize primitive op names in `vm_`. */ void DeserializePrimitiveOpNames(); /*! \brief Deserialize the vm functions in `vm_`. */ void DeserializeCodeSection(); /*! \brief The code to be serialized. */ std::string code_; /*! \brief The stream used for serialization. */ dmlc::Stream* strm_; /*! \brief The VM to be created. */ std::shared_ptr<VirtualMachine> vm_; }; } // namespace vm } // namespace relay } // namespace tvm #endif // TVM_RELAY_BACKEND_VM_DESERIALIZER_H_ <file_sep>/topi/python/topi/x86/conv2d.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-variable,unused-argument,no-member """Conv2D schedule on x86""" import logging import re import tvm from tvm import autotvm from tvm.autotvm.task.topi_integration import deserialize_args from tvm.autotvm.task import get_config from .. import generic, tag from .. import nn from ..util import get_const_tuple, get_shape from ..nn.conv2d import conv2d, conv2d_NCHWc, \ conv2d_alter_layout, conv2d_infer_layout, _get_workload as _get_conv2d_workload from ..nn.depthwise_conv2d import _get_workload as _get_depthwise_conv2d_workload from ..nn.depthwise_conv2d import depthwise_conv2d_NCHWc, depthwise_conv2d_nchw from ..nn.pad import pad from . import conv2d_avx_1x1, conv2d_avx_common logger = logging.getLogger('topi') def _is_int8_hw_support(data_dtype, kernel_dtype, target): """ Checks to ensure that we can use Intel DLBoost instructions 1) The datatypes are correct. 2) LLVM version has support for the instructions. 3) Target is skylake and above. """ # 1) Check datatypes is_dtype_support = data_dtype == 'uint8' and kernel_dtype == 'int8' # 2) Check LLVM support llvm_intrin_fast_int8 = "llvm.x86.avx512.pmaddubs.w.512" llvm_id = tvm.codegen.llvm_lookup_intrinsic_id(llvm_intrin_fast_int8) is_llvm_support = llvm_id != 0 # 3) Check target is_target_support = False for opt in target.options: if opt == '-mcpu=skylake-avx512': is_target_support = True return is_dtype_support and is_llvm_support and is_target_support def _get_default_config(cfg, data, kernel, strides, padding, out_dtype, is_depthwise=False, layout='NCHW'): """ Get default schedule config for the workload """ if is_depthwise: wkl = _get_depthwise_conv2d_workload(data, kernel, strides, padding, out_dtype) from .depthwise_conv2d import _fallback_schedule _fallback_schedule(cfg, wkl) else: wkl = _get_conv2d_workload(data, kernel, strides, padding, out_dtype, layout) is_kernel_1x1 = wkl.hkernel == 1 and wkl.wkernel == 1 if is_kernel_1x1: conv2d_avx_1x1._fallback_schedule(cfg, wkl) else: conv2d_avx_common._fallback_schedule(cfg, wkl) def _create_tuning_space(cfg, data, kernel, strides, padding, dilation, layout): """Create schedule configuration from input arguments""" dshape = get_const_tuple(data.shape) kshape = get_const_tuple(kernel.shape) pat = re.compile(r'NCHW.+(\d+)c') if layout == 'NCHW': n, ic, h, w = dshape oc, _, kh, kw = kshape elif layout == 'NHWC': n, h, w, ic = dshape kh, kw, oc, _ = kshape elif pat.match(layout) is not None: n, ic_chunk, h, w, ic_bn = dshape target = tvm.target.current_target(allow_none=False) if _is_int8_hw_support(data.dtype, kernel.dtype, target): oc_chunk, k_ic, kh, kw, k_ic_f, oc_bn, k_ic_s = kshape ic = ic_chunk*ic_bn assert ic == k_ic*k_ic_f*kic_s else: oc_chunk, k_ic_chunk, kh, kw, k_ic_bn, oc_bn = kshape assert ic_chunk == k_ic_chunk assert ic_bn == k_ic_bn ic = ic_chunk*ic_bn oc = oc_chunk*oc_bn else: raise ValueError("Not support this layout {} with " "schedule template.".format(layout)) is_kernel_1x1 = kh == 1 and kw == 1 ph, pw = padding if isinstance(padding, (tuple, list)) else (padding, padding) sh, sw = strides if isinstance(strides, (tuple, list)) else (strides, strides) oh = (h - kh + 2 * ph) // sh + 1 ow = (w - kw + 2 * pw) // sw + 1 # Create schedule config cfg.define_split("tile_ic", ic, num_outputs=2) cfg.define_split("tile_oc", oc, num_outputs=2) cfg.define_split("tile_ow", ow, num_outputs=2, filter=lambda y: y.size[-1] <= 64) if is_kernel_1x1: cfg.define_knob("tile_oh", [1, 2] if oh > 1 else [1]) else: cfg.define_knob("unroll_kw", [True, False]) @autotvm.register_topi_compute(conv2d, 'cpu', ['direct']) def _declaration_conv(cfg, data, kernel, strides, padding, dilation, layout, out_dtype): out_dtype = data.dtype if out_dtype is None else out_dtype padding = padding if isinstance(padding, (tuple, list)) else (padding, padding) strides = strides if isinstance(strides, (tuple, list)) else (strides, strides) dilation = dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation) if layout == 'NCHW': _create_tuning_space(cfg, data, kernel, strides, padding, dilation, layout) if cfg.is_fallback: _get_default_config(cfg, data, kernel, strides, padding, out_dtype) return _declaration_conv_impl(cfg, data, kernel, strides, padding, dilation, layout, out_dtype) # HWOI kernel layout is for NHWC and HWCN kh, kw, _, _ = get_const_tuple(kernel.shape) if layout == 'HWCN': return nn.conv2d_hwcn(data, kernel, strides, padding, dilation, out_dtype) elif layout == 'NHWC' and kh == 1 and kw == 1 and kernel.dtype == "int8": if cfg.is_fallback: _get_default_config(cfg, data, kernel, strides, padding, out_dtype, False, layout) # specialize for INT8 1X1 conv on X86 return conv2d_avx_1x1._declaration_conv_nhwc_pack(cfg, data, kernel, strides, padding, dilation, out_dtype) elif layout == 'NHWC': return nn.conv2d_nhwc(data, kernel, strides, padding, dilation, out_dtype) raise ValueError("not support this layout {} yet".format(layout)) def _declaration_conv_impl(cfg, data, kernel, strides, padding, dilation, layout, out_dtype): out_dtype = data.dtype if out_dtype is None else out_dtype assert layout == 'NCHW', "only support NCHW convolution for AVX" assert isinstance(dilation, int) or len(dilation) == 2 if isinstance(dilation, int): dilation_h, dilation_w = dilation else: dilation_h, dilation_w = dilation HPAD, WPAD = padding HSTR, WSTR = strides batch_size, in_channel, in_height, in_width = get_const_tuple(data.shape) num_filter, _, kernel_height, kernel_width = get_const_tuple(kernel.shape) pad_height = in_height + 2 * HPAD pad_width = in_width + 2 * WPAD dilated_kernel_h = (kernel_height - 1) * dilation_h + 1 dilated_kernel_w = (kernel_width - 1) * dilation_w + 1 out_height = (in_height + 2 * HPAD - dilated_kernel_h) // HSTR + 1 out_width = (in_width + 2 * WPAD - dilated_kernel_w) // WSTR + 1 # pack data DOPAD = (HPAD != 0 or WPAD != 0) if DOPAD: data_pad = pad(data, (0, 0, HPAD, WPAD), name="data_pad") else: data_pad = data # fetch schedule ic_bn, oc_bn = cfg["tile_ic"].size[-1], cfg["tile_oc"].size[-1] shape = (batch_size, in_channel // ic_bn, pad_height, ic_bn, pad_width) data_vec = tvm.compute(shape, lambda n, C, h, c, w: data_pad[n, C * ic_bn + c, h, w], name='data_vec') # pack kernel shape = (num_filter//oc_bn, in_channel//ic_bn, kernel_height, kernel_width, ic_bn, oc_bn) kernel_vec = tvm.compute(shape, lambda CO, CI, h, w, ci, co: kernel[CO * oc_bn + co, CI * ic_bn + ci, h, w], name='kernel_vec') # convolution oshape = (batch_size, num_filter//oc_bn, out_height, out_width, oc_bn) unpack_shape = (batch_size, num_filter, out_height, out_width) ic = tvm.reduce_axis((0, in_channel), name='ic') kh = tvm.reduce_axis((0, kernel_height), name='kh') kw = tvm.reduce_axis((0, kernel_width), name='kw') conv = tvm.compute(oshape, lambda n, oc_chunk, oh, ow, oc_block: tvm.sum(data_vec[n, ic//ic_bn, oh*HSTR+kh*dilation_h, ic%ic_bn, ow*WSTR+kw*dilation_w].astype(out_dtype) * kernel_vec[oc_chunk, ic//ic_bn, kh, kw, ic%ic_bn, oc_block].astype(out_dtype), axis=[ic, kh, kw]), name='conv') unpack = tvm.compute(unpack_shape, lambda n, c, h, w: conv[n, c // oc_bn, h, w, c % oc_bn] .astype(out_dtype), name='output_unpack', tag='conv2d_nchw') return unpack @autotvm.register_topi_schedule(generic.schedule_conv2d_nchw, 'cpu', ['direct']) def schedule_conv2d(cfg, outs): """Create schedule for tensors""" s = tvm.create_schedule([x.op for x in outs]) scheduled_ops = [] def traverse(op): """Traverse operators from computation graph""" # inline all one-to-one-mapping operators except the last stage (output) if tag.is_broadcast(op.tag): if op not in s.outputs: s[op].compute_inline() for tensor in op.input_tensors: if isinstance(tensor.op, tvm.tensor.ComputeOp) and tensor.op not in scheduled_ops: traverse(tensor.op) if 'conv2d_nchw' in op.tag: output = op.output(0) conv_out = op.input_tensors[0] kernel_vec = conv_out.op.input_tensors[1] kernel = kernel_vec.op.input_tensors[0] if isinstance(kernel.op, tvm.tensor.ComputeOp) and "dilate" in kernel.op.tag: s[kernel].compute_inline() data_vec = conv_out.op.input_tensors[0] data = data_vec.op.input_tensors[0] data_pad = None if isinstance(data.op, tvm.tensor.ComputeOp) and "pad" in data.op.tag: data_pad = data data = data_pad.op.input_tensors[0] _, _, kh, kw = get_const_tuple(kernel.shape) is_kernel_1x1 = kh == 1 and kw == 1 args = [s, cfg, data, data_pad, data_vec, kernel_vec, conv_out, output, outs[0]] if is_kernel_1x1: conv2d_avx_1x1._schedule_conv(*args) else: conv2d_avx_common._schedule_conv(*args) scheduled_ops.append(op) traverse(outs[0].op) return s @autotvm.register_topi_schedule(generic.schedule_conv2d_nhwc_pack, 'cpu', ['direct']) def schedule_conv2d_nhwc_pack(cfg, outs): """Create schedule for tensors""" s = tvm.create_schedule([x.op for x in outs]) output_op = outs[0].op scheduled_ops = [] def traverse(op): """Traverse operators from computation graph""" # inline all one-to-one-mapping operators except the last stage (output) if tag.is_broadcast(op.tag): if op not in s.outputs: s[op].compute_inline() else: # inject custom schedule if len(op.axis) == 4: # schedule bias + bn + relu n, h, w, c = op.axis fused = s[op].fuse(n, h, w) s[op].parallel(fused) s[op].vectorize(c) for tensor in op.input_tensors: if isinstance(tensor.op, tvm.tensor.ComputeOp) and tensor.op not in scheduled_ops: traverse(tensor.op) if 'conv2d_nhwc_pack_int8' in op.tag: conv_out = op.output(0) kernel = conv_out.op.input_tensors[1] data_vec = conv_out.op.input_tensors[0] data = data_vec.op.input_tensors[0] \ if isinstance(data_vec.op, tvm.tensor.ComputeOp) and "pad" not in data_vec.op.tag \ else data_vec if isinstance(data.op, tvm.tensor.ComputeOp) and "pad" in data.op.tag: data_pad = data data = data_pad.op.input_tensors[0] args = [s, cfg, data_vec, conv_out, outs[0]] if data.dtype == 'uint8': kh, kw, _, _, _ = get_const_tuple(kernel.shape) if kh == 1 and kw == 1: conv2d_avx_1x1._schedule_conv_nhwc_pack_int8(*args) else: raise ValueError("Only support 1x1 kernel with " "schedule_conv2d_nhwc_pack.") else: raise ValueError("Not support this data type {} with " "schedule_conv2d_nhwc_pack. Only support int8".format(data.dtype)) scheduled_ops.append(op) traverse(output_op) return s @generic.schedule_conv2d_nhwc.register("cpu") def schedule_conv2d_nhwc(outs): """Create schedule for tensors""" s = tvm.create_schedule([x.op for x in outs]) output_op = outs[0].op scheduled_ops = [] def traverse(op): """Traverse operators from computation graph""" # inline all one-to-one-mapping operators except the last stage (output) if tag.is_broadcast(op.tag): if op not in s.outputs: s[op].compute_inline() else: # inject custom schedule if len(op.axis) == 4: # schedule bias + bn + relu n, h, w, c = op.axis fused = s[op].fuse(n, h, w) s[op].parallel(fused) s[op].vectorize(c) for tensor in op.input_tensors: if isinstance(tensor.op, tvm.tensor.ComputeOp) and tensor.op not in scheduled_ops: traverse(tensor.op) if 'conv2d_nhwc' in op.tag: conv = op.output(0) kernel = op.input_tensors[1] if isinstance(kernel.op, tvm.tensor.ComputeOp) and "dilate" in kernel.op.tag: s[kernel].compute_inline() data = op.input_tensors[0] data_pad = None if isinstance(data.op, tvm.tensor.ComputeOp) and "pad" in data.op.tag: data_pad = data data = data_pad.op.input_tensors[0] n_pad, h_pad, w_pad, c_pad = data_pad.op.axis pad_fused = s[data_pad].fuse(n_pad, h_pad) s[data_pad].parallel(pad_fused) C = conv n, h, w, c = C.op.axis ry, rx, rc = C.op.reduce_axis n_out, h_out, w_out, c_out = output_op.axis s[C].vectorize(c) if op != output_op: # fuse bias + bn + relu into conv s[C].compute_at(s[output_op], c_out) else: fused = s[C].fuse(n, h, w) s[C].parallel(fused) scheduled_ops.append(op) traverse(output_op) return s # Define template function for autotvm task # We define schedule template in this function instead of # declaration function since actual input arguments need # to be altered by the schedule selected. @autotvm.task.register("topi_x86_conv2d_NCHWc") def _topi_nn_conv2d_NCHWc(*args, **kwargs): assert not kwargs, "Do not support kwargs in template function call" args = deserialize_args(args) if len(args) == 7: data, kernel, strides, padding, dilation, origin_layout, dtype = args else: assert len(args) == 8 data, kernel, strides, padding, dilation, origin_layout, out_layout, dtype = args raw_data_shape = get_const_tuple(data.shape) raw_kernel_shape = get_const_tuple(kernel.shape) # get config here cfg = get_config() _create_tuning_space(cfg, data, kernel, strides, padding, dilation, origin_layout) # change shape with the value in config ic_bn, oc_bn, ow_bn = (cfg["tile_ic"].size[-1], cfg["tile_oc"].size[-1], cfg["tile_ow"].size[-1]) new_data_shape = (raw_data_shape[0], raw_data_shape[1] // ic_bn, raw_data_shape[2], raw_data_shape[3], ic_bn) data_layout = "NCHW%dc" % ic_bn out_layout = "NCHW%dc" % oc_bn new_kernel_shape = (raw_kernel_shape[0] // oc_bn, raw_kernel_shape[1] // ic_bn, raw_kernel_shape[2], raw_kernel_shape[3], ic_bn, oc_bn) new_data = tvm.placeholder(new_data_shape, data.dtype) new_kernel = tvm.placeholder(new_kernel_shape, kernel.dtype) C = _declaration_conv_NCHWc(cfg, new_data, new_kernel, strides, padding, dilation, data_layout, out_layout, dtype) s = _schedule_conv2d_NCHWc(cfg, [C]) return s, [new_data, new_kernel, C] @conv2d_alter_layout.register("cpu") def _alter_conv2d_layout(attrs, inputs, tinfo, F): copy_inputs = [s for s in inputs] new_attrs = {k : attrs[k] for k in attrs.keys()} if F.__name__ == 'tvm.relay.op': # Derive channels for frontends (e.g ONNX) that miss "channel" field. new_attrs["channels"] = inputs[1].checked_type.shape[attrs['kernel_layout'].index('O')] data, kernel = tinfo[0], tinfo[1] batch_size, in_channel, height, width = get_const_tuple(data.shape) groups = attrs.get_int("groups") out_channel = attrs.get_int("channels") \ if F.__name__ == 'nnvm.symbol' else new_attrs["channels"] padding = attrs.get_int_tuple("padding") strides = attrs.get_int_tuple("strides") dilation = attrs.get_int_tuple("dilation") out_dtype = attrs["out_dtype"] layout_name = 'layout' if F.__name__ == 'nnvm.symbol' else 'data_layout' layout = attrs[layout_name] kh, kw = attrs.get_int_tuple("kernel_size") dtype = data.dtype out_dtype = dtype if out_dtype in ("same", "") else out_dtype kshape = get_shape(kernel.shape, attrs["kernel_layout"], "OIHW") is_depthwise = groups == kshape[0] and kshape[1] == 1 # only optimize for NCHW if layout != 'NCHW' or attrs["kernel_layout"] != "OIHW": return None if groups != 1 and not is_depthwise: return None dispatch_ctx = autotvm.task.DispatchContext.current target = tvm.target.current_target() # query schedule and fallback if necessary workload = autotvm.task.args_to_workload( [data, kernel, strides, padding, dilation, out_dtype], depthwise_conv2d_nchw) \ if is_depthwise else \ autotvm.task.args_to_workload( [data, kernel, strides, padding, dilation, layout, out_dtype], conv2d) cfg = dispatch_ctx.query(target, workload) if cfg.is_fallback: _get_default_config(cfg, data, kernel, strides, padding, out_dtype, is_depthwise) ic_bn, oc_bn = cfg["tile_ic"].size[-1], cfg["tile_oc"].size[-1] new_attrs[layout_name] = 'NCHW%dc' % ic_bn new_attrs['out_layout'] = 'NCHW%dc' % oc_bn new_data = tvm.placeholder((batch_size, in_channel//ic_bn, height, width, ic_bn), dtype=data.dtype) if is_depthwise: new_attrs['kernel_layout'] = 'OIHW1i%do' % oc_bn # Store altered operator's config new_kernel = tvm.placeholder((out_channel//oc_bn, 1, kh, kw, 1, oc_bn), dtype=kernel.dtype) new_workload = autotvm.task.args_to_workload( [new_data, new_kernel, strides, padding, dilation, new_attrs[layout_name], new_attrs['out_layout'], out_dtype], depthwise_conv2d_NCHWc) dispatch_ctx.update(target, new_workload, cfg) else: if _is_int8_hw_support(data.dtype, kernel.dtype, target): # Convert kernel data layout from 4D to 7D n_elems = 4 out_channel, _, kh, kw = get_const_tuple(kernel.shape) data_expr, kernel_expr = inputs kernel_IHWO = F.transpose(kernel_expr, axes=(1, 2, 3, 0)) kernel_IHWOo = F.reshape(kernel_IHWO, (in_channel, kh, kw, out_channel//oc_bn, oc_bn)) kernel_OHWoI = F.transpose(kernel_IHWOo, axes=(3, 1, 2, 4, 0)) kernel_OHWoIi = F.reshape(kernel_OHWoI, (out_channel//oc_bn, kh, kw, oc_bn, in_channel//ic_bn, ic_bn)) kernel_OHWoIie = F.reshape(kernel_OHWoIi, (out_channel//oc_bn, kh, kw, oc_bn, in_channel//ic_bn, ic_bn//n_elems, n_elems)) kernel_OIHWioe = F.transpose(kernel_OHWoIie, axes=(0, 4, 1, 2, 5, 3, 6)) copy_inputs = [data_expr, kernel_OIHWioe] # Store altered operator's config new_kernel = tvm.placeholder((out_channel//oc_bn, kh, kw, oc_bn, in_channel//ic_bn, ic_bn//n_elems, n_elems)) new_workload = autotvm.task.args_to_workload( [new_data, new_kernel, strides, padding, dilation, new_attrs[layout_name], new_attrs['out_layout'], out_dtype], conv2d_NCHWc) dispatch_ctx.update(target, new_workload, cfg) else: out_channel, _, kh, kw = get_const_tuple(kernel.shape) # (oc, ic, h, w) -> (OC, IC, h, w, ic, oc) new_attrs['kernel_layout'] = 'OIHW%di%do' % (ic_bn, oc_bn) # Store altered operator's config new_kernel = tvm.placeholder((out_channel//oc_bn, in_channel//ic_bn, kh, kw, ic_bn, oc_bn), dtype=kernel.dtype) new_workload = autotvm.task.args_to_workload( [new_data, new_kernel, strides, padding, dilation, new_attrs[layout_name], new_attrs['out_layout'], out_dtype], conv2d_NCHWc) dispatch_ctx.update(target, new_workload, cfg) if is_depthwise: if F.__name__ == 'nnvm.symbol': logging.warning("Use native layout for depthwise convolution on NNVM.") return None return F.nn.contrib_depthwise_conv2d_nchwc(*copy_inputs, **new_attrs) else: if F.__name__ == 'nnvm.symbol': return F.contrib.conv2d_NCHWc(*copy_inputs, **new_attrs) return F.nn.contrib_conv2d_nchwc(*copy_inputs, **new_attrs) @conv2d_infer_layout.register("cpu") def _conv2d_infer_layout(workload, cfg): _, data, kernel, strides, padding, dilation, layout, dtype = workload batch_size, in_channel, in_height, in_width = data[:-1] out_channel, _, k_height, k_width = kernel[:-1] out_height = (in_height + 2 * padding[0] - k_height) // strides[0] + 1 out_width = (in_width + 2 * padding[1] - k_width) // strides[1] + 1 tile_ic, tile_oc = cfg["tile_ic"].size[-1], cfg["tile_oc"].size[-1] in_shape = (batch_size, in_channel // tile_ic, in_height, in_width, tile_ic) in_layout = "NCHW%dc" % tile_ic out_shape = (batch_size, out_channel // tile_oc, out_height, out_width, tile_oc) out_layout = "NCHW%dc" % tile_oc return ((in_shape, in_layout),), ((out_shape, out_layout),) @autotvm.register_topi_compute(conv2d_NCHWc, 'cpu', 'direct') def _declaration_conv_NCHWc(cfg, data, kernel, strides, padding, dilation, layout, out_layout, out_dtype): # layout and out_layout are not used here, # we keep them for debug convenience when dumping autotvm workload HPAD, WPAD = padding if isinstance(padding, (tuple, list)) else (padding, padding) HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides) dilation_h, dilation_w = dilation if isinstance(dilation, (tuple, list)) \ else (dilation, dilation) n, ic_chunk, ih, iw, ic_bn = get_const_tuple(data.shape) in_channel = ic_chunk * ic_bn target = tvm.target.current_target(allow_none=False) if _is_int8_hw_support(data.dtype, kernel.dtype, target): oc_chunk, ic_chunk_group, kernel_height, kernel_width, _, oc_bn, _ = \ get_const_tuple(kernel.shape) else: oc_chunk, ic_chunk_group, kernel_height, kernel_width, _, oc_bn = \ get_const_tuple(kernel.shape) num_filter = oc_chunk * oc_bn groups = ic_chunk // ic_chunk_group dilated_kernel_h = (kernel_height - 1) * dilation_h + 1 dilated_kernel_w = (kernel_width - 1) * dilation_w + 1 if cfg.is_fallback: _get_default_config(cfg, tvm.placeholder((n, in_channel, ih, iw), dtype=data.dtype), tvm.placeholder((num_filter, in_channel, kernel_height, kernel_width), dtype=kernel.dtype), strides, padding, out_dtype) # output shape out_height = (ih + 2 * HPAD - dilated_kernel_h) // HSTR + 1 out_width = (iw + 2 * WPAD - dilated_kernel_w) // WSTR + 1 oshape = (n, oc_chunk, out_height, out_width, oc_bn) # DOPAD DOPAD = (HPAD != 0 or WPAD != 0) if DOPAD: data_pad = pad(data, (0, 0, HPAD, WPAD, 0), name="data_pad") else: data_pad = data ic = tvm.reduce_axis((0, in_channel), name='ic') kh = tvm.reduce_axis((0, kernel_height), name='kh') kw = tvm.reduce_axis((0, kernel_width), name='kw') if _is_int8_hw_support(data.dtype, kernel.dtype, target) and groups == 1: assert out_dtype == "int32", \ "INT8 convolution requires input dtype = uint8 and output dtype=int32" # Intel performs dot product of 2 "4" Int8 values # Current implementation requires ic_bn to be a multiple of 4 n_elems = 4 assert ic_bn % n_elems == 0 ic_outer = tvm.reduce_axis((0, in_channel//ic_bn), name='ic_outer') ic_f_inner = tvm.reduce_axis((0, ic_bn//n_elems), name='ic_f_inner') ic_s_inner = tvm.reduce_axis((0, n_elems), name='ic_s_inner') return tvm.compute(oshape, lambda n, oc_chunk, oh, ow, oc_block: tvm.sum(data_pad[n, ic_outer, oh*HSTR+kh*dilation_h, ow*WSTR+kw*dilation_w, ic_f_inner * n_elems + ic_s_inner] .astype(out_dtype) * kernel[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner].astype(out_dtype), axis=[kh, kw, ic_outer, ic_f_inner, ic_s_inner]), name='conv2d_NCHWc_int8', tag="conv2d_NCHWc_int8") if _is_int8_hw_support(data.dtype, kernel.dtype, target): # for int8 group conv support n_elems = 4 ic_chunk = in_channel//ic_bn ic_outer = tvm.reduce_axis((0, ic_chunk//groups), name='ic_outer') ic_f_inner = tvm.reduce_axis((0, ic_bn//n_elems), name='ic_f_inner') ic_s_inner = tvm.reduce_axis((0, n_elems), name='ic_s_inner') oshape = (n, oc_chunk, out_height, out_width, oc_bn) return tvm.compute(oshape, lambda n, occ, oh, ow, oc_block: tvm.sum(data_pad[n, (occ*oc_bn//(oc_chunk*oc_bn//groups))*\ (ic_chunk//groups)+ic_outer, oh*HSTR+kh, ow*WSTR+kw, ic_f_inner * n_elems + ic_s_inner].astype(out_dtype) * kernel[occ, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner].astype(out_dtype), axis=[kh, kw, ic_outer, ic_f_inner, ic_s_inner]), name='conv2d_NCHWc_int8', tag="conv2d_NCHWc_int8") # else: fp implementation return tvm.compute(oshape, lambda n, oc_chunk, oh, ow, oc_block: tvm.sum(data_pad[n, ic//ic_bn, oh*HSTR+kh*dilation_h, ow*WSTR+kw*dilation_w, ic%ic_bn].astype(out_dtype) * kernel[oc_chunk, ic//ic_bn, kh, kw, ic%ic_bn, oc_block], axis=[ic, kh, kw]), name='conv2d_NCHWc', tag="conv2d_NCHWc") @autotvm.register_topi_schedule(generic.schedule_conv2d_NCHWc, 'cpu', ['direct']) def _schedule_conv2d_NCHWc(cfg, outs): """Create schedule for tensors""" s = tvm.create_schedule([x.op for x in outs]) scheduled_ops = [] def traverse(op): """Traverse operators from computation graph""" # inline all one-to-one-mapping operators except the last stage (output) if tag.is_broadcast(op.tag): if op not in s.outputs: s[op].compute_inline() for tensor in op.input_tensors: if isinstance(tensor.op, tvm.tensor.ComputeOp) and tensor.op not in scheduled_ops: traverse(tensor.op) if 'conv2d_NCHWc' in op.tag: conv_out = op.output(0) kernel = conv_out.op.input_tensors[1] data_vec = conv_out.op.input_tensors[0] data = data_vec.op.input_tensors[0] \ if isinstance(data_vec.op, tvm.tensor.ComputeOp) and "pad" not in data_vec.op.tag \ else data_vec if isinstance(data.op, tvm.tensor.ComputeOp) and "pad" in data.op.tag: data_pad = data data = data_pad.op.input_tensors[0] args = [s, cfg, data_vec, conv_out, outs[0]] target = tvm.target.current_target(allow_none=False) if _is_int8_hw_support(data.dtype, kernel.dtype, target): # int8 conv kernel is 7-dim _, _, kh, kw, _, _, _ = get_const_tuple(kernel.shape) if kh == 1 and kw == 1: conv2d_avx_1x1._schedule_conv_NCHWc_int8(*args) else: conv2d_avx_common._schedule_conv_NCHWc_int8(*args) else: _, _, kh, kw, _, _, = get_const_tuple(kernel.shape) if kh == 1 and kw == 1: conv2d_avx_1x1._schedule_conv_NCHWc(*args) else: conv2d_avx_common._schedule_conv_NCHWc(*args) scheduled_ops.append(op) traverse(outs[0].op) return s <file_sep>/python/tvm/_ffi/vmobj.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Runtime Object api""" from __future__ import absolute_import import sys from .base import _FFI_MODE IMPORT_EXCEPT = RuntimeError if _FFI_MODE == "cython" else ImportError try: # pylint: disable=wrong-import-position if _FFI_MODE == "ctypes": raise ImportError() if sys.version_info >= (3, 0): from ._cy3.core import _set_class_object from ._cy3.core import ObjectBase as _ObjectBase from ._cy3.core import _register_object else: from ._cy2.core import _set_class_object from ._cy2.core import ObjectBase as _ObjectBase from ._cy2.core import _register_object except IMPORT_EXCEPT: # pylint: disable=wrong-import-position from ._ctypes.function import _set_class_object from ._ctypes.vmobj import ObjectBase as _ObjectBase from ._ctypes.vmobj import _register_object class ObjectTag(object): """Type code used in API calls""" TENSOR = 0 CLOSURE = 1 DATATYPE = 2 class Object(_ObjectBase): """The VM Object used in Relay virtual machine.""" def register_object(cls): _register_object(cls.tag, cls) return cls _set_class_object(Object) <file_sep>/python/tvm/_ffi/_ctypes/node.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, protected-access # pylint: disable=no-member, missing-docstring, not-callable from __future__ import absolute_import import ctypes from ..base import _LIB, check_call, c_str from ..node_generic import _set_class_node_base from .types import TVMValue, TypeCode from .types import RETURN_SWITCH, C_TO_PY_ARG_SWITCH, _wrap_arg_func NodeHandle = ctypes.c_void_p __init_by_constructor__ = None """Maps node type to its constructor""" NODE_TYPE = {} def _register_node(index, cls): """register node class""" NODE_TYPE[index] = cls def _return_node(x): """Return node function""" handle = x.v_handle if not isinstance(handle, NodeHandle): handle = NodeHandle(handle) tindex = ctypes.c_int() check_call(_LIB.TVMNodeGetTypeIndex(handle, ctypes.byref(tindex))) cls = NODE_TYPE.get(tindex.value, NodeBase) # Avoid calling __init__ of cls, instead directly call __new__ # This allows child class to implement their own __init__ node = cls.__new__(cls) node.handle = handle return node RETURN_SWITCH[TypeCode.NODE_HANDLE] = _return_node C_TO_PY_ARG_SWITCH[TypeCode.NODE_HANDLE] = _wrap_arg_func( _return_node, TypeCode.NODE_HANDLE) class NodeBase(object): __slots__ = ["handle"] # pylint: disable=no-member def __del__(self): if _LIB is not None: check_call(_LIB.TVMNodeFree(self.handle)) def __getattr__(self, name): ret_val = TVMValue() ret_type_code = ctypes.c_int() ret_success = ctypes.c_int() check_call(_LIB.TVMNodeGetAttr( self.handle, c_str(name), ctypes.byref(ret_val), ctypes.byref(ret_type_code), ctypes.byref(ret_success))) if not ret_success.value: raise AttributeError( "'%s' object has no attribute '%s'" % (str(type(self)), name)) return RETURN_SWITCH[ret_type_code.value](ret_val) def __init_handle_by_constructor__(self, fconstructor, *args): """Initialize the handle by calling constructor function. Parameters ---------- fconstructor : Function Constructor function. args: list of objects The arguments to the constructor Note ---- We have a special calling convention to call constructor functions. So the return handle is directly set into the Node object instead of creating a new Node. """ # assign handle first to avoid error raising self.handle = None handle = __init_by_constructor__(fconstructor, args) if not isinstance(handle, NodeHandle): handle = NodeHandle(handle) self.handle = handle _set_class_node_base(NodeBase) <file_sep>/topi/python/topi/cuda/__init__.py # pylint: disable=redefined-builtin, wildcard-import """CUDA specific declaration and schedules.""" from __future__ import absolute_import as _abs from . import conv2d, depthwise_conv2d, conv2d_transpose_nchw, deformable_conv2d, \ group_conv2d_nchw, dense from .conv2d_hwcn import schedule_conv2d_hwcn from .depthwise_conv2d import schedule_depthwise_conv2d_backward_input_nhwc from .depthwise_conv2d import schedule_depthwise_conv2d_backward_weight_nhwc from .group_conv2d_nchw import schedule_conv2d_nchw_cuda from .reduction import schedule_reduce from .softmax import schedule_softmax from .injective import schedule_injective, schedule_elemwise, schedule_broadcast from .dense import schedule_dense from .pooling import schedule_pool, schedule_adaptive_pool from .extern import schedule_extern from .nn import schedule_lrn, schedule_l2_normalize from .batch_matmul import schedule_batch_matmul from .vision import * from . import ssd from .ssd import * from .nms import * from .rcnn import * from .sort import * <file_sep>/.github/PULL_REQUEST_TEMPLATE.md Thanks for contributing to TVM! Please refer to guideline https://docs.tvm.ai/contribute/ for useful information and tips. After the pull request is submitted, please request code reviews from [Reviewers](https://github.com/dmlc/tvm/blob/master/CONTRIBUTORS.md#reviewers). <file_sep>/python/tvm/relay/op/_transform.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Backend compiler related feature registration""" # pylint: disable=invalid-name,unused-argument, len-as-condition from __future__ import absolute_import from topi.util import get_const_int, get_const_tuple from . import op as _reg from ._reduce import _schedule_reduce from .op import OpPattern from ...hybrid import script from ...api import convert schedule_injective = _reg.schedule_injective schedule_broadcast = _reg.schedule_injective schedule_concatenate = _reg.schedule_concatenate _reg.register_schedule("collapse_sum_like", _schedule_reduce) _reg.register_schedule("broadcast_to", schedule_broadcast) _reg.register_schedule("broadcast_to_like", schedule_broadcast) _reg.register_schedule("expand_dims", schedule_broadcast) _reg.register_schedule("squeeze", schedule_injective) _reg.register_schedule("reshape", schedule_injective) _reg.register_schedule("reshape_like", schedule_injective) _reg.register_schedule("full", schedule_injective) _reg.register_schedule("full_like", schedule_injective) _reg.register_schedule("arange", schedule_injective) _reg.register_schedule("reverse", schedule_injective) _reg.register_schedule("repeat", schedule_broadcast) _reg.register_schedule("tile", schedule_broadcast) _reg.register_schedule("cast", schedule_injective) _reg.register_schedule("cast_like", schedule_injective) _reg.register_schedule("reinterpret", schedule_injective) _reg.register_schedule("strided_slice", schedule_injective) _reg.register_schedule("slice_like", schedule_injective) _reg.register_schedule("split", schedule_injective) _reg.register_schedule("take", schedule_injective) _reg.register_schedule("transpose", schedule_injective) _reg.register_schedule("where", schedule_broadcast) _reg.register_schedule("stack", schedule_injective) _reg.register_schedule("concatenate", schedule_concatenate) _reg.register_schedule("_contrib_reverse_reshape", schedule_injective) _reg.register_schedule("gather_nd", schedule_injective) _reg.register_schedule("sequence_mask", schedule_injective) _reg.register_schedule("one_hot", schedule_injective) # layout_transform _reg.register_schedule("layout_transform", schedule_injective) _reg.register_pattern("layout_transform", OpPattern.INJECTIVE) # shape func @script def _arange_shape_func(start, stop, step): out = output_tensor((1,), "int64") out[0] = int64(ceil_div((float32(stop[0]) - float32(start[0])), float32(step[0]))) return out @_reg.register_shape_func("arange", True) def arange_shape_func(attrs, inputs, _): return [_arange_shape_func(*inputs)] @script def _concatenate_shape_func(inputs, axis): ndim = inputs[0].shape[0] out = output_tensor((ndim,), "int64") for i in const_range(ndim): if i != axis: out[i] = inputs[0][i] for j in const_range(1, len(inputs)): assert out[i] == inputs[j][i], \ "Dims mismatch in the inputs of concatenate." else: out[i] = int64(0) for j in const_range(len(inputs)): out[i] += inputs[j][i] return out @_reg.register_shape_func("concatenate", False) def concatenate_shape_func(attrs, inputs, _): axis = get_const_int(attrs.axis) return [_concatenate_shape_func(inputs, convert(axis))] @script def _reshape_shape_func(data_shape, newshape, ndim): out = output_tensor((ndim,), "int64") src_idx = 0 dst_idx = 0 infer_idx = -1 copy = False skip = 0 for i in const_range(len(newshape)): if skip > 0: skip -= 1 elif newshape[i] > 0: out[dst_idx] = int64(newshape[i]) src_idx += 1 dst_idx += 1 elif newshape[i] == 0: out[dst_idx] = data_shape[src_idx] src_idx += 1 dst_idx += 1 elif newshape[i] == -1: assert infer_idx < 0, "One and only one dim can be inferred" out[dst_idx] = int64(1) infer_idx = i dst_idx += 1 elif newshape[i] == -2: copy = True elif newshape[i] == -3: assert data_shape.shape[0] - src_idx > 1, \ "Not enough dims in input shape for -3" out[dst_idx] = data_shape[src_idx] * data_shape[src_idx+1] src_idx += 2 dst_idx += 1 elif newshape[i] == -4: assert len(newshape) - i > 2, "Not enough dims in new shape for -4" if newshape[i+1] == -1: assert newshape[i+2] != -1, "Split dims cannot both be -1." out[dst_idx] = data_shape[src_idx] / int64(newshape[i+2]) out[dst_idx+1] = int64(newshape[i+2]) else: out[dst_idx] = int64(newshape[i+1]) if newshape[i+2] == -1: out[dst_idx+1] = data_shape[src_idx] / int64(newshape[i+1]) else: out[dst_idx+1] = int64(newshape[i+2]) assert data_shape[src_idx] == out[dst_idx] * out[dst_idx+1],\ "Product of split dims doesn't match to input dim" src_idx += 1 dst_idx += 2 skip = 2 else: assert False, "Invalid special values in new shape" if len(data_shape.shape) > 0: # if data is not constant, we can then handle -1 and -2 if copy: for i in range(src_idx, data_shape.shape[0]): out[dst_idx] = data_shape[i] dst_idx += 1 if infer_idx >= 0: old_size = int64(1) for i in const_range(data_shape.shape[0]): old_size *= data_shape[i] new_size = int64(1) for i in const_range(out.shape[0]): new_size *= out[i] out[infer_idx] = old_size / new_size return out @_reg.register_shape_func("reshape", False) def reshape_shape_func(attrs, inputs, out_ndims): newshape = get_const_tuple(attrs.newshape) return [_reshape_shape_func(inputs[0], convert(newshape), out_ndims[0])] @script def _take_no_axis_shape_func(indices_shape, out_ndim): out = output_tensor((out_ndim,), "int64") for i in const_range(out_ndim): out[i] = indices_shape[i] return out @script def _take_with_axis_shape_func(data_shape, indices_shape, axis, out_ndim): out = output_tensor((out_ndim,), "int64") for i in const_range(axis): out[i] = data_shape[i] if len(indices_shape.shape) == 0: # indices is constant for i in const_range(axis+1, len(data_shape)): out[i-1] = data_shape[i] else: for i in const_range(len(indices_shape)): out[axis+i] = indices_shape[i] for i in const_range(axis+1, len(data_shape)): out[len(indices_shape)+i-1] = data_shape[i] return out @_reg.register_shape_func("take", False) def take_shape_func(attrs, inputs, out_ndims): """ Shape function for take op. """ if attrs.axis is None: return [_take_no_axis_shape_func(inputs[1], out_ndims[0])] else: axis = get_const_int(attrs.axis) data_ndim = int(inputs[0].shape[0]) if axis < 0: axis += data_ndim assert 0 <= axis < data_ndim return [_take_with_axis_shape_func(*inputs, convert(axis), out_ndims[0])] <file_sep>/topi/python/topi/intel_graphics/__init__.py # pylint: disable=redefined-builtin, wildcard-import """Intel Gen9 GPU specific declaration and schedules.""" from __future__ import absolute_import as _abs from .conv2d import * <file_sep>/topi/python/topi/x86/conv2d_transpose.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-variable,unused-argument,no-member """Conv2D Transpose schedule on x86""" import tvm from tvm import autotvm from .. import generic, tag from ..nn.conv2d_transpose import conv2d_transpose_nchw, declaration_conv2d_transpose_impl @autotvm.register_topi_compute(conv2d_transpose_nchw, 'cpu', ['direct']) def _declaration_conv2d_transpose(cfg, data, kernel, strides, padding, out_dtype): # TODO cfg is not used for now return declaration_conv2d_transpose_impl(data, kernel, strides, padding, out_dtype) @autotvm.register_topi_schedule(generic.schedule_conv2d_transpose_nchw, 'cpu', ['direct']) def schedule_conv2d_transpose(cfg, outs): """Create schedule for tensors""" outs = [outs] if isinstance(outs, tvm.tensor.Tensor) else outs s = tvm.create_schedule([x.op for x in outs]) scheduled_ops = [] def traverse(op): """Traverse operators from computation graph""" # inline all one-to-one-mapping operators except the last stage (output) if tag.is_injective(op.tag): if op not in s.outputs: s[op].compute_inline() for tensor in op.input_tensors: if isinstance(tensor.op, tvm.tensor.ComputeOp) and tensor.op not in scheduled_ops: traverse(tensor.op) if 'conv2d_transpose_nchw' in op.tag: C = op.output(0) N, OC, OH, OW = C.op.axis rc, ry, rx = C.op.reduce_axis OH, oh = s[C].split(OH, factor=2) OC, oc = s[C].split(OC, factor=32) IC, ic = s[C].split(rc, factor=32) s[C].reorder(N, OC, OH, OW, oc, IC, ry, rx, ic) N = s[C].fuse(N, OC) s[C].vectorize(oc) s[C].parallel(N) scheduled_ops.append(op) traverse(outs[0].op) return s <file_sep>/Makefile # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. ROOTDIR = $(CURDIR) .PHONY: clean all test doc pylint cpplint lint\ cython cython2 cython3 web runtime vta ifndef DMLC_CORE_PATH DMLC_CORE_PATH = $(ROOTDIR)/3rdparty/dmlc-core endif ifndef DLPACK_PATH DLPACK_PATH = $(ROOTDIR)/3rdparty/dlpack endif INCLUDE_FLAGS = -Iinclude -I$(DLPACK_PATH)/include -I$(DMLC_CORE_PATH)/include PKG_CFLAGS = -std=c++11 -Wall -O2 $(INCLUDE_FLAGS) -fPIC PKG_LDFLAGS = all: @mkdir -p build && cd build && cmake .. && $(MAKE) runtime: @mkdir -p build && cd build && cmake .. && $(MAKE) runtime vta: @mkdir -p build && cd build && cmake .. && $(MAKE) vta cpptest: @mkdir -p build && cd build && cmake .. && $(MAKE) cpptest # EMCC; Web related scripts EMCC_FLAGS= -std=c++11 -DDMLC_LOG_STACK_TRACE=0\ -Oz -s RESERVED_FUNCTION_POINTERS=2 -s MAIN_MODULE=1 -s NO_EXIT_RUNTIME=1\ -s TOTAL_MEMORY=1073741824\ -s EXTRA_EXPORTED_RUNTIME_METHODS="['addFunction','cwrap','getValue','setValue']"\ -s USE_GLFW=3 -s USE_WEBGL2=1 -lglfw\ $(INCLUDE_FLAGS) web: build/libtvm_web_runtime.js build/libtvm_web_runtime.bc build/libtvm_web_runtime.bc: web/web_runtime.cc @mkdir -p build/web @mkdir -p $(@D) emcc $(EMCC_FLAGS) -MM -MT build/libtvm_web_runtime.bc $< >build/web/web_runtime.d emcc $(EMCC_FLAGS) -o $@ web/web_runtime.cc build/libtvm_web_runtime.js: build/libtvm_web_runtime.bc @mkdir -p $(@D) emcc $(EMCC_FLAGS) -o $@ build/libtvm_web_runtime.bc # Lint scripts cpplint: python3 3rdparty/dmlc-core/scripts/lint.py vta cpp vta/include vta/src python3 3rdparty/dmlc-core/scripts/lint.py topi cpp topi/include; python3 3rdparty/dmlc-core/scripts/lint.py nnvm cpp nnvm/include nnvm/src; python3 3rdparty/dmlc-core/scripts/lint.py tvm cpp include src verilog\ examples/extension/src examples/graph_executor/src pylint: python3 -m pylint python/tvm --rcfile=$(ROOTDIR)/tests/lint/pylintrc python3 -m pylint topi/python/topi --rcfile=$(ROOTDIR)/tests/lint/pylintrc python3 -m pylint nnvm/python/nnvm --rcfile=$(ROOTDIR)/tests/lint/pylintrc python3 -m pylint vta/python/vta --rcfile=$(ROOTDIR)/tests/lint/pylintrc jnilint: python3 3rdparty/dmlc-core/scripts/lint.py tvm4j-jni cpp jvm/native/src lint: cpplint pylint jnilint doc: doxygen docs/Doxyfile javadoc: # build artifact is in jvm/core/target/site/apidocs cd jvm && mvn javadoc:javadoc # Cython build cython: cd python; python setup.py build_ext --inplace cython2: cd python; python2 setup.py build_ext --inplace cython3: cd python; python3 setup.py build_ext --inplace cyclean: rm -rf python/tvm/*/*/*.so python/tvm/*/*/*.dylib python/tvm/*/*/*.cpp # JVM build rules ifeq ($(OS),Windows_NT) JVM_PKG_PROFILE := windows SHARED_LIBRARY_SUFFIX := dll else UNAME_S := $(shell uname -s) ifeq ($(UNAME_S), Darwin) JVM_PKG_PROFILE := osx-x86_64 SHARED_LIBRARY_SUFFIX := dylib else JVM_PKG_PROFILE := linux-x86_64 SHARED_LIBRARY_SUFFIX := so endif endif JVM_TEST_ARGS := $(if $(JVM_TEST_ARGS),$(JVM_TEST_ARGS),-DskipTests -Dcheckstyle.skip=true) jvmpkg: (cd $(ROOTDIR)/jvm; \ mvn clean package -P$(JVM_PKG_PROFILE) -Dcxx="$(CXX)" \ -Dcflags="$(PKG_CFLAGS)" -Dldflags="$(PKG_LDFLAGS)" \ -Dcurrent_libdir="$(ROOTDIR)/build" $(JVM_TEST_ARGS)) jvminstall: (cd $(ROOTDIR)/jvm; \ mvn install -P$(JVM_PKG_PROFILE) -Dcxx="$(CXX)" \ -Dcflags="$(PKG_CFLAGS)" -Dldflags="$(PKG_LDFLAGS)" \ -Dcurrent_libdir="$(ROOTDIR)/build" $(JVM_TEST_ARGS)) # clean rule clean: @mkdir -p build && cd build && cmake .. && $(MAKE) clean <file_sep>/src/runtime/vulkan/vulkan_common.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file vulkan_common.h * \brief Vulkan common header */ #ifndef TVM_RUNTIME_VULKAN_VULKAN_COMMON_H_ #define TVM_RUNTIME_VULKAN_VULKAN_COMMON_H_ #include <tvm/runtime/c_runtime_api.h> #include <tvm/runtime/packed_func.h> #include <tvm/runtime/device_api.h> #include <dmlc/logging.h> #include <vulkan/vulkan.h> #include <mutex> #include <string> #include <vector> #include <memory> #include "../workspace_pool.h" namespace tvm { namespace runtime { namespace vulkan { inline const char* VKGetErrorString(VkResult error) { switch (error) { case VK_SUCCESS: return "VK_SUCCESS"; case VK_NOT_READY: return "VK_NOT_READY"; case VK_TIMEOUT: return "VK_TIMEOUT"; case VK_EVENT_SET: return "VK_EVENT_SET"; case VK_EVENT_RESET: return "VK_EVENT_RESET"; case VK_INCOMPLETE: return "VK_INCOMPLETE"; case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY"; case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY"; case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED"; case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST"; case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED"; case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT"; case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT"; case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT"; case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER"; case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS"; case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED"; case VK_ERROR_FRAGMENTED_POOL: return "VK_ERROR_FRAGMENTED_POOL"; default: return "Unknown Vulkan error code"; } } /*! * \brief Protected Vulkan call * \param func Expression to call. */ #define VULKAN_CHECK_ERROR(__e) \ { \ CHECK(__e == VK_SUCCESS) \ << "Vulan Error, code=" << __e << ": " << vulkan::VKGetErrorString(__e); \ } #define VULKAN_CALL(func) \ { \ VkResult __e = (func); \ VULKAN_CHECK_ERROR(__e); \ } /*! \brief Auxiliary context structure for vulkan */ struct VulkanContext { // phyiscal device VkPhysicalDevice phy_device{nullptr}; // Phyiscal device property VkPhysicalDeviceProperties phy_device_prop; // Memory type index for staging. uint32_t staging_mtype_index{0}; // whether staging is coherent bool coherent_staging{false}; // Memory type index for compute uint32_t compute_mtype_index{0}; // The logical device VkDevice device{nullptr}; // command queue VkQueue queue{nullptr}; // queue family_index; uint32_t queue_family_index{0}; // Queue family index. VkQueueFamilyProperties queue_prop; }; /*! \brief The buffer object */ struct VulkanBuffer { /*! \brief underlying buffer */ VkBuffer buffer{VK_NULL_HANDLE}; /*! \brief underlying buffer */ VkDeviceMemory memory{VK_NULL_HANDLE}; }; /*! \brief Buffer only used for stagging */ struct VulkanStagingBuffer { /*! \brief the corresponding device */ VkDevice device{nullptr}; /*! \brief underlying buffer */ VkBuffer buffer{VK_NULL_HANDLE}; /*! \brief underlying buffer */ VkDeviceMemory memory{VK_NULL_HANDLE}; /*! \brief host address */ void* host_addr{nullptr}; /*! \brief size of the memory */ size_t size{0}; }; /*! * \brief Process global Vulkan workspace. */ class VulkanWorkspace final : public DeviceAPI { public: // global mutex std::mutex mu; // whether the workspace it initialized. bool initialized_{false}; // vulkan instance VkInstance instance_{nullptr}; // The physical devices, have 1 to 1 mapping to devices std::vector<VulkanContext> context_; // Destructor ~VulkanWorkspace(); // Initialize workspace // Return false if already initialized, otherwise return true. void Init(); // override device API void SetDevice(TVMContext ctx) final; void GetAttr(TVMContext ctx, DeviceAttrKind kind, TVMRetValue* rv) final; void* AllocDataSpace(TVMContext ctx, size_t nbytes, size_t alignment, TVMType type_hint) final; void FreeDataSpace(TVMContext ctx, void* ptr) final; void CopyDataFromTo(const void* from, size_t from_size, void* to, size_t to_size, size_t size, TVMContext ctx_from, TVMContext ctx_to, TVMType type_hint, TVMStreamHandle stream) final; void StreamSync(TVMContext ctx, TVMStreamHandle stream) final; void* AllocWorkspace(TVMContext ctx, size_t size, TVMType type_hint) final; void FreeWorkspace(TVMContext ctx, void* data) final; // get the global workspace static const std::shared_ptr<VulkanWorkspace>& Global(); }; /*! \brief Helper command buffer resource */ struct VulkanCommandBuffer { /*! \brief fence to signal the resource is ready to use */ VkFence fence{VK_NULL_HANDLE}; /*! \brief The internal command buffer */ VkCommandBuffer cmd_buffer{nullptr}; /*! \brief Descriptor set used to bind arguments */ VkDescriptorSet descriptor_set{VK_NULL_HANDLE}; /*! \brief Internal utilities for write command */ VkWriteDescriptorSet write_descriptor_set; VulkanCommandBuffer() { write_descriptor_set.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write_descriptor_set.pNext = nullptr; write_descriptor_set.dstSet = VK_NULL_HANDLE; write_descriptor_set.dstBinding = 0; write_descriptor_set.dstArrayElement = 0; write_descriptor_set.descriptorCount = 1; write_descriptor_set.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write_descriptor_set.pImageInfo = nullptr; write_descriptor_set.pBufferInfo = nullptr; write_descriptor_set.pTexelBufferView = nullptr; } }; /*! * \brief Command pool backed by a fixed size ring buffer. * * Vulkan requires us not to reuse command buffer until * All its corresponding jobs have finished. * * This class to faciliate automatic management * of the command buffers. A fence is created * for each launch of command buffer jobs * and when we try to reuse the same entry * in the ring, we need to make sure that * the previous pending job already finishes. * */ class VulkanCommandPool { public: /*! \brief Maximum number of pending jobs in the pool */ static constexpr const int kMaxPending = 4; /*! \brief Maximum number of pending jobs in the pool */ static constexpr const int kMaxNumArgs = 16; /*! * \brief constructor * \param vctx The corresponding vulkan context. */ explicit VulkanCommandPool(const VulkanContext& vctx); /*! \brief destructor */ ~VulkanCommandPool(); /*! * \brief Allocate a new command buffer entry * * The caller must only submit the entry once * with the given fence in the entry, * before calling next Alloc. * * This function may block to wait for a * previously unfinished command when * there is more than kMaxPending jobs. * * \returns The allocated entry. */ VulkanCommandBuffer* Alloc(); /*! * \brief Allocate a new command buffer entry * \param dlayout the descriptor layout. * * \returns The allocated entry. */ VulkanCommandBuffer* Alloc(const VkDescriptorSetLayout* dlayout); private: /*! \brief Local ring buffer */ std::vector<VulkanCommandBuffer> ring_; /*! \brief clock pointer */ size_t clock_ptr_{0}; /*! \brief the corresponding device*/ VkDevice device_{nullptr}; /*! \brief internal command buffer pool */ VkCommandPool cmd_pool_{VK_NULL_HANDLE}; /*! \brief Descriptor pool */ VkDescriptorPool descriptor_pool_{VK_NULL_HANDLE}; }; /*! \brief Thread local workspace */ class VulkanThreadEntry { public: /*! \brief The current context */ TVMContext context; /*! \brief workspace pool */ WorkspacePool pool; /*! \brief The staging buffers */ std::vector<VulkanStagingBuffer> staging_buffer_; /*! * \brief Get the command pool of corresponding device; * \param device_id The device id * \return The corresponding command buffer. */ VulkanCommandPool* CommandPool(int device_id); /*! * \brief Get the stagging buffer. * \param device_id The device id * \return The corresponding stagging buffer. */ VulkanStagingBuffer* StagingBuffer(int device_id, size_t size); // constructor VulkanThreadEntry() : pool(static_cast<DLDeviceType>(kDLVulkan), VulkanWorkspace::Global()) { context.device_id = 0; context.device_type = static_cast<DLDeviceType>(kDLVulkan); } ~VulkanThreadEntry(); // get the global workspace static VulkanThreadEntry* ThreadLocal(); private: /*! \brief the command pools */ std::vector<std::unique_ptr<VulkanCommandPool> > pool_; }; // inline implementation } // namespace vulkan } // namespace runtime } // namespace tvm #endif // TVM_RUNTIME_VULKAN_VULKAN_COMMON_H_ <file_sep>/topi/python/topi/__init__.py # pylint: disable=redefined-builtin, wildcard-import """TVM Operator Inventory. TOPI is the operator collection library for TVM, to provide sugars for constructing compute declaration as well as optimized schedules. Some of the schedule function may have been specially optimized for a specific workload. """ from __future__ import absolute_import as _abs from tvm._ffi.libinfo import __version__ # Ensure C++ schedules get registered first, so python schedules can # override them. from . import cpp from .math import * from .tensor import * from .generic_op_impl import * from .reduction import * from .transform import * from .broadcast import * from .sort import * from . import nn from . import x86 from . import cuda from . import arm_cpu from . import mali from . import intel_graphics from . import opengl from . import util from . import rocm from . import vision from . import image from . import sparse from . import hls # error reporting from .util import InvalidShapeError # not import testing by default # because testing can have extra deps that are not necessary # we can import them from test cases explicitly # from . import testing <file_sep>/nnvm/python/nnvm/_ctypes/__init__.py """"ctypes implementation of the Symbol""" <file_sep>/src/runtime/vulkan/vulkan_module.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file vulkan_module.cc */ #include <dmlc/memory_io.h> #include <tvm/runtime/registry.h> #include <tvm/runtime/module.h> #include <array> #include <string> #include <mutex> #include "vulkan_common.h" #include "vulkan_module.h" #include "../pack_args.h" #include "../thread_storage_scope.h" #include "../meta_data.h" #include "../file_util.h" namespace tvm { namespace runtime { void VulkanShader::Save(dmlc::Stream* writer) const { writer->Write(flag); writer->Write(data); } bool VulkanShader::Load(dmlc::Stream* reader) { if (!reader->Read(&flag)) return false; if (!reader->Read(&data)) return false; return true; } // Multi-device enabled module. class VulkanModuleNode final :public runtime::ModuleNode { public: // Pipeline cache states struct PipelineEntry { VkShaderModule shader{VK_NULL_HANDLE}; VkPipelineLayout pipeline_layout{VK_NULL_HANDLE}; VkDescriptorSetLayout descriptor_layout{VK_NULL_HANDLE}; VkPipeline pipeline{VK_NULL_HANDLE}; }; // constructor explicit VulkanModuleNode(std::unordered_map<std::string, VulkanShader> smap, std::unordered_map<std::string, FunctionInfo> fmap, std::string source) : smap_(smap), fmap_(fmap), source_(source) { } ~VulkanModuleNode() { // cleanup vulkan related caches. for (DeviceEntry& e : finfo_) { if (e.device == nullptr) continue; for (auto &kv : e.smap) { PipelineEntry& pe = kv.second; vkDestroyShaderModule(e.device, pe.shader, nullptr); vkDestroyDescriptorSetLayout(e.device, pe.descriptor_layout, nullptr); vkDestroyPipelineLayout(e.device, pe.pipeline_layout, nullptr); vkDestroyPipeline(e.device, pe.pipeline, nullptr); } } } const char* type_key() const final { return "vulkan"; } PackedFunc GetFunction( const std::string& name, const std::shared_ptr<ModuleNode>& sptr_to_self) final; void SaveToFile(const std::string& file_name, const std::string& format) final { std::string fmt = GetFileFormat(file_name, format); CHECK_EQ(fmt, fmt_) << "Can only save to customized format vulkan"; std::string meta_file = GetMetaFilePath(file_name); SaveMetaDataToFile(meta_file, fmap_); std::string data_bin; dmlc::MemoryStringStream fs(&data_bin); dmlc::Stream* stream = &fs; uint32_t magic = kVulkanModuleMagic; stream->Write(magic); stream->Write(smap_); SaveBinaryToFile(file_name, data_bin); } void SaveToBinary(dmlc::Stream* stream) final { stream->Write(fmt_); stream->Write(fmap_); stream->Write(smap_); } std::string GetSource(const std::string& format) final { // can only return source code. return source_; } // get a from primary context in device_id PipelineEntry GetPipeline(size_t device_id, const std::string& func_name, size_t num_pack_args) { vulkan::VulkanWorkspace* w = vulkan::VulkanWorkspace::Global().get(); CHECK_LT(device_id, w->context_.size()); // start lock scope. std::lock_guard<std::mutex> lock(mutex_); if (finfo_.size() <= device_id) { finfo_.resize(device_id + 1, DeviceEntry()); } DeviceEntry& e = finfo_[device_id]; auto it = e.smap.find(func_name); if (it != e.smap.end()) return it->second; PipelineEntry pe; if (e.device == nullptr) { e.device = w->context_[device_id].device; } { // create shader auto sit = smap_.find(func_name); CHECK(sit != smap_.end()); const std::vector<uint32_t>& data = sit->second.data; VkShaderModuleCreateInfo shader_cinfo; shader_cinfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; shader_cinfo.pNext = nullptr; shader_cinfo.flags = 0; shader_cinfo.codeSize = data.size() * sizeof(uint32_t); shader_cinfo.pCode = data.data(); VULKAN_CALL(vkCreateShaderModule( e.device, &shader_cinfo, nullptr, &(pe.shader))); } std::vector<VkDescriptorSetLayoutBinding> arg_binding; uint32_t num_pod = 0, num_buffer = 0; { auto fit = fmap_.find(func_name); CHECK(fit != fmap_.end()); for (TVMType arg_type : fit->second.arg_types) { if (arg_type.code == kHandle) { VkDescriptorSetLayoutBinding bd; bd.binding = num_buffer; bd.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; bd.descriptorCount = 1; bd.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; bd.pImmutableSamplers = nullptr; arg_binding.push_back(bd); ++num_buffer; } else { ++num_pod; } } } VkDescriptorSetLayoutCreateInfo descrip_cinfo; descrip_cinfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descrip_cinfo.pNext = nullptr; descrip_cinfo.flags = 0; descrip_cinfo.bindingCount = arg_binding.size(); descrip_cinfo.pBindings = arg_binding.data(); VULKAN_CALL(vkCreateDescriptorSetLayout( e.device, &descrip_cinfo, nullptr, &(pe.descriptor_layout))); VkPushConstantRange crange; crange.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; crange.offset = 0; crange.size = sizeof(ArgUnion) * num_pack_args; VkPipelineLayoutCreateInfo playout_cinfo; playout_cinfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; playout_cinfo.pNext = nullptr; playout_cinfo.flags = 0; playout_cinfo.setLayoutCount = 1; playout_cinfo.pSetLayouts = &(pe.descriptor_layout); if (num_pack_args != 0) { playout_cinfo.pushConstantRangeCount = 1; playout_cinfo.pPushConstantRanges = &crange; CHECK_LE(crange.size, w->context_[device_id].phy_device_prop.limits.maxPushConstantsSize); } else { playout_cinfo.pushConstantRangeCount = 0; playout_cinfo.pPushConstantRanges = nullptr; } VULKAN_CALL(vkCreatePipelineLayout( e.device, &playout_cinfo, nullptr, &(pe.pipeline_layout))); VkComputePipelineCreateInfo pipeline_cinfo; pipeline_cinfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; pipeline_cinfo.pNext = nullptr; pipeline_cinfo.flags = 0; pipeline_cinfo.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; pipeline_cinfo.stage.pNext = nullptr; pipeline_cinfo.stage.flags = 0; pipeline_cinfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; pipeline_cinfo.stage.module = pe.shader; pipeline_cinfo.stage.pName = func_name.c_str(); pipeline_cinfo.stage.pSpecializationInfo = nullptr; pipeline_cinfo.layout = pe.pipeline_layout; pipeline_cinfo.basePipelineHandle = VK_NULL_HANDLE; pipeline_cinfo.basePipelineIndex = 0; VULKAN_CALL(vkCreateComputePipelines( e.device, VK_NULL_HANDLE, 1, &pipeline_cinfo, nullptr, &(pe.pipeline))); e.smap[func_name] = pe; return pe; } private: // device specific entry struct DeviceEntry { VkDevice device{nullptr}; std::unordered_map<std::string, PipelineEntry> smap; }; // the binary data std::vector<uint32_t> data_; // function information table. std::unordered_map<std::string, VulkanShader> smap_; // function information table. std::unordered_map<std::string, FunctionInfo> fmap_; // The format std::string fmt_{"vulkan"}; // The source std::string source_; // device local pipeline information. std::vector<DeviceEntry> finfo_; // internal mutex when updating the module std::mutex mutex_; }; // a wrapped function class to get packed func. class VulkanWrappedFunc { public: // initialize the VULKAN function. void Init(VulkanModuleNode* m, std::shared_ptr<ModuleNode> sptr, const std::string& func_name, size_t num_buffer_args, size_t num_pack_args, const std::vector<std::string>& thread_axis_tags) { w_ = vulkan::VulkanWorkspace::Global().get(); m_ = m; sptr_ = sptr; func_name_ = func_name; num_buffer_args_ = num_buffer_args; num_pack_args_ = num_pack_args; thread_axis_cfg_.Init(num_buffer_args + num_pack_args, thread_axis_tags); } // invoke the function with void arguments void operator()(TVMArgs args, TVMRetValue* rv, const ArgUnion* pack_args) const { vulkan::VulkanThreadEntry* tls = vulkan::VulkanThreadEntry::ThreadLocal(); int device_id = tls->context.device_id; CHECK_LT(device_id, kVulkanMaxNumDevice); const vulkan::VulkanContext& vctx = w_->context_[device_id]; VulkanModuleNode::PipelineEntry& pe = scache_[device_id]; if (pe.pipeline == VK_NULL_HANDLE) { pe = m_->GetPipeline(device_id, func_name_, num_pack_args_); } ThreadWorkLoad wl = thread_axis_cfg_.Extract(args); vulkan::VulkanCommandBuffer* cmd = tls->CommandPool(device_id)->Alloc( &(pe.descriptor_layout)); cmd->write_descriptor_set.dstSet = cmd->descriptor_set; // setup descriptors for (uint32_t i = 0; i < num_buffer_args_; ++i) { void* buf = args[static_cast<int>(i)]; VkDescriptorBufferInfo binfo; binfo.buffer = static_cast<vulkan::VulkanBuffer*>(buf)->buffer; binfo.offset = 0; binfo.range = VK_WHOLE_SIZE; cmd->write_descriptor_set.dstBinding = i; cmd->write_descriptor_set.pBufferInfo = &binfo; vkUpdateDescriptorSets( vctx.device, 1, &(cmd->write_descriptor_set), 0, nullptr); } // dispatch VkCommandBufferBeginInfo cb_begin; cb_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cb_begin.pNext = nullptr; cb_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; cb_begin.pInheritanceInfo = 0; VkSubmitInfo cb_submit; cb_submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; cb_submit.pNext = nullptr; cb_submit.waitSemaphoreCount = 0; cb_submit.pWaitSemaphores = nullptr; cb_submit.pWaitDstStageMask = 0; cb_submit.commandBufferCount = 1; cb_submit.pCommandBuffers = &(cmd->cmd_buffer); cb_submit.signalSemaphoreCount = 0; cb_submit.pSignalSemaphores = nullptr; // 0: begin VULKAN_CALL(vkBeginCommandBuffer(cmd->cmd_buffer, &cb_begin)); // 1: dispatch vkCmdBindPipeline( cmd->cmd_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pe.pipeline); vkCmdBindDescriptorSets( cmd->cmd_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pe.pipeline_layout, 0, 1, &(cmd->descriptor_set), 0, nullptr); // bind push constant if necessary if (num_pack_args_ != 0) { vkCmdPushConstants( cmd->cmd_buffer, pe.pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, num_pack_args_ * sizeof(ArgUnion), pack_args); } vkCmdDispatch( cmd->cmd_buffer, wl.grid_dim(0), wl.grid_dim(1), wl.grid_dim(2)); // 2: barrier(compute->compute|transfer) VkMemoryBarrier barrier_info; barrier_info.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; barrier_info.pNext = nullptr; barrier_info.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT; barrier_info.dstAccessMask = (VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); vkCmdPipelineBarrier( cmd->cmd_buffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &barrier_info, 0, nullptr, 0, nullptr); // 3: end VULKAN_CALL(vkEndCommandBuffer(cmd->cmd_buffer)); // 4: submit with cmd->fence VULKAN_CALL(vkQueueSubmit(vctx.queue, 1, &cb_submit, cmd->fence)); } private: // Reference to global workspace. vulkan::VulkanWorkspace* w_; // internal module VulkanModuleNode* m_; // the resource holder std::shared_ptr<ModuleNode> sptr_; // The name of the function. std::string func_name_; // Number of buffer arguments size_t num_buffer_args_; // number of packed arguments. size_t num_pack_args_; // Device state cache per device. // mark as mutable, to enable lazy initialization mutable std::array<VulkanModuleNode::PipelineEntry, kVulkanMaxNumDevice> scache_; // thread axis configuration ThreadAxisConfig thread_axis_cfg_; }; PackedFunc VulkanModuleNode::GetFunction( const std::string& name, const std::shared_ptr<ModuleNode>& sptr_to_self) { CHECK_EQ(sptr_to_self.get(), this); CHECK_NE(name, symbol::tvm_module_main) << "Device function do not have main"; auto it = fmap_.find(name); if (it == fmap_.end()) return PackedFunc(); const FunctionInfo& info = it->second; VulkanWrappedFunc f; size_t num_buffer_args = NumBufferArgs(info.arg_types); f.Init(this, sptr_to_self, name, num_buffer_args, info.arg_types.size() - num_buffer_args, info.thread_axis_tags); return PackFuncNonBufferArg(f, info.arg_types); } Module VulkanModuleCreate( std::unordered_map<std::string, VulkanShader> smap, std::unordered_map<std::string, FunctionInfo> fmap, std::string source) { vulkan::VulkanWorkspace::Global()->Init(); std::shared_ptr<VulkanModuleNode> n = std::make_shared<VulkanModuleNode>(smap, fmap, source); return Module(n); } // Load module from module. Module VulkanModuleLoadFile(const std::string& file_name, const std::string& format) { std::string data; std::unordered_map<std::string, VulkanShader> smap; std::unordered_map<std::string, FunctionInfo> fmap; std::string fmt = GetFileFormat(file_name, format); std::string meta_file = GetMetaFilePath(file_name); LoadBinaryFromFile(file_name, &data); LoadMetaDataFromFile(meta_file, &fmap); dmlc::MemoryStringStream fs(&data); dmlc::Stream* stream = &fs; uint32_t magic; stream->Read(&magic); CHECK_EQ(magic, kVulkanModuleMagic) << "VulkanModule Magic mismatch"; stream->Read(&smap); return VulkanModuleCreate(smap, fmap, ""); } Module VulkanModuleLoadBinary(void* strm) { dmlc::Stream* stream = static_cast<dmlc::Stream*>(strm); std::unordered_map<std::string, VulkanShader> smap; std::unordered_map<std::string, FunctionInfo> fmap; std::string fmt; stream->Read(&fmt); stream->Read(&fmap); stream->Read(&smap); return VulkanModuleCreate(smap, fmap, ""); } TVM_REGISTER_GLOBAL("module.loadfile_vulkan") .set_body_typed(VulkanModuleLoadFile); TVM_REGISTER_GLOBAL("module.loadbinary_vulkan") .set_body_typed(VulkanModuleLoadBinary); } // namespace runtime } // namespace tvm <file_sep>/apps/android_deploy/app/src/main/jni/Application.mk ifndef config ifneq ("$(wildcard ./config.mk)","") config ?= config.mk else config ?= make/config.mk endif endif include $(config) APP_STL := c++_static APP_CPPFLAGS += -DDMLC_LOG_STACK_TRACE=0 -DTVM4J_ANDROID=1 -std=c++11 -Oz -frtti ifeq ($(USE_OPENCL), 1) APP_CPPFLAGS += -DTVM_OPENCL_RUNTIME=1 endif <file_sep>/src/runtime/vm/object.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2019 by Contributors * \file object.cc * \brief A managed object in the TVM runtime. */ #include <tvm/logging.h> #include <tvm/runtime/object.h> #include <tvm/runtime/registry.h> #include <tvm/runtime/c_runtime_api.h> #include <iostream> #include "../runtime_base.h" namespace tvm { namespace runtime { std::ostream& operator<<(std::ostream& os, const ObjectTag& tag) { switch (tag) { case ObjectTag::kClosure: os << "Closure"; break; case ObjectTag::kDatatype: os << "Datatype"; break; case ObjectTag::kTensor: os << "Tensor"; break; default: LOG(FATAL) << "Invalid object tag: found " << static_cast<int>(tag); } return os; } Object Object::Tensor(const NDArray& data) { ObjectPtr<ObjectCell> ptr = MakeObject<TensorCell>(data); return Object(ptr); } Object Object::Datatype(size_t tag, const std::vector<Object>& fields) { ObjectPtr<ObjectCell> ptr = MakeObject<DatatypeCell>(tag, fields); return Object(ptr); } Object Object::Tuple(const std::vector<Object>& fields) { return Object::Datatype(0, fields); } Object Object::Closure(size_t func_index, const std::vector<Object>& free_vars) { ObjectPtr<ObjectCell> ptr = MakeObject<ClosureCell>(func_index, free_vars); return Object(ptr); } ObjectPtr<TensorCell> Object::AsTensor() const { CHECK(ptr_.get()); CHECK(ptr_.get()->tag == ObjectTag::kTensor); return ptr_.As<TensorCell>(); } ObjectPtr<DatatypeCell> Object::AsDatatype() const { CHECK(ptr_.get()); CHECK(ptr_.get()->tag == ObjectTag::kDatatype); return ptr_.As<DatatypeCell>(); } ObjectPtr<ClosureCell> Object::AsClosure() const { CHECK(ptr_.get()); CHECK(ptr_.get()->tag == ObjectTag::kClosure); return ptr_.As<ClosureCell>(); } NDArray ToNDArray(const Object& obj) { auto tensor = obj.AsTensor(); return tensor->data; } TVM_REGISTER_GLOBAL("_vmobj.GetTensorData") .set_body([](TVMArgs args, TVMRetValue* rv) { Object obj = args[0]; auto cell = obj.AsTensor(); *rv = cell->data; }); TVM_REGISTER_GLOBAL("_vmobj.GetDatatypeTag") .set_body([](TVMArgs args, TVMRetValue* rv) { Object obj = args[0]; auto cell = obj.AsDatatype(); *rv = static_cast<int>(cell->tag); }); TVM_REGISTER_GLOBAL("_vmobj.GetDatatypeNumberOfFields") .set_body([](TVMArgs args, TVMRetValue* rv) { Object obj = args[0]; auto cell = obj.AsDatatype(); *rv = static_cast<int>(cell->fields.size()); }); TVM_REGISTER_GLOBAL("_vmobj.GetDatatypeFields") .set_body([](TVMArgs args, TVMRetValue* rv) { Object obj = args[0]; int idx = args[1]; auto cell = obj.AsDatatype(); CHECK_LT(idx, cell->fields.size()); *rv = cell->fields[idx]; }); TVM_REGISTER_GLOBAL("_vmobj.Tensor") .set_body([](TVMArgs args, TVMRetValue* rv) { *rv = Object::Tensor(args[0]); }); TVM_REGISTER_GLOBAL("_vmobj.Tuple") .set_body([](TVMArgs args, TVMRetValue* rv) { std::vector<Object> fields; for (auto i = 0; i < args.size(); ++i) { fields.push_back(args[i]); } *rv = Object::Tuple(fields); }); TVM_REGISTER_GLOBAL("_vmobj.Datatype") .set_body([](TVMArgs args, TVMRetValue* rv) { int itag = args[0]; size_t tag = static_cast<size_t>(itag); std::vector<Object> fields; for (int i = 1; i < args.size(); i++) { fields.push_back(args[i]); } *rv = Object::Datatype(tag, fields); }); } // namespace runtime } // namespace tvm using namespace tvm::runtime; int TVMGetObjectTag(TVMObjectHandle handle, int* tag) { API_BEGIN(); *tag = static_cast<int>(static_cast<ObjectCell*>(handle)->tag); API_END(); } <file_sep>/include/tvm/node/ir_functor.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file tvm/node/ir_functor.h * \brief Defines the IRFunctor data structures. */ #ifndef TVM_NODE_IR_FUNCTOR_H_ #define TVM_NODE_IR_FUNCTOR_H_ #include <dmlc/logging.h> #include <string> #include <vector> #include <memory> #include <type_traits> #include <utility> #include <functional> #include "node.h" namespace tvm { /*! * \brief A dynamically dispatched functor on NodeRef in the first argument. * * \code * IRFunctor<std::string (const NodeRef& n, std::string prefix)> tostr; * tostr.set_dispatch<Add>([](const Add* op, std::string prefix) { * return prefix + "Add"; * }); * tostr.set_dispatch<IntImm>([](const IntImm* op) { * return prefix + "IntImm" * }); * * Expr x = make_const(1); * Expr y = x + x; * // dispatch to IntImm, outputs "MyIntImm" * LOG(INFO) << tostr(x, "My"); * // dispatch to IntImm, outputs "MyAdd" * LOG(INFO) << tostr(y, "My"); * \endcode * * \tparam FType function signiture * This type if only defined for FType with function signature */ template<typename FType> class IRFunctor; template<typename R, typename ...Args> class IRFunctor<R(const NodeRef& n, Args...)> { private: using Function = std::function<R (const NodeRef&n, Args...)>; using TSelf = IRFunctor<R (const NodeRef& n, Args...)>; /*! \brief internal function table */ std::vector<Function> func_; public: /*! \brief the result type of this functor */ using result_type = R; /*! * \brief Whether the functor can dispatch the corresponding Node * \param n The node to be dispatched * \return Whether dispatching function is registered for n's type. */ inline bool can_dispatch(const NodeRef& n) const { uint32_t type_index = n.type_index(); return type_index < func_.size() && func_[type_index] != nullptr; } /*! * \brief invoke the functor , dispatch on type of n * \param n The Node argument * \param args The additional arguments * \return The result. */ inline R operator()(const NodeRef& n, Args... args) const { uint32_t type_index = n.type_index(); CHECK(type_index < func_.size() && func_[type_index] != nullptr) << "IRFunctor calls un-registered function on type " << Node::TypeIndex2Key(type_index); return func_[type_index](n, std::forward<Args>(args)...); } /*! * \brief set the dispacher for type TNode * \param f The function to be set. * \tparam TNode the type of Node to be dispatched. * \return reference to self. */ template<typename TNode> inline TSelf& set_dispatch(Function f) { // NOLINT(*) uint32_t tindex = Node::TypeKey2Index(TNode::_type_key); if (func_.size() <= tindex) { func_.resize(tindex + 1, nullptr); } CHECK(func_[tindex] == nullptr) << "Dispatch for " << Node::TypeIndex2Key(tindex) << " is already set"; func_[tindex] = f; return *this; } /*! * \brief set the dispacher for type TNode * This allows f to used detailed const Node pointer to replace NodeRef * * \param f The function to be set. * \tparam TNode the type of Node to be dispatched. * \return reference to self. */ template<typename TNode> inline TSelf& set_dispatch(std::function<R(const TNode* n, Args...)> f) { // NOLINT(*) Function fun = [f](const NodeRef& n, Args... args) { return f(static_cast<const TNode*>(n.node_.get()), std::forward<Args>(args)...); }; return this->set_dispatch<TNode>(fun); } /*! * \brief unset the dispacher for type TNode * * \tparam TNode the type of Node to be dispatched. * \return reference to self. */ template<typename TNode> inline TSelf& clear_dispatch() { // NOLINT(*) uint32_t tindex = Node::TypeKey2Index(TNode::_type_key); CHECK_LT(tindex, func_.size()) << "clear_dispatch: index out of range"; func_[tindex] = nullptr; return *this; } }; #if defined(__GNUC__) #define TVM_ATTRIBUTE_UNUSED __attribute__((unused)) #else #define TVM_ATTRIBUTE_UNUSED #endif /*! \brief helper macro to generate string concat */ #define TVM_STR_CONCAT_(__x, __y) __x##__y #define TVM_STR_CONCAT(__x, __y) TVM_STR_CONCAT_(__x, __y) #define TVM_REGISTER_VAR_DEF(ClsName) \ static TVM_ATTRIBUTE_UNUSED auto & __make_functor ## _ ## ClsName /*! * \brief Useful macro to set IRFunctor dispatch in a global static field. * * \code * // Use IRFunctor to implement IRPrinter similar to Visitor Pattern. * // vtable allows easy patch in of new Node types, without changing * // interface of IRPrinter. * * class IRPrinter { * public: * std::ostream& stream; * // the dispatch function. * void print(Expr e) { * const static FType& f = *vtable(); * f(e, this); * } * * using FType = IRFunctor<void (const NodeRef&, IRPrinter *)>; * // function to return global function table * static FType& vtable(); * }; * * // in cpp/cc file * IRPrinter::FType& IRPrinter::vtable() { // NOLINT(*) * static FType inst; return inst; * } * * TVM_STATIC_IR_FUNCTOR(IRPrinter, vtable) * .set_dispatch<Add>([](const Add* n, IRPrinter* p) { * p->print(n->a); * p->stream << '+' * p->print(n->b); * }); * * * \endcode * * \param ClsName The name of the class * \param FField The static function that returns a singleton of IRFunctor. */ #define TVM_STATIC_IR_FUNCTOR(ClsName, FField) \ TVM_STR_CONCAT(TVM_REGISTER_VAR_DEF(ClsName), __COUNTER__) = \ ClsName::FField() /*! * \brief A container for a list of callbacks. All callbacks are invoked when * the object is destructed. */ class IRFunctorCleanList { public: ~IRFunctorCleanList() { for (auto &f : clean_items) { f(); } } void append(std::function<void()> func) { clean_items.push_back(func); } private: std::vector< std::function<void()> > clean_items; }; /*! * \brief A wrapper around IRFunctor that will record calls to set_dispatch * and make a corresponding call to clear_dispatch when the last copy of * the IRFunctorStaticRegistry is destructed. When assigned to a static variable, * this can be used by NNVM and other libraries to unregister callbacks when * the library is unloaded. This prevents crashes when the underlying IRFunctor * is destructed as it will no longer contain std::function instances allocated * by a library that has been unloaded. */ template<typename FType> class IRFunctorStaticRegistry; template<typename R, typename ...Args> class IRFunctorStaticRegistry<R(const NodeRef& n, Args...)> { private: IRFunctor<R(const NodeRef& n, Args...)> *irf_; std::shared_ptr<IRFunctorCleanList> free_list; using TSelf = IRFunctorStaticRegistry<R(const NodeRef& n, Args...)>; public: IRFunctorStaticRegistry(IRFunctor<R(const NodeRef& n, Args...)> *irf) { irf_ = irf; free_list = std::make_shared<IRFunctorCleanList>(); } template<typename TNode> inline TSelf& set_dispatch(std::function<R(const TNode* n, Args...)> f) { // NOLINT(*) irf_->template set_dispatch<TNode>(f); auto irf_copy = irf_; free_list.get()->append([irf_copy] { irf_copy->template clear_dispatch<TNode>(); }); return *this; } }; /*! * \brief Helper function for constructing an IRFunctorStaticRegistry. This allows * the compiler to deduce the template types. */ template<typename R, typename ...Args> IRFunctorStaticRegistry<R(const NodeRef& n, Args...)> MakeIRFunctorStaticRegistry( IRFunctor<R(const NodeRef& n, Args...)> *irf) { return IRFunctorStaticRegistry<R(const NodeRef& n, Args...)>(irf); } #define TVM_AUTO_REGISTER_VAR_DEF(ClsName) \ static TVM_ATTRIBUTE_UNUSED auto __make_functor ## _ ## ClsName /*! * \brief Macro to set IRFunctor dispatch in a global static field using an IRFunctorStaticRegistry. * Usage is exactly the same as TVM_STATIC_IR_FUNCTOR. Libraries should use this instead of * TVM_STATIC_IR_FUNCTOR. */ #define TVM_STATIC_IR_FUNCTOR_REGISTER(ClsName, FField) \ TVM_STR_CONCAT(TVM_AUTO_REGISTER_VAR_DEF(ClsName), __COUNTER__) = \ MakeIRFunctorStaticRegistry(&ClsName::FField()) } // namespace tvm #endif // TVM_NODE_IR_FUNCTOR_H_ <file_sep>/topi/python/topi/cpp.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """FFI for C++ TOPI ops and schedules""" import sys import os import ctypes from imp import new_module as _new_module from tvm._ffi.function import _init_api_prefix from tvm._ffi import libinfo def _get_lib_names(): if sys.platform.startswith('win32'): return ['libtvm_topi.dll', 'tvm_topi.dll'] if sys.platform.startswith('darwin'): return ['libtvm_topi.dylib', 'tvm_topi.dylib'] return ['libtvm_topi.so', 'tvm_topi.so'] def _load_lib(): """Load libary by searching possible path.""" curr_path = os.path.dirname(os.path.realpath(os.path.expanduser(__file__))) lib_search = curr_path lib_path = libinfo.find_lib_path(_get_lib_names(), lib_search, optional=True) if lib_path is None: return None, None lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_GLOBAL) return lib, os.path.basename(lib_path[0]) _LIB, _LIB_NAME = _load_lib() _init_api_prefix("topi.cpp", "topi") def _create_module(name): fullname = __name__ + "." + name mod = _new_module(fullname) sys.modules[fullname] = mod return mod # pylint: disable-msg=C0103 nn = _create_module("nn") _init_api_prefix("topi.cpp.nn", "topi.nn") generic = _create_module("generic") _init_api_prefix("topi.cpp.generic", "topi.generic") cuda = _create_module("cuda") _init_api_prefix("topi.cpp.cuda", "topi.cuda") rocm = _create_module("rocm") _init_api_prefix("topi.cpp.rocm", "topi.rocm") x86 = _create_module("x86") _init_api_prefix("topi.cpp.x86", "topi.x86") vision = _create_module("vision") _init_api_prefix("topi.cpp.vision", "topi.vision") yolo = _create_module("vision.yolo") _init_api_prefix("topi.cpp.vision.yolo", "topi.vision.yolo") image = _create_module("image") _init_api_prefix("topi.cpp.image", "topi.image") <file_sep>/vta/python/vta/testing/__init__.py """Testing utilities, this namespace is not imported by default.""" from . util import run <file_sep>/topi/python/topi/hls/__init__.py # pylint: disable=redefined-builtin, wildcard-import """HLS specific declaration and schedules.""" from __future__ import absolute_import as _abs from .injective import schedule_injective, schedule_elemwise, schedule_broadcast from .nn import * <file_sep>/include/tvm/node/memory.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file tvm/node/memory.h * \brief Node memory management. */ #ifndef TVM_NODE_MEMORY_H_ #define TVM_NODE_MEMORY_H_ #include <utility> #include "node.h" namespace tvm { /*! * \brief Allocate a node object. * \param args arguments to the constructor. * \tparam T the node type. * \return The NodePtr to the allocated object. */ template<typename T, typename... Args> inline NodePtr<T> make_node(Args&&... args); // Detail implementations after this // // The current design allows swapping the // allocator pattern when necessary. // // Possible future allocator optimizations: // - Arena allocator that gives ownership of memory to arena (deleter_= nullptr) // - Thread-local object pools: one pool per size and alignment requirement. // - Can specialize by type of object to give the specific allocator to each object. // template<typename T> class SimpleNodeAllocator { public: template<typename... Args> static T* New(Args&&... args) { return new T(std::forward<Args>(args)...); } static NodeBase::FDeleter Deleter() { return Deleter_; } private: static void Deleter_(NodeBase* ptr) { delete static_cast<T*>(ptr); } }; template<typename T, typename... Args> inline NodePtr<T> make_node(Args&&... args) { using Allocator = SimpleNodeAllocator<T>; static_assert(std::is_base_of<NodeBase, T>::value, "make_node can only be used to create NodeBase"); T* node = Allocator::New(std::forward<Args>(args)...); node->deleter_ = Allocator::Deleter(); return NodePtr<T>(node); } } // namespace tvm #endif // TVM_NODE_MEMORY_H_ <file_sep>/python/tvm/relay/quantize/quantize.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. #pylint: disable=unused-argument """Automatic quantization toolkit.""" from __future__ import absolute_import import numpy as np from . import _quantize from .. import expr as _expr from .. import module as _module from .. import analysis as _analysis from .. import transform as _transform from .. import op as _op from ... import make as _make from ..base import NodeBase, register_relay_node class QAnnotateKind(object): """Denote the kind of annotation field, corresponding to different nbit configure.""" IDENTITY = 0 INPUT = 1 WEIGHT = 2 ACTIVATION = 3 def kind2str(kind): """Convert a `QAnnotateKind` to string""" str_map = { QAnnotateKind.INPUT: "input", QAnnotateKind.WEIGHT: "weight", QAnnotateKind.ACTIVATION: "activation", QAnnotateKind.IDENTITY: "identity" } assert kind in str_map return str_map[kind] def _forward_op(ref_call, args): """forward the operator of ref_call with provided arguments""" return _expr.Call( ref_call.op, args, ref_call.attrs, ref_call.type_args) @register_relay_node("relay.quantize.QConfig") class QConfig(NodeBase): """Configure the quantization behavior by setting config variables. Note ---- This object is backed by node system in C++, with arguments that can be exchanged between python and C++. Do not construct directly, use qconfig instead. The fields that are backed by the C++ node are immutable once an instance is constructed. See _node_defaults for the fields. """ _node_defaults = { "nbit_input": 8, "nbit_weight": 8, "nbit_activation": 32, "dtype_input": "int8", "dtype_weight": "int8", "dtype_activation": "int32", "global_scale": 8.0, "skip_conv_layers": [0], "do_simulation": False, "round_for_shift": True, "debug_enabled_ops": None, } # pylint: disable=no-member def __init__(self, handle): """Initialize the function with handle Parameters ---------- handle : SymbolHandle the handle to the underlying C++ Symbol """ super(QConfig, self).__init__(handle) self.handle = handle def guard(self, ref_call): """Return true if op is enabled, otherwise return false""" op_name = ref_call.op.name if self.debug_enabled_ops is not None: name_list = [x.value for x in self.debug_enabled_ops] if op_name not in name_list: return False return True def get_nbit_by_kind(self, kind): name = kind2str(kind) return getattr(self, 'nbit_' + name) def get_dtype_by_kind(self, kind): name = kind2str(kind) return getattr(self, 'dtype_' + name) def __enter__(self): # pylint: disable=protected-access _quantize._EnterQConfigScope(self) return self def __exit__(self, ptype, value, trace): _quantize._ExitQConfigScope(self) def __setattr__(self, name, value): if name in QConfig._node_defaults: raise AttributeError( "'%s' object cannot set attribute '%s'" % (str(type(self)), name)) return super(QConfig, self).__setattr__(name, value) def current_qconfig(): """Get the current quantization configuration.""" return _quantize._GetCurrentQConfig() def qconfig(**kwargs): """Configure the quantization behavior by setting config variables. Parameters --------- nbit_dict: dict of QAnnotateKind -> int Number of bit for every kind of annotate field. global_scale: float The global scale for calibration. skip_conv_layers: list Specifying which layers to be skipped. Provide a list of indices that indicate which conv2d layers to leave untouched. Start from 0. do_simulation: boolean Whether to do simulation with float operation only. round_for_shift: boolean Whether to add bias for rounding during shift. debug_enabled_ops: None or list of str Partially quantize specified operators for debugging. The default value is None, which means will try to call all operartors' annotate rewrite function. Returns ------- config: QConfig The quantization configuration """ node_args = {k: v if k not in kwargs else kwargs[k] for k, v in QConfig._node_defaults.items()} return _make.node("relay.quantize.QConfig", **node_args) class QuantizeContext(object): """An internal used global context object for annotation, for putting some state variables like `conv2d_counter`.""" Current = None def __init__(self): self.qnode_map = dict() self._conv2d_counter = 0 self._stop_quantize = False def check_to_skip(self, ref_call): """Check the index of conv2d layer to decide whether to skip the current operator.""" if self._stop_quantize: return True if current_qconfig().skip_conv_layers is not None: # check skip conv layers skipped_indices = [int(x) for x in current_qconfig().skip_conv_layers] if self._conv2d_counter in skipped_indices: if ref_call.op.name == 'nn.conv2d': self._conv2d_counter += 1 return True if ref_call.op.name == 'nn.conv2d': self._conv2d_counter += 1 return False def stop_quantize(self): self._stop_quantize = True def reset(self): self._conv2d_counter = 0 self._stop_quantize = False def __enter__(self): self.reset() return self def __exit__(self, ptype, value, traceback): pass def quantize_context(): """Get the global singleton scope""" if QuantizeContext.Current is None: QuantizeContext.Current = QuantizeContext() return QuantizeContext.Current def partition(): """Partition graph into small low-precision sections by `cast_hint` and `stop_fusion`. Returns ------- ret: tvm.relay.Pass The registered pass for VTA rewrite. """ return _quantize.QuantizePartition() def annotate(): """Given a float32 graph, this pass will rewrite the graph and return a graph which simulates the error brought by the current quantization scheme. Returns ------- ret: tvm.relay.Pass The registered pass for quantization annotation. """ return _quantize.QuantizeAnnotate() def collect_stats(graph): """Given an annotated graph, create a profile graph to collect profile data from the calibration dataset. This pass collects simulated_quantize op input into a tuple. Simulated_quantize ops are rewritten to identity mode. The tuple is the output of the profile graph. Parameters ---------- graph: Function The simulation graph after annotation. Returns ------- ret: Function The profile graph which outputs a tuple of profile data. """ return _quantize.CollectStats(graph) def calibrate(graph, mod=None, ctx=None, weight_scales='power2', scales=None): """The calibrate procedure will try to calculate the content of dom_scale, nbit, clip_min, clip_max for every `simulated_quantize` operator. Parameters --------- graph: Function The simulation graph after annotation. mod: tvm.relay.Module The module where calibration happens on. ctx: tvm.relay.PassContext The pass context used for calibration. weight_scales: 'power2' or 'max'. The way to calculate scales for weights (annotated with QAnnotateKind.WEIGHT). power2: Find the maximum of the absolute value of the tensor, and then round up to power of two. max: Find the maximum of the absolute value of the tensor. scales: List[float] Pre-calculated scales for input and activations. Length and the order of elements of the scales list should match the output tuple of the profile graph created by collect_stats. Returns ------- ret: Function The graph after calibration """ def power2_scale(arr): """calculate weight scale with nearest mode-2 scale""" val = np.amax(np.abs(arr.asnumpy())) return 2**np.math.ceil(np.math.log(val, 2)) if val > 0 else 1.0 def max_scale(arr): """calculate weight scale with maximum absolute value""" val = np.amax(np.abs(arr.asnumpy())) return val scale_idx = 0 cfg = current_qconfig() const_params = {} quantize_op = _op.get("relay.op.annotation.simulated_quantize") def visit_func(expr): """Internal visit function""" nonlocal scale_idx if isinstance(expr, _expr.Call) and expr.op == quantize_op: _, ndom_scale, nclip_min, nclip_max = expr.args attrs = expr.attrs kind = attrs.kind nbit = cfg.get_nbit_by_kind(kind) valid_bit = nbit - attrs.sign if kind in [QAnnotateKind.WEIGHT]: if all([isinstance(arg, _expr.Constant) for arg in [ndom_scale, nclip_min, nclip_max]]): return var = expr.args[0] assert isinstance(var, _expr.Constant) if weight_scales == 'max': scale = max_scale(var.data) elif weight_scales == 'power2': scale = power2_scale(var.data) else: raise ValueError('{} not supported'.format(weight_scales)) elif scales is not None: scale = scales[scale_idx] scale_idx += 1 else: scale = cfg.global_scale def _make_const(val): return _expr.const(val, 'float32') valid_range = 2**valid_bit const_params[ndom_scale] = _make_const(scale / valid_range) const_params[nclip_min] = _make_const(- (valid_range - 1)) const_params[nclip_max] = _make_const((valid_range - 1)) _analysis.post_order_visit(graph, visit_func) ret = _expr.bind(graph, const_params) return ret def realize(): """The realize pass will transform the simulated quantized graph, which actually computes with float32, to a real low-bit integer graph. It will replace the `simulated_quantize` with several fine-grained operators like add, multiply, and shift as much as possible for better performance. Returns ------- ret: tvm.relay.Pass The registered pass for quantization realization. """ return _quantize.QuantizeRealize() def _bind_params(func, params): """Bind the params to the expression. """ name_dict = {} for arg in func.params: name = arg.name_hint if name in name_dict: name_dict[name] = None else: name_dict[name] = arg bind_dict = {} for k, v in params.items(): if k not in name_dict: continue arg = name_dict[k] if arg is None: raise ValueError("Multiple args in the function have name %s" % k) bind_dict[arg] = _expr.const(v) return _expr.bind(func, bind_dict) def prerequisite_optimize(graph, params=None): """ Prerequisite optimization passes for quantization. Perform "SimplifyInference", "FoldScaleAxis", "FoldConstant", and "CanonicalizeOps" optimization before quantization. """ optimize = _transform.Sequential([_transform.SimplifyInference(), _transform.FoldConstant(), _transform.FoldScaleAxis(), _transform.CanonicalizeOps(), _transform.FoldConstant()]) if params: graph = _bind_params(graph, params) mod = _module.Module.from_expr(graph) with _transform.PassContext(opt_level=3): mod = optimize(mod) return mod["main"] def quantize(graph, params=None, dataset=None): """ The quantization procedure. Before running the three main procedure of quantization, "annotate", "calibrate" and "realize" , we need to do "SimplifyInference", "FoldScaleAxis", "FoldConstant" first for optimizing. Parameters --------- graph: Function The original graph. params : dict of str to NDArray Input parameters to the graph that do not change during inference time. Used for constant folding. dataset: list of dict of Var -> NDArray The calibration dataset. Returns ------- ret: Function The graph after quantization """ graph = prerequisite_optimize(graph, params) mod = _module.Module.from_expr(graph) calibrate_pass = _transform.function_pass(calibrate, opt_level=1, name="QuantizeCalibrate") quant_passes = [partition(), annotate(), calibrate_pass] if not current_qconfig().do_simulation: quant_passes.append(realize()) quant_passes.append(_transform.FoldConstant()) quantize_seq = _transform.Sequential(quant_passes) with _transform.PassContext(opt_level=3, required_pass=["QuantizeAnnotate", "QuantizeCalibrate", "QuantizeRealize"]): with quantize_context(): mod = quantize_seq(mod) return mod["main"] <file_sep>/nnvm/python/nnvm/top/__init__.py """Tensor operator property registry Provide information to lower and schedule tensor operators. """ from .attr_dict import AttrDict from . import tensor from . import nn from . import transform from . import reduction from . import vision from . import image from .registry import OpPattern from .registry import register_compute, register_schedule, register_pattern <file_sep>/topi/python/topi/arm_cpu/__init__.py """Schedule for ARM CPU""" from . import conv2d from . import depthwise_conv2d from . import conv2d_transpose from . import bitserial_conv2d from . import bitserial_dense from . import injective <file_sep>/tests/python/frontend/caffe2/model_zoo/__init__.py """Store for caffe2 examples and common models.""" from __future__ import absolute_import as _abs import os import sys import importlib from . import squeezenet from caffe2.python.models.download import ModelDownloader models = [ 'squeezenet', 'resnet50', 'vgg19', ] mf = ModelDownloader() class Model: def __init__(self, model_name): self.init_net, self.predict_net, self.value_info = mf.get_c2_model(model_name) for model in models: try: locals()['c2_' + model] = importlib.import_module('caffe2.python.models.' + model) except ImportError: locals()['c2_' + model] = Model(model) # squeezenet def relay_squeezenet(): return squeezenet.get_workload() <file_sep>/vta/python/vta/top/__init__.py """TVM TOPI connector, eventually most of these should go to TVM repo""" from . import bitpack from .graphpack import graph_pack from . import op from . import vta_conv2d from . import vta_conv2d_transpose from . import vta_dense from . import util # NNVM is deprecated for VTA # from . import nnvm_bitpack # from .nnvm_graphpack import nnvm_graph_pack # from . import nnvm_op <file_sep>/tests/python/unittest/test_codegen_vulkan.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm import re def test_vector_comparison(): if not tvm.module.enabled("vulkan"): print("Skipping due to no Vulkan module") return target = 'vulkan' def check_correct_assembly(dtype): n = (1024,) A = tvm.placeholder(n, dtype=dtype, name='A') B = tvm.compute( A.shape, lambda i: tvm.expr.Select( A[i] >= 0, A[i] + tvm.const(1, dtype), tvm.const(0, dtype)), name='B') s = tvm.create_schedule(B.op) (bx, tx) = s[B].split(s[B].op.axis[0], factor=128) (tx, vx) = s[B].split(tx, factor=4) s[B].bind(bx, tvm.thread_axis("blockIdx.x")) s[B].bind(tx, tvm.thread_axis("threadIdx.x")) s[B].vectorize(vx) f = tvm.build(s, [A, B], target) # Verify we generate the boolx4 type declaration and the OpSelect # v4{float,half,int} instruction assembly = f.imported_modules[0].get_source() matches = re.findall("%v4bool = OpTypeVector %bool 4", assembly) assert len(matches) == 1 matches = re.findall("OpSelect %v4.*", assembly) assert len(matches) == 1 check_correct_assembly('float32') check_correct_assembly('int32') check_correct_assembly('float16') if __name__ == "__main__": test_vector_comparison() <file_sep>/nnvm/make/config.mk #------------------------------------------------------------------------------- # Template configuration for compiling nnvm # # If you want to change the configuration, please use the following # steps. Assume you are on the root directory of nnvm. First copy the this # file so that any local changes will be ignored by git # # $ cp make/config.mk . # # Next modify the according entries, and then compile by # # $ make # # or build in parallel with 8 threads # # $ make -j8 #------------------------------------------------------------------------------- #--------------------- # choice of compiler #-------------------- export NVCC = nvcc # choice of archiver export AR = ar # the additional link flags you want to add ADD_LDFLAGS= # the additional compile flags you want to add ADD_CFLAGS= # path to dmlc-core module #DMLC_CORE_PATH= #---------------------------- # plugins #---------------------------- # whether to use fusion integration. This requires installing cuda. # ifndef CUDA_PATH # CUDA_PATH = /usr/local/cuda # endif # NNVM_FUSION_PATH = plugin/nnvm-fusion # NNVM_PLUGINS += $(NNVM_FUSION_PATH)/nnvm-fusion.mk <file_sep>/topi/include/topi/cuda/extern.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file cuda/extern.h * \brief CUDA schedule for extern followed by injective operations */ #ifndef TOPI_CUDA_EXTERN_H_ #define TOPI_CUDA_EXTERN_H_ #include "topi/tags.h" #include "topi/detail/fuse.h" #include "tvm/operation.h" #include "tvm/build_module.h" namespace topi { using namespace tvm; namespace cuda { /*! * \brief Schedule a given operation representing one of the outputs of an * external function which is followed by injective operations. * * \param target The target to generate a schedule for. * \param op The operation representing the output followed by injective operations. * \param sch The schedule to apply this scheduling to * * \return The schedule given by sch */ inline Schedule ScheduleOutputForExtern(Target target, Operation op, Schedule sch) { auto x = op.output(0); auto fused = detail::Fuse(sch[x], sch[x]->op.as<ComputeOpNode>()->axis); auto num_thread = target->max_num_threads; IterVar bx, tx; sch[x].split(fused, num_thread, &bx, &tx); sch[x].bind(bx, tvm::thread_axis(Range(), "blockIdx.x")); sch[x].bind(tx, tvm::thread_axis(Range(), "threadIdx.x")); return sch; } /*! * \brief Schedule an extern op followed by injective operations. * For example, cudnn kernel + bias add + relu * * \param target The target to generate a schedule for. * \param outs The output tensors. * * \return A schedule for the op. */ inline Schedule schedule_extern(const Target& target, Array<Tensor> outs) { Array<Operation> out_ops; for (auto t : outs) { out_ops.push_back(t->op); } auto s = create_schedule(out_ops); tvm::schedule::AutoInlineInjective(s); for (auto out : outs) { if (out->op->derived_from<ExternOpNode>()) { continue; } ScheduleOutputForExtern(target, out->op, s); } return s; } } // namespace cuda } // namespace topi #endif // TOPI_CUDA_EXTERN_H_ <file_sep>/src/pass/simple_passes.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2016 by Contributors * \file simple_passes.cc * \brief Implementation of simple passes */ #include <tvm/ir.h> #include <tvm/ir_visitor.h> #include <tvm/ir_mutator.h> #include <tvm/ir_pass.h> namespace tvm { namespace ir { class IRSideEffect : public IRVisitor { public: void Visit(const NodeRef& e) final { if (has_side_effect_) return; IRVisitor::Visit(e); } void Visit_(const Call* op) final { if (!op->is_pure()) { has_side_effect_ = true; return; } else { IRVisitor::Visit_(op); } } bool has_side_effect_{false}; }; bool HasSideEffect(const Expr& e) { IRSideEffect v; v.Visit(e); return v.has_side_effect_; } class IRSubstitue : public IRMutator { public: explicit IRSubstitue( const std::unordered_map<const Variable*, Expr>& smap) : smap_(smap) { } Expr Mutate_(const Variable* op, const Expr& e) final { auto it = smap_.find(op); if (it != smap_.end()) { return it->second; } else { return e; } } private: const std::unordered_map<const Variable*, Expr>& smap_; }; Stmt Substitute(Stmt stmt, const std::unordered_map<const Variable*, Expr>& value_map) { if (value_map.size() == 0) return stmt; return IRSubstitue(value_map).Mutate(stmt); } Expr Substitute(Expr expr, const std::unordered_map<const Variable*, Expr>& value_map) { if (value_map.size() == 0) return expr; return IRSubstitue(value_map).Mutate(expr); } Stmt Substitute(Stmt stmt, const Map<Var, Expr>& value_map) { std::unordered_map<const Variable*, Expr> vmap; for (const auto& kv : value_map) { vmap[kv.first.get()] = kv.second; } return Substitute(stmt, vmap); } Expr Substitute(Expr expr, const Map<Var, Expr>& value_map) { std::unordered_map<const Variable*, Expr> vmap; for (const auto& kv : value_map) { vmap[kv.first.get()] = kv.second; } return Substitute(expr, vmap); } class VarTouchVisitor : public IRVisitor { public: void Visit(const NodeRef& e) final { if (use_var_) return; IRVisitor::Visit(e); } void Visit_(const Variable* op) final { Handle(op); } void Visit_(const Load* op) final { Handle(op->buffer_var.get()); IRVisitor::Visit_(op); } virtual void Handle(const Variable* var) = 0; bool use_var_{false}; }; class ExprUseVarVisitor : public VarTouchVisitor { public: explicit ExprUseVarVisitor(const Variable* var) : var_(var) {} void Handle(const Variable* var) final { if (var == var_) use_var_ = true; } private: const Variable* var_; }; class ExprUseVSetVisitor : public VarTouchVisitor { public: explicit ExprUseVSetVisitor( const std::unordered_set<const Variable*>& vset) : vset_(vset) {} void Handle(const Variable* var) final { if (vset_.count(var)) use_var_ = true; } private: const std::unordered_set<const Variable*>& vset_; }; bool ExprUseVar(const Expr& e, const Var& v) { ExprUseVarVisitor visitor(v.get()); visitor.Visit(e); return visitor.use_var_; } bool ExprUseVar(const Expr& e, const std::unordered_set<const Variable*>& vset) { ExprUseVSetVisitor visitor(vset); visitor.Visit(e); return visitor.use_var_; } } // namespace ir } // namespace tvm <file_sep>/src/relay/backend/vm/deserializer.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2019 by Contributors * \file src/relay/backend/vm/deserializer.cc * \brief Implementation of APIs to deserialize the serialized VM bytecode. */ #include "deserializer.h" #include <tvm/runtime/registry.h> #include <memory> #include <sstream> #include "serialize_util.h" namespace tvm { namespace relay { namespace vm { #define STREAM_CHECK(val, section) \ CHECK(val) << "Invalid VM file format in the " << section << " section." \ << "\n"; void Deserializer::Init(const std::string& code, const runtime::Module& lib) { code_ = code; vm_ = std::make_shared<VirtualMachine>(); vm_->lib = lib; strm_ = new dmlc::MemoryStringStream(&code_); } runtime::PackedFunc Deserializer::GetFunction( const std::string& name, const std::shared_ptr<ModuleNode>& sptr_to_self) { if (name == "deserialize") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { this->Deserialize(); *rv = runtime::Module(vm_); }); } else { LOG(FATAL) << "Unknown packed function: " << name; return PackedFunc([sptr_to_self, name](TVMArgs args, TVMRetValue* rv) {}); } } void Deserializer::Deserialize() { // Check header. uint64_t header; STREAM_CHECK(strm_->Read(&header), "header"); STREAM_CHECK(header == kTVMVMBytecodeMagic, "header"); // Check version. std::string version; STREAM_CHECK(strm_->Read(&version), "version"); STREAM_CHECK(version == TVM_VERSION, "version"); // Global section. DeserializeGlobalSection(); // Constant section. DeserializeConstantSection(); // Primitive names that will be invoked by `InvokePacked` instructions. DeserializePrimitiveOpNames(); // Code section. DeserializeCodeSection(); } void Deserializer::DeserializeGlobalSection() { std::vector<std::string> globals; STREAM_CHECK(strm_->Read(&globals), "global"); for (size_t i = 0; i < globals.size(); i++) { vm_->global_map.insert({globals[i], i}); } } void Deserializer::DeserializeConstantSection() { uint64_t sz; // Load the number of constants. STREAM_CHECK(strm_->Read(&sz, sizeof(sz)), "constant"); size_t size = static_cast<size_t>(sz); // Load each of the constants. for (size_t i = 0; i < size; i++) { runtime::NDArray constant; STREAM_CHECK(constant.Load(strm_), "constant"); runtime::Object obj = runtime::Object::Tensor(constant); vm_->constants.push_back(obj); } } void Deserializer::DeserializePrimitiveOpNames() { std::vector<std::string> primitive_names; STREAM_CHECK(strm_->Read(&primitive_names), "primitive name"); for (size_t i = 0; i < primitive_names.size(); i++) { vm_->primitive_map.insert({primitive_names[i], i}); } } // Extract the `cnt` number of fields started at `start` from the list // `instr_fields`. inline std::vector<Index> ExtractFields(const std::vector<Index>& instr_fields, Index start, Index cnt) { CHECK_LE(static_cast<size_t>(start + cnt), instr_fields.size()); std::vector<Index> ret; for (auto i = start; i < start + cnt; i++) { ret.push_back(instr_fields[i]); } return ret; } Instruction DeserializeInstruction(const VMInstructionSerializer& instr) { Opcode opcode = static_cast<Opcode>(instr.opcode); switch (opcode) { case Opcode::Move: { // Number of fields = 2 DCHECK_EQ(instr.fields.size(), 2U); return Instruction::Move(instr.fields[0], instr.fields[1]); } case Opcode::Ret: { // Number of fields = 1 DCHECK_EQ(instr.fields.size(), 1U); return Instruction::Ret(instr.fields[0]); } case Opcode::Fatal: { // Number of fields = 0 DCHECK(instr.fields.empty()); return Instruction::Fatal(); } case Opcode::InvokePacked: { // Number of fields = 3 + instr.arity DCHECK_GE(instr.fields.size(), 3U); DCHECK_EQ(instr.fields.size(), 3U + static_cast<size_t>(instr.fields[1])); Index packed_index = instr.fields[0]; Index arity = instr.fields[1]; Index output_size = instr.fields[2]; std::vector<RegName> args = ExtractFields(instr.fields, 3, arity); return Instruction::InvokePacked(packed_index, arity, output_size, args); } case Opcode::AllocTensor: { // Number of fields = 5 + instr.alloc_tensor.ndim DCHECK_GE(instr.fields.size(), 5U); DCHECK_EQ(instr.fields.size(), 5U + static_cast<size_t>(instr.fields[3])); DLDataType dtype; dtype.code = instr.fields[0]; dtype.bits = instr.fields[1]; dtype.lanes = instr.fields[2]; Index ndim = instr.fields[3]; RegName dst = instr.fields[4]; std::vector<Index> shape = ExtractFields(instr.fields, 5, ndim); return Instruction::AllocTensor(shape, dtype, dst); } case Opcode::AllocTensorReg: { // Number of fields = 5 DCHECK_EQ(instr.fields.size(), 5U); Index shape_register = instr.fields[0]; DLDataType dtype; dtype.code = instr.fields[1]; dtype.bits = instr.fields[2]; dtype.lanes = instr.fields[3]; RegName dst = instr.fields[4]; return Instruction::AllocTensorReg(shape_register, dtype, dst); } case Opcode::AllocDatatype: { // Number of fields = 3 + instr.num_fields DCHECK_GE(instr.fields.size(), 3U); DCHECK_EQ(instr.fields.size(), 3U + static_cast<size_t>(instr.fields[1])); Index constructor_tag = instr.fields[0]; Index num_fields = instr.fields[1]; RegName dst = instr.fields[2]; std::vector<Index> fields = ExtractFields(instr.fields, 3, num_fields); return Instruction::AllocDatatype(constructor_tag, num_fields, fields, dst); } case Opcode::AllocClosure: { // Number of fields = 3 + instr.num_freevar DCHECK_GE(instr.fields.size(), 3U); DCHECK_EQ(instr.fields.size(), 3U + static_cast<size_t>(instr.fields[1])); Index clo_index = instr.fields[0]; Index num_freevar = instr.fields[1]; RegName dst = instr.fields[2]; std::vector<Index> free_vars = ExtractFields(instr.fields, 3, num_freevar); return Instruction::AllocClosure(clo_index, num_freevar, free_vars, dst); } case Opcode::If: { // Number of fields = 4 DCHECK_EQ(instr.fields.size(), 4U); Index test = instr.fields[0]; Index target = instr.fields[1]; Index true_offset = instr.fields[2]; Index false_offset = instr.fields[3]; return Instruction::If(test, target, true_offset, false_offset); } case Opcode::Invoke: { // Number of fields = 3 + instr.num_args DCHECK_GE(instr.fields.size(), 3U); DCHECK_EQ(instr.fields.size(), 3U + static_cast<size_t>(instr.fields[1])); Index func_index = instr.fields[0]; Index num_args = instr.fields[1]; RegName dst = instr.fields[2]; std::vector<Index> args = ExtractFields(instr.fields, 3, num_args); return Instruction::Invoke(func_index, args, dst); } case Opcode::InvokeClosure: { // Number of fields = 3 + instr.num_closure_args DCHECK_GE(instr.fields.size(), 3U); DCHECK_EQ(instr.fields.size(), 3U + static_cast<size_t>(instr.fields[1])); Index closure = instr.fields[0]; Index num_closure_args = instr.fields[1]; RegName dst = instr.fields[2]; std::vector<Index> args = ExtractFields(instr.fields, 3, num_closure_args); return Instruction::InvokeClosure(closure, args, dst); } case Opcode::LoadConst: { // Number of fields = 2 DCHECK_EQ(instr.fields.size(), 2U); return Instruction::LoadConst(instr.fields[0], instr.fields[1]); } case Opcode::LoadConsti: { // Number of fields = 2 DCHECK_EQ(instr.fields.size(), 2U); return Instruction::LoadConsti(instr.fields[0], instr.fields[1]); } case Opcode::GetField: { // Number of fields = 3 DCHECK_EQ(instr.fields.size(), 3U); return Instruction::GetField(instr.fields[0], instr.fields[1], instr.fields[2]); } case Opcode::GetTag: { // Number of fields = 2 DCHECK_EQ(instr.fields.size(), 2U); return Instruction::GetTag(instr.fields[0], instr.fields[1]); } case Opcode::Goto: { // Number of fields = 1 DCHECK_EQ(instr.fields.size(), 1U); return Instruction::Goto(instr.fields[0]); } default: LOG(FATAL) << "Invalid opcode" << instr.opcode; return Instruction(); } } void Deserializer::DeserializeCodeSection() { // Load the number of functions. uint64_t sz; STREAM_CHECK(strm_->Read(&sz, sizeof(sz)), "code"); size_t num_funcs = static_cast<size_t>(sz); vm_->functions.resize(num_funcs); for (size_t i = 0; i < num_funcs; i++) { // Load the function info. VMFunctionSerializer loaded_func; STREAM_CHECK(loaded_func.Load(strm_), "code/function"); // Load the instructions. std::vector<Instruction> instructions; for (size_t j = 0; j < loaded_func.num_instructions; j++) { VMInstructionSerializer instr; std::vector<Index> instr_fields; STREAM_CHECK(instr.Load(strm_), "code/instruction"); instructions.push_back(DeserializeInstruction(instr)); } // Create the VM function. VMFunction vm_func = VMFunction(loaded_func.name, loaded_func.params, instructions, loaded_func.register_file_size); auto it = vm_->global_map.find(loaded_func.name); CHECK(it != vm_->global_map.end()); CHECK_LE(it->second, vm_->global_map.size()); vm_->functions[it->second] = vm_func; } } runtime::Module CreateDeserializer(const std::string& code, const runtime::Module lib) { std::shared_ptr<Deserializer> exec = std::make_shared<Deserializer>(); exec->Init(code, lib); return runtime::Module(exec); } TVM_REGISTER_GLOBAL("relay._vm._Deserializer") .set_body_typed(CreateDeserializer); } // namespace vm } // namespace relay } // namespace tvm <file_sep>/include/tvm/c_dsl_api.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file tvm/c_dsl_api.h * * \brief TVM DSL Node C API, used to interact to DSL compilation. * * These are only a few functions needed for DSL construction time. * These function are only available when link libtvm. * If only TVM runtime is linked, calling these function will trigger error. * * \note Most API functions are registerd as PackedFunc and * can be grabbed via TVMFuncGetGlobal */ #ifndef TVM_C_DSL_API_H_ #define TVM_C_DSL_API_H_ #include "runtime/c_runtime_api.h" #ifdef __cplusplus extern "C" { #endif /*! \brief handle to node */ typedef void* NodeHandle; /*! * \brief free the node handle * \param handle The node handle to be freed. * \return 0 when success, -1 when failure happens */ TVM_DLL int TVMNodeFree(NodeHandle handle); /*! * \brief Convert type key to type index. * \param type_key The key of the type. * \param out_index the corresponding type index. * \return 0 when success, -1 when failure happens */ TVM_DLL int TVMNodeTypeKey2Index(const char* type_key, int* out_index); /*! * \brief Get runtime type index of the node. * \param handle the node handle. * \param out_index the corresponding type index. * \return 0 when success, -1 when failure happens */ TVM_DLL int TVMNodeGetTypeIndex(NodeHandle handle, int* out_index); /*! * \brief get attributes given key * \param handle The node handle * \param key The attribute name * \param out_value The attribute value * \param out_type_code The type code of the attribute. * \param out_success Whether get is successful. * \return 0 when success, -1 when failure happens * \note API calls always exchanges with type bits=64, lanes=1 */ TVM_DLL int TVMNodeGetAttr(NodeHandle handle, const char* key, TVMValue* out_value, int* out_type_code, int* out_success); /*! * \brief get attributes names in the node. * \param handle The node handle * \param out_size The number of functions * \param out_array The array of function names. * \return 0 when success, -1 when failure happens */ TVM_DLL int TVMNodeListAttrNames(NodeHandle handle, int *out_size, const char*** out_array); #ifdef __cplusplus } // TVM_EXTERN_C #endif #endif // TVM_C_DSL_API_H_ <file_sep>/topi/python/topi/rocm/__init__.py # pylint: disable=redefined-builtin, wildcard-import """rocm specific declaration and schedules.""" from __future__ import absolute_import as _abs from .conv2d import * from .dense import * from .nn import * <file_sep>/tests/python/frontend/coreml/model_zoo/__init__.py import os from PIL import Image import numpy as np from tvm.contrib.download import download_testdata def get_mobilenet(): url = 'https://docs-assets.developer.apple.com/coreml/models/MobileNet.mlmodel' dst = 'mobilenet.mlmodel' real_dst = download_testdata(url, dst, module='coreml') return os.path.abspath(real_dst) def get_resnet50(): url = 'https://docs-assets.developer.apple.com/coreml/models/Resnet50.mlmodel' dst = 'resnet50.mlmodel' real_dst = download_testdata(url, dst, module='coreml') return os.path.abspath(real_dst) def get_cat_image(): url = 'https://gist.githubusercontent.com/zhreshold/bcda4716699ac97ea44f791c24310193/raw/fa7ef0e9c9a5daea686d6473a62aacd1a5885849/cat.png' dst = 'cat.png' real_dst = download_testdata(url, dst, module='data') img = Image.open(real_dst).resize((224, 224)) # CoreML's standard model image format is BGR img_bgr = np.array(img)[:, :, ::-1] img = np.transpose(img_bgr, (2, 0, 1))[np.newaxis, :] return np.asarray(img)<file_sep>/topi/python/topi/generic/__init__.py # pylint: disable=wildcard-import """Generic declaration and schedules. This is a recommended way of using TOPI API. To use the generic schedule function, user must set the current target scope using with block. See also :any:`tvm.target` Example ------- .. code-block:: python # create schedule that dispatches to topi.cuda.schedule_injective with tvm.target.create("cuda"): s = tvm.generic.schedule_injective(outs) """ from __future__ import absolute_import as _abs from .nn import * from .injective import * from .extern import * from .vision import * from .sort import * <file_sep>/src/relay/backend/vm/serializer.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2019 by Contributors * \file src/relay/backend/vm/serializer.h * \brief Define a serializer for the Relay VM. * * The following components of a Relay VM will be serialized: * - The `constants`, e.g., the constant pool, that contains the * constants used in a Relay program. * - The `packed_funcs` that essentially contains the generated code for * a specific target. We return it as a runtime module that can be exported as * a library file (e.g., .so, .o, or .tar). * - The `global_map` that contains the globals. * - The `primitive_map` that contains the name of individual primitive operators. * - The `functions`, e.g., the `VMFunction`. Each `VMFunction` is composed of * a list of instructions/bytecode. * * Note that only the library is returned as a separate module. All othere parts * are stored in a single serialized code that is organized with the following * sections in order. * - Global section, containing all globals. * - Constant section, storing the constant pool. * - Primitive name section, containing the function name of the primitive ops * used by the virtual machine. * - Code section, handling the VM functions and bytecode. * * The code section is again organized as follows for each VM function: * func_name, register_file_size, num_instructions (N) * param1, param2, ..., paramM * instruction1 * instruction2 * ... * instructionN * * Serializing an `Instruction` requires us to deal with the bytecode. Each line * of the instructions could be serialized as the following format: * hash, opcode, f1, f2, ..., fX, field with variable length * 1. hash: the hash of the instruction. This number will be used to help us * validate if an instruction is well-formed during deserialization. * 2. opcode: the opcode code of the instruction. * 3. f1, f2, ..., fX. These fields together represent the fixed fields in * an instruction, e.g., `from` and `dst` fields of a `Move` instruction. For * example, `DLDataType` will be unpacked into three fields (code, bits, lanes). * 4. The rest of the line indicates the field with variable length, e.g., * the shape of a tensor, the args used by an `InvokPacked` instruction, etc. */ #ifndef TVM_RELAY_BACKEND_VM_SERIALIZER_H_ #define TVM_RELAY_BACKEND_VM_SERIALIZER_H_ #include <dmlc/io.h> #include <dmlc/memory_io.h> #include <tvm/ir.h> #include <tvm/node/container.h> #include <tvm/packed_func_ext.h> #include <tvm/runtime/packed_func.h> #include <tvm/runtime/vm.h> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace tvm { namespace relay { namespace vm { using namespace tvm::runtime; using namespace tvm::runtime::vm; /*! * \brief The Relay VM serializer. */ class Serializer : public runtime::ModuleNode { public: /*! * \brief Initialize the serializer for a virtual machine. * * \param vm The Relay virtual machine. */ inline void Init(const VirtualMachine* vm); /*! * \brief Return the member function to the frontend. * * \param name The name of the function. * \param sptr_to_self The pointer to the module node. * * \return The corresponding member function. */ PackedFunc GetFunction(const std::string& name, const std::shared_ptr<ModuleNode>& sptr_to_self) final; const char* type_key() const final { return "Serializer"; } /*! * \brief Print the detailed statistics of the given code, i.e. number of * globls and constants, etc. */ std::string Stats() const; /*! * \brief Serialize the `vm_` into global section, constant section, and code * section. * * \return The binary representation of the VM. */ TVMByteArray Serialize(); /*! * \brief Get a list of the globals used by the `_vm`. * * \return The global map in the form a list. */ tvm::Array<tvm::Expr> GetGlobals() const; /*! * \brief Get the primitive operators that are contained in the Relay VM. * * \return The list of primitve operators. */ tvm::Array<tvm::Expr> GetPrimitiveOps() const; /*! * \brief Get the serialized form of the `functions` in `vm_`. This is * essentially bytecode serialization. * * \return The serialized vm bytecode. * * \note The bytecode is in the following format: * func_name reg_file_size num_instructions * param1 param2 ... paramM * instruction1 * instruction2 * ... * instructionN * * Each instruction is printed in the following format: * opcode num_fields field1 ... fieldX # The text format. * * The field starting from # is only used for debugging. The serialized code * doesn't contain it, therefore the deserializer doens't need to handle it. */ std::string GetBytecode() const; /*! \brief Get the `lib` module in vm_. Serialization of `runtime::module` * has already been supported by TVM. Therefore, we only return the runtime * module and let users have the flexibility to call `export_library` from * the frontend to save the library to disk. * * \return The runtime module that contains the hardwre dependent code. */ inline runtime::Module GetLib() const; virtual ~Serializer() { delete strm_; } private: /*! \brief Serialize the globals in vm_. */ void SerializeGlobalSection(); /*! \brief Serialize the constant pool in vm_. */ void SerializeConstantSection(); /*! \brief Serialize primitive op names in vm_. */ void SerializePrimitiveOpNames(); /*! \brief Serialize the vm functions in vm_. */ void SerializeCodeSection(); /*! \brief The Relay virtual machine for to be serialized. */ const VirtualMachine* vm_; /*! \brief The stream used for serialization. */ dmlc::Stream* strm_; /*! \brief The serialized code. */ std::string code_; }; } // namespace vm } // namespace relay } // namespace tvm #endif // TVM_RELAY_BACKEND_VM_SERIALIZER_H_ <file_sep>/src/runtime/dsl_api.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file cpu_dsl_api.cc * \brief DSL API dispatcher */ #ifndef TVM_RUNTIME_DSL_API_H_ #define TVM_RUNTIME_DSL_API_H_ #include <tvm/c_dsl_api.h> namespace tvm { namespace runtime { /*! * \brief Common interface for DSL API * Used for runtime registration */ class DSLAPI { public: virtual ~DSLAPI() = default; virtual void NodeFree(NodeHandle handle) const = 0; virtual void NodeTypeKey2Index(const char* type_key, int* out_index) const = 0; virtual void NodeGetTypeIndex(NodeHandle handle, int* out_index) const = 0; virtual void NodeGetAttr(NodeHandle handle, const char* key, TVMValue* out_value, int* out_type_code, int* out_success) const = 0; virtual void NodeListAttrNames(NodeHandle handle, int *out_size, const char*** out_array) const = 0; }; } // namespace runtime } // namespace tvm #endif // TVM_RUNTIME_DSL_API_H_ <file_sep>/nnvm/python/nnvm/testing/__init__.py """Utilities for testing and benchmarks""" from __future__ import absolute_import as _abs from .config import ctx_list from .utils import create_workload from . import mobilenet from . import mobilenet_v2 from . import mlp from . import resnet from . import vgg from . import densenet from . import squeezenet from . import inception_v3 from . import dcgan from . import dqn from . import check_computation <file_sep>/src/node/node.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Implementation of Node API * \file node.cc */ #include <tvm/node/node.h> #include <memory> #include <atomic> #include <mutex> #include <unordered_map> // TODO(tqchen): // Think of re-organize and consolidate with object. namespace tvm { namespace { // single manager of operator information. struct TypeManager { // mutex to avoid registration from multiple threads. // recursive is needed for trigger(which calls UpdateAttrMap) std::mutex mutex; std::atomic<uint32_t> type_counter{0}; std::unordered_map<std::string, uint32_t> key2index; std::vector<std::string> index2key; // get singleton of the static TypeManager* Global() { static TypeManager inst; return &inst; } }; } // namespace TVM_DLL bool Node::_DerivedFrom(uint32_t tid) const { static uint32_t tindex = TypeKey2Index(Node::_type_key); return tid == tindex; } // this is slow, usually caller always hold the result in a static variable. TVM_DLL uint32_t Node::TypeKey2Index(const char* key) { TypeManager *t = TypeManager::Global(); std::lock_guard<std::mutex>(t->mutex); std::string skey = key; auto it = t->key2index.find(skey); if (it != t->key2index.end()) { return it->second; } uint32_t tid = ++(t->type_counter); t->key2index[skey] = tid; t->index2key.push_back(skey); return tid; } TVM_DLL const char* Node::TypeIndex2Key(uint32_t index) { TypeManager *t = TypeManager::Global(); std::lock_guard<std::mutex>(t->mutex); CHECK_NE(index, 0); return t->index2key.at(index - 1).c_str(); } } // namespace tvm <file_sep>/topi/python/topi/image/__init__.py # pylint: disable=wildcard-import """IMAGE network operators""" from __future__ import absolute_import as _abs from .resize import * <file_sep>/src/runtime/vulkan/vulkan_device_api.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file vulkan_device_api.cc */ #include <tvm/runtime/registry.h> #include <dmlc/thread_local.h> #include <cstring> #include "vulkan_common.h" namespace tvm { namespace runtime { namespace vulkan { VulkanWorkspace::~VulkanWorkspace() { for (VulkanContext& ctx : context_) { vkDestroyDevice(ctx.device, nullptr); } if (instance_ != nullptr) { vkDestroyInstance(instance_, nullptr); } } const std::shared_ptr<VulkanWorkspace>& VulkanWorkspace::Global() { static std::shared_ptr<VulkanWorkspace> inst = std::make_shared<VulkanWorkspace>(); return inst; } void VulkanWorkspace::SetDevice(TVMContext ctx) { VulkanThreadEntry::ThreadLocal()->context.device_id = ctx.device_id; } void VulkanWorkspace::GetAttr( TVMContext ctx, DeviceAttrKind kind, TVMRetValue* rv) { this->Init(); size_t index = static_cast<size_t>(ctx.device_id); if (kind == kExist) { *rv = static_cast<int>(index< context_.size()); return; } CHECK_LT(index, context_.size()) << "Invalid device id " << index; switch (kind) { case kMaxThreadsPerBlock: { VkPhysicalDeviceProperties phy_prop; vkGetPhysicalDeviceProperties(context_[ctx.device_id].phy_device, &phy_prop); int64_t value = phy_prop.limits.maxComputeWorkGroupSize[0]; *rv = value; break; } case kMaxSharedMemoryPerBlock: { VkPhysicalDeviceProperties phy_prop; vkGetPhysicalDeviceProperties(context_[ctx.device_id].phy_device, &phy_prop); int64_t value = phy_prop.limits.maxComputeSharedMemorySize; *rv = value; break; } case kWarpSize: { *rv = 1; break; } case kComputeVersion: { VkPhysicalDeviceProperties phy_prop; vkGetPhysicalDeviceProperties(context_[ctx.device_id].phy_device, &phy_prop); int64_t value = phy_prop.apiVersion; std::ostringstream os; os << VK_VERSION_MAJOR(value) << "." << VK_VERSION_MINOR(value) << "." << VK_VERSION_PATCH(value); *rv = os.str(); break; } case kDeviceName: return; case kMaxClockRate: return; case kMultiProcessorCount: return; case kExist: break; case kMaxThreadDimensions: break; } } void* VulkanWorkspace::AllocDataSpace( TVMContext ctx, size_t size, size_t alignment, TVMType type_hint) { this->Init(); VulkanContext& vctx = context_[ctx.device_id]; VkBufferCreateInfo info; info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; info.pNext = nullptr; info.flags = 0; info.size = size; info.queueFamilyIndexCount = 1; info.pQueueFamilyIndices = &(vctx.queue_family_index); info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; // create buffer VkBuffer buffer; VULKAN_CALL(vkCreateBuffer(vctx.device, &info, nullptr, &buffer)); // bind to memory VkMemoryAllocateInfo minfo; minfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; minfo.pNext = nullptr; minfo.allocationSize = size; minfo.memoryTypeIndex = vctx.compute_mtype_index; VkDeviceMemory memory; VULKAN_CALL(vkAllocateMemory(vctx.device, &minfo, nullptr, &memory)); VULKAN_CALL(vkBindBufferMemory(vctx.device, buffer, memory, 0)); VulkanBuffer* pbuf = new VulkanBuffer(); pbuf->memory = memory; pbuf->buffer = buffer; return pbuf; } void VulkanWorkspace::FreeDataSpace(TVMContext ctx, void* ptr) { VulkanContext& vctx = context_[ctx.device_id]; VulkanBuffer* pbuf = static_cast<VulkanBuffer*>(ptr); vkDestroyBuffer(vctx.device, pbuf->buffer, nullptr); vkFreeMemory(vctx.device, pbuf->memory, nullptr); delete pbuf; } void VulkanWorkspace::CopyDataFromTo(const void* from, size_t from_offset, void* to, size_t to_offset, size_t size, TVMContext ctx_from, TVMContext ctx_to, TVMType type_hint, TVMStreamHandle stream) { this->Init(); CHECK(stream == nullptr); TVMContext ctx = ctx_from; if (ctx_from.device_type == kDLCPU) ctx = ctx_to; VulkanThreadEntry* tls = VulkanThreadEntry::ThreadLocal(); VulkanCommandBuffer* cmd = tls->CommandPool(ctx.device_id)->Alloc(); VkCommandBufferBeginInfo cb_begin; cb_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cb_begin.pNext = nullptr; cb_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; cb_begin.pInheritanceInfo = 0; VkSubmitInfo cb_submit; cb_submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; cb_submit.pNext = nullptr; cb_submit.waitSemaphoreCount = 0; cb_submit.pWaitSemaphores = nullptr; cb_submit.pWaitDstStageMask = 0; cb_submit.commandBufferCount = 1; cb_submit.pCommandBuffers = &(cmd->cmd_buffer); cb_submit.signalSemaphoreCount = 0; cb_submit.pSignalSemaphores = nullptr; int from_dev_type = static_cast<int>(ctx_from.device_type); int to_dev_type = static_cast<int>(ctx_to.device_type); if (from_dev_type == kDLVulkan && to_dev_type == kDLVulkan) { CHECK_EQ(ctx_from.device_id, ctx_to.device_id) << "Vulkan disallow cross device copy."; const VulkanContext& vctx = context_[ctx_from.device_id]; const VulkanBuffer* from_buf = static_cast<const VulkanBuffer*>(from); VulkanBuffer* to_buf = static_cast<VulkanBuffer*>(to); // The assumption is that subsequence ops only perform compute/transfer // 0: begin VULKAN_CALL(vkBeginCommandBuffer(cmd->cmd_buffer, &cb_begin)); // 1: copy VkBufferCopy copy_info; copy_info.srcOffset = from_offset; copy_info.dstOffset = to_offset; copy_info.size = size; vkCmdCopyBuffer(cmd->cmd_buffer, from_buf->buffer, to_buf->buffer, 1, &copy_info); // 2: barrier(transfer-> compute|transfer) VkMemoryBarrier barrier_info; barrier_info.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; barrier_info.pNext = nullptr; barrier_info.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier_info.dstAccessMask = (VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT); vkCmdPipelineBarrier( cmd->cmd_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &barrier_info, 0, nullptr, 0, nullptr); // 3: end VULKAN_CALL(vkEndCommandBuffer(cmd->cmd_buffer)); // 4: submit with cmd->fence VULKAN_CALL(vkQueueSubmit(vctx.queue, 1, &cb_submit, cmd->fence)); } else if (from_dev_type == kDLVulkan && to_dev_type == kDLCPU) { const VulkanContext& vctx = context_[ctx_from.device_id]; const VulkanBuffer* from_buf = static_cast<const VulkanBuffer*>(from); VulkanStagingBuffer* temp = tls->StagingBuffer(ctx_from.device_id, size); // 0: begin VULKAN_CALL(vkBeginCommandBuffer(cmd->cmd_buffer, &cb_begin)); // 1: copy VkBufferCopy copy_info; copy_info.srcOffset = from_offset; copy_info.dstOffset = 0; copy_info.size = size; vkCmdCopyBuffer(cmd->cmd_buffer, from_buf->buffer, temp->buffer, 1, &copy_info); // 2: end VULKAN_CALL(vkEndCommandBuffer(cmd->cmd_buffer)); // 4: submit with cmd->fence VULKAN_CALL(vkQueueSubmit(vctx.queue, 1, &cb_submit, cmd->fence)); // Block until done, to make sure temp can be reused later. VULKAN_CALL(vkQueueWaitIdle(vctx.queue)); // host side invalidation if access is not coherent. // so writes from GPU is visible to CPU if (!vctx.coherent_staging) { VkMappedMemoryRange mrange; mrange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; mrange.pNext = nullptr; mrange.memory = temp->memory; mrange.offset = 0; mrange.size = size; VULKAN_CALL(vkInvalidateMappedMemoryRanges( vctx.device, 1, &mrange)); } memcpy(static_cast<char*>(to) + to_offset, static_cast<char*>(temp->host_addr), size); } else if (from_dev_type == kDLCPU && to_dev_type == kDLVulkan) { const VulkanContext& vctx = context_[ctx_to.device_id]; const VulkanBuffer* to_buf = static_cast<const VulkanBuffer*>(to); VulkanStagingBuffer* temp = tls->StagingBuffer(ctx_to.device_id, size); memcpy(temp->host_addr, static_cast<const char*>(from) + from_offset, size); // host side flush if access is not coherent. // so writes from CPU is visible to GPU if (!vctx.coherent_staging) { VkMappedMemoryRange mrange; mrange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; mrange.pNext = nullptr; mrange.memory = temp->memory; mrange.offset = 0; mrange.size = size; VULKAN_CALL(vkFlushMappedMemoryRanges(vctx.device, 1, &mrange)); } VULKAN_CALL(vkBeginCommandBuffer(cmd->cmd_buffer, &cb_begin)); // 0: barrier(host->transfer) VkMemoryBarrier barrier_info; barrier_info.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; barrier_info.pNext = nullptr; barrier_info.srcAccessMask = 0; barrier_info.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; vkCmdPipelineBarrier(cmd->cmd_buffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &barrier_info, 0, nullptr, 0, nullptr); // 1: copy VkBufferCopy copy_info; copy_info.srcOffset = 0; copy_info.dstOffset = to_offset; copy_info.size = size; vkCmdCopyBuffer(cmd->cmd_buffer, temp->buffer, to_buf->buffer, 1, &copy_info); // 2: end VULKAN_CALL(vkEndCommandBuffer(cmd->cmd_buffer)); // 4: submit with cmd->fence VULKAN_CALL(vkQueueSubmit(vctx.queue, 1, &cb_submit, cmd->fence)); // wait until copy finishes, so we can reuse temp next time. VULKAN_CALL(vkQueueWaitIdle(vctx.queue)); } else { LOG(FATAL) << "Expect copy from/to Metal or between Metal" << ", from=" << from_dev_type << ", to=" << to_dev_type; } } void VulkanWorkspace::StreamSync(TVMContext ctx, TVMStreamHandle stream) { CHECK(stream == nullptr); VulkanContext& vctx = context_[ctx.device_id]; VULKAN_CALL(vkQueueWaitIdle(vctx.queue)); } void* VulkanWorkspace::AllocWorkspace(TVMContext ctx, size_t size, TVMType type_hint) { return VulkanThreadEntry::ThreadLocal()->pool.AllocWorkspace(ctx, size); } void VulkanWorkspace::FreeWorkspace(TVMContext ctx, void* data) { VulkanThreadEntry::ThreadLocal()->pool.FreeWorkspace(ctx, data); } // VulkanCommandPool VulkanCommandPool::VulkanCommandPool(const VulkanContext& vctx) { ring_.resize(kMaxPending, VulkanCommandBuffer()); device_ = vctx.device; { // create command pool VkCommandPoolCreateInfo cmd_pool_cinfo; cmd_pool_cinfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; cmd_pool_cinfo.pNext = nullptr; cmd_pool_cinfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; cmd_pool_cinfo.queueFamilyIndex = vctx.queue_family_index; VULKAN_CALL(vkCreateCommandPool(device_, &cmd_pool_cinfo, nullptr, &cmd_pool_)); } { // create descriptor pool VkDescriptorPoolSize pool_size; pool_size.type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; pool_size.descriptorCount = kMaxPending * kMaxNumArgs; VkDescriptorPoolCreateInfo descrip_pool_cinfo; descrip_pool_cinfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; descrip_pool_cinfo.pNext = nullptr; descrip_pool_cinfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; descrip_pool_cinfo.maxSets = kMaxPending + 2; descrip_pool_cinfo.poolSizeCount = 1; descrip_pool_cinfo.pPoolSizes = &pool_size; VULKAN_CALL(vkCreateDescriptorPool( device_, &descrip_pool_cinfo, nullptr, &descriptor_pool_)); } VkCommandBufferAllocateInfo buffer_alloc_info; buffer_alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; buffer_alloc_info.pNext = nullptr; buffer_alloc_info.commandPool = cmd_pool_; buffer_alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; buffer_alloc_info.commandBufferCount = 1; VkFenceCreateInfo fence_cinfo; fence_cinfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fence_cinfo.pNext = nullptr; fence_cinfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < ring_.size(); ++i) { VULKAN_CALL(vkAllocateCommandBuffers( device_, &buffer_alloc_info, &(ring_[i].cmd_buffer))); VULKAN_CALL(vkCreateFence( device_, &fence_cinfo, nullptr, &(ring_[i].fence))); } } VulkanCommandPool::~VulkanCommandPool() { // wait device to be idle so we know we can recycle buffers VULKAN_CALL(vkDeviceWaitIdle(device_)); // start recycling. for (size_t i = 0; i < ring_.size(); ++i) { if (ring_[i].cmd_buffer != nullptr) { vkFreeCommandBuffers(device_, cmd_pool_, 1, &(ring_[i].cmd_buffer)); ring_[i].cmd_buffer = nullptr; } if (ring_[i].fence != VK_NULL_HANDLE) { vkDestroyFence(device_, ring_[i].fence, nullptr); } } // delete cmd_pool and descriptor pool vkDestroyCommandPool(device_, cmd_pool_, nullptr); vkDestroyDescriptorPool(device_, descriptor_pool_, nullptr); } VulkanCommandBuffer* VulkanCommandPool::Alloc() { return Alloc(nullptr); } VulkanCommandBuffer* VulkanCommandPool::Alloc( const VkDescriptorSetLayout* dlayout) { // always allocate resource in round robin manner VulkanCommandBuffer* e = &(ring_[clock_ptr_]); clock_ptr_ = (clock_ptr_ + 1) % ring_.size(); // Wait until previous usage of commad buffer is finished. uint64_t timeout = 1UL << 30UL; VkResult res; res = vkWaitForFences(device_, 1, &(e->fence), 0, timeout); while (res == VK_TIMEOUT) { res = vkWaitForFences(device_, 1, &(e->fence), 0, timeout); } VULKAN_CHECK_ERROR(res); vkResetFences(device_, 1, (&e->fence)); if (e->descriptor_set != VK_NULL_HANDLE) { VULKAN_CALL(vkFreeDescriptorSets( device_, descriptor_pool_, 1, &(e->descriptor_set))); e->descriptor_set = VK_NULL_HANDLE; } if (dlayout != nullptr) { VkDescriptorSetAllocateInfo alloc_info; alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; alloc_info.pNext = nullptr; alloc_info.descriptorPool = descriptor_pool_; alloc_info.descriptorSetCount = 1; alloc_info.pSetLayouts = dlayout; VULKAN_CALL(vkAllocateDescriptorSets( device_, &alloc_info, &(e->descriptor_set))); } return e; } // VulkanThreadEntry typedef dmlc::ThreadLocalStore<VulkanThreadEntry> VulkanThreadStore; VulkanThreadEntry* VulkanThreadEntry::ThreadLocal() { return VulkanThreadStore::Get(); } VulkanCommandPool* VulkanThreadEntry::CommandPool(int device_id) { while (pool_.size() <= static_cast<size_t>(device_id)) { pool_.emplace_back(std::unique_ptr<VulkanCommandPool>()); } if (pool_[device_id] == nullptr) { const VulkanContext& vctx = VulkanWorkspace::Global()->context_[device_id]; pool_[device_id].reset(new VulkanCommandPool(vctx)); } return pool_[device_id].get(); } VulkanStagingBuffer* VulkanThreadEntry::StagingBuffer(int device_id, size_t size) { if (staging_buffer_.size() <= static_cast<size_t>(device_id)) { staging_buffer_.resize(device_id + 1, VulkanStagingBuffer()); } VulkanStagingBuffer& buf = staging_buffer_[device_id]; if (buf.device != nullptr && buf.size < size) { // free previous buffer if (buf.host_addr != nullptr) { vkUnmapMemory(buf.device, buf.memory); } if (buf.memory != VK_NULL_HANDLE) { vkFreeMemory(buf.device, buf.memory, nullptr); } if (buf.buffer != VK_NULL_HANDLE) { vkDestroyBuffer(buf.device, buf.buffer, nullptr); } buf.host_addr = nullptr; buf.memory = VK_NULL_HANDLE; buf.buffer = VK_NULL_HANDLE; } const VulkanContext& vctx = VulkanWorkspace::Global()->context_[device_id]; if (buf.device == nullptr) { buf.device = vctx.device; } if (buf.memory == VK_NULL_HANDLE) { // allocate the stagging buffer memory if necessary VkBufferCreateInfo info; info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; info.pNext = nullptr; info.flags = 0; info.size = size; info.queueFamilyIndexCount = 1; info.pQueueFamilyIndices = &(vctx.queue_family_index); info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VULKAN_CALL(vkCreateBuffer(vctx.device, &info, nullptr, &(buf.buffer))); VkMemoryAllocateInfo minfo; minfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; minfo.pNext = nullptr; minfo.allocationSize = size; minfo.memoryTypeIndex = vctx.staging_mtype_index; VULKAN_CALL(vkAllocateMemory(vctx.device, &minfo, nullptr, &(buf.memory))); VULKAN_CALL(vkBindBufferMemory(vctx.device, (buf.buffer), buf.memory, 0)); VULKAN_CALL(vkMapMemory(vctx.device, buf.memory, 0, size, 0, &(buf.host_addr))); buf.size = size; } memset(buf.host_addr, 0, size); return &buf; } VulkanThreadEntry::~VulkanThreadEntry() { // Because the thread entry refers to Device API // The command buffer always will be destroyed before // the instance and device get destroyed. // The destruction need to be manually called // to ensure the destruction order. pool_.clear(); for (VulkanStagingBuffer buf : staging_buffer_) { if (buf.host_addr != nullptr) { vkUnmapMemory(buf.device, buf.memory); } if (buf.memory != VK_NULL_HANDLE) { vkFreeMemory(buf.device, buf.memory, nullptr); } if (buf.buffer != VK_NULL_HANDLE) { vkDestroyBuffer(buf.device, buf.buffer, nullptr); } } } VkInstance CreateInstance() { VkApplicationInfo app_info; app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; app_info.pNext = nullptr; app_info.pApplicationName = "TVM"; app_info.applicationVersion = 0; app_info.pEngineName = ""; app_info.engineVersion = 0; app_info.apiVersion = VK_MAKE_VERSION(1, 0, 65); VkInstanceCreateInfo inst_info; inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; inst_info.pNext = nullptr; inst_info.flags = 0; inst_info.pApplicationInfo = &app_info; inst_info.enabledLayerCount = 0; inst_info.ppEnabledLayerNames = nullptr; inst_info.enabledExtensionCount = 0; inst_info.ppEnabledExtensionNames = nullptr; VkInstance inst; VULKAN_CALL(vkCreateInstance(&inst_info, nullptr, &inst)); return inst; } // find suitable mem_type_index for staging and compute void FindMemoryTypeIndex(VulkanContext* vctx) { // Find suitable compute index. VkBuffer buffer; VkMemoryRequirements req_staging, req_compute; VkBufferCreateInfo info; info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; info.pNext = nullptr; info.flags = 0; info.size = 1024; info.queueFamilyIndexCount = 1; info.pQueueFamilyIndices = &(vctx->queue_family_index); // get staging requirement info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VULKAN_CALL(vkCreateBuffer(vctx->device, &info, nullptr, &buffer)); vkGetBufferMemoryRequirements(vctx->device, buffer, &req_staging); vkDestroyBuffer(vctx->device, buffer, nullptr); // get compute requirement info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; VULKAN_CALL(vkCreateBuffer(vctx->device, &info, nullptr, &buffer)); vkGetBufferMemoryRequirements(vctx->device, buffer, &req_compute); vkDestroyBuffer(vctx->device, buffer, nullptr); // Query phyiscal device property // find a memory that is host visible, no need to be consistent int win_rank = -1; VkPhysicalDeviceMemoryProperties prop; vkGetPhysicalDeviceMemoryProperties(vctx->phy_device, &prop); for (uint32_t k = 0; k < prop.memoryTypeCount; ++k) { VkMemoryType ty = prop.memoryTypes[k]; size_t heap_size = prop.memoryHeaps[ty.heapIndex].size; // host visible if (!(ty.propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) continue; // match copy requirment if (!(req_staging.memoryTypeBits & (1 << k))) continue; if (heap_size < 1024) continue; int rank = 0; rank += ty.propertyFlags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT; if (rank > win_rank) { win_rank = rank; vctx->staging_mtype_index = k; vctx->coherent_staging = ty.propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; } } CHECK_GE(win_rank, 0) << "Cannot find suitable staging memory on device."; win_rank = -1; for (uint32_t k = 0; k < prop.memoryTypeCount; ++k) { VkMemoryType ty = prop.memoryTypes[k]; size_t heap_size = prop.memoryHeaps[ty.heapIndex].size; // host visible if (!(ty.propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) continue; // match copy requirment if (!(req_staging.memoryTypeBits & (1 << k))) continue; if (heap_size < 1024) continue; int rank = 0; // prefer not host visible rank += !(ty.propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); if (rank > win_rank) { win_rank = rank; vctx->compute_mtype_index = k; } } CHECK_GE(win_rank, 0) << "Cannot find suitable staging memory on device."; } // Get all logic devices that support compute std::vector<VulkanContext> GetContext(VkInstance instance) { std::vector<VulkanContext> result; uint32_t phy_dev_count = 0; VULKAN_CALL(vkEnumeratePhysicalDevices( instance, &phy_dev_count, nullptr)); std::vector<VkPhysicalDevice> all_phy_devs(phy_dev_count); VULKAN_CALL(vkEnumeratePhysicalDevices( instance, &phy_dev_count, dmlc::BeginPtr(all_phy_devs))); for (VkPhysicalDevice phy_dev : all_phy_devs) { uint32_t queue_prop_count = 0; vkGetPhysicalDeviceQueueFamilyProperties( phy_dev, &queue_prop_count, nullptr); std::vector<VkQueueFamilyProperties> queue_props(queue_prop_count); vkGetPhysicalDeviceQueueFamilyProperties( phy_dev, &queue_prop_count, dmlc::BeginPtr(queue_props)); uint32_t queue_family_index = 0; std::vector<VkDeviceQueueCreateInfo> queue_create_info; for (uint32_t i = 0; i < queue_props.size(); i++) { // find queues that support compute if (VK_QUEUE_COMPUTE_BIT & queue_props[i].queueFlags) { float priority = 1.0f; VkDeviceQueueCreateInfo info; info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; info.pNext = nullptr; info.flags = 0; info.queueFamilyIndex = i; info.queueCount = 1; info.pQueuePriorities = &priority; queue_create_info.push_back(info); // only use the first available queue for now if (queue_create_info.size() == 0) { queue_family_index = i; } } } if (queue_create_info.size() == 0) continue; VkDeviceCreateInfo device_create_info; device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; device_create_info.pNext = nullptr; device_create_info.flags = 0; device_create_info.queueCreateInfoCount = static_cast<uint32_t>(queue_create_info.size()); device_create_info.pQueueCreateInfos = queue_create_info.data(); device_create_info.enabledLayerCount = 0; device_create_info.ppEnabledLayerNames = nullptr; device_create_info.enabledExtensionCount = 0; device_create_info.ppEnabledExtensionNames = nullptr; device_create_info.pEnabledFeatures = nullptr; VulkanContext ctx; // setup context ctx.phy_device = phy_dev; vkGetPhysicalDeviceProperties(ctx.phy_device, &(ctx.phy_device_prop)); VULKAN_CALL(vkCreateDevice( phy_dev, &device_create_info, nullptr, &(ctx.device))); vkGetDeviceQueue(ctx.device, queue_family_index, 0, &(ctx.queue)); ctx.queue_family_index = queue_family_index; FindMemoryTypeIndex(&ctx); // Find suitable memory type for staging and compute result.push_back(ctx); } return result; } void VulkanWorkspace::Init() { if (initialized_) return; std::lock_guard<std::mutex> lock(this->mu); if (initialized_) return; initialized_ = true; try { instance_ = CreateInstance(); context_ = GetContext(instance_); LOG(INFO) << "Initialize Vulkan with " << context_.size() << " devices.."; for (size_t i = 0; i < context_.size(); ++i) { LOG(INFO) << "vulkan(" << i << ")=\'" << context_[i].phy_device_prop.deviceName << "\' phy_dev_id=" << context_[i].phy_device; } } catch (const dmlc::Error& err) { LOG(INFO) << "Cannot initialize vulkan: " << err.what() << "\n" << "You can still compile vulkan module but cannot run locally"; } } bool InitVulkan(TVMArgs args, TVMRetValue* rv) { vulkan::VulkanWorkspace::Global()->Init(); return true; } TVM_REGISTER_GLOBAL("device_api.vulkan") .set_body([](TVMArgs args, TVMRetValue* rv) { DeviceAPI* ptr = VulkanWorkspace::Global().get(); *rv = static_cast<void*>(ptr); }); } // namespace vulkan } // namespace runtime } // namespace tvm <file_sep>/tests/python/unittest/test_arith_stmt_simplify.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm def test_stmt_simplify(): ib = tvm.ir_builder.create() A = ib.pointer("float32", name="A") C = ib.pointer("float32", name="C") n = tvm.var("n") with ib.for_range(0, n, name="i") as i: with ib.if_scope(i < 12): A[i] = C[i] body = tvm.stmt.LetStmt(n, 10, ib.get()) body = tvm.ir_pass.CanonicalSimplify(body) assert isinstance(body.body, tvm.stmt.Store) if __name__ == "__main__": test_stmt_simplify() <file_sep>/include/tvm/runtime/object.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2019 by Contributors * \file tvm/runtime/object.h * \brief A managed object in the TVM runtime. */ #ifndef TVM_RUNTIME_OBJECT_H_ #define TVM_RUNTIME_OBJECT_H_ #include <tvm/runtime/ndarray.h> #include <memory> #include <utility> #include <vector> namespace tvm { namespace runtime { template <typename T> class ObjectPtr; class Object; enum struct ObjectTag { /*! \brief The tag of a tensor. */ kTensor = 0U, /*! \brief The tag of a closure. */ kClosure = 1U, /*! \brief The tag of a structure. */ kDatatype = 2U, }; std::ostream& operator<<(std::ostream& os, const ObjectTag&); struct ObjectCell { public: /*! * \brief The type of object deleter. * \param The self pointer to the ObjectCell. */ typedef void (*FDeleter)(ObjectCell* self); /*! \brief The tag of the object. * * Describes which type of value * is represented by this object. */ ObjectTag tag; /*! * \brief Increment the reference count. */ void IncRef() { ref_counter_.fetch_add(1, std::memory_order_relaxed); } /*! * \brief Decrement the reference count. */ void DecRef() { if (ref_counter_.fetch_sub(1, std::memory_order_release) == 1) { std::atomic_thread_fence(std::memory_order_acquire); if (this->deleter_ != nullptr) { (*this->deleter_)(this); } } } protected: // default constructor and copy constructor ObjectCell() {} explicit ObjectCell(ObjectTag tag) : tag(tag) {} // override the copy and assign constructors to do nothing. // This is to make sure only contents, but not deleter and ref_counter // are copied when a child class copies itself. ObjectCell(const ObjectCell& other) { // NOLINT(*) } ObjectCell(ObjectCell&& other) { // NOLINT(*) } ObjectCell& operator=(const ObjectCell& other) { // NOLINT(*) return *this; } ObjectCell& operator=(ObjectCell&& other) { // NOLINT(*) return *this; } private: /*! \brief Internal reference counter */ std::atomic<int> ref_counter_{0}; /*! * \brief deleter of this object to enable customized allocation. * If the deleter is nullptr, no deletion will be performed. * The creator of the Node must always set the deleter field properly. */ FDeleter deleter_ = nullptr; int use_count() const { return ref_counter_.load(std::memory_order_relaxed); } // friend declaration template <typename> friend class ObjectPtr; template <typename Y, typename... Args> friend ObjectPtr<Y> MakeObject(Args&&...); }; /*! * \brief A custom smart pointer for Object. * must be subclass of NodeBase * \tparam T the content data type. */ template <typename T> class ObjectPtr { public: /*! \brief default constructor */ ObjectPtr() {} /*! \brief default constructor */ ObjectPtr(std::nullptr_t) {} // NOLINT(*) /*! * \brief copy constructor * \param other The value to be moved */ ObjectPtr(const ObjectPtr<T>& other) // NOLINT(*) : ObjectPtr(other.data_) {} /*! * \brief copy constructor * \param other The value to be moved */ template <typename U> ObjectPtr(const ObjectPtr<U>& other) // NOLINT(*) : ObjectPtr(other.data_) { static_assert(std::is_base_of<T, U>::value, "can only assign of child class ObjectPtr to parent"); } /*! * \brief move constructor * \param other The value to be moved */ ObjectPtr(ObjectPtr<T>&& other) // NOLINT(*) : data_(other.data_) { other.data_ = nullptr; } /*! * \brief move constructor * \param other The value to be moved */ template <typename Y> ObjectPtr(ObjectPtr<Y>&& other) // NOLINT(*) : data_(other.data_) { static_assert(std::is_base_of<T, Y>::value, "can only assign of child class ObjectPtr to parent"); other.data_ = nullptr; } /*! \brief destructor */ ~ObjectPtr() { this->reset(); } /*! * \brief Swap this array with another Object * \param other The other Object */ void swap(ObjectPtr<T>& other) { // NOLINT(*) std::swap(data_, other.data_); } /*! * \return Get the content of the pointer */ T* get() const { return static_cast<T*>(data_); } /*! * \return The pointer */ T* operator->() const { return get(); } /*! * \return The reference */ T& operator*() const { // NOLINT(*) return *get(); } /*! * \brief copy assignmemt * \param other The value to be assigned. * \return reference to self. */ ObjectPtr<T>& operator=(const ObjectPtr<T>& other) { // NOLINT(*) // takes in plane operator to enable copy elison. // copy-and-swap idiom ObjectPtr(other).swap(*this); // NOLINT(*) return *this; } /*! * \brief move assignmemt * \param other The value to be assigned. * \return reference to self. */ ObjectPtr<T>& operator=(ObjectPtr<T>&& other) { // NOLINT(*) // copy-and-swap idiom ObjectPtr(std::move(other)).swap(*this); // NOLINT(*) return *this; } /*! \brief reset the content of ptr to be nullptr */ void reset() { if (data_ != nullptr) { data_->DecRef(); data_ = nullptr; } } /*! \return The use count of the ptr, for debug purposes */ int use_count() const { return data_ != nullptr ? data_->use_count() : 0; } /*! \return whether the reference is unique */ bool unique() const { return data_ != nullptr && data_->use_count() == 1; } /*! \return Whether two ObjectPtr do not equal each other */ bool operator==(const ObjectPtr<T>& other) const { return data_ == other.data_; } /*! \return Whether two ObjectPtr equals each other */ bool operator!=(const ObjectPtr<T>& other) const { return data_ != other.data_; } /*! \return Whether the pointer is nullptr */ bool operator==(std::nullptr_t null) const { return data_ == nullptr; } /*! \return Whether the pointer is not nullptr */ bool operator!=(std::nullptr_t null) const { return data_ != nullptr; } /* ObjectPtr's support custom allocators. * * The below allocator represents the simplest * possible impl. It can be easily swapped * for customized executor's, different allocation * strategies, and so on. * * See memory.h for more discussion on NodePtr's * allocator. */ class StdAllocator { public: template <typename... Args> static T* New(Args&&... args) { return new T(std::forward<Args>(args)...); } static ObjectCell::FDeleter Deleter() { return Deleter_; } private: static void Deleter_(ObjectCell* ptr) { delete static_cast<T*>(ptr); } }; template <typename U> ObjectPtr<U> As() const { auto ptr = reinterpret_cast<U*>(get()); return ObjectPtr<U>(ptr); } private: /*! \brief internal pointer field */ ObjectCell* data_{nullptr}; /*! * \brief constructor from NodeBase * \param data The node base pointer */ // TODO(jroesch): NodePtr design doesn't really work here due to the passing. public: explicit ObjectPtr(ObjectCell* data) : data_(data) { if (data != nullptr) { data_->IncRef(); } } private: template <typename Y, typename... Args> friend ObjectPtr<Y> MakeObject(Args&&...); template <typename> friend class ObjectPtr; friend class NDArray; friend class TVMPODValue_; friend class TVMArgValue; friend class TVMRetValue; friend class RPCWrappedFunc; }; struct TensorCell; struct DatatypeCell; struct ClosureCell; /*! * \brief A managed object in the TVM runtime. * * For example a tuple, list, closure, and so on. * * Maintains a reference count for the object. */ class Object { public: ObjectPtr<ObjectCell> ptr_; explicit Object(ObjectPtr<ObjectCell> ptr) : ptr_(ptr) {} explicit Object(ObjectCell* ptr) : ptr_(ptr) {} Object() : ptr_() {} Object(const Object& obj) : ptr_(obj.ptr_) {} ObjectCell* operator->() { return this->ptr_.operator->(); } const ObjectCell* operator->() const { return this->ptr_.operator->(); } /*! \brief Construct a tensor object. */ static Object Tensor(const NDArray& data); /*! \brief Construct a datatype object. */ static Object Datatype(size_t tag, const std::vector<Object>& fields); /*! \brief Construct a tuple object. */ static Object Tuple(const std::vector<Object>& fields); /*! \brief Construct a closure object. */ static Object Closure(size_t func_index, const std::vector<Object>& free_vars); ObjectPtr<TensorCell> AsTensor() const; ObjectPtr<DatatypeCell> AsDatatype() const; ObjectPtr<ClosureCell> AsClosure() const; }; /*! \brief An object containing an NDArray. */ struct TensorCell : public ObjectCell { /*! \brief The NDArray. */ NDArray data; explicit TensorCell(const NDArray& data) : ObjectCell(ObjectTag::kTensor), data(data) {} }; /*! \brief An object representing a structure or enumeration. */ struct DatatypeCell : public ObjectCell { /*! \brief The tag representing the constructor used. */ size_t tag; /*! \brief The fields of the structure. */ std::vector<Object> fields; DatatypeCell(size_t tag, const std::vector<Object>& fields) : ObjectCell(ObjectTag::kDatatype), tag(tag), fields(fields) {} }; /*! \brief An object representing a closure. */ struct ClosureCell : public ObjectCell { /*! \brief The index into the VM function table. */ size_t func_index; /*! \brief The free variables of the closure. */ std::vector<Object> free_vars; ClosureCell(size_t func_index, const std::vector<Object>& free_vars) : ObjectCell(ObjectTag::kClosure), func_index(func_index), free_vars(free_vars) {} }; /*! \brief Extract the NDArray from a tensor object. */ NDArray ToNDArray(const Object& obj); /*! * \brief Allocate a node object. * \param args arguments to the constructor. * \tparam T the node type. * \return The NodePtr to the allocated object. */ template <typename T, typename... Args> inline ObjectPtr<T> MakeObject(Args&&... args) { using Allocator = typename ObjectPtr<T>::StdAllocator; static_assert(std::is_base_of<ObjectCell, T>::value, "MakeObject can only be used to create "); T* node = Allocator::New(std::forward<Args>(args)...); node->deleter_ = Allocator::Deleter(); return ObjectPtr<T>(node); } } // namespace runtime } // namespace tvm #endif // TVM_RUNTIME_OBJECT_H_ <file_sep>/nnvm/python/nnvm/_cy3/__init__.py """Cython generated modules""" <file_sep>/nnvm/python/nnvm/__init__.py #!/usr/bin/env python # coding: utf-8 """NNVM python API for ease of use and help new framework establish python API. """ from __future__ import absolute_import as _abs from . import _base from . import symbol as sym from . import symbol from ._base import NNVMError from . import frontend __version__ = _base.__version__ <file_sep>/topi/python/topi/sparse/__init__.py # pylint: disable=wildcard-import """Sparse operators""" from __future__ import absolute_import as _abs from .csrmv import csrmv from .csrmm import csrmm from .dense import dense <file_sep>/nnvm/python/nnvm/compiler/__init__.py """NNVM compiler toolchain. User only need to use :any:`build` and :any:`build_config` to do the compilation, and :any:`save_param_dict` to save the parameters into bytes. The other APIs are for more advanced interaction with the compiler toolchain. """ from __future__ import absolute_import import tvm from . import build_module from . build_module import build, optimize, build_config from . compile_engine import engine, graph_key from . param_dict import save_param_dict, load_param_dict from .. import symbol as _symbol from .. import graph as _graph from .. import top as _top tvm.register_extension(_symbol.Symbol, _symbol.Symbol) tvm.register_extension(_graph.Graph, _graph.Graph) <file_sep>/topi/python/topi/x86/batch_matmul.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,too-many-locals,unused-variable """x86 batch_matmul operators""" from __future__ import absolute_import as _abs import tvm from tvm.contrib import cblas from topi.nn import batch_matmul, batch_matmul_default from .. import generic from ..util import traverse_inline, get_const_tuple, get_max_power2_factor @batch_matmul.register(["cpu"]) def batch_matmul_x86(x, y): """Computes batch matrix multiplication of `x` and `y` when `x` and `y` are data in batch. Parameters ---------- x : tvm.Tensor 3-D with shape [batch, M, K] y : tvm.Tensor 3-D with shape [batch, N, K] Returns ------- output : tvm.Tensor 3-D with shape [batch, M, N] """ target = tvm.target.current_target() if "cblas" in target.libs: return cblas.batch_matmul(x, y, False, True) return batch_matmul_default(x, y) @generic.schedule_batch_matmul.register(["cpu"]) def schedule_batch_matmul(outs): """Schedule for batch_matmul Parameters ---------- outs: Array of Tensor The computation graph description of batch_matmul in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ target = tvm.target.current_target() if "cblas" in target.libs: return generic.schedule_extern(outs) s = tvm.create_schedule([x.op for x in outs]) def _callback(op): if "batch_matmul" in op.tag: C = op.output(0) A, B = s[C].op.input_tensors _, M, N = get_const_tuple(C.shape) k, = s[C].op.reduce_axis ko, ki = s[C].split(k, 16) CC = s.rfactor(C, ki) b, y, x = s[C].op.axis y_bn = get_max_power2_factor(M, 8) x_bn = get_max_power2_factor(N, 8) yo, yi = s[C].split(y, y_bn) xo, xi = s[C].split(x, x_bn) s[C].reorder(b, yo, xo, yi, xi) bxyo = s[C].fuse(b, yo, xo) s[C].parallel(bxyo) s[C].fuse(yi, xi) s[CC].compute_at(s[C], bxyo) _, _, y, x = s[CC].op.axis s[CC].fuse(y, x) s[CC].vectorize(s[CC].op.axis[0]) s[C].pragma(bxyo, 'auto_unroll_max_step', 16) traverse_inline(s, outs[0].op, _callback) return s <file_sep>/src/api/dsl_api.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2016 by Contributors * Implementation of DSL API * \file dsl_api.cc */ #include <dmlc/base.h> #include <dmlc/logging.h> #include <dmlc/thread_local.h> #include <tvm/api_registry.h> #include <tvm/attrs.h> #include <vector> #include <string> #include <exception> #include "../runtime/dsl_api.h" namespace tvm { namespace runtime { /*! \brief entry to to easily hold returning information */ struct TVMAPIThreadLocalEntry { /*! \brief result holder for returning strings */ std::vector<std::string> ret_vec_str; /*! \brief result holder for returning string pointers */ std::vector<const char *> ret_vec_charp; /*! \brief result holder for retruning string */ std::string ret_str; }; /*! \brief Thread local store that can be used to hold return values. */ typedef dmlc::ThreadLocalStore<TVMAPIThreadLocalEntry> TVMAPIThreadLocalStore; using TVMAPINode = NodePtr<Node>; struct APIAttrGetter : public AttrVisitor { std::string skey; TVMRetValue* ret; bool found_ref_object{false}; void Visit(const char* key, double* value) final { if (skey == key) *ret = value[0]; } void Visit(const char* key, int64_t* value) final { if (skey == key) *ret = value[0]; } void Visit(const char* key, uint64_t* value) final { CHECK_LE(value[0], static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) << "cannot return too big constant"; if (skey == key) *ret = static_cast<int64_t>(value[0]); } void Visit(const char* key, int* value) final { if (skey == key) *ret = static_cast<int64_t>(value[0]); } void Visit(const char* key, bool* value) final { if (skey == key) *ret = static_cast<int64_t>(value[0]); } void Visit(const char* key, void** value) final { if (skey == key) *ret = static_cast<void*>(value[0]); } void Visit(const char* key, Type* value) final { if (skey == key) *ret = value[0]; } void Visit(const char* key, std::string* value) final { if (skey == key) *ret = value[0]; } void Visit(const char* key, NodeRef* value) final { if (skey == key) { *ret = value[0]; found_ref_object = true; } } void Visit(const char* key, runtime::NDArray* value) final { if (skey == key) { *ret = value[0]; found_ref_object = true; } } void Visit(const char* key, runtime::Object* value) final { if (skey == key) { *ret = value[0]; found_ref_object = true; } } }; struct APIAttrDir : public AttrVisitor { std::vector<std::string>* names; void Visit(const char* key, double* value) final { names->push_back(key); } void Visit(const char* key, int64_t* value) final { names->push_back(key); } void Visit(const char* key, uint64_t* value) final { names->push_back(key); } void Visit(const char* key, bool* value) final { names->push_back(key); } void Visit(const char* key, int* value) final { names->push_back(key); } void Visit(const char* key, void** value) final { names->push_back(key); } void Visit(const char* key, Type* value) final { names->push_back(key); } void Visit(const char* key, std::string* value) final { names->push_back(key); } void Visit(const char* key, NodeRef* value) final { names->push_back(key); } void Visit(const char* key, runtime::NDArray* value) final { names->push_back(key); } void Visit(const char* key, runtime::Object* value) final { names->push_back(key); } }; class DSLAPIImpl : public DSLAPI { public: void NodeFree(NodeHandle handle) const final { delete static_cast<TVMAPINode*>(handle); } void NodeTypeKey2Index(const char* type_key, int* out_index) const final { *out_index = static_cast<int>(Node::TypeKey2Index(type_key)); } void NodeGetTypeIndex(NodeHandle handle, int* out_index) const final { *out_index = static_cast<int>( (*static_cast<TVMAPINode*>(handle))->type_index()); } void NodeGetAttr(NodeHandle handle, const char* key, TVMValue* ret_val, int* ret_type_code, int* ret_success) const final { TVMRetValue rv; APIAttrGetter getter; TVMAPINode* tnode = static_cast<TVMAPINode*>(handle); getter.skey = key; getter.ret = &rv; if (getter.skey == "type_key") { ret_val->v_str = (*tnode)->type_key(); *ret_type_code = kStr; *ret_success = 1; return; } else if (!(*tnode)->is_type<DictAttrsNode>()) { (*tnode)->VisitAttrs(&getter); *ret_success = getter.found_ref_object || rv.type_code() != kNull; } else { // specially handle dict attr DictAttrsNode* dnode = static_cast<DictAttrsNode*>(tnode->get()); auto it = dnode->dict.find(key); if (it != dnode->dict.end()) { *ret_success = 1; rv = (*it).second; } else { *ret_success = 0; } } if (*ret_success) { if (rv.type_code() == kStr || rv.type_code() == kTVMType) { TVMAPIThreadLocalEntry *e = TVMAPIThreadLocalStore::Get(); e->ret_str = rv.operator std::string(); *ret_type_code = kStr; ret_val->v_str = e->ret_str.c_str(); } else { rv.MoveToCHost(ret_val, ret_type_code); } } } void NodeListAttrNames(NodeHandle handle, int *out_size, const char*** out_array) const final { TVMAPIThreadLocalEntry *ret = TVMAPIThreadLocalStore::Get(); ret->ret_vec_str.clear(); TVMAPINode* tnode = static_cast<TVMAPINode*>(handle); APIAttrDir dir; dir.names = &(ret->ret_vec_str); if (!(*tnode)->is_type<DictAttrsNode>()) { (*tnode)->VisitAttrs(&dir); } else { // specially handle dict attr DictAttrsNode* dnode = static_cast<DictAttrsNode*>(tnode->get()); for (const auto& kv : dnode->dict) { ret->ret_vec_str.push_back(kv.first); } } ret->ret_vec_charp.clear(); for (size_t i = 0; i < ret->ret_vec_str.size(); ++i) { ret->ret_vec_charp.push_back(ret->ret_vec_str[i].c_str()); } *out_array = dmlc::BeginPtr(ret->ret_vec_charp); *out_size = static_cast<int>(ret->ret_vec_str.size()); } }; TVM_REGISTER_GLOBAL("dsl_api.singleton") .set_body([](TVMArgs args, TVMRetValue* rv) { static DSLAPIImpl impl; void* ptr = &impl; *rv = ptr; }); } // namespace runtime } // namespace tvm <file_sep>/docs/frontend/tensorflow.md <!--- Licensed to the Apache Software Foundation (ASF) under one --> <!--- or more contributor license agreements. See the NOTICE file --> <!--- distributed with this work for additional information --> <!--- regarding copyright ownership. The ASF licenses this file --> <!--- to you under the Apache License, Version 2.0 (the --> <!--- "License"); you may not use this file except in compliance --> <!--- with the License. You may obtain a copy of the License at --> <!--- http://www.apache.org/licenses/LICENSE-2.0 --> <!--- Unless required by applicable law or agreed to in writing, --> <!--- software distributed under the License is distributed on an --> <!--- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY --> <!--- KIND, either express or implied. See the License for the --> <!--- specific language governing permissions and limitations --> <!--- under the License. --> # Tensorflow Frontend Tensorflow frontend helps in importing tensorflow released model into TVM. This document helps few steps while importing various different models from [tensorflow research/slim](https://github.com/tensorflow/models/tree/master/research/slim). Current frontend is tested with all versions of below models - Inception (V1/V2/V3/V4) - Resnet (All) - Mobilenet (V1/V2 All) - Vgg (16/19) Tensorflow frontend expects a freezed protobuf format as input. Not all models are released as freezed protobuf. Some of them are checkpoints (.ckpt). Please refer to [export](https://github.com/tensorflow/models/tree/master/research/slim#exporting-the-inference-graph) and [freeze](https://github.com/tensorflow/models/tree/master/research/slim#freezing-the-exported-graph) instructions to generate protobuf from checkpoint. ## General Instructions ### Add Shapes: While freezing of protobuf add additional option ```add_shapes=True``` to embed output shapes of each node into graph. You may use ```tvm.relay.testing.tf.AddShapesToGraphDef``` from nnvm for the same. Please refer to [tensorflow tutorial](https://github.com/dmlc/tvm/blob/master/tutorials/nnvm/from_tensorflow.py). ### Explicit Shape: There might be situations where the add_shapes=True may not provide sufficient information about shape. You may pass explicit dictionary of input shapes argument for ```from_tensorflow```. Please refer to [test cases](https://github.com/dmlc/tvm/blob/master/nnvm/tests/python/frontend/tensorflow/test_forward.py#L36). ### GPU: Most of these tensorflow models are released for CPU with NHWC layout. To compile for GPU we need to pass extra argument ```layout='NCHW'``` for from_tensorflow. This option will do a layout conversion before and after for neural network ops. Remaining nnvm build options for GPU compilation remain as it is. <file_sep>/apps/bundle_deploy/Makefile # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # Makefile Example to bundle TVM modules. TVM_ROOT=$(shell cd ../..; pwd) NNVM_PATH=nnvm DMLC_CORE=${TVM_ROOT}/3rdparty/dmlc-core PKG_CFLAGS = -std=c++14 -Oz -fPIC\ -I${TVM_ROOT}/include\ -I${DMLC_CORE}/include\ -I${TVM_ROOT}/3rdparty/dlpack/include\ PKG_LDFLAGS = -L${TVM_ROOT}/build build_dir := build test: $(build_dir)/demo $(build_dir)/bundle.so $(build_dir)/demo $(build_dir)/bundle.so $(build_dir)/demo: demo.cc @mkdir -p $(@D) $(CXX) $(PKG_CFLAGS) -o $@ $^ # Serialize our graph.json file. $(build_dir)/graph.json.cc: $(build_dir)/graph.json xxd -i $^ > $@ # Serialize our params.bin file. $(build_dir)/params.bin.cc: $(build_dir)/params.bin xxd -i $^ > $@ $(build_dir)/model.o $(build_dir)/graph.json $(build_dir)/params.bin: build_model.py python $< -o $(build_dir) # Build our bundle against the serialized bundle.cc API, the runtime.cc API, and # the serialized graph.json and params.bin $(build_dir)/bundle.so: bundle.cc runtime.cc $(build_dir)/model.o $(build_dir)/graph.json.cc $(build_dir)/params.bin.cc @mkdir -p $(@D) $(CXX) $(PKG_CFLAGS) -fvisibility=hidden -o $@ $^ $(PKG_LDFLAGS) -shared clean: rm -r $(build_dir) <file_sep>/tests/scripts/packages.mk # rules for gtest .PHONY: iverilog iverilog: | ${CACHE_PREFIX}/bin/vvp ${CACHE_PREFIX}/bin/vvp: rm -rf verilog-10.1.tar.gz verilog-10.1 wget ftp://icarus.com/pub/eda/verilog/v10/verilog-10.1.tar.gz tar xf verilog-10.1.tar.gz cd verilog-10.1;./configure --prefix=${CACHE_PREFIX}; make install <file_sep>/nnvm/tests/python/frontend/caffe2/model_zoo/__init__.py """Store for caffe2 examples and common models.""" from __future__ import absolute_import as _abs import os import importlib models = [ 'squeezenet', 'resnet50', 'vgg19', ] # skip download if model exist for model in models: try: locals()['c2_' + model] = importlib.import_module('caffe2.python.models.' + model) except ImportError: os.system("python -m caffe2.python.models.download -i -f " + model) locals()['c2_' + model] = importlib.import_module('caffe2.python.models.' + model) <file_sep>/vta/python/vta/__init__.py """VTA Package is a TVM backend extension to support VTA hardwares Besides the compiler toolchain. It also include utility functions to configure the hardware Environment and access remote through RPC """ from __future__ import absolute_import as _abs import sys from .bitstream import get_bitstream_path, download_bitstream from .environment import get_env, Environment from .rpc_client import reconfig_runtime, program_fpga __version__ = "0.1.0" # do not import nnvm/topi when running vta.exec.rpc_server # to maintain minimum dependency on the board if sys.argv[0] not in ("-c", "-m"): from . import top from .build_module import build_config, lower, build from . import graph <file_sep>/src/relay/op/op_common.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file op_common.h * \brief A set of utilities and common functionality * for relay ops. */ #ifndef TVM_RELAY_OP_OP_COMMON_H_ #define TVM_RELAY_OP_OP_COMMON_H_ #include <tvm/relay/expr.h> #include <tvm/relay/op.h> #include <tvm/relay/op_attr_types.h> #include <vector> #include "type_relations.h" #include "../pass/alter_op_layout.h" namespace tvm { namespace relay { /*! Quick helper macro * - Expose a positional make function to construct the node. * - Register op to the registry. * * We make the decision to always only expose positional argument. * We will do rewrapping in the frontend to support language * sugars such as keyword arguments and default value. * \param OpName the name of registry. */ #define RELAY_REGISTER_UNARY_OP(OpName) \ TVM_REGISTER_API("relay.op._make." OpName) \ .set_body_typed<Expr(Expr)>([](Expr data) { \ static const Op& op = Op::Get(OpName); \ return CallNode::make(op, {data}, Attrs(), {}); \ }); \ RELAY_REGISTER_OP(OpName) \ .set_num_inputs(1) \ .add_argument("data", "Tensor", "The input tensor.") \ .add_type_rel("Identity", IdentityRel) \ .set_attr<TOpPattern>("TOpPattern", kElemWise) \ .set_attr<TOpIsStateful>("TOpIsStateful", false) \ .set_attr<FInferCorrectLayout>("FInferCorrectLayout", \ ElemwiseArbitraryLayout) \ /*! Quick helper macro * - Expose a positional make function to construct the node. * - Register op to the registry. * * We make the decision to always only expose positional argument. * We will do rewrapping in the frontend to support language * sugars such as keyword arguments and default value. * * \param OpName the name of registry. */ #define RELAY_REGISTER_BINARY_OP(OpName) \ TVM_REGISTER_API("relay.op._make." OpName) \ .set_body_typed<Expr(Expr, Expr)>([](Expr lhs, Expr rhs) { \ static const Op& op = Op::Get(OpName); \ return CallNode::make(op, {lhs, rhs}, Attrs(), {}); \ }); \ RELAY_REGISTER_OP(OpName) \ .set_num_inputs(2) \ .add_argument("lhs", "Tensor", "The left hand side tensor.") \ .add_argument("rhs", "Tensor", "The right hand side tensor.") \ .add_type_rel("Broadcast", BroadcastRel) \ .set_attr<TOpPattern>("TOpPattern", kBroadcast) \ .set_attr<TOpIsStateful>("TOpIsStateful", false) \ .set_attr<FInferCorrectLayout>("FInferCorrectLayout", \ BinaryBroadcastLayout) // Comparisons #define RELAY_REGISTER_CMP_OP(OpName) \ TVM_REGISTER_API("relay.op._make." OpName) \ .set_body_typed<Expr(Expr, Expr)>([](Expr lhs, Expr rhs) { \ static const Op& op = Op::Get(OpName); \ return CallNode::make(op, {lhs, rhs}, Attrs(), {}); \ }); \ RELAY_REGISTER_OP(OpName) \ .set_num_inputs(2) \ .add_argument("lhs", "Tensor", "The left hand side tensor.") \ .add_argument("rhs", "Tensor", "The right hand side tensor.") \ .add_type_rel("BroadcastComp", BroadcastCompRel) \ .set_attr<TOpPattern>("TOpPattern", kBroadcast) \ .set_attr<TOpIsStateful>("TOpIsStateful", false) \ .set_attr<FInferCorrectLayout>("FInferCorrectLayout", \ BinaryBroadcastLayout) } // namespace relay } // namespace tvm #endif // TVM_RELAY_OP_OP_COMMON_H_ <file_sep>/python/tvm/relay/backend/vm.py # License .to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=no-else-return, unidiomatic-typecheck, undefined-variable, invalid-name """ The Relay Virtual Machine. Implements a Python interface to compiling and executing on the Relay VM. """ import numpy as np import tvm from tvm._ffi.runtime_ctypes import TVMByteArray from . import _vm from . import vmobj as _obj from .interpreter import Executor def _update_target(target): target = target if target else tvm.target.current_target() if target is None: raise ValueError("Target is not set in env or passed as argument.") tgts = {} if isinstance(target, (str, tvm.target.Target)): dev_type = tvm.expr.IntImm("int32", tvm.nd.context(str(target)).device_type) tgts[dev_type] = tvm.target.create(target) elif isinstance(target, dict): for dev, tgt in target.items(): dev_type = tvm.expr.IntImm("int32", tvm.nd.context(dev).device_type) tgts[dev_type] = tvm.target.create(tgt) else: raise TypeError("target is expected to be str, tvm.target.Target, " + "or dict of str to str/tvm.target.Target, but received " + "{}".format(type(target))) return tgts def _convert(arg, cargs): if isinstance(arg, (np.ndarray, tvm.nd.NDArray)): cargs.append(_obj.tensor_object(arg)) elif isinstance(arg, (tuple, list)): field_args = [] for field in arg: _convert(field, field_args) cargs.append(_obj.tuple_object(field_args)) else: raise "unsupported type" def convert(args): cargs = [] for arg in args: _convert(arg, cargs) return cargs class VirtualMachine(object): """Relay VM runtime.""" def __init__(self, mod): self.mod = mod self._init = self.mod["init"] self._load_params = self.mod["load_params"] self._invoke = self.mod["invoke"] def init(self, ctx): """Initialize the context in the VM. Parameters ---------- ctx : :py:class:`TVMContext` The runtime context to run the code on. """ args = [ctx.device_type, ctx.device_id] self._init(*args) def load_params(self, params): """Load parameters for the VM. Parameters ---------- params : Union[bytearray, Dict] The dictionary that contains serialized parameters. """ if isinstance(params, dict): params = tvm.relay.save_param_dict(params) elif isinstance(params, (bytes, str)): params = bytearray(params) if not isinstance(params, (bytearray, TVMByteArray)): raise TypeError("params must be a bytearray") self._load_params(bytearray(params)) def invoke(self, func_name, *args): """Invoke a function. Parameters ---------- func_name : str The name of the function. args : list[NDArray] or list[np.ndarray] The arguments to the function. Returns ------- result : Object The output. """ cargs = convert(args) return self._invoke(func_name, *cargs) def run(self, *args): """Run the main function. Parameters ---------- args : list[NDArray] or list[np.ndarray] The arguments to the function. Returns ------- result : Object The output. """ return self.invoke("main", *args) @property def module(self): """Return the runtime module contained in a virtual machine.""" return self.mod class VMCompiler(object): """Build Relay module to run on VM runtime.""" def __init__(self): self.mod = _vm._VMCompiler() self._compile = self.mod["compile"] self._get_vm = self.mod["get_vm"] def compile(self, mod, target=None, target_host=None): """ Parameters ---------- mod : relay.Module The Relay module to build. target : str, :any:`tvm.target.Target`, or dict of str(i.e. device/context name) to str/tvm.target.Target, optional For heterogeneous compilation, it is a dictionary indicating context to target mapping. For homogeneous compilation, it is a build target. target_host : str or :any:`tvm.target.Target`, optional Host compilation target, if target is device. When TVM compiles device specific program such as CUDA, we also need host(CPU) side code to interact with the driver to setup the dimensions and parameters correctly. target_host is used to specify the host side codegen target. By default, llvm is used if it is enabled, otherwise a stackvm intepreter is used. Returns ------- vm : VirtualMachine The VM runtime. """ target = _update_target(target) target_host = None if target_host == "" else target_host if not target_host: target_host = "llvm" if tvm.module.enabled("llvm") else "stackvm" target_host = tvm.target.create(target_host) self._compile(mod, target, target_host) return VirtualMachine(self._get_vm()) class VMExecutor(Executor): """ An implementation of the executor interface for the Relay VM. Useful interface for experimentation and debugging the VM can also be used directly from the API. supported by `tvm.relay.vm`. Parameters ---------- mod : :py:class:`~tvm.relay.module.Module` The module to support the execution. ctx : :py:class:`TVMContext` The runtime context to run the code on. target : :py:class:`Target` The target option to build the function. """ def __init__(self, mod, ctx, target): if mod is None: raise RuntimeError("Must provide module to get VM executor.") self.mod = mod self.ctx = ctx self.target = target compiler = VMCompiler() self.vm = compiler.compile(mod, target) self.vm.init(ctx) def _make_executor(self, expr=None): main = self.mod["main"] def _vm_wrapper(*args, **kwargs): args = self._convert_args(main, args, kwargs) return self.vm.run(*args) return _vm_wrapper <file_sep>/apps/extension/python/tvm_ext/__init__.py """Example extension package of TVM.""" from __future__ import absolute_import import os import ctypes # Import TVM first to get library symbols import tvm def load_lib(): """Load library, the functions will be registered into TVM""" curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) # load in as global so the global extern symbol is visible to other dll. lib = ctypes.CDLL( os.path.join(curr_path, "../../lib/libtvm_ext.so"), ctypes.RTLD_GLOBAL) return lib _LIB = load_lib() # Expose two functions into python bind_add = tvm.get_global_func("tvm_ext.bind_add") sym_add = tvm.get_global_func("tvm_ext.sym_add") ivec_create = tvm.get_global_func("tvm_ext.ivec_create") ivec_get = tvm.get_global_func("tvm_ext.ivec_get") class IntVec(object): """Example for using extension class in c++ """ _tvm_tcode = 17 def __init__(self, handle): self.handle = handle def __del__(self): # You can also call your own customized # deleter if you can free it via your own FFI. tvm.nd.free_extension_handle(self.handle, self.__class__._tvm_tcode) @property def _tvm_handle(self): return self.handle.value def __getitem__(self, idx): return ivec_get(self, idx) # Register IntVec extension on python side. tvm.register_extension(IntVec, IntVec) nd_create = tvm.get_global_func("tvm_ext.nd_create") nd_add_two = tvm.get_global_func("tvm_ext.nd_add_two") nd_get_addtional_info = tvm.get_global_func("tvm_ext.nd_get_addtional_info") class NDSubClass(tvm.nd.NDArrayBase): """Example for subclassing TVM's NDArray infrastructure. By inheriting TMV's NDArray, external libraries could leverage TVM's FFI without any modification. """ # Should be consistent with the type-trait set in the backend _array_type_code = 1 @staticmethod def create(addtional_info): return nd_create(addtional_info) @property def addtional_info(self): return nd_get_addtional_info(self) def __add__(self, other): return nd_add_two(self, other) tvm.register_extension(NDSubClass, NDSubClass) <file_sep>/nnvm/tests/python/frontend/onnx/model_zoo/__init__.py """Store for onnx examples and common models.""" from __future__ import absolute_import as _abs import os import logging from .super_resolution import get_super_resolution from tvm.contrib.download import download_testdata URLS = { 'super_resolution.onnx': 'https://gist.github.com/zhreshold/bcda4716699ac97ea44f791c24310193/raw/93672b029103648953c4e5ad3ac3aadf346a4cdc/super_resolution_0.2.onnx', 'squeezenet1_1.onnx': 'https://gist.github.com/zhreshold/bcda4716699ac97ea44f791c24310193/raw/93672b029103648953c4e5ad3ac3aadf346a4cdc/squeezenet1_1_0.2.onnx', 'lenet.onnx': 'https://gist.github.com/zhreshold/bcda4716699ac97ea44f791c24310193/raw/93672b029103648953c4e5ad3ac3aadf346a4cdc/lenet_0.2.onnx', 'resnet18_1_0.onnx': 'https://gist.github.com/zhreshold/bcda4716699ac97ea44f791c24310193/raw/b385b1b242dc89a35dd808235b885ed8a19aedc1/resnet18_1.0.onnx'} # download and add paths for k, v in URLS.items(): name = k.split('.')[0] relpath = os.path.join('onnx', k) abspath = download_testdata(v, relpath, module='onnx') locals()[name] = abspath # symbol for graph comparison super_resolution_sym = get_super_resolution() <file_sep>/src/relay/op/nn/pad.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file pad.cc * \brief Implementation of operator pad */ #include <tvm/data_layout.h> #include <tvm/expr_operator.h> #include <tvm/relay/op.h> #include <tvm/relay/attrs/nn.h> #include <topi/nn.h> #include <vector> #include "../op_common.h" namespace tvm { namespace relay { // relay.nn.pad TVM_REGISTER_NODE_TYPE(PadAttrs); bool PadRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { CHECK_EQ(types.size(), 2); const auto* data = types[0].as<TensorTypeNode>(); if (data == nullptr) return false; const PadAttrs* param = attrs.as<PadAttrs>(); CHECK(param != nullptr); // check that pad widths match lengths CHECK(data->shape.size() == param->pad_width.size()) << "There should be as many pad width pairs as shape dimensions " << "but the shape has " << data->shape.size() << " dimensions " << "and there are " << param->pad_width.size() << " pad width pairs."; // each pad width element should be a pair of positive integers std::vector<IndexExpr> oshape; for (size_t i = 0; i < param->pad_width.size(); i++) { CHECK(param->pad_width[i].size() == 2) << "Each pad width element should be a pair but at index " << i << " there are " << param->pad_width[i].size() << " elements."; auto width1 = as_const_int(param->pad_width[i][0]); auto width2 = as_const_int(param->pad_width[i][1]); CHECK(width1 != nullptr); CHECK(width2 != nullptr); CHECK(*width1 >= 0) << "Param width elements should be positive but first pad width at " << "index " << i << " is " << *width1 << "."; CHECK(*width2 >= 0) << "Param width elements should be positive but first pad width at " << "index " << i << " is " << *width2 << "."; auto padding = make_const(data->shape[i].type(), *width1 + *width2); oshape.push_back(data->shape[i] + padding); } reporter->Assign(types[1], TensorTypeNode::make(Array<IndexExpr>(oshape), data->dtype)); return true; } Array<Tensor> PadCompute(const Attrs& attrs, const Array<Tensor>& inputs, const Type& out_type, const Target& target) { const auto* param = attrs.as<PadAttrs>(); CHECK(param != nullptr); auto pad_width = param->pad_width; CHECK(pad_width.size() == inputs[0].ndim() && pad_width[0].size() == 2) << "Illegal pad_width"; Array<IndexExpr> pad_before; for (size_t i = 0; i < pad_width.size(); ++i) { pad_before.push_back(pad_width[i][0]); } Array<IndexExpr> pad_after; for (size_t i = 0; i < pad_width.size(); ++i) { pad_after.push_back(pad_width[i][1]); } const auto* out_ttype = out_type.as<TensorTypeNode>(); return Array<Tensor>{ topi::pad(inputs[0], pad_before, pad_after, tvm::make_const(out_ttype->dtype, param->pad_value)) }; } // Handler to create a call to the padding op used by front-end FFI Expr MakePad(Expr data, Array<Array<IndexExpr> > pad_width, double pad_value) { auto attrs = make_node<PadAttrs>(); attrs->pad_value = pad_value; attrs->pad_width = std::move(pad_width); static const Op& op = Op::Get("nn.pad"); return CallNode::make(op, {data}, Attrs(attrs), {}); } TVM_REGISTER_API("relay.op.nn._make.pad") .set_body_typed(MakePad); RELAY_REGISTER_OP("nn.pad") .describe(R"code(Pad for n-D tensor. )code" TVM_ADD_FILELINE) .set_attrs_type_key("relay.attrs.PadAttrs") .set_num_inputs(1) .add_argument("data", "Tensor", "The input tensor.") .set_support_level(2) .add_type_rel("Pad", PadRel) .set_attr<TOpPattern>("TOpPattern", kInjective) .set_attr<FTVMCompute>("FTVMCompute", PadCompute); // relay.nn.mirror_pad TVM_REGISTER_NODE_TYPE(MirrorPadAttrs); bool MirrorPadRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { CHECK_EQ(types.size(), 2); const auto* data = types[0].as<TensorTypeNode>(); if (data == nullptr) return false; const MirrorPadAttrs* param = attrs.as<MirrorPadAttrs>(); CHECK(param != nullptr); // check that pad widths match lengths CHECK(data->shape.size() == param->pad_width.size()) << "There should be as many pad width pairs as shape dimensions " << "but the shape has " << data->shape.size() << " dimensions " << "and there are " << param->pad_width.size() << " pad width pairs."; // each pad width element should be a pair of positive integers std::vector<IndexExpr> oshape; for (size_t i = 0; i < param->pad_width.size(); i++) { CHECK(param->pad_width[i].size() == 2) << "Each pad width element should be a pair but at index " << i << " there are " << param->pad_width[i].size() << " elements."; auto width1 = as_const_int(param->pad_width[i][0]); auto width2 = as_const_int(param->pad_width[i][1]); CHECK(width1 != nullptr); CHECK(width2 != nullptr); CHECK(*width1 >= 0) << "Param width elements should be positive but first pad width at " << "index " << i << " is " << *width1 << "."; CHECK(*width2 >= 0) << "Param width elements should be positive but first pad width at " << "index " << i << " is " << *width2 << "."; auto padding = make_const(data->shape[i].type(), *width1 + *width2); oshape.push_back(data->shape[i] + padding); } reporter->Assign(types[1], TensorTypeNode::make(Array<IndexExpr>(oshape), data->dtype)); return true; } // Handler to create a call to the padding op used by front-end FFI Expr MakeMirrorPad(Expr data, Array<Array<IndexExpr> > pad_width, std::string mode) { auto attrs = make_node<MirrorPadAttrs>(); attrs->mode = mode; attrs->pad_width = std::move(pad_width); static const Op& op = Op::Get("nn.mirror_pad"); return CallNode::make(op, {data}, Attrs(attrs), {}); } TVM_REGISTER_API("relay.op.nn._make.mirror_pad") .set_body_typed(MakeMirrorPad); RELAY_REGISTER_OP("nn.mirror_pad") .describe(R"code(MirrorPad for n-D tensor. )code" TVM_ADD_FILELINE) .set_attrs_type_key("relay.attrs.MirrorPadAttrs") .set_num_inputs(1) .add_argument("data", "Tensor", "The input tensor.") .set_support_level(2) .add_type_rel("MirrorPad", MirrorPadRel) .set_attr<TOpPattern>("TOpPattern", kInjective); } // namespace relay } // namespace tvm <file_sep>/python/tvm/_ffi/_ctypes/vmobj.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Runtime Object api""" from __future__ import absolute_import import ctypes from ..base import _LIB, check_call from .types import TypeCode, RETURN_SWITCH ObjectHandle = ctypes.c_void_p """Maps object type to its constructor""" OBJECT_TYPE = {} def _register_object(index, cls): """register object class""" OBJECT_TYPE[index] = cls def _return_object(x): handle = x.v_handle if not isinstance(handle, ObjectHandle): handle = ObjectHandle(handle) tag = ctypes.c_int() check_call(_LIB.TVMGetObjectTag(handle, ctypes.byref(tag))) cls = OBJECT_TYPE.get(tag.value, ObjectBase) obj = cls(handle) return obj RETURN_SWITCH[TypeCode.OBJECT_CELL] = _return_object class ObjectBase(object): __slots__ = ["handle"] def __init__(self, handle): self.handle = handle <file_sep>/vta/python/vta/exec/__init__.py """VTA Command line utils.""" <file_sep>/apps/android_deploy/app/src/main/jni/make/config.mk #------------------------------------------------------------------------------- # Template configuration for compiling # # If you want to change the configuration, please use the following # steps. Assume you are on the root directory. First copy the this # file so that any local changes will be ignored by git # # cp make/config.mk . # # Next modify the according entries, and then compile by # # ./build.sh # #------------------------------------------------------------------------------- APP_ABI = all APP_PLATFORM = android-17 # whether enable OpenCL during compile USE_OPENCL = 0 # the additional include headers you want to add, e.g., SDK_PATH/adrenosdk/Development/Inc ADD_C_INCLUDES = # the additional link libs you want to add, e.g., ANDROID_LIB_PATH/libOpenCL.so ADD_LDLIBS = <file_sep>/src/codegen/llvm/intrin_rule_llvm.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file intrin_rule_llvm.cc */ #ifdef TVM_LLVM_VERSION #include "intrin_rule_llvm.h" namespace tvm { namespace codegen { namespace llvm { TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.prefetch") .set_body(DispatchLLVMIntrin<::llvm::Intrinsic::prefetch, 0>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.exp") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::exp, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.fma") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::fmuladd, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.log") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::log, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.sqrt") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::sqrt, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.floor") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::floor, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.ceil") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::ceil, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.trunc") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::trunc, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.fabs") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::fabs, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.round") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::round, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.tanh") .set_body([](const TVMArgs& targs, TVMRetValue* rv) { Expr e = targs[0]; const ir::Call* call = e.as<ir::Call>(); CHECK(call != nullptr); const Expr& x = call->args[0]; Expr one = make_const(x.type(), 1); Expr two = make_const(x.type(), 2); Expr neg_two = make_const(x.type(), -2); Expr exp_neg2x = ir::Call::make( x.type(), "exp", {neg_two * x}, ir::Call::PureIntrinsic); Expr exp_pos2x = ir::Call::make( x.type(), "exp", {two * x}, ir::Call::PureIntrinsic); Expr tanh_pos = (one - exp_neg2x) / (one + exp_neg2x); Expr tanh_neg = (exp_pos2x - one) / (exp_pos2x + one); *rv = ir::Select::make( x >= make_zero(x.type()), tanh_pos, tanh_neg); }); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.pow") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::pow, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.popcount") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::ctpop, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.cos") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::cos, 1>); TVM_REGISTER_GLOBAL("tvm.intrin.rule.llvm.sin") .set_body(DispatchLLVMPureIntrin<::llvm::Intrinsic::sin, 1>); } // namespace llvm } // namespace codegen } // namespace tvm #endif // LLVM_VERSION <file_sep>/src/runtime/c_dsl_api.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file cpu_dsl_api.cc * \brief DSL API dispatcher */ #include <tvm/runtime/registry.h> #include <tvm/c_dsl_api.h> #include "dsl_api.h" #include "runtime_base.h" namespace tvm { namespace runtime { DSLAPI* FindDSLAPI() { auto* f = Registry::Get("dsl_api.singleton"); if (f == nullptr) { throw dmlc::Error("TVM runtime only environment,"\ " DSL API is not available"); } void* ptr = (*f)(); return static_cast<DSLAPI*>(ptr); } static DSLAPI* GetDSLAPI() { static DSLAPI* inst = FindDSLAPI(); return inst; } } // namespace runtime } // namespace tvm using namespace tvm::runtime; int TVMNodeFree(NodeHandle handle) { API_BEGIN(); GetDSLAPI()->NodeFree(handle); API_END(); } int TVMNodeTypeKey2Index(const char* type_key, int* out_index) { API_BEGIN(); GetDSLAPI()->NodeTypeKey2Index(type_key, out_index); API_END(); } int TVMNodeGetTypeIndex(NodeHandle handle, int* out_index) { API_BEGIN(); GetDSLAPI()->NodeGetTypeIndex(handle, out_index); API_END(); } int TVMNodeGetAttr(NodeHandle handle, const char* key, TVMValue* out_value, int* out_type_code, int* out_success) { API_BEGIN(); GetDSLAPI()->NodeGetAttr( handle, key, out_value, out_type_code, out_success); API_END(); } int TVMNodeListAttrNames(NodeHandle handle, int *out_size, const char*** out_array) { API_BEGIN(); GetDSLAPI()->NodeListAttrNames( handle, out_size, out_array); API_END(); } <file_sep>/python/tvm/relay/backend/serializer.py # License .to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """ The Relay Virtual Machine serializer. Python interface for serializing a Relay VM. """ import tvm from . import _vm from . import vm as rly_vm def _create_serializer(vm): """Create a VM serializer. Parameters ---------- vm : Union[VirtualMachine, :py:class:`~tvm.module.Module`] The virtual machine to be serialized. Returns ------- ret : Serializer The created virtual machine serializer. """ if isinstance(vm, rly_vm.VirtualMachine): vm = vm.module elif not isinstance(vm, tvm.module.Module): raise TypeError("vm is expected to be the type of VirtualMachine or " + "tvm.Module, but received {}".format(type(vm))) return _vm._Serializer(vm) class Serializer: """Relay VM serializer.""" def __init__(self, vm): self.mod = _create_serializer(vm) self._get_lib = self.mod["get_lib"] self._get_bytecode = self.mod["get_bytecode"] self._get_globals = self.mod["get_globals"] self._get_stats = self.mod["get_stats"] self._get_primitive_ops = self.mod["get_primitive_ops"] self._serialize = self.mod["serialize"] @property def stats(self): """Get the statistics of the Relay VM. Returns ------- ret : String The serialized statistic information. """ return self._get_stats() @property def primitive_ops(self): """Get the name of the primitive ops that are executed in the VM. Returns ------- ret : List[:py:class:`~tvm.expr.StringImm`] The list of primitive ops. """ return [prim_op.value for prim_op in self._get_primitive_ops()] @property def bytecode(self): """Get the bytecode of the Relay VM. Returns ------- ret : String The serialized bytecode. Notes ----- The bytecode is in the following format: func_name reg_file_size num_instructions param1 param2 ... paramM instruction1 instruction2 ... instructionN Each instruction is printed in the following format: hash opcode field1 ... fieldX # The text format. The part starting from # is only used for visualization and debugging. The real serialized code doesn't contain it, therefore the deserializer doesn't need to deal with it as well. """ return self._get_bytecode() @property def globals(self): """Get the globals used by the Relay VM. Returns ------- ret : List[:py:class:`~tvm.expr.StringImm`] The serialized globals. """ return [glb.value for glb in self._get_globals()] def serialize(self): """Serialize the Relay VM. Returns ------- code : bytearray The binary blob representing a serialized Relay VM. It can then be saved to disk and later deserialized into a new VM. lib : :py:class:`~tvm.module.Module` The runtime module that contains the generated code. It is basically a library that is composed of hardware dependent code. Notes ----- The returned code is organized with the following sections in order. - Global section. This section contains the globals used by the virtual machine. - Constant section. This section is used to store the constant pool of a virtual machine. - Primitive name section. This section is introduced to accommodate the list of primitive operator names that will be invoked by the virtual machine. - Code section. The VM functions, including bytecode, are sitting in this section. Examples -------- .. code-block:: python import numpy as np import tvm from tvm import relay # define a simple network. x = relay.var('x', shape=(10, 10)) f = relay.Function([x], x + x) mod = relay.Module({"main": f}) # create a Relay VM. ctx = tvm.cpu() target = "llvm" compiler = relay.vm.VMCompiler() vm = compiler.compile(mod, target) vm.init(ctx) # serialize. ser = relay.serializer.Serializer(vm) code, lib = ser.serialize() # save and load the code and lib file. tmp = tvm.contrib.util.tempdir() path_lib = tmp.relpath("lib.so") lib.export_library(path_lib) with open(tmp.relpath("code.bc"), "wb") as fo: fo.write(code) loaded_lib = tvm.module.load(path_lib) loaded_code = bytearray(open(tmp.relpath("code.bc"), "rb").read()) # deserialize. deser = relay.deserializer.Deserializer(loaded_code, loaded_lib) des_vm = deser.deserialize() # execute the deserialized vm. des_vm.init(ctx) x_data = np.random.rand(10, 10).astype('float32') res = des_vm.run(x_data) print(res.asnumpy()) """ return self._serialize(), self._get_lib() <file_sep>/3rdparty/cma/cma.c /* cma.c - ARM specific Linux driver for allocating physically contigious memory. * * The MIT License (MIT) * * COPYRIGHT (C) 2017 Institute of Electronics and Computer Science (EDI), Latvia. * AUTHOR: <NAME> (<EMAIL>) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * * DESCRIPTION: * In some DMA use cases there is a need or it is more efficient to use large * physically contigous memory regions. When Linux kernel is compiled with CMA * (Contigous Memory Allocator) feature, this module allows to allocate this * contigous memory and pass it to the user space. Memory can be either cached * or uncached. * * For api description, see "cma_api.h" header file. * */ /* Linux driver includes */ #include <linux/init.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/device.h> #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/mutex.h> /* CMA specific includes */ #include <linux/dma-mapping.h> #include <linux/dma-contiguous.h> /* IOCTL description */ #include "cma.h" /* Handle defines */ #ifndef CONFIG_DMA_CMA #error "CMA configuration not set in kernel!" #endif #ifndef CMA_DEBUG #define CMA_DEBUG 0 #endif #ifndef DRIVER_NODE_NAME #define DRIVER_NODE_NAME "cma" #endif /* Commonly used printk statements */ #define __ERROR(fmt, args...) printk(KERN_ERR "CMA_ERROR: " fmt, ##args) #define __INFO(fmt, args...) printk(KERN_INFO "CMA_INFO: " fmt, ##args) #if CMA_DEBUG == 1 #define __DEBUG(fmt, args...) printk(KERN_INFO "CMA_DEBUG: " fmt, ##args) #else #define __DEBUG(fmt, args...) #endif /* cma entry flags */ #define CMA_ENTRY_CACHED 0 #define CMA_ENTRY_MAPPED (1<<0) #define CMA_ENTRY_NONCACHED (1<<1) /* fops declarations */ static int cma_ioctl(struct file *filp, unsigned int cmd, unsigned int arg); static int cma_mmap(struct file *filp, struct vm_area_struct *vm_area_dscr); /* ioctl interface commands */ static int cma_ioctl_alloc(struct file *filp, unsigned int cmd, unsigned int arg, int cached_flag); static int cma_ioctl_free(struct file *filp, unsigned int cmd, unsigned int arg); static int cma_ioctl_get_phy_addr(struct file *filp, unsigned int cmd, unsigned int arg); static int cma_ioctl_get_size(struct file *filp, unsigned int cmd, unsigned int arg); /* CMA entry specific functions */ struct cma_entry *cma_entry_get_by_phy_addr(unsigned int phy_addr); struct cma_entry *cma_entry_get_by_v_usr_addr(unsigned v_usr_addr); static int cma_entry_add(struct cma_entry *entry); static int cma_entry_release(unsigned v_usr_addr); /* mmap ops declarations */ void cma_mmap_close(struct vm_area_struct *vma); /* File operations */ struct file_operations fops = { .owner = THIS_MODULE, .unlocked_ioctl = cma_ioctl, .mmap = cma_mmap }; /* mmap operation structure */ static struct vm_operations_struct cma_ops = { .close = cma_mmap_close }; /* List structure for containing memory allocation information */ struct cma_entry{ struct cma_entry *next; pid_t pid; /* calling process id */ unsigned size; /* size of allocation */ dma_addr_t phy_addr; /* physical address */ void *v_ptr; /* kernel-space pointer */ unsigned v_usr_addr; /* user-space addr */ int flags; /* memory allocation related flags */ }; /* Global variables */ int major; static struct class *class; static struct device *device; struct cma_entry *cma_start = NULL; static struct mutex mutex_cma_list_modify; struct cma_entry *cma_entry_get_by_phy_addr(unsigned int phy_addr) { struct cma_entry *walk = cma_start; __DEBUG("cma_entry_get_by_phy_addr()\n"); if (mutex_lock_interruptible(&mutex_cma_list_modify)) return NULL; /* search for physical address */ while (walk != NULL) { if (walk->phy_addr == phy_addr) { goto leave; } walk = walk->next; } leave: mutex_unlock(&mutex_cma_list_modify); return walk; } struct cma_entry *cma_entry_get_by_v_usr_addr(unsigned v_usr_addr) { struct cma_entry *walk = cma_start; __DEBUG("cma_entry_get_by_v_usr_addr()\n"); if (mutex_lock_interruptible(&mutex_cma_list_modify)) { __DEBUG("cma_entry_get_by_v_usr_addr: failed to call mutex_lock_interruptible().\n"); return NULL; } /* search for user virtual address */ while (walk != NULL) { if (walk->v_usr_addr == v_usr_addr) { __DEBUG("found an entry with v_usr_addr (0x%x).\n", v_usr_addr); goto leave; } __DEBUG("> walk->v_usr_addr=(0x%x), expected v_usr_addr=(0x%x).\n", walk->v_usr_addr, v_usr_addr); walk = walk->next; } __DEBUG("failed to find an entry with v_usr_addr (0x%x).\n", v_usr_addr); leave: mutex_unlock(&mutex_cma_list_modify); return walk; } static int cma_entry_add(struct cma_entry *entry) { struct cma_entry *walk; __DEBUG("cma_entry_add() - phy_addr 0x%x; pid 0x%x\n", entry->phy_addr, entry->pid); if (mutex_lock_interruptible(&mutex_cma_list_modify)) return -EAGAIN; /* add entry in start - this is more effective */ entry->next = cma_start; cma_start = entry; /* print entry list for debugging */ walk = cma_start; while (walk != NULL) { __DEBUG("> walk->phy_addr=(0x%x).\n", walk->phy_addr); walk = walk->next; } mutex_unlock(&mutex_cma_list_modify); return 0; } static int cma_entry_release(unsigned v_usr_addr) { int err; struct cma_entry *walk_prev, *walk_curr; /* print entry list for debugging */ struct cma_entry *walk; __DEBUG("cma_entry_release() - v_usr_addr 0x%x; pid 0x%x\n", v_usr_addr, current->pid); if (mutex_lock_interruptible(&mutex_cma_list_modify)) return -EAGAIN; walk_prev = NULL; walk_curr = cma_start; while (walk_curr != NULL) { if (walk_curr->v_usr_addr == v_usr_addr) { /* check if mapped */ if (walk_curr->flags & CMA_ENTRY_MAPPED) { __DEBUG("failed to find a valid entry with v_usr_addr(0x%x), entry mapped.\n", v_usr_addr); err = -1; goto leave; } /* check if not the first entry */ if (walk_prev != NULL) walk_prev->next = walk_curr->next; else cma_start = walk_curr->next; if ((walk_curr->next == NULL) && (cma_start == walk_curr)) cma_start = NULL; __DEBUG("found an entry with v_usr_addr=0x%x, phy_addr=0x%x, next=0x%x\n", v_usr_addr, walk_curr->phy_addr, (int)walk_curr->next); dma_free_coherent(NULL, walk_curr->size, walk_curr->v_ptr, walk_curr->phy_addr); kfree(walk_curr); err = 0; goto leave; } __DEBUG("skip entry with v_usr_addr (0x%x).\n", walk_curr->v_usr_addr); /* prepare next walk */ walk_prev = walk_curr; walk_curr = walk_curr->next; } __DEBUG("failed to find an entry with v_usr_addr (0x%x).\n", v_usr_addr); err = -1; leave: /* print entry list for debugging */ walk = cma_start; while (walk != NULL) { __DEBUG("> walk->v_usr_addr=(0x%x), walk->next=0x%x\n", walk->v_usr_addr, (int)walk->next); walk = walk->next; } mutex_unlock(&mutex_cma_list_modify); return err; } /* inline function for readability */ inline int check_entry_accordance(struct cma_entry *entry, struct vm_area_struct *vma) { if ( entry == NULL ) return -EFAULT; if ( entry->phy_addr != vma->vm_pgoff << PAGE_SHIFT ) return -EFAULT; if ( entry->size != vma->vm_end-vma->vm_start ) return -EFAULT; if ( entry->pid != current->pid ) return -EACCES; return 0; } static int cma_mmap(struct file *filp, struct vm_area_struct *vma) { int err; struct cma_entry *entry; __DEBUG("cma_mmap() - phy_addr 0x%lx, v_user_addr 0x%lx\n", vma->vm_pgoff << PAGE_SHIFT, vma->vm_start); entry = cma_entry_get_by_phy_addr(vma->vm_pgoff << PAGE_SHIFT); /* check if mmap is alligned with according entry */ err = check_entry_accordance(entry, vma); if (err) return err; /* set user address for later reference (used when freeing the memory ) */ entry->v_usr_addr = vma->vm_start; /* should memory be uncached? */ if ( entry->flags & CMA_ENTRY_NONCACHED ) vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); /* map memory to user space */ if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, vma->vm_end-vma->vm_start, vma->vm_page_prot)) { up_write(&current->mm->mmap_sem); return -EAGAIN; } /* save mmap ops and set entry mapped flag */ vma->vm_ops = &cma_ops; entry->flags = (entry->flags & (~CMA_ENTRY_MAPPED)) | CMA_ENTRY_MAPPED; return 0; } void cma_mmap_close(struct vm_area_struct *vma) { struct cma_entry *entry; __DEBUG("cma_mmap_close()\n"); /* remove custom mapped flag */ entry = cma_entry_get_by_phy_addr(vma->vm_pgoff << PAGE_SHIFT); if ( entry != NULL ) entry->flags &= (~CMA_ENTRY_MAPPED); } static int cma_ioctl(struct file *filp, unsigned int cmd, unsigned int arg) { /* routine check */ __DEBUG("IOCTL command issued\n"); /* check validity of the cmd */ if (_IOC_TYPE(cmd) != CMA_IOCTL_MAGIC) { __ERROR("IOCTL Incorrect magic number\n"); return -ENOTTY; } if (_IOC_NR(cmd) > CMA_IOCTL_MAXNR) { __ERROR("IOCTL Command is not valid\n"); return -ENOTTY; } /* get size from userspace */ switch (cmd) { case CMA_ALLOC_CACHED: return cma_ioctl_alloc(filp, cmd, arg, CMA_ENTRY_CACHED); case CMA_ALLOC_NONCACHED: return cma_ioctl_alloc(filp, cmd, arg, CMA_ENTRY_NONCACHED); case CMA_FREE: return cma_ioctl_free(filp, cmd, arg); case CMA_GET_PHY_ADDR: return cma_ioctl_get_phy_addr(filp, cmd, arg); case CMA_GET_SIZE: return cma_ioctl_get_size(filp, cmd, arg); default: __DEBUG("This should never happen!\n"); } return 0; } static int cma_ioctl_alloc(struct file *filp, unsigned int cmd, unsigned int arg, int cached_flag) { int err; struct cma_entry *entry; __DEBUG("cma_ioctl_alloc() called!\n"); if (!access_ok(VERIFY_READ, (void __user*) arg, _IOC_SIZE(cmd))) { __DEBUG("fail to get read access to %d bytes of memory.\n", entry->size); return -EFAULT; } if (!access_ok(VERIFY_WRITE, (void __user*) arg, _IOC_SIZE(cmd))) { __DEBUG("fail to get write access to %d bytes of memory.\n", entry->size); return -EFAULT; } /* create new cma entry */ entry = kmalloc(sizeof(struct cma_entry), GFP_KERNEL); /* set entry params */ __get_user(entry->size, (typeof(&entry->size))arg); entry->pid = current->pid; entry->flags = cached_flag; /* allocate contigous memory */ entry->v_ptr = dma_alloc_coherent(NULL, entry->size, &entry->phy_addr, GFP_KERNEL); if ( entry->v_ptr == NULL ) { err = -ENOMEM; __DEBUG("==== FAILED TO ALLOCATE 0x%X BYTES OF COHERENT MEMORY ====\n", entry->size); goto error_dma_alloc_coherent; } /* add entry */ err = cma_entry_add(entry); if (err) goto error_cma_entry_add; /* put physical address to user space */ __put_user(entry->phy_addr, (typeof(&entry->phy_addr))arg); __DEBUG("allocated 0x%x bytes of coherent memory at phy_addr=0x%x\n", entry->size, entry->phy_addr); return entry->phy_addr; error_cma_entry_add: dma_free_coherent(NULL, entry->size, entry->v_ptr, entry->phy_addr); error_dma_alloc_coherent: kfree(entry); return err; } static int cma_ioctl_free(struct file *filp, unsigned int cmd, unsigned int arg) { dma_addr_t v_usr_addr; __DEBUG("cma_ioctl_free() called!\n"); if (!access_ok(VERIFY_READ, (void __user*) arg, _IOC_SIZE(cmd))) return -EFAULT; __get_user(v_usr_addr, (typeof(&v_usr_addr))arg); return cma_entry_release(v_usr_addr); } static struct cma_entry *cma_ioctl_get_entry_from_v_usr_addr(unsigned int cmd, unsigned int arg) { unsigned v_usr_addr; __DEBUG("cma_ioctl_get_entry_from_v_usr_addr() called!\n"); /* routine check */ if (!access_ok(VERIFY_READ, (void __user*) arg, _IOC_SIZE(cmd))) { __DEBUG("failed to get read access to virtual user address: 0x%x\n", arg); return NULL; } if (!access_ok(VERIFY_WRITE, (void __user*) arg, _IOC_SIZE(cmd))) { __DEBUG("failed to get write access to virtual user address: 0x%x\n", arg); return NULL; } /* get process user address */ __get_user(v_usr_addr, (typeof(&v_usr_addr))arg); /* search for appropriate entry */ return cma_entry_get_by_v_usr_addr(v_usr_addr); } static int cma_ioctl_get_phy_addr(struct file *filp, unsigned int cmd, unsigned int arg) { struct cma_entry *entry; __DEBUG("cma_ioctl_get_phy_addr() called!\n"); /* get entry */ entry = cma_ioctl_get_entry_from_v_usr_addr(cmd, arg); if (entry == NULL) { __DEBUG("cma entry has not been found.\n"); return -EFAULT; } /* put physical address into user space */ __put_user(entry->phy_addr, (typeof(&entry->phy_addr))arg); return 0; } static int cma_ioctl_get_size(struct file *filp, unsigned int cmd, unsigned int arg) { struct cma_entry *entry; __DEBUG("cma_ioctl_get_size() called!\n"); /* get entry */ entry = cma_ioctl_get_entry_from_v_usr_addr(cmd, arg); if (entry == NULL) { __DEBUG("cma_ioctl_get_size: failed to get_entry_from_v_usr_addr.\n"); return -EFAULT; } /* put size into user space */ __put_user(entry->size, (typeof(&entry->size))arg); return 0; } static int cma_init(void) { int err; __INFO("Initializeing Contigous Memory Allocator module\n"); /* obtain major number */ major = register_chrdev(0, DRIVER_NODE_NAME, &fops); if ( major < 0 ) { __ERROR("Failed to allocate major number\n"); return -major; } /* create class */ class = class_create(THIS_MODULE, DRIVER_NODE_NAME); if ( IS_ERR(class) ) { __ERROR("Failed to create class\n"); err = PTR_ERR(class); goto error_class_create; } /* create device node */ device = device_create(class, NULL, MKDEV(major, 0), NULL, DRIVER_NODE_NAME); if ( IS_ERR(device) ) { __ERROR("Failed to create device\n"); err = PTR_ERR(device); goto error_device_create; } mutex_init(&mutex_cma_list_modify); return 0; error_device_create: class_destroy(class); error_class_create: unregister_chrdev(major, DRIVER_NODE_NAME); return err; } static void cma_exit(void) { __INFO("Releasing Contigous Memory Allocator module\n"); /* TODO: walk_list_remove_pid */ device_destroy(class, MKDEV(major, 0)); class_destroy(class); unregister_chrdev(major, DRIVER_NODE_NAME); } MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Driver for allocating cached and noncached physically contigous memory. " "Exploits kernel CMA feature."); module_init(cma_init); module_exit(cma_exit); <file_sep>/vta/src/de10nano/cma_api.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * The MIT License (MIT) * * COPYRIGHT (C) 2017 Institute of Electronics and Computer Science (EDI), Latvia. * AUTHOR: <NAME> (<EMAIL>) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ /*! * Copyright (c) 2018 by Contributors * \file cma_api.cc * \brief Application layer implementation for contigous memory allocation. */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/mman.h> #include "cma_api.h" #ifndef CMA_IOCTL_MAGIC #define CMA_IOCTL_MAGIC 0xf2 #endif #define CMA_ALLOC_CACHED _IOC(_IOC_WRITE|_IOC_READ, CMA_IOCTL_MAGIC, 1, 4) #define CMA_ALLOC_NONCACHED _IOC(_IOC_WRITE|_IOC_READ, CMA_IOCTL_MAGIC, 2, 4) #define CMA_FREE _IOC(_IOC_WRITE, CMA_IOCTL_MAGIC, 3, 4) #define CMA_GET_PHY_ADDR _IOC(_IOC_WRITE|_IOC_READ, CMA_IOCTL_MAGIC, 4, 4) #define CMA_GET_SIZE _IOC(_IOC_WRITE|_IOC_READ, CMA_IOCTL_MAGIC, 5, 4) #define CMA_IOCTL_MAXNR 5 #ifndef CMA_DEBUG #define CMA_DEBUG 0 #endif #ifndef DRIVER_NODE_NAME #define DRIVER_NODE_NAME "cma" #endif #if CMA_DEBUG == 1 #define __DEBUG(fmt, args...) printf("CMA_API_DEBUG: " fmt, ##args) #else #define __DEBUG(fmt, args...) #endif #define ROUND_UP(N, S) ((((N) + (S) - 1) / (S)) * (S)) /* Private functions */ void *cma_alloc(size_t size, unsigned ioctl_cmd); /* Global file descriptor */ int cma_fd = 0; int cma_init(void) { __DEBUG("Opening \"/dev/" DRIVER_NODE_NAME "\" file\n"); cma_fd = open("/dev/" DRIVER_NODE_NAME, O_RDWR); if (cma_fd == -1) { __DEBUG("Failed to initialize api - \"%s\"\n", strerror(errno)); return -1; } return 0; } int cma_release(void) { __DEBUG("Closing \"/dev/" DRIVER_NODE_NAME "\" file\n"); if (close(cma_fd) == -1) { __DEBUG("Failed to finilize api - \"%s\"\n", strerror(errno)); return -1; } return 0; } void *cma_alloc_cached(size_t size) { return cma_alloc(size, CMA_ALLOC_CACHED); } void *cma_alloc_noncached(size_t size) { return cma_alloc(size, CMA_ALLOC_NONCACHED); } int cma_free(void *mem) { __DEBUG("Releasing contigous memory from 0x%x\n", (unsigned)mem); unsigned data, v_addr; /* save user space pointer value */ data = (unsigned)mem; v_addr = (unsigned)mem; if ( ioctl(cma_fd, CMA_GET_SIZE, &data) == -1 ) { __DEBUG("cma_free - ioctl command unsuccsessful - 0\n"); return -1; } /* data now contains size */ /* unmap memory */ munmap(mem, data); /* free cma entry */ if ( ioctl(cma_fd, CMA_FREE, &v_addr) == -1 ) { __DEBUG("cma_free - ioctl command unsuccsessful - 1\n"); return -1; } return 0; } unsigned cma_get_phy_addr(void *mem) { unsigned data; __DEBUG("Getting physical address from 0x%x\n", (unsigned)mem); /* save user space pointer value */ data = (unsigned)mem; /* get physical address */ if ( ioctl(cma_fd, CMA_GET_PHY_ADDR, &data) == -1 ) { __DEBUG("cma_free - ioctl command unsuccsessful\n"); return 0; } /* data now contains physical address */ return data; } void *cma_alloc(size_t size, unsigned ioctl_cmd) { unsigned data; void *mem; __DEBUG("Allocating 0x%x bytes of contigous memory\n", size); /* Page align size */ size = ROUND_UP(size, getpagesize()); /* ioctl cmd to allocate contigous memory */ data = (unsigned)size; if ( ioctl(cma_fd, ioctl_cmd, &data) == -1 ) { __DEBUG("cma_alloc - ioctl command unsuccsessful\n"); return NULL; } /* at this point phy_addr is written to data */ /* mmap memory */ mem = mmap(NULL, size, PROT_WRITE | PROT_READ, MAP_SHARED, cma_fd, data); if (mem == MAP_FAILED) { __DEBUG("cma_alloc - mmap unsuccsessful\n"); return NULL; } return mem; } <file_sep>/topi/python/topi/cuda/rcnn/__init__.py # pylint: disable=wildcard-import """Faster R-CNN and Mask R-CNN operators""" from .proposal import * <file_sep>/topi/python/topi/vision/rcnn/proposal.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Proposal operator""" import math import tvm def generate_anchor(ratio, scale, base_size): """Generate anchor""" w = h = float(base_size) x_ctr = 0.5 * (w - 1.) y_ctr = 0.5 * (h - 1.) size = w * h size_ratios = math.floor(size / ratio) new_w = math.floor(math.sqrt(size_ratios) + 0.5) * scale new_h = math.floor((new_w / scale * ratio) + 0.5) * scale return (x_ctr - 0.5 * (new_w - 1.0), y_ctr - 0.5 * (new_h - 1.0), x_ctr + 0.5 * (new_w - 1.0), y_ctr + 0.5 * (new_h - 1.0)) def reg_bbox(x1, y1, x2, y2, dx, dy, dw, dh): """Bounding box regression function""" bbox_w = x2 - x1 + 1.0 bbox_h = y2 - y1 + 1.0 ctr_x = x1 + 0.5 * (bbox_w - 1.0) ctr_y = y1 + 0.5 * (bbox_h - 1.0) pred_ctr_x = dx * bbox_w + ctr_x pred_ctr_y = dy * bbox_h + ctr_y pred_w = tvm.exp(dw) * bbox_w pred_h = tvm.exp(dh) * bbox_h pred_x1 = pred_ctr_x - 0.5 * (pred_w - 1.0) pred_y1 = pred_ctr_y - 0.5 * (pred_h - 1.0) pred_x2 = pred_ctr_x + 0.5 * (pred_w - 1.0) pred_y2 = pred_ctr_y + 0.5 * (pred_h - 1.0) return pred_x1, pred_y1, pred_x2, pred_y2 def reg_iou(x1, y1, x2, y2, dx1, dy1, dx2, dy2): """Bounding box regression function""" pred_x1 = x1 + dx1 pred_y1 = y1 + dy1 pred_x2 = x2 + dx2 pred_y2 = y2 + dy2 return pred_x1, pred_y1, pred_x2, pred_y2 @tvm.target.generic_func def proposal(cls_prob, bbox_pred, im_info, scales, ratios, feature_stride, threshold, rpn_pre_nms_top_n, rpn_post_nms_top_n, rpn_min_size, iou_loss): """Proposal operator. Parameters ---------- cls_prob : tvm.Tensor 4-D with shape [batch, 2 * num_anchors, height, width] bbox_pred : tvm.Tensor 4-D with shape [batch, 4 * num_anchors, height, width] im_info : tvm.Tensor 2-D with shape [batch, 3] scales : list/tuple of float Scales of anchor windoes. ratios : list/tuple of float Ratios of anchor windoes. feature_stride : int The size of the receptive field each unit in the convolution layer of the rpn, for example the product of all stride's prior to this layer. threshold : float Non-maximum suppression threshold. rpn_pre_nms_top_n : int Number of top scoring boxes to apply NMS. -1 to use all boxes. rpn_post_nms_top_n : int Number of top scoring boxes to keep after applying NMS to RPN proposals. rpn_min_size : int Minimum height or width in proposal. iou_loss : bool Usage of IoU loss. Returns ------- out : tvm.Tensor 2-D tensor with shape [batch * rpn_post_nms_top_n, 5]. The last dimension is in format of [batch_index, w_start, h_start, w_end, h_end]. """ # pylint: disable=unused-argument raise ValueError("missing register for topi.vision.rcnn.proposal") <file_sep>/src/relay/pass/combine_parallel_conv2d.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * * \file combine_parallel_conv2d.cc * \brief Combine parallel 2d convolutions into a single convolution. * * This pass replaces convolutions that share the same input node and the same * arguments (except that the number of output channels can be different) with a * single convolution. The weight of the new 2d convolution is the concatenation * of the original weights. Elemwise and broadcast ops following conv2d are also * combined if possible. * * This prevents launching multiple kernels in networks with multiple * convolution branches, such as Inception block. */ #include <tvm/relay/analysis.h> #include <tvm/relay/expr_functor.h> #include <tvm/relay/attrs/nn.h> #include <tvm/relay/attrs/transform.h> #include <tvm/relay/op_attr_types.h> #include <tvm/relay/transform.h> #include <unordered_map> #include <unordered_set> #include "./expr_subst.h" #include "./pattern_util.h" namespace tvm { namespace relay { using Branch = std::vector<const CallNode*>; using Group = std::vector<Branch>; /* Find parallel branches starting with conv2d as shown below and then group branches by kernel shape and attributes of conv2d. Conv2d can be followed by zero or more elemwise or broadcast ops. Intermediate nodes have exactly one successor. It is possible that branches meet at a point, which should be handled in ParallelConv2DCombiner. data / \ conv2d conv2d | | op op | | */ class BranchGroupFinder : private ExprVisitor { public: std::vector<Group> Find(const Expr& expr) { static const Op& conv2d = Op::Get("nn.conv2d"); this->VisitExpr(expr); std::vector<Group> groups; for (const auto& root : conv_roots_) { const auto& children = children_map_.at(root); size_t ngroups = groups.size(); for (const CallNode* child : children) { if (!child->op.same_as(conv2d)) continue; auto&& branch = CreateBranch(child); // add the branch to a group, or create a new group auto it = std::find_if(groups.begin() + ngroups, groups.end(), [&](const Group& group) { CHECK(!group.empty() && !group[0].empty()); return IsCompatibleConv2D(child, group[0][0]); }); if (it != groups.end()) { it->push_back(branch); } else { groups.emplace_back(); // each group has at least one branch groups.back().push_back(branch); } } } return groups; } private: std::unordered_set<Expr, NodeHash, NodeEqual> conv_roots_; std::unordered_map<Expr, std::vector<const CallNode*>, NodeHash, NodeEqual> children_map_; // Two 2d convolutions can be combined if they have the same attributes or // only have different output channels. bool IsCompatibleConv2D(const CallNode* a, const CallNode* b) { AttrsEqual eq; static const Layout kOIHW("OIHW"); const auto* attrs_a = a->attrs.as<Conv2DAttrs>(); const auto* attrs_b = b->attrs.as<Conv2DAttrs>(); CHECK(attrs_a); CHECK(attrs_b); const auto* tweight_a = a->args[1]->type_as<TensorTypeNode>(); const auto* tweight_b = b->args[1]->type_as<TensorTypeNode>(); const auto shape_a = BijectiveLayoutNode::make( Layout(attrs_a->kernel_layout), kOIHW).ForwardShape(tweight_a->shape); const auto shape_b = BijectiveLayoutNode::make( Layout(attrs_b->kernel_layout), kOIHW).ForwardShape(tweight_b->shape); return eq(attrs_a->strides, attrs_b->strides) && eq(attrs_a->padding, attrs_b->padding) && eq(attrs_a->dilation, attrs_b->dilation) && eq(attrs_a->groups, attrs_b->groups) && eq(attrs_a->data_layout, attrs_b->data_layout) && eq(attrs_a->kernel_layout, attrs_b->kernel_layout) && eq(attrs_a->out_dtype, attrs_b->out_dtype) && eq(attrs_a->out_layout, attrs_b->out_layout) && eq(shape_a[2], shape_b[2]) && eq(shape_a[3], shape_b[3]); } // Create a branch starting from conv2d. Branch CreateBranch(const CallNode* conv) { static auto fpattern = Op::GetAttr<TOpPattern>("TOpPattern"); // each branch has at least one element, the first element is always conv2d Branch branch{conv}; auto it = children_map_.find(GetRef<Expr>(branch.back())); while (it != children_map_.end() && it->second.size() == 1) { const CallNode* call = it->second[0]; auto pattern = fpattern[Downcast<Op>(call->op)]; if (pattern <= kBroadcast) { branch.push_back(call); it = children_map_.find(GetRef<Expr>(branch.back())); } else { break; } } return branch; } void VisitExpr_(const CallNode* n) final { static const Op& conv2d = Op::Get("nn.conv2d"); ExprVisitor::VisitExpr_(n); if (n->op.same_as(conv2d) && n->attrs.as<Conv2DAttrs>()->groups == 1) { conv_roots_.insert(n->args[0]); children_map_[n->args[0]].push_back(n); } else { for (size_t i = 0; i < n->args.size(); i++) { children_map_[n->args[i]].push_back(n); } } } }; class ParallelConv2DCombiner { public: explicit ParallelConv2DCombiner(uint64_t min_num_branches) : min_num_branches_(min_num_branches) { } Expr Combine(const Expr& expr) { auto groups = BranchGroupFinder().Find(expr); for (const Group& group : groups) { if (group.size() < min_num_branches_) { continue; } CombineBranches(group); } return ExprSubst(expr, std::move(subst_map_)); } private: std::unordered_map<Expr, Expr, NodeHash, NodeEqual> subst_map_; uint64_t min_num_branches_; std::tuple<Expr, IndexExpr> TransformWeight(const Group& branches) { int64_t num_filters = 0; // number of filters of the transformed weight Array<Expr> weights; for (const auto& branch : branches) { auto conv2d = branch[0]; weights.push_back(conv2d->args[1]); auto channels = GetConv2DSuperChannelsDim(conv2d); num_filters += channels; } auto index = branches[0][0]->attrs.as<Conv2DAttrs>()->kernel_layout.find('O'); CHECK_NE(index, std::string::npos); return std::make_tuple(MakeConcatenate(TupleNode::make(weights), index), MakeConstScalar(Int(32), num_filters)); } Call MakeCombinedConv2D(const Group& branches) { static const Op& conv2d = Op::Get("nn.conv2d"); Expr data = branches[0][0]->args[0]; Expr new_weight; IndexExpr new_channels; std::tie(new_weight, new_channels) = TransformWeight(branches); const CallNode* group_root = branches[0][0]; const auto* attrs = group_root->attrs.as<Conv2DAttrs>(); CHECK(attrs); const auto new_attrs = make_node<Conv2DAttrs>(); new_attrs->strides = attrs->strides; new_attrs->padding = attrs->padding; new_attrs->dilation = attrs->dilation; new_attrs->groups = attrs->groups; new_attrs->kernel_size = attrs->kernel_size; new_attrs->data_layout = attrs->data_layout; new_attrs->kernel_layout = attrs->kernel_layout; new_attrs->out_layout = attrs->out_layout; new_attrs->out_dtype = attrs->out_dtype; new_attrs->channels = new_channels; return CallNode::make(conv2d, {data, new_weight}, Attrs{new_attrs}, {}); } bool IsArgCompatible(const CallNode* a, const CallNode* b, size_t index, size_t channel_pos) { AttrsEqual eq; auto ta = a->args[index]->type_as<TensorTypeNode>(); auto tb = b->args[index]->type_as<TensorTypeNode>(); auto toutput_a = a->type_as<TensorTypeNode>(); auto toutput_b = b->type_as<TensorTypeNode>(); if (!eq(ta->dtype, tb->dtype) || ta->shape.size() != tb->shape.size()) return false; // Position of the 'C' dimension in the argument size_t arg_channel_pos = channel_pos - toutput_a->shape.size() + ta->shape.size(); // Channel super-dimension shoule be present and not broadcasted if ((arg_channel_pos > channel_pos) || // size_t overflow !eq(ta->shape[arg_channel_pos], toutput_a->shape[channel_pos]) || !eq(tb->shape[arg_channel_pos], toutput_b->shape[channel_pos])) return false; for (size_t i = 0; i < ta->shape.size(); i++) { if (i == arg_channel_pos) continue; if (!eq(ta->shape[i], tb->shape[i])) return false; } return true; } // Check if ops in depth-th level can be combined bool CheckLevel(const Group& branches, size_t depth, size_t channel_pos, size_t parent_index) { const CallNode* call = branches[0][depth]; AttrsEqual attrs_equal; // check if all branches in current depth can be combined for (auto it = branches.begin() + 1; it != branches.end(); it++) { const Branch& branch = *it; if (!branch[depth]->op.same_as(call->op) || !attrs_equal(branch[depth]->attrs, call->attrs) || branch[depth]->args.size() != call->args.size()) { return false; } if (branch[depth]->args[parent_index].get() != branch[depth - 1]) return false; // Check args for (size_t i = 0; i < call->args.size(); i++) { if (i == parent_index) continue; if (!IsArgCompatible(call, branch[depth], i, channel_pos) || !attrs_equal(call->attrs, branch[depth]->attrs)) { return false; } } } return true; } // Combine args and make the combined CallNode Call MakeCombinedCall(const Expr& data, const Group& branches, size_t depth, size_t channel_pos, size_t parent_index) { Array<Expr> new_args; const CallNode* call = branches[0][depth]; size_t ndim = call->type_as<TensorTypeNode>()->shape.size(); for (size_t i = 0; i < call->args.size(); i++) { if (i == parent_index) { new_args.push_back(data); continue; } size_t arg_ndim = call->args[i]->type_as<TensorTypeNode>()->shape.size(); size_t arg_channel_pos = channel_pos - ndim + arg_ndim; Array<Expr> tuple; for (const auto& branch : branches) { tuple.push_back(branch[depth]->args[i]); } auto concat = MakeConcatenate(TupleNode::make(tuple), arg_channel_pos); new_args.push_back(std::move(concat)); } return CallNode::make(call->op, new_args, call->attrs, {}); } // Replace output of each branch with slices of the combined output void UpdateGroupOutput(const Expr& data, const Group& branches, size_t depth, size_t channel_pos) { int64_t index = 0; for (const auto& branch : branches) { const CallNode* conv2d = branch[0]; int64_t channels = GetConv2DSuperChannelsDim(conv2d); Array<Integer> begin; Array<Integer> end; for (size_t i = 0; i < channel_pos; i++) { begin.push_back(0); end.push_back(NullValue<Integer>()); } begin.push_back(index); index += channels; end.push_back(index); auto slice = MakeStridedSlice(data, std::move(begin), std::move(end), Array<Integer>{}); subst_map_[GetRef<Expr>(branch[depth])] = slice; } } // Combine branches in a group. Conv2d in different branches in the same group are safe to // combine. Subsequent ops may or may not be combined. We start from conv2d and try to // combine ops from all branches in the same depth. void CombineBranches(const Group& branches) { Call combined = MakeCombinedConv2D(branches); auto conv_param = combined->attrs.as<Conv2DAttrs>(); const std::string& layout = conv_param->out_layout == "" ? conv_param->data_layout : conv_param->out_layout; size_t channel_pos = layout.find('C'); CHECK_NE(channel_pos, std::string::npos); auto it = std::min_element(branches.begin(), branches.end(), [](const Branch& branch_a, const Branch& branch_b) { return branch_a.size() < branch_b.size(); }); size_t depth = it->size(); size_t i; // starting from 1 to skip the conv2d for (i = 1; i < depth; i++) { size_t parent_index; for (parent_index = 0; parent_index < branches[0][i]->args.size(); parent_index++) { if (branches[0][i]->args[parent_index].get() == branches[0][i - 1]) break; } CHECK_NE(parent_index, branches[0][i]->args.size()); if (!CheckLevel(branches, i, channel_pos, parent_index)) break; combined = MakeCombinedCall(combined, branches, i, channel_pos, parent_index); } UpdateGroupOutput(combined, branches, i - 1, channel_pos); } }; /*! \brief Combine parallel conv2d if number of branches >= min_num_branches */ Expr CombineParallelConv2D(const Expr& expr, uint64_t min_num_branches) { return ParallelConv2DCombiner(min_num_branches).Combine(expr); } namespace transform { Pass CombineParallelConv2D(uint64_t min_num_branches) { runtime::TypedPackedFunc<Function(Function, Module, PassContext)> pass_func = [=](Function f, Module m, PassContext pc) { return Downcast<Function>(CombineParallelConv2D(f, min_num_branches)); }; return CreateFunctionPass(pass_func, 4, "CombineParallelConv2d", {ir::StringImm::make("InferType")}); } TVM_REGISTER_API("relay._transform.CombineParallelConv2D") .set_body_typed(CombineParallelConv2D); } // namespace transform } // namespace relay } // namespace tvm <file_sep>/src/runtime/vulkan/vulkan_module.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file metal_module.h * \brief Execution handling of Metal kernels */ #ifndef TVM_RUNTIME_VULKAN_VULKAN_MODULE_H_ #define TVM_RUNTIME_VULKAN_VULKAN_MODULE_H_ #include <tvm/runtime/packed_func.h> #include <dmlc/type_traits.h> #include <memory> #include <vector> #include <string> #include <unordered_map> #include "../meta_data.h" namespace tvm { namespace runtime { /*! \brief Maximum number of GPU supported in VulkanModule. */ static constexpr const int kVulkanMaxNumDevice = 8; /*! \brief TVM Vulkan binary pack magic number */ static constexpr const int kVulkanModuleMagic = 0x02700027; /*! * \brief A single VK shader program * * Due to the global resource declaration. * Current SPIRV only allows one entry program per shader, * making it less useful for a Module like system. * * Instead we pass in map of str->VulkanShader until * there is a native solution available. */ struct VulkanShader { /*! \brief header flag */ uint32_t flag{0}; /*! \brief Data segment */ std::vector<uint32_t> data; void Save(dmlc::Stream *writer) const; bool Load(dmlc::Stream *reader); }; /*! * \brief create a metal module from data. * * \param pmap The program map. * \param fmap The function information map. * \param source Optional, source code. */ Module VulkanModuleCreate( std::unordered_map<std::string, VulkanShader> smap, std::unordered_map<std::string, FunctionInfo> fmap, std::string source); } // namespace runtime } // namespace tvm namespace dmlc { DMLC_DECLARE_TRAITS(has_saveload, ::tvm::runtime::VulkanShader, true); } // namespace dmlc #endif // TVM_RUNTIME_VULKAN_VULKAN_MODULE_H_ <file_sep>/python/tvm/relay/prelude.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=no-else-return, unidiomatic-typecheck, invalid-name """A prelude containing useful global functions and ADT definitions.""" from .ty import GlobalTypeVar, TypeVar, FuncType, TupleType, scalar_type from .expr import Var, Function, GlobalVar, Let, If, Tuple, TupleGetItem, const from .op.tensor import add, subtract, equal from .adt import Constructor, TypeData, Clause, Match from .adt import PatternConstructor, PatternVar, PatternWildcard, PatternTuple from .module import Module class Prelude: """Contains standard definitions.""" def define_list_adt(self): """Defines a LISP-style list ADT. An empty list is represented by nil(). A member x can be appended to the front of a list l via the constructor cons(x, l).""" self.l = GlobalTypeVar("list") a = TypeVar("a") self.nil = Constructor("nil", [], self.l) self.cons = Constructor("cons", [a, self.l(a)], self.l) self.mod[self.l] = TypeData(self.l, [a], [self.nil, self.cons]) def define_list_hd(self): """Defines a function to get the head of a list. Assume the list has at least one element. hd(l) : list[a] -> a """ self.hd = GlobalVar("hd") a = TypeVar("a") x = Var("x", self.l(a)) y = Var("y") z = Var("z") cons_case = Clause(PatternConstructor(self.cons, [PatternVar(y), PatternVar(z)]), y) self.mod[self.hd] = Function([x], Match(x, [cons_case], False), a, [a]) def define_list_tl(self): """Defines a function to get the tail of a list. tl(l) : list[a] -> list[a] """ self.tl = GlobalVar("tl") a = TypeVar("a") x = Var("x", self.l(a)) y = Var("y") z = Var("z") cons_case = Clause(PatternConstructor(self.cons, [PatternVar(y), PatternVar(z)]), z) self.mod[self.tl] = Function([x], Match(x, [cons_case], False), self.l(a), [a]) def define_list_nth(self): """Defines a function to get the nth element of a list. nth(l) : list[a] -> Tensor[(), int32] -> a """ self.nth = GlobalVar("nth") a = TypeVar("a") x = Var("x", self.l(a)) n = Var("n", scalar_type('int32')) body = If(equal(n, const(0)), self.hd(x), self.nth(self.tl(x), subtract(n, const(1)))) self.mod[self.nth] = Function([x, n], body, a, [a]) def define_list_update(self): """Defines a function to update the nth element of a list and return the updated list. update(l, i, v) : list[a] -> Tensor[(), int32] -> a -> list[a] """ self.update = GlobalVar("update") a = TypeVar("a") l = Var("l", self.l(a)) n = Var("n", scalar_type('int32')) v = Var("v", a) body = If(equal(n, const(0)), self.cons(v, self.tl(l)), self.cons(self.hd(l), self.update(self.tl(l), subtract(n, const(1)), v))) self.mod[self.update] = Function([l, n, v], body, self.l(a), [a]) def define_list_map(self): """Defines a function for mapping a function over a list's elements. That is, map(f, l) returns a new list where the ith member is f applied to the ith member of l. map(f, l) : fn<a, b>(fn(a) -> b, list[a]) -> list[b] """ self.map = GlobalVar("map") a = TypeVar("a") b = TypeVar("b") f = Var("f", FuncType([a], b)) x = Var("x", self.l(a)) y = Var("y") z = Var("z") nil_case = Clause(PatternConstructor(self.nil), self.nil()) cons_case = Clause(PatternConstructor(self.cons, [PatternVar(y), PatternVar(z)]), self.cons(f(y), self.map(f, z))) self.mod[self.map] = Function([f, x], Match(x, [nil_case, cons_case]), self.l(b), [a, b]) def define_list_foldl(self): """Defines a left-way fold over a list. foldl(f, z, l) : fn<a, b>(fn(a, b) -> a, a, list[b]) -> a foldl(f, z, cons(a1, cons(a2, cons(a3, cons(..., nil))))) evaluates to f(...f(f(f(z, a1), a2), a3)...) """ self.foldl = GlobalVar("foldl") a = TypeVar("a") b = TypeVar("b") f = Var("f", FuncType([a, b], a)) av = Var("av", a) bv = Var("bv", self.l(b)) y = Var("y") z = Var("z") nil_case = Clause(PatternConstructor(self.nil), av) cons_case = Clause(PatternConstructor(self.cons, [PatternVar(y), PatternVar(z)]), self.foldl(f, f(av, y), z)) self.mod[self.foldl] = Function([f, av, bv], Match(bv, [nil_case, cons_case]), a, [a, b]) def define_list_foldr(self): """Defines a right-way fold over a list. foldr(f, l, z) : fn<a, b>(fn(a, b) -> b, list[a], b) -> b foldr(f, cons(a1, cons(a2, cons(..., cons(an, nil)))), z) evalutes to f(a1, f(a2, f(..., f(an, z)))...) """ self.foldr = GlobalVar("foldr") a = TypeVar("a") b = TypeVar("b") f = Var("f", FuncType([a, b], b)) av = Var("av", self.l(a)) bv = Var("bv", b) y = Var("y") z = Var("z") nil_case = Clause(PatternConstructor(self.nil), bv) cons_case = Clause(PatternConstructor(self.cons, [PatternVar(y), PatternVar(z)]), f(y, self.foldr(f, bv, z))) self.mod[self.foldr] = Function([f, bv, av], Match(av, [nil_case, cons_case]), b, [a, b]) def define_list_foldr1(self): """Defines a right-way fold over a nonempty list. foldr1(f, l) : fn<a>(fn(a, a) -> a, list[a]) -> a foldr1(f, cons(a1, cons(a2, cons(..., cons(an, nil))))) evalutes to f(a1, f(a2, f(..., f(an-1, an)))...) """ self.foldr1 = GlobalVar("foldr1") a = TypeVar("a") f = Var("f", FuncType([a, a], a)) av = Var("av", self.l(a)) x = Var("x") y = Var("y") z = Var("z") one_case = Clause(PatternConstructor(self.cons, [PatternVar(x), PatternConstructor(self.nil)]), x) cons_case = Clause(PatternConstructor(self.cons, [PatternVar(y), PatternVar(z)]), f(y, self.foldr1(f, z))) self.mod[self.foldr1] = Function([f, av], Match(av, [one_case, cons_case], False), a, [a]) def define_list_concat(self): """Defines a function that concatenates two lists. concat(l1, l2) : fn<a>(list[a], list[a]) -> list[a]""" self.concat = GlobalVar("concat") a = TypeVar("a") l1 = Var("l1", self.l(a)) l2 = Var("l2", self.l(a)) h = Var("h") t = Var("t") updater = Function([h, t], self.cons(h, t)) self.mod[self.concat] = Function([l1, l2], self.foldr(updater, l2, l1), self.l(a), [a]) def define_list_filter(self): """Defines a function that filters a list. filter(f, l) : fn<a>(fn(a) -> Tensor[(), bool], list[a]) -> list[a] It returns the sublist of l consisting of the elements for which f returns true. """ self.filter = GlobalVar("filter") a = TypeVar("a") f = Var("f", FuncType([a], scalar_type("bool"))) l = Var("l", self.l(a)) h = Var("h") t = Var("t") nil_case = Clause(PatternConstructor(self.nil), self.nil()) cons_case = Clause(PatternConstructor(self.cons, [PatternVar(h), PatternVar(t)]), If(f(h), self.cons(h, self.filter(f, t)), self.filter(f, t))) self.mod[self.filter] = Function([f, l], Match(l, [nil_case, cons_case]), self.l(a), [a]) def define_list_zip(self): """Defines a function that combines two lists into a list of tuples of their elements. zip(l, m) : fn<a, b>(list[a], list[b]) -> list[(a, b)] The zipped list will be the length of the shorter list. """ self.zip = GlobalVar("zip") a = TypeVar("a") b = TypeVar("b") l1 = Var("l1") l2 = Var("l2") h1 = Var("h1") h2 = Var("h2") t1 = Var("t1") t2 = Var("t2") cons_case = Clause(PatternTuple([PatternConstructor(self.cons, [PatternVar(h1), PatternVar(t1)]), PatternConstructor(self.cons, [PatternVar(h2), PatternVar(t2)])]), self.cons(Tuple([h1, h2]), self.zip(t1, t2))) nil_case = Clause(PatternWildcard(), self.nil()) self.mod[self.zip] = Function([l1, l2], Match(Tuple([l1, l2]), [cons_case, nil_case]), self.l(TupleType([a, b])), [a, b]) def define_list_rev(self): """Defines a function that reverses a list. rev(l) : fn<a>(list[a]) -> list[a] """ self.rev = GlobalVar("rev") a = TypeVar("a") l = Var("l", self.l(a)) x = Var("x") y = Var("y") updater = Function([y, x], self.cons(x, y)) self.mod[self.rev] = Function([l], self.foldl(updater, self.nil(), l), self.l(a), [a]) def define_list_map_accumr(self): """Defines an accumulative map, which is a fold that simulataneously updates an accumulator value and a list of results. map_accumr(f, s, l) : fn<a, b, c>(fn(a, b) -> (a, c), a, list[b]) -> (a, list[c]) This map proceeds through l from right to left. """ self.map_accumr = GlobalVar("map_accumr") a = TypeVar("a") b = TypeVar("b") c = TypeVar("c") f = Var("f", FuncType([a, b], TupleType([a, c]))) acc = Var("acc", a) l = Var("l", self.l(b)) v = Var("v", b) p = Var("p", TupleType([a, self.l(c)])) f_out = Var("f_out", TupleType([a, c])) updater = Function([v, p], Let(f_out, f(TupleGetItem(p, 0), v), Tuple([TupleGetItem(f_out, 0), self.cons(TupleGetItem(f_out, 1), TupleGetItem(p, 1))])), TupleType([a, self.l(c)])) self.mod[self.map_accumr] = Function([f, acc, l], self.foldr(updater, Tuple([acc, self.nil()]), l), TupleType([a, self.l(c)]), [a, b, c]) def define_list_map_accuml(self): """Defines an accumulative map, which is a fold that simulataneously updates an accumulator value and a list of results. map_accuml(f, s, l) : fn<a, b, c>(fn(a, b) -> (a, c), a, list[b]) -> (a, list[c]) This map proceeds through l from left to right. """ self.map_accuml = GlobalVar("map_accuml") a = TypeVar("a") b = TypeVar("b") c = TypeVar("c") f = Var("f", FuncType([a, b], TupleType([a, c]))) acc = Var("acc", a) l = Var("l", self.l(b)) v = Var("v", b) p = Var("p", TupleType([a, self.l(c)])) f_out = Var("f_out", TupleType([a, c])) updater = Function([p, v], Let(f_out, f(TupleGetItem(p, 0), v), Tuple([TupleGetItem(f_out, 0), self.cons(TupleGetItem(f_out, 1), TupleGetItem(p, 1))])), TupleType([a, self.l(c)])) self.mod[self.map_accuml] = Function([f, acc, l], self.foldl(updater, Tuple([acc, self.nil()]), l), TupleType([a, self.l(c)]), [a, b, c]) def define_optional_adt(self): """Defines an optional ADT, which can either contain some other type or nothing at all.""" self.optional = GlobalTypeVar("optional") a = TypeVar("a") self.some = Constructor("some", [a], self.optional) self.none = Constructor("none", [], self.optional) self.mod[self.optional] = TypeData(self.optional, [a], [self.some, self.none]) def define_list_unfoldr(self): """Defines a function that builds up a list starting from a seed value. unfoldr(f, s) : fn<a, b>(fn(a) -> Optional[(a, b)], a) -> list[b] f returns an option containing a new seed and an output value. f will continue to be called on the new seeds until it returns None. All the output values will be combined into a list, right to left. """ self.unfoldr = GlobalVar("unfoldr") a = TypeVar("a") b = TypeVar("b") f = Var("f", FuncType([a], self.optional(TupleType([a, b])))) s = Var("s", a) p = Var("p", TupleType([a, b])) none_case = Clause(PatternConstructor(self.none), self.nil()) some_case = Clause(PatternConstructor(self.some, [PatternVar(p)]), self.cons(TupleGetItem(p, 1), self.unfoldr(f, TupleGetItem(p, 0)))) self.mod[self.unfoldr] = Function([f, s], Match(f(s), [none_case, some_case]), self.l(b), [a, b]) def define_list_unfoldl(self): """Defines a function that builds up a list starting from a seed value. unfoldl(f, s) : fn<a, b>(fn(a) -> Optional[(a, b)], a) -> list[b] f returns an option containing a new seed and an output value. f will continue to be called on the new seeds until it returns None. All the output values will be combined into a list, left to right. """ self.unfoldl = GlobalVar("unfoldl") a = TypeVar("a") b = TypeVar("b") f = Var("f", FuncType([a], self.optional(TupleType([a, b])))) s = Var("s", a) # easiest way to implement is to do a right unfold and reverse self.mod[self.unfoldl] = Function([f, s], self.rev(self.unfoldr(f, s)), self.l(b), [a, b]) def define_list_sum(self): """Defines a function that computes the sum of a list of integer scalars.""" self.sum = GlobalVar("sum") a = Var("a", self.l(scalar_type('int32'))) x = Var('x') y = Var('y') addf = Function([x, y], add(x, y)) self.mod[self.sum] = Function([a], self.foldl(addf, const(0), a)) def define_list_length(self): """Defines a function that returns the length of a list""" self.length = GlobalVar("length") a = TypeVar("a") x = Var("x", self.l(a)) y = Var("y") nil_case = Clause(PatternConstructor(self.nil), const(0)) cons_case = Clause(PatternConstructor(self.cons, [PatternWildcard(), PatternVar(y)]), add(const(1), self.length(y))) self.mod[self.length] = Function([x], Match(x, [nil_case, cons_case]), scalar_type('int32'), [a]) def define_tree_adt(self): """Defines a tree ADT. A tree can contain any type. It has only one constructor, rose(x, l), where x is the content of that point of the tree and l is a list of more trees of the same type. A leaf is thus rose(x, nil()). """ self.tree = GlobalTypeVar("tree") a = TypeVar("a") self.rose = Constructor("rose", [a, self.l(self.tree(a))], self.tree) self.mod[self.tree] = TypeData(self.tree, [a], [self.rose]) def define_tree_map(self): """Defines a function that maps over a tree. The function is applied to each subtree's contents. Signature: fn<a, b>(f : fn(a) -> b, t : tree[a]) -> tree[b] """ self.tmap = GlobalVar("tmap") a = TypeVar("a") b = TypeVar("b") t = Var("t", self.tree(a)) f = Var("f", FuncType([a], b)) x = Var("x", self.tree(a)) y = Var("y") z = Var("z") rose_case = Clause(PatternConstructor(self.rose, [PatternVar(y), PatternVar(z)]), self.rose(f(y), self.map(Function([x], self.tmap(f, x)), z))) self.mod[self.tmap] = Function([f, t], Match(t, [rose_case]), self.tree(b), [a, b]) def define_tree_size(self): """Defines a function that computes the size of a tree. Signature: fn<a>(t : tree[a]) -> Tensor[(), int32] """ self.size = GlobalVar("size") a = TypeVar("a") t = Var("t", self.tree(a)) z = Var("z") rose_case = Clause(PatternConstructor(self.rose, [PatternWildcard(), PatternVar(z)]), add(const(1), self.sum(self.map(self.size, z)))) self.mod[self.size] = Function([t], Match(t, [rose_case]), scalar_type('int32'), [a]) def define_iterate(self): """Defines a function that take a number n and a function f; returns a closure that takes an argument and applies f n times to its argument. Signature: fn<a>(f : fn(a) -> a, n : Tensor[(), int32]) -> fn(a) -> a """ self.iterate = GlobalVar("iterate") a = TypeVar("a") f = Var("f", FuncType([a], a)) x = Var("x", scalar_type('int32')) body = If(equal(x, const(0)), self.id, self.compose(f, self.iterate(f, subtract(x, const(1))))) self.mod[self.iterate] = Function([f, x], body, FuncType([a], a), [a]) def load_prelude(self): """ Parses the portions of the Prelude written in Relay's text format and adds them to the module. """ # TODO(@jroesch): we should remove this helper when we port over prelude self.mod.import_from_std("prelude.rly") self.id = self.mod.get_global_var("id") self.compose = self.mod.get_global_var("compose") def __init__(self, mod=None): if mod is None: mod = Module() self.mod = mod self.load_prelude() self.define_list_adt() self.define_list_hd() self.define_list_tl() self.define_list_map() self.define_list_foldl() self.define_list_foldr() self.define_list_foldr1() self.define_list_concat() self.define_list_filter() self.define_list_zip() self.define_list_rev() self.define_list_map_accumr() self.define_list_map_accuml() self.define_optional_adt() self.define_list_unfoldr() self.define_list_unfoldl() self.define_list_length() self.define_list_nth() self.define_list_update() self.define_list_sum() self.define_tree_adt() self.define_tree_map() self.define_tree_size() self.define_iterate() <file_sep>/topi/python/topi/nn/__init__.py # pylint: disable=wildcard-import """Neural network operators""" from __future__ import absolute_import as _abs from .conv2d import * from .deformable_conv2d import * from .depthwise_conv2d import * from .elemwise import * from .dilate import * from .flatten import * from .dense import * from .mapping import * from .pooling import * from .softmax import * from .conv2d_transpose import * from .bnn import * from .upsampling import * from .local_response_norm import * from .bitserial_conv2d import * from .bitserial_dense import * from .l2_normalize import * from .batch_matmul import * from .sparse import * from .pad import * <file_sep>/include/tvm/base.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file tvm/base.h * \brief Defines the base data structure */ #ifndef TVM_BASE_H_ #define TVM_BASE_H_ #include <dmlc/logging.h> #include <dmlc/registry.h> #include <tvm/node/node.h> #include <string> #include <memory> #include <functional> #include <utility> #include "runtime/registry.h" namespace tvm { using ::tvm::Node; using ::tvm::NodeRef; using ::tvm::AttrVisitor; /*! * \brief Macro to define common node ref methods. * \param TypeName The name of the NodeRef. * \param BaseTypeName The Base type. * \param NodeName The node container type. */ #define TVM_DEFINE_NODE_REF_METHODS(TypeName, BaseTypeName, NodeName) \ TypeName() {} \ explicit TypeName(::tvm::NodePtr<::tvm::Node> n) : BaseTypeName(n) {} \ const NodeName* operator->() const { \ return static_cast<const NodeName*>(node_.get()); \ } \ operator bool() const { return this->defined(); } \ using ContainerType = NodeName; /*! * \brief Macro to define CopyOnWrite function in a NodeRef. * \param NodeName The Type of the Node. * * CopyOnWrite will generate a unique copy of the internal node. * The node will be copied if it is referenced by multiple places. * The function returns the raw pointer to the node to allow modification * of the content. * * \code * * MyCOWNodeRef ref, ref2; * ref2 = ref; * ref.CopyOnWrite()->value = new_value; * assert(ref2->value == old_value); * assert(ref->value == new_value); * * \endcode */ #define TVM_DEFINE_NODE_REF_COW(NodeName) \ NodeName* CopyOnWrite() { \ CHECK(node_ != nullptr); \ if (!node_.unique()) { \ NodePtr<NodeName> n = make_node<NodeName>(*(operator->())); \ NodePtr<Node>(std::move(n)).swap(node_); \ } \ return static_cast<NodeName*>(node_.get()); \ } /*! \brief Macro to make it easy to define node ref type given node */ #define TVM_DEFINE_NODE_REF(TypeName, NodeName) \ class TypeName : public ::tvm::NodeRef { \ public: \ TVM_DEFINE_NODE_REF_METHODS(TypeName, ::tvm::NodeRef, NodeName); \ }; \ /*! * \brief Macro to make it easy to define node ref type that * has a CopyOnWrite member function. */ #define TVM_DEFINE_COW_NODE_REF(TypeName, BaseType, NodeName) \ class TypeName : public BaseType { \ public: \ TVM_DEFINE_NODE_REF_METHODS(TypeName, BaseType, NodeName); \ TVM_DEFINE_NODE_REF_COW(NodeName); \ }; /*! * \brief RAII wrapper function to enter and exit a context object * similar to python's with syntax. * * \code * // context class * class MyContext { * private: * friend class With<MyContext>; MyContext(arguments); * void EnterWithScope(); * void ExitWithScope(); * }; * * { * With<MyContext> scope(arguments); * // effect take place. * } * \endcode * * \tparam ContextType Type of the context object. */ template<typename ContextType> class With { public: /*! * \brief constructor. * Enter the scope of the context. */ template<typename ...Args> explicit With(Args&& ...args) : ctx_(std::forward<Args>(args)...) { ctx_.EnterWithScope(); } /*! \brief destructor, leaves the scope of the context. */ ~With() DMLC_THROW_EXCEPTION { ctx_.ExitWithScope(); } private: /*! \brief internal context type. */ ContextType ctx_; }; /*! * \brief save the node as well as all the node it depends on as json. * This can be used to serialize any TVM object * * \return the string representation of the node. */ std::string SaveJSON(const NodeRef& node); /*! * \brief Internal implementation of LoadJSON * Load tvm Node object from json and return a shared_ptr of Node. * \param json_str The json string to load from. * * \return The shared_ptr of the Node. */ NodePtr<Node> LoadJSON_(std::string json_str); /*! * \brief Load the node from json string. * This can be used to deserialize any TVM object. * * \param json_str The json string to load from. * * \tparam NodeType the nodetype * * \code * Expr e = LoadJSON<Expr>(json_str); * \endcode */ template<typename NodeType, typename = typename std::enable_if<std::is_base_of<NodeRef, NodeType>::value>::type > inline NodeType LoadJSON(const std::string& json_str) { return NodeType(LoadJSON_(json_str)); } /*! * \brief Registry entry for NodeFactory. * * There are two types of Nodes that can be serialized. * The normal node requires a registration a creator function that * constructs an empty Node of the corresponding type. * * The global singleton(e.g. global operator) where only global_key need to be serialized, * in this case, FGlobalKey need to be defined. */ struct NodeFactoryReg { /*! * \brief creator function. * \param global_key Key that identifies a global single object. * If this is not empty then FGlobalKey * \return The created function. */ using FCreate = std::function<NodePtr<Node>(const std::string& global_key)>; /*! * \brief Global key function, only needed by global objects. * \param node The node pointer. * \return node The global key to the node. */ using FGlobalKey = std::function<std::string(const Node* node)>; /*! \brief registered name */ std::string name; /*! * \brief The creator function */ FCreate fcreator = nullptr; /*! * \brief The global key function. */ FGlobalKey fglobal_key = nullptr; // setter of creator NodeFactoryReg& set_creator(FCreate f) { // NOLINT(*) this->fcreator = f; return *this; } // setter of creator NodeFactoryReg& set_global_key(FGlobalKey f) { // NOLINT(*) this->fglobal_key = f; return *this; } // global registry singleton TVM_DLL static ::dmlc::Registry<::tvm::NodeFactoryReg> *Registry(); }; /*! * \brief Register a Node type * \note This is necessary to enable serialization of the Node. */ #define TVM_REGISTER_NODE_TYPE(TypeName) \ static DMLC_ATTRIBUTE_UNUSED ::tvm::NodeFactoryReg & __make_Node ## _ ## TypeName ## __ = \ ::tvm::NodeFactoryReg::Registry()->__REGISTER__(TypeName::_type_key) \ .set_creator([](const std::string&) { return ::tvm::make_node<TypeName>(); }) #define TVM_STRINGIZE_DETAIL(x) #x #define TVM_STRINGIZE(x) TVM_STRINGIZE_DETAIL(x) #define TVM_DESCRIBE(...) describe(__VA_ARGS__ "\n\nFrom:" __FILE__ ":" TVM_STRINGIZE(__LINE__)) /*! * \brief Macro to include current line as string */ #define TVM_ADD_FILELINE "\n\nDefined in " __FILE__ ":L" TVM_STRINGIZE(__LINE__) } // namespace tvm #endif // TVM_BASE_H_ <file_sep>/tests/python/relay/test_pass_eta_expand.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from tvm import relay import tvm.relay.module as _module import tvm.relay.transform as _transform def test_eta_expand_basic(): x = relay.var('x', 'int32') orig = relay.Function([x], x) mod = _module.Module.from_expr(orig) seq = _transform.Sequential([_transform.EtaExpand()]) with _transform.PassContext(opt_level=3): mod = seq(mod) got = mod["main"] y = relay.var('y', 'int32') expected = relay.Function([y], orig(y)) gv = relay.GlobalVar("gv") mod[gv] = expected mod = _transform.InferType()(mod) expected = mod["gv"] assert(relay.analysis.alpha_equal(got, expected)) if __name__ == "__main__": test_eta_expand_basic() <file_sep>/topi/python/topi/cuda/ssd/__init__.py # pylint: disable=wildcard-import """VISION network operators""" from __future__ import absolute_import as _abs from .multibox import * <file_sep>/tests/python/relay/test_any.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import tvm from tvm import relay from tvm.relay.loops import while_loop from tvm.relay.testing import run_infer_type as infer_type def int32(val): return relay.const(val, 'int32') def any_dims(ndim): shape = [] for _ in range(ndim): shape.append(relay.Any()) return tuple(shape) # TODO(@wweic): because vm doesn't support heterogeneous exec, we can only test # shape function on CPU. def verify_any_broadcast(x_shape, y_shape, x_np_shape, y_np_shape, op, np_op): dtype = 'float32' x = relay.var('x', shape=x_shape, dtype=dtype) y = relay.var('y', shape=y_shape, dtype=dtype) mod = relay.module.Module() mod["main"] = relay.Function([x, y], op(x, y)) x_np = np.random.uniform(size=x_np_shape).astype(dtype) y_np = np.random.uniform(size=y_np_shape).astype(dtype) for kind in ["debug", "vm"]: ex = relay.create_executor(kind, mod=mod, ctx=tvm.cpu(), target="llvm") result = ex.evaluate()(x_np, y_np) tvm.testing.assert_allclose(result.asnumpy(), np_op(x_np, y_np)) def test_any_broadcast(): verify_any_broadcast((relay.Any(),), (3, 2), (1,), (3, 2), relay.add, np.add) verify_any_broadcast((relay.Any(), 2), (1, 2), (1, 2), (1, 2), relay.add, np.add) verify_any_broadcast((relay.Any(), 2), (1, 2), (3, 2), (1, 2), relay.add, np.add) verify_any_broadcast((relay.Any(), 2), (3, 2), (1, 2), (3, 2), relay.add, np.add) verify_any_broadcast((relay.Any(), 2), (3, relay.Any()), (1, 2), (3, 1), relay.add, np.add) # The following currently fail because topi compute treats Any as 1 # will requires auto_broadcast buffer to solve the problem # TODO(@zhiics): Fix this # verify_any_broadcast((relay.Any(),), (3, 2), (2,), (3, 2), relay.add, np.add) # verify_any_broadcast((relay.Any(), 2), (3, 2), (3, 2), (3, 2), relay.add, np.add) def test_any_concat(): x = relay.var('x', shape=(relay.Any(), 2), dtype="float32") y = relay.var('y', shape=(1, 2), dtype="float32") z = relay.op.concatenate([x, y], axis=0) mod = relay.module.Module() mod["main"] = relay.Function([x, y], z) x_np = np.random.uniform(size=(3, 2)).astype('float32') y_np = np.random.uniform(size=(1, 2)).astype('float32') for kind in ["debug", "vm"]: ex = relay.create_executor(kind, mod=mod, ctx=tvm.cpu(), target="llvm") result = ex.evaluate()(x_np, y_np) ref = np.concatenate([x_np, y_np], axis=0) tvm.testing.assert_allclose(result.asnumpy(), ref) def verify_any_reshape(x_shape, newshape, x_np_shape, out_shape): x = relay.var('x', shape=x_shape, dtype="float32") y = relay.reshape(x, newshape=newshape) mod = relay.module.Module() mod["main"] = relay.Function([x], y) data = np.random.uniform(size=x_np_shape).astype('float32') for kind in ["debug", "vm"]: ex = relay.create_executor(kind, mod=mod, ctx=tvm.cpu(), target="llvm") result = ex.evaluate()(data).asnumpy() assert result.shape == out_shape tvm.testing.assert_allclose(result.flatten(), data.flatten()) def test_any_reshape(): verify_any_reshape(any_dims(3), (1, -1), (2, 3, 4), (1, 24)) verify_any_reshape(any_dims(3), (0, -1), (2, 3, 4), (2, 12)) verify_any_reshape(any_dims(3), (0, -2), (2, 3, 4), (2, 3, 4)) verify_any_reshape(any_dims(3), (-4, 2, -1, -2), (6, 3, 4), (2, 3, 3, 4)) verify_any_reshape(any_dims(3), (-4, -1, 2, -3), (6, 3, 4), (3, 2, 12)) def verify_any_take(data_shape, indices_shape, axis, data_np_shape, indices_np_shape): mod = relay.Module() data = relay.var('data', shape=data_shape, dtype='float32') indices = relay.var('indices', shape=indices_shape, dtype='int32') y = relay.take(data, indices, axis=axis) mod["main"] = relay.Function([data, indices], y) data_np = np.random.uniform(size=data_np_shape).astype('float32') if axis is None: max_index = data_np.size else: max_index = data_np.shape[axis] indices_np = np.random.randint(max_index, size=indices_np_shape).astype('int32') ref = np.take(data_np, indices_np, axis=axis) for kind in ["debug", "vm"]: ex = relay.create_executor(kind, mod=mod, ctx=tvm.cpu(), target="llvm") result = ex.evaluate()(data_np, indices_np) tvm.testing.assert_allclose(result.asnumpy(), ref) def test_any_take(): verify_any_take(any_dims(2), (1,), 0, (4, 5), (1,)) verify_any_take(any_dims(2), (), 0, (4, 5), ()) verify_any_take(any_dims(2), (), None, (4, 5), ()) verify_any_take(any_dims(3), any_dims(2), 1, (3, 4, 5), (2, 3)) verify_any_take(any_dims(2), any_dims(3), None, (4, 5), (2, 3, 4)) verify_any_take(any_dims(2), any_dims(4), -1, (4, 5), (2, 3, 4, 5)) def test_any_shape_of(): x = relay.var('x', shape=any_dims(2), dtype='float32') y = relay.shape_of(x) mod = relay.module.Module() mod["main"] = relay.Function([x], y) data = np.random.uniform(size=(3, 4)).astype('float32') for kind in ["debug", "vm"]: ex = relay.create_executor(kind, mod=mod, ctx=tvm.cpu(), target="llvm") result = ex.evaluate()(data) tvm.testing.assert_allclose(result.asnumpy(), np.array([3,4]).astype("int64")) x = relay.var('x', shape=any_dims(3), dtype='float32') y0 = relay.shape_of(x) y1 = relay.take(y0, relay.const(1, 'int32')) mod = relay.module.Module() mod["main"] = relay.Function([x], y1) data = np.random.uniform(size=(2, 3, 4)).astype('float32') for kind in ["debug", "vm"]: ex = relay.create_executor(kind, mod=mod, ctx=tvm.cpu(), target="llvm") result = ex.evaluate()(data) tvm.testing.assert_allclose(result.asnumpy(), np.array(3).astype("int64")) def test_fused_ops(): x = relay.var('x', shape=(relay.Any(), relay.Any()), dtype='float32') y0 = x + relay.const(1.0, 'float32') y1 = y0 * relay.const(2.0, 'float32') mod = relay.module.Module() mod["main"] = relay.Function([x], y1) data = np.random.uniform(size=(5, 4)).astype('float32') for kind in ["vm"]: ex = relay.create_executor(kind, mod=mod, ctx=tvm.cpu(), target="llvm") result = ex.evaluate()(data) tvm.testing.assert_allclose(result.asnumpy(), (data + 1) * 2) def test_arange_with_dynamic_shape(): m, n, k = relay.ShapeVar('m'), relay.ShapeVar('n'), relay.ShapeVar('k') x = relay.var('x', shape=(m.var, n.var, k.var), dtype='float32') y0 = relay.shape_of(x) y1 = relay.take(y0, relay.const(0, 'int32')) y2 = relay.op.arange(y1, dtype="int32") y3 = y2 + relay.const(1, dtype="int32") data = np.random.rand(10, 5, 3).astype('float32') mod = relay.module.Module() mod["main"] = relay.Function([x], y3, type_params=[m, n, k]) for kind in ["debug", "vm"]: ex = relay.create_executor(kind, mod=mod, ctx=tvm.cpu(), target="llvm") result = ex.evaluate()(data) tvm.testing.assert_allclose(result.asnumpy(), np.array(range(10)).astype("int32")+1) def test_recursive_concat(): """ fn @concat_loop(%i: int32, %st: (any, 1)) -> (any, 1) { if (%i < 10) { let %i = reshape(cast(i, "float32"), newshape=(1, )) let %new_st = concatenate((st, i), axis=0) concat_loop(%i + 1, ) } else { st } } """ # Initial Values. i = relay.var('i', shape=(), dtype='int32') st = relay.var('st', shape=(relay.Any(), 1), dtype='int32') def _cond(i, st): return relay.op.min(relay.op.less(i, int32(10))) def _body(i, st): i_vec = relay.op.reshape(i, (1,1)) ret = relay.op.concatenate([st, i_vec], axis=0) return i + int32(1), ret loop = while_loop(_cond, [i, st], _body) start = relay.var('start', shape=(), dtype='int32') body = loop(start, relay.op.reshape(relay.const(0), newshape=(1, 1))) func = relay.Function([start], relay.TupleGetItem(body, 1)) mod = relay.module.Module() mod["main"] = func data = np.array(0.0, dtype='int32') # TODO(@jroesch): After LambdaLift pass, TypeInfer pass will fail # so currently we cannot run this test case on VM for kind in ["debug"]: ex = relay.create_executor(kind, mod=mod, ctx=tvm.cpu(), target="llvm") result = ex.evaluate()(data) ref = np.array([0] + list(range(10))).reshape((11, 1)).astype("int32") np.testing.assert_allclose(result.asnumpy(), ref) def test_recursive_concat_with_wrong_annotation(): """ v0.0.1 fn (%start: int32) { %7 = { let %while_loop = fn (%i: int32, %st: Tensor[(1, 1), int32]) { %0 = less(%i, 10) %1 = min(%0) if (%1) { %2 = add(%i, 1) %3 = reshape(%i, newshape=[1, 1]) %4 = (%st, %3) /* The result of concat should be 1,1 but it is 2, 1. */ %5 = concatenate(%4) %while_loop(%2, %5) } else { (%i, %st) } } %6 = reshape(0, newshape=[1, 1]) %while_loop(%start, %6) } %7.1 } """ # Initial Values. i = relay.var('i', shape=(), dtype='int32') st = relay.var('st', shape=(1, 1), dtype='int32') def _cond(i, st): return relay.op.min(relay.op.less(i, int32(10))) def _body(i, st): i_vec = relay.op.reshape(i, (1,1)) ret = relay.op.concatenate([st, i_vec], axis=0) return i + int32(1), ret loop = while_loop(_cond, [i, st], _body) start = relay.var('start', shape=(), dtype='int32') body = loop(start, relay.op.reshape(relay.const(0), newshape=(1, 1))) func = relay.Function([start], relay.TupleGetItem(body, 1)) try: func = infer_type(func) assert False except Exception as e: assert "in particular dimension 0 conflicts 2 does not match 1" in str(e) if __name__ == "__main__": test_any_broadcast() test_any_concat() test_any_reshape() test_any_take() test_any_shape_of() test_fused_ops() test_arange_with_dynamic_shape() test_recursive_concat() test_recursive_concat_with_wrong_annotation() <file_sep>/topi/python/topi/mali/__init__.py # pylint: disable=redefined-builtin, wildcard-import """ARM Mali GPU specific declaration and schedules.""" from __future__ import absolute_import as _abs from .conv2d import * from .depthwise_conv2d import * from .dense import * <file_sep>/src/relay/backend/vm/serializer.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2019 by Contributors * \file src/relay/backend/vm/serializer.cc * \brief Implementation of serializing APIs for the Relay VM. */ #include "serializer.h" #include <tvm/runtime/registry.h> #include <tvm/runtime/c_runtime_api.h> #include <algorithm> #include <memory> #include <sstream> #include <utility> #include <vector> #include "serialize_util.h" namespace tvm { namespace relay { namespace vm { void Serializer::Init(const VirtualMachine* vm) { vm_ = vm; // Initialize the stream object. strm_ = new dmlc::MemoryStringStream(&code_); } runtime::PackedFunc Serializer::GetFunction( const std::string& name, const std::shared_ptr<ModuleNode>& sptr_to_self) { if (name == "get_lib") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->GetLib(); }); } else if (name == "get_primitive_ops") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->GetPrimitiveOps(); }); } else if (name == "get_bytecode") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->GetBytecode(); }); } else if (name == "get_globals") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->GetGlobals(); }); } else if (name == "get_stats") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->Stats(); }); } else if (name == "serialize") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->Serialize(); }); } else { LOG(FATAL) << "Unknown packed function: " << name; return PackedFunc([sptr_to_self, name](TVMArgs args, TVMRetValue* rv) {}); } } tvm::Array<tvm::Expr> Serializer::GetPrimitiveOps() const { std::vector<tvm::Expr> ret; for (const auto& it : vm_->primitive_map) { auto packed_name = tvm::ir::StringImm::make(it.first); auto packed_index = static_cast<size_t>(it.second); if (ret.size() <= packed_index) { ret.resize(packed_index + 1); } ret[packed_index] = packed_name; } return ret; } std::string Serializer::Stats() const { std::ostringstream oss; oss << "Relay VM statistics:" << std::endl; // Get the number of constants and the shape of each of them. oss << " Constant shapes (# " << vm_->constants.size() << "): ["; for (const auto& it : vm_->constants) { auto cell = it.AsTensor(); CHECK(cell.operator->()); runtime::NDArray data = cell->data; const auto& shape = data.Shape(); // Scalar if (shape.empty()) { oss << "scalar, "; continue; } oss << "["; for (auto s : shape) { oss << s << ", "; } oss.seekp(-2, oss.cur); oss << "], " << std::endl; } if (!vm_->constants.empty()) oss.seekp(-2, oss.cur); oss << "]" << std::endl; // Get the number of globals and the name of each of them. oss << " Globals (#" << vm_->global_map.size() << "): ["; for (const auto& it : vm_->global_map) { oss << "(\"" << it.first << "\", " << it.second << ")" << ", "; } if (!vm_->global_map.empty()) oss.seekp(-2, oss.cur); oss << "]" << std::endl; // Get the number of primitive ops and the name of each of them. oss << " Primitive ops (#" << vm_->primitive_map.size() << "): ["; const auto& prim_ops = GetPrimitiveOps(); for (const auto& it : prim_ops) { oss << it << ", "; } if (!prim_ops.empty()) oss.seekp(-2, oss.cur); oss << "]" << std::endl; return oss.str(); } TVMByteArray Serializer::Serialize() { uint64_t header = kTVMVMBytecodeMagic; strm_->Write(header); std::string version = TVM_VERSION; strm_->Write(version); // Global section. SerializeGlobalSection(); // Constant section. SerializeConstantSection(); // Primitive names. SerializePrimitiveOpNames(); // Code section. SerializeCodeSection(); TVMByteArray arr; arr.data = code_.c_str(); arr.size = code_.length(); return arr; } void Serializer::SerializeGlobalSection() { auto globals = GetGlobals(); std::vector<std::string> glbs; for (const auto& it : globals) { glbs.push_back(it.as<tvm::ir::StringImm>()->value); } strm_->Write(glbs); } void Serializer::SerializeConstantSection() { std::vector<DLTensor*> arrays; for (const auto& obj : vm_->constants) { auto cell = obj.AsTensor(); runtime::NDArray data = cell->data; arrays.push_back(const_cast<DLTensor*>(data.operator->())); } strm_->Write(static_cast<uint64_t>(vm_->constants.size())); for (const auto& it : arrays) { runtime::SaveDLTensor(strm_, it); } } void Serializer::SerializePrimitiveOpNames() { auto names = GetPrimitiveOps(); std::vector<std::string> primitive_names; for (const auto& it : names) { primitive_names.push_back(it.as<tvm::ir::StringImm>()->value); } strm_->Write(primitive_names); } // Serialize a virtual machine instruction. It creates a list that contains the // hash, opcode, and all fields of an instruction. // // For example, the function signature used to create an `AllocTensor` // instruction is: // Instruction AllocTensor(std::vector<Index> shape, DLDataType dtype, RegName dst) // // The serialized form will be: // `hash 5 dtype.code dtype.bits dtype.lanes ndim dst_register val1 val2 ... valn` // // where hash is the hash of serialized instruction that is computed internally // by the `VMInstructionSerializer`. It is used for sanity check before decoding. // 5 shows opcode of `AllocTensor`, `(dtype.code dtype.bits dtype.lanes)` // represents a `DLDataType`, `ndim` is the number of dimensions, `dst_register` // is the destination register, and the rest of it together indicates the shape // of the tensor to be allocated. VMInstructionSerializer SerializeInstruction(const Instruction& instr) { std::vector<Index> fields; // Save the opcode. DLOG(INFO) << "Serializing: " << instr << std::endl; switch (instr.op) { case Opcode::Move: { // Number of fields = 2 fields.assign({instr.from, instr.dst}); break; } case Opcode::Ret: { // Number of fields = 1 fields.push_back(instr.result); break; } case Opcode::Fatal: { // Number of fields = 0 break; } case Opcode::InvokePacked: { // Number of fields = 3 + instr.arity // Note that arity includes both input arguments and outputs. We will // put all the `arity` number of fields in the end for serialization. fields.assign({instr.packed_index, instr.arity, instr.output_size}); // Save the args. fields.insert(fields.end(), instr.packed_args, instr.packed_args + instr.arity); break; } case Opcode::AllocTensor: { // Number of fields = 5 + instr.alloc_tensor.ndim // Save `DLDataType` and the dst register. const auto& dtype = instr.alloc_tensor.dtype; fields.assign({dtype.code, dtype.bits, dtype.lanes}); // The number of dimensions is not needed for constructing an // `AllocTensor` instruction as it equals to the length of the `shape` // vector. However, we save it to conveniently deserialize the instruction // because we will know how many fields are needed by the `shape` argument. fields.push_back(instr.alloc_tensor.ndim); fields.push_back(instr.dst); // Save the shape of the tensor. // Note that this field is rotated to the end of the list. fields.insert(fields.end(), instr.alloc_tensor.shape, instr.alloc_tensor.shape + instr.alloc_tensor.ndim); break; } case Opcode::AllocTensorReg: { // Number of fields = 5 fields.push_back(instr.alloc_tensor_reg.shape_register); // Save `DLDataType` and the dst register. const auto& dtype = instr.alloc_tensor.dtype; fields.assign({dtype.code, dtype.bits, dtype.lanes}); fields.push_back(instr.dst); break; } case Opcode::AllocDatatype: { // Number of fields = 3 + instr.num_fields fields.assign({instr.constructor_tag, instr.num_fields, instr.dst}); // Save the fields. fields.insert(fields.end(), instr.datatype_fields, instr.datatype_fields + instr.num_fields); break; } case Opcode::AllocClosure: { // Number of fields = 3 + instr.num_freevar fields.assign({instr.clo_index, instr.num_freevar, instr.dst}); // Save the free vars. fields.insert(fields.end(), instr.free_vars, instr.free_vars + instr.num_freevar); break; } case Opcode::If: { // Number of fields = 4 fields.assign({instr.if_op.test, instr.if_op.target, instr.if_op.true_offset, instr.if_op.false_offset}); break; } case Opcode::Invoke: { // Number of fields = 3 + instr.num_args fields.assign({instr.func_index, instr.num_args, instr.dst}); // Save the args. fields.insert(fields.end(), instr.invoke_args_registers, instr.invoke_args_registers + instr.num_args); break; } case Opcode::InvokeClosure: { // Number of fields = 3 + instr.num_closure_args fields.assign({instr.closure, instr.num_closure_args, instr.dst}); // Save the args. fields.insert(fields.end(), instr.closure_args, instr.closure_args + instr.num_closure_args); break; } case Opcode::LoadConst: { // Number of fields = 2 fields.assign({instr.const_index, instr.dst}); break; } case Opcode::LoadConsti: { // Number of fields = 2 fields.assign({instr.load_consti.val, instr.dst}); break; } case Opcode::GetField: { // Number of fields = 3 fields.assign({instr.object, instr.field_index, instr.dst}); break; } case Opcode::GetTag: { // Number of fields = 2 fields.assign({instr.get_tag.object, instr.dst}); break; } case Opcode::Goto: { // Number of fields = 1 fields.push_back(instr.pc_offset); break; } default: LOG(FATAL) << "Invalid opcode" << static_cast<int>(instr.op); break; } return VMInstructionSerializer(static_cast<Index>(instr.op), fields); } void Serializer::SerializeCodeSection() { // Save the number of functions. strm_->Write(static_cast<uint64_t>(vm_->functions.size())); for (const auto& func : vm_->functions) { // Serialize the function info. VMFunctionSerializer func_format(func.name, func.register_file_size, func.instructions.size(), func.params); func_format.Save(strm_); // Serialize each instruction. for (const auto& instr : func.instructions) { const auto& serialized_instr = SerializeInstruction(instr); serialized_instr.Save(strm_); } } } tvm::Array<tvm::Expr> Serializer::GetGlobals() const { tvm::Array<tvm::Expr> ret; std::vector<std::pair<std::string, Index> > globals(vm_->global_map.begin(), vm_->global_map.end()); auto comp = [](const std::pair<std::string, Index>& a, const std::pair<std::string, Index>& b) { return a.second < b.second; }; std::sort(globals.begin(), globals.end(), comp); for (const auto& it : globals) { ret.push_back(tvm::ir::StringImm::make(it.first)); } return ret; } std::string Serializer::GetBytecode() const { std::ostringstream oss; for (const auto& func : vm_->functions) { // Print the header of the function format. oss << "# func name, reg file size, param count, inst count:" << std::endl; oss << func.name << " " << func.register_file_size << " " << func.params.size() << " " << func.instructions.size() << std::endl; // Print pramams of a `VMFunction`. oss << "# Parameters:"<< std::endl; for (const auto& param : func.params) { oss << param << " "; } oss << std::endl; // Print the instructions of a `VMFunction`. // The part after ";" is the instruction in text format. oss << "hash, opcode, fields # inst(text):"<< std::endl; for (const auto& instr : func.instructions) { const auto& serialized_instr = SerializeInstruction(instr); oss << std::hex << "0x" << serialized_instr.Hash() << " " << std::dec << serialized_instr.opcode << " "; for (auto it : serialized_instr.fields) { oss << it << " "; } oss << " # " << instr; if (oss.str().back() != '\n') oss << std::endl; } } return oss.str(); } runtime::Module Serializer::GetLib() const { return vm_->lib; } runtime::Module CreateSerializer(const VirtualMachine* vm) { std::shared_ptr<Serializer> exec = std::make_shared<Serializer>(); exec->Init(vm); return runtime::Module(exec); } TVM_REGISTER_GLOBAL("relay._vm._Serializer") .set_body([](TVMArgs args, TVMRetValue* rv) { runtime::Module mod = args[0]; const auto* vm = dynamic_cast<VirtualMachine*>(mod.operator->()); CHECK(vm) << "Virtual machine has not been defined yet." << "\n"; *rv = CreateSerializer(vm); }); } // namespace vm } // namespace relay } // namespace tvm <file_sep>/src/relay/pass/eta_expand.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file eta_expand.cc * * \brief Add abstraction over a function. For example, abs will become (fun x -> abs x). * */ #include <tvm/relay/type.h> #include <tvm/relay/transform.h> namespace tvm { namespace relay { Expr EtaExpand(const Expr& e, const Module& mod) { tvm::Array<Var> original_params; tvm::Array<Expr> params; tvm::Array<Var> args; tvm::Array<TypeVar> original_type_params; Type ret_type; if (e->is_type<GlobalVarNode>()) { auto gvar_node = e.as_derived<GlobalVarNode>(); auto func = mod->Lookup(GetRef<GlobalVar>(gvar_node)); original_params = func->params; original_type_params = func->type_params; ret_type = func->ret_type; } else { CHECK(e->is_type<FunctionNode>()); auto func = GetRef<Function>(e.as_derived<FunctionNode>()); original_params = func->params; original_type_params = func->type_params; ret_type = func->ret_type; } for (size_t i = 0; i < original_params.size(); ++i) { auto var = VarNode::make("a", original_params[i]->type_annotation); params.push_back(var); args.push_back(var); } auto new_func = FunctionNode::make(args, CallNode::make(e, params), ret_type, original_type_params); return std::move(new_func); } namespace transform { Pass EtaExpand() { runtime::TypedPackedFunc<Function(Function, Module, PassContext)> pass_func = [=](Function f, Module m, PassContext pc) { return Downcast<Function>(EtaExpand(f, m)); }; Pass expanded = CreateFunctionPass(pass_func, 1, "EtaExpand", {}); return Sequential({expanded, InferType()}); } TVM_REGISTER_API("relay._transform.EtaExpand") .set_body_typed(EtaExpand); } // namespace transform } // namespace relay } // namespace tvm <file_sep>/vta/hardware/xilinx/Makefile # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # Directories ROOTDIR = $(CURDIR) VTA_DIR = $(CURDIR)/../.. BUILD_DIR = $(VTA_DIR)/build/hardware/xilinx SCRIPT_DIR = $(CURDIR)/scripts SRC_DIR = $(CURDIR)/src # Executables VIVADO_HLS = vivado_hls VIVADO = vivado # Process VTA JSON config VTA_CONFIG := $(CURDIR)/../../config/vta_config.py # Derive config name CONF := $(shell python ${VTA_CONFIG} --cfg-str) IP_BUILD_PATH := $(BUILD_DIR)/hls/$(CONF) HW_BUILD_PATH := $(BUILD_DIR)/vivado/$(CONF) # IP file path IP_PATH := $(BUILD_DIR)/hls/$(CONF)/vta_compute/soln/impl/ip/xilinx_com_hls_compute_1_0.zip # Bitstream file path BIT_PATH := $(BUILD_DIR)/vivado/$(CONF)/export/$(CONF).bit .PHONY: all ip bit clean clean_all all: bit ip: $(IP_PATH) bit: $(BIT_PATH) $(IP_PATH): $(SRC_DIR)/* mkdir -p $(IP_BUILD_PATH) cd $(IP_BUILD_PATH) && \ $(VIVADO_HLS) \ -f $(SCRIPT_DIR)/hls.tcl \ -tclargs \ $(VTA_DIR) \ ${VTA_CONFIG} $(BIT_PATH): $(IP_PATH) mkdir -p $(HW_BUILD_PATH) cd $(HW_BUILD_PATH) && \ $(VIVADO) \ -mode tcl \ -source $(SCRIPT_DIR)/vivado.tcl \ -tclargs \ $(BUILD_DIR)/hls/$(CONF) \ ${VTA_CONFIG} clean: rm -rf *.out *.log cleanall: clean rm -rf $(BUILD_DIR) <file_sep>/src/pass/lower_intrin.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * Lower intrinsic calls to device specific ir when possible. * \file lower_intrin.cc */ #include <tvm/ir.h> #include <tvm/ir_mutator.h> #include <tvm/ir_pass.h> #include <tvm/api_registry.h> #include <unordered_set> #include "ir_util.h" namespace tvm { namespace ir { class IntrinInjecter : public IRMutator { public: explicit IntrinInjecter(std::string target) { std::istringstream is(target); std::string starget; is >> starget; patterns_.push_back("tvm.intrin.rule." + starget + "."); patterns_.push_back("tvm.intrin.rule.default."); fma_ = runtime::Registry::Get(patterns_[0] + "fma"); } Expr Mutate_(const Call* op, const Expr& e) final { if (op->call_type == Call::Intrinsic || op->call_type == Call::PureIntrinsic) { Expr r = ApplyPattern(op->name, e); if (r.defined()) return r; } return IRMutator::Mutate_(op, e); } Expr Mutate_(const Add* op, const Expr& e) final { if (const Mul* mb = op->b.as<Mul>()) { return MakeFMA(mb->a, mb->b, op->a, op, e); } else if (const Mul* ma = op->a.as<Mul>()) { return MakeFMA(ma->a, ma->b, op->b, op, e); } return IRMutator::Mutate_(op, e); } private: Expr SwapBroadcastCast(const Expr& e) { // Try to change broadcast(cast(x)) to cast(broadcast(x)) // For some targets, LLVM will generate more efficient FMA // instruction with the latter. For example, vmla vs. vmlal // on ARM. if (const Broadcast* bcast = e.as<Broadcast>()) { if (const Cast* cast = bcast->value.as<Cast>()) { auto should_swap = [&]() { // Maintain behaviour (int8 -> int16, fp16 -> fp32). if (cast->type.bits() == cast->value.type().bits() * 2) { return true; } // Check both operands are integer-like. if (!cast->type.is_uint() && !cast->type.is_int()) { return false; } if (!cast->value.type().is_uint() && !cast->value.type().is_int()) { return false; } // If both are integer-like, swap if we have a widening cast. return cast->type.bits() > cast->value.type().bits(); }; if (should_swap()) { Expr new_bcast = Broadcast::make(cast->value, bcast->lanes); return Cast::make(bcast->type, new_bcast); } } } return e; } Expr MakeFMA(const Expr& a, const Expr& b, const Expr& c, const Add* op, const Expr& e) { // emit fma instruction: a * b + c Expr lhs = SwapBroadcastCast(a); Expr rhs = SwapBroadcastCast(b); if (fma_ != nullptr && op->type.is_float()) { Expr r = (*fma_)(Call::make( op->type, "fma", {lhs, rhs, c}, Call::PureIntrinsic)); if (r.defined()) return this->Mutate(r); } else { if (!lhs.same_as(a) || !rhs.same_as(b)) { Expr mul = this->Mutate(Mul::make(lhs, rhs)); return Add::make(mul, this->Mutate(c)); } } return IRMutator::Mutate_(op, e); } Expr ApplyPattern(const std::string& name, const Expr& e) { for (size_t i = 0; i < patterns_.size(); ++i) { std::string& p = patterns_[i]; size_t psize = p.length(); p.resize(psize + name.length()); name.copy(&p[0] + psize, name.length()); const runtime::PackedFunc* f = runtime::Registry::Get(p); p.resize(psize); // if pattern exists. if (f != nullptr) { Expr r = (*f)(e); CHECK(r.defined()) << "intrinsic rule must always return valid Expr"; if (!r.same_as(e)) { return this->Mutate(r); } } } return Expr(); } // patterns std::vector<std::string> patterns_; const PackedFunc* fma_{nullptr}; }; LoweredFunc LowerIntrin(LoweredFunc f, const std::string& target) { auto n = make_node<LoweredFuncNode>(*f.operator->()); n->body = IntrinInjecter(target).Mutate(n->body); return LoweredFunc(n); } } // namespace ir } // namespace tvm <file_sep>/python/tvm/relay/backend/deserializer.py # License .to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """ The Relay Virtual Machine deserializer. Python interface for deserializing a Relay VM. """ from tvm import module from tvm._ffi.runtime_ctypes import TVMByteArray from . import _vm from . import vm as rly_vm def _create_deserializer(code, lib): """Create a deserializer object. Parameters ---------- code : bytearray The serialized virtual machine code. lib : :py:class:`~tvm.module.Module` The serialized runtime module/library that contains the hardware dependent binary code. Returns ------- ret : Deserializer The created virtual machine deserializer. """ if isinstance(code, (bytes, str)): code = bytearray(code) elif not isinstance(code, (bytearray, TVMByteArray)): raise TypeError("vm is expected to be the type of bytearray or " + "TVMByteArray, but received {}".format(type(code))) if not isinstance(lib, module.Module): raise TypeError("lib is expected to be the type of tvm.module.Module" + ", but received {}".format(type(lib))) return _vm._Deserializer(code, lib) class Deserializer: """Relay VM deserializer. Parameters ---------- code : bytearray The serialized virtual machine code. lib : :py:class:`~tvm.module.Module` The serialized runtime module/library that contains the hardware dependent binary code. """ def __init__(self, code, lib): self.mod = _create_deserializer(code, lib) self._deserialize = self.mod["deserialize"] def deserialize(self): """Deserialize the serialized bytecode into a Relay VM. Returns ------- ret : VirtualMachine The deserialized Relay VM. """ return rly_vm.VirtualMachine(self._deserialize()) <file_sep>/python/tvm/relay/backend/vmobj.py # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """TVM Runtime Object API.""" from __future__ import absolute_import as _abs import numpy as _np from tvm._ffi.vmobj import Object, ObjectTag, register_object from tvm import ndarray as _nd from . import _vmobj # TODO(@icemelon9): Add ClosureObject @register_object class TensorObject(Object): """Tensor object.""" tag = ObjectTag.TENSOR def __init__(self, handle): """Constructs a Tensor object Parameters ---------- handle : object Object handle Returns ------- obj : TensorObject A tensor object. """ super(TensorObject, self).__init__(handle) self.data = _vmobj.GetTensorData(self) def asnumpy(self): """Convert data to numpy array Returns ------- np_arr : numpy.ndarray The corresponding numpy array. """ return self.data.asnumpy() @register_object class DatatypeObject(Object): """Datatype object.""" tag = ObjectTag.DATATYPE def __init__(self, handle): """Constructs a Datatype object Parameters ---------- handle : object Object handle Returns ------- obj : DatatypeObject A Datatype object. """ super(DatatypeObject, self).__init__(handle) self.tag = _vmobj.GetDatatypeTag(self) num_fields = _vmobj.GetDatatypeNumberOfFields(self) self.fields = [] for i in range(num_fields): self.fields.append(_vmobj.GetDatatypeFields(self, i)) def __getitem__(self, idx): return self.fields[idx] def __len__(self): return len(self.fields) def __iter__(self): return iter(self.fields) # TODO(icemelon9): Add closure object def tensor_object(arr, ctx=_nd.cpu(0)): """Create a tensor object from source arr. Parameters ---------- arr : numpy.ndarray or tvm.nd.NDArray The source array. ctx : TVMContext, optional The device context to create the array Returns ------- ret : TensorObject The created object. """ if isinstance(arr, _np.ndarray): tensor = _vmobj.Tensor(_nd.array(arr, ctx)) elif isinstance(arr, _nd.NDArray): tensor = _vmobj.Tensor(arr) else: raise RuntimeError("Unsupported type for tensor object.") return tensor def tuple_object(fields): """Create a datatype object from source tuple. Parameters ---------- fields : list[Object] or tuple[Object] The source tuple. Returns ------- ret : DatatypeObject The created object. """ for f in fields: assert isinstance(f, Object) return _vmobj.Tuple(*fields) def datatype_object(tag, fields): """Create a datatype object from tag and source fields. Parameters ---------- tag : int The tag of datatype. fields : list[Object] or tuple[Object] The source tuple. Returns ------- ret : DatatypeObject The created object. """ for f in fields: assert isinstance(f, Object) return _vmobj.Datatype(tag, *fields) <file_sep>/src/codegen/codegen_cuda.cc /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file codegen_cuda.cc */ #include <tvm/base.h> #include <tvm/runtime/registry.h> #include <tvm/packed_func_ext.h> #include <vector> #include <string> #include "codegen_cuda.h" namespace tvm { namespace codegen { CodeGenCUDA::CodeGenCUDA() { restrict_keyword_ = "__restrict__"; } void CodeGenCUDA::Init(bool output_ssa) { CodeGenC::Init(output_ssa); vid_global_barrier_state_ = GetUniqueName(runtime::symbol::tvm_global_barrier_state); vid_global_barrier_expect_ = GetUniqueName("__barrier_expect"); CHECK_EQ(vid_global_barrier_state_, runtime::symbol::tvm_global_barrier_state); } void CodeGenCUDA::AddFunction(LoweredFunc f) { this->stream << "extern \"C\" __global__ "; CodeGenC::AddFunction(f); } std::string CodeGenCUDA::Finish() { if (enable_fp16_) { decl_stream << "#include <cuda_fp16.h>\n"; } if (enable_int8_) { decl_stream << "#include <sm_61_intrinsics.h>\n"; } if (need_math_constants_h_) { decl_stream << "#include <math_constants.h>\n"; } return CodeGenC::Finish(); } void CodeGenCUDA::VisitStmt_(const ir::For* op) { CHECK(is_const_int(op->min, 0)); if (op->for_type == ir::ForType::Unrolled) { PrintIndent(); stream << "#pragma unroll\n"; } CodeGenC::VisitStmt_(op); } void CodeGenCUDA::BindThreadIndex(const IterVar& iv) { CHECK(!var_idmap_.count(iv->var.get())); var_idmap_[iv->var.get()] = CastFromTo(iv->thread_tag, UInt(32), iv->var.type()); } void CodeGenCUDA::PrintType(Type t, std::ostream& os) { // NOLINT(*) int lanes = t.lanes(); if (t.is_handle()) { CHECK_EQ(lanes, 1) << "do not yet support vector types"; os << "void*"; return; } bool fail = false; if (t.is_float()) { switch (t.bits()) { case 16: os << "half"; enable_fp16_ = true; break; case 32: os << "float"; break; case 64: os << "double"; break; default: fail = true; break; } if (!fail && lanes == 1) return; if (!fail && (lanes >= 2 && lanes <= 4)) { os << lanes; return; } } else if (t == Bool()) { os << "bool"; return; } else if (t.is_uint() || t.is_int()) { if (t.is_uint()) { if (t.lanes() != 1) { os << "u"; } else { os << "unsigned "; } } switch (t.bits()) { case 8: { if (t.lanes() == 4) { // directly 4 8 bit int in integer. enable_int8_ = true; // We use int for int8x4 instead of char4 because using char4 is // likely to produce extra instructions to pack four int8 elements // into 32-bit data. os << "int"; return; } else if (t.lanes() == 8) { enable_int8_ = true; os << "int2"; return; } else if (t.lanes() == 16) { enable_int8_ = true; os << "int4"; return; } else if (!t.is_uint() && t.lanes() == 1) { os << "signed char"; break; } else { os << "char"; break; } } case 16: os << "short"; break; case 32: os << "int"; break; case 64: { if (sizeof(long) != 8) { // NOLINT(*) if (t.lanes() == 1) { os << "long long"; break; } else if (t.lanes() == 2) { os << "longlong"; break; } else { // No longlong3, longlong4 LOG(FATAL) << "Cannot convert type " << t << " to CUDA type on a L32 platform"; } } else { os << "long"; break; } } case 1: os << "int"; break; default: fail = true; break; } if (!fail && lanes == 1) { return; } if (!fail && (lanes >= 2 && lanes <= 4)) { os << lanes; return; } } LOG(FATAL) << "Cannot convert type " << t << " to CUDA type"; } void CodeGenCUDA::PrintVecBinaryOp( const std::string&op, Type t, Expr lhs, Expr rhs, std::ostream& os) { // NOLINT(*) // unpacking operations. int lanes = t.lanes(); { // The assignment below introduces side-effect, and the resulting value cannot // be reused across multiple expression, thus a new scope is needed int vec_scope = BeginScope(); // default: unpack into individual ops. std::string vlhs = SSAGetID(PrintExpr(lhs), lhs.type()); std::string vrhs = SSAGetID(PrintExpr(rhs), rhs.type()); std::string sret = GetUniqueName("_"); { // delcare type. this->PrintIndent(); this->PrintType(t, stream); stream << ' ' << sret << ";\n"; } for (int i = 0; i < lanes; ++i) { std::ostringstream value_temp; if (isalpha(op[0])) { value_temp << op << "("; PrintVecElemLoad(vlhs, lhs.type(), i, value_temp); value_temp << ", "; PrintVecElemLoad(vrhs, rhs.type(), i, value_temp); value_temp << ")"; } else { value_temp << "("; PrintVecElemLoad(vlhs, lhs.type(), i, value_temp); value_temp << op; PrintVecElemLoad(vrhs, rhs.type(), i, value_temp); value_temp << ")"; } PrintVecElemStore(sret, t, i, value_temp.str()); } os << sret; EndScope(vec_scope); } } void CodeGenCUDA::PrintVecElemLoad( const std::string& vec, Type t, int i, std::ostream& os) { // NOLINT(*) static const char access[] = {'x', 'y', 'z', 'w'}; CHECK(i >= 0 && i < 4); os << vec << "." << access[i]; } void CodeGenCUDA::PrintVecElemStore( const std::string& vec, Type t, int i, const std::string& value) { this->PrintIndent(); static const char access[] = {'x', 'y', 'z', 'w'}; CHECK(i >= 0 && i < 4); stream << vec << "." << access[i] << " = " << value << ";\n"; } void CodeGenCUDA::PrintStorageSync(const Call* op) { const std::string& sync = op->args[0].as<StringImm>()->value; if (sync == "warp") { // DO nothing. } else if (sync == "shared") { this->PrintIndent(); this->stream << "__syncthreads();\n"; } else if (sync == "global") { if (!need_global_barrier_) { need_global_barrier_ = true; this->decl_stream << "extern \"C\" __device__ unsigned " << vid_global_barrier_state_ << ";\n"; } // global synchronizer std::string is_load = PrintExpr(op->args[1]); std::string num_blocks = PrintExpr(op->args[2]); this->PrintIndent(); // In theory only threadfence is needed // but we observed problems with only threadfence this->stream <<"__threadfence_system();\n"; this->PrintIndent(); this->stream <<"if (" << is_load << ") {\n"; int wb = this->BeginScope(); this->PrintIndent(); this->stream << "atomicAdd(&" << vid_global_barrier_state_ << ", 1);\n"; this->PrintIndent(); std::string ptr = GetUniqueName("pf"); this->stream << "volatile unsigned* " << ptr << " = &" << vid_global_barrier_state_<< ";\n"; this->PrintIndent(); this->stream << vid_global_barrier_expect_ << " += " << num_blocks << ";\n"; this->PrintIndent(); this->stream <<"while (" << ptr << "[0] < " << vid_global_barrier_expect_ << ");\n"; this->EndScope(wb); this->PrintIndent(); this->stream <<"}\n"; this->PrintIndent(); this->stream <<"__syncthreads();\n"; } } void CodeGenCUDA::PrintStorageScope( const std::string& scope, std::ostream& os) { // NOLINT(*) CHECK_NE(scope, "global"); if (scope == "shared") { os << "__shared__"; } } void CodeGenCUDA::VisitStmt_(const Evaluate *op) { if (is_const(op->value)) return; const Call* call = op->value.as<Call>(); if (call && call->is_intrinsic(intrinsic::tvm_global_barrier_kinit)) { PrintIndent(); stream << "__shared__ unsigned " << vid_global_barrier_expect_ << ";\n"; PrintIndent(); stream << "if (threadIdx.x == 0) {\n"; PrintIndent(); stream << " " << vid_global_barrier_expect_ << " = 0;\n"; PrintIndent(); stream << "}\n"; } else { CodeGenC::VisitStmt_(op); } } void CodeGenCUDA::VisitExpr_(const Ramp* op, std::ostream& os) { os << "((make_int" << op->lanes << ")("; for (int i = 0; i < op->lanes; i++) { os << "(" << PrintExpr(op->base) << ")" << "+(" << PrintExpr(op->stride) << "*" << i <<")"; if (i != op->lanes - 1) os << ", "; } os << "))"; } void CodeGenCUDA::VisitExpr_(const Broadcast* op, std::ostream& os) { // NOLINT(*) if (op->type.is_int() && op->type.bits() == 8 && op->lanes == 4) { // make_int8x4 const int64_t *p = as_const_int(op->value); CHECK(p); int64_t v = *p & 0xFF; v = (v << 24) | (v << 16) | (v << 8) | v; os << "(int)" << v; return; } std::string v = PrintExpr(op->value); os << "make_"; PrintType(op->type, os); os << '('; for (int i = 0; i < op->lanes; ++i) { if (i != 0) os << ", "; os << v; } os << ')'; } void CodeGenCUDA::VisitExpr_(const Shuffle* op, std::ostream &os) { std::vector<std::string> to_shuffle(op->vectors.size()); for (int i = 0, e = op->vectors.size(); i < e; ++i) { CHECK(op->vectors[i].type().lanes() == 1) << "Only scalars can be shuffled in CUDA!"; to_shuffle[i] = PrintExpr(op->vectors[i]); } os << "make_"; PrintType(op->type, os); os << '('; for (int i = 0, e = op->indices.size(); i < e; ++i) { const int64_t *val = as_const_int(op->indices[i]); CHECK(val && *val >= 0 && (int) *val < (int) to_shuffle.size()); if (i != 0) os << ", "; os << to_shuffle[*val]; } os << ')'; } inline void PrintConst(const FloatImm* op, std::ostream& os, CodeGenCUDA* p) { // NOLINT(*) switch (op->type.bits()) { case 64: case 32: { std::ostringstream temp; if (std::isinf(op->value)) { if (op->value < 0) { temp << "-"; } temp << ((op->type.bits() == 32) ? "CUDART_INF_F" : "CUDART_INF"); p->need_math_constants_h_ = true; } else if (std::isnan(op->value)) { temp << ((op->type.bits() == 32) ? "CUDART_NAN_F" : "CUDART_NAN"); p->need_math_constants_h_ = true; } else { temp << std::scientific << op->value; if (op->type.bits() == 32) temp << 'f'; } p->MarkConst(temp.str()); os << temp.str(); break; } case 16: { os << "__float2half_rn"; os << '(' << std::scientific << op->value << 'f' << ')'; break; } default: LOG(FATAL) << "Bad bit-width for float: " << op->type << "\n"; } } void CodeGenCUDA::VisitExpr_(const FloatImm *op, std::ostream& os) { // NOLINT(*) PrintConst(op, os, this); } } // namespace codegen } // namespace tvm <file_sep>/apps/android_deploy/app/src/main/jni/Android.mk LOCAL_PATH := $(call my-dir) MY_PATH := $(LOCAL_PATH) include $(CLEAR_VARS) LOCAL_PATH := $(MY_PATH) ROOT_PATH := $(MY_PATH)/../../../../../.. ifndef config ifneq ("$(wildcard ./config.mk)","") config ?= config.mk else config ?= make/config.mk endif endif include $(config) LOCAL_SRC_FILES := ml_dmlc_tvm_native_c_api.cc LOCAL_LDFLAGS := -L$(SYSROOT)/usr/lib/ -llog LOCAL_C_INCLUDES := $(ROOT_PATH)/include \ $(ROOT_PATH)/3rdparty/dlpack/include \ $(ROOT_PATH)/3rdparty/dmlc-core/include \ $(ROOT_PATH)/3rdparty/HalideIR/src \ $(ROOT_PATH)/topi/include LOCAL_MODULE = tvm4j_runtime_packed LOCAL_CPP_FEATURES += exceptions LOCAL_LDLIBS += -latomic LOCAL_ARM_MODE := arm ifdef ADD_C_INCLUDES LOCAL_C_INCLUDES += $(ADD_C_INCLUDES) endif ifdef ADD_LDLIBS LOCAL_LDLIBS += $(ADD_LDLIBS) endif include $(BUILD_SHARED_LIBRARY) <file_sep>/topi/python/topi/testing/__init__.py """TOPI Testing Util functions. Used to verify the correctness of operators in TOPI . """ from __future__ import absolute_import as _abs from .conv2d_hwcn_python import conv2d_hwcn_python from .conv2d_nchw_python import conv2d_nchw_python from .conv2d_nhwc_python import conv2d_nhwc_python from .conv2d_transpose_nchw_python import conv2d_transpose_nchw_python from .deformable_conv2d_nchw_python import deformable_conv2d_nchw_python from .depthwise_conv2d_python import depthwise_conv2d_python_nchw, depthwise_conv2d_python_nhwc from .dilate_python import dilate_python from .softmax_python import softmax_python, log_softmax_python from .upsampling_python import upsampling_python from .bilinear_resize_python import bilinear_resize_python from .reorg_python import reorg_python from .roi_align_python import roi_align_nchw_python from .roi_pool_python import roi_pool_nchw_python from .lrn_python import lrn_python from .l2_normalize_python import l2_normalize_python from .gather_nd_python import gather_nd_python from .strided_slice_python import strided_slice_python from .batch_matmul import batch_matmul from .slice_axis_python import slice_axis_python from .sequence_mask_python import sequence_mask from .pool_grad_python import pool_grad_nchw from .one_hot import one_hot <file_sep>/include/tvm/node/node.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file tvm/node/node.h * \brief Node system data structure. */ #ifndef TVM_NODE_NODE_H_ #define TVM_NODE_NODE_H_ #include <dmlc/logging.h> #include <tvm/runtime/c_runtime_api.h> #include <tvm/runtime/node_base.h> #include <string> #include <vector> #include <utility> #include <type_traits> namespace tvm { // forward declaration class DataType; class Node; class NodeRef; namespace runtime { // forward declaration class NDArray; // forward declaration class Object; } // namespace runtime /*! * \brief Visitor class to each node content. * The content is going to be called for each field. */ class TVM_DLL AttrVisitor { public: //! \cond Doxygen_Suppress virtual ~AttrVisitor() = default; virtual void Visit(const char* key, double* value) = 0; virtual void Visit(const char* key, int64_t* value) = 0; virtual void Visit(const char* key, uint64_t* value) = 0; virtual void Visit(const char* key, int* value) = 0; virtual void Visit(const char* key, bool* value) = 0; virtual void Visit(const char* key, std::string* value) = 0; virtual void Visit(const char* key, void** value) = 0; virtual void Visit(const char* key, DataType* value) = 0; virtual void Visit(const char* key, NodeRef* value) = 0; virtual void Visit(const char* key, runtime::NDArray* value) = 0; virtual void Visit(const char* key, runtime::Object* value) = 0; template<typename ENum, typename = typename std::enable_if<std::is_enum<ENum>::value>::type> void Visit(const char* key, ENum* ptr) { static_assert(std::is_same<int, typename std::underlying_type<ENum>::type>::value, "declare enum to be enum int to use visitor"); this->Visit(key, reinterpret_cast<int*>(ptr)); } //! \endcond }; /*! * \brief base class of node container in DSL AST. */ class TVM_DLL Node : public NodeBase { public: /*! \brief virtual destructor */ virtual ~Node() {} /*! \return The unique type key of the node */ virtual const char* type_key() const = 0; /*! * \brief Apply visitor to each field of the Node * Visitor could mutate the content of the node. * override if Node contains attribute fields. * \param visitor The visitor */ virtual void VisitAttrs(AttrVisitor* visitor) {} /*! \return the type index of the node */ virtual uint32_t type_index() const = 0; /*! * \brief Whether this node derives from node with type_index=tid. * Implemented by TVM_DECLARE_NODE_TYPE_INFO * * \param tid The type index. * \return the check result. */ virtual bool _DerivedFrom(uint32_t tid) const; /*! * \brief get a runtime unique type index given a type key * \param type_key Type key of a type. * \return the corresponding type index. */ static uint32_t TypeKey2Index(const char* type_key); /*! * \brief get type key from type index. * \param index The type index * \return the corresponding type key. */ static const char* TypeIndex2Key(uint32_t index); /*! * \return whether the type is derived from */ template<typename T> inline bool derived_from() const; /*! * \return whether the node is of type T * \tparam The type to be checked. */ template<typename T> inline bool is_type() const; /*! * \brief Get a NodePtr that holds reference to this Node. * \return the NodePtr */ inline NodePtr<Node> GetNodePtr() const; // node ref can see this friend class NodeRef; static constexpr const char* _type_key = "Node"; }; /*! \brief Base class of all node reference object */ class NodeRef { public: /*! \brief type indicate the container type */ using ContainerType = Node; /*! * \brief Comparator * \param other Another node ref. * \return the compare result. */ inline bool operator==(const NodeRef& other) const; /*! * \brief Comparator * \param other Another node ref. * \return the compare result. */ inline bool same_as(const NodeRef& other) const; /*! * \brief Comparator * \param other Another node ref. * \return the compare result. */ inline bool operator<(const NodeRef& other) const; /*! * \brief Comparator * \param other Another node ref. * \return the compare result. */ inline bool operator!=(const NodeRef& other) const; /*! \return the hash function for NodeRef */ inline size_t hash() const; /*! \return whether the expression is null */ inline bool defined() const; /*! \return the internal type index of IRNode */ inline uint32_t type_index() const; /*! \return the internal node pointer */ inline const Node* get() const; /*! \return the internal node pointer */ inline const Node* operator->() const; /*! * \brief Downcast this ir node to its actual type (e.g. Add, or * Select). This returns nullptr if the node is not of the requested * type. Example usage: * * if (const Add *add = node->as<Add>()) { * // This is an add node * } * \tparam T the target type, must be subtype of IRNode */ template<typename T> inline const T *as() const; /*! * \brief A more powerful version of as that also works with * intermediate base types. * \tparam T the target type, must be subtype of IRNode */ template<typename T> inline const T *as_derived() const; /*! \brief default constructor */ NodeRef() = default; explicit NodeRef(NodePtr<Node> node) : node_(node) {} /*! \brief the internal node object, do not touch */ NodePtr<Node> node_; }; /*! * \brief Get a reference type from a Node ptr type * * It is always important to get a reference type * if we want to return a value as reference or keep * the node alive beyond the scope of the function. * * \param ptr The node pointer * \tparam RefType The reference type * \tparam NodeType The node type * \return The corresponding RefType */ template <typename RefType, typename NodeType> inline RefType GetRef(const NodeType* ptr); /*! * \brief Downcast a base reference type to a more specific type. * * \param ref The inptut reference * \return The corresponding SubRef. * \tparam SubRef The target specific reference type. * \tparam BaseRef the current reference type. */ template <typename SubRef, typename BaseRef> inline SubRef Downcast(BaseRef ref); /*! * \brief helper macro to declare type information in a base node. */ #define TVM_DECLARE_BASE_NODE_INFO(TypeName, Parent) \ bool _DerivedFrom(uint32_t tid) const override { \ static uint32_t tidx = TypeKey2Index(TypeName::_type_key); \ if (tidx == tid) return true; \ return Parent::_DerivedFrom(tid); \ } /*! * \brief helper macro to declare type information in a terminal node */ #define TVM_DECLARE_NODE_TYPE_INFO(TypeName, Parent) \ const char* type_key() const final { \ return TypeName::_type_key; \ } \ uint32_t type_index() const final { \ static uint32_t tidx = TypeKey2Index(TypeName::_type_key); \ return tidx; \ } \ bool _DerivedFrom(uint32_t tid) const final { \ static uint32_t tidx = TypeKey2Index(TypeName::_type_key); \ if (tidx == tid) return true; \ return Parent::_DerivedFrom(tid); \ } // implementations of inline functions after this template<typename T> inline bool Node::derived_from() const { // use static field so query only happens once. static uint32_t type_id = Node::TypeKey2Index(T::_type_key); return this->_DerivedFrom(type_id); } template<typename T> inline bool Node::is_type() const { // use static field so query only happens once. static uint32_t type_id = Node::TypeKey2Index(T::_type_key); return type_id == this->type_index(); } inline NodePtr<Node> Node::GetNodePtr() const { return NodePtr<Node>(const_cast<Node*>(this)); } template <typename RefType, typename NodeType> inline RefType GetRef(const NodeType* ptr) { static_assert(std::is_base_of<typename RefType::ContainerType, NodeType>::value, "Can only cast to the ref of same container type"); return RefType(ptr->GetNodePtr()); } template <typename SubRef, typename BaseRef> inline SubRef Downcast(BaseRef ref) { CHECK(ref->template is_type<typename SubRef::ContainerType>() || ref->template derived_from<typename SubRef::ContainerType>()) << "Downcast from " << ref->type_key() << " to " << SubRef::ContainerType::_type_key << " failed."; return SubRef(std::move(ref.node_)); } inline const Node* NodeRef::get() const { return node_.get(); } inline const Node* NodeRef::operator->() const { return node_.get(); } inline bool NodeRef::defined() const { return node_.get() != nullptr; } inline bool NodeRef::operator==(const NodeRef& other) const { return node_.get() == other.node_.get(); } inline bool NodeRef::same_as(const NodeRef& other) const { return node_.get() == other.node_.get(); } inline bool NodeRef::operator<(const NodeRef& other) const { return node_.get() < other.node_.get(); } inline bool NodeRef::operator!=(const NodeRef& other) const { return node_.get() != other.node_.get(); } inline size_t NodeRef::hash() const { return std::hash<Node*>()(node_.get()); } inline uint32_t NodeRef::type_index() const { CHECK(node_.get() != nullptr) << "null type"; return get()->type_index(); } template<typename T> inline const T* NodeRef::as() const { const Node* ptr = static_cast<const Node*>(get()); if (ptr && ptr->is_type<T>()) { return static_cast<const T*>(ptr); } return nullptr; } template<typename T> inline const T* NodeRef::as_derived() const { const Node* ptr = static_cast<const Node*>(get()); if (ptr && (ptr->is_type<T>() || ptr->derived_from<T>())) { return static_cast<const T*>(ptr); } return nullptr; } /*! \brief The hash function for nodes */ struct NodeHash { size_t operator()(const NodeRef& a) const { return a.hash(); } }; /*! \brief The equal comparator for nodes */ struct NodeEqual { bool operator()(const NodeRef& a, const NodeRef& b) const { return a.get() == b.get(); } }; } // namespace tvm #endif // TVM_NODE_NODE_H_ <file_sep>/src/relay/pass/alter_op_layout.h /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file alter_op_layout.h * \brief Alternate the layouts of operators or replace primitive operators with other expressions. This pass can be used for computing convolution in custom layouts or other general weight pre-transformation. */ #ifndef TVM_RELAY_PASS_ALTER_OP_LAYOUT_H_ #define TVM_RELAY_PASS_ALTER_OP_LAYOUT_H_ #include <tvm/data_layout.h> #include <tvm/relay/expr.h> namespace tvm { namespace relay { /*! * \brief Infer & correct function of node layout. See \p Layout for layout convention * \param attrs The attribute of the node. * \param new_in_layouts The layouts of input arguments after alter_op_layout. * This can be undefined, which means we call this function before alternating * any operators. * \param old_in_layouts The layouts of input arguments before alter_op_layout. * \param old_in_shapes The shapes of old input arguments. * \return infered_layout An array of two elements that are inferred input layouts and * inferred output layouts. */ using FInferCorrectLayout = runtime::TypedPackedFunc< Array<Array<Layout>>(const Attrs& attrs, const Array<Layout>& new_in_layouts, const Array<Layout>& old_in_layouts, const Array<Array<IndexExpr>> &old_in_shapes)>; /*! \brief take arbitrary input layout and copy to output */ inline Array<Array<Layout> > ElemwiseArbitraryLayout(const Attrs& attrs, const Array<Layout>& new_in_layouts, const Array<Layout>& old_in_layouts, const Array<Array<IndexExpr>> &old_in_shapes) { Layout ret; if (new_in_layouts.defined()) { CHECK_GE(new_in_layouts.size(), 1); ret = new_in_layouts[0]; } else { for (size_t i = 0; i < old_in_layouts.size(); ++i) { if (old_in_layouts[i].defined()) { ret = old_in_layouts[i]; break; } } } return Array<Array<Layout> >{Array<Layout>(old_in_layouts.size(), ret), {ret}}; } /*! \brief Infer layout for binary broadcast operators */ inline Array<Array<Layout> > BinaryBroadcastLayout(const Attrs& attrs, const Array<Layout>& new_in_layouts, const Array<Layout>& old_in_layouts, const Array<Array<IndexExpr>> &old_in_shapes) { Array<Layout> layouts; if (new_in_layouts.defined()) { layouts.assign(new_in_layouts.begin(), new_in_layouts.end()); } else { layouts.assign(old_in_layouts.begin(), old_in_layouts.end()); } if (!layouts[0].defined() && !layouts[1].defined()) { // both undefined, infer fails return Array<Array<Layout> > {{Layout::Undef()}, {Layout::Undef()}}; } else if (!layouts[0].defined() || !layouts[1].defined()) { // only one is defined, use shape information to help infer int defined_idx = layouts[0].defined() ? 0 : 1; int undef_idx = 1 - defined_idx; if (old_in_shapes[defined_idx].size() >= old_in_shapes[undef_idx].size()) { layouts.Set(undef_idx, layouts[defined_idx].SubLayout( old_in_shapes[defined_idx].size() - old_in_shapes[undef_idx].size(), old_in_shapes[undef_idx].size())); return Array<Array<Layout> >{layouts, {layouts[defined_idx]}}; } else { // only know the tensor with smaller dimensions, // so we cannot infer the final broadcasted output. // fails in this case. return Array<Array<Layout> >{{Layout::Undef()}, {Layout::Undef()}}; } } else if (layouts[0].defined() && layouts[1].defined() && (layouts[0].ndim() == 0 || layouts[1].ndim() == 0)) { int scalar = layouts[0].ndim() == 0 ? 0 : 1; return Array<Array<Layout> >{layouts, {layouts[1-scalar]}}; } else { // try to broadcast the tensors to the larger dimension int large_idx = layouts[0].ndim_primal() >= layouts[1].ndim_primal() ? 0 : 1; int small_idx = 1 - large_idx; Layout ret = layouts[large_idx]; // extract common part size_t i = layouts[large_idx].ndim(); for (; i != 0; --i) { const auto& axis = layouts[large_idx][i-1]; if (!layouts[small_idx].Contains(axis.ToPrimal())) { break; } } Layout common_part = layouts[large_idx].SubLayout(i, layouts[large_idx].ndim() - i); if (!BijectiveLayoutNode::make(layouts[small_idx], common_part).defined()) { // not convertible return Array<Array<Layout> > {{Layout::Undef()}, {Layout::Undef()}}; } layouts.Set(small_idx, common_part); return Array<Array<Layout> > {layouts, {ret}}; } } } // namespace relay } // namespace tvm #endif // TVM_RELAY_PASS_ALTER_OP_LAYOUT_H_ <file_sep>/vta/tests/hardware/metal_test/Makefile # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. CC ?= g++ CFLAGS = -Wall -O3 -std=c++11 -I/usr/include LDFLAGS = -L/usr/lib -L/opt/python3.6/lib/python3.6/site-packages/pynq/lib/ LIBS = -l:libcma.so -lstdc++ -pthread INCLUDE_DIR = ../../../include DRIVER_DIR = ../../../src/pynq TESTLIB_DIR = ../common VPATH = $(DRIVER_DIR):$(TESTLIB_DIR) SOURCES = pynq_driver.cc test_lib.cc OBJECTS = pynq_driver.o test_lib.o metal_test.o EXECUTABLE = vta # Include VTA config VTA_CONFIG = python ../../../config/vta_config.py CFLAGS += `${VTA_CONFIG} --cflags` LDFLAGS += `${VTA_CONFIG} --ldflags` VTA_TARGET := $(shell ${VTA_CONFIG} --target) # Include bitstream VTA_PROGRAM = python3 ../../../python/vta/program_bitstream.py VTA_BIT = "vta.bit" # Define flags CFLAGS += -I $(INCLUDE_DIR) -DNO_SIM -DVTA_DEBUG=0 # All Target all: vtainstall $(EXECUTABLE) %.o: %.cc $(SOURCES) $(CC) -c -o $@ $< $(CFLAGS) $(EXECUTABLE): $(OBJECTS) $(CC) $(LDFLAGS) $(OBJECTS) -o $@ $(LIBS) vtainstall: ${VTA_PROGRAM} ${VTA_TARGET} ${VTA_BIT} clean: rm -rf *.o $(EXECUTABLE) <file_sep>/apps/android_rpc/app/src/main/jni/Application.mk ifndef config ifneq ("$(wildcard ./config.mk)","") config ?= config.mk else config ?= make/config.mk endif endif include $(config) # We target every architecture except armeabi here, for two reasons: # 1) armeabi is deprecated in NDK r16 and removed in r17 # 2) vulkan is not supported in armeabi APP_ABI ?= armeabi-v7a arm64-v8a x86 x86_64 mips APP_STL := c++_shared APP_CPPFLAGS += -DDMLC_LOG_STACK_TRACE=0 -DTVM4J_ANDROID=1 -std=c++11 -Oz -frtti ifeq ($(USE_OPENCL), 1) APP_CPPFLAGS += -DTVM_OPENCL_RUNTIME=1 endif ifeq ($(USE_VULKAN), 1) APP_CPPFLAGS += -DTVM_VULKAN_RUNTIME=1 APP_LDFLAGS += -lvulkan endif ifeq ($(USE_SORT), 1) APP_CPPFLAGS += -DUSE_SORT=1 endif
4c4378386eb09182f1baec6f6636119682e29bfd
[ "Markdown", "Makefile", "Python", "C", "C++" ]
112
Python
microsoft/onnxruntime-tvm
984dc1b111aeb02c8a8c68e9724ecff814db11ff
2e4a64b3358d43a15a586c1da9d323326c4fcafd
refs/heads/master
<repo_name>chestergrant/TinyGP<file_sep>/tiny_gp.py import sys import math import random class tiny_gp: POPSIZE = 100000 ADD = 110 SUB = 111 MUL = 112 DIV = 113 FSET_START = ADD FSET_END = DIV DEPTH = 15 MAX_LEN = 10 GENERATIONS = 10000 TSIZE = 2 CROSSOVER_PROB = 0.9 PMUT_PER_NODE = 0.05 def __init__(self,fname,s): self.fitness = [0.0]*self.POPSIZE self.seed = s if self.seed >= 0: random.seed(self.seed) self.setup_fitness(fname) self.x = [] for i in range(self.FSET_START): self.x.append((self.maxrandom-self.minrandom)*random.uniform(0,1)+self.minrandom) self.pop = self.create_random_pop(self.POPSIZE,self.DEPTH,self.fitness) def grow(self, pos, max, depth): prim = random.randint(0,1) if pos >= max: return -1 if pos == 0: prim = 1 if prim == 0 or depth == 0: prim = random.randint(0,self.varnumber+self.randomnumber-1) self.buffer.append(prim) return pos+1 else: prim = random.randint(0,self.FSET_END-self.FSET_START) + self.FSET_START if prim == self.ADD or prim == self.SUB or prim == self.MUL or prim == self.DIV: self.buffer.append(prim) one_child = self.grow(pos+1,max,depth-1) if one_child < 0: return -1 return self.grow(one_child,max,depth-1) return 0 #should never get here def create_random_indiv(self,depth): self.buffer = [] len_g = self.grow(0,self.MAX_LEN,depth) while(len_g < 0): self.buffer = [] len_g = self.grow(0,self.MAX_LEN,depth) ind = [] for i in range(len_g): ind.append(self.buffer[i]) return ind def traverse(self,buffer,buffercount): if buffer[buffercount] < self.FSET_START: return buffercount+1 if buffer[buffercount] == self.ADD or buffer[buffercount] == self.SUB or buffer[buffercount] == self.MUL or buffer[buffercount] == self.DIV: return self.traverse(buffer,self.traverse(buffer,buffercount+1)) return 0 #should never get here def run(self): primitive = self.program[self.PC] self.PC += 1 if primitive < self.FSET_START: return self.x[primitive] if primitive == self.ADD: return self.run() + self.run() if primitive == self.SUB: return self.run() - self.run() if primitive == self.MUL: return self.run() * self.run() if primitive == self.DIV: num = self.run() den = self.run() if den <= 0.001: return num return num/den return 0 #should never get here def fitness_function(self,Prog): len = self.traverse(Prog,0) fit = 0.0 for i in range(self.fitnesscases): for j in range(self.varnumber): self.x[j] = self.targets[i][j] self.program = Prog self.PC = 0 result = self.run() fit += abs(result - self.targets[i][self.varnumber]) return -1*fit def create_random_pop(self,n,depth,fitness): pop = [] print "Creating population" for i in range(n): pop.append(self.create_random_indiv(depth)) self.fitness[i] = self.fitness_function(pop[i]) return pop def setup_fitness(self,fname): f_in = open(fname,"r") line = f_in.readline().strip() tokens = line.split() self.varnumber = int(tokens[0]) self.randomnumber = int(tokens[1]) self.minrandom = int(tokens[2]) self.maxrandom = int(tokens[3]) self.fitnesscases = int(tokens[4]) if self.varnumber+self.randomnumber >= self.FSET_START: print "too many variables and constants" self.targets = [] for i in range(self.fitnesscases): line = f_in.readline().strip() tokens = line.split() temp = [] for j in range(self.varnumber+1): temp.append(float(tokens[j])) self.targets.append(temp) f_in.close() print "" def print_indiv(self,buffer,buffercounter): a1 = 0 if(buffer[buffercounter] < self.FSET_START): if buffer[buffercounter] < self.varnumber: sys.stdout.write( "X"+str(buffer[buffercounter]+1)+" ") else: sys.stdout.write(str(self.x[buffer[buffercounter]])) return buffercounter + 1 if buffer[buffercounter] == self.ADD: sys.stdout.write("(") a1 = self.print_indiv(buffer,buffercounter+1) sys.stdout.write(" + ") elif buffer[buffercounter] == self.SUB: sys.stdout.write("(") a1 = self.print_indiv(buffer,buffercounter+1) sys.stdout.write(" - ") elif buffer[buffercounter] == self.MUL: sys.stdout.write("(") a1 = self.print_indiv(buffer,buffercounter+1) sys.stdout.write(" * ") elif buffer[buffercounter] == self.DIV: sys.stdout.write("(") a1 = self.print_indiv(buffer,buffercounter+1) sys.stdout.write(" / ") a2 = self.print_indiv(buffer,a1) sys.stdout.write(" ) ") return a2 def stats(self, fitness,pop,gen): best = random.randint(0,self.POPSIZE-1) self.fbestpop = fitness[best] self.favgpop = 0.0 node_count = 0.0 for i in range(self.POPSIZE): node_count += self.traverse(pop[i],0) self.favgpop += fitness[i] if fitness[i] > self.fbestpop: best = i self.fbestpop = fitness[i] avg_len = node_count/self.POPSIZE self.favgpop = self.favgpop /self.POPSIZE print "Generation="+str(gen)+" Avg Fitness="+str(-1*self.favgpop)+" Best Fitness="+str(-1*self.fbestpop)+" Avg Size="+str(avg_len)+"\nBest Individual: " self.print_indiv(pop[best],0) def print_parms(self): print "-- TINY GP (Python Version) --" print "SEED="+str(self.seed)+"\nMAX_LEN="+str(self.MAX_LEN)+"\nPOPSIZE="+str(self.POPSIZE)+"\nDEPTH="+str(self.DEPTH)+"\nCROSSOVER_PROB="+str(self.CROSSOVER_PROB)+"\nPMUT_PER_NODE="+str(self.PMUT_PER_NODE)+"\nMIN_RANDOM="+str(self.minrandom)+"\nMAX_RANDOM="+str(self.maxrandom)+"\nGENERATIONS="+str(self.GENERATIONS)+"\nTSIZE="+str(self.TSIZE)+"\n----------------------------------" def tournament (self, fitness, tsize): best = random.randint(0,self.POPSIZE-1) fbest = -1.0e34 for i in range(tsize): competitor = random.randint(0,self.POPSIZE-1) if fitness[competitor] > fbest: fbest =fitness[competitor] best = competitor return best def arraycopy(self, scr,scr_start,dest,dest_start, length): for i in range(length): dest[dest_start + i] = scr[scr_start+i] def crossover(self,parent1,parent2): offspring = [] len1 = self.traverse(parent1,0) len2 = self.traverse(parent2,0) xo1start = random.randint(0,len1-1) xo1end = self.traverse(parent1,xo1start) xo2start = random.randint(0,len2-1) xo2end = self.traverse(parent2,xo2start) lenoff = xo1start + (xo2end - xo2start) + (len1-xo1end); offspring = [1]*lenoff; self.arraycopy( parent1, 0, offspring, 0, xo1start ); self.arraycopy( parent2, xo2start, offspring, xo1start,(xo2end - xo2start) ); self.arraycopy( parent1, xo1end, offspring,xo1start + (xo2end - xo2start), (len1-xo1end) ); """for i in range(xo1start): offspring.append(parent1[i]) for i in range(xo2start,xo2end): offspring.append(parent2[i]) for i in range(xo1end,len1): offspring.append(parent1[i])""" return offspring def mutation(self,parent,pmut): parentcopy = [] len = self.traverse(parent,0) for i in range(len): parentcopy.append(parent[i]) for i in range(len): if random.uniform(0.0,1.0) < pmut : mutsite = i if parentcopy[mutsite] <self.FSET_START: parentcopy[mutsite] = random.randint(0,self.varnumber+self.randomnumber-1) else: if parentcopy[mutsite] == self.ADD or parentcopy[mutsite] == self.SUB or parentcopy[mutsite] == self.MUL or parentcopy[mutsite] == self.DIV: parentcopy[mutsite] = random.randint(0,self.FSET_END-self.FSET_START) +self.FSET_START return parentcopy def negative_tournament(self,fitness,tsize): worst = random.randint(0,self.POPSIZE-1) fworst = 1e34 for i in range(tsize): competitor = random.randint(0,self.POPSIZE-1) if fitness[competitor] < fworst: fworst = fitness[competitor] worst = competitor return worst def evolve(self): self.print_parms() self.stats(self.fitness,self.pop,0) #raise KeyboardInterrupt for gen in range(1,self.GENERATIONS): if self.fbestpop > -0.00005: print "PROBLEM SOLVED" sys.exit(0) for indivs in range(self.POPSIZE): if random.uniform(0.0,1.0) < self.CROSSOVER_PROB: parent1 = self.tournament(self.fitness,self.TSIZE) parent2 = self.tournament(self.fitness,self.TSIZE) newind = self.crossover(self.pop[parent1],self.pop[parent2]) max = 0; parent1_len = self.traverse(self.pop[parent1],0); parent2_len = self.traverse(self.pop[parent2],0); max = parent2_len; if parent1_len > parent2_len: max = parent1_len; max += 10; while self.traverse(newind,0) > max: parent1 = self.tournament(self.fitness,self.TSIZE) parent2 = self.tournament(self.fitness,self.TSIZE) newind = self.crossover(self.pop[parent1],self.pop[parent2]) max = 0; parent1_len = self.traverse(self.pop[parent1],0); parent2_len = self.traverse(self.pop[parent2],0); max = parent2_len; if parent1_len > parent2_len: max = parent1_len; max += 10; else: parent = self.tournament(self.fitness,self.TSIZE) newind = self.mutation(self.pop[parent],self.PMUT_PER_NODE) newfit = self.fitness_function(newind) offspring = self.negative_tournament(self.fitness,self.TSIZE) self.pop[offspring] = newind self.fitness[offspring] = newfit self.stats(self.fitness,self.pop,gen) print "PROBLEM *NOT* SOLVED" sys.exit(0) def main(): fname = "C:\\Train\\TinyGP\\problem.dat" s = -1 if len(sys.argv) == 3: s = int(sys.argv[1]) fname = sys.argv[2] if len(sys.argv) == 2: fname = sys.argv[1] gp = tiny_gp(fname,s) gp.evolve() if __name__ == '__main__': main()
3e7445955c11ca7a516caa4a66f68297863e1bc6
[ "Python" ]
1
Python
chestergrant/TinyGP
63a6c26a2f11dac0a2ff91f44c41d23cbcd00010
4565013568cff0cad31e0bbc702a12b5220e1569
refs/heads/master
<repo_name>CSer2294365315/coolweather_Q2<file_sep>/app/src/main/java/com/cmxCor/weather/service/AutoUpdateService.java package com.cmxCor.weather.service; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.os.IBinder; import android.os.SystemClock; import android.preference.PreferenceManager; import com.cmxCor.weather.gson.Weather; import com.cmxCor.weather.util.HttpUtil; import com.cmxCor.weather.util.Utility; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class AutoUpdateService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { updateWeather(); updateBingPic(); AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE); int anHour = 8 * 60 * 60 * 1000; // 这是8小时的毫秒数 long triggerAtTime = SystemClock.elapsedRealtime() + anHour; Intent i = new Intent(this, AutoUpdateService.class); PendingIntent pi = PendingIntent.getService(this, 0, i, 0); manager.cancel(pi); manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi); return super.onStartCommand(intent, flags, startId); } /** * 更新天气信息。 */ private void updateWeather(){ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String weatherString = prefs.getString("weather", null); if (weatherString != null) { // 有缓存时直接解析天气数据 Weather weather = Utility.handleWeatherResponse(weatherString); String weatherId = weather.basic.weatherId; String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=<KEY>"; HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { String responseText = response.body().string(); Weather weather = Utility.handleWeatherResponse(responseText); if (weather != null && "ok".equals(weather.status)) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit(); editor.putString("weather", responseText); editor.apply(); } } @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } }); } } /** * 更新必应每日一图 */ private void updateBingPic() { String requestBingPic = "http://guolin.tech/api/bing_pic"; HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { String bingPic = response.body().string(); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit(); editor.putString("bing_pic", bingPic); editor.apply(); } @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } }); } } <file_sep>/app/src/main/java/com/cmxCor/weather/util/Utility.java package com.cmxCor.weather.util; import android.text.TextUtils; import com.cmxCor.weather.db.City; import com.cmxCor.weather.db.County; import com.cmxCor.weather.db.Province; import com.cmxCor.weather.gson.Weather; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Utility { /** * 解析和处理服务器返回的省级数据 */ public static boolean handleProvinceResponse(String response) { if (!TextUtils.isEmpty(response)) { try { JSONArray allProvinces = new JSONArray(response); for (int i = 0; i < allProvinces.length(); i++) { JSONObject provinceObject = allProvinces.getJSONObject(i); Province province = new Province(); province.setProvinceName(provinceObject.getString("name")); province.setProvinceCode(provinceObject.getInt("id")); province.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } /** * 解析和处理服务器返回的市级数据 */ public static boolean handleCityResponse(String response, int provinceId) { if (!TextUtils.isEmpty(response)) { try { JSONArray allCities = new JSONArray(response); for (int i = 0; i < allCities.length(); i++) { JSONObject cityObject = allCities.getJSONObject(i); City city = new City(); city.setCityName(cityObject.getString("name")); city.setCityCode(cityObject.getInt("id")); city.setProvinceId(provinceId); city.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } /** * 解析和处理服务器返回的县级数据 */ public static boolean handleCountyResponse(String response, int cityId) { if (!TextUtils.isEmpty(response)) { try { JSONArray allCounties = new JSONArray(response); for (int i = 0; i < allCounties.length(); i++) { JSONObject countyObject = allCounties.getJSONObject(i); County county = new County(); county.setCountyName(countyObject.getString("name")); county.setWeatherId(countyObject.getString("weather_id")); county.setCityId(cityId); county.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } /** * 将返回的JSON数据解析成Weather实体类 */ public static Weather handleWeatherResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather"); String weatherContent = jsonArray.getJSONObject(0).toString(); return new Gson().fromJson(weatherContent, Weather.class); } catch (Exception e) { e.printStackTrace(); } return null; } } <file_sep>/app/src/main/java/com/cmxCor/weather/ChooseAreaFragment.java package com.cmxCor.weather; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.cmxCor.weather.db.City; import com.cmxCor.weather.db.County; import com.cmxCor.weather.db.Province; import com.cmxCor.weather.util.HttpUtil; import com.cmxCor.weather.util.Utility; import org.litepal.crud.DataSupport; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class ChooseAreaFragment extends Fragment { private static final String TAG = "ChooseAreaFragment"; public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private Button backButton; private ListView listView; private ArrayAdapter<String> adapter; private List<String> dataList = new ArrayList<>(); /** * 省列表 */ private List<Province> provinceList; /** * 市列表 */ private List<City> cityList; /** * 县列表 */ private List<County> countyList; /** * 选中的省份 */ private Province selectedProvince; /** * 选中的城市 */ private City selectedCity; /** * 当前选中的级别 */ private int currentLevel; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_area, container, false); titleText = (TextView) view.findViewById(R.id.title_text); backButton = (Button) view.findViewById(R.id.back_button); listView = (ListView) view.findViewById(R.id.list_view); adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (currentLevel == LEVEL_PROVINCE) { selectedProvince = provinceList.get(position); queryCities(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(position); queryCounties(); } else if (currentLevel == LEVEL_COUNTY) { String weatherId = countyList.get(position).getWeatherId(); if (getActivity() instanceof MainActivity) { Intent intent = new Intent(getActivity(), WeatherActivity.class); intent.putExtra("weather_id", weatherId); startActivity(intent); getActivity().finish(); } else if (getActivity() instanceof WeatherActivity) { WeatherActivity activity = (WeatherActivity) getActivity(); activity.drawerLayout.closeDrawers(); activity.swipeRefresh.setRefreshing(true); activity.requestWeather(weatherId); } } } }); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentLevel == LEVEL_COUNTY) { queryCities(); } else if (currentLevel == LEVEL_CITY) { queryProvinces(); } } }); queryProvinces(); } /** * 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询。 */ private void queryProvinces() { titleText.setText("中国"); backButton.setVisibility(View.GONE); provinceList = DataSupport.findAll(Province.class); if (provinceList.size() > 0) { dataList.clear(); for (Province province : provinceList) { dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_PROVINCE; } else { String address = "http://guolin.tech/api/china"; queryFromServer(address, "province"); } } /** * 查询选中省内所有的市,优先从数据库查询,如果没有查询到再去服务器上查询。 */ private void queryCities() { titleText.setText(selectedProvince.getProvinceName()); backButton.setVisibility(View.VISIBLE); cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class); if (cityList.size() > 0) { dataList.clear(); for (City city : cityList) { dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_CITY; } else { int provinceCode = selectedProvince.getProvinceCode(); String address = "http://guolin.tech/api/china/" + provinceCode; queryFromServer(address, "city"); } } /** * 查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询。 */ private void queryCounties() { titleText.setText(selectedCity.getCityName()); backButton.setVisibility(View.VISIBLE); countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class); if (countyList.size() > 0) { dataList.clear(); for (County county : countyList) { dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_COUNTY; } else { int provinceCode = selectedProvince.getProvinceCode(); int cityCode = selectedCity.getCityCode(); String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode; queryFromServer(address, "county"); } } /** * 根据传入的地址和类型从服务器上查询省市县数据。 */ private void queryFromServer(String address, final String type) { showProgressDialog(); HttpUtil.sendOkHttpRequest(address, new Callback() { @Override public void onResponse(Call call, Response response) throws IOException { String responseText = response.body().string(); boolean result = false; if ("province".equals(type)) { result = Utility.handleProvinceResponse(responseText); } else if ("city".equals(type)) { result = Utility.handleCityResponse(responseText, selectedProvince.getId()); } else if ("county".equals(type)) { result = Utility.handleCountyResponse(responseText, selectedCity.getId()); } if (result) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)) { queryProvinces(); } else if ("city".equals(type)) { queryCities(); } else if ("county".equals(type)) { queryCounties(); } } }); } } @Override public void onFailure(Call call, IOException e) { // 通过runOnUiThread()方法回到主线程处理逻辑 getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show(); } }); } }); } /** * 显示进度对话框 */ private void showProgressDialog() { if (progressDialog == null) { progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("正在加载..."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } /** * 关闭进度对话框 */ private void closeProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); } } } <file_sep>/app/src/main/java/com/cmxCor/weather/gson/Weather.java package com.cmxCor.weather.gson; import com.google.gson.annotations.SerializedName; import java.util.List; public class Weather { public String status; public Basic basic; public AQI aqi; public Now now; public Suggestion suggestion; @SerializedName("daily_forecast") public List<Forecast> forecastList; } <file_sep>/app/src/main/java/com/cmxCor/weather/gson/Now.java package com.cmxCor.weather.gson; import com.google.gson.annotations.SerializedName; public class Now { @SerializedName("tmp") public String temperature; @SerializedName("cond") public More more; public class More { @SerializedName("txt") public String info; } }
74d024648e1eebb0c3d0c2c4a4f82768ed789482
[ "Java" ]
5
Java
CSer2294365315/coolweather_Q2
7034fd0c3ae4ac8569e9c27bd4bc3279851160f0
385c72c07a9a3457de1358e907d41f3d12f781bd
refs/heads/master
<file_sep>$('.submenu-icon').on('click', function() { var $submenu = $(this).parent().siblings('.submenu'), pointingRight = 'matrix(-1, 1.22465e-16, -1.22465e-16, -1, 0, 0)', WEBKITpointingRight = 'matrix(-1, 0.00000000000000012246467991473532, -0.00000000000000012246467991473532, -1, 0, 0)', MOZpointingRight = 'matrix(0, -1, 1, 0, 0, 0)', pointingDown = 'matrix(-1.83697e-16, -1, 1, -1.83697e-16, 0, 0)', WEBKITpointingDown = 'matrix(-0.0000000000000002220446049250313, -1, 1, -0.0000000000000002220446049250313, 0, 0)', $svgClicked = $submenu.siblings('div.tab-cont').find('svg'), $transformValue = $svgClicked.css('transform'), $MOZtransformValue = $svgClicked.css('-moz-transform'), $WEBKITtransformValue = $svgClicked.css('-webkit-transform'); //$('.submenu-icon').parent().siblings('.submenu').siblings('div.tab-cont').find('svg').css('-webkit-transform') $('.submenu').each(function() { var $thisSubmenu = $(this)[0], $clickedsubmenu = $submenu[0]; if( $thisSubmenu !== $clickedsubmenu ) { $(this).slideUp(); $(this).siblings('div.tab-cont').find('svg').css({ '-webkit-transform' : WEBKITpointingRight, '-moz-transform' : MOZpointingRight, 'transform' : pointingRight }) } }); $submenu.slideToggle(); if( pointingRight === $transformValue || MOZpointingRight === $MOZtransformValue || WEBKITpointingRight === $WEBKITtransformValue) { $transformValue = $svgClicked.css({ '-webkit-transform' : WEBKITpointingDown, '-moz-transform' : 'rotate(360deg)', 'transform' : pointingDown }); } else { $transformValue = $svgClicked.css({ '-webkit-transform' : WEBKITpointingRight, '-moz-transform' : MOZpointingRight, 'transform' : pointingRight }); } })<file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Christmas Lights</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="assets/img/FSsymbol.png" type="image/x-icon" /> <link href="https://fonts.googleapis.com/css?family=Open+Sans:700,800i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Cabin+Condensed:700" rel="stylesheet"> <link rel="stylesheet" href="normalize.css" /> <link rel="stylesheet" href="landing_styles.css" /> </head> <body> <div class="div1"> <div class="FSsymbol"> <div class="FScontainer"> <a href="index.html"><img src="assets/svg/FSsymbol.svg" /></a> </div> </div> <div class="holiday_lights"> <div class="HLcontainer"> <img src="assets/svg/HolidayLights.svg" /> </div> </div> <div class="phone"> <div class="phoneContainer"><a href="tel:9186054763">918-605-4763</a></div> </div> </div> <div class="div2"> <div class="inside_div2"> <div class="snow"></div> </div> </div> <div class="div3"> <div class="inside_div3"> <ul class="info"> <li>Create a feeling of home based around your personal style.</li> <li>Options include Gutters and/or roofline or custom package.</li> <li>Traditional - Modern - Country</li> <li>More than just lights! We can tailor a package with additional greenary, wreaths, yard statuaries etc. to create your ultimate idea of the perfect display.</li> </ul> <div class="pic"> <div class="picContainer"> <img src="assets/img/stringLights.jpg" /> </div> </div> </div> </div> <div class="divider"> <div class="snow"></div> </div> <div class="div4"> <?php $lightingType = ""; if (isset($_POST["submitButton"]) && !empty($_POST["submitButton"])) { if(!isset($_POST['property_type'])) { $_POST['property_type'] = ""; } if(!isset($_POST['lighting_type'])) { $lightingType = ""; } else { foreach ($_POST['lighting_type'] as $value) { $lightingType .= $value . "/"; } } $to = "<EMAIL>"; $subject = "QUOTE REQUEST - CHRISTMAS LIGHTS"; $txt = "Name: ". $_POST['name'] . "\n Email: " . $_POST['email'] . "\n Phone: " . $_POST['phone'] . "\n Address: " . $_POST['address'] . "\n Property Type: " . $_POST['property_type'] ."\n Lighting Type: " . $lightingType . "\n Comment: " . $_POST['comment'] ; $headers = "Reply-To: " . $_POST['email']; if(mail($to,$subject,$txt,$headers)) { echo "<h1 class='response'>Thank you for your interest! We will contact you soon</h1>"; } else { echo "<h1 class='response'>There was a problem sending your email. Please try again later</h1>"; } } else { echo '<h3>Contact Form</h3> <form method="POST" class="myForm"> <div class="box1"> <div class="inputWrapper"><label for="name">Name: </label><span><input type="text" id="name" name="name"></span></div> <div class="inputWrapper"><label for="email">Email: </label><span><input type="email" id="email" name="email"></span></div> <div class="inputWrapper"><label for="phone">Phone: </label><span><input type="tel" id="phone" name="phone"></span></div> <div class="inputWrapper"><label for="address">Address: </label><span><input type="text" id="address" name="address"></span></div> </div> <div class="box2"> <div class="inputWrapper"> <label class="breakAfter">Property Type: </label> <input type="radio" id="property_type1" name="property_type" value="Commerical"/><label for="property_type1">Commerical</label> <input type="radio" id="property_type2" name="property_type" value="Residential"/><label for="property_type2">Residential</label><br /> </div> <div class="inputWrapper"> <label class="breakAfter">Lighting Type: </label> <input type="checkbox" id="lighting_type1" name="lighting_type[]" value="Front-Face"><label for="lighting_type1">Front Face</label> <input type="checkbox" id="lighting_type2" name="lighting_type[]" value="Roofline"><label for="lighting_type2">Roofline</label> <input type="checkbox" id="lighting_type3" name="lighting_type[]" value="Custom"><label for="lighting_type3">Custom</label><br /> <div class="inputWrapper"> <label for="comments">Comments: </label><br /> <textarea id="comments" name="comment"></textarea> </div> </div> </div> <input type="submit" name="submitButton" value="Click Here to Submit!"/> </form>'; } ?> </div> <div class="div5"> <div class="snow"></div> </div> </body> </html> <file_sep> /************************TESTIMONIALS CAROUSEL******************************/ $('.testimonials').slick({ dots : false, autoplay : true, arrows : false, }); /************************PHOTO GALLERY CAROUSEL******************************/ $('.photo_gallery').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: true, fade: true, });<file_sep>var windowWidth = $(window).width(); if(windowWidth > 768){ $('.nav_toggle_btn').on('click', function() { var $navigationStatus = $('.nav-outer-cont-mobile').css('margin-left'), $pointingRight = 'matrix3d(-0.866025, 0, -0.5, 0, 0, 1, 0, 0, 0.5, 0, -0.866025, 0, 0, 0, 0, 1)'; if( $navigationStatus === '0px') { $('.nav-outer-cont-mobile').css('margin-left', '-270px'); $('.nav_toggle_btn .arrow').css('transform', $pointingRight); $('.mainarea').css('margin-left', '0px'); } else { $('.nav-outer-cont-mobile').css('margin-left', '0px'); $('.nav_toggle_btn .arrow').css('transform', 'rotateY(0deg)'); $('.mainarea').css('margin-left', '270px'); } }) } if(windowWidth < 768) { $('.nav_toggle_btn').on('click', function() { var $navigationStatus = $('.nav-outer-cont-mobile').css('margin-left'), $pointingRight = 'matrix3d(-0.866025, 0, -0.5, 0, 0, 1, 0, 0, 0.5, 0, -0.866025, 0, 0, 0, 0, 1)'; if( $navigationStatus === '0px') { $('.nav-outer-cont-mobile').css('margin-left', '-270px'); $('.nav_toggle_btn .arrow').css('transform', $pointingRight); } else { $('.nav-outer-cont-mobile').css('margin-left', '0px'); $('.nav_toggle_btn .arrow').css('transform', 'rotateY(0deg)'); } }) }<file_sep>/******************Service Item Hover***********************/ $('.service_item').on('mouseenter', function() { $(this).find('.service_overlay').stop().fadeIn(); $(this).find('.service_overlay .service_overlay_content').stop().animate({ top: "45px", opacity: "1" }, 200, "linear"); $(this).find('.service_title_container').stop().animate({ top : "52%" }, 200); }).on('mouseleave', function() { $(this).find('.service_overlay').stop().fadeOut(); $(this).find('.service_overlay .service_overlay_content').stop().animate({ top: "100px", opacity: "0" }, 200); $(this).find('.service_title_container').stop().animate({ top : "47%" }); }) /******************Flow Navigation***********************/ $('.nav-list li').on('mouseenter', function() { $(this).find('.services_nav_list').stop().slideDown("fast"); }).on('mouseleave', function() { $(this).find('.services_nav_list').stop().slideUp("fast"); }) /******************Phone Input Formatting***********************/ $("input[name='phone']").keyup(function() { $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3")); }); /******************Header Scroll Shrink***********************/ $(function(){ $('.header_and_nav').data('size','big'); }); $(window).scroll(function(){ if($(document).scrollTop() > 0) { if($('.header_and_nav').data('size') == 'big') { $('.header_and_nav').data('size','small'); $('.nav-list').addClass("shrink_nav_list"); $('.logo').addClass("shrink_logo"); $('.contact_info').addClass("shrink_contact_info"); $('.header_and_nav').addClass("shrink_header_and_nav"); $('.services_nav_list').addClass("services_list_shrink_adjustment"); } } else { if($('.header_and_nav').data('size') == 'small') { $('.header_and_nav').data('size','big'); $('.nav-list').removeClass("shrink_nav_list"); $('.logo').removeClass("shrink_logo"); $('.contact_info').removeClass("shrink_contact_info"); $('.header_and_nav').removeClass("shrink_header_and_nav"); $('.services_nav_list').removeClass("services_list_shrink_adjustment"); } } }); /******************Content Scroll Fade/Slide In***********************/ $(window).scroll(function(){ if($(document).scrollTop() > 600) { $('.outer:eq(' + '0'+ ')').removeClass('hide_it'); } if($(document).scrollTop() > 1500) { $('.outer:eq(1)').removeClass('hide_it'); } if($(document).scrollTop() > 2100) { $('.outer:eq(2)').removeClass('hide_it'); } });
eac49db98035c099828d835b2703be26dde0c2a3
[ "JavaScript", "PHP" ]
5
JavaScript
shaun0072/FiftyShadesofGreen
b5d364a5a61e07fa1160698129598b0b9c9bf335
e5daca1faec7e24ce948fa467be2046d43e07058
refs/heads/master
<repo_name>Zebrilus/kicktipper<file_sep>/src/de/nufta/kicktipper/Game.java package de.nufta.kicktipper; import de.nufta.kicktipper.KickTipper.Mode; public class Game implements Comparable<Game> { public enum Result { WON, LOST, DRAW }; static volatile int counter = 0; final private String tournamentPhaseName; final private int tournamentPhaseNumber; final private int season; final private int day; final private String date; final private Team team1; final private Team team2; private int score1; private int score2; private int id = ++counter; /** * @param score1 the score1 to set */ public void setScore1(int score1) { this.score1 = score1; } /** * @param score2 the score2 to set */ public void setScore2(int score2) { this.score2 = score2; } private double ratingBefore1; private double ratingBefore2; private double ratingAfter1; private double ratingAfter2; public Game(final String date, final int season, final int day, final Team team1, final Team team2, final int score1, final int score2) { this("", 0, date, season, day, team1, team2, score1, score2); } public Game(final String tournamentPhaseName, final int tournamentPhaseNumber, final String date, final int season, final int day, final Team team1, final Team team2, final int score1, final int score2) { this.tournamentPhaseName = tournamentPhaseName; this.tournamentPhaseNumber = tournamentPhaseNumber; this.day = day; this.team1 = team1; this.team2 = team2; this.score1 = score1; this.score2 = score2; this.season = season; this.date = date; } /** Create a reverse game for ease of prediction in world cup mode */ private Game(Game o) { this.tournamentPhaseName = o.tournamentPhaseName; this.tournamentPhaseNumber = o.tournamentPhaseNumber; this.day = o.day; this.team1 = o.team2; this.team2 = o.team1; this.score1 = o.score2; this.score2 = o.score1; this.season = o.season; this.date = o.date; this.ratingBefore1 = o.ratingBefore2; this.ratingAfter1 = o.ratingAfter2; this.ratingBefore2 = o.ratingBefore1; this.ratingAfter2 = o.ratingAfter1; this.id = o.id; } Game createReverseGame() { return new Game(this); } /** * @return the season */ public int getSeason() { return season; } /** * @return the date */ public int getDay() { return day; } /** * @return tournament Phase ID */ public int getTournamentPhaseNumber() { return tournamentPhaseNumber; } public String getTournamentPhaseName() { return tournamentPhaseName; } /** * @return the team1 */ public Team getTeam1() { return team1; } /** * @return the team2 */ public Team getTeam2() { return team2; } /** * @return the score1 */ public int getScore1() { return score1; } /** * @return the score2 */ public int getScore2() { return score2; } /** * @return the rating1 */ public double getRatingBefore1() { return ratingBefore1; } /** * @param rating1 the rating1 to set */ public void setRatingBefore1(double rating1) { this.ratingBefore1 = rating1; } /** * @return the rating2 */ public double getRatingBefore2() { return ratingBefore2; } /** * @param rating2 the rating2 to set */ public void setRatingBefore2(double rating2) { this.ratingBefore2 = rating2; } /** * @return the ratingAfter1 */ public double getRatingAfter1() { return ratingAfter1; } /** * @return the ratingAfter2 */ public double getRatingAfter2() { return ratingAfter2; } /** * @param ratingAfter1 the ratingAfter1 to set */ public void setRatingAfter1(double ratingAfter1) { this.ratingAfter1 = ratingAfter1; } /** * @param ratingAfter2 the ratingAfter2 to set */ public void setRatingAfter2(double ratingAfter2) { this.ratingAfter2 = ratingAfter2; } // Standard @Override public int compareTo(Game o) { if (this.tournamentPhaseNumber != o.tournamentPhaseNumber) { return new Integer(this.tournamentPhaseNumber).compareTo(o.tournamentPhaseNumber); } if (this.day != o.day) { return new Integer(this.day).compareTo(new Integer(o.day)); } return new Integer(this.id).compareTo(new Integer(o.id)); } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + day; result = prime * result + id; long temp; temp = Double.doubleToLongBits(ratingAfter1); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(ratingAfter2); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(ratingBefore1); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(ratingBefore2); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + score1; result = prime * result + score2; result = prime * result + season; result = prime * result + ((team1 == null) ? 0 : team1.hashCode()); result = prime * result + ((team2 == null) ? 0 : team2.hashCode()); result = prime * result + ((tournamentPhaseName == null) ? 0 : tournamentPhaseName.hashCode()); result = prime * result + tournamentPhaseNumber; return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Game other = (Game) obj; if (day != other.day) return false; if (id != other.id) return false; if (Double.doubleToLongBits(ratingAfter1) != Double.doubleToLongBits(other.ratingAfter1)) return false; if (Double.doubleToLongBits(ratingAfter2) != Double.doubleToLongBits(other.ratingAfter2)) return false; if (Double.doubleToLongBits(ratingBefore1) != Double.doubleToLongBits(other.ratingBefore1)) return false; if (Double.doubleToLongBits(ratingBefore2) != Double.doubleToLongBits(other.ratingBefore2)) return false; if (score1 != other.score1) return false; if (score2 != other.score2) return false; if (season != other.season) return false; if (team1 == null) { if (other.team1 != null) return false; } else if (!team1.equals(other.team1)) return false; if (team2 == null) { if (other.team2 != null) return false; } else if (!team2.equals(other.team2)) return false; if (tournamentPhaseName == null) { if (other.tournamentPhaseName != null) return false; } else if (!tournamentPhaseName.equals(other.tournamentPhaseName)) return false; if (tournamentPhaseNumber != other.tournamentPhaseNumber) return false; return true; } public Result getResult() { int diff = getScore1() - getScore2(); if (diff < 0) { return Result.LOST; } else if (diff > 0) { return Result.WON; } return Result.DRAW; } private double getRatingDifference() { return getRatingBefore1() - getRatingBefore2(); } double getCorrectedRatingDifference() { double diff = getRatingBefore1() - getRatingBefore2(); double correction = WorldRepository.getInstance().getCorrection(getTeam1().getName(), getTeam2().getName()); return diff + correction; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(season + " "); if (!tournamentPhaseName.isEmpty()) { sb.append(tournamentPhaseName + " # "); } if (day < SeasonParser.FINALS_OFFSET) { sb.append("," + day + ".ST "); } else { sb.append(SeasonParser.FINALS_NAMES[day - SeasonParser.FINALS_OFFSET] + " "); } sb.append("<" + date + ">:"); sb.append(team1.getName() + "(" + Math.round(ratingBefore1)); if (ratingAfter1 > 0) { sb.append("->" + Math.round(ratingAfter1)); } sb.append(") "); sb.append(score1 + ":" + score2 + " " + team2.getName() + "(" + Math.round(ratingBefore2)); if (ratingAfter2 > 0) { sb.append("->" + Math.round(ratingAfter2)); } sb.append(") -> diff:" + (Math.round(getRatingDifference()))); if (KickTipper.getMode().equals(Mode.WORLD_CUP)) { WorldRepository worldRepository = WorldRepository.getInstance(); sb.append(" -- corrected diff: " + (Math.round(getRatingDifference() + worldRepository.getCorrection(getTeam1().getName(), getTeam2().getName())))); } return sb.toString(); } public int getID() { return id; } } <file_sep>/src/de/nufta/kicktipper/KickTipper.java package de.nufta.kicktipper; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.goochjs.glicko2.RatingCalculator; import de.nufta.kicktipper.Game.Result; /** * @author ulrich.luebke * */ public class KickTipper { enum Mode { LEAGUE, WORLD_CUP }; // private static final String[] SEASON_NAMES = { "blfr_2013_res.txt", "blfr_2014_res.txt", "blfr_2015_res.txt", // "blfr_2016_res.txt", "blfr_2017_res.txt" }; // private static final int FIRST_YEAR = 2013; // private static final int PREDICT_YEAR = 2017; // private static final String PRED_GAMES = "blfr_pred.txt"; private static Mode mode; private final String tournamentName; private final String tournamentShortName; private final int startYear; private final int endYear; private final int predictionYear; /** * Show debug printouts on console */ private static boolean debug = false; List<Season> seasons = new ArrayList<Season>(); RatingCalculator calc = new RatingCalculator(); Season predictions; /** * Creates a new Instance * * @param mode Tournament Mode (Necessary for fileformat parsing) // Data copy-pasted from flashscore.de * @param tournamentName name of the tournament * @param tournamentShortName short name for identifying files ("blfr" -> Bundesliga Frauen "wm" -> * Fußballweltmeisterschaft) * @param fromYear use historical data beginning with this year * @param toYear use historical data up to and including this year * @param predictionYear year of the tournament to predict */ KickTipper(final String tournamentName, final String tournamentShortName, final int startYear, final int endYear, final int predictionYear) { this.tournamentName = tournamentName; this.tournamentShortName = tournamentShortName; this.startYear = startYear; this.endYear = endYear; this.predictionYear = predictionYear; } private void run() { loadSeasons(); loadPredictions(); } /** * Enable / disable debug output */ static void setDebug(boolean b) { debug = b; } static boolean isDebug() { return debug; } private void loadSeasons() { int year = startYear; Season previousSeason = null; final String resultFilePrefix = tournamentShortName + "_"; final String resultFilePostfix = "_res.txt"; while (year <= endYear) { final String seasonFileName = resultFilePrefix + year + resultFilePostfix; SeasonParser parser = new SeasonParser(year, seasonFileName, SeasonParser.SEASON_MODE, calc, previousSeason); switch (mode) { case LEAGUE: { year++; break; } case WORLD_CUP: { year += 4; break; } } Season s = parser.parse(); s.rate(); if (mode.equals(Mode.WORLD_CUP)) { List<Game> games = s.getGames(); WorldRepository worldRepository = WorldRepository.getInstance(); for (Game game : games) { worldRepository.rate(game.getTeam1().getName(), game.getTeam2().getName(), game.getScore1(), game.getScore2()); } } if (isDebug()) { System.out.println("SeasonParser: " + s.toString()); } seasons.add(s); previousSeason = s; } } private void loadPredictions() { String predictionFileName = tournamentShortName + "_pred.txt"; SeasonParser parser = new SeasonParser(predictionYear, predictionFileName, SeasonParser.PREDICT_MODE, calc, seasons.get(seasons.size() - 1)); predictions = parser.parse(); } private void predict() { ArrayList<Game> allGames = new ArrayList<Game>(); for (Season season : seasons) { // In the first season the glicko rating is not yet accurate, so leave that out. if (season.year > this.startYear) { List<Game> games = season.getGames(); allGames.addAll(games); if (Mode.WORLD_CUP.equals(getMode())) { for (Game game : games) { allGames.add(game.createReverseGame()); } } } } List<Game> predGames = predictions.getGames(); System.out.println("Predictions for \"" + tournamentName + " " + predictionYear + "\""); for (Game pGame : predGames) { double rating1 = pGame.getTeam1().getRating().getRating(); pGame.setRatingBefore1(rating1); double rating2 = pGame.getTeam2().getRating().getRating(); pGame.setRatingBefore2(rating2); final double diff = pGame.getCorrectedRatingDifference(); allGames.sort((g1, g2) -> { double diff1 = g1.getCorrectedRatingDifference(); double diff2 = g2.getCorrectedRatingDifference(); double d1 = Math.abs(diff - diff1); double d2 = Math.abs(diff - diff2); int compareTo = new Double(d1).compareTo(new Double(d2)); return compareTo; }); int target = 6; int cnt = 0; final int maxQualityDifference = mode.equals(Mode.LEAGUE) ? 20 : 10; final int maxRatingDifference = 700; List<Game> selected = new ArrayList<>(); HashSet<Integer> selectedIDs = new HashSet<>(); int[] results = new int[Game.Result.values().length]; for (Game mGame : allGames) { double tDiff = mGame.getCorrectedRatingDifference(); double quality = Math.abs(tDiff - diff); double rDiff = Math.abs(mGame.getRatingBefore1()-pGame.getTeam1().getRating().getRating()); if (cnt++ >= target && (quality > maxQualityDifference || rDiff > maxRatingDifference)) { break; } Result result = mGame.getResult(); results[result.ordinal()]++; if (!selectedIDs.contains(mGame.getID()) ) { selected.add(mGame); selectedIDs.add(mGame.getID()); } } int leeway = selected.size() / 5; int max = Math.max(results[0], Math.max(results[1], results[2])); for (Iterator<Game> i = selected.iterator(); i.hasNext();) { Game game = i.next(); if (results[game.getResult().ordinal()] < max - leeway) { i.remove(); } } double home = 0, away = 0; final double gameBaseFactor = 1.0; final double qualityBaseFactor = 0.5; double divider = 0; for (Game mGame : selected) { double tDiff = mGame.getCorrectedRatingDifference(); double quality = Math.abs(tDiff - diff); if (cnt++ >= target && quality > maxQualityDifference) { break; } double qualityfactor = (maxQualityDifference - quality) * (qualityBaseFactor / maxQualityDifference); if (debug) { System.out.print("Quality: " + (Math.round(quality)) + ", Factor " + new DecimalFormat("0.00").format(gameBaseFactor + qualityfactor) + " ->"); System.out.println(mGame); } home += (mGame.getScore1() * (gameBaseFactor + qualityfactor)); away += (mGame.getScore2() * (gameBaseFactor + qualityfactor)); divider += (gameBaseFactor + qualityfactor); } home /= divider; away /= divider; double goalDiff = away - home; pGame.setScore1((int) Math.round(home)); pGame.setScore2((int) Math.round(pGame.getScore1() + goalDiff)); if (debug) { System.out.println("----> Predicted Result: " + pGame + " GoalDiff:" + new DecimalFormat("0.00").format(goalDiff)); System.out.println("\n\n"); } } System.out.println(predictions.toString()); } public static Mode getMode() { return mode; } public void printRanking(String...teamNames) { HashSet<String> filterSet = new HashSet<>(); filterSet.addAll(Arrays.asList(teamNames)); List<Team> allTeams = TeamRepository.getInstance().getAllTeams(); allTeams.sort((t1, t2) -> { return new Double(t2.getRating().getRating()).compareTo(new Double(t1.getRating().getRating())); });; for (Team team : allTeams) { if (filterSet.isEmpty() || filterSet.contains(team.getName())) { System.out.println(team); } } } /** * @param args */ public static void main(String[] args) { boolean debug = false; setDebug(debug); //setMode(Mode.LEAGUE); //KickTipper tipper = new KickTipper( "Bundesliga Frauen", "blfr", 2013, 2017, 2017); setMode(Mode.WORLD_CUP); KickTipper tipper = new KickTipper("Weltmeisterschaft", "wm", 2002, 2018, 2018); tipper.run(); tipper.predict(); //System.out.println(); //tipper.printRanking(); //System.out.println(WorldRepository.getInstance().getRegions()); //System.out.println(WorldRepository.getInstance().getRanking()); // tipper.printRanking("Russland", "Saudi Arabien", "Uruguay", "Ägypten"); // System.out.println(); // tipper.printRanking("Iran","Marokko", "Portugal", "Spanien"); // System.out.println(); // tipper.printRanking("Australien", "Dänemark", "Frankreich", "Peru"); // System.out.println(); // tipper.printRanking("Argentinien", "Island", "Kroatien", "Dänemark"); // System.out.println(); // tipper.printRanking("Brasilien", "Costa Rica", "Schweiz", "Serbien"); // System.out.println(); // tipper.printRanking("Deutschland","Mexiko", "Schweden", "Südkorea"); // System.out.println(); // tipper.printRanking("Belgien", "England", "Panama", "Tunesien"); // System.out.println(); // tipper.printRanking("Japan", "Kolumbien", "Polen", "Senegal"); } private static void setMode(final Mode mode) { KickTipper.mode = mode; } } <file_sep>/README.md # kicktipper Playing around with glicko ratings for the german woman's football league Needs Glicko2 Lib to run: https://github.com/goochjs/glicko2 PD. Do whatever you want with it. No guarantees of any kind though. Dedicated to <NAME> and <NAME>
2c018e3f61ef8114516a33966a65a932e52f8dd5
[ "Markdown", "Java" ]
3
Java
Zebrilus/kicktipper
9d68829c6b8bae0f40d3da6fb7118aa1198d2e0b
3bee97a1457d77a94c58af87f830d22663a7dcdc
refs/heads/master
<repo_name>twobraids/pytn-midi<file_sep>/framework.py #!/usr/bin/env python3 from configman import ( configuration, Namespace ) from configman.converters import ( class_converter ) from iostreams import ( StdInStream, StdOutStream ) from transforms import ( PassThrough ) required_config = Namespace() required_config.namespace("input") required_config.input.add_option( name="implementation", default=StdInStream, from_string_converter=class_converter ) required_config.namespace("transform") required_config.transform.add_option( name="implementation", default=PassThrough, from_string_converter=class_converter ) required_config.namespace("output") required_config.output.add_option( name="implementation", default=StdOutStream, from_string_converter=class_converter ) config = configuration(required_config) in_stream = config.input.implementation(config.input) transform = config.transform.implementation(config.transform) out_stream = config.output.implementation(config.output) for message in in_stream: out_stream.send(transform(message)) out_stream.close() <file_sep>/iostreams.py from mido import ( MidiFile, MidiTrack, Message, MetaMessage, midifiles, parse_string ) import sys from configman import ( Namespace, RequiredConfig ) class FileStream(RequiredConfig): required_config = Namespace() required_config.add_option( name="pathname" ) def __init__(self, config): self.config = config self.pathname = config.pathname class FileInputStream(FileStream): def __init__(self, config): super(FileInputStream, self).__init__(config) self.midi_file = MidiFile(self.pathname) # The file may contain many tracks. Merge them into a single track, # since the pipeline does not care about tracks. track = midifiles.tracks.merge_tracks(self.midi_file.tracks) self.midi_file.tracks = [track] def __iter__(self): return iter(self.midi_file.tracks[0]) class FileOutputStream(FileStream): def __init__(self, config): super(FileOutputStream, self).__init__(config) self.output_file = MidiFile() self.track = MidiTrack() self.output_file.tracks.append(self.track) def send(self, message): self.track.append(message) def close(self): self.output_file.save(self.pathname) def parse_meta_message(body): """ Parse a MetaMessage. For example, parse_meta_message("track_name name='Piano left' time=0") returns MetaMessage('track_name', name='Piano left', time=0). """ import tokenize, token lines = [body] def next_line(): if lines: return lines.pop() else: return '' tokens = list(tokenize.generate_tokens(next_line)) if len(tokens) == 0 or tokens[0][0] != token.NAME: raise ValueError("can't parse meta message type: " + body) message_type = tokens.pop(0)[1] kwargs = {} while len(tokens) > 0 and tokens[0][0] != token.ENDMARKER: if len(tokens) < 3: raise ValueError("unexpected end of line {!r}".format(body)) if tokens[0][0] != token.NAME: raise ValueError("expected key, got {!r} in line {!r}".format(tokens[0][1], body)) if tokens[1][1] != '=': raise ValueError("expected =, got {!r} in line {!r}".format(tokens[1][1], body)) if tokens[2][0] not in (token.NUMBER, token.STRING): raise ValueError("expected number or string, got {!r} in line {!r}".format(tokens[2][1], body)) name = tokens[0][1] value = eval(tokens[2][1]) kwargs[name] = value del tokens[:3] return MetaMessage(message_type, **kwargs) class StdInStream(RequiredConfig): required_config = Namespace() def __init__(self, config): self.config = config def __iter__(self): for line in sys.stdin: line = line.split('#', 1)[0].strip() if line.startswith('<message ') and line.endswith('>'): yield parse_string(line[9:-1]) elif line.startswith('<meta message ') and line.endswith('>'): yield parse_meta_message(line[14:-1]) elif line == '': pass else: raise ValueError("unrecognized line: " + repr(line)) class StdOutStream(RequiredConfig): required_config = Namespace() def __init__(self, config): self.config = config def send(self, message): print (repr(message)) def close(self): pass from mido.sockets import ( PortServer, connect ) class NetworkStream(RequiredConfig): required_config = Namespace() required_config.add_option( name="port", default=9000, ) required_config.add_option( name="host", default="localhost", ) def __init__(self, config): self.config = config self.host = config.host self.port = config.port class NetworkInStream(NetworkStream): def __init__(self, config): super(NetworkInStream, self).__init__(config) self.server = PortServer(self.host, self.port) def __iter__(self): for message in self.server: yield message class NetworkOutStream(NetworkStream): def __init__(self, config): super(NetworkOutStream, self).__init__(config) self.connection = connect(self.host, self.port) def send(self, message): self.connection.send(message) def close(self): self.connection.close()<file_sep>/transforms.py from configman import ( Namespace, RequiredConfig ) class PassThrough(RequiredConfig): required_config = Namespace() def __init__(self, config): self.config = config def __call__(self, message): return message
472829d3d67baa16d9efa456d26ab85f6a9689c7
[ "Python" ]
3
Python
twobraids/pytn-midi
ed78a5821492f78aa08a39971e4a80171d1a7a85
f54455cbd5590718b0b6f458c18fd3c5affb443a